I want test if an alias exists with the following code :
if( (get-alias ls) ) {
echo "=> Alias ls already exists."
} else {
echo "=> Alias ls does not exist."
}
When run, it says :
CommandType Name Version Source
----------- ---- ------- ------
Alias ls -> Get-ChildItem
=> Alias ls already exits.
I tried to redirect the output of the command to $null :
if( (get-alias ls >$null) ) {
echo "=> Alias ls already exits."
} else {
echo "=> Alias ls does not exist."
}
I expected this output when run :
=> Alias ls already exists.
But the outcome of the code snippet somehow changed :
=> Alias ls does not exist.
If I redirect after the first set of parenthesis, I also get :
=> Alias ls does not exist.
Why does redirection interfere with the result?
If
tests whether or not there's output, not the result code $?
of the command. You can combine two statements with $( )
.
echo hi > foo
if (dir foo > $null) <# no result #> { 'yes' }
if ($(dir foo > $null; $?)) { 'yes' }
yes