首页 > 解决方案 > 检查最后创建的文件是否存在并使用 PowerShell 创建事件日志条目

问题描述

我正在使用 PowerShell 编写文件以在其中存储特定信息。我还想创建 Windows 事件日志条目以检查“新”创建的文件是否真的存在。

New-EventLog -LogName System -Source "Files I store information in"
Write-EventLog -LogName System -Source "Files I store information in" -EntryType Information -EventId 1 -Message "Information written to file script started"
$FilePath = "C:\Path\Files"
command.exe -Out-File $FilePath\${env:computername}_$(get-date -f dd-MM-yyyy-hhmm).file

基本上我正在寻找一种方法来验证上述 command.exe 是否创建了一个文件。当我使用“get-date”选项将其附加到文件名时,我不确定该怎么做。如果创建了文件,我想创建一个成功的事件日志条目。如果没有创建,我想创建一个不成功的事件日志条目。

有人对此有提示吗?

标签: powershell

解决方案


尝试捕捉,会工作

try{
$FilePath = "C:\Path\Files"
command.exe -Out-File $FilePath\${env:computername}_$(get-date -f dd-MM-yyyy-hhmm).file
       
--write below successfull log entry
you also could add more checks like below
 if (test-path "$FilePath\${env:computername}_$(get-date -f dd-MM-yyyy-hhmm)"){
write here successfull log entry
}
else
{
 ---write here unsuccessfull log entry
}     
catch{
---write here unsuccessfull log entry
}

推荐阅读