Powershell - How to write output to file

C Emmons
C Emmons used Ask the Experts™
on
I am trying to figure out how to write data so that I can redirect it into a file.  For instance, if I have write-host $a,$b,$c -- it writes to the screen and on one line - which is what I want -- wonderful.  However, I want to capture data in a file -- I can't redirect "./test.ps1 > filename" because write-host doesn't redirect.  Some things I try don't put the data on one line -- but each field on a separate line.  Can someone tell me how to write comma-separated variables to  one line and redirect or write it to a file.Basically, I need the desired fields on one record on one line each - looping through multiple records - into a file.
Thanks
C Emmons
foreach ($objResult in $results)
    {$objItem = $objResult.Properties
	[string]$timestamp=$objitem.lastlogontimestamp
	$lstlogon = [datetime]::FromFileTime($timestamp)
       write-host $objItem.name,", ", $objitem.samaccountname,", ",$objItem.jobTitle,", ",$objItem.department,", ",$objItem.description,", ",$lstlogon 

      }

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Use Write-Output instead of Write-Host:

http://www.powershellpro.com/write-host/171/#comment-67
C EmmonsAdmin

Author

Commented:
This command puts each field on a separate line - I need fields for each record on one line each per record?
PS C:\scripts> $a=1
PS C:\scripts> $b=2
PS C:\scripts> $c=3
PS C:\scripts> write-output $a,$b,$c
1
2
3
PS C:\scripts> write-host $a,$b,$c
1 2 3
PS C:\scripts>
Thanks
Just enclose it in quotes:
 
Windows PowerShell
Copyright (C) 2006 Microsoft Corporation. All rights reserved.

PS C:\Users\Administrator> $a=1
PS C:\Users\Administrator> $b=2
PS C:\Users\Administrator> $c=3
PS C:\Users\Administrator> write-output $a,$b,$c
1
2
3
PS C:\Users\Administrator> write-output "$a,$b,$c"
1,2,3

Open in new window

C EmmonsAdmin

Author

Commented:
Thanks.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial