powershell - 用不同的名称重命名多个文件

标签 powershell rename-item-cmdlet

我绝不是一名程序员,并且对使用 powershell 是全新的,但我的任务是为我们 FTP 的日常文件设置一些批量导出过程。我需要想出一个脚本来更改文件名并将它们在同一目录中更改为新名称;

示例:文件将如下所示(YYYYMMDD 将是变化的变量)

YYYYMMDD_Share_Support.txt
YYYYMMDD_Person_Support.txt

我们需要将它们从上面剥离以:

Share.txt
Person.txt

等等等等。

我已经找到了使这项工作起作用的方法,但仅在需要的基础上一次使用一个具有特定名称的文件,而不是每天都会更改的名称。

到目前为止,我正在使用:

Get-ChildItem -Filter *.txt

Dir | %{Rename-Item $_ -NewName ("NEWFILENAME.txt" -f $nr++)}

最佳答案

您可以使用正则表达式 -replace管道绑定(bind)脚本 block 内的运算符:

$files = Get-ChildItem -filter *.txt 
$files |Rename-Item -NewName { $_.Name -replace '^\d{8}_(.*)_Support\.txt$', '$1.txt' }

suggested by TheIncorrigible1 ,如果你知道你需要的词的相对位置,你也可以使用-split :
$files |Rename-Item -NewName {'{0}.txt' -f ($_.Name -split '_')[-2]}  # grab 2nd last word

关于powershell - 用不同的名称重命名多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58939007/

相关文章:

powershell - 为 Node.js/PHP 构建 Windows Azure PowerShell CmdLet 时出现问题

c# - 根据标题行将文本文件拆分为多个文件

powershell - 在 powershell 中使用 new-guid 重命名每个文件

powershell - 使用 PowerShell 将前导零添加到文件名字符串

PowerShell:使用 $_.FullName.Replace 重命名多个文件夹

Powershell 检查 IIS 中是否存在 MIME

linux - 计算PowerShell中的字符,单词和行数

powershell - 在powershell中,如何使用Rename-Item同时输出新旧文件名?

powershell - 如何使用 PowerShell 使应用程序静音

powershell -++ 变量上的运算符未按 ScriptBlock 中的预期更改