PowerShell: How to Use Equivalent of mkdir -p


In a Linux environment, you can use the command mkdir -p to recursively create folders.

If any depth of the folder path already exists, then that specific depth will not be created and no error will be shown.

You can use the following syntax to replicate this behavior in PowerShell:

$null = New-Item -ItemType Directory -Path players/positions -Force

This particular example attempts to create a folder named players in the current directory and then a subfolder within that folder named positions.

Here is what the various commands do:

  • $null: This ensures that there is no output produced by this code.
  • New-Item: This creates the new folders and subfolders.
  • -Force: This ensures that no error is produced if the path already exists.

The following example shows how to use this syntax in practice.

Example: How to Use Equivalent of mkdir -p in PowerShell

We can use the following syntax to first list out all folders and subfolders in our current directory:

Get-ChildItem -Recurse -Directory

The following screenshot shows how to use this syntax in practice:

We can see that three folders currently exist in this directory:

  • coaches
  • managers
  • teams

None of these folders currently have subfolders.

We can use the following syntax to create a new folder named players that contains a subfolder inside of it name positions:

$null = New-Item -ItemType Directory -Path players/positions -Force

The following screenshot shows how to use this syntax in practice:

PowerShell mkdir -p

Notice that no output is produced from this command.

We can use the Get-ChildItem cmdlet once again to view the updated folder structure of our current directory:

We can see that a new folder named players has been created along with a subfolder within it named positions.

Now suppose that we ran the exact same code again:

$null = New-Item -ItemType Directory -Path players/positions -Force

The following screenshot shows how to use this syntax in practice:

Notice that we receive no error even though this path already exists.

Also notice that the folder structure simply remained unchanged.

This replicates the exact behavior of the mkdir -p statement in a Linux environment.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Delete File if it Exists
PowerShell: How to Find Empty Folders
PowerShell: Check if File Has Been Modified in last 24 Hours

Leave a Reply