如何从PowerShell中删除数组中的项?

Mar*_*son 6 arrays powershell arraylist

我正在使用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!"}
    }
}
Run Code Online (Sandbox Code Playgroud)

我意识到powershell中的Get-ChildItem返回一个System.Array类型.因此,我在尝试使用Remove方法时遇到此错误:

Method invocation failed because [System.Object[]] doesn't contain a method named 'Remove'.
Run Code Online (Sandbox Code Playgroud)

我想做的是将$ filesToDelete转换为ArrayList,然后使用ArrayList.Remove删除项目.这是一个好主意还是我应该以某种方式直接操作$ filesToDelete作为System.Array?

谢谢

Ric*_*ard 9

执行此操作的最佳方法是使用Where-Object执行过滤并使用返回的数组.

您还可以使用@splat将多个参数传递给命令(V2中的新增功能).如果你不能升级(并且你应该尽可能地,那么只需从Get-ChildItems收集输出(只重复那个CmdLet)并在公共代码中进行所有过滤).

脚本的工作部分变为:

$moreArgs = @{}
if (-not $NoRecurse) {
  $moreArgs["Recurse"] = $true
}

$filesToDelete = Get-ChildItem $BackupDir @moreArgs |
                 where-object {-not $_.PsIsContainer -and 
                               $_.LastWriteTime -lt $(Get-Date).AddDays($days) -and
                              -not $_.FullName.Contains($exclusion)}
Run Code Online (Sandbox Code Playgroud)

在PSH数组中是不可变的,你不能修改它们,但是很容易创建一个新+=数组(像数组上的运算符实际上创建一个新数组并返回它).