【问题标题】:How can I get the time and date my PowerShell script deletes a file如何获取 PowerShell 脚本删除文件的时间和日期
【发布时间】:2021-08-19 11:41:22
【问题描述】:

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

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

感谢您的帮助。

【问题讨论】:

  • 嗯,你可以把它通过管道传递给Foreach-Object,然后把Remove-Item扔进去,然后你就可以运行Get-Date之类的东西了?
  • 感谢您的回复@AbrahamZinala 您能举个例子吗?
  • 见@Theos 回答

标签: powershell date time


【解决方案1】:

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

然后可以将此输出保存为结构化 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 安全开关。

【讨论】:

    【解决方案2】:

    这行得通吗?

    $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:\...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-12
      • 1970-01-01
      • 2022-10-04
      • 1970-01-01
      相关资源
      最近更新 更多