![](/img/trans.png)
[英]Copy folders without files, files without folders, or everything using PowerShell
[英]Copy files and folders in several Powershell versions (2.0, 3.0-4.0)
我有2.0版本的PowerShell腳本(Windows 2008)。 但是在PS 3.0 - 4.0(Windows 2012)中我失敗了。 當有文件時,因為沒有獲取任何文件而失敗。
我有4.0版本的PowerShell腳本(Windows 2012)。 但是在PS 2.0(Windows 2008)中我失敗了。 因為無法識別目錄開關而失敗。
腳本包含文件夾復制功能。
這個代碼為Powershell 2.0
function CopyWithFilterOlder ($sourcePath, $destPath)
{
$exclude = @('Thumbs.db' )
# Call this function again, using the child folders of the current source folder.
Get-ChildItem $sourcePath -Exclude $exclude | Where-Object { $_.Length -eq $null } | % { CopyWithFilterOlder $_.FullName (Join-Path -Path $destPath -ChildPath $_.Name) }
# Create the destination directory, if it does not already exist.
if (!(Test-Path $destPath)) { New-Item -Path $destPath -ItemType Directory | Out-Null }
# Copy the child files from source to destination.
Get-ChildItem $sourcePath -Exclude $exclude | Where-Object { $_.Length -ne $null } | Copy-Item -Destination $destPath
}
現在這個代碼為Powershell 3.0 - 4.0
function CopyWithFilter ($sourcePath, $destPath)
{
$exclude = @('Thumbs.db' )
# Call this function again, using the child folders of the current source folder.
Get-ChildItem $sourcePath -Directory -Exclude $exclude | % {
CopyWithFilter $_.FullName (Join-Path -Path $destPath -ChildPath $_.Name)
}
# Create the destination directory, if it does not already exist.
if (!(Test-Path $destPath)) { New-Item -Path $destPath -ItemType Directory | Out-Null }
# Copy the child files from source to destination.
Get-ChildItem -File -Path $sourcePath | % {
Write-Host ("`t`t`tCopy {0} to {1}" -f $_.FullName, $destPath);
Copy-Item $_.FullName -Destination $destPath -Force
}
}
我想保留相同的代碼,獨立於PS版本。
關於它的任何建議?
看起來你依賴於PS 2.0在System.IO.DirectoryInfo上評估.Length屬性的$ null值的行為,而當你在PS 3/4上運行時,它返回一個'1'。 如果您需要與PS 2.0向后兼容,為什么不直接檢查where-object子句中的類型,以便為您的第一個語句過濾目錄:
Where-Object { $_ -is [System.IO.DirectoryInfo] }
然后將此作為您針對文件的最后一條語句:
Where-Object { $_ -is [System.IO.FileInfo] }
這樣您就不會依賴於行為可能在不同版本之間變化的屬性。
完整樣本
function CopyWithFilterCommon ($sourcePath, $destPath)
{
$exclude = @('Thumbs.db' )
# Call this function again, using the child folders of the current source folder.
Get-ChildItem $sourcePath -Exclude $exclude | Where-Object { $_ -is [System.IO.DirectoryInfo] } | % { CopyWithFilterCommon $_.FullName (Join-Path -Path $destPath -ChildPath $_.Name) }
# Create the destination directory, if it does not already exist.
if (!(Test-Path $destPath)) { New-Item -Path $destPath -ItemType Directory | Out-Null }
# Copy the child files from source to destination.
Get-ChildItem $sourcePath -Exclude $exclude | Where-Object { $_ -is [System.IO.FileInfo] } | Copy-Item -Destination $destPath
Get-ChildItem -Path $sourcePath -Exclude $exclude | Where-Object { $_ -is [System.IO.FileInfo] } | % {
Copy-Item $_.FullName -Destination $destPath -Force
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.