PowerShell Write-Host Help

Hello,

I am new to PS and I am writing some simple scripts and need help. Once each item is successful I would like it to write- host -ForegroundColor Green or Red if it failed. I am sure this is simple, just looking for some help.

#######################################################
# Disable NetBIOS over TCP/IP
$nic = Get-WmiObject Win32_NetworkAdapterConfiguration -filter "ipenabled = 'true'"
$nic.SetTcpipNetbios(2)

#######################################################
# Uncheck "Register this connection's addressed in DNS
(Get-WmiObject Win32_NetworkAdapter -Filter "NetEnabled=True").GetRelated('Win32_NetworkAdapterConfiguration').SetDynamicDNSRegistration($false,$false)

#######################################################
# Set WinRM to Automatic
Set-Service -Name WinRM -StartupType Automatic -Status Running

#######################################################
# Nightly Reboot Task (Change Path to XML)
schtasks.exe /Create /XML "C:Base Build Files\Task\Nightly_Reboot.xml" /tn "Nightly Reboot"

#######################################################
# Disable IPv6
netsh interface ipv6 set global randomizeidentifiers=disabled

March 20th, 2015 6:45pm

You have to check the error variable to see if an error has happened or use try/catch.

help error

help about_try_catch

March 20th, 2015 7:06pm

Hi Garrett,

you can do this by using try/catch. Here's an example:

#######################################################
# Disable NetBIOS over TCP/IP
try
{
	$nic = Get-WmiObject Win32_NetworkAdapterConfiguration -filter "ipenabled = 'true'"
	$nic.SetTcpipNetbios(2)
	Write-Host "Successfully disabled NetBIOS over TCP/IP" -ForegroundColor 'DarkGreen'
}
catch
{
	Write-Host "Failed to disable NetBIOS over TCP/IP: $($_.Exception.Message)" -ForegroundColor 'Red'
}

On the other hand, is Write-Host really the best way to report on operation success? Here's an example on how you can build a custom result object that shows you success or failure for each step. It can easily be stored in a variable or exported to file (csv, xml, etc.).

#######################################################
# Disable NetBIOS over TCP/IP
try
{
	$nic = Get-WmiObject Win32_NetworkAdapterConfiguration -filter "ipenabled = 'true'"
	$nic.SetTcpipNetbios(2)
	$DoNB = $true
}
catch
{
	$DoNB = $false
}

#######################################################
# Uncheck "Register this connection's addressed in DNS
try
{
	(Get-WmiObject Win32_NetworkAdapter -Filter "NetEnabled=True").GetRelated('Win32_NetworkAdapterConfiguration').SetDynamicDNSRegistration($false, $false)
	$DoDNS = $true
}
catch { $DoDNS = $false }

#######################################################
# Set WinRM to Automatic
try
{
	Set-Service -Name WinRM -StartupType Automatic -Status Running -ErrorAction 'Stop'
	$DoWinRM = $true
}
catch { $DoWinRM = $false }

#######################################################
# Nightly Reboot Task (Change Path to XML)
$result = schtasks.exe /Create /XML "C:Base Build Files\Task\Nightly_Reboot.xml" /tn "Nightly Reboot"
if ($result -like "ERROR*") { $DoTask = $false }
else { $DoTask = $true }

#######################################################
# Disable IPv6
$result2 = netsh interface ipv6 set global randomizeidentifiers=disabled
if (($result2 | Select-Object -First 1) -like "OK*") { $DoNetsh = $true }
else { $DoNetsh = $false }

$Props = @{
	DisabledNetBIOS = $DoNB
	DisabledDNSRegistration = $DoDNS
	EnabledWinRM = $DoWinRM
	RegisteredTask = $DoTask
	DisabledIPv6RIdent = $DoNetsh
}
New-Object PSObject -Property $Props

Write-Host is a dead end where data is concerned. Returning objects allows you to actually handle it like the output of any other cmdlet. Export it to file or build logic depending on the values.

Cheers,
Fred

Free Windows Admin Tool Kit Click here and download it now
March 20th, 2015 7:24pm

FWN - you forgot a few 'Stop' params.
March 20th, 2015 7:36pm

Thank You Mike,

Seems pretty simple now after looking at it.

I have one other question. When I run just one of these, like the one below. How do i only have "Successfully disabled NetBIOS over TCP/IP" display and not everything else. See attachement.

#######################################################
# Disable NetBIOS over TCP/IP
try
{
	$nic = Get-WmiObject Win32_NetworkAdapterConfiguration -filter "ipenabled = 'true'"
	$nic.SetTcpipNetbios(2)
	Write-Host "Successfully disabled NetBIOS over TCP/IP" -ForegroundColor 'DarkGreen'
}
catch
{
	Write-Host "Failed to disable NetBIOS over TCP/IP: $($_.Exception.Message)" -ForegroundColor 'Red'
}

Free Windows Admin Tool Kit Click here and download it now
March 20th, 2015 7:47pm

Hi Garret,

like this:

#######################################################
# Disable NetBIOS over TCP/IP
try
{
	$nic = Get-WmiObject Win32_NetworkAdapterConfiguration -filter "ipenabled = 'true'"
	$nic.SetTcpipNetbios(2) | Out-Null
	Write-Host "Successfully disabled NetBIOS over TCP/IP" -ForegroundColor 'DarkGreen'
}
catch
{
	Write-Host "Failed to disable NetBIOS over TCP/IP: $($_.Exception.Message)" -ForegroundColor 'Red'
}

The SetTcpipNetbios() method returns an object. If you don't deal with it (Out-Null throws it away) it will be returned and shown in the console.

Cheers,
Fred

March 20th, 2015 7:50pm

FWN - you forgot a few 'Stop' params.

Don't think I did. Get-WmiObject failure to find anything with the given filter will return $null. Then calling a method on a null object will throw a terminating error and thus be caught.

Other errors while running Get-WmiObject probably ought to be read, thus displaying them instead of merely suppressing them would be good. The invalid method call later on will still be caught, so it won't report success anyway.

Any other error-actions I missed?

Free Windows Admin Tool Kit Click here and download it now
March 20th, 2015 7:57pm

FWN - you forgot a few 'Stop' params.

Don't think I did. Get-WmiObject failure to find anything with the given filter will return $null. Then calling a method on a null object will throw a terminating error and thus be caught.

Other errors while running Get-WmiObject probably ought to be read, thus displaying them instead of merely suppressing them would be good. The invalid method call later on will still be caught, so it won't report success anyway.

Any other error-actions I m

March 20th, 2015 8:15pm

Fred,

I have one more item I would like to add to the main one up top. Not sure how to add the &false and $true.  so it is added to the bottom read out for everything that completed or failed.

Set-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\services\Tcpip\Parameters -Name SyncDomainWithMembership -Value "0" -Force



Free Windows Admin Tool Kit Click here and download it now
March 20th, 2015 9:57pm

Hi Garrett,

as before, this is a case for try / catch. You'll need to enforce the ErrorAction 'Stop' once again though:

try
{
    Set-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\services\Tcpip\Parameters -Name SyncDomainWithMembership -Value "0" -Force -ErrorAction 'Stop'
    # ...
}
catch
{
    # ...
}

A little background on error handling in PowerShell: There are two kinds of errors - terminating and non-terminating. Terminating errors are grave errors, where the programmer decided that afterwards, there is no point in proceeding with an action.

Non-Terminating errors are more like minor flaws, where-after continuing might still make sense. A try / catch statement tries to do whatever is in the curly braces of the try until something grave enough to stop happens (a terminating error) or until it's done.

If a terminating error occurs, it immediately stops the try block and continues with the catch block (which is ignored if everything works fine).

Now we may have a different opinion than the cmdlet programmer about what constitutes a critical error for our script. That is handled by the -ErrorAction parameter.

  • 'Stop' turns any error into a terminating error
  • 'Continue' turns any error into a non-terminating error
  • 'SilentlyContinue' is the same as Continue but doesn't show the error on the screen
  • 'Ignore' is similar to SilentlyContinue, but doesn't even log the error (normally, all uncaught-errors can be retrieved with the $error variable)
  • 'Inquire' allows you to let the user decide how s/he wants to handle a given error.

Cheers,
Fred

March 21st, 2015 3:28am

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics