Announcement

Collapse
No announcement yet.

Error Handling with Powershell

Collapse
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Error Handling with Powershell

    Ok,
    First time I use powershell...
    I've to create about 1200 DHCP scopes on 2 servers.

    So far so good, I created a pretty simple script which reads from a csv file and dumps it into DHCP using the netsh command..

    Code:
    import-csv c:\DHCP.csv | foreach-object {
    
    $scopename = $_.DHCP_Names
    $scope = $_.Networkrange
    $mask = $_.Mask
    $gateway = $_.Gateway
    $lowResStart = $_.Res1_start
    $lowResEnd = $_.Res1_stop
    $DHCP1_start = $_.DHCP1_start
    $DHCP1_stop = $_.DHCP1_stop
    $DHCP2_start = $_.DHCP2_start
    $DHCP2_stop = $_.DHCP2_stop
    $highResStart = $_.Network_start
    $highResStop = $_.network_stop
    $leasetime = $_.Leasetime
    $hname = $env:computername
    $currentServer = ""
    
    # find out hostname where script is running.
    # this is to decide what scope should be excluded.
    
    $hname = $env:computername
    $currentserver = ""
    if ($hname -eq "WINDOWS2008DHCP") {$currentserver = "DHCP1"} 
    If ($hname -eq "SERVER1") {$currentserver = "DHCP2"}
    
    
    # Add DHCP scope on the running server
    netsh dhcp server add scope $scope $mask $scopename # servername needs to be added.... still to come..
    
    # add the IP range
    
    if ($lowResStart -ne "" -and $highResStop -ne ""){
    netsh dhcp server scope $scope add iprange $lowResStart $highResStop   # ff verder nakijken hoe dit te verwerken in Excel.
    }
    else
    {
      if ($currentserver -eq "DHCP1"){
    	netsh dhcp server scope $scope add iprange $DHCP1_start $DHCP1_stop
      }
      if ($currentserver -eq "DHCP2"){
     	netsh dhcp server scope $scope add iprange $DHCP2_start $DHCP2_stop
      }
    }
    
    
    # 3. Connect to (DHCP-01 MyScope), and add IP exclusion range
    
    
    	if ($LowResStart -ne "" -AND $LowResEnd -ne "" ) {
    
    	netsh dhcp server scope $scope add excluderange $LowResStart $lowResEnd
    	}
    	if ($highResStart -ne "" -AND $highResStop -ne "" ) {
    	netsh dhcp server scope $scope add excluderange $highResStart $highResStop
    	}
    
    
    	# When current server equals to the first DHCP server (where the scrupt is executed) then set the exclusions for DHCP2
    	if ($currentserver -eq "DHCP1"){
    		if ($DHCP2_start -ne "" -OR $DHCP2_stop -ne ""){
    		 netsh dhcp server scope $scope add excluderange $DHCP2_start $DHCP2_stop
    		}
    	 }
    
    	 # When current server quals to the second DHCP server (where the scrupt is executed) then set the exclusions for DHCP1
    	if ($currentserver -eq "DHCP2"){
    		if ($DHCP1_start -ne "" -OR $DHCP1_stop -ne ""){
    		 netsh dhcp server scope $scope add excluderange DHCP1_start $DHCP1_stop
    		}
    	 }
    	 
    # 4 Add default Gateway for that scope
    netsh dhcp server  scope $scope set optionvalue 003 IPADDRESS $gateway
    
    # 5 Add lease time...
    netsh dhcp server  scope $scope set optionvalue 51 DWORD $leasetime
    
    }
    However is there a way to check if each command succesfully?
    Sure I can simply run script > textfile.txt or something but I'm more looking for an elegant way.

    so what I actually wanting to do is something like:

    Code:
    $compare = netsh dhcp server  scope $scope set optionvalue 51 DWORD $leasetime
    	If ($compare.EndsWith("successfully.")) {
    		write-host "Successfull...."
    	}
    	else {
    		write-host "NOT Successfull.... starting some log function"
    	}
    For some reason sometimes it works and sometimes it doesnt.. It especially works when it gives me the else statement... :S

    If it's true then it actually give me this error message.
    Method invocation failed because [System.Object[]] doesn't contain a method named 'EndsWith'.



    Edit:

    this test script simply works, so it has something to do with the results i guess...

    Code:
    $compare =  "Changed the current scope context to 192.168.21.0 scope.  Command completed successfully."
    
    #write-host $compare
    
    If ($compare.EndsWith("successfully.")) {
    write-host "boe"
    }
    else
    {
    write-host "boeboe"
    }
    Marcel
    Technical Consultant
    Netherlands
    http://www.phetios.com
    http://blog.nessus.nl

    MCITP(EA, SA), MCSA/E 2003:Security, CCNA, SNAF, DCUCI, CCSA/E/E+ (R60), VCP4/5, NCDA, NCIE - SAN, NCIE - BR, EMCPE
    "No matter how secure, there is always the human factor."

    "Enjoy life today, tomorrow may never come."
    "If you're going through hell, keep going. ~Winston Churchill"


  • #2
    Re: Error Handling with Powershell

    In your script $compare is of type Object[] (System.ArrayObject) when you create it for the netsh command line. And of type String (System.Object) when you had entered the string for testing.

    To get the results as a string try this (I have not yet tested this with netsh.exe):
    Code:
    $results = (netsh dhcp server  scope $scope set optionvalue 51 DWORD $leasetime) 2>&1
    $compare = "$($results)".trim()
    
    	If ($compare.EndsWith("successfully.")) {
    		write-host -foregroundcolor Green "Successfull...."
    	}
    	else {
    		write-host -foregroundcolor Red "NOT Successfull.... starting some log function"
    	}
    Or, maybe better would it to retrieve the exit code (I have not yet tested this with netsh.exe):
    Code:
    (netsh dhcp server  scope $scope set optionvalue 51 DWORD $leasetime) 2>&1
    $lec_netsh1 = $lastexitcode
    
       if ($lec_netsh1 -ne 0)
       {
           $results = "Failed"
           Write-Host -foregroundcolor Red "NOT Successfull.... ***Error code $lec_netsh1"
           #exit 1
       } ELSE
       {
          $results = "Success"
          Write-Host -foregroundcolor Green "Successfull.... "
       }
    Write-Host "last result...: $results"
    \Rems
    Last edited by Rems; 20th July 2009, 22:22.

    This posting is provided "AS IS" with no warranties, and confers no rights.

    __________________

    ** Remember to give credit where credit's due **
    and leave Reputation Points for meaningful posts

    Comment


    • #3
      Re: Error Handling with Powershell

      Ahh ik think I see what I've missed... the 2>&1 thingie... And setting a $sign for the netsh command...
      Hmmm don't know what it does, but I will check it out tomorrow.

      Oh btw, $compare was another test where I thought that $results might be a restricted variable
      Pretty cool that Powershell... I've somewhere a book about it.. I think I should look it up
      Marcel
      Technical Consultant
      Netherlands
      http://www.phetios.com
      http://blog.nessus.nl

      MCITP(EA, SA), MCSA/E 2003:Security, CCNA, SNAF, DCUCI, CCSA/E/E+ (R60), VCP4/5, NCDA, NCIE - SAN, NCIE - BR, EMCPE
      "No matter how secure, there is always the human factor."

      "Enjoy life today, tomorrow may never come."
      "If you're going through hell, keep going. ~Winston Churchill"

      Comment


      • #4
        Re: Error Handling with Powershell

        Don't forget the trim() function, because otherwise the sting to compare with should end with a space.
        I think it is better to compare the error level than the output string.

        \Rems

        This posting is provided "AS IS" with no warranties, and confers no rights.

        __________________

        ** Remember to give credit where credit's due **
        and leave Reputation Points for meaningful posts

        Comment


        • #5
          Re: Error Handling with Powershell

          The last one seems to work nicely.
          I've a question, how is the $lastexitcode being filled?
          Ah it seems to work just like @errorlevel... ok thanks!

          Hmmm this script seems to start going somewhere
          Update 3: hmmmm quite cool that powershell....
          whoohoo...
          This script worked flawlessly in my lab


          Code:
          function errorhandling
          {
          
          param ($ParsedLEC, $where)
          
          if ($ParsedLEC -ne 0){
          	$whatresults = "Failed"
          	Write-Host -foregroundcolor Red " Failed to create the $($where) with VLAN_ID $($scopename)... start logging...."
          	}
          ELSE{	
          	$whatresults = "Success"
          	Write-Host -foregroundcolor Green "Successfully created the $($where) for VLAN_ID" $scopename
             	}
          
          	if ($whatresults -eq "Failed"){
          		$logFile = "c:\DHCPerror.log"
          			if(! (Test-Path $logFile)) {New-Item -ItemType file $logFile}
          		$content = "Failed to create the $($where) with VLAN_ID $($scopename)"
          		add-content $logFile $content
          	}
          }
          
          
          
          function mainscript
          {
          import-csv c:\DHCP.csv | foreach-object {
          
          
          #declaring variables....
          $scopename = $_.DHCP_Names
          $scope = $_.Networkrange
          $mask = $_.Mask
          $gateway = $_.Gateway
          $lowResStart = $_.Res1_start
          $lowResEnd = $_.Res1_stop
          $DHCP1_start = $_.DHCP1_start
          $DHCP1_stop = $_.DHCP1_stop
          $DHCP2_start = $_.DHCP2_start
          $DHCP2_stop = $_.DHCP2_stop
          $highResStart = $_.Network_start
          $highResStop = $_.network_stop
          $leasetime = $_.Leasetime
          $hname = $env:computername
          $currentServer = ""
          
          # find out hostname where script is running.
          # this is to decide what scope should be excluded.
          
          $hname = $env:computername
          if ($hname -eq "WINDOWS2008DHCP") {$currentserver = "DHCP1"} 
          If ($hname -eq "SERVER1") {$currentserver = "DHCP2"}
          
          ####################################################################################################################
          
          
          
          # 1.  Add DHCP scope on the running server
          
          	if ($currentserver -eq "DHCP1")
          	{
          		If ($lowResStart -ne "" -OR $DHCP1_start -ne "")
          		{
          			write-host "Creating scope for DHCP1"
          			$resultings = (netsh dhcp server add scope $scope $mask $scopename) 
          			$lec_netsh1 = $lastexitcode
          			errorhandling $lec_netsh1 scope
          		}
          	}
          
          	if ($currentserver -eq "DHCP2")	{
          		
          		If ($lowResStart -ne ""-OR $DHCP2_start -ne "")
          		{
          			$resultings = (netsh dhcp server add scope $scope $mask $scopename) 
          			$lec_netsh1 = $lastexitcode
          			errorhandling $lec_netsh1 scope
          		}
          	}
          
          	
          	
          # 2.  add the IP range
          
          
          	# add the IP range
          	if ($lowResStart -ne "" -and $highResStop -ne ""){
          		$resultings = (netsh dhcp server scope $scope add iprange $lowResStart $highResStop)   # LowResStart wordt alleen gebruikt wanneer deze ingegeven is.
          		$lec_netsh1 = $lastexitcode
          		errorhandling $lec_netsh1 iprange
          
          	}
          	else{ 									# When lowResStart & highResStop is not filled in the CSV file, then we will create the scope based on the DHCP scope itself.
          		if ($currentserver -eq "DHCP1"){
          			if ($DHCP1_start -ne ""){
          				$resultings = (netsh dhcp server scope $scope add iprange $DHCP1_start $DHCP1_stop)
          				$lec_netsh1 = $lastexitcode
          				errorhandling $lec_netsh1 iprange
          			}
          		}
          		if ($currentserver -eq "DHCP2"){
          			if ($DHCP2_start -ne ""){
          				$resultings = (netsh dhcp server scope $scope add iprange $DHCP2_start $DHCP2_stop)
          				$lec_netsh1 = $lastexitcode
          				errorhandling $lec_netsh1 iprange
          			}
          		}
          	}
          
          
          # 3. Connect to (DHCP-01 MyScope), and add IP exclusion range
          
          	if ($LowResStart -ne "" -AND $LowResEnd -ne "" ) {
          		$resultings = (netsh dhcp server scope $scope add excluderange $LowResStart $lowResEnd)
          		$lec_netsh1 = $lastexitcode
          		errorhandling $lec_netsh1 exclusion
          	}
          	if ($highResStart -ne "" -AND $highResStop -ne "" ) {
          		$resultings = (netsh dhcp server scope $scope add excluderange $highResStart $highResStop)
          		$lec_netsh1 = $lastexitcode
          		errorhandling $lec_netsh1 exclusion
          	}
          
          
          																																			# When current server equals to the first DHCP server (where the script is executed) then set the exclusions for DHCP2
          	if ($currentserver -eq "DHCP1"){
          		if ($DHCP2_start -ne "" -OR $DHCP2_stop -ne "" -AND $DHCP1_start -ne "" ){
          			$resultings = (netsh dhcp server scope $scope add excluderange $DHCP2_start $DHCP2_stop)
          			$lec_netsh1 = $lastexitcode
          			errorhandling $lec_netsh1 exclusion
          	 	}
          	}
          
          																																			# When current server quals to the second DHCP server (where the script is executed) then set the exclusions for DHCP1
          	if ($currentserver -eq "DHCP2"){
          
          		if ($DHCP1_start -ne "" -OR $DHCP1_stop -ne "" -AND $DHCP2_start -NE ""){
          			$resultings = (netsh dhcp server scope $scope add excluderange $DHCP1_start $DHCP1_stop)
          			$lec_netsh1 = $lastexitcode
          			errorhandling $lec_netsh1 exclusion
          		}
          	 }
          	 
          # 4 Add default Gateway for that scope
          
          	if ($currentserver -eq "DHCP1" -and $DHCP1_start -ne "" ){
          		$resultings = (netsh dhcp server  scope $scope set optionvalue 003 IPADDRESS $gateway)
          		$lec_netsh1 = $lastexitcode
          		errorhandling $lec_netsh1 gateway
          	}
          	
          
          
          	if ($currentserver -eq "DHCP2" -and $DHCP2_start -ne "" ){
          		$resultings = (netsh dhcp server  scope $scope set optionvalue 003 IPADDRESS $gateway)
          		$lec_netsh1 = $lastexitcode
          		errorhandling $lec_netsh1 gateway
          	}
          
          # 5 Add lease time...
          
          if ($currentserver -eq "DHCP1" -and $DHCP1_start -ne "" ){
          	$resultings = (netsh dhcp server  scope $scope set optionvalue 51 DWORD $leasetime)
          	$lec_netsh1 = $lastexitcode
          	errorhandling $lec_netsh1 leasetime
          }
          
          if ($currentserver -eq "DHCP2" -and $DHCP2_start -ne "" ){
          	$resultings = (netsh dhcp server  scope $scope set optionvalue 51 DWORD $leasetime)
          	$lec_netsh1 = $lastexitcode
          	errorhandling $lec_netsh1 leasetime
          }
          } #END FOR-LOOP
          
          
          } #end function
          
          
          
          ########################################## START OF the script.... ############################################
          
          ########################################## Check Service Existence ############################################
          $serviceresults = Get-Service "DHCPserver"
          
          if ($serviceresults -eq "")
          {
          	write-host -foregroundcolor Red "***********************************************************************"
          	Write-host -foregroundcolor Red "NO DHCP server found"
          	write-host -foregroundcolor Red "***********************************************************************"
          	break
          }
          	if ($serviceresults.Status -NE "Running") 
          	{
          		write-host -foregroundcolor Yellow "***********************************************************************"
          		write-host -foregroundcolor Yellow "DHCP Server has not been started..."
          		write-host -foregroundcolor Yellow "***********************************************************************"
          		break
          	}
          	
          	else	{  
          			clear
          			write-host -foregroundcolor Green "***********************************************************************"
          			write-host -foregroundcolor Green "DCHP server is running"
          			write-host -foregroundcolor Green "Starting importing CSV file and running the rest of the script......"
          			write-host -foregroundcolor Green "***********************************************************************"
          			mainscript
          		}
          Last edited by Dumber; 23rd July 2009, 09:53.
          Marcel
          Technical Consultant
          Netherlands
          http://www.phetios.com
          http://blog.nessus.nl

          MCITP(EA, SA), MCSA/E 2003:Security, CCNA, SNAF, DCUCI, CCSA/E/E+ (R60), VCP4/5, NCDA, NCIE - SAN, NCIE - BR, EMCPE
          "No matter how secure, there is always the human factor."

          "Enjoy life today, tomorrow may never come."
          "If you're going through hell, keep going. ~Winston Churchill"

          Comment

          Working...
          X