PS脚本的简单日志文件?

我有一个PS脚本,可以从文件夹中删除特定文件。但是我希望在脚本运行时创建并更新一个日志文件,其中列出了已删除的文件。

我的脚本:

$Directory = "C:\test"
Get-ChildItem -path $Directory | 
Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-45) } | 
Remove-Item -Recurse -Force -Confirm:$false
monkey1210 回答:PS脚本的简单日志文件?

您可以使用Set-Content和Update-Content设置简单的日志记录。然后修改您的脚本以完成这两个任务。

$Directory = "C:\test"
$files = Get-ChildItem -path $Directory | 
    where-object { $_.LastWriteTime -lt (Get-Date).AddDays(-45) } | 
    Select-Object -ExpandProperty FullName
foreach($file in $files){
    Add-Content -Path C:\test\log.log -Value "Deleted file: $file"
    Remove-Item -path $file -Recurse -Force -Confirm:$false
}
,

如果您希望在应用程序中具有有意义且易于编写和读取的日志,建议您使用Powershell上的EventLog cmdlet。

直接从Powershell帮助中:

get-help New-EventLog -ShowWindow

Example 1: Create an event log and register its source
    PS C:\>New-EventLog -Source "TestApp" -LogName "TestLog" -MessageResourceFile "C:\Test\TestApp.dll"

get-help Write-EventLog -ShowWindow

Example 1: Write an event to the Application event log
    PS C:\>Write-EventLog -LogName "Application" -Source "MyApp" -EventID 3001 -EntryType Information -Message "MyApp added a user-requested feature to the display." -Category 1 -RawData 10,20

然后,您可以阅读日志并将其保存到文件中。

本文链接:https://www.f2er.com/3165132.html

大家都在问