Home > Software design >  Running a For Loop through a Multiline Powershell Variable
Running a For Loop through a Multiline Powershell Variable

Time:10-05

I have section of a script where the user enters a list of server names which then checks to make sure there they exist in AD and then runs a command on each of the ones that do exist. This is what I have:

$machineNames = (read-host "Enter Server Name(s) (space separated)").Trim()

foreach ($machineName in (($machineNames).Split(' '))) {
    Try {
        Get-ADComputer $machineName | Out-Null
        $veriMachineNames  = "$machineName`n"
    }
    Catch {
        Write-Host "*****Invalid Machine Name:  $machineName" -Foreground Yellow
        Write-Host "*****Skipping $machineName`n" -Foreground Yellow
    }
}

foreach ($machine in $sepMachineNames) {
    Write-Host "Server: $machine `n"
}

When I run this part of the script I get the following output (error intentionally included):

PS C:\> C:\script.ps1

Enter Machine Name(s) (space separated): server1 server2 server3
*****Invalid Machine Name:  server3
*****Skipping server3

Server: server1
server2

As you can see it appears that the second foreach is seeing server1 and server2 as being on one line and not two lines. Is there a way to do this with just a variable? I'd rather not output the list to a file.

CodePudding user response:

Instead of concatenating each name onto a big multi-line string manually, just output the individual names 1 by 1 and store them in a variable:

$veriMachines = foreach ($machineName in (($machineNames).Split(' '))) {
    Try {
        Get-ADComputer $machineName | Out-Null
        # no piping to `|Out-Null`, this will "bubble up" to the variable
        $machineName
    }
    Catch {
        Write-Host "*****Invalid Machine Name:  $machineName" -Foreground Yellow
        Write-Host "*****Skipping $machineName`n" -Foreground Yellow
    }
}

Now $veriMachines is an array of string (the machine names we just verified) that you can iterate over:

foreach($machine in $veriMachines){
    Write-Host "Server: $machine"
}
  • Related