在Invoke-Command Cmdlet中处理ScriptBlock中的错误 [英] Handle errors in ScriptBlock in Invoke-Command Cmdlet
问题描述
到目前为止,我有以下几点:
Invoke-Command -ComputerName $ remoteComputerName -ScriptBlock {
param($ password = $ password,$ username = $ username)
$ secpasswd = ConvertTo -SecureString $ password -AsPlainText -Force
$ credentials =新对象System.Management.Automation.PSCredential($ username,$ secpasswd)
新服务-NameXXX-BinaryPathNamec:\\ \\ XXX.exe-DisplayNameXXX XXX XXX - 说明XXXXXX。 -Credential $ credentials -ErrorVariable errortext
写入主机(Error in:+ $ errortext)
} -ArgumentList $ password,$ username -ErrorVariable errortext
Write-Host(Error out:+ $ errortext)
执行时出现错误New-Service $ errortext ErrorVariable在ScriptBlock内正确设置,因为文本:错误:显示错误。
Invoke-Command的ErrorVariable我的问题是:
这是不可能的设置Invoke-Command的ErrorVariable到ScriptBlock里面的错误?
我知道我也可以使用InstalUtil,WMI和SC来安装该服务,但这与目前无关。
不,您不能得到
等于脚本块。 Invoke-Command
调用成为错误变量
但是,如果您的目标是检测并处理scriptblock中的错误,并且还会返回到 Invoke-Command
caller,然后手动执行:
$ results = Invoke -Command -ComputerName server.contoso.com -ScriptBlock {
try
{
New-Service -ErrorAction 1
}
catch
{
<日志到文件,清理等等>
return $ _
}
<只有在没有失败时才执行的东西>
}
$ results
now包含错误信息。
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)
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.
The ErrorVariable of the Invoke-Command does not get set (which I expected).
My question is:
Is it somehow possible to set the ErrorVariable of the Invoke-Command to the error I got inside the ScriptBlock?
I know I could also use InstalUtil, WMI and SC to install the service, but this is not relevant at the moment.
No, you can't get the Errorvariable
from the Invoke-Command
call to be set the same as in the scriptblock.
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
now contains the error information.
这篇关于在Invoke-Command Cmdlet中处理ScriptBlock中的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!