so cal cheesehead
so cal cheesehead

Reputation: 2573

How to capture exit code from a cmdlet in a powershell script

I'm extremely new to powershell scripting and I'm having a hell of a time trying to capture whether something simply failed or succeeded. I have a simple example:

test1.ps1

get-psdrive -name ds | out-null

if($? -ne "False")
{ 
   echo "drive doesn't exist"
}
else { echo "Found drive" }

This however isn't working for me. I also tried the variable $LastExitCode but that doesn't work either. I'm seriously misunderstanding something here. Can someone please point me in the right direction or show me a working example

Upvotes: 2

Views: 5832

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200493

Try something like this:

$drive = Get-PSDrive -Name ds 2>Out-Null

or

$drive = Get-PSDrive -Name ds -EA SilentlyContinue

If the cmdlet is successful, $drive holds the drive object, otherwise its value is $null:

if ($drive -eq $null) {
  echo "Drive doesn't exist."
} else {
  echo "Found drive."
}

Upvotes: 2

Related Questions