gpt4 book ai didi

powershell - 使用Windows Powershell批量重命名

转载 作者:行者123 更新时间:2023-12-02 23:50:15 38 4
gpt4 key购买 nike

我正忙着Windows Powershell脚本来批量重命名带有ID的一堆文件夹,这工作得很好。我的问题是,当我的所有文件都被重命名时,如何添加验证以确保所有ID是唯一的。这是代码:

    param(    
[Parameter(Mandatory=$true)]
[int]$idx
)

Get-ChildItem *.sql | Foreach-Object {
$iPrefix = ('{0:d5}' -f $idx)
$path = (Split-Path -Path($_))
$filename = (Split-Path -Path($_) -Leaf) -replace "\[|\]",""
#%{ write-host $path}
%{ write-host $filename}

if(!$filename.StartsWith("script","CurrentCultureIgnoreCase"))
{
#%{ write-host "Script$iPrefix - $filename"}
Rename-Item -LiteralPath(($_)) -NewName("Script$iPrefix - $filename")
++$idx
%{ write-host "Renamed: " + $filename}
}
}
这是我要避免的屏幕截图:
Renamed Folders
如您所见, Script02185重复了两次,因为脚本是在两个不同的时间运行的。如何确保数字保持唯一?

最佳答案

试试这个。

$files = Get-ChildItem . -Filter *.sql

$prefixedFiles, $unprefixedFiles = $files.Where({ $_.Name -match "^Script\d{5} - " }, 'split')

$usedIDs = [int[]]$prefixedFiles.Name.Substring(6, 5)
$unusedIDs = [System.Collections.Generic.HashSet[int]](1..99999)
$unusedIDs.ExceptWith($usedIDs)

$enumerator = $unusedIDs.GetEnumerator()

$unprefixedFiles | Rename-Item -NewName {

if (!$enumerator.MoveNext()) { throw "`nThere are no unused IDs." }
"Script{0:D5} - {1}" -f $enumerator.Current, ($_.Name -replace '\[|\]')

} -ErrorAction Stop -PassThru

关于powershell - 使用Windows Powershell批量重命名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60903803/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com