Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Redirections changes "get-alias" command return code in powershell

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading