我使用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