Menu & Search
PowerShell Create Folder If Not Exists

PowerShell Create Folder If Not Exists

This post is one part of my other post – How to Create New Files & Folders in PowerShell
The linked post covers more info on creating files vs folders.

This one is a specific guide on how to create a folder (and/or sub-folder) if it doesn’t already exist, using PowerShell. We use this in scripts to check if objects exist before executing the create folder command.

The create folder command is New-Item, which runs conditionally depending on the Test-Path true/false result.


Create New Folder (if not exists) in PowerShell

We’re creating a new folder, only if it doesn’t already exist – “C:\temp\demo”

When we run this script it also creates your C:\temp directory if it doesn’t already exist.

# create folder if not exists
$path = "c:\temp\demo"
If(!(Test-Path $path) ){
    New-Item -ItemType Directory -Force -Path $path
}

Share

0 Comments