PowerShell: Copy-Item Same Directory

So I came across a question at http://stackoverflow.com – the user wanted to create a backup directory inside the same directory. I also noticed the user didn’t have any error handling.

The user was having two issues: Firstly it didn’t work, secondly even if it did work it would create an endless loop until it crashed. What I did was create a simple function called Get-CopySameDirectory. First we create our Dynamic & Static Variables. Then we use a Test-Path cmdlet for error handling to make sure we are not writing over an existing backup. Next we use the Copy-Item cmdlet to copy the files from the $AppPath to $BackupPath, but we have to keep in mind that if we do this it will create a loop. We use the -exclude option to exclude anything named Backup, by using the wildcard Backup*. I made this into a variable for anyone to use.

Function Get-CopySameDirectory{
#####################
# Dynamic Variables #
#####################</code>

$Date = Get-Date -format ddMM-yyyy
####################
# Static Variables #
####################
$AppPath = "F:\Test\"
$BackupPath = "$AppPath\BACKUP_$Date\"
$Exclude="Backup*"

if (Test-Path $BackupPath) {
Write-Host "Backup Exist" -f Cyan
}
else
{
Copy-Item "$AppPath\*" $BackupPath -Exclude $Exclude -recurse -verbose
}
}
CLS
Get-CopySameDirectory

If you ever have any questions or requests, leave them below in the comments, and I will do anything in my power to help you out!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s