【问题标题】:Logging actions of my powershell into a file将我的 powershell 的操作记录到文件中
【发布时间】:2014-11-19 01:47:30
【问题描述】:

我实际上是在做一个脚本来将我的文件夹/文件名中的每个“o”替换为“0”

这是我的简单脚本:

Get-ChildItem -recurse |`
Where-Object { $_.name -match 'o' } |`
Rename-Item -NewName { $_name -replace 'o', '0' }

它正在工作,但现在我想登录到每个已更改的文件/文件夹的文件。 所以基本上我想添加一个函数来在重命名之前和之后写入我的文件名。

例如,对于“BEFORE name”,我尝试在 Where-Object 管道之后添加此命令:

Add-content $MylogFile 

它成功地记录了每个内部带有“o”但没有路径的文件。并且拥有 1000 多个没有路径的文件的日志是没有用的......

您是否有任何想法简单地记录每个已被脚本重命名的文件的前/后名称及其路径?

提前致谢! 问候,

【问题讨论】:

  • rename-item cmdlet 之后使用-passthru 开关

标签: powershell logging replace path rename


【解决方案1】:

您只需将原始搜索存储到一个变量中,然后对其进行迭代。以下应该做你想做的事:

如果您只想重命名文件:

$files = Get-ChildItem -recurse | Where-Object { $_.PSIscontainer -eq $false -and $_.name -match 'o' }
$files | % { 
  $newname = $_.name -replace 'o', '0'
  write-host "Before: $($_.fullname)"
  write-host "After: $newname"
  $_ | Rename-Item -NewName $newname
}

要重命名文件文件夹:

$files = Get-ChildItem -recurse | Where-Object { $_.PSIscontainer -eq $false -and $_.name -match 'o' }
$files | % { 
  $newname = $_.name -replace 'o', '0'
  write-host "Before: $($_.fullname)"
  write-host "After: $newname"
  $_ | Rename-Item -NewName $newname
}
$dirs = Get-ChildItem -recurse | Where-Object { $_.PSIscontainer -eq $true -and $_.name -match 'o' }
$dirs | % { 
  $newname = $_.name -replace 'o', '0'
  write-host "Dir Before: $($_.fullname)"
  write-host "Dir After: $newname"
  $_ | Rename-Item -NewName $newname
}

【讨论】:

  • 感谢您的快速回答,但此代码的问题仍然存在。我将它执行到我的测试文件夹中,该文件夹包含多个名为 o.txt 的文件(进入子文件夹,子子文件夹等。)每个文件的输出仍然是这样的:之前:o.txt 之后:0 .txt 没有路径,只有文件名。
  • 好的,我找到了方法!我将脚本中的这一行“之前:$($_.name)”替换为“之前:$($_.Fullname)”正如有人提议的那样,它有效!但是仍然存在一个问题,如果脚本尝试将文件重命名为他之前重命名的文件夹,它会说文件的路径不再存在(因为文件夹已重命名并且他正在使用它的旧名称路径)
  • 你想同时替换文件夹名称,还是只替换文件?
  • 两者。第二个选项很好,它运行良好,只是将“Write-Host”更改为“add-content $log”。非常感谢您的帮助!
  • 没问题,很高兴你把它整理好了。
猜你喜欢
  • 2018-03-13
  • 1970-01-01
  • 2021-11-23
  • 2014-07-24
  • 1970-01-01
  • 1970-01-01
  • 2016-06-06
  • 1970-01-01
  • 2020-06-06
相关资源
最近更新 更多