Powershell 将重命名项事件输出到日志文件

Powershell 将重命名项事件输出到日志文件,powershell,file-io,powershell-2.0,Powershell,File Io,Powershell 2.0,我尝试使用以下脚本记录文件重命名的相关数据。唯一的问题是日志文件包含由于尝试重命名时出现“拒绝访问”错误而未重命名的文件。我需要弄清楚如何只为成功重命名的文件创建日志条目,或者将失败的重命名通过管道传输到其他日志文件。如果可能的话,我还希望在日志文件的顶部列出重命名的文件总数(即“xxx文件已重命名”),我非常感谢您对使用powershell v2实现此功能的建议 $drivesArray = Get-PSDrive -PSProvider 'FileSystem' | select -

我尝试使用以下脚本记录文件重命名的相关数据。唯一的问题是日志文件包含由于尝试重命名时出现“拒绝访问”错误而未重命名的文件。我需要弄清楚如何只为成功重命名的文件创建日志条目,或者将失败的重命名通过管道传输到其他日志文件。如果可能的话,我还希望在日志文件的顶部列出重命名的文件总数(即“xxx文件已重命名”),我非常感谢您对使用powershell v2实现此功能的建议

    $drivesArray = Get-PSDrive -PSProvider 'FileSystem' | select -Expand Root 
foreach ($drive in $drivesArray) {
  Get-ChildItem $drive | Where-Object {
    $_.FullName -notlike "${Env:WinDir}*" -and
    $_.FullName -notlike "${Env:ProgramFiles}*"
  } | ForEach-Object {
    Get-ChildItem $_.FullName -Recurse -ErrorAction SilentlyContinue
  } | Where-Object {
    -not $_.PSIsContainer -and
    $_.Extension -notmatch '^\.(xxx|exe|html)$'
  } | ForEach-Object {
    $newName = $_.FullName + '.xxx';
    Rename-Item -Path $_.FullName -NewName  ($_.FullName + '.xxx')  -ErrorAction SilentlyContinue
    Add-Content c:\temp\renameLog.txt -Value $('{0} {1} {2} {3}' -f $(Get-Date),$_.fullname,$_.name,$newName )   
  }
}

这是一个例子,当然没有经过测试

$success = 0
$failed = 0

$drivesArray = Get-PSDrive -PSProvider 'FileSystem' | select -Expand Root 

foreach ($drive in $drivesArray) {
  Get-ChildItem $drive | Where-Object {
  $_.FullName -notlike "${Env:WinDir}*" -and
  $_.FullName -notlike "${Env:ProgramFiles}*"
  } | ForEach-Object {
Get-ChildItem $_.FullName -Recurse -ErrorAction SilentlyContinue
  } | Where-Object {
-not $_.PSIsContainer -and $_.Extension -notmatch '^\.(xxx|exe|html)$' -and $_.Name -notmatch '^renameLog.txt|^renameLog_failed.txt'
  } | ForEach-Object {
    try {
    $newName = $_.FullName + '.xxx';
    Rename-Item -Path $_.FullName -NewName  ($_.FullName + '.xxx')  -ErrorAction Stop 
    Add-Content c:\temp\renameLog.txt -Value $('{0} {1} {2} {3}' -f $(Get-Date),$_.fullname,$_.name,$newName ) 
    $success ++  
    } catch [exception] {
        Add-Content c:\temp\renameLog_failed.txt -Value $('{0} {1} {2} {3}' -f $(Get-Date),$_.fullname,$_.name,$newName )   
        $failed ++
        $error.Clear()
    }
  }
}

 Add-Content "c:\temp\renameLog.txt" -Value $("Total: " + $success)
 Add-Content "c:\temp\renameLog_failed.txt" -Value $("Total: " + $failed)

干得好!只需要将日志文件从重命名中排除,它就像一个符咒