Skip to content

Instantly share code, notes, and snippets.

@scanbix
Last active October 3, 2023 09:28
Show Gist options
  • Save scanbix/ab375f534e346df112709d745d288dac to your computer and use it in GitHub Desktop.
Save scanbix/ab375f534e346df112709d745d288dac to your computer and use it in GitHub Desktop.
$LASTEXITCODE. It will always be the exit code of the last program you ran in the current session.
$LastExitCode is the return code of native applications. $? just returns True or False depending on whether the last command (cmdlet or native) exited without error or not.
PowerShell writes its messages to different streams that can be redirected to files for capturing the respective output.
Stream 1 (default): regular output ("STDOUT")
Stream 2: error messages ("STDERR"), including error messages from external programs
Stream 3: warning messages
Stream 4: verbose messages
Stream 5: debug messages
Stream 6: information messages (only PowerShell v5 and newer)
To capture a particular stream in a file you need to redirect the stream number to a file name. Overwrite >, append >>.
# Error stream into standard
$msg = command 2>&1
# Error stream to file
command 2>error.txt
# You can also combine other streams with STDOUT to process/redirect all command output:
command >>"C:\path\to\all.log" *>&1
# Capture the messages it sends to console this way:
$output = [string[]] (.\Cli.exe -p $param 2>&1)
#
Calling other scripts and commnads https://stackoverflow.com/questions/1673967/how-to-run-an-exe-file-in-powershell-with-parameters-with-spaces-and-quotes
#
https://www.tutorialspoint.com/powershell/if_else_statement_in_powershell.htm
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_operators?view=powershell-7.3#call-operator-
https://learn.microsoft.com/en-us/powershell/scripting/learn/shell/running-commands?view=powershell-7.3
# other powershell cheatsheets
https://gist.github.com/pcgeek86/336e08d1a09e3dd1a8f0a30a9fe61c8a
#
arr = @(1,2,3)
$msg1 = "$arr.length"
echo $msg1 # prints 1 2 3.length - .length was treated as part of the string
$msg2 = "$($arr.length)"
echo $msg2 # prints 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment