Need Help with PowerShell Copy-Item Command

0
19
Asked By CuriousCoder99 On

I'm looking for help with a PowerShell script that I've been using for a while to back up a legacy Windows program that doesn't have built-in backup capabilities. The script runs daily via the Windows Task Scheduler, and here are the details:

- Operating System: Windows 10 Pro
- Scheduled Program: Powershell.exe
- Arguments: -ExecutionPolicy Bypass -WindowStyle Hidden C:PEMcopyPEMscript.ps1

The script (copyPEMscript.ps1) uses the command:

`Copy-Item -Path C:PEM*.* -Destination "D:foofoo2PEM Backup" -Force -Recurse`

However, it seems to only create a single file in the destination directory instead of copying the entire directory structure as expected with the -Recurse flag. What could be going wrong? Thanks for your assistance!

2 Answers

Answered By PowerShellPro On

If you're looking for something more robust, here's a modified script that includes error handling and optional logging:

```powershell
$source = 'E:Foo'
$destination = 'C:foofoo2Pem Backup'

try {
if (-not (Test-Path -Path $source)) {
throw "Source path '$source' does not exist."
}
New-Item -Path $destination -ItemType Directory -Force | Out-Null
Copy-Item -Path (Join-Path $source '*') -Destination $destination -Recurse -Force -ErrorAction Stop
}
catch {
exit 1
}
```

This script checks if the source exists, creates the destination directory, and copies all files/folders while preserving structure. You can uncomment the log lines if you want to track what happens during the process!

CuriousCoder99 -

I tried this too and it works. I like the log file aspect as well. I'm using this as my final solution. Thanks!

Answered By ScriptWizard123 On

It looks like the issue lies in the way you're specifying the files to copy. Using `*.*` is an old-style way to indicate all files, which might only match certain file names and not everything. Try changing your command to:

`Copy-Item -Path C:PEM* -Destination "D:foofoo2PEM Backup" -Force -Recurse`

This should correctly copy all files and folders from the source. Let me know if that works for you!

CuriousCoder99 -

I tried the modification and it works! Thank you. What I still don't understand is, the source directory contains a number of files with extensions. It seems that the old *.* wildcard didn't even copy those, which I thought it should have.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.