gpt4 book ai didi

用于 logrotate 日志的 Powershell 脚本

转载 作者:行者123 更新时间:2023-12-03 11:21:51 26 4
gpt4 key购买 nike

好的。所以我想编写一个 PowerShell 脚本来模拟(某种)在 Linux 中找到的 LogRotate 选项。对于单个文件:没问题。但我希望它适用于文件夹内的所有文件。但是......它不起作用......完全没有。我尝试用 foreach-object 来做,但它仍然不起作用。我是 PowerShell 编程的新手,所以如果我的脚本看起来不那么好,请原谅我干净的。
这里是:

function RotateLog {
$log = "C:\Users\nvali\Desktop\scripts"
Push-Location $log
$target = Get-ChildItem $log -Filter "*.txt"
$threshold = 300
$datetime = Get-Date -uformat "%Y-%m-%d-%H%M"
#$target_path =Get-ChildItem $log
$filesize = $target.length/1MB
$target | ForEach-Object {
if ($filesize -ge $threshold) {
$filename = $_.name -replace $_.extension,""
$newname = "${filename}_${datetime}.log_old"
Rename-Item $_.fullname $newname
$rotationmessage = ""
Write-Host "Done"
}
echo "$rotationmessage"
}
}

最佳答案

您需要检查 foreach 中每个文件的文件大小为 LotPings提到,并作为 BenH评论说,在 foreach 中你需要使用 $_访问正在访问的当前对象。

这个脚本对我有用,没有任何错误。

function RotateLog {
$log = "C:\logDir"
$target = Get-ChildItem $log -Filter "*.txt"
$threshold = 30
$datetime = Get-Date -uformat "%Y-%m-%d-%H%M"
$target | ForEach-Object {
if ($_.Length -ge $threshold) {
Write-Host "file named $($_.name) is bigger than $threshold KB"
$newname = "$($_.BaseName)_${datetime}.log_old"
Rename-Item $_.fullname $newname
Write-Host "Done rotating file"
}
else{
Write-Host "file named $($_.name) is not bigger than $threshold KB"
}
Write-Host " "
}

关于用于 logrotate 日志的 Powershell 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43593248/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com