lazyadmin.nl Open in urlscan Pro
2606:4700:3034::ac43:a4bc  Public Scan

Submitted URL: http://lazyadmin.nl/powershell/output-to-file/
Effective URL: https://lazyadmin.nl/powershell/output-to-file/
Submission: On February 22 via manual from AE — Scanned from NL

Form analysis 4 forms found in the DOM

GET https://lazyadmin.nl/

<form method="get" class="search-form navigation-search" action="https://lazyadmin.nl/">
  <input type="search" class="search-field" value="" name="s" title="Search">
</form>

GET https://lazyadmin.nl/

<form method="get" class="search-form navigation-search" action="https://lazyadmin.nl/">
  <input type="search" class="search-field" value="" name="s" title="Search">
</form>

Name: mc-embedded-subscribe-formPOST https://lazyadmin.us3.list-manage.com/subscribe/post?u=af146d20f4a5c8c9d4f2263c5&id=b15b03d22a

<form action="https://lazyadmin.us3.list-manage.com/subscribe/post?u=af146d20f4a5c8c9d4f2263c5&amp;id=b15b03d22a" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate="">
  <div id="mc_embed_signup_scroll">
    <h2>Get more stuff like this</h2>
    <p class="text">IT, Office365, Smart Home, PowerShell and Blogging Tips</p>
    <div class="mc-field-group">
      <input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL" placeholder="Enter your email address">
      <input type="submit" value="SIGN UP" name="subscribe" id="mc-embedded-subscribe" class="button">
    </div>
    <div id="mce-responses" class="clear">
      <div class="response" id="mce-error-response" style="display:none"></div>
      <div class="response" id="mce-success-response" style="display:none"></div>
    </div>
    <div style="position: absolute; left: -5000px;" aria-hidden="true"><input type="text" name="b_af146d20f4a5c8c9d4f2263c5_b15b03d22a" tabindex="-1" value=""></div>
    <p class="note">I hate spam to, so you can unsubscribe at any time.</p>
  </div>
</form>

POST https://lazyadmin.nl/wp-comments-post.php

<form action="https://lazyadmin.nl/wp-comments-post.php" method="post" id="commentform" class="comment-form" novalidate="">
  <p class="comment-form-comment"><label for="comment" class="screen-reader-text">Comment</label><textarea id="comment" name="comment" cols="45" rows="8" required=""></textarea></p><label for="author" class="screen-reader-text">Name</label><input
    placeholder="Name *" id="author" name="author" type="text" value="" size="30">
  <label for="email" class="screen-reader-text">Email</label><input placeholder="Email *" id="email" name="email" type="email" value="" size="30">
  <label for="url" class="screen-reader-text">Leave Empty</label><input placeholder="Leave Empty " id="url" name="url" type="text" value="" size="30">
  <p class="comment-form-subscriptions"><label for="subscribe-reloaded"><input style="width:30px" type="checkbox" name="subscribe-reloaded" id="subscribe-reloaded" value="yes"> Notify me of followup comments via e-mail. You can also
      <a href="https://lazyadmin.nl/comment-subscriptions/?srp=6122&amp;srk=1ee5dad2be1a3f5b900eccf9b5db9a3b&amp;sra=s&amp;srsrc=f">subscribe</a> without commenting.</label></p>
  <p class="form-submit"><input name="submit" type="submit" id="submit" class="submit" value="Post Comment"> <input type="hidden" name="comment_post_ID" value="6122" id="comment_post_ID">
    <input type="hidden" name="comment_parent" id="comment_parent" value="0">
  </p>
  <p style="display: none;"><input type="hidden" id="akismet_comment_nonce" name="akismet_comment_nonce" value="47cac38c3b"></p>
  <p style="display: none !important;"><label>Δ<textarea name="ak_hp_textarea" cols="45" rows="8" maxlength="100"></textarea></label><input type="hidden" id="ak_js_1" name="ak_js" value="142">
    <script type="rocketlazyloadscript">document.getElementById( "ak_js_1" ).setAttribute( "value", ( new Date() ).getTime() );</script>
  </p>
</form>

Text Content

Skip to content

Menu
 * Articles
   * Home Network
   * Office 365
     * Microsoft Office 365 Comparison
   * PowerShell
   * Smart Home
   * SysAdmin
   * Windows 11
   * Blogging
 * Tools
 * Network Gear
 * About
 * 


Menu
 * Articles
   * Home Network
   * Office 365
     * Microsoft Office 365 Comparison
   * PowerShell
   * Smart Home
   * SysAdmin
   * Windows 11
   * Blogging
 * Tools
 * Network Gear
 * About
 * 


HOW TO OUTPUT TO FILE WITH POWERSHELL OUT-FILE CMDLET

March 1, 2022 Last Updated on February 10, 2023 by Rudy Mens3 Comments

The output of PowerShell commands is by default displayed in the terminal. But
in some situations, it’s more useful to redirect the output to a file in
PowerShell. For this, we are going to use the Out-File cmdlet.

There are different ways to output the results of a PowerShell script or command
to file. It’s even possible to show the output in the terminal and export it to
a file at the same time. And did you know that you can also export only the
success, warning, or error results?

In this article

1
 * Powershell Write Output to File
   * PowerShell Redirect Operator
   * PowerShell Append to File
   * Using PowerShell Add-Content
 * Write only Errors, Warnings, or Success to file
 * Powershell Write to Log File
 * Wrapping Up

In this article, we are going to take a look at how to write the output to a
file in PowerShell. I will also explain how you can append to an existing file
or how you can create a log file.


POWERSHELL WRITE OUTPUT TO 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. We are going to focus
on the first two, but I will briefly mention the alternative if relevant.



The Out-File cmdlet and redirect operator > allows you to write and append (>>)
the PowerShell output to a file. The difference between the two is that the
first accepts parameters and the latter doesn’t.

With the Out-File cmdlet we can use the following parameters:

ParameterDescription-FilepathSet the location and name of the file-AppendAppend
the output to the existing content of the file-ForceOverwrite a read-only
file-NoClobberPrevent overwrite of file-NoNewLineNo newline character will be
written.-WidthLimit the number of characters on each line (default 80)-WhatIfRun
in test mode

Out-File cmdlet Parameters


POWERSHELL REDIRECT OPERATOR

The redirect operator however doesn’t have any parameters. But it has an
advantage compared to Out-File. When using the Out-File cmdlet, only the
successful results are exported, so warnings or errors won’t be written to the
file.



When using the redirect operator we can specify which stream we want to export:

OperatorDescription / StreamWrite cmdlet>Success onlyWrite-Output2>Error
onlyWrite-Error3>Warning onlyWrite-Warning4>Verbose only Write-Verbose5>Debug
onlyWrite-Debug6>Information onlyWrite-Information*>All

PowerShell Redirect Operator

I will explain more about the different streams later, but let’s first take a
look at how we can simply write the output to a file in PowerShell.



To write the output to a file all you have to do is pipe the Out-File cmdlet
behind your script or command and specify the path. If the file doesn’t exist,
then it will be created by the cmdlet:

Get-Process -Name explorer | Out-File -FilePath c:\temp\process.txt

# Same as:
Get-Process -Name explorer > c:\temp\process.txt

# The results
 Get-Content C:\temp\process.txt

 NPM(K)    PM(M)      WS(M)     CPU(s)      Id  SI ProcessName
 ------    -----      -----     ------      --  -- -----------
    132    94,56     158,22     131,45  123364   1 explorer

PS C:\>

As you can see, the results of the Get-Process cmdlet is stored in the
process.txt file:


Powershell Output to File

If you don’t specify any other parameter, then the Out-File cmdlet and redirect
operator will overwrite any existing file by default. We can prevent this by
adding the -NoClobber parameter to the cmdlet



Get-Process -Name explorer | Out-File c:\temp\process.txt -NoClobber

Note that you can’t prevent overwriting with the redirect operator

If the file already exists, then an error will be thrown:

Don’t overwrite existing files

If you want to output to a file inside a script then I recommend that you use
the Test-Path cmdlet first to determine if the file already exists. This way you
can write a better solution, like appending a date to the file name, instead of
simply trying to write to it:



$exportPath = "C:\temp\process.txt"

If (Test-Path $exportPath) {
    # Show a warning or change the file name here
    Write-Warning "File already exists"
    $exportPath = "C:\temp\process-1.txt" # create something nice with a date or timestamp
}else{
    Get-Process -Name explorer | Out-File $exportPath -NoClobber
}


POWERSHELL APPEND TO FILE

Instead of overwriting, we can also append the output to the existing content of
the file. For this, we can either use the -append parameter or use the redirect
operator >>. In both cases, the contents of the output will be added to the
existing file.



You can also append to a non-existing file, both methods will create a new file
if the specified file doesn’t exist.

# Append with the Out-File cmdlet
'Apple' | Out-File -FilePath C:\temp\fruits.txt -Append
Get-Content -Path c:\temp\fruits.txt

# Result
Apple

# Append with the redirect operator
'Pear' >> C:\temp\fruits.txt
Get-Content -Path c:\temp\fruits.txt

# Result
Apple
Pear

When appending output to an existing file the content will be placed on a new
line. If you want to have the content on one single line, creating one long
string, then you will need to use the Out-File cmdlet with the -NoNewLine
parameter.



The newline character is placed after the value that you have added to the file.
So it’s important to add the -NoNewLine parameter to the first Output as well.

# Note that you will need to specify NoNewLine for the first entry as well
'BlueBerry;' | Out-File -FilePath C:\temp\fruits.txt -NoNewline

# Appending more berries
'StrawBerry;' | Out-File -FilePath C:\temp\fruits.txt -Append -NoNewline
'BlackBerry;' | Out-File -FilePath C:\temp\fruits.txt -Append -NoNewline
'RaspBerry;' | Out-File -FilePath C:\temp\fruits.txt -Append -NoNewline
'CranBerry;' | Out-File -FilePath C:\temp\fruits.txt -Append -NoNewline

To make the result more readable I have added a semi-colon to all values. As you
can see all the results are on the same line:


Append to file with no newline


USING POWERSHELL ADD-CONTENT

Another option to add content to a file is to use the Add-Content cmdlet. One of
the biggest advantages of the Add-Content cmdlet is that it allows you to append
content to multiple files at once.

Just like with the Out-File cmdlet and redirect operator, the Add-Content cmdlet
creates a new file if the file doesn’t exist

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

Add-Content -Path c:\temp\file.txt -Value "New line to add"

To add the same content to multiple files we have a couple of parameters to help
us. We can use wildcards in the path to specify the files that we want to
update. Also, we can exclude files names and even use a filter.

The example below will add the current date to all TXT files in the path
c:\temp\files, except in the file with readme in the filename:

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

All the files, except the readme files, are updated:


PowerShell Add-Content

Both the include and exclude parameters allow you to specify a string array of
files that you want or do not want to update.

If we take the example from above, we could also use the filter parameter to
select only the files that include the word log:

Add-Content -Path C:\temp\files\* -Value (Get-Date) -Filter "*log*"


WRITE ONLY ERRORS, WARNINGS, OR SUCCESS TO FILE

The out-file cmdlet will write only the successful result of your command or
script to a file. But sometimes you also want warnings or errors to be outputted
as well.

To achieve this, we can use the redirect operator. It allows you to specify
which stream you want to output to a file.

Let’s take the script below as an example:

Function Get-ProcessCpu {
    param(
        [Parameter(Mandatory = $true)]$name
    )
    Get-Process -Name $name | select cpu
}
Get-ProcessCpu -name "explorer2" | Out-File C:\temp\process.txt

The process “Explorer2” doesn’t exist, so the Get-Process cmdlet will throw an
error. If we run the script like this, then the process.txt file will be
completely empty.



However, if we use the redirect operator we can specify which stream we want to
output.

# Write all results to the file:
Get-ProcessCpu -name "explorer2" *> C:\temp\process.txt

# Write only the error to the file:
Get-ProcessCpu -name "explorer2" 2> C:\temp\process-error-log.txt

# Write only warnings to a file:
Get-ProcessCpu -name "explorer2" 3> C:\temp\process-error-log.txt

As you can see, the error is written to the text file with the redirect
operator:

Powershell Write to Log File




POWERSHELL WRITE TO LOG FILE

The best option to write to a log file is to use the Start-Transcript cmdlet,
but we can also write our own log function using the Add-Content cmdlet or the
redirect operator.

Using the redirect operator will limit your possibilities, but is a great way if
you only want to write the errors of a script to a log file:



Function Get-ProcessCpu {
    param(
        [Parameter(Mandatory = $true)]$name
    )
    Get-Process -Name $name | select cpu
}

# Write only errors to a log file
Get-ProcessCpu -name "explorer2" 2>> "C:\temp\files\$env:computername-process.log"

But when you are writing messages to a log file you probably want to have a bit
more control. With log files it’s important we can see when the event happened
and the severity of the event. So what we want to do is add a timestamp and an
event level to the log message.

This way we can easily read the log file and identity any errors that have
occurred.

# Set log file path
$logFile = "C:\temp\files\$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"

The function above is an example of a simple log file creator for PowerShell
that allows you to write messages (events) to a log file with the severity and
timestamp.


Powershell Write to Log File


WRAPPING UP

As you have seen there are multiple ways in PowerShell to output the results to
a file. To quickly output something to a file you can use the redirect operator
or the Out-File cmdlet.

When you want to export the output to a CSV file, then make sure that you read
this article. It’s also possible to replace content inside a file using the
Replace method.

If you have any questions, just drop a comment below.


Tweet
Pin
Share
Share
0 Shares

Tags Powershell


RELATED POSTS

Feb 7, 2023


HOW TO USE POWERSHELL GET-CONTENT TO READ A FILE

Jan 19, 2023


HOW TO USE POWERSHELL ARRAY – COMPLETE GUIDE

Dec 8, 2022


HOW TO CONCATENATE A STRING IN POWERSHELL


GET MORE STUFF LIKE THIS

IT, Office365, Smart Home, PowerShell and Blogging Tips





I hate spam to, so you can unsubscribe at any time.




3 THOUGHTS ON “HOW TO OUTPUT TO FILE WITH POWERSHELL OUT-FILE CMDLET”

 1. JimLuschen
    February 10, 2023 at 09:55 | Reply
    
    Great article, it helped me a lot!

 2. Rafael Goncalves
    August 10, 2022 at 22:13 | Reply
    
    Hi Ruud, very nice content on your website, congrats!
    
    There is a way to write a CSV output file without limit? I’m only get the
    first 100 records for each Enterprise Application I am consulting
    
    * Rudy Mens
      August 13, 2022 at 08:02 | Reply
      
      The CSV output is not throwing in the limit, it’s the command before that.
      Use Get-AzureADApplication -all | Export-CSV


LEAVE A COMMENT CANCEL REPLY

Comment

Name Email Leave Empty

Notify me of followup comments via e-mail. You can also subscribe without
commenting.





Δ

Hey! I'm Ruud. I work as a SysAdmin in the Netherlands and I love to write about
IT, Office 365, Smart Home stuff, and PowerShell.  Follow me on Twitter or
LinkedIn


LAST ARTICLES

 1. SharePoint Archiving Options
 2. Getting Started with PDQ Deploy & Inventory




RECOMMENDED ARTICLE

Smart Home
 1. Best Home Automation Ideas updated
 2. Getting started with your Smart Home
 3. Best Smart Home Kit new
 4. Make your Outdoor Lights Smart

Home Network
 1. Monitor your home network for free
 2. UniFi Cloud Controller new
 3. How to set up your home network
 4. Unifi Protect Review
 5. Unifi Dream Machine Pro Review
 6. Home Network Wiring Guide

IT & Office 365 Related
 1. Best Practice to Secure Office 365Popular
 2. Why you should backup Microsoft 365
 3. Microsoft Office 365 Plans compared
 4. SharePoint Permissionsnew
 5. Automatically assign licenses in Office 365

 

LazyAdmin.nl is a participant in the Amazon Services LLC Associates Program, an
affiliate advertising program designed to provide a means for sites to earn
advertising fees by advertising and linking to Amazon.com. LazyAdmin.nl also
participates in affiliate programs with Microsoft, Flexoffers, CJ, and other
sites. LazyAdmin.nl is compensated for referring traffic and business to these
companies at no expense to you. Your support helps running this website and I
genuinely appreciate it. I always try to make my reviews, articles and how-to's,
unbiased, complete and based on my own expierence.



Disclaimer | Privacy Policy

© 2023 Pixel Supply B.V. , Build with GeneratePress | Hosted on Cloudways |
Optimized with Cloudflare | Ads by AdThrive
0 Shares
Tweet
Pin
Share
Share




Update Privacy Preferences
An Elite CafeMedia Tech Publisher