在脚本中通过 new shell 传递 arg

Pass arg through new shell within script

由于库内存泄漏,我正在尝试调用新的 shell。当我调用 shell 时,我需要传递一个 arg(实际代码将传递 2 个 arg)。在新 shell 中执行代码块后,它需要 return 一个值。我写了一些测试代码来重现错误:

Function GetLastName
{
    Param ($firstName)

    $lastName = Powershell -firstName $firstName {
        Param ([string]$firstName)
        $lastName = ''
        if ($firstName = 'John')
        {
            $lastName = 'Doe'
            Write-Host "Hello $firstName, your last name is registered as $lastName"
        }
        Write-Host "Last name not found"
        Write-Output $lastName
    }
    Write-Output $lastName
}

Function Main
{
    $firstName = 'John'

    $lastName = GetLastName $firstName

    Write-Host "Your name is $firstName $lastName"
}

Main

我得到的错误...

Powershell : -firstName : The term '-firstName' is not recognized as the name of
a cmdlet, function, script file, or operable
At C:\Scripts\Tests\test1.ps1:5 char:15
+         $lastName = Powershell -firstName $firstName {
+                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (-firstName : Th...e, or operable :String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

program. Check the spelling of the name, or if a path was included, verify that
the path is correct and try again.
At line:1 char:1
+ -firstName John -encodedCommand DQAKAAkACQAJAFAAYQByAGEAbQAgACgAWwBzAHQAcgBpAG4A ...
+ ~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (-firstName:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

谁能帮我怎么做?

将您的代码拆分为两个单独的脚本,并将一个用作第二个的启动器。像这样:

# launcher.ps1
powershell.exe -File 'C:\path\to\worker.ps1' -FirstName $firstName

# worker.ps1
[CmdletBinding()]
Param($firstName)

$lastName = ''
if ($firstName = 'John') {
    $lastName = 'Doe'
    Write-Host "Hello $firstName, your last name is registered as $lastName"
}
Write-Host "Last name not found"
Write-Output $lastName

但是请注意,从调用者的角度来看,新进程的主机输出 (Write-Host) 已合并到其常规输出 (Write-Output) 中。

从 PowerShell 中调用 powershell.exe 执行脚本块的语法有点不同:

powershell.exe -command { scriptblock content here } -args "arguments","go","here"

所以在你的脚本中应该是:

$lastName = powershell -Command {
    Param ([string]$firstName)
    $lastName = ''
    if ($firstName = 'John')
    {
        $lastName = 'Doe'
        Write-Host "Hello $firstName, your last name is registered as $lastName"
    } else {
        Write-Host "Last name not found"
    }
    Write-Output $lastName
} -args $firstName