Create a New Empty File with the PowerShell Out-File Cmdlet

A few weeks ago I was setting up OpenSSL on a Windows machine and I was following a Linux tutorial which used the “touch” command to create a new empty file.

To accomplish the task of creating a new empty file with PowerShell, the most straight forward way is to use the New-Item cmdlet:

create-newemptyfile1a

I inadvertently discovered another way to create a new empty file with PowerShell which I thought I would share with you guys, the readers of my blog.

You may see some people piping $null to the Out-File cmdlet, but when you pipe $null it doesn’t produce any output so you could simply use the Out-File cmdlet by itself:

create-newemptyfile2a

Even though the length of the file created using Out-File is two instead of zero, it is indeed an empty file.

If I were typing the previous command interactively in the PowerShell console, I would omit the FilePath positional parameter, but I consider it to be a best practice to always use full cmdlet and parameter names in my blog articles.

µ

5 Comments

  1. Ben Miller

    Nice. If you put -Encoding ascii at the end of your Out-File you get a 0 byte file. Otherwise it is using Unicode as the Encoding which would put 2 bytes for a nothing in the file.

    Reply
  2. brooks3204

    I wrote a script that renames the TextFile.txt based on the CreateDate. Used Rename-Item to TextFile_2015-0608.txt. Archived the Renamed file. Deleted the Renamed file using Remove-Item and then Creates a New File file by the original name TextFile.txt using the (“$timestamp $LineSeperator” | Out-File TextFile.txt -Encoding ascii) approach

    My issue is the Create Date of the New File is the same date as the deleted file.

    Any thoughts on what might be causing this behavior

    – Brooks

    Reply
  3. brooks3204

    I found the cause of the CreationDate issue which is because Windows caches the original file information and creating a new file by the same name will assume those values.

    This is described in a pose by David M. Candy titled “CreationTime set oddly in PowerShell”

    https://social.msdn.microsoft.com/Forums/en-US/44c7e8b4-778d-49cc-aad2-bdd40e90b55d/creationtime-set-oddly-in-powershell?forum=scripting

    Unfortunately, there is no solution on how to clear that information before creating the file again.

    My Work-Around solution was to set the CreationDate after creating the file:

    $LogPath = “C:\Logs\TestFile.log”
    Remove-Item -Path $LogPath -Force
    $LineSeperator = ‘=’ * 60
    $timestamp = Get-Date -DisplayHint Time
    “$timestamp $LineSeperator” | Out-File $LogPath
    (dir $LogPath).CreationTime = $timestamp

    -Brooks

    Reply
  4. Mamba

    Awesome thank you so much

    Reply
  5. Clive

    Good information Mike, seems to work like copy con of yesteryear.

    Reply

Leave a Reply

%d bloggers like this: