2

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

1 Answer 1

2

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."
}
Sign up to request clarification or add additional context in comments.

1 Comment

-EA SilentlyContinue doesn't work most of the time usually you have to do $ErrorAction = "SilentlyContinue" on a separate line or > Out-Null as mentioned above

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.