如何使用Powershell脚本在日志文件中附加换行文本?

时间:2019-05-21 06:48:35

标签: powershell

我需要从C:\中的原始路径中提取日志到D:\ Logs中的日志目录中,但是每次原始路径创建新日志时,脚本都需要追加新行,而不是替换或重写整行。 / p>

我已经尝试过了,但是我猜想它会替换整个文件,并且我不确定Param的事情。

$SourceFolder       = "C:\ProgramData\Sophos\Sophos Anti-Virus\logs"
$DestinationFolder  = "D:\Logs\SophosAntivirus"

Function ChangeTabToSpace 
{
    Param(
        [string] $OldFile = "",
        [string] $NewFile = ""
    )
    $OldText = (Get-Content $OldFile -Raw)
    #Change all tabt \t to space 
    $NewText = ($OldText -replace "`t"," ")
    #Delete the last empty line
    if ($NewText.Length -ge 2) {
        $NewText = $NewText.Substring(0,$NewText.Length-2)
    }
    if (!(Test-path "$NewFile")) {
        New-Item -type file "$NewFile" -force | Out-Null
    }
    #Write-Output $NewText | Out-File -Encoding utf8 "$NewFile"
    [System.IO.File]::WriteAllLines($NewFile, $NewText)
}

1 个答案:

答案 0 :(得分:1)

如果它是一个简单的文本文件,则可以使用以下

"the string you want or have" | out-file -path $path -append

这会将字符串添加到文件末尾的新行中。

您不需要像我一样输入输入内容……这只是我学会使用并一直使用的方式。