本帖最后由 wrove 于 2019-1-26 00:37 编辑
- function Copy-ItemWithKeepTheDirectoryStructure {
- <#
- .EXAMPLE
- Copy-ItemWithKeepTheDirectoryStructure -FromFolder D:\ `
- -ToFolder test -Extensions txt, xml `
- -SearchSubFolders bin, data
-
- .EXAMPLE
- Copy-ItemWithKeepTheDirectoryStructure -FromFolder e:\ `
- -ToFolder test -Extensions txt, doc
- #>
- param(
- [Parameter(Mandatory = $true,
- Position = 1)]
- [ValidateScript({ Test-Path $_ })]
- [string]$FromFolder,
-
- [Parameter(Mandatory = $true,
- Position = 2)]
- [string]$ToFolder,
-
- [Parameter(Mandatory = $true)]
- [string[]]$Extensions,
-
- [Parameter(Mandatory = $false)]
- [string[]]$SearchSubFolders
- )
- #0.检查并标准化参数
- if(!(Test-Path $ToFolder)) {
- New-Item -ItemType Directory -Path $ToFolder | Out-Null
- }
- $ToFolder = (Resolve-Path $ToFolder).Path
- $FromFolder = (Resolve-Path $FromFolder).Path
- if($FromFolder -eq $ToFolder) {
- throw [System.ArgumentException]::new(
- 'FromFolder与ToFolder必须指向不同的目录')
- }
- $Extensions = $Extensions |
- ForEach-Object {
- if($_.StartsWith('*.')) {
- $_
- } else {
- '*.' + $_
- }
- }
- #1.切换目录
- Push-Location
- Set-Location $FromFolder
- #2.开始处理
- if($SearchSubFolders -eq $null) {
- Get-ChildItem -Recurse -File -Include $Extensions |
- ForEach-Object {
- $sPath = Resolve-Path $_.FullName -Relative
- $lPath = Split-Path $sPath
- $rPath = Split-Path $sPath -Leaf
- $dPath = $ToFolder + $sPath.Substring(1)
- $dFolder = $ToFolder + $lPath.Substring(1)
- if(!(Test-Path $dFolder)) {
- New-Item -ItemType Directory -Path $dFolder | Out-Null
- }
- Copy-Item -LiteralPath $sPath -Destination $dPath | Out-Null
- }
- } else {
- Get-ChildItem -Recurse -Directory -Include $SearchSubFolders |
- ForEach-Object {
- Get-ChildItem -Path ($_.FullName + '\*') -File `
- -Include $Extensions
- } | ForEach-Object {
- $sPath = Resolve-Path $_.FullName -Relative
- $lPath = Split-Path $sPath
- $rPath = Split-Path $sPath -Leaf
- $dPath = $ToFolder + $sPath.Substring(1)
- $dFolder = $ToFolder + $lPath.Substring(1)
- if(!(Test-Path $dFolder)) {
- New-Item -ItemType Directory -Path $dFolder | Out-Null
- }
- Copy-Item -LiteralPath $sPath -Destination $dPath | Out-Null
- }
- }
- #3.切换回原有的当前目录
- Pop-Location
- }
复制代码
|