Link to home
Start Free TrialLog in
Avatar of ashsysad
ashsysadFlag for United States of America

asked on

Capturing Exit status in PowerCLI/PowerShell

Hello,

Please look at my PowerCLI script given below.  I'm taking a list of Virtual machine names in a file "sheet1.txt" and am trying to find the GuestOS Name for the corresponding Virtual Machines. The list actually consists of some Invalid Virtual Machine names. Hence when the command "Get-VM $VM_Name | Get-VMGuest" gets executed, it returns a "Not Found" error. I wish to capture that event and create an 'if-else' condition for it, based on the Exit status of the Get-VM command.

Based on the following link :   http://blogs.msdn.com/b/powershell/archive/2006/10/14/windows-powershell-exit-codes.aspx,  I tried to create an 'if-else' condition but it isn't working.   Could you please correct it and let me know. Basically am looking for "$?" (in unix) equivalent in powershell. Thanks in advance !!


-------------------------------------------------------------------------------------------------------------------------
$VM_list = Get-Content "C:\PCLI\VCM\sheet1.txt"

 foreach($VM_Name in $VM_list) {
       $vm = Get-VM $VM_Name | Get-VMGuest
      $check = echo %errorlevel%
      if($check -eq '0'){
            # Capturing Virtual Machine Name
            $OEL_VMname = $vm.VmName
            # Capturing the Guest OS Name
            $OS_Fullname = $vm.OSFullName
            # Redirecting to a File
            "$OEL_VMname`t`t$OS_Fullname" | Out-File -filepath C:\PCLI\VCM\result.txt -Append
      }
      else {
            "$VM_Name" | Out-File -filepath C:\PCLI\VCM\notfound.txt -Append
            }
    }
---------------------------------------------------------------------------------------------------------------------------------------
Avatar of stevejarvi
stevejarvi
Flag of United States of America image

Powershell does support "$?" but try using Try/Catch in this case.  I think it'll work better for what you're doing:

$VM_list = Get-Content "C:\PCLI\VCM\sheet1.txt"

 foreach($VM_Name in $VM_list) {
       
	Try {
		$vm = Get-VM $VM_Name | Get-VMGuest
		# Capturing Virtual Machine Name
		$OEL_VMname = $vm.VmName
		# Capturing the Guest OS Name
		$OS_Fullname = $vm.OSFullName
		# Redirecting to a File
		"$OEL_VMname`t`t$OS_Fullname" | Out-File -filepath C:\PCLI\VCM\result.txt -Append
	}
	Catch {
		"$VM_Name" | Out-File -filepath C:\PCLI\VCM\notfound.txt -Append
    }
   
   
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of stevejarvi
stevejarvi
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ashsysad

ASKER

Thankyou so much for your response. Let me check it out today and update you.
No problem. Lemme know how it works.

SJ
Hello stevejarvi,  This one worked as per my expectation. Thankyou so much !