Quantcast
Channel: Windows PowerShell forum
Viewing all articles
Browse latest Browse all 21975

Try, Catch, If, Invoke-Command and error handling

$
0
0

I'm still learning Powershell so please take it easy on me. Here is what I am trying to do, find a process called wview.exe on multiple remote computers, if wview.exe exist stop it + log it + increase counter, if it doesn't but computer is up, log it + increase counter, if we can't connect log it + increase counter. I would like to avoid having to test the connection first.

Here is a sample of what I have:

Foreach ($Computer in $Computers){    #Try to connect to the computer    Try{        $ProcessCount = Invoke-Command -ComputerName $Computer -ScriptBlock {@(Stop-Process -force -passthru -processname wview).count} -SessionOption (New-PSSessionOption -NoMachineProfile)        #If we find 1 or more wview.exe let's log it and + counters        If($ProcessCount -eq 1){            Write-Host $Computer " Processes killed: $ProcessCount"            #$Result is an array to store the result to log to a file in the full script            $Results += $Computer + " Processes killed: $ProcessCount"            #Counters to store in summary for log file            $SuccessConnectCount++            $SuccessKillCount++        }            #Else ... no wview processes found, let's log it and + counter            Else{                Write-Host $Computer ": 0 WView processes to kill"                $Results += $Computer + ": 0 WView processes to kill"                #Counter to store in summary for log file                $SuccessConnectCount++            }    }       #If we get a system error, let's catch it and log it as failed count.    Catch{        Write-Host $Computer ": Connection error"        $Results += $Computer + ": Connection error"        #Counter to store in summary for log file        $FailConnectCount++    }
}

I've tried multiple things like erroractions, catching system errors etc, however the script seems to either hit the try statement (if or else, never both) or catch statement and never all 3 (try, if, else and catch) when all 3 scenarios are present.





Viewing all articles
Browse latest Browse all 21975

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>