我使用Powershell 1.0从数组中删除项目。这是我的脚本:如何从PowerShell中的数组中删除项目?
param (
[string]$backupDir = $(throw "Please supply the directory to housekeep"),
[int]$maxAge = 30,
[switch]$NoRecurse,
[switch]$KeepDirectories
)
$days = $maxAge * -1
# do not delete directories with these values in the path
$exclusionList = Get-Content HousekeepBackupsExclusions.txt
if ($NoRecurse)
{
$filesToDelete = Get-ChildItem $backupDir | where-object {$_.PsIsContainer -ne $true -and $_.LastWriteTime -lt $(Get-Date).AddDays($days)}
}
else
{
$filesToDelete = Get-ChildItem $backupDir -Recurse | where-object {$_.PsIsContainer -ne $true -and $_.LastWriteTime -lt $(Get-Date).AddDays($days)}
}
foreach ($file in $filesToDelete)
{
# remove the file from the deleted list if it's an exclusion
foreach ($exclusion in $exclusionList)
{
"Testing to see if $exclusion is in " + $file.FullName
if ($file.FullName.Contains($exclusion)) {$filesToDelete.Remove($file); "FOUND ONE!"}
}
}
我意识到,PowerShell中的Get-ChildItem返回一个System.Array类型。
Method invocation failed because [System.Object[]] doesn't contain a method named 'Remove'.
我想要做的是$ filesToDelete转换到一个ArrayList,然后用ArrayList.Remove删除项目:尝试使用Remove方法时,因此,我得到这个错误。这是一个好主意,还是应该以某种方式直接操作$ filesToDelete作为System.Array?
感谢
(一个错字'PSIsContainere')是的,我更喜欢'Where-Object'。但是在这个问题中有两个循环 - 内部通过'$ exclusionList',所以条件应该是'-not $($ f = $ _。Fullname; $ exclusionList |?{$ f.Contains($ _ )})' – stej 2010-02-26 11:47:56
感谢理查德 - 我可以使用字符串数组作$排除。如果仔细观察代码,您会看到我必须为每个排除项都调用get-childitem。如果我有很多排除,这将不会很好。 – 2010-02-26 11:48:47
@stej:将更正 – Richard 2010-02-26 14:41:31