0

I am using Powershell version 5.1 on Windows 10.

I have the below code where I am trying to check the execution status, if it works then output as success else failed.

When I run the code, the code works, but it gives an output as failed.

Below is the code

if(Enable-LocalUser -Name TEST)
{
    Write-Host "Success"
}
else
{
    Write-Host "Failed"
}

How can I get a proper confirmation of the command execution? Please help

1
  • 1
    the Enable-LocalUser cmdlet does not return ANYTHING. [grin] from the help for that cmdlet >>> OUTPUTS - None - This cmdlet does not generate any output. <<< ///// that means your IF will always test against a $NULL and $NULL coerces to $False just like zero does. ///// instead, run the cmdlet and use something like (Get-LocalUser -Name $env:USERNAME).Enabled to test if the account is enabled. Commented Apr 24, 2019 at 6:54

1 Answer 1

1

You can use $? to check whether the last powershell command executed successfully or not :

Enable-LocalUser -Name TEST
if($?)
{
    Write-Host "Success"
}
else
{
    Write-Host "Failed"
}

If you wanted exception details , then i would suggest try catch :

try{
    Enable-LocalUser -Name TEST2 -ErrorAction Stop
    #The below line will only run if enable-localuser did not generate any exception
    Write-Host "Success"
}
catch
{
    Write-Host "Failed,Due to :"
    $_.exception
}

$? Contains the execution status of the last operation. It contains TRUE if the last operation succeeded and FALSE if it failed.(Excerpt from: Powershell Automatic Variables Documentation)

Sign up to request clarification or add additional context in comments.

3 Comments

If I need to capture the Exception Message, can I use the above code in try block and catch the exception?
@RajivIyer I have updated the answer with a version that gives exception details
Thank you very much for your help

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.