Search code examples
powershellvariablessyntaxoutputpipeline

Powershell Add Output of Select to Variable


I'd like to store the output of the command Select in a variable. Here's the original code:

# OUs to search for servers
"OU=Domain Controllers,$mydomain", "OU=Server,OU=Berlin,$mydomain" | 
# For each OU get Windows Server
ForEach { Get-ADComputer -Filter { OperatingSystem -Like '*Windows Server*' } -Properties OperatingSystem -SearchBase $_ } | 
Select -Exp Name | Add-Content C:\serverfile.txt

In the last line I'd like to change Add-Content to a command that adds the output to a variable $Servers. However I can't get the syntax right. I tried:

| Add-Content $Servers

| $Servers

"> $Servers"

$Servers += Select -Exp Name

Solution

  • You can create and array ($Servers for example) then add each result into it:

    $Servers = @()
    "OU=Domain Controllers,$mydomain", "OU=Server,OU=Berlin,$mydomain" | 
    # For each OU get Windows Server
    ForEach { $Servers += Get-ADComputer -Filter { OperatingSystem -Like '*Windows Server*' } -Properties OperatingSystem -SearchBase $_ | Select -ExpandProperty Name}