Powershell Error Handling not working in Invoke-command block - powershell

I want to print error message when service is not found or machine is offline
$csv = Import-Csv "C:\Users\user\Desktop\computers.csv" -delimiter ","
foreach ($cs in $csv){
$computers = $cs.DNSHostname
foreach ($computer in $computers){
Try{
Invoke-Command -ComputerName $computer -ScriptBlock {
$ProcessCheck = Get-Process -Name agentid-service -ErrorAction Stop
if ($null -eq $ProcessCheck) {
Write-output "agentid-service IS not running $env:computername"
}
else {
Write-output "agentid-service IS running $env:computername"
}
}
}
catch{
Write-Warning $Error[0]
}
}
}
Instead, when service name is not found, i'm getting error:
Cannot find a process with the name "agentid-service". Verify the process name and call the cmdlet again.
And if connection to computer is not possible then getting:
[vm.domain.local] Connecting to remote server vm.domain.local failed with the following error message : The WinRM client cannot process the request because the server name cannot be resolved.
And script continue execution (as it should).
How can i get "Catch" block to be executed ?

You can do this in one foreach loop.
Try
$computers = (Import-Csv "C:\Users\user\Desktop\computers.csv").DNSHostname
foreach ($computer in $computers) {
if (!(Test-Connection -ComputerName $computer -Count 1 -Quiet)) {
Write-Warning "Computer $computer cannot be reached"
continue # skip this one and proceed with the next computer
}
try{
Invoke-Command -ComputerName $computer -ScriptBlock {
$ProcessCheck = Get-Process -Name 'agentid-service' -ErrorAction Stop
if (!$ProcessCheck.Responding) {
"agentid-service is NOT not running on computer '$env:computername'"
}
else {
"agentid-service is running on computer '$env:computername'"
}
}
}
catch{
Write-Warning $_.Exception.Message
}
}

Thanks to #Theo's answer, managed to fix it:
$csv = Import-Csv "C:\Users\user\Desktop\computers.csv" -delimiter ","
foreach ($cs in $csv){
$error.Clear()
$computers = $cs.DNSHostname
foreach ($computer in $computers){
Try{
Invoke-Command -ComputerName $computer -ScriptBlock {
$ProcessCheck = Get-Process -Name agentid-service -ErrorAction Stop
if ($null -ne $ProcessCheck) {
Write-output "agentid-service IS running $env:computername"
}
} -ErrorAction Stop
}
catch{
if ($null -eq $ProcessCheck){
Write-warning "agentid-service IS not running $env:computername"
}
Write-Warning $Error[0]
}
}
}

Related

PowerShell - get-hotfix on multiple servers - error handling

I have a problem with my script to check multiple hotfixes on multiple servers. Sometimes I don't have a rpc connection to a server, in this case I want to log this information to the same output file. Can someone please help me? thanks
$computers = Get-Content -path C:\00-Scripts\printer\server.txt
$Patch = Get-Content -path C:\00-Scripts\printer\kb.txt
foreach ($computer in $computers) {
foreach ($patch1 in $patch) {
Try {
if (get-hotfix -id $patch1 -ComputerName $computer -ErrorAction stop) {
Add-content "$patch1 is Present in $computer" -path C:\00-Scripts\printer\Hotfix.txt
}
Else {
Add-content "$patch1 is not Present in $computer" -path C:\00-Scripts\printer\Hotfix.txt
}
}
catch {
Add-content "can not check $computer" -path C:\00-Scripts\printer\Hotfix.txt
}
}
}
In this case, you need to first check if the computer can be reached. If so, loop over the patches to report if they can be found or not. In you cannot reach the machine, write just one failure line in the log and proceed with the next computer.
$computers = Get-Content -path 'C:\00-Scripts\printer\server.txt'
$Patch = Get-Content -path 'C:\00-Scripts\printer\kb.txt'
$logFile = 'C:\00-Scripts\printer\Hotfix.txt'
foreach ($computer in $computers) {
if (Test-Connection -ComputerName $computer -Count 1 -Quiet) {
foreach ($patch1 in $patch) {
# use -ErrorAction SilentlyContinue here so $hotfix will either become $null or an object
$hotfix = Get-HotFix -Id $patch1 -ComputerName $computer -ErrorAction SilentlyContinue
if ($hotfix) {
"$patch1 is Present in $computer" | Add-Content -Path $logFile
}
else {
"$patch1 is not Present in $computer" | Add-Content -Path $logFile
}
}
}
else {
"Can not check $computer" | Add-Content -Path $logFile
}
}
With the above answer, script is not scanning the next computer and the results are not getting generated for the rest of computers
for example
Get-HotFix -ComputerName PC1,PC2 -ErrorAction SilentlyContinue
In above command if PC1 is not available or access denied. The command stops wihtout checking PC2 and generating output

PowerShell get output in CSV format

I am seeking help to get output in csv format. I have written powershell code and would want to tweak the output to get in csv format as shown in below pic.
$servers = Get-Content 'C:\Temp\listofservers.txt'
foreach ($server in $servers)
{
#DHCP
if (((Get-Service -ComputerName $server -ServiceName 'DHCPServer' -ErrorAction SilentlyContinue).Status) -eq 'Running')
{
if ((((Get-DhcpServerv4Scope -ComputerName $server | Get-DhcpServerv4Lease -ComputerName $server) | Measure-Object).Count) -ge 1)
{
Write-Host "DHCP present on $server and in use"
}
else
{
Write-Host "DHCP present on $server and not in use"
}
}
else
{
Write-Host("DHCP is not present on $server")
}
#Certificate authority
if (((Get-Service -ComputerName $server -ServiceName 'CertSvc' -ErrorAction SilentlyContinue).Status) -eq 'Running')
{
Write-Host "Certificate Authority is present on $server"
}
else
{
Write-Host "Certificate Authority is not present on $server"
}
}
Send all outputs to a custom object then export them:
$servers = get-content "C:\Temp\listofservers.txt"
$ExportPath = 'c:\temp\results.csv'
$Servers | ForEach-Object {
Write-Host "Checking $_"
# DHCP status
# Use Try....Catch to trap the errors - it's more robust than
# If...Then and prevents a wall of red text if something goes wrong
Try {
$DHCPStatus = Get-Service -ComputerName $_ -Name 'DHCPServer' -ErrorAction Stop
If ($DHCPStatus.Status -eq "Running") {
Try {
If ((((Get-DhcpServerv4Scope -ComputerName $_ -ErrorAction Stop | Get-DhcpServerv4Lease -ComputerName $_ -ErrorAction Stop) | Measure-Object).Count) -ge 1) {
$DHCPResult = "DHCP present on, in use"
}
Else {
$DHCPResult = "DHCP present, not in use"
}
}
Catch {
$DHCPResult = "DHCP present - error obtaining details: $_"
}
}
}
Catch {
$DHCPResult = "DHCP is not present"
}
#Certificate authority
Try {
If (((Get-Service -ComputerName $_ -ServiceName 'CertSvc' -ErrorAction Stop).Status) -eq "Running") {
$CAResult = "Certificate Authority is present"
}
}
Catch {
$CAResult = "Certificate Authority is not present"
}
[pscustomobject]#{ComputerName = $_;DHCP = $DHCPResult;CA=$CAResult}
} | Export-Csv -Path $ExportPath -NoTypeInformation
Use a hashtable to build your object, adding key/values for each property along the way. Then convert the hashtable to a [PSCustomObject] and output it capturing in a variable ($results). Finally, export it to csv using Export-Csv
$servers = Get-Content 'C:\Temp\listofservers.txt'
$results = foreach ($server in $servers) {
# Create hashtable to build object and add ComputerName property
$output = [ordered]#{ComputerName = $server }
#DHCP
if (((Get-Service -ComputerName $server -ServiceName 'DHCPServer' -ErrorAction SilentlyContinue).Status) -eq 'Running') {
if ((((Get-DhcpServerv4Scope -ComputerName $server |
Get-DhcpServerv4Lease -ComputerName $server) |
Measure-Object).Count) -ge 1) {
# add Dhcp property if present, in use
$output.Add('Dhcp', 'Present, in use')
}
else {
# add Dhcp property if present, not in use
$output.Add('Dhcp', 'Present, not in use')
}
}
else {
# add Dhcp property if not present
$output.Add('Dhcp', 'Not present')
}
#Certificate authority
if (((Get-Service -ComputerName $server -ServiceName 'CertSvc' -ErrorAction SilentlyContinue).Status) -eq 'Running') {
# add CA property if present
$output.Add('CA', 'Present')
}
else {
# add CA property if not present
$output.Add('CA', 'Not present')
}
# Convert hashtable to pscustomobject and output it
[PSCustomObject]$output
}
# output results to screen
$results
# export results to csv file
$results | Export-Csv -Path c:\temp\server_dhcp_ca_check.csv -NoTypeInformation

Scanning For a Service on Online Devices with Powershell Script

I wrote a script to tell me if the SEP Master Service is running for all computer listed in a file, start the service if its stopped, and let me know if it doesn't exist. It's working, but when the script hits a computer that is not online, it slows down until an error is returned and then finally goes to the next computer in the list. Is there a way to only scan for the service on the deivces in the list that are online and can be pinged on the network?
$computers = Get-Content -Path "C:\temp2\ComputerList.txt"
foreach ($computer in $computers) {
$service = Get-Service -name SepMasterService -computername $computer
$ServiceStatus = $service.Status
$ServiceDisplayName = $service.DisplayName
if ($ServiceStatus -eq 'Running') {
Write-Output "Service OK - Status of $ServiceDisplayName is $ServiceStatus on $computer"
}
elseif ($ServiceStatus -eq 'stopped') {
Start-Service -Name SepMasterService -PassThru
}
else {
Write-Output "Symantec Endpoint Protection doesn't exist on $computer"
}
}
Add a check for online machines using the test-connection cmdlet and go to the next computer.
$computers = Get-Content -Path "C:\temp2\ComputerList.txt"
foreach ($computer in $computers) {
if(!(Test-Connection -ComputerName $computer -Count 1 -Quiet))
{
Write-Output "$computer is offline"
continue
}
$service = Get-Service -name SepMasterService -computername $computer
$ServiceStatus = $service.Status
$ServiceDisplayName = $service.DisplayName
if ($ServiceStatus -eq 'Running') {
Write-Output "Service OK - Status of $ServiceDisplayName is $ServiceStatus on $computer"
}
elseif ($ServiceStatus -eq 'stopped') {
Start-Service -Name SepMasterService -PassThru
}
else {
Write-Output "Symantec Endpoint Protection doesn't exist on $computer"
}
}
The -Count parameter specifies how many time to ping the computer. The default is 4 but this will speed up your process. The continue statement will stop executing any of the code in the current iteration of the foreach loop and go to the next computer.
Hope this helps.

Can't assign value to a variable inside of Invoke-Command

It seems to be strange but I can't assign a value to variable inside of Invoke-Command. Here is the code below but when print out $targetComputerPath it's simply empty. What's wrong?
foreach ($item in $computersPath){
$computername = $item.Name
$username = $item.UserID
Write-Host computer $computername and user $username
if (Test-Connection -ComputerName $computername -Count 1 -ErrorAction SilentlyContinue)
{
if ($((Get-Service WinRM -ComputerName $computername).Status) -eq "stopped")
{
(Get-Service WinRM -ComputerName $computername).Start()
}
Invoke-Command -ComputerName $computername -ScriptBlock {
if ($((Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion").ReleaseId) -eq "1903" )
{
$targetComputerPath = "\\"+$computername+"\c$\Users\"+$username+"\Desktop\"
write-host "1903"
}
else
{
$targetComputerPath = "\\"+$computername+"\c$\Users\"+$username+"\Desktop\"
write-host "something else"
}
}
}
write-host $targetComputerPath
}
The point of WinRM is that you take a script block, and execute it on a different machine.
None of the variables you define in the host script will be available on the remote machine.
This becomes more apparent when you separate the "task", a.k.a the script block, from the Invoke-Command, like this:
$task = {
$version = Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion"
if ($version.ReleaseId -eq "1903") {
# note that `$username` cannot be available here, it's never been defined!
return "\\$env:COMPUTERNAME\c$\Users\$username\Desktop"
} else {
return "\\$env:COMPUTERNAME\c$\Users\$username\Desktop"
}
}
foreach ($item in $computersPath) {
$computername = $item.Name
$username = $item.UserID
Write-Host computer $computername and user $username
if (Test-Connection -ComputerName $computername -Count 1 -ErrorAction SilentlyContinue) {
$winrm = Get-Service WinRM -ComputerName $computername
if ($winrm.Status -eq "stopped") { $winrm.Start() }
$targetComputerPath = Invoke-Command -ComputerName $computername -ScriptBlock $task
Write-Host "The machine returned: $targetComputerPath"
}
}
As you can see, you can return values from the script block and they will be available as the return value of Invoke-Command.
If you want to pass arguments to your script block, this thread talks about that: How do I pass named parameters with Invoke-Command?

How do I add multi-threading?

Is there a way of getting the below to run in parallel (multi-threading)? I have about 200 servers that need to run and was wondering if there is a way of checking say 10 servers at once rather then one at a time...WMI is very slow in checking this one at a time.
clear
Write-Host "Script to Check if Server is Alive and Simple WMI Check"
$servers = Get-Content -Path c:\Temp\Servers.txt
foreach($server in $servers)
{
if (Test-Connection -ComputerName $server -Quiet)
{
$wmi = (Get-WmiObject -Class Win32_ComputerSystem -ComputerName $server).Name
Write-Host "$server responds: WMI reports the name is: $wmi"
}
else
{
Write-Host "***$server ERROR - Not responding***"
}
}
Use powershell jobs:
$scriptblock = {
Param($server)
IF (Test-Connection $server -Quiet){
$wmi = (gwmi win32_computersystem -ComputerName $server).Name
Write-Host "***$server responds: WMI reports the name is: $wmi"
} ELSE { Write-Host "***$server ERROR -Not responding***" }
}
$servers | % {Start-Job -Scriptblock $scriptblock -ArgumentList $_ | Out-Null}
Get-Job | Wait-Job | Receive-Job