Search code examples
powershellfilepathfile-move

how to copy files to different path with Powershell?


I am trying to copy files with powershell.

$datestamp = (Get-Date).ToString("yyyyMMdd")
    Copy-Item -Path \\User\LS\ADMIN\HW\DATA\Payroll\$datestamp\*.txt -Destination C:\Users\User1\Desktop\New folder

The files that I am trying to copy are txt type and path for this and files are located two folders down from $datestamp. I've tried with this code and its not copying the files to path that I wanted. Is there any ways to fix this code to work?


Solution

  • What you are after is a loop. This will cycle through all *.txt files in the location and copy them as requested.

    $datestamp = (Get-Date).ToString("yyyyMMdd")
    $Files = Get-ChildItem -Path "\\User\LS\ADMIN\HW\DATA\Payroll\$datestamp\" -Filter "*.txt"
    Foreach($File in $Files) {
        Copy-Item -Path $File.FullName -Destination "C:\Users\User1\Desktop\New folder\"
    }
    

    A one liner (piped) version would look like this:

    Get-ChildItem 
        -Path "\\User\LS\ADMIN\HW\DATA\Payroll\$((Get-Date).ToString("yyyyMMdd"))\" 
        -Filter "*.txt" `
        | % {
            Copy-Item 
                -Path $_.FullName 
                -Destination "C:\Users\User1\Desktop\New folder\"
        }
    

    All new lines can be removed from the sample, did it this way for formatting otherwise it appears like this.

    Get-ChildItem -Path "\\User\LS\ADMIN\HW\DATA\Payroll\$((Get-Date).ToString("yyyyMMdd"))\" -Filter "*.txt" | % {Copy-Item -Path $_.FullName -Destination "C:\Users\User1\Desktop\New folder\"}