共用方式為


Output formatted PowerShell data to file (LogWrite)

I am sure that I am not the only person that got frustrated with not being able to output formatted PowerShell tables to file (am I?!)...If you too are still seeing this logged in your output file, read on:

The above output file was a result of the following command: Get-SCVirtualMachine | ft Name | export-csv C:\Output.txt

In order to overcome this issue I have discovered "LogWrite", by simply adding the following lines to the beginning of your script, you will be able to log any results/comments to the output file:

$Logfile = Read-Host "Enter the LogFile Path (example: C:\Output.txt)"
Function LogWrite
{
Param ([string]$logstring)

Add-content $Logfile -value $logstring
}

So, now using the above command I am able to create a script that will return the values I was originally attempting to capture.

Script used to generate the above Output.txt:

$Logfile = Read-Host "Enter the LogFile Path (example: C:\Output.txt)"
Function LogWrite
{
Param ([string]$logstring)
Add-content $Logfile -value $logstring
}
LogWrite "VMName"
ForEach ($VM in Get-SCVirtualMachine){
LogWrite $VM.Name
}

This is just another one of those simple PowerShell tricks that allow you to overcome a frustrating task.

Comments

  • Anonymous
    January 01, 2003
    Great, easy alternative. thanks for the comment
  • Anonymous
    May 20, 2015
    Or you could use Get-SCVirtualMachine | Select Name | export-csv C:Output.txt