LTI/ZTI PowerShell: Trapping warning messages(again!)

Over the last few posts I’ve mentioned the dreaded warning message returned from your PowerShell scripts. To recap, here’s my Rename-Computer script and what happens at the end of the deployment.

Param (
 [String]$Name = $TSEnv:OSDComputername,
 [String]$WorkGroupName = $TSEnv:JoinWorkgroup
)
Begin{}

Process{
 (Get-WmiObject win32_computersystem).rename($Name)
 Add-Computer -WorkGroupName $WorkGroupName
}
End{}

Warning-FinishAction

And this is what I get in the log file:

Warning-Log

Ok, so my script has worked exactly as expected yet I still get this warning message at the end. Aaarrrrhhhh! Like I said there are a couple ways of handling this. One method is to leverage the common parameters and supress the warning by adding –WarningAction “SilentlyContinue” to the end of the cmdlet line.

Add-Computer -WorkGroupName $WorkGroupName -WarningAction SilentlyContinue 

Another action is to supress the messages in the scope of the entire script itself by altering the warning preferences. Do this by adding this line to the start of your script.

$WarningPreference = “SilentlyContinue

FinishAction

Life is good? Not quite. One problem here is that the warning information is now gone(notice that we’re calling it information now?). But don’t worry, you can store the warning information in a variable and resurrect it later by simply appending the command line with the –WarningVariable common parameter.

Add-Computer -WorkGroupName $WorkGroupName -WarningAction SilentlyContinue -WarningVariable Message

Now you can take the warning message and transform it into a harmless information message.

Write-Host $Message 

Now when you check the log files, the information is preserved and your deployments end cleanly without warnings.

Information-Log

Looks like you can have your cake and eat it! This is how the full script looks now.

Param (
[String]$Name = $TSEnv:OSDComputername,
[String]$WorkGroupName = $TSEnv:JoinWorkgroup
)

Begin{}
Process{
(Get-WmiObject win32_computersystem).rename($Name)
Add-Computer -WorkGroupName $WorkGroupName -WarningAction SilentlyContinue -WarningVariable Message
Write-Host $Message
}
End{}
Advertisements

About Andrew Barnes

A Scripting and Deployment Specialist.
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s