dobbs
dobbs

Reputation: 1043

PowerShell for-each loop output to file

How do I output/append the contents of this foreach loop to a text file?

The following below is not working out.

$Groups = Get-AdGroup -Properties * -filter * | Where {$_.name -like "www*"}
Foreach($G in $Groups)
{
    write-host " "
    write-host $G.Name
    write-host "----------"
    get-adgroupmember -Identity $G | select-object -Property SamAccountName
    Out-File -filepath C:\test.txt -Append
}

Upvotes: 4

Views: 25180

Answers (1)

Thomas Stringer
Thomas Stringer

Reputation: 5862

$output = 
    Foreach($G in $Groups)
    {
        write-output " " 
        write-output $G.Name
        write-output "----------"
        get-adgroupmember -Identity $G | select-object -Property SamAccountName
    }

$output | Out-File "C:\Your\File.txt"

All this does is saves the output of your foreach loop into the variable $output, and then dumps to data to your file upon completion.

Note: Write-Host will write to the host stream, and not the output stream. Changing that to Write-Output will dump it to the $output variable, and subsequently the file upon loop completion.

The reason your original code isn't working is that you're not actually writing anything to the file. In other words, you're piping no data to your Out-File call. Either way, my approach prefers a cache-then-dump methodology.

Upvotes: 13

Related Questions