Pickle
Pickle

Reputation: 1124

Outputting foreach loop in Powershell

I'm trying to simply get a list of computers and their OU's from a CSV file of computer names

Add-PSSnapin quest.activeroles.admanagement

$results = @()
$computers = Get-Content "computers.csv"

foreach ($computer in $computers)
{
    $results += Get-QADComputer $computer | select name, parentcontainer
}

$results = Export-CSV -path "computerswithous.csv"

But it errors out asking me to supply values. How can I simply output this data to a CSV file?

Upvotes: 1

Views: 2311

Answers (2)

Matt
Matt

Reputation: 46730

You did not include it in the post but is this what you were getting:

cmdlet Export-Csv at command pipeline position 1
Supply values for the following parameters:
InputObject: 

Simple answer is this line

$results = Export-CSV -path "computerswithous.csv"

Should most likely be this

$results | Export-CSV -path "computerswithous.csv"

In your example Export-CSV has no input data which is what your prompt (not error) is requesting. You actually want to pipe the $results to the CSV file.

You also could do away with that construct as well and just use standard pipeline to get what you are looking for.

Add-PSSnapin quest.activeroles.admanagement

Get-Content "computers.csv" | ForEach-Object{Get-QADComputer $_} | 
    Select Name,ParentContainer | Export-CSV -Path "computerswithous.csv" -NoTypeInformation

Upvotes: 1

mjolinor
mjolinor

Reputation: 68341

You don't need that intermediate collection ($results) at all. Just wrap the foreach loop in a sub-expression, and send it on to the pipeline.

Add-PSSnapin quest.activeroles.admanagement

$computers = Get-Content "computers.csv"

$(foreach ($computer in $computers)
{
  Get-QADComputer $computer | select name, parentcontainer
}) | Export-CSV -path "computerswithous.csv"

Upvotes: 0

Related Questions