在脚本中通过新shell传递arg

时间:2016-01-24 18:02:01

标签: powershell powershell-v3.0

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

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

任何人都可以帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

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

# 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)中。