PowerShell Copy-item Create Folder If Not Exist

In this tutorial, I will explain how to use the PowerShell Copy-Item cmdlet to copy files and folders while automatically creating the destination folder if it doesn’t already exist.

In my previous tutorial, I explained about PowerShell Copy-Item.

The Copy-Item cmdlet is used to copy files and directories from one location to another. Here is the basic syntax:

Copy-Item -Path <Source> -Destination <Destination> [-Recurse] [-Force]
  • -Path: Specifies the source file or directory.
  • -Destination: Specifies the destination file or directory.
  • -Recurse: Copies all subdirectories and files recursively.
  • -Force: Overwrites existing files or directories without prompting.

PowerShell Copy-item Create Folder If Not Exist

By default, the Copy-Item cmdlet will not create the destination folder if it doesn’t already exist. You will encounter an error if you attempt to copy an item to a non-existent folder.

To ensure that the destination folder exists before copying files, you can use a combination of Test-Path and New-Item cmdlets. Here’s how to do it:

  • Check if the Destination Folder Exists: You can use the Test-Path cmdlet to check if the destination folder exists; if it does not exist, it will create it.
$destinationPath = "C:\NewFolder"
if (-Not (Test-Path -Path $destinationPath)) {
    New-Item -Path $destinationPath -ItemType Directory
}
  • Copy Files to the Destination Folder: After ensuring the folder exists, use Copy-Item to copy the files:
$sourcePath = "C:\SourceFolder\*"
Copy-Item -Path $sourcePath -Destination $destinationPath -Recurse -Force

Here is the complete script:

$sourcePath = "C:\MyFolder\file.txt"
$destinationPath = "C:\NewFolder"

# Check if the destination folder exists
if (-Not (Test-Path -Path $destinationPath)) {
    New-Item -Path $destinationPath -ItemType Directory
}

# Copy files to the destination folder
Copy-Item -Path $sourcePath -Destination $destinationPath -Recurse -Force

This will only check the top-level folder.

I executed the above code, and you can see the exact output in the screenshot below:

powershell copy-item create folder if not exist

Handle Errors With Try Catch Blocks

It’s always good practice to handle potential errors that might occur during file operations. You can use Try-Catch blocks for this purpose:

try {
    # Ensure the destination folder exists
    if (-Not (Test-Path -Path $destinationPath)) {
        New-Item -Path $destinationPath -ItemType Directory
    }

    # Copy files
    Copy-Item -Path $sourcePath -Destination $destinationPath -Recurse -Force
}
catch {
    Write-Error "An error occurred: $_"
}

Copy Specific File Types

If you need to copy only specific types of files, you can use the Get-ChildItem cmdlet to filter files:

$sourcePath = "C:\SourceFolder"
$destinationPath = "C:\NewFolder"

# Ensure the destination folder exists
if (-Not (Test-Path -Path $destinationPath)) {
    New-Item -Path $destinationPath -ItemType Directory
}

# Copy only .txt files
Get-ChildItem -Path $sourcePath -Filter *.txt | ForEach-Object {
    Copy-Item -Path $_.FullName -Destination $destinationPath -Force
}

Check out Get the First 10 Files in a Folder Using PowerShell

PowerShell Copy-item Create Folder If Not Exist Recursively

To handle the recursive folder case, we need to ensure that the script not only checks for the existence of the top-level destination folder but also creates any necessary subdirectories as it copies files and folders from the source.

Here is a complete script:

$sourcePath = "C:\MyFolder\*"
$destinationPath = "C:\NewFolder"

# Function to ensure a directory exists
function Ensure-DirectoryExists {
    param (
        [string]$path
    )
    if (-Not (Test-Path -Path $path)) {
        New-Item -Path $path -ItemType Directory | Out-Null
    }
}

# Ensure the top-level destination folder exists
Ensure-DirectoryExists -path $destinationPath

# Get all items in the source path recursively
$items = Get-ChildItem -Path $sourcePath -Recurse

foreach ($item in $items) {
    # Determine the relative path of the item
    $relativePath = $item.FullName.Substring($sourcePath.Length-1)
    $destinationItemPath = Join-Path -Path $destinationPath -ChildPath $relativePath

    if ($item.PSIsContainer) {
        # Ensure the destination directory exists
        Ensure-DirectoryExists -path $destinationItemPath
    } else {
        # Copy the file to the destination directory
        Copy-Item -Path $item.FullName -Destination $destinationItemPath -Force
    }
}

Here the Ensure-DirectoryExists function checks if a directory exists and creates it if it doesn’t. This is used to ensure both the top-level destination folder and any necessary subdirectories are created.

Conclusion

Here, I explained how to use PowerShell’s Copy-Item cmdlet to copy files and create a folder if it doesn’t exist. By combining Test-Path and New-Item, you can ensure that your destination directories are created automatically.

If you have any questions or run into issues, feel free to leave a comment below.

You may also like:

100 PowerShell cmdlets download free

100 POWERSHELL CMDLETS E-BOOK

FREE Download an eBook that contains 100 PowerShell cmdlets with complete script and examples.