raj
raj

Reputation: 353

How to do custom file copy in Powershell?

Below power shell script will copy and replace all the contents from source to destination.

Copy-Item -Path $sourcePath -Destination $installationPath -Recurse -Force

This looks simple. But in my case, I need to implement a custom file copy logic.

  1. Logging everything about files being copied.
  2. Skipping certain set of folders.

Sample script:

[Array]$files=Get-ChildItem ($sourceDirectoryPath) -Recurse | Format-Table Name, Directory, FullName
for($i=0;$i -le $files.Length-1;$i++)
{
    . . . . . . 
    # Build destination path based on the source path.
    # Check and create folders if it doesn't exists
    # Add if cases to skip certain parts.         
    Copy-Item -Force $sourcePath -Destination $destinationPath
}

Any ideas on how to achieve this? Any other ideas also will help.

Thanks.

Upvotes: 0

Views: 114

Answers (1)

mhu
mhu

Reputation: 18041

Something like this:

$ErrorActionPreference = "Stop"
Set-StrictMode -Version Latest

$sourceDir = "c:\temp\source"
$targetDir = "c:\temp\target"

$skipFiles = @(
    "skip.me",
    "and.me"
)

Get-ChildItem -Path $sourceDir -Recurse | ForEach-Object {
    # ignore folders
    if ($_.PSIsContainer)
    {
        return
    }

    # skip this file?
    if ($skipFiles -contains $_.Name)
    {
        Write-Verbose "Skipping '$_.FullName'"
        return
    }

    # create target folder when needed
    $path = $_.DirectoryName -replace "^$([RegEx]::Escape($sourceDir))",$targetDir
    if (!(Test-Path $path))
    {
        Write-Verbose "Creating target path '$path'..."
        New-Item -Path $path -ItemType Directory
    }

    # copy the file
    Write-Verbose "Copying '$_.FullName' to '$path'..."
    Copy-Item $_.FullName $path | Out-Null
}

Upvotes: 1

Related Questions