Estoy usando Powershell 1.0 para eliminar un elemento de una matriz. Aquí está mi script:¿Cómo eliminar un elemento de una matriz en 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!"}
}
}
Soy consciente de que Get-ChildItem en PowerShell devuelve un tipo de System.array. Por lo tanto, me sale este error al intentar utilizar el método Remove:
Method invocation failed because [System.Object[]] doesn't contain a method named 'Remove'.
Lo que me gustaría hacer es convertir $ filesToDelete a un ArrayList y luego eliminar elementos usando ArrayList.Remove. ¿Es esta una buena idea o debería manipular directamente $ filesToDelete como System.Array de alguna manera?
Gracias
(un error 'PSIsContainere') Sí, preferiría' Where-Object' también. Sin embargo, en la cuestión hay dos bucles - el interior pasa por '$ exclusionList' lo que la condición probablemente debería ser algo como' -no $ ($ f = $ _ Nombre completo; $ ExclusionList | {$ f.Contains ($ _.?)}) ' – stej
Gracias Richard - puedo usar una matriz de cadenas para $ exclusion. Si miran más de cerca el código, verán que tendré que llamar a get-childitem para cada exclusión. Esto no funcionaría bien si tengo muchas exclusiones. –
@stej: corregirá – Richard