Home > Net >  Powershell Copy-Item Not going to destination
Powershell Copy-Item Not going to destination

Time:05-26

I'm running the below PS to move files from one directory to another. The issue I'm having is that it does not copy the items to the destination, it copies them to the directory I'm calling the script from. The destination is a file share that I've mapped.

$originalPath1 = "C:\Source\Source\"
$targetFile1 = "Q:\destination\"

Get-ChildItem $originalPath1\* -Include  *.xxx, *.yyy, *.ddd, *.eee, *.ttt |
   ForEach-Object{ $targetFile1 = $htmPath   $_.FullName.SubString($originalPath1.Length);
 New-Item -ItemType File -Path $targetFile1 -Force;
 Copy-Item $_.FullName -destination $targetFile1 }

CodePudding user response:

As 'poor mans backup', you could use below code to copy the files that match the pattern to a destination folder.

This will also create the subfolder structure the original file was in:

$originalPath = 'C:\Source\Source'
$destination  = 'Q:\destination'
$includeThese = '*.xxx', '*.yyy', '*.ddd', '*.eee', '*.ttt'

Get-ChildItem -Path $originalPath -File -Recurse -Include $includeThese |
ForEach-Object {
    # create the destination folder
    $target = Join-Path -Path $destination -ChildPath $_.DirectoryName.Substring($originalPath.Length)
    $null = New-Item -ItemType Directory -Path $target -Force
    # copy the file to the target path
    $_ | Copy-Item -Destination $target -Force
}
  • Related