Home > Enterprise >  Why doesn't my Powershell loop grab a PDF file if im calling -Include "*.pdf"
Why doesn't my Powershell loop grab a PDF file if im calling -Include "*.pdf"

Time:12-09

foreach ($file in Get-ChildItem -Path $srcRoot -File -Include "*.pdf" -Force -Recurse {

Above is just a line out of my script that is moving files from one directory to another. Long story short.. My script is working and has been for months. However, today I came across where it didnt move two files that were named like the following.

Thisismyfile.pdf2.pdf

Thisisanotherfile.pdf2.pdf

Now like I said.. the script has been working fine until these files came about. Of course I told the users to make sure they name files correctly ect.. but I dont know why it still didnt move those files. It still contains "*.pdf" as an extenstion.. so what gives?

CodePudding user response:

I suspect that files are not moved in scenario where you have file in folder A with the same name as in folder B. Moving files to the one destination folder will cause name collision with error like Move-Item : Cannot create a file when that file already exists. If that is the case, please use one of snippets from this answer: Powershell Move-Item Rename If File Exists

I placed few .pdf files (named like a.pdf.pdf, b.pdf.pdf ...) in src directory, running snippet below moves those files to dst folder correctly.

$srcRoot = "C:\Users\$env:username\Desktop\src\"

foreach ($file in Get-ChildItem -Path $srcRoot -File -Include "*.pdf" -Force -Recurse)
{
Move-Item -Path $file -Destination "C:\Users\$env:username\Desktop\dst\"
}

  • Related