1
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.

Minerbob
  • 447
  • 6
  • 14
  • *I would like it to create that folder location if it does not exist.* Umm... what's stopping you from doing just that? – Ansgar Wiechers Dec 29 '17 at 19:56
  • What if: Performing the operation "Copy File" on target "Item: \\\c$\ProgramData\Scripts\log\log.log Destination: C:\Users\scotry\Desktop\PS". Copies the file to a file on my desktop instead of going into a folder named PS – Minerbob Dec 29 '17 at 20:01
  • 3
    Just create the folder if it doesn't exist. *Before* you start copying stuff to it. – Ansgar Wiechers Dec 29 '17 at 20:02

1 Answers1

0

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

Adil B
  • 14,635
  • 11
  • 60
  • 78
  • 1
    This worked slick, thank you from other peoples comments I could of also if ( !(test-path $dest\Script)){ New-Item -ItemType Directory -Path $dest\Script -force } – Minerbob Dec 29 '17 at 20:48