2013-05-17 4 views

risposta

32

Ecco un bel modo sintetico ma molto leggibile per fare questo:

$lastWrite = (get-item $fullPath).LastWriteTime 
$timespan = new-timespan -days 5 -hours 10 -minutes 5 

if (((get-date) - $lastWrite) -gt $timespan) { 
    # older 
} else { 
    # newer 
} 

Il motivo per cui funziona è perché sottraendo due date ti dà un intervallo di tempo. I tempi sono paragonabili agli operatori standard.

Spero che questo aiuti.

5

Questo script PowerShell mostrerà file più vecchi di 5 giorni, 10 ore e 5 minuti. È possibile salvare come file con estensione .ps1 e quindi eseguirlo:

# You may want to adjust these 
$fullPath = "c:\path\to\your\files" 
$numdays = 5 
$numhours = 10 
$nummins = 5 

function ShowOldFiles($path, $days, $hours, $mins) 
{ 
    $files = @(get-childitem $path -include *.* -recurse | where {($_.LastWriteTime -lt (Get-Date).AddDays(-$days).AddHours(-$hours).AddMinutes(-$mins)) -and ($_.psIsContainer -eq $false)}) 
    if ($files -ne $NULL) 
    { 
     for ($idx = 0; $idx -lt $files.Length; $idx++) 
     { 
      $file = $files[$idx] 
      write-host ("Old: " + $file.Name) -Fore Red 
     } 
    } 
} 

ShowOldFiles $fullPath $numdays $numhours $nummins 

Quello che segue è un po 'più in dettaglio circa la linea che filtra i file. E 'diviso in più righe (potrebbe non essere PowerShell legale) in modo che io possa includere commenti:

$files = @(
    # gets all children at the path, recursing into sub-folders 
    get-childitem $path -include *.* -recurse | 

    where { 

    # compares the mod date on the file with the current date, 
    # subtracting your criteria (5 days, 10 hours, 5 min) 
    ($_.LastWriteTime -lt (Get-Date).AddDays(-$days).AddHours(-$hours).AddMinutes(-$mins)) 

    # only files (not folders) 
    -and ($_.psIsContainer -eq $false) 

    } 
) 
4

Test-Path può fare questo per voi:

Test-Path $fullPath -OlderThan (Get-Date).AddDays(-5).AddHours(-10).AddMinutes(-5) 
+0

L'interruttore -OlderThan non è disponibile in PS2.0. Non sono sicuro quando è stato presentato, ma è sicuramente disponibile in PS4.0. – Mike