Freddie R
Freddie R

Reputation: 387

Pipe a string through multiple if-statements with an else for each

Essentially I have an If statement that has two conditions using -and, which a string is then run through. However, what I really want is the string to be run through the first condition, then if that is true, it checks for the second, and if that is true it does one thing, and if it is false do something else.

I currently have:

if(($_ -match "/cls") -and ($env:UserName -eq $Name)){cls}

I know I can do what I want with:

if(($_ -match "/cls") -and ($env:UserName -eq $Name)){cls}
 elseif(($_ -match "/cls") -and ($env:UserName -ne $Name)){OTHER COMMAND}

But I would like to know if there was a more simple way.

(The result is already being piped in from somewhere else, hence the $_)

Upvotes: 2

Views: 503

Answers (2)

jessehouwing
jessehouwing

Reputation: 114822

Move the first match to the outer scope.

if($_ -match "/cls") 
{
   if ($env:UserName -eq $Name))
   {
      cls 
   } 
   else
   {
      other command
   }
}

Upvotes: 3

Martin Brandl
Martin Brandl

Reputation: 58981

I would write two if statements to improve readabilty. This way, you also need the pipeline value only once::

if($_ -match "/cls") 
{
    if ($env:UserName -eq $Name)
    {
        cls
    }
    else
    {
        #OTHER COMMAND
    }
}

Upvotes: 2

Related Questions