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

前端 未结 9 2496
余生分开走
余生分开走 2020-12-05 12:55
$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\\

9条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-05 12:58

    I modified @FrinkTheBrave 's answer to also create sub-directories, and resolve relative paths:

    $src_root = Resolve-Path("./source/path/")
    $target_root = Resolve-Path("./target/path/")
    $glob_filter = "*.*"
    Get-ChildItem -path $src_root -filter $glob_filter -recurse | 
      ForEach-Object {
            $target_filename=($_.FullName -replace [regex]::escape($src_root),$target_root) 
            $target_path=Split-Path $target_filename
            if (!(Test-Path -Path $target_path)) {
                New-Item $target_path -ItemType Directory
            }
            Copy-Item $_.FullName -destination $target_filename
        }
    

提交回复
热议问题