Skip to content

PowerShell Creating Files

How to create files in PowerShell using New-Item, Out-File, and Set-Content, including handling empty files, parent directories, and content writing.

Creating files on a filesystem is a fundamental task in automation, configuration management, and log generation. In PowerShell, files can be instantiated as empty filesystem objects using New-Item, written to directly using the pipeline via Out-File, or created and populated using content management cmdlets like Set-Content. This page covers the three most common approaches and helps you choose the right one for each scenario.

Creating Files with New-Item

The New-Item cmdlet (alias: ni) creates new items within a specified PSProvider. When targeting the FileSystem provider, supplying the -ItemType File parameter creates a file and emits a System.IO.FileInfo object into the pipeline.

Basic Syntax

New-Item -Path <Path> -Name <String> -ItemType File [-Value <Object>] [-Force]
New-Item -Path "C:\Logs\app.log" -ItemType File
    Directory: C:\Logs

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a----         9/27/2026   6:13 PM              0 app.log

Where:

  • -Path specifies the full path of the file to create.
  • -ItemType File explicitly tells PowerShell to create a file, not a directory.
  • The resulting file has a Length of 0, confirming it's empty.

Creating a File with Initial Content

New-Item also accepts a -Value parameter to populate the file at creation time.

New-Item -Path "C:\Logs\startup.log" -ItemType File -Value "Log initialized on $(Get-Date)"

    Directory: C:\Logs


Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a----         9/27/2026   6:13 PM             38 startup.log

and then let's see what inside it:

Get-Content "C:\Logs\startup.log"
Log initialized on 09/27/2026 18:13:47

Creating Parent Directories Automatically

If the parent folder doesn't exist, -Force also creates any missing intermediate directories.

New-Item -Path "C:\Data\2024\March\report.txt" -ItemType File -Force
    Directory: C:\Data\2024\March


Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a----         9/27/2026   6:15 PM              0 report.txt

Where -Force creates the entire C:\Data\2024\March folder structure if it doesn't already exist, in addition to the file itself.

Creating and Writing with Out-File

The Out-File cmdlet creates a new file and writes console or pipeline output directly to it. If the target file does not exist, Out-File automatically creates it; if it already exists, Out-File overwrites its content by default.

Piping Data to Out-File

Out-File formats incoming pipeline data into plain text, preserving the visual layout seen in the terminal console.

Get-Process | Out-File -FilePath "C:\Logs\processes.txt"

Where -FilePath specifies the destination file, created fresh if it doesn't exist, or overwritten if it does.

"Deployment started" | Out-File -FilePath "C:\Logs\deploy.log"

and let's see the content of deploy.log:

Get-Content "C:\Logs\deploy.log"
Deployment started

A more complete example captures formatted service information:

$ReportPath = "$PSScriptRoot\system-baseline.txt"

Get-Service -Name "wuauserv", "Spooler" |
    Format-Table -Property Name, Status, StartType |
    Out-File -FilePath $ReportPath -Encoding utf8

Get-Item -Path $ReportPath
    Directory: C:\Scripts

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a---           10/24/2024  11:20 PM            312 system-baseline.txt

Where:

  • Get-Service emits service controller objects.
  • Format-Table converts objects into columnar text.
  • Out-File -FilePath $ReportPath creates the file on disk and writes the formatted text.
  • -Encoding utf8 enforces standard UTF-8 character encoding.

Set-Content vs New-Item

Both Set-Content and New-Item can create new files on disk, but they serve different architectural roles.

New-Item:

  • Role: Creates filesystem items and structures.
  • Output: Returns a System.IO.FileInfo object when creating a file.
  • Existing file: Produces an error if the item already exists, unless -Force is used.
  • Parent directories: With -Force, it can create missing parent directories when applicable.

Set-Content:

  • Role: Creates or writes the content of a file.
  • Output: Does not produce output by default. Use -PassThru to return the resulting object.
  • Existing file: Overwrites the existing content automatically.
  • Parent directories: Fails if the specified parent directory does not already exist.

Architectural Comparison

Feature New-Item -ItemType File Out-File Set-Content
Primary purpose Create a file (empty or with fixed initial content) Write pipeline output to a file Write string content to a file
Overwrites by default? No, errors unless -Force is specified Yes Yes
Accepts pipeline input? No (uses -Value for content) Yes (designed for it) Yes
Typical use case One-time file/folder scaffolding Redirecting cmdlet output to a file Writing or replacing plain text content
Encoding control N/A -Encoding parameter -Encoding parameter
Default pipeline output Emits a FileInfo object None None (silent)
Missing parent folders Creates missing parent folders when using -Force Fails if parent directory does not exist Fails if the parent folder does not exist
New-Item -Path "C:\Temp\a.txt" -ItemType File -Force

Get-Date | Out-File -FilePath "C:\Temp\b.txt"

Set-Content -Path "C:\Temp\c.txt" -Value "Direct string content"

Example: Set-Content with Parent Directory Creation

$TargetFile = "$env:TEMP\AppConfig\config.json"

$ParentDir = Split-Path -Path $TargetFile -Parent
if (-not (Test-Path -Path $ParentDir)) {
    $null = New-Item -ItemType Directory -Path $ParentDir
}

Set-Content -Path $TargetFile -Value '{"status": "initialized", "tier": 1}'

Get-Content -Path $TargetFile
{"status": "initialized", "tier": 1}

Where:

  • Split-Path -Path $TargetFile -Parent isolates the directory container portion of the path.
  • New-Item -ItemType Directory creates the missing directory.
  • Set-Content writes the JSON string directly into the newly created file.

Choosing the Right Cmdlet

Scenario Recommended Cmdlet
Create an empty file or scaffold a folder structure New-Item -ItemType File
Create a file only if it doesn't already exist New-Item (without -Force)
Redirect the output of a cmdlet to a file Out-File
Write or overwrite plain text content quickly Set-Content

Practical Example: Safe Configuration Initializer

The following script initializes an application configuration file safely. It verifies parent directory structures, checks if the target configuration file exists before overwriting, and emits a structured creation audit record.

param (
    [string]$TargetDirectory = "$PSScriptRoot\Config",
    [string]$FileName        = "appsettings.production.json",
    [switch]$Overwrite
)

$FullFilePath = Join-Path -Path $TargetDirectory -ChildPath $FileName

if (-not (Test-Path -Path $TargetDirectory -PathType Container)) {
    Write-Output "Parent directory missing. Creating: $TargetDirectory"
    $null = New-Item -ItemType Directory -Path $TargetDirectory -Force
}

$FileExists = Test-Path -Path $FullFilePath -PathType Leaf

if ($FileExists -and -not $Overwrite) {
    Write-Warning "File '$FullFilePath' already exists! Skipping creation (use -Overwrite to replace)."
    $CreationStatus = "Skipped"
}
else {
    $DefaultConfig = @{
        Environment  = "Production"
        LoggingLevel = "Information"
        CreatedAt    = (Get-Date -Format "yyyy-MM-dd HH:mm:ss")
    } | ConvertTo-Json -Depth 2

    $NewFileItem = New-Item -Path $FullFilePath -ItemType File -Value $DefaultConfig -Force
    $CreationStatus = if ($FileExists) { "Overwritten" } else { "Created" }
}

[PSCustomObject]@{
    FilePath       = $FullFilePath
    Status         = $CreationStatus
    SizeBytes      = if (Test-Path -Path $FullFilePath) { (Get-Item $FullFilePath).Length } else { 0 }
    CheckedBy      = $env:USERNAME
}

Where:

  • Join-Path constructs an absolute path respecting operating system path separators.
  • New-Item -ItemType Directory -Force safely initializes the directory hierarchy.
  • [switch]$Overwrite provides a safety parameter preventing accidental file truncation.
  • ConvertTo-Json converts a PowerShell hash table into a formatted JSON string passed directly to -Value.

Execute the script from the console:

pwsh ./initialize-application-config.ps1 -Overwrite
Parent directory missing. Creating: C:\Scripts\Config

FilePath                                         Status      SizeBytes CheckedBy
--------                                         ------      --------- ---------
C:\Scripts\Config\appsettings.production.json    Created           112 Tom
Navigation