为什么我的powershell脚本返回错误的退出代码?

时间:2017-02-17 05:50:30

标签: windows shell powershell

我正在尝试从远程计算机上执行的powershell脚本返回退出代码。但是,当我检查ExitCode时,它有一些随机数。

我做错了什么?另外,是否可以返回整个文本?

我的剧本

$proc = Start-Process -Filepath "$PSExec" -ArgumentList "\\$server -h -u $user -p $pass -d PowerShell $command" -PassThru -Wait
$proc.ExitCode

远程脚本

New-Item "c:\temp\1.txt" -type file -force
exit 123

更新

$secureString = ConvertTo-SecureString $password -Force -AsPlainText #$password includes password in clear text
$cred = New-Object System.Management.Automation.PSCredential($usrName, $secureString)  
$sess = New-PSSession -ComputerName $serverName -Credential $cred
$command = "`"C:\temp\1.ps1`""
$result = Invoke-Command -Session $sess -ScriptBlock { 
    Start-Process -Filepath "$PSExec" -ArgumentList "\\$server -h -u $usrName -p $password -d PowerShell $command" -PassThru -Wait
}

2 个答案:

答案 0 :(得分:0)

您可以使用Invoke-Command作为替代方案吗?

示例:

$session = New-PSSesson -ComputerName $serverName -Credential (Get-Credential)
$result = Invoke-Command -Session $session -ScriptBlock { 
    Start-Process ...
}

作为Get-Credential的替代方案,您可以创建凭据对象并通过-Credential参数将其传递给Invoke-Command。例如:

$secureString = ConvertTo-SecureString $password -Force -AsPlainText #$password includes password in clear text
$cred = [System.Management.Automation.PSCredential]::new($usrName, $secureString)  
$sess = New-PSSession -ComputerName $ComputerName -Credential $cred
Invoke-Command -Session $sess -ScriptBlock { ... }

$result还应包含ExitCode属性,因为Powershell Remoting序列化了远程对象。与cmdlet特定的ComputerName实现相比,我总是建议使用Powershell Remoting。它使用更标准化的方式(WsMan - > HTTP(S))。有关详细信息,请参阅此link

希望有所帮助。

答案 1 :(得分:0)

对于您的第一种方法,您的问题是当使用.get-this:before { content: none; } (请勿等待)标志运行psexec时,它会返回启动它的命令的pid,而不是等待并返回退出码。

总的来说,您的流程也可以进行优化。首先,如果你想使用-d,我没有看到psexec.exe的原因,因为你正在等待和通过。只需Start-Process即可。

然而,Moerwald建议使用& $psexec ...是一个很好的建议。在更新的代码中,您仍然在运行Invoke-CommandStart-Process,这是不必要的。当您调用该命令时,您已经远程运行代码,因此只需运行代码:

Psexec

此外,由于它看起来不像您正在重用会话,因此我将会话保存到变量中。最好用Get-Credential替换所有凭据设置,而不是传递明文密码(避免密码以保存的记录结尾)。这看起来像这样:

$secureString = ConvertTo-SecureString $password -Force -AsPlainText 
$cred = New-Object System.Management.Automation.PSCredential($usrName, $secureString)  
$result = Invoke-Command -ComputerName $serverName -Credential $cred -ScriptBlock { 
    New-Item "c:\temp\1.txt" -type file -force
    exit 123
}