header
header Register : : Login header
header
divider
menuleft
menuright
submenu
left

[August 25th, 2008] Check the home page regarding PowerShell related news from a brand new sponsor: Idera

help with error handling & powershell
Last Post 06 Nov 2008 05:54 AM by glnsize. 1 Replies.
Printer Friendly
Sort:
PrevPrev NextNext
You are not authorized to post a reply.
Author Messages
gjw01User is Offline
New Member
New Member
Posts:1
Avatar

--
06 Nov 2008 02:21 AM  

hi

first attempt at a powershell script

have some vbscripting experience

basically, attempting to read a text file for server names, check if there any any dhcp enabled nics, then output results to a text file. im having issues with error handling, basically, if there is an access denied error, then the 'silentlycontinue' method of error handling dosent work. in the event of an error, id like a basic description of the error logged also.

Any idea why silentlycontinue with an access denied error dosent work, if the server is down, or dosent exist, then error handling works...

are there more efficient ways of capturing errors?

#####################################

write-host "Gathering list of dhcp enabled servers....."

#get list of servers to check
$List = get-content d:\pshellscripts\servers.txt.tst

#recreate outputfile
new-item d:\pshellscripts\list.txt -type file -force


ForEach ($Entry in $List)
{
$CS = Get-Wmiobject -Class Win32_NetworkAdapterConfiguration -Filter "IPEnabled=true" -ComputerName $entry -errorvariable myerror -erroraction silentlycontinue

if ($myerror -ne '0')
{
$entry + "," + $myerror + ","| out-file d:\pshellscripts\list.txt -append
}
else {$CS.__SERVER + "," + $CS.caption + "," + $CS.dhcpenabled | out-file d:\pshellscripts\list.txt -append}
}
###################################################

glnsizeUser is Offline
Basic Member
Basic Member
Posts:101

--
06 Nov 2008 05:54 AM  

I modified one of my earlier scripts Link... Try something like this.

Function Get-DHCPEnabled {
param ([string]$path,[string]$computer,[switch]$verbose)
    begin {
        #create an empty array to hold our results.
        $obj = @()
        $computers = @()
        if ($Verbose) {$VerbosePreference = "Continue"; $WarningPreference = "Continue"}
        
        #validate our params... why js... why must you delay V2!
        if ($path -and (Test-Path $path)) {
            $computers = Get-Content $path    
        } elseif ($computer) {
            $computers += $computer
        } else {
            Throw 'either -path <string> or -computer <string> must be supplied!'
        }
    }
    process {
        #Set ErrorAction to silent... we'll handle the error's ourselves.
        $ErrorActionPreference = "SilentlyContinue"
        
        foreach ($entry in $computers)
        {
            Write-Verbose "querying $entry ..."
            $results = Get-Wmiobject -Class Win32_NetworkAdapterConfiguration -Filter "IPEnabled=true" -ComputerName $entry 
        
            # If there was an error while attempting the gwmi call, there will be only one error.
            # We check that error to help annotate why we were unsuccessful.
            switch -regex ($Error[ 0 ].Exception)
            {
                "The RPC server is unavailable"
                {
                    Write-warning "RPC Unavailable on $computer"
                    $obj += "" | Select @{e={$entry};n='Target'},@{e={"RPC_Unavalable"};n='caption'}
                    continue
                }
                #vista/2k8
                "Access denied"
                {
                    Write-warning "Access Denied on $computer"
                    $obj += "" | Select @{e={$entry};n='Target'},@{e={"Access_Denied"};n='caption'}
                    continue
                }
                #XP/Server 2k3
                "Access is denied"
                {
                    Write-warning "Access Denied on $computer"
                    $obj += "" | Select @{e={$entry};n='Target'},@{e={"Access_Denied"};n='caption'}
                    continue
                }
                # No error -> record our info!
                $null
                {
                    $obj += "" | Select @{e={$entry};n='Target'},@{e={$results.caption };n='caption'},@{e={$results.dhcpenabled };n='DHCP'}
                }
            }
            $Error.clear()
        }
    }
    end {
        return $obj
    }
}

 

Instead of writing to a file in your script output full objects, and then pipe those objects to out-file. like so...

Get-DHCPEnabled -path d:\pshellscripts\servers.txt | out-file d:\pshellscripts\list.txt -Encoding ASCII

or a slightly more interactive approach, perhaps something like....

Get-DHCPEnabled -path d:\pshellscripts\servers.txt | ? {$_.DHCP -eq "True"} | out-file d:\pshellscripts\list.txt -Encoding ASCII

As you can see this is where putting in the effort to keep your data in powershell and objectized realy starts to pay off. Also while I'm still a fan of the server.txt, I would recomend supporting both a file, and adhoc.

Get-DHCPEnabled -Computer Server20 -verbose

by building that support in early you enable the flexibility to do stuff like...

1..20 | %{ Get-DHCPEnabled -Computer Server$($_) -verbose }

or for the Vmware fan (ME!)

get-vm | % {Get-DHCPEnabled -Computer $_.name}

Hope that helps, if I failed to explain something please let me know! 

~Glenn
 

You are not authorized to post a reply.

Active Forums 4.1
right
   
footer Sponsored by Quest Software • SAPIEN Technologies • ShellTools, LLC • Microsoft Windows Server 2008 footer
footer