Quantcast
Channel: PowerShell.com – PowerShell Scripts, Tips, Forums, and Resources
Viewing all articles
Browse latest Browse all 6937

Outputting "foreach" loop as a table to text file

$
0
0

Hello all,

New to powershell here. I have searched high and low on the internet reading about hash tables and format-table and so on, and have finally decided to come here for guidance. What I have is a text file full of contact usernames, and what I want to do is loop through those usernames and create a table containing columns for user attributes that I specify. For example, column 1 can contain user's displayname, column 2 can contain the user's email, column 3 could contain what the user is a Member of, etc. What I would like is to have the column header at the top, followed by values (like an excel spreadsheet). What I am currrently getting is the column header followed by the first value, and then the column header again followed by the next value, etc. It also seems tricky to me since I'm dealing with a Contact object and not a User object. Here is my current code:

$resultsfile = "C:\Results.txt"
clear-content $resultsfile

foreach($contact in gc C:\Contactnames.txt){

$mailobject = get-adobject -LDAPfilter "(&(objectclass=contact)(name=$contact))" -Properties mail | %{$_.mail}

$MemberOfobject = get-adobject -LDAPfilter "(&(objectclass=contact)(name=$contact))" -Properties MemberOf | %{$_.MemberOf}

$Nameobject = get-adobject -LDAPfilter "(&(objectclass=contact)(name=$contact))" -Properties Name | %{$_.Name}

$output = New-Object PSobject -Property @{
    "Name" = $nameobject
    "Email Address" = $mailobject
    "Member Of" = $memberofobject
    } | out-file $resultsfile -Append
write-output $output
}

notepad $resultsfile

 

If you remove the last "out-file" pipe from the PSObject, the table outputs in the powershell window perfectly.

What am I doing wrong? And is there an easier way to get the results I'm after?

 

EDIT: sorry forgot to indent code inside foreach loop for easier reading.

Viewing all articles
Browse latest Browse all 6937

Trending Articles