我需要从Invoke-Command
输出变量,但是当打印显示为空时,下面是示例代码:
$ServiceName = "Service"
Invoke-Command -ScriptBlock {
try {
iisreset
$BodyContent += "Server: <b>$server</b> IIS reset completed<br>"
}
catch {
$BodyContent += "Server: <b>$server</b> is Failed to restart IIS<br>"
$ErrorStat = 1
}
try {
Stop-Service -DisplayName $using:ServiceName
$BodyContent += "Server: <b>$server</b> is successfully Stopped $using:ServiceName<br>"
}
catch {
$BodyContent += "Server: <b>$server</b> is failed to Stop $using:ServiceName<br>"
$ErrorStat = 1
}
try {
Start-Service -DisplayName $using:ServiceName
$BodyContent += "Server: <b>$server</b> is successfully Started $using:ServiceName<br>"
}
catch {
$BodyContent += "Server: <b>$server</b> is failed to Start $using:ServiceName<br>"
$ErrorStat = 1
}
} -ComputerName $server -Credential $user -ErrorAction Stop
在这里,我想捕获$BodyContent
和$ErrorStat
答案 0 :(得分:1)
Invoke-Command
会返回打印到管道末尾的内容。如果你想返回一个变量,你应该Return <variable>
喜欢:
$ret = Invoke-Command -ScriptBlock { $var="test string"; return $var; }
其中$ret
现在包含值test string
。
当你想要返回多个变量时,你可以将它们加入一个变量,例如像这样:
$str1 = "test"
$str2 = "123"
$combinedObjs = New-Object PSObject -Property @{1 = $str1; 2 = $str2}
现在你可以将它们全部组合
$ret = Invoke-Command -ScriptBlock {
$str1 = "test";
$str2 = "123";
$combinedObjs = @{val1 = $str1; val2 = $str2};
Return $combinedObjs;
}
现在$ret
包含
Name Value
---- -----
val1 test
val2 123
您可以致电$ret.val1
或$ret.val2
答案 1 :(得分:0)
将一些输出添加到给定scriptblock的最末端,例如
@{ BodyContent = $BodyContent
ErrorStat = $ErrorStat
}
如果您使用例如
$result = Invoke-Command -ScriptBlock {
### original script block body here
@{ BodyContent = $BodyContent
ErrorStat = $ErrorStat
}
} -ComputerName $server -Credential $user -ErrorAction Stop
然后你可以检查
$result.BodyContent
$result.ErrorStat