M. Henderson
M. Henderson

Reputation: 51

How to output arrays to text file?

I borrowed code from Powershellbros.com which displays the requested data is returned properly in the output pane, but I want to output it to a txt file.

I got the code from https://www.powershellbros.com/powershell-tip-of-the-week-get-sccm-client-version-remotely/ and want the better formatted version. The way I ended the script creates the file, but nothing is in it (1KB).

if ($Array) {
    return $Array 
}
& $Array Out-File -Append c:\temp\Version.txt

Upvotes: 5

Views: 37968

Answers (4)

user3068371
user3068371

Reputation: 1

Simpler:

$Array | Tee-Object -Append c:\temp\Version.txt

See https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/tee-object

Upvotes: 0

Vlad
Vlad

Reputation: 33

This code actually works (verified just now):

foreach($line in $Array) 
{ 
  Add-Content "D:\data\filename.txt" $line
}

Upvotes: 0

Jeffrey Eldredge
Jeffrey Eldredge

Reputation: 969

You need to send $Array through the pipeline. Include the vertical bar.

$Array | Out-File -Append c:\temp\Version.txt

Upvotes: 16

AdminOfThings
AdminOfThings

Reputation: 25031

Assuming that $array does have data, you just need to add a pipe

If($Array) { Return $Array }
$Array | Out-File -append c:\temp\Version.txt

Upvotes: 5

Related Questions