PowerShell - Copy file using Copy-Item

by
Jeremy Canfield |
Updated: May 02 2023
| PowerShell articles
Copy-Item can be used to copy a file from one directory to another directory. In this example, the example.txt file will be copied from the C:\Users\JohnDoe\foo directory to the C:\Users\JohnDoe\bar directory.
Copy-Item -Path C:\Users\JohnDoe\foo\example.txt C:\Users\JohnDoe\bar
By default, the file name will remain the same. Or, you can give the file a new name. In this example, the example.txt file is renamed to new.txt.
Copy-Item -Path C:\Users\JohnDoe\foo\example.txt C:\Users\JohnDoe\bar\new.txt
It's probably a good idea to use Test-Path to determine if the file exists.
$file = "C:\Users\JohnDoe\foo\example.txt"
if (!(Test-Path -Path $file)) {
Write-Host $file does NOT exist
exit
}
else {
Copy-Item -Path $file C:\Users\JohnDoe\bar
}
Did you find this article helpful?
If so, consider buying me a coffee over at