[英]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.