Home > Mobile >  how to process multiple foreach statements separately?
how to process multiple foreach statements separately?

Time:11-23

I am very new at PowerShell and I don't even know how to Google this properly.

This is what I'm trying to do: run some commands at multiple computers.

I can get them to run command1 at computerA, then command2 at computerA, then command3 at Computer A... then command1 at computerB command2 at computerB...and so forth

But I want to run command1 at all the computers then command2 at all the computers then command3 ...etc

So this is how it is right now: 1A 2A 3A 1B 2B 3B 1C 2C 3C...

Is is possible to do this in the if $state -eq 'Start' statement?

1A 1B 1C 2A 2B 2C 3A 3B 3C... without creating another function?

I don't want to reverse everything, just the "start" statement that I need to follow that pattern.

This is my basically what I have right now:

$Computers = "ComputerA","ComputerB","ComputerC"
function Set-CService {
param(
    [Parameter(Mandatory)]
    [ValidateSet('Start','Stop','Restart','Install')]
    [string]$State,

    [Parameter(Mandatory, ValueFromPipeline)]
    [array]$Computers
)

process {
$ErrorActionPreference = "SilentlyContinue"

If ($state -eq 'Start') {
foreach ($Computer in $Computers) {Write-Host "statement1 on $Computer"}
foreach ($Computer in $Computers) {Write-Host "statement2 on $Computer"}
foreach ($Computer in $Computers) {Write-Host "statement3 on $Computer"}
}


foreach ($Computer in $Computers){
If ($State -eq 'Stop') {Write-Host "It is stopping on $Computer"}

If ($state -eq 'Restart') {
Write-Host "Restart statement1 on $Computer"
write-host "Restart statement2 on $Computer"
Write-Host "Restart statement3 on $Computer"}

If ($State -eq 'Install') {
Write-Host "Install statement1 on $Computer"
write-host "Install statement2 on $Computer"
Write-Host "Install statement3 on $Computer"}
                            }                                
        }
            }

$Computers | Set-CService -State Start

CodePudding user response:

Use Invoke-Command -AsJob to invoke the remote work loads as background jobs:

If ($state -eq 'Start') {
  # Kick off remoting jobs on each computer in $Computers
  $jobs = Invoke-Command -ComputerName $Computers -Scriptblock {
    Write-Host "statement1 on $env:ComputerName"
    Write-Host "statement2 on $env:ComputerName"
    Write-Host "statement3 on $env:ComputerName"
  } -AsJob

  # Wait for jobs to succeed, then receive the output
  $jobs |Receive-Job -Wait
}
  • Related