4

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
}
2
  • 1
    Thomas Stringer's got it. Commented Jul 23, 2015 at 19:33
  • Can't you pipe the Get-ADGroupMember to Out-File within the loop? Commented Jul 23, 2015 at 23:14

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

I tried this but it just stores the header tags of all the jobs. What am i doing wrong?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.