我如何利用 try/catch 语句将计算机添加到 Invoke-Command cmdlet 中的数组中?
我有以下不符合我预期的行为:
$IisServers = "Server1","Server2","Server3"
$Action = "remove"
$FileName = "iisstart.htm"
If ($Action -eq "remove") {
"`n`r*** CONFIGURING IIS ON REMOTE COMPUTERS ***" #| Tee-Object -Append $LogFile
# Run config command on array - Results will come back unsorted due to the parallel processing nature of invoke-command
Invoke-Command -ComputerName $IisServers -ErrorAction stop {
Try {
# Import PowerShell module (Only essential for Win 2k8r2 servers)
Import-Module WebAdministration
# Remove filename from list if exists
If (Get-WebConfiguration -PSPath 'MACHINE/WEBROOT/APPHOST' -Filter 'system.webServer/defaultDocument/files/add' | Where-Object {$_.value -eq $Using:FileName}) {
Remove-webconfigurationproperty /system.webServer/defaultDocument -name files -atElement @{value=$Using:Filename}
Write-Output "$Env:ComputerName`: '$Using:FileName' removed from Default Document list"
}
Else {
Write-Output "$Env:ComputerName`: '$Using:FileName' doesn't exist in Default Document list"
}
}
Catch {
$ErrorMessage = $_.Exception.Message
Write-Output "$Env:ComputerName`: $ErrorMessage"
$ExecutionIssues += $Env:ComputerName
}
$props = @{ComputerName=$ExecutionIssues}
New-Object -Type PSObject -Prop $Props
} #| Tee-Object -Append $LogFile
}
- If/Else 循环被忽略,每次我运行它时,它都只运行 If 部分。
- Try/Catch 似乎正在执行 If 命令错误,但“ErrorAction Stop”参数似乎在遇到第一个 WinRM 连接错误时终止脚本,而不是记录并继续执行其余操作。
- 失败时不会向 $ExecutionIssues 变量添加任何内容。
我是否遗漏了一些显而易见的东西?
答案1
Keith 在下面的帖子中的回答给了我一个看起来合适的解决方法:
https://stackoverflow.com/questions/12600921/handle-errors-in-scriptblock-in-invoke-command-cmdlet
不使用 try/catch 语句即可使用此语句解决上述所有问题。