Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <#
- .SYNOPSIS
- Replacefiles copies from one directory to the other, optionally only replacing files that exist in the target directory
- .DESCRIPTION
- Replacefiles copies from one directory to the other, optionally only replacing files that exist in the target directory
- .PARAMETER SourceDirectory
- Location of new files \\SourceLocation
- .PARAMETER TargetDirectory
- Location of old files \\TargetLocation
- .PARAMETER Filenames
- Name of files to copy -Filenames fileone.ext, filetwo.ext, file3.ext
- .PARAMETER AlwaysCopy
- Replacefiles will also copy files that are not present in the target directory
- .EXAMPLE
- ReplaceFiles -source C:\Build\Executables -target \\SomewhereElse -filenames thisfile.exe, somefile.txt, thatfile.exe -AlwaysCopy
- #>
- [CmdletBinding()]
- param (
- [Parameter(Mandatory=$True)]
- [Alias('source')]
- [String]$SourceDirectory,
- [Parameter(Mandatory=$True)]
- [Alias('target')]
- [String]$TargetDirectory,
- [Parameter(Mandatory=$True)]
- [String[]]$Filenames,
- [switch]$AlwaysCopy
- )
- if (test-path $SourceDirectory)
- {
- if (test-path $TargetDirectory)
- {
- Write-Verbose "Replace files in $TargetDirectory from $SourceDirectory"
- if ($alwayscopy)
- {
- Write-Verbose "and add files that are not already present."
- }
- foreach($file in $Filenames)
- {
- Write-Verbose $file
- $new = Join-Path $SourceDirectory $file
- $old = Join-Path $TargetDirectory $file
- $newtmp = $old + '.new'
- $tmp = $old + '.tmp'
- $tmpfile = $file + '.tmp'
- $cpy = $AlwaysCopy
- if (Test-Path $old)
- {
- $cpy = $True
- }
- if (-not (Test-Path $New))
- {
- Write-Host $new not found
- $cpy = $False
- }
- if ($cpy)
- {
- Write-Host "Copying $file"
- if (Test-Path $tmp)
- {
- Write-Verbose "Deleting $tmp"
- Remove-Item $tmp -Force -ErrorAction SilentlyContinue
- }
- if (Test-Path $newtmp)
- {
- Write-Verbose "Deleting $newtmp"
- Remove-Item $newtmp -Force -ErrorAction SilentlyContinue
- }
- Write-Verbose "Copying $new to $newtmp"
- Copy-Item $new -Destination $newtmp -Force
- if (Test-Path $old)
- {
- Write-Verbose "Renaming $file to $tmpfile"
- Rename-Item $old -NewName $tmpfile -Force
- }
- Write-Verbose "Renaming $newtmp to $file"
- Rename-Item $newtmp -NewName $file -Force
- if (Test-Path $tmp)
- {
- Write-Verbose "Deleting $tmp"
- Remove-Item $tmp -Force -ErrorAction SilentlyContinue
- }
- }
- else {
- Write-Verbose "Skipped $file"
- }
- }
- Write-Verbose "ReplaceFiles completed"
- }
- else {
- Write-Error "Target directory $TargetDirectory does not exists"
- }
- } else {
- Write-Error "Source directory $SourceDirectory does not exists"
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement