How would I add a computer to an array within an Invoke-Command cmdlet also utilizing try/catch statement?
I have the following which isn't behaving as I'm expecting:
$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
}
- The If/Else loop is being ignored and each time I run it, it just runs the If section regardless.
- The Try/Catch appears to be working for execution of the If command errors but the "ErrorAction Stop" argument appears to be terminating the script on the first WinRM connection error it hits rather than logging and continuing with the rest.
- Nothing is being added to the $ExecutionIssues variable on failure.
Am I missing something obvious?
Keith's answer in the following post has given me a workaround which looks suitable:
https://stackoverflow.com/questions/12600921/handle-errors-in-scriptblock-in-invoke-command-cmdlet
Using this along without the try/catch statement has addressed all the above points.