Peter
Peter

Reputation: 3

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

Upvotes: 0

Views: 8252

Answers (2)

Matt
Matt

Reputation: 46710

  • Add-Content $Servers - Add-content would expect that $servers is a file path. This is not what you want. See more from Add-Content.
  • | $Servers - $servers is not a function, cmdlet, alias or command that accepts pipeline input. This is not what you want. Here is a video that can be a start for understanding the pipeline. Not the best example but it is a start.
  • "> $Servers" - Redirection is also supposed to be used for file paths (for the most part.). $servers is not a file path. This is not what you want. See more from about_redirection.

You can just assign the output from the pipeline to a variable directly. This is what you could do. Other options do exist as well like building the array inside the loop. That is unnecessary.

$servers = "OU=Domain Controllers,$mydomain", "OU=Server,OU=Berlin,$mydomain" | ForEach-Object { 
    Get-ADComputer -Filter { OperatingSystem -Like '*Windows Server*' } -Properties OperatingSystem -SearchBase $_ } | 
    Select-Object -ExpandProperty Name

Or if you need to do both output to file and variable you can use Tee-Object

"OU=Domain Controllers,$mydomain", "OU=Server,OU=Berlin,$mydomain" | ForEach-Object { 
    Get-ADComputer -Filter { OperatingSystem -Like '*Windows Server*' } -Properties OperatingSystem -SearchBase $_ } | 
    Select-Object -ExpandProperty Name | Tee-Object -Variable servers | Add-Content "C:\serverfile.txt"

In both cases $servers will contain the output.

Upvotes: 1

Avshalom
Avshalom

Reputation: 8889

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} 

Upvotes: 0

Related Questions