在 Invoke-Command Cmdlet 中处理 ScriptBlock 中的错误 [英] Handle errors in ScriptBlock in Invoke-Command Cmdlet
问题描述
我正在尝试使用 powershell 在远程计算机上安装服务.
I am trying to install a service on a remote machine using the powershell.
到目前为止,我有以下几点:
So far I have the following:
Invoke-Command -ComputerName $remoteComputerName -ScriptBlock {
param($password=$password,$username=$username)
$secpasswd = ConvertTo-SecureString $password -AsPlainText -Force
$credentials = New-Object System.Management.Automation.PSCredential ($username, $secpasswd)
New-Service -Name "XXX" -BinaryPathName "c:XXX.exe" -DisplayName "XXX XXX XXX" -Description "XXXXXX." -Credential $credentials -ErrorVariable errortext
Write-Host("Error in: " + $errortext)
} -ArgumentList $password,$username -ErrorVariable errortext
Write-Host("Error out: " + $errortext)
当执行 New-Service 时出现错误时,$errortext ErrorVariable 会在 ScriptBlock 中正确设置,因为文本:Error in: 显示错误.
When there is an error while executing New-Service the $errortext ErrorVariable get set properly inside the ScriptBlock, because the text: "Error in: shows me the error.
Invoke-Command 的 ErrorVariable 未设置(这是我预期的).
The ErrorVariable of the Invoke-Command does not get set (which I expected).
我的问题是:
是否可以将 Invoke-Command 的 ErrorVariable 设置为我在 ScriptBlock 中遇到的错误?
我知道我也可以使用 InstalUtil、WMI 和 SC 来安装该服务,但目前这不相关.
I know I could also use InstalUtil, WMI and SC to install the service, but this is not relevant at the moment.
推荐答案
不,您无法从 Invoke-Command
调用中获取 Errorvariable
以设置与脚本块中的相同.
No, you can't get the Errorvariable
from the Invoke-Command
call to be set the same as in the scriptblock.
但如果您的目标是检测和处理脚本块中的错误,并将错误返回到 Invoke-Command
调用者的上下文",那么只需手动执行:
But if your goal is "detect and handle errors in the scriptblock, and also get errors returned back to the context of the Invoke-Command
caller" then just do it manually:
$results = Invoke-Command -ComputerName server.contoso.com -ScriptBlock {
try
{
New-Service -ErrorAction 1
}
catch
{
<log to file, do cleanup, etc>
return $_
}
<do stuff that should only execute when there are no failures>
}
$results
现在包含错误信息.
这篇关于在 Invoke-Command Cmdlet 中处理 ScriptBlock 中的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!