我正在使用 Powershell 1.0 从数组中删除一个元素。以下是我的脚本:
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。因此,当尝试使用Remove方法时,会出现以下错误:
Method invocation failed because [System.Object[]] doesn't contain a method named 'Remove'.
我想做的是将$filesToDelete转换为ArrayList,然后使用ArrayList.Remove删除项。这个想法好吗?还是应该以某种方式直接操作$filesToDelete作为System.Array?谢谢。
Where-Object
。但是在这个问题中有两个循环 - 内部循环遍历$exclusionList
,因此条件应该类似于-not $($f=$_.Fullname; $exclusionList |?{$f.Contains($_)})
。 - stej-exclude
参数接受string[]
类型,因此您可以传递多个通配符。 - Richard