Copy file from PowerShell script

89 Views Asked by At

I am trying to copy some file from source directory to target directory by a script. The condition is the new file supposed to come everyday at some certain time. My scripts is checking the pattern of the file name and check the dates if greater than today's date (00:00:00) then copying it. But its working fine if latest date's file is available on next morning then copy that file. But if the latest file is not available then it copying all the other files from that source directory. Can anyone check my script and tell me what's wrong in it?

$fromDir = "\\fil\folder\path\files" 

$destinationMask = Join-Path "C:\XXX\ABCD_K_Integration\F_datafiles" "{0}.kis.txt" 
    
$files = Get-ChildItem $fromDir `
    | where Name -match "ALMR12_\d+.txt" `
    | where { ! $_.PSIsContainer } `
    | where LastWriteTime -gt (get-date -Hour 0 -Minute 0 -Second 0)
    
# copy file 
Get-ChildItem $fromDir -filter "$files" | where { ! $_.PSIsContainer } | Copy-Item -Dest {"$destinationMask" -f $_.BaseName} 

This is my source file list.

enter image description here

You can see last file came on 30th, which means if i run my job it is copying all the files, but if i create a 0 byte file with todays date for testing then my script is working properly. Can't understand what's wrong in the script.

2

There are 2 best solutions below

4
Civette On

Tested following and it works fine for me. Nothing is copied if no file fullfils the filter

$fromDir = "path_from_folder" 
$toDir = "path_to_folder"
   
Get-ChildItem $fromDir |
    Where-Object {($_.Name -match "ALMR12_\d+.txt") -and `
        (! $_.PSIsContainer) -and `
        ($_.LastWriteTime -gt (get-date -Hour 0 -Minute 0 -Second 0))
    } |
    Copy-Item -Destination $toDir
2
notjustme On

There should be no need to filter the files twice, $files should contain the files you're after. In fact, filtering by "$files" in the second Get-ChildItem would fail if the variable contains more than one single file.

If you replace this line

Get-ChildItem $fromDir -filter "$files" | where { ! $_.PSIsContainer } | Copy-Item -Dest {"$destinationMask" -f $_.BaseName}

with the following it'll probably work.

$files | Copy-Item -Dest { "$destinationMask" -f $_.BaseName } -WhatIf

Please note that I added -WhatIf to the command to avoid any accidental file copies - remove it after you've tested it.