【问题标题】:RotateLog with powershell使用 powershell 旋转日志
【发布时间】:2020-04-17 13:34:50
【问题描述】:

我是脚本和 Powershell 的新手,我正在尝试创建一个脚本来每天只保留最后 3 天的日志文件

function RotateLog {
$dir="C:\Users\user1\Documents\Project\LOG"
$DayMax= -3
$CurrentDate= Get-Date -uformat "%d-%m-%Y-%H%M"
$DatetoDelete= (get-date -UFormat "%d-%m-%Y-%H%M").AddDays($DayMax)

get-childitem -path $dir -filter "YYYY-mm-dd-*.LOG"
foreach-object {
if ($_.LastWriteTime -lt $DatetoDelete)
{remove-item}
}
}

当我运行 $DatetoDelete 时,它​​返回失败,因为 [System.String] 不包含名为“AddDays”的方法。

所以我尝试将变量替换为

$dtt=(get-date).AddDays($DayMax)

它是这样工作的,但我需要获取格式。 我该怎么做?

另一个问题,当我运行命令remove-item时,它在命令管道位置1返回cmdlet remove-item 为以下参数提供值:path[0] 什么意思?

【问题讨论】:

  • 为了比较事物,使用[datetime] objects ...除了显示之外,切勿将它们转换为日期时间strings

标签: powershell logrotate


【解决方案1】:

-Format-UFormat 参数使Get-Date 输出对应[datetime] 对象的字符串表示,并且“将-3 天添加到字符串”并没有多大意义感觉。

使用Get-Date 不带格式参数来获取[datetime]对象,该对象可以进行有意义的修改和比较:

# Get current date and time as a [datetime] object
$CurrentDate = Get-Date

# Here I reference the `Date` property on our DateTime object
# this gives us the same date, but at 00:00 local time
$DateToDelete = $CurrentDate.Date.AddDays($DayMax)

现在,$_.LastWriteTime -lt $DatetoDelete 更有意义,因为我们将 [datetime][datetime] 进行比较,而不是与格式化字符串进行比较

【讨论】:

    猜你喜欢
    • 2016-09-08
    • 1970-01-01
    • 1970-01-01
    • 2015-08-14
    • 2020-03-02
    • 2012-12-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多