Reputation: 183
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
Upvotes: 0
Views: 1326
Reputation: 4069
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)
Upvotes: 1