Używam Powershell 1.0 do usuwania elementu z tablicy. Oto mój skrypt:Jak usunąć element z tablicy w 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!"}
}
}
Zdaję sobie sprawę, że Get-ChildItem w powershell zwraca typ System.Array. I dlatego ten błąd, gdy próbuje użyć metody usunięcia:
Method invocation failed because [System.Object[]] doesn't contain a method named 'Remove'.
Co chciałbym zrobić, to przekształcić $ filesToDelete do ArrayList, a następnie usunąć elementy używając ArrayList.Remove. Czy jest to dobry pomysł, czy powinienem bezpośrednio manipulować $ filesToDelete jako System.Array w jakiś sposób?
Dzięki
(jeden litero 'PSIsContainere') Tak, wolałbym również' Where-Object'. Jednak w pytaniu są dwie pętle - wewnętrzna przechodzi przez '$ exclusionList', więc warunek powinien prawdopodobnie wyglądać jak' -nie $ ($ f = $ _. Pełna nazwa; $ exclusionList |? {$ F.Contains ($ _)}) ' – stej
Dzięki Richard - czy mogę użyć tablicy łańcuchów dla $ wykluczenia. Jeśli przyjrzysz się bliżej kodowi, zobaczysz, że będę musiał wywołać get-childitem dla każdego wykluczenia. Nie działałoby to dobrze, jeśli mam wiele wyjątków. –
@stej: Poprawnie – Richard