代码之家  ›  专栏  ›  技术社区  ›  MicMit

如果不存在创建文件夹的powershell 2复制项

  •  55
  • MicMit  · 技术社区  · 14 年前
    $from = "\\something\1 XLS\2010_04_22\*"
    $to =  "c:\out\1 XLS\2010_04_22\"
    copy-item $from $to -Recurse 
    

    如果c:\ out\1 xls\2010_04_22\确实存在,则此操作有效。如果不存在,是否可以用一个命令创建“c:\ out\1 xls\2010_04_22\”。

    8 回复  |  直到 6 年前
        1
  •  71
  •   Ben    10 年前

    是的,添加 -Force 参数。

    copy-item $from $to -Recurse -Force
    
        2
  •  91
  •   FrinkTheBrave    10 年前

    在Powershell 2.0中,仍然无法获取复制项cmdlet来创建目标文件夹,您需要以下代码:

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

    如果在复制项中使用-recurse,它将在目标中创建源结构的所有子文件夹,但不会创建实际的目标文件夹,即使使用-force。

        3
  •  10
  •   mjudd    9 年前

    在powershell 3及更高版本中,我将复制项与新项一起使用。

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

    我还没试过第二版。

        4
  •  2
  •   majkinetor    8 年前
      $filelist | % {
        $file = $_
        mkdir -force (Split-Path $dest) | Out-Null
        cp $file $dest
      } 
    
        5
  •  2
  •   Michael Erickson    8 年前

    我最喜欢使用.net[io.directoryinfo]类,它负责一些逻辑。实际上,我用它来解决很多类似的脚本问题。它有一个.create()方法,可以创建不存在的目录,如果存在,则不会出错。

    因为这仍然是一个两步问题,所以我使用foreach别名来保持它的简单性。对于单个文件:

    [IO.DirectoryInfo]$to |% {$_.create(); cp $from $_}
    

    就多文件/目录匹配而言,我将在xcopy上使用robocopy。从中删除“*”,然后使用:

    RoboCopy.exe $from $to *
    

    您仍然可以添加/r(recurse),/e(recurse包括empty),还有50个其他有用的开关。

    编辑: 回顾一下这段代码,它很简洁,但是如果您不经常使用代码,它的可读性就不是很强。通常我把它分成两部分,就像这样:

    ([IO.DirectoryInfo]$to).Create()
    cp $from $to
    

    也, 目录信息 是的父属性的类型 文件信息 所以如果你 美元到 是一个文件,可以一起使用:

    ([IO.FileInfo]$to).Parent.Create()
    cp $from $to
    
        6
  •  2
  •   peter.hrasko.sk Florin Ghita    7 年前
    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
        } 
    }
    
        7
  •  2
  •   Toby Bierly    6 年前

    这是一个对我有用的例子。我在一个文本文件中有一个大约500个特定文件的列表,包含在大约100个不同的文件夹中,我应该复制到一个备份位置,以防以后需要这些文件。文本文件包含完整路径和文件名,每行一个。在我的例子中,我想从每个文件名中去掉驱动器号和第一个子文件夹名。我想将所有这些文件复制到我指定的另一个根目标文件夹下的类似文件夹结构。我希望其他用户觉得这有帮助。

    # Copy list of files (full path + file name) in a txt file to a new destination, creating folder structure for each file before copy
    $rootDestFolder = "F:\DestinationFolderName"
    $sourceFiles = Get-Content C:\temp\filelist.txt
    foreach($sourceFile in $sourceFiles){
        $filesplit = $sourceFile.split("\")
        $splitcount = $filesplit.count
        # This example strips the drive letter & first folder ( ex: E:\Subfolder\ ) but appends the rest of the path to the rootDestFolder
        $destFile = $rootDestFolder + "\" + $($($sourceFile.split("\")[2..$splitcount]) -join "\")
        # Output List of source and dest 
        Write-Host ""
        Write-Host "===$sourceFile===" -ForegroundColor Green
        Write-Host "+++$destFile+++"
        # Create path and file, if they do not already exist
        $destPath = Split-Path $destFile
        If(!(Test-Path $destPath)) { New-Item $destPath -Type Directory }
        If(!(Test-Path $destFile)) { Copy-Item $sourceFile $destFile }
    }
    
        8
  •  0
  •   ATek    8 年前

    我在这里绊倒了两次,而这最后一次是一个独特的情况,即使我放弃使用 copy-item 我想发布我使用的解决方案。

    只有完整路径的文件列表,在大多数情况下,这些文件没有扩展名。这个 -Recurse -Force 选择对我不起作用,所以我放弃了 复制项目 函数并使用xcopy返回到下面这样的地方,因为我仍然希望它保持一行。最初我和robocopy联系在一起,但它显然在寻找一个文件扩展名,而且由于我的许多文件都没有扩展名,所以它认为它是一个目录。

    $filelist = @("C:\Somepath\test\location\here\file","C:\Somepath\test\location\here2\file2")
    
    $filelist | % { echo f | xcopy $_  $($_.Replace("somepath", "somepath_NEW")) }
    

    希望它能帮助别人。

    推荐文章