用于记录日志的Powershell脚本

时间:2017-04-24 16:23:35

标签: powershell

好的。所以我想编写一个PowerShell脚本来模拟(排序)在Linux中找到的LogRotate选项。对于一个文件:没问题。但我希望它适用于所有文件INSIDE一个文件夹。但是。 ..它根本不起作用。我尝试用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"
    }
}

1 个答案:

答案 0 :(得分:0)

您需要检查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 " "
}