PowerShell: Use Copy-Item and Create New Directory


Often you may want to use the Copy-Item cmdlet in PowerShell to copy a file to a new folder that may not exist yet.

You can use the following syntax to do so:

$source = "c:\users\bobbi\data1\teams1.txt"
$destination = "c:\users\bobbi\data2\teams1.txt"

New-Item -ItemType File -Path $destination -Force
Copy-Item $source $destination -Force

This particular example copies the file named teams1.txt from the path specified by the $source variable into the folder specified by the $destination variable, which does not currently exist.

By using the New-Item cmdlet, we’re able to create the folder named data2 before using the Copy-Item cmdlet to copy the file named teams1.txt into it.

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

Example: Use Copy-Item and Create New Directory in PowerShell

Suppose that our current directory has the following path:

  • C:\Users\bobbi\data1

We can type Dir to list out all files in this current directory:

Suppose that we would like to copy the file named teams1.txt to a new folder named data2 that does not currently exist.

Suppose we attempt to use the Copy-Item cmdlet to do so:

$source = "c:\users\bobbi\data1\teams1.txt"
$destination = "c:\users\bobbi\data2\teams1.txt"

Copy-Item $source $destination -Recurse

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

We can see that we receive an error since the destination folder that we specified does not currently exist.

We must instead use the New-item cmdlet to create the folder before attempting to copy the file into it:

$source = "c:\users\bobbi\data1\teams1.txt"
$destination = "c:\users\bobbi\data2\teams1.txt"

New-Item -ItemType File -Path $destination -Force
Copy-Item $source $destination -Force

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

PowerShell Copy-Item create folder

We can see that we’re able to successfully copy the file named teams1.txt into the new folder named data2.

Note that we used the Dir statement to display all files in this new folder named data2 and we’re able to see the teams1.txt file in this folder.

Related Tutorials

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

PowerShell: How to Copy and Rename a File
PowerShell: How to List Files in Directory by Date
PowerShell: How to Rename File Extension of Multiple Files

Leave a Reply