我在我的腳本中使用了日志,并寫下了這樣的日期、月份和時間:
我在我的腳本中使用了日志。
$LogTime = Get-Date -Format "dd-MM HH: mm"
我想從檔案中洗掉所有超過一個月的行數 我想像這樣做,但它不作業:
$DateOld = (get-date (獲取日期).addDays(-30) -UFormat "%d-%m")
$RemoveLog = get-content -Path C:.....LogUserLog.txt | where {($_.split('-')) [1] -gt $DateOld} | Set-Content "C:......Logout.txt" | Out-Null
Remove-Item -Path C:........LogUserLog.txt -Force | Out-Null
Rename-Item -Path "C:.........Logout.txt" -NewName "UserLog.txt"| Out-Null
日志中的這一行看起來是這樣的:
20-09 11:30 ::: 有關于日志資訊的一行uj5u.com熱心網友回復:
類似這樣的事情。 備注。 -powershell陣列在大陣列上會變得很慢,所以你最好使用一個generic.list
。- 這只是一個初稿。
- 這只是一個初稿,根據具體的要求和日志檔案,你將需要一些微調和/或例外處理,但你應該得到這個想法: 。
#tmp 20 09 2021
$logfile = 'your path'。
[array]$log = Get-Content $logfile
$newLog = @()
$limitDate = (Get-Date).AddDays(-30)
foreach ($line in $log) {
$regex = [regex]::match($line, '(d{2}-d{2})sd{2}:d{2}')
if($regex.Success -eq 'True') {
$lineDate = [datetime]::ParseExact($regex。 Groups[1].Value.ToString(), "dd-MM", $null)
if ($lineDate -ge$limitDate) {
$newLog = $line
}
}
else {
[console]::WriteLine('Big Exception in Logfile! Will Quit')
退出。
}
}
Remove-Item $logfile -Force
if(-not (Test-Path $logfile) ) {
$newLog | Out-File $logfile !
}
else {
[console]::WriteLine('Big Exception in Logfile! 請調查')
}
uj5u.com熱心網友回復:
你可以使用[datetime]::ParseExact()方法來讀取你的檔案日期和時間作為[datetime]物件。你可以使用Move-Item來使用其-Force引數以一個新的名稱覆寫一個檔案。
$DateOld=(Get-Date).AddDays(-30)
Get-Content UserLog.txt | Where {
[datetime]::ParseExact([string](-split $_) [0. .1],'dd-MM HH:mm'。
[System.Globalization.DateTimeFormatInfo]::InvariantInfo) -ge $DateOld。
} | Set-Content out.txt
Move-Item out.txt UserLog.txt -Force
使用-split value,value基于一個空格分隔符進行分割。因為我們只想要前兩個元素,所以我們使用范圍0...1來表示前兩個結果元素。鑄成[string]后,用一個空格分隔符重新加入分割的專案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/326672.html
標籤:
