Tuesday, May 16, 2023
HomeSoftware TestingHow To Use PowerShell Out-File Cmdlet Output To A File

How To Use PowerShell Out-File Cmdlet Output To A File


PowerShell instructions robotically ship their outcomes to the terminal. Nevertheless, there are occasions when it’s extra useful to make the most of PowerShell to ship the output to a file. We’re going to make use of the Out-File cmdlet for this.

The output of a PowerShell script or command could be performed in quite a lot of methods. Even higher, you’ll be able to export the outcomes to a file whereas concurrently displaying it within the terminal. 

How Does Out-File Work?

This home windows PowerShell cmdlet is easy in design. Its major operate is to avoid wasting obtained output to a textual content file. It was made to take the place of the operator for atypical output redirection (>). The PowerShell technique is that this cmdlet.
 
The powershell output closing step generally makes use of the Out-File cmdlet. Its essential operate is to carelessly transmit the uncooked output on to a textual content file. There are just a few minor modifications that may be made to the output.

Strategies To Use PowerShell Out-File Cmdlet Output to Textual content File

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

1. Sending Output to a File

Think about the situation the place you will have a script that outputs a listing of all of the Home windows providers which can be configured to run robotically in your system. You will note each factor you might anticipate on the console if you execute Get-Service.

You may wish to save that output to a textual content file although. To attain that, the Out-File cmdlet is unbelievable. It may be utilized by piping virtually something by the pipeline to it.

Get-Service | the place{$_.StartType -eq "Computerized"} | 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 handed to the cmdlet, which produced the precise console show in a textual content file known as AutomaticServices.txt.

2.  Appending to a File

The whole lot within the current file that’s supplied by the FilePath choice is overwritten by default. By using the Append argument, you’ll be able to modify this habits.

Maybe you wish to add textual content to a file quite than overwrite it as you accumulate console output in it. The output is appended to the top of the file when the Out-File -Append argument is used.

Get-Service | the place{$_.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. Utilizing PowerShell Add-Content material

Utilizing the Add-material cmdlet is one other means so as to add materials to a file. The flexibility to append materials to many recordsdata directly is without doubt one of the essential advantages of the Add-material cmdlet.

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

Consequently, we will use the next command to easily add content material to a file:

Add-Content material -Path D:pattern.txt -Worth "New line so as 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 now just a few elements to help us in including an identical content material to many recordsdata. To outline the recordsdata that we want to replace, we will use wildcards within the path. We are able to additionally use a filter and exclude sure file names.

Add-Content material -Path D:*.txt -Worth (Get-Date) -Exclude "readme*"
Add-Content -Path D:*.txt -Value (Get-Date) -Exclude "readme*"
How To Use PowerShell Out-File Cmdlet Output To A File | 4 Finest Methods Defined 11
Add-Content -Path D:*.txt -Value (Get-Date) -Exclude "readme*"

Except the file with readme within the filename, the instance under will add the present date to all TXT recordsdata within the path D::

Aside from the readme recordsdata, all of the recordsdata have been up to date. You’ll be able to outline a string array of recordsdata that you really want or don’t wish to replace utilizing the embody and exclude choices. 

4. Powershell Write to Log File

The Begin-Transcript cmdlet is the perfect technique for writing to a log file, though the Add-Content material cmdlet or the redirect operator may also be used to create customized log capabilities.

The redirect operator will prohibit your choices, but it surely’s a superb approach to solely report a script’s errors to a log file:

Operate Get-ProcessCpu  choose cpu

Get-ProcessCpu -name "explorer2" 2>> "D:$env:computername-process.log"
Powershell Write to Log File

Nevertheless, you typically wish to have slightly bit extra management when you find yourself sending messages to a log file. It’s essential that we will decide the occasion’s timing and seriousness utilizing log recordsdata. Due to this fact, we want to replace the log message to incorporate a timestamp and an occasion stage.

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

This makes it easy for us to learn the log file and find any errors. The operate proven above is an illustration of a simple PowerShell log file creator that lets you add messages (occasions) to a log file together with the severity and timestamp.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments