Search code examples
powershellcopy-item

Powershell Copy-Item -Destination


Get-ChildItem -Path \\$SiteMachineName\c$\ProgramData\Scripts\log -Recurse |
    Where-Object {$_.LastWriteTime -gt (Get-Date).AddDays(-40)} |
    select * |
    Select -ExpandProperty FullName |
    Copy-Item -Destination C:\Users\<username>\Desktop\PS

This is the script I'm trying to run, It grabs all the files older then 40 days from the script folder on a remote machine. This part works. The issue is that if I don't have a folder on my desktop named PS, it just creates a file named PS instead of copying all the files to that folder location.

I would like it to create that folder location if it does not exist.

This is not a duplicate adding the -force -Recurse gives the error

Copy-Item : Could not find a part of the path

adding the New-Item to the Destination flag resolved the issue.


Solution

  • Try replacing your Copy-Item's Destination flag with a New-Item -force directive:

    copy-item -Destination (new-item -type directory -force ("C:\Users\<username>\Desktop\PS")) -force
    

    Source answer