I want test if an alias exist with the following code :
if( (get-alias ls) ) {
echo "=> Alias ls already exits."
} else {
echo "=> Alias ls does not exit."
}
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 exit."
}
I expected this output when run :
=> Alias ls already exits.
But the outcome of the code snippet somehow changed :
=> Alias ls does not exit.
If I redirect after the first set of parenthesis, I also get :
=> Alias ls does not exit.
Why does redirection interfere with the result ?
>Solution :
If tests whether or not there’s output, not the result code "$?" of the command.
echo hi > foo
if (dir foo > $null) { 'yes' } <# no result #>
if ($(dir foo > $null; $?)) { 'yes' }
yes