fbpx

How To Use PowerShell Out-File Cmdlet Output To A File | 4 Best Ways Explained

PowerShell commands automatically send their results to the terminal. However, there are times when it’s more beneficial to utilize PowerShell to send the output to a file. We’re going to use the Out-File cmdlet for this.

The output of a PowerShell script or command can be done in a variety of ways. Even better, you can export the results to a file while simultaneously displaying it in the terminal. 

How Does Out-File Work?

This windows PowerShell cmdlet is straightforward in design. Its primary function is to save received output to a text file. It was made to take the place of the operator for ordinary output redirection (>). The PowerShell method is this cmdlet.
 
The powershell output final step commonly uses the Out-File cmdlet. Its main function is to carelessly transmit the raw output directly to a text file. There are only a few minor changes that can be made to the output.

Methods To Use PowerShell Out-File Cmdlet Output to Text File

  1. Sending Output to a File
  2. Appending to a File
  3. Using PowerShell Add-Content
  4. Powershell Write to Log File

1. Sending Output to a File

Consider the scenario where you have a script that outputs a list of all the Windows services that are configured to run automatically on your system. You will see every thing you may anticipate on the console when you execute Get-Service.

You might want to save that output to a text file though. To achieve that, the Out-File cmdlet is fantastic. It can be used by piping practically anything through the pipeline to it.

Get-Service | where{$_.StartType -eq "Automatic"} | Out-File -FilePath D:\automaticServices.txt
Get-Service | where{$_.StartType -eq "Automatic"} | Out-File -FilePath D:\automaticServices.txt
Get-Service | where{$_.StartType -eq "Automatic"} | Out-File -FilePath D:\automaticServices.txt

The output of Get-Service was passed to the cmdlet, which produced the exact console display in a text file called AutomaticServices.txt.

2.  Appending to a File

Everything in the existing file that is provided by the FilePath option is overwritten by default. By utilizing the Append argument, you can modify this behavior.

Perhaps you want to add text to a file rather than overwrite it as you accumulate console output in it. The output is appended to the end of the file when the Out-File -Append argument is used.

Get-Service | where{$_.StartType -eq "disabled"} | Out-File -append -FilePath D:\automaticServices.txt
Get-Service | where{$_.StartType -eq "disabled"} | Out-File -append -FilePath D:\automaticServices.txt
Get-Service | where{$_.StartType -eq "disabled"} | Out-File -append -FilePath D:\automaticServices.txt

3. Using PowerShell Add-Content

Using the Add-material cmdlet is another way to add material to a file. The ability to append material to many files at once is one of the main benefits of the Add-material cmdlet.

Similar to the redirect operator and out-file cmdlet, the add-content cmdlet generates a new file if one doesn’t already exist.


Consequently, we can use the following command to simply add content to a file:

Add-Content -Path D:\sample.txt -Value "New line to add"
Add-Content -Path D:\sample.txt -Value "New line to add"
Add-Content -Path D:\sample.txt -Value "New line to add"


We have a few factors to aid us in adding identical content to many files. To define the files that we wish to update, we can use wildcards in the path. We can also use a filter and exclude certain file names.

Add-Content -Path D:\*.txt -Value (Get-Date) -Exclude "readme*"
Add-Content -Path D:\*.txt -Value (Get-Date) -Exclude "readme*"
Add-Content -Path D:\*.txt -Value (Get-Date) -Exclude "readme*"

With the exception of the file with readme in the filename, the example below will add the current date to all TXT files in the path D::

Except for the readme files, all the files have been updated. You can define a string array of files that you want or do not want to update using the include and exclude options. 

4. Powershell Write to Log File

The Start-Transcript cmdlet is the ideal method for writing to a log file, although the Add-Content cmdlet or the redirect operator can also be used to create custom log functions.

The redirect operator will restrict your options, but it’s an excellent technique to only report a script’s errors to a log file:

Function Get-ProcessCpu {
    param(
        [Parameter(Mandatory = $true)]$name
    )
    Get-Process -Name $name | select cpu
}
Get-ProcessCpu -name "explorer2" 2>> "D:\$env:computername-process.log"
Powershell Write to Log File

However, you generally want to have a little bit more control when you are sending messages to a log file. It’s crucial that we can determine the event’s timing and seriousness using log files. Therefore, we wish to update the log message to include a timestamp and an event level.

$logFile = "D:\$env:computername-process.log"
Function Write-Log {
    param(
        [Parameter(Mandatory = $true)][string] $message,
        [Parameter(Mandatory = $false)]
        [ValidateSet("INFO","WARN","ERROR")]
        [string] $level = "INFO"
    )
    # Create timestamp
    $timestamp = (Get-Date).toString("yyyy/MM/dd HH:mm:ss")
    # Append content to log file
    Add-Content -Path $logFile -Value "$timestamp [$level] - $message"
}
Write-Log -level ERROR -message "String failed to be a string"
Powershell Write to Log File

This makes it simple for us to read the log file and locate any mistakes. The function shown above is an illustration of a straightforward PowerShell log file creator that enables you to add messages (events) to a log file along with the severity and timestamp.