将参数传递给Invoke-Command

时间:2017-04-04 15:18:38

标签: powershell

我在将参数传递给Invoke-Command时遇到问题,我尝试使用-Args-ArgumentList无效。

function One {
 $errcode = $args
 $username = "Ron"
 $password = ConvertTo-SecureString -String "Baxter" -AsPlainText -Force
 $cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $password
 $cred
 $Result = Invoke-Command -ComputerName MyPc -ScriptBlock { & cmd.exe /c "C:\Scripts\test.bat" Param1 $errcode ; $lastexitcode}  -Credential $cred
 echo $result
}


One 10

1 个答案:

答案 0 :(得分:1)

您可以更新您的函数以将参数作为$errcode传递,而不是使用$args,这是更好的代码,因为它不那么令人困惑。 (我建议在parameters and functions上阅读,因为它肯定有帮助)

然后,您需要使用$errcode参数将Invoke-Command传递到ArgumentList,并在其位置使用$args[0]

function One ($errcode) {
    $username = "Ron"
    $password = ConvertTo-SecureString -String "Baxter" -AsPlainText -Force
    $cred = New-Object -typename System.Management.Automation.PSCredential -argumentlist $username, $password

    $Result = Invoke-Command -ComputerName MyPc -ScriptBlock { & cmd.exe /c "C:\Scripts\test.bat" Param1 $args[0] ; $lastexitcode} -Credential $cred -ArgumentList $errcode
    echo $Result
}
One 10
相关问题