我面临着用PowerShell在文件系统中移动和复制一些项目的问题。
通过实验,我知道,即使使用PowerShell v3,cmdlet Copy-Item、Move-Item和Delete-Item 也不能正确处理像连接和符号链接这样的应答点,如果与交换机-Recurse一起使用,也会导致灾难。
我想阻止这种情况的发生。我必须处理两个或更多的文件夹,每次运行,所以我想这样的事情。
$Strings = @{ ... }
$ori = Get-ChildItem $OriginPath -Recurse
$dri = Get-ChildItem $DestinationPath -Recurse
$items = ($ori + $dri) | where { $_.Attributes -match 'ReparsePoint' }
if ($items.Length -gt 0)
{
Write-Verbose ($Strings.LogExistingReparsePoint -f $items.Length)
$items | foreach { Write-Verbose " $($_.FullName)" }
throw ($Strings.ErrorExistingReparsePoint -f $items.Length)
}这不起作用,因为$ori和$dri也可以是单个项,而不是数组:op-Addition将失败。变到
$items = @(@($ori) + @($dri)) | where { $_.Attributes -match 'ReparsePoint' }这带来了另一个问题,因为$ori和$dri也可以是$null,而我可以以包含$null的数组结尾。同样,当连接返回到Where-Object时,我可以用一个$null、一个单项或一个数组来结束。
唯一明显有效的解决方案是下面的更复杂的代码
$items = $()
if ($ori -ne $null) { $items += @($ori) }
if ($dri -ne $null) { $items += @($dri) }
$items = $items | where { $_.Attributes -match 'ReparsePoint' }
if ($items -ne $null)
{
Write-Verbose ($Strings.LogExistingReparsePoint -f @($items).Length)
$items | foreach { Write-Verbose " $($_.FullName)" }
throw ($Strings.ErrorExistingReparsePoint -f @($items).Length)
}有更好的方法吗?
我很感兴趣的是,是否有一种方法可以用PowerShell cmdlet正确地处理修复点,但是更感兴趣的是如何加入和过滤两个或更多的"PowerShell集合“。
我总结说,目前,PowerShell的这一特性,即“多态数组”,对我来说并没有这样的好处。
感谢您的阅读。
发布于 2012-12-24 05:00:45
只需添加一个过滤器就可以抛出空值。你走在正确的轨道上。
$items = @(@($ori) + @($dri)) | ? { $_ -ne $null }
发布于 2013-02-18 07:29:54
我使用Powershell 3已经有一段时间了,但据我所知,它在2.0中也能工作:
$items = @($ori, $dri) | %{ $_ } | ? { $_.Attributes -match 'ReparsePoint' }基本上,%{ $_ }是一个foreach循环,它通过迭代内部数组并将每个内部元素($_)沿管道向下传递来展开内部数组。Nulls将自动被排除在管道之外。
https://stackoverflow.com/questions/12953366
复制相似问题