How can the $? be used in powershell.
It reports whether or not the last-run command considered itself to have completed successfully. You get no details on what happened with it. It returns a boolean value.
The $? variable is a Boolean value that is automatically set after each PowerShell statement or pipeline finishes execution. It should be set to True if the previous command was successful, and False if there was an error. If the previous command was a call to a native exe, $? will be set to True if the $LASTEXITCODE variable equals zero, and False otherwise. When the previous command was a PowerShell statement, $? will be set to False if any errors occurred (even if ErrorAction was set to SilentlyContinue or Ignore.)
Just be aware that the value of this variable is reset after every statement. You must check its value immediately after the command you’re interested in, or it will be overwritten (probably to True).
The $? variable doesn’t give you any details about what
error occurred; it’s simply a flag that something went wrong. In the case of calling executable programs,
you need to be sure that they return an exit code of 0 to indicate success and
non-zero to indicate an error before you can rely on the contents of $?.
Example:
Add-Computer -DomainName $Domain -Credential $cred -OUPath $OUPath
if ($? -ne 'True') {exit 100} #if the above line of command failed for some reason it returns 'False' or if it successfully completed it returns 'True'.
Simpler example.
Happy scripting..
No comments:
Post a Comment