In this short tutorial I will show how to check if a file exists, and then copy a file if it exists using PowerShell (or move a file if it exists !). This might be useful if you have something like a backup job that zips up a bunch of files every so often. You can use a small PowerShell script to check if the file exists and then copy it or move it to another location.
To do so we will make use of the test-path cmdlet and the copy-item cmdlet. We can use test-path to check if the file exists, then if it does, use copy-item to copy it to a different location. Let’s have a look at the code. First we will set a variable for the name of the file we want to work with:
$FileName = "c:\scripts\backup.zip"
Now the code to copy the file if it exists:
if (Test-Path $FileName = True) {
Copy-Item $FileName -Destination c:\backups\
}
If the file – backup.zip exists the test-path cmdlet returns a true
value. If that happens the copy-item cmdlet is ran and the file is copied, in this case to the destination folder c:\backups
. Now we can build on the script with some helpful text feedback, and an else statement to print a string if the test-path cmdlet returns a false value. Let’s look at the complete code:
$FileName = "C:\scripts\backup.zip"
if (Test-Path $FileName) {
Copy-Item $FileName -Destination c:\backups
write-host "$FileName has been copied"
}
else {
Write-host "$FileName doesn't exist"
}
And that’s it! If we had wanted to move the backups.zip file instead of copying it, we could have done so by swapping the copy-item cmdlet for move-item.
A simple and quick way to check if a file exists and then copy it using PowerShell.