Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell 2 copy-item which creates a folder if doesn't exist

$from = "\\something\1 XLS\2010_04_22\*" $to =  "c:\out\1 XLS\2010_04_22\" copy-item $from $to -Recurse  

This works if c:\out\1 XLS\2010_04_22\ does exist . Is it possible with a single command to create c:\out\1 XLS\2010_04_22\ if it doesn't exist?

like image 652
MicMit Avatar asked Apr 23 '10 00:04

MicMit


People also ask

Can copy item Create folder if not exist?

Copy a file to a directory that does not exist Instead, you need to create the folder before copying the file.

Does xcopy work in PowerShell?

xcopy is the windows command. It works with both PowerShell and cmd as well because it is a system32 utility command.

Does copy item overwrite?

By default, when you will copy item in PowerShell using the Copy-Item, it will overwrite the files in the destination folder. The above PowerShell script will overwrite the files but it will show an error for folders: Copy-Item : An item with the specified name D:\Bijay\Destination\Folder1 already exists.

How do I copy an entire folder in PowerShell?

Use Copy-Item Cmdlet to Copy Folder With Subfolders in PowerShell. The Copy-Item cmdlet copies an item from one location to another. You can use this cmdlet to copy the folder and its contents to the specified location. You will need to provide the source and destination path to copy from one place to another.


2 Answers

In PowerShell 2.0, it is still not possible to get the Copy-Item cmdlet to create the destination folder, you'll need code like this:

$destinationFolder = "C:\My Stuff\Subdir"  if (!(Test-Path -path $destinationFolder)) {New-Item $destinationFolder -Type Directory} Copy-Item "\\server1\Upgrade.exe" -Destination $destinationFolder 

If you use -Recurse in the Copy-Item it will create all the subfolders of the source structure in the destination but it won't create the actual destination folder, even with -Force.

like image 57
FrinkTheBrave Avatar answered Sep 21 '22 18:09

FrinkTheBrave


Yes, add the -Force parameter.

copy-item $from $to -Recurse -Force 
like image 36
Shay Levy Avatar answered Sep 18 '22 18:09

Shay Levy