Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output PowerShell variables to a text file

Tags:

powershell

I'm new to PowerShell and have a script which loops through Active Directory searching for certain computers. I get several variables and then run functions to check things like WMI and registry settings.

In the console, my script runs great and simple Write-Host command prints the data on the screen as I want. I know about Export-Csv when using the pipeline...but I'm not looking to print from the pipeline.

I want to write the variables to a text file, continue the loop, and check the next computer in AD...output the next iteration of the same variables on the next line. Here is my Write-Host:

Write-Host ($computer)","($Speed)","($Regcheck)","($OU) 

Output file:

$computer,$Speed,$Regcheck | out-file -filepath C:\temp\scripts\pshell\dump.txt -append -width 200 

It gives me the data, but each variable is on its own line. Why? I'd like all the variables on one line with comma separation. Is there a simple way to do this akin to VB writeline? My PowerShell version appears to be 2.0.

like image 805
user3067193 Avatar asked Dec 31 '13 13:12

user3067193


People also ask

How do you output a variable in PowerShell?

The echo command is used to print the variables or strings on the console. The echo command has an alias named “Write-Output” in Windows PowerShell Scripting language. In PowerShell, you can use “echo” and “Write-Output,” which will provide the same output.

How do I write a PowerShell script to a file?

There are a couple of ways to write the output of PowerShell to a file. The most common ways are to use the Out-File cmdlet or the redirection operator > . Other options are to use the Set-Content and Add-Content cmdlet.

How do you write output to a file?

the shortcut is Ctrl + Shift + S ; it allows the output to be saved as a text file, or as HTML including colors!


1 Answers

I usually construct custom objects in these loops, and then add these objects to an array that I can easily manipulate, sort, export to CSV, etc.:

# Construct an out-array to use for data export $OutArray = @()  # The computer loop you already have foreach ($server in $serverlist)     {         # Construct an object         $myobj = "" | Select "computer", "Speed", "Regcheck"          # Fill the object         $myobj.computer = $computer         $myobj.speed = $speed         $myobj.regcheck = $regcheck          # Add the object to the out-array         $outarray += $myobj          # Wipe the object just to be sure         $myobj = $null     }  # After the loop, export the array to CSV $outarray | export-csv "somefile.csv" 
like image 169
Trondh Avatar answered Sep 22 '22 14:09

Trondh