# try and establish a connection to port async $tcpobject = New-Object System.Net.Sockets.TcpClient $connect = $tcpobject.BeginConnect($computername,$port,$null,$null)
# wait for the connection no longer than $timeoutMilliseconds $wait = $connect.AsyncWaitHandle.WaitOne($timeoutMilliseconds,$false)
# this is the folder keeping the log files $LogFileDir = "c:\myLogFiles"
# find all log files... Get-ChildItem-Path$LogFileDir-Filter *.log | # sort by last change ascending # (oldest first)... Sort-Object-Property LastWriteTime | # take the first (oldest) one Select-Object-First1 | # remove it (remove -whatif to actually delete) Remove-Item-WhatIf
如果只希望保留最新的 5 个文件,请像这样更改:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
# this is the folder keeping the log files $LogFileDir = "c:\myLogFiles" $Keep = 5
if ($NumberToDelete-gt0) { $files | # sort by last change ascending # (oldest first)... Sort-Object-Property LastWriteTime | # take the first (oldest) one Select-Object-First$NumberToDelete | # remove it (remove -whatif to actually delete) Remove-Item-WhatIf }