Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell for-each loop output to file

Tags:

powershell

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
}
like image 330
dobbs Avatar asked Oct 29 '25 18:10

dobbs


1 Answers

$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.

like image 157
Thomas Stringer Avatar answered Oct 31 '25 12:10

Thomas Stringer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!