tags:

views:

60

answers:

4

So I want to build a try method into my powershell script below. If I am denied access to a server, I want it to skip that server. Please help..

[code]$Computers = "server1", "server2"

Get-WmiObject Win32_LogicalMemoryConfiguration -Computer $Computers | Select-Object `
@{n='Server';e={ $_.__SERVER }}, `
@{n='Physical Memory';e={ "$('{0:N2}' -f ($_.TotalPhysicalMemory / 1024))mb" }}, `
@{n='Virtual Memory';e={ "$('{0:N2}' -f ($_.TotalPageFileSpace / 1024))mb" }} | `
Export-CSV "output.csv"[/code]
A: 

You can use trap to replicate Try/Catch, see http://huddledmasses.org/trap-exception-in-powershell/ or http://weblogs.asp.net/adweigert/archive/2007/10/10/powershell-try-catch-finally-comes-to-life.aspx for examples.

Stuart Dunkeld
In V2, there is built in support for try/catch/finally. The posts are out of date.
stej
+3  A: 

Try/catch functionality is built-into PowerShell 2.0 e.g.:

PS> try {$i = 0; 1/$i } catch { Write-Debug $_.Exception.Message }; 'moving on'
Attempted to divide by zero.
moving on

Just wrap you script in a similar try/catch. Note you could totally ignore the error by leaving the catch block empty catch { } but I would recommend at least spitting out the error info if your $DebugPreference is set to 'Continue'.

Keith Hill
A: 

You can simply suppress errors with the ErrorAction parameter:

Get-WmiObject Win32_LogicalMemoryConfiguration -Computer $Computers -ErrorAction SilentlyContinue | ...

Shay Levy
Just to qualify that statement a bit - you can suppress "non-terminating" errors with the ErrorAction parameter. :-)
Keith Hill
Indeed, thanks Keith :) (Wmi's 'Access Denied' is a "non-terminating" error)
Shay Levy
A: 

Use a filter function? Like this tutorial explains.

He passes a list of computers to his pipeline - first it tries to ping each one, and then only passes the ones that respond to the next command (reboot). You could customize this for whatever actual functionality you wanted.

Lee