r/PowerShell • u/Western-Rip-1559 • Nov 26 '25
Help with copy-item command
Hi,
(OS=Windows 10 Pro)
I have a PowerShell script that I set up years ago to copy the entire directory structure of a legacy windows program that has no native backup capability.
This script is triggered daily by a windows task scheduler event with the following action:
Program/script = Powershell.exe
arguments = -ExecutionPolicy Bypass -WindowStyle Hidden C:\PEM\copyPEMscript.ps1
The contents of copyPEMscript.ps1 is as follows:
Copy-Item -Path C:\PEM\*.* -Destination "D:\foo\foo2\PEM Backup" -Force -Recurse
Unfortunately, I didn't keep good enough notes. What I don't understand is, the script appears to be producing a single file in the foo2 directory, not the entire source directory structure I thought would be produced by the -Recurse flag.
What am I missing?
Thanks.
View all comments
Show parent comment
1
u/surfingoldelephant Nov 26 '25 edited Nov 26 '25
When wildcard matching is performed and the
-Destinationpath doesn't already exist, it's the first discovered source item that dictates whether-Destinationbecomes a file or directory. You're only matching files with*.*, soPEM Backupis designated a file, not a directory.Since the destination is the same file path for each source file, you end up with a single file that matches whatever source file happened to be discovered last.
It's not at all intuitive, but is just how
Copy-Itemhas always behaved.I wouldn't use
C:\PEM\*.If the
PEM Backupdirectory doesn't already exist andC:\PEMhappens to only contain files, you'll end up with the same issue. Use the following instead. It'll work irrespective ofC:\PEM's contents.(
-LiteralPathdoesn't make a difference in this case, but it's good practice to use whenever wildcard interpretation isn't required.)Alternatively (or just for good measure), create the destination directory before calling
Copy-Item.