简体   繁体   中英

Basic multiple if statement logic flow syntax in PowerShell

I can't seem to understand how to continue to another IF statement. What I'm trying to do is:

  • IF Action 1 succeed then do X AND go to Action 2, else log it and RETURN to the next loop
  • If Action 2 succeed then do X AND go to Action 3, else log it and RETURN to the next loop

I am having issues with "AND go to Action 2" after action 1. I tried various ways but obviously the script below does not work. It can do Action 1 the test-connection, and if it succeeds will export the log else it will log a failure and RETURN to the next loop. HOWEVER, I cannot make it do the next action if successful.

$hostname = Import-Csv C:\Users\jackie.cheng\Desktop\TestComputers.csv

$hostname | % {

if (Test-Connection $_.hostname -count 1)

{Write-Host "$($_.hostname) Test-Connection Succeeded"
            $array += [pscustomobject]@{
                Name = $currentobject.hostname
                Status = "Test-Connection Success"}
}

else  {Write-Host "$($_.hostname) Test-Connection Failed"
            $array2 += [pscustomobject]@{
                Name = $currentobject.hostname
                Status = "Failed Test-Connection"}
       } return

if (Test-Connection $_.hostname -count 1)

{Write-Host "Second action ran"}

else {Write-Host "Second action failed"} return


}

Within the script block of a Foreach-Object , which is the full name of the command with the alias % , you can in fact use return to skip any statements after the return, and continue on to the next loop.

In your case you simply need to move your return into your else blocks like this:

If (Success Condition){
   Actions to do on success
}
else{
   Actions to do on fail
   return
}

If (Success Condition 2){
   ...
}
else{
   ...
   return 
}

As mentioned in the comments to your question, be sure to read up on how return works in PowerShell as it is somewhat unusual and behaves differently in different contexts.

I would do it this way, just output the objects for either case. Notice the indenting to help see the structure of the code. Return is usually not needed. -ea 0 means "-erroraction silentlycontinue".

Import-Csv TestComputers.csv |
% {
  if (Test-Connection $_.hostname -count 1 -ea 0) {
    [pscustomobject]@{
      Name = $_.hostname
      Status = $true}
  }
  else {
    [pscustomobject]@{
      Name = $_.hostname
      Status = $false}
  }
}


Name          Status
----          ------
yahoo.com       True
microsoft.com  False

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM