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

149,293

Solution 1

Yes, add the -Force parameter.

copy-item $from $to -Recurse -Force

Solution 2

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.

Solution 3

In PowerShell 3 and above I use the Copy-Item with New-Item.

copy-item -Path $file -Destination (new-item -type directory -force ("C:\Folder\sub\sub\" + $newSub)) -force -ea 0

I haven't tried it in ver 2.

Solution 4

function Copy-File ([System.String] $sourceFile, [System.String] $destinationFile, [Switch] $overWrite) {

    if ($sourceFile -notlike "filesystem::*") {
        $sourceFile = "filesystem::$sourceFile" 
    }

    if ($destinationFile -notlike "filesystem::*") {
        $destinationFile = "filesystem::$destinationFile" 
    }

    $destinationFolder = $destinationFile.Replace($destinationFile.Split("\")[-1],"")

    if (!(Test-Path -path $destinationFolder)) {
        New-Item $destinationFolder -Type Directory
    }

    try {
        Copy-Item -Path $sourceFile -Destination $destinationFile -Recurse -Force
        Return $true 
    } catch [System.IO.IOException] {
        # If overwrite enabled, then delete the item from the destination, and try again:
        if ($overWrite) {
            try {
                Remove-Item -Path $destinationFile -Recurse -Force        
                Copy-Item -Path $sourceFile -Destination $destinationFile -Recurse -Force 
                Return $true
            } catch {
                Write-Error -Message "[Copy-File] Overwrite error occurred!`n$_" -ErrorAction SilentlyContinue
                #$PSCmdlet.WriteError($Global:Error[0])
                Return $false
            }
        } else {
            Write-Error -Message "[Copy-File] File already exists!" -ErrorAction SilentlyContinue
            #$PSCmdlet.WriteError($Global:Error[0])
            Return $false
        }
    } catch {
        Write-Error -Message "[Copy-File] File move failed!`n$_" -ErrorAction SilentlyContinue
        #$PSCmdlet.WriteError($Global:Error[0]) 
        Return $false
    } 
}

Solution 5

  $filelist | % {
    $file = $_
    mkdir -force (Split-Path $dest) | Out-Null
    cp $file $dest
  } 
Share:
149,293
MicMit
Author by

MicMit

Updated on March 12, 2021

Comments

  • MicMit
    MicMit about 3 years
    $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?

  • stej
    stej about 14 years
    PowerShell is so easy when one knows it :)
  • Gary Evans
    Gary Evans over 13 years
    That works for entire directories, but what if I'm just copying individual files (so I can have a status)? How do you copy c:\test1\file.txt to c:\test2\file.txt when c:\test2 does not exist? That's what I really need to know how to do. Thanks, Gary
  • rjschnorenberg
    rjschnorenberg about 12 years
    I ran into this same problem and solved it by calling New-Item first: New-Item -Force $to Copy-Item -Force $from $to
  • Joost van der Griendt
    Joost van der Griendt over 7 years
    Thanks for this observation. I got some inconsistent copy actions; sometimes it copied a subfolder and sometimes it did not. After making sure the destination folder existed this inconsistency was gone.
  • vicancy
    vicancy about 7 years
    I also encounter the wrong behavior when the target folder does not exist
  • Toby Speight
    Toby Speight almost 7 years
    Welcome to Stack Overflow! Thank you for this code snippet, which may provide some immediate help. A proper explanation would greatly improve its educational value by showing why this is a good solution to the problem, and would make it more useful to future readers with similar, but not identical, questions. Please edit your answer to add explanation, and give an indication of what limitations and assumptions apply.
  • Hicsy
    Hicsy over 6 years
    This works great for local copy thanks! Not when using -ToSession command though :'(
  • jdawiz
    jdawiz over 5 years
    Thanks. This was the answer I was looking for. To bad there not switch to create destination folder.