regex - 重命名文件时使用Move-Item,并使用正则表达式 “cleaning”文件名

标签 regex powershell powershell-2.0

我正在使用脚本将文件从一个目录移动到另一个目录。它还通过一些RegEx工作剥离了一些文本。但是,尽管我的脚本比较短,但我认为我仍然可以做得更好。以下是我的示例脚本。

$Source = "C:\temp\test\source"
$Dest = "C:\temp\test\dest"

get-childitem $Source\*.* | rename-item -newname {$_.name -replace '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}IP\.',''} -WhatIf
move-item $Source\*.* $Dest -WhatIf

现在,这可以工作,但是,正如您所看到的,这是两行,我很确定它可以在一行中完成。我认为我从move-item命令中“赚不到我的钱”。我将如何完成此任务而不必执行单独的rename-item命令?如果您需要更多信息,请告诉我,我会解决的。我是PS和RegEx的新手。我处理批处理文件更多,但我认为它不能处理RegEx。这就是为什么我尝试PS。

最佳答案

您可以在Move-Item cmdlet的目标参数上使用正则表达式替换。那应该为您完成工作。调整您的示例:

$Source = "C:\temp\test\source"
$Dest = "C:\temp\test\dest"

get-childitem $Source | Foreach-Object {
  Move-Item -Path $_.FullName -Destination "$Dest\$($_.name -replace '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}IP\.','')" -WhatIf
}

关于regex - 重命名文件时使用Move-Item,并使用正则表达式 “cleaning”文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9843926/

相关文章:

regex - 为什么用。*正则表达式有两个匹配项?

javascript - 这个奇怪的 JavaScript 素数检查函数是如何工作的?

powershell - 将变量输出到文本文件

c# - 从 C# 运行 Powershell 会出现错误 : `running scripts is disabled on this system`

powershell - 当我已经定义了变量时出现意外的 token 错误

.net - Microsoft.SharePoint.PowerShell Snapin : Incorrect Windows PowerShell version 3. 0. 当前控制台支持 Window PowerShell 版本 2.0

带有 "[^a-zA-Z0-9]+"的 Java String.split 仍然将空格显示为一个单词

java - 从文本中提取特定单词

json - 在Powershell或VBS中翻译的CURL命令

powershell - 使用Add-Member从数组创建对象