【问题标题】:How i get a Logfile from my Powershellscript我如何从我的 Powershell 脚本中获取日志文件
【发布时间】:2018-01-17 12:03:58
【问题描述】:

我想将我的 Powershell 脚本的所有输入和输出记录到一个日志文件中。我尝试了一个函数,但我必须在每一行中编写函数。我已经用 Start-transcript 对其进行了测试,我不知道,但我认为它仅适用于错误,它并不能很好地工作。 如果我启动脚本以获取所有行的日志,是否有可能?

例如:

$u=rene
New-AdUser -Name $u ...
Write-Hoste "New User ist Create $u"

并且在我的日志文件中应该是:

17.01.2018 13:00 $u=rene
17.01.2018 13:00 New-AdUser -Name $u ...
17.01.2018 13:00 Write-Hoste "New User ist Create $u"

...以及其他所有内容(例如错误)

【问题讨论】:

    标签: powershell


    【解决方案1】:

    如果你想记录整个脚本,那么你可以这样做

    @(
    $u=rene
    New-AdUser -Name $u ...
    Write-Hoste "New User ist Create $u"
    ... Rest of your script
    ) | Out-file -FilePath \\PathToYourLogFile\Logfile.txt"
    

    这是一种方法。另一种方法是在脚本的开头使用Start-Transcript,并使用Stop-Transcript cmdlet 结束脚本,并将输出重定向到文本文件。详情请参阅start-transcriptstop-transcript

    我找到了一个示例,该示例将为您的脚本创建每日日志(如果您每天多次运行它,它只会附加到您所拥有的日志中)。该日志将与您的脚本位于同一文件夹中,并且会清除所有超过 15 天的日志。

    $VerbosePreference = "Continue"
    $LogPath = Split-Path $MyInvocation.MyCommand.Path
    Get-ChildItem "$LogPath\*.log" | Where LastWriteTime -LT (Get-Date).AddDays(-15) | Remove-Item -Confirm:$false
    $LogPathName = Join-Path -Path $LogPath -ChildPath "$($MyInvocation.MyCommand.Name)-$(Get-Date -Format 'MM-dd-yyyy').log"
    Start-Transcript $LogPathName -Append
    

    然后在脚本的末尾,添加

    Stop-Transcript
    

    Here 是相同的链接。 如果您想记录特定的事情,那么您可以在特定和所需的位置使用Out-File cmdlet。希望对您有所帮助!

    【讨论】:

    • 如果我使用 Transcript,如果他有错误,他只会写一个日志,如果我创建了一个没有错误的新用户,那么他不会在日志中写入任何内容。原始脚本更大,并且需要在输出文件的每一行添加很多工作
    • 那是因为如果用户创建成功没有遇到错误。如果您也希望在日志中使用它,则需要在脚本中添加额外的自定义消息。类似write-output "User created successfully!"
    • 是的,没错,但我会记录一个从开始到停止的日志。从创建或成功到错误的所有消息。
    猜你喜欢
    • 2021-09-30
    • 2021-03-28
    • 1970-01-01
    • 2012-10-03
    • 2010-10-17
    • 1970-01-01
    • 2022-10-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多