Link to home
Create AccountLog in
Avatar of gzugg
gzuggFlag for United States of America

asked on

Trapping all Powershell errors to a seperate log file wiht server name and error while continue down list of servers

I have a PS script that does a GC from a text file and does a foreach of the txt file and run a get-wmiobject to get the OS version number.  I want to trap the errros in a seperate log file so I know which servers did not run or had issues.  Ive read alot of web pages on trap but still not 100% sure I understand.  i am fairly new to PS  but getting better at it each day.  I have a copy of my script below.  Any suggestions would greatly help.
# 
# NAME:Get_OS_Versions.ps1
# 
# 
# AUTHOR: George Zugg, ISE
# DATE  : 12/29/2010
# 
# 
#COMMENT: Use this to get the Windows OS Version Number for each server in the file C:\temp\MachineList.txt
#
#Ver 2.3
#==============================================================================================

#Setting HighLevel Running
get-credential

# Create necessary variables to use throughout the script for logging
$logFolder = "C:\scripts\Get_OS_Versions\Logs\"
$DateTime = (Get-Date -Format d).Replace("/", "-")
$ActivityLog = $logFolder + "Get_OS_Versions_$DateTime.log"
If ((Test-Path $logFolder) -eq $False) {New-Item -Path $logFolder -type directory}
If ((Test-Path $ActivityLog) -eq $False) {New-Item -Path $ActivityLog -type File}

# Variables to be passed in at PS prompt

#Checking Security Levels for PS Scripts
Get-Date | Add-Content -Path $ActivityLog 
"Checking Execution Policy Settings" | Add-Content -Path $ActivityLog
$currentState = get-executionPolicy 

	If ($currentState -ne "RemoteSigned") 
  			{
				$setexecutionpolicy = Read-Host "Executionpolicy on $computer is not set to RemoteSigned.  Would you like to set this setting? (Y/N)"
  					If ($Setexecutionpolicy -eq "Y")
						{
							Write-Host "Attempting to set the Executionpolicy on $computer ....."
							set-executionpolicy remotesigned -force	 | Add-Content -Path $ActivityLog
							$currentState
						}
					else	
						{
							Write-Host "Current Executionpolicy for $computer was not changed.  Exiting script at user request."
								"$(Get-Date -Format T) ---> Server status is ($currentState).  Exiting script at user request." | Add-Content -Path $ActivityLog
								"======================================================================" | Add-Content -Path $ActivityLog
								Exit
						}
			}			
	If ($currentState -eq "RemoteSigned")
			{
				$Catalog = GC "C:\temp\MachineList.txt"
				ForEach($Machine in $Catalog) 
						{
						$QueryString = Get-WmiObject -Class win32_OperatingSystem -namespace "root\CIMV2" -ComputerName $Machine -erroraction Silentlycontinue | select CSName,Caption,Version | ft -autosize 
						write-output $QueryString | Out-File "c:\Temp\machine_versions.txt" -Append
						}

			}

Open in new window

Avatar of Dale Harris
Dale Harris
Flag of United States of America image

George,

I found this great method a while back on trapping your errors.  This is using a command  Try, Catch, and Finally.  It's quite ingenious and I take no credit for figuring out the if ($?) portion.

#Your code:
$QueryString = Get-WmiObject -Class win32_OperatingSystem -namespace "root\CIMV2" -ComputerName $Machine -erroraction Silentlycontinue | select CSName,Caption,Version | ft -autosize
                                    write-output $QueryString | Out-File "c:\Temp\machine_versions.txt" -Append

#Recommended change (with shorter commands to let you know you don't have to write everything out all the time):

Try {
$QueryString = gwmi Win32_OperatingSystem -Comp $Machine -ea "SilentlyContinue"

if ($?){ #if it's True, then it worked, if it's false, then it had an error when it last ran
{
foreach ($object in $QueryString){
$CSName = $object.CSName
$Caption = $object.Caption
$Version = $object.version
"$Machine `n CSName: $CSName `n Caption: $Caption `n Version: $Version" >> "c:\Temp\machine_versions.txt"
}#end foreach object in QueryString
}
else
{
"$Machine Not Reachable" >> "ErrorLog.txt"
}#end if ($?)
}#end Try
Catch {}
Finally {
$CSName = $null
$Caption = $null
$Version = $null
}




Let me know if this works for you.  I haven't tested it yet so I may have made a typo somewhere, but you get the general idea.

Dale Harris
Avatar of gzugg

ASKER

I may have missed something.  I added entry  but got these type of erroros:


PS PS:\> & '\\dcncsrvrmsf14\Server_software\ISE_scripts\Get_OS_Versions.ps1'

cmdlet Get-Credential at command pipeline position 1
Supply values for the following parameters:
Credential

UserName
--------
fcb\gzugg



                                    foreach ($object in $QueryString)
                                            {
                                                $CSName = $object.CSName
                                                $Caption = $object.Caption
                                                $Version = $object.version
                                                "$Machine `n CSName: $CSName `n Caption: $Caption `n Version: $Version" >> "c:\Temp\machine_versions.txt"
                                            }#end foreach object in QueryString

The term 'else' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At \\dcncsrvrmsf14\Server_software\ISE_scripts\Get_OS_Versions.ps1:66 char:12
+                             else <<<<
    + CategoryInfo          : ObjectNotFound: (else:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException


                                        "$Machine Not Reachable" >> "c:\temp\machine_version_ErrorLog.txt"

The term 'Catch' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At \\dcncsrvrmsf14\Server_software\ISE_scripts\Get_OS_Versions.ps1:71 char:15
+                                     Catch <<<<  {}
    + CategoryInfo          : ObjectNotFound: (Catch:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

The term 'Finally' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At \\dcncsrvrmsf14\Server_software\ISE_scripts\Get_OS_Versions.ps1:72 char:17
+                                     Finally <<<<
    + CategoryInfo          : ObjectNotFound: (Finally:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException


                                        $CSName = $null
                                        $Caption = $null
                                        $Version = $null


                                    foreach ($object in $QueryString)
                                            {
                                                $CSName = $object.CSName
                                                $Caption = $object.Caption
                                                $Version = $object.version
                                                "$Machine `n CSName: $CSName `n Caption: $Caption `n Version: $Version" >> "c:\Temp\machine_versions.txt"
                                            }#end foreach object in QueryString

The term 'else' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At \\dcncsrvrmsf14\Server_software\ISE_scripts\Get_OS_Versions.ps1:66 char:12
+                             else <<<<
    + CategoryInfo          : ObjectNotFound: (else:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException


                                        "$Machine Not Reachable" >> "c:\temp\machine_version_ErrorLog.txt"

The term 'Catch' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At \\dcncsrvrmsf14\Server_software\ISE_scripts\Get_OS_Versions.ps1:71 char:15
+                                     Catch <<<<  {}
    + CategoryInfo          : ObjectNotFound: (Catch:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

The term 'Finally' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At \\dcncsrvrmsf14\Server_software\ISE_scripts\Get_OS_Versions.ps1:72 char:17
+                                     Finally <<<<
    + CategoryInfo          : ObjectNotFound: (Finally:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException


                                        $CSName = $null
                                        $Caption = $null
                                        $Version = $null


                                    foreach ($object in $QueryString)
                                            {
                                                $CSName = $object.CSName
                                                $Caption = $object.Caption
                                                $Version = $object.version
                                                "$Machine `n CSName: $CSName `n Caption: $Caption `n Version: $Version" >> "c:\Temp\machine_versions.txt"
                                            }#end foreach object in QueryString

The term 'else' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At \\dcncsrvrmsf14\Server_software\ISE_scripts\Get_OS_Versions.ps1:66 char:12
+                             else <<<<
    + CategoryInfo          : ObjectNotFound: (else:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException


                                        "$Machine Not Reachable" >> "c:\temp\machine_version_ErrorLog.txt"

The term 'Catch' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At \\dcncsrvrmsf14\Server_software\ISE_scripts\Get_OS_Versions.ps1:71 char:15
+                                     Catch <<<<  {}
    + CategoryInfo          : ObjectNotFound: (Catch:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

The term 'Finally' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At \\dcncsrvrmsf14\Server_software\ISE_scripts\Get_OS_Versions.ps1:72 char:17
+                                     Finally <<<<
    + CategoryInfo          : ObjectNotFound: (Finally:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException


                                        $CSName = $null
                                        $Caption = $null
                                        $Version = $null


                                    foreach ($object in $QueryString)
                                            {
                                                $CSName = $object.CSName
                                                $Caption = $object.Caption
                                                $Version = $object.version
                                                "$Machine `n CSName: $CSName `n Caption: $Caption `n Version: $Version" >> "c:\Temp\machine_versions.txt"
                                            }#end foreach object in QueryString

The term 'else' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At \\dcncsrvrmsf14\Server_software\ISE_scripts\Get_OS_Versions.ps1:66 char:12
+                             else <<<<
    + CategoryInfo          : ObjectNotFound: (else:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException


                                        "$Machine Not Reachable" >> "c:\temp\machine_version_ErrorLog.txt"

The term 'Catch' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At \\dcncsrvrmsf14\Server_software\ISE_scripts\Get_OS_Versions.ps1:71 char:15
+                                     Catch <<<<  {}
    + CategoryInfo          : ObjectNotFound: (Catch:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

The term 'Finally' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At \\dcncsrvrmsf14\Server_software\ISE_scripts\Get_OS_Versions.ps1:72 char:17
+                                     Finally <<<<
    + CategoryInfo          : ObjectNotFound: (Finally:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException


                                        $CSName = $null
                                        $Caption = $null
                                        $Version = $null


                                    foreach ($object in $QueryString)
                                            {
                                                $CSName = $object.CSName
                                                $Caption = $object.Caption
                                                $Version = $object.version
                                                "$Machine `n CSName: $CSName `n Caption: $Caption `n Version: $Version" >> "c:\Temp\machine_versions.txt"
                                            }#end foreach object in QueryString

The term 'else' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At \\dcncsrvrmsf14\Server_software\ISE_scripts\Get_OS_Versions.ps1:66 char:12
+                             else <<<<
    + CategoryInfo          : ObjectNotFound: (else:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException


                                        "$Machine Not Reachable" >> "c:\temp\machine_version_ErrorLog.txt"

The term 'Catch' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At \\dcncsrvrmsf14\Server_software\ISE_scripts\Get_OS_Versions.ps1:71 char:15
+                                     Catch <<<<  {}
    + CategoryInfo          : ObjectNotFound: (Catch:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

The term 'Finally' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At \\dcncsrvrmsf14\Server_software\ISE_scripts\Get_OS_Versions.ps1:72 char:17
+                                     Finally <<<<
    + CategoryInfo          : ObjectNotFound: (Finally:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException


                                        $CSName = $null
                                        $Caption = $null
                                        $Version = $null


                                    foreach ($object in $QueryString)
                                            {
                                                $CSName = $object.CSName
                                                $Caption = $object.Caption
                                                $Version = $object.version
                                                "$Machine `n CSName: $CSName `n Caption: $Caption `n Version: $Version" >> "c:\Temp\machine_versions.txt"
                                            }#end foreach object in QueryString

The term 'else' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At \\dcncsrvrmsf14\Server_software\ISE_scripts\Get_OS_Versions.ps1:66 char:12
+                             else <<<<
    + CategoryInfo          : ObjectNotFound: (else:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException


                                        "$Machine Not Reachable" >> "c:\temp\machine_version_ErrorLog.txt"

The term 'Catch' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At \\dcncsrvrmsf14\Server_software\ISE_scripts\Get_OS_Versions.ps1:71 char:15
+                                     Catch <<<<  {}
    + CategoryInfo          : ObjectNotFound: (Catch:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

The term 'Finally' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At \\dcncsrvrmsf14\Server_software\ISE_scripts\Get_OS_Versions.ps1:72 char:17
+                                     Finally <<<<
    + CategoryInfo          : ObjectNotFound: (Finally:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException


                                        $CSName = $null
                                        $Caption = $null
                                        $Version = $null

# 
# NAME:Get_OS_Versions.ps1
# 
# 
# AUTHOR: George Zugg, ISE
# DATE  : 12/29/2010
# 
# 
#COMMENT: Use this to get the Windows OS Version Number for each server in the file C:\temp\MachineList.txt
#
#Ver 2.3
#==============================================================================================

#Setting HighLevel Running
get-credential

# Create necessary variables to use throughout the script for logging
$logFolder = "C:\scripts\Get_OS_Versions\Logs\"
$DateTime = (Get-Date -Format d).Replace("/", "-")
$ActivityLog = $logFolder + "Get_OS_Versions_$DateTime.log"
If ((Test-Path $logFolder) -eq $False) {New-Item -Path $logFolder -type directory}
If ((Test-Path $ActivityLog) -eq $False) {New-Item -Path $ActivityLog -type File}

# Variables to be passed in at PS prompt

#Checking Security Levels for PS Scripts
Get-Date | Add-Content -Path $ActivityLog 
"Checking Execution Policy Settings" | Add-Content -Path $ActivityLog
$currentState = get-executionPolicy 

	If ($currentState -ne "RemoteSigned") 
  			{
				$setexecutionpolicy = Read-Host "Executionpolicy on $computer is not set to RemoteSigned.  Would you like to set this setting? (Y/N)"
  					If ($Setexecutionpolicy -eq "Y")
						{
							Write-Host "Attempting to set the Executionpolicy on $computer ....."
							set-executionpolicy remotesigned -force	 | Add-Content -Path $ActivityLog
							$currentState
						}
					else	
						{
							Write-Host "Current Executionpolicy for $computer was not changed.  Exiting script at user request."
								"$(Get-Date -Format T) ---> Server status is ($currentState).  Exiting script at user request." | Add-Content -Path $ActivityLog
								"======================================================================" | Add-Content -Path $ActivityLog
								Exit
						}
			}			
	If ($currentState -eq "RemoteSigned")
			{
				$Catalog = GC "C:\temp\MachineList.txt"
				ForEach($Machine in $Catalog) 
						{
						#$QueryString = Get-WmiObject -Class win32_OperatingSystem -namespace "root\CIMV2" -ComputerName $Machine -erroraction Silentlycontinue | select CSName,Caption,Version | ft -autosize 
						#write-output $QueryString | Out-File "c:\Temp\machine_versions.txt" -Append
						$QueryString = gwmi Win32_OperatingSystem -Comp $Machine -ea "SilentlyContinue"
                           if ($?)
						   		{ #if it's True, then it worked, if it's false, then it had an error when it last ran
									{
									foreach ($object in $QueryString)
											{
												$CSName = $object.CSName
												$Caption = $object.Caption
												$Version = $object.version
												"$Machine `n CSName: $CSName `n Caption: $Caption `n Version: $Version" >> "c:\Temp\machine_versions.txt"
											}#end foreach object in QueryString
									}
									else
									{
										"$Machine Not Reachable" >> "c:\temp\machine_version_ErrorLog.txt"
									}#end if ($?)
									}#end Try
									Catch {}
									Finally 
								{
										$CSName = $null
										$Caption = $null
										$Version = $null
									}


						
						
						}

			}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Dale Harris
Dale Harris
Flag of United States of America image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account