如何获取我的 PowerShell 脚本删除文件的时间和日期

How can I get the time and date my PowerShell script deletes a file

我正在使用以下脚本读取文件名列表,然后将其删除。有没有办法可以输出每个文件被删除的日期和时间?

$targetFolder = "D:\" $fileList = "C:\DeleteList.txt" Get-ChildItem
-Path "$targetFolder\*" -Recurse -Include @(Get-Content $fileList) | Remove-Item -Verbose

感谢您的帮助。

您可以通过输出包含文件全名和当前日期的对象来跟踪删除的文件和删除时间。

然后可以将此输出另存为结构化 CSV 文件

$targetFolder = "D:\" 
$fileList     = Get-Content -Path "C:\DeleteList.txt" 

$deleted = Get-ChildItem -Path $targetFolder -Recurse -Include $fileList | ForEach-Object {
    # output an object with the current date and the file FullName
    $_ | Select-Object @{Name = 'DeletedOn'; Expression = {(Get-Date)}}, FullName
    $_ | Remove-Item -WhatIf
} 

# output on screen
$deleted | Format-Table -AutoSize

# output to csv file
$deleted | Export-Csv -Path 'C:\RemovedFiles.csv' -NoTypeInformation

如果您对屏幕上显示的结果满意,请移除 -WhatIf 安全开关。

这行得通吗?

$targetFolder = "D:" 
$fileList = "C:\DeleteList.txt" 
$Files = Get-ChildItem -Path "$targetFolder" -Recurse -Include @(Get-Content $fileList)

# Once you have the desires files stored in the $Files variable, then run a Foreach loop. 

$Obj = @() # create an array called $Obj
Foreach ($File in $Files)
{
    # store info in hash table
    $hash = @{
        DateTime = (get-date)
        fileName = $File.name
        fullpath = $File.fullname
    }
    Write-Host "deleting file $($file.name)" -for cyan
    Remove-Item $File.fullname # *** BE VERY CAREFUL!!!***

    # record information in an array called $Obj
    $Obj += New-Object psobject -Property $hash
}

$Obj | select fileName, DateTime | Export-csv C:\...