Willy
Willy

Reputation: 41

Try method in powershell

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]

Upvotes: 0

Views: 1342

Answers (4)

Lee
Lee

Reputation: 145

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.

Upvotes: 0

Shay Levy
Shay Levy

Reputation: 126712

You can simply suppress errors with the ErrorAction parameter:

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

Upvotes: 2

Keith Hill
Keith Hill

Reputation: 201602

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'.

Upvotes: 4

Related Questions