Powershell脚本,用相同文件的前32个字符重命名文件夹中的文件



我正在尝试使用powershell重命名文件夹的多个子文件夹中的所有文件。这些文件包含一个32个字符长的字符串序列,然后是一个"-1"或"-2",我不再需要它了。所以我希望文件的新名称只有32个字符。

示例:

大文件夹//子文件夹1/abcabcabcabcabCabcabcabcab 1,abcabcabCabCabcabcab 2,abcabCabcab 3,/子文件夹2/abcabcabcabcabCabcabcabcab 1,abcabcabCabCabcabcab 2,abcabCabcabCabcab 3,。。等

他们需要:

大文件夹//子文件夹1/abcabcabcabcab,abcabcab,/子文件夹2/abcabcabcabcab,abcabcab,。。

到目前为止,我尝试的是:

$sourceDirectory = "C:UsersDesktopCustomerspowershellTestsScriptOutput"
$filesToBeRenamed = Get-ChildItem -Path $sourceDirectory -Recurse
Foreach($file in $filesToBeRenamed){
$fileName=$file.BaseName
$firstChars=$fileName.SubString(0,31)
$filePath=Join-Path -Path $sourceDirectory -ChildPath $xmlFile.Name
Rename-Item -NewName $firstChars
}

这并没有给出任何错误,但在示例中它只重命名了我的初始根文件夹(BigFolder(。

谢谢!

在循环中,重命名项目时无需尝试组合$filePath。此外,如果将文件重命名为仅包含前32个字符,则会忘记文件的扩展名。

您的代码可以简化为:

$sourceDirectory = "C:UsersDesktopCustomerspowershellTestsScriptOutput"
Get-ChildItem -Path $sourceDirectory -File -Recurse |
Where-Object { $_.BaseName -match 'w{32,}-d+$' } | 
Rename-Item -NewName {'{0}{1}' -f $_.BaseName.SubString(0,32), $_.Extension} -ErrorAction SilentlyContinue

Where-Object子句中的regex匹配确保您只搜索基名称在结束-之前至少有32个字符和一个或多个数字的文件。

在这里,您可能会尝试将文件重命名为已经存在的名称,为了不收到终止错误,我添加了-ErrorAction SilentlyContinue。现在,当由于具有该名称的文件已经存在而无法重命名时,代码只会跳过该文件。

Regex详细信息:

w          Match a single character that is a “word character” (letters, digits, etc.)
{32,}    Between 32 and unlimited times, as many times as possible, giving back as needed (greedy)
-           Match the character “-” literally
d          Match a single digit 0..9
+        Between one and unlimited times, as many times as possible, giving back as needed (greedy)
$           Assert position at the end of the string (or before the line break at the end of the string, if any)

最新更新