确定并获取目录名称中的数字,然后在表达式中使用该数字

时间:2019-03-11 18:44:25

标签: powershell scripting

我需要做的是创建一个变量,该变量可以执行目录的ls,找到具有特定命名约定的目录,确定这些目录中的最高编号(每个目录都以{{结尾1}}),然后将该数字加1以创建下一个目录。

例如:

_#输出:

c:\ABC
c:\foo1
c:\foo2

我需要创建ls c:\,因为c:\foo3是当前最高的。因此,我需要确定最高目录是什么,然后使用下一个递增编号创建一个新目录。

我完成了所有这些工作,但我什么也无法工作。

2 个答案:

答案 0 :(得分:0)

$nextIndex = 1 + (
  (Get-ChildItem -Directory C:\foo*[0-9]).Name -replace '^.*\D' |
    Measure-Object -Maximum
).Maximum

New-Item -Type Directory C:\foo${nextIndex}
  • (Get-ChildItem -Directory C:\foo*[0-9]).Name返回C:\中所有目录的名称,这些目录的名称以foo开头并以(至少)一位数字结尾。

  • -replace '^.*\D'会删除每个名称中末尾的数字。

  • Measure-Object -Maximum然后确定所得的仅数字字符串中的最大值(PowerShell在确定最大值时会自动将字符串转换为数字)。

  • 因此,
  • 1 + (...).Maximum返回目录名称中当前嵌入的最高数字,该数字以1递增。

答案 1 :(得分:0)

这是我的尝试。它可能不像mklement0的答案那么简洁,但我认为它会做您想要的。

它会找到在给定路径(1级)内具有序列号的所有文件夹,并创建具有相同名称但尾随编号更高的新文件夹。

$path = 'C:\'                                                                           #'# (dummy comment to fix broken syntax highlighting)
Get-ChildItem -Path $path -Directory | 
    Where-Object { $_.Name -match '\d+$' } |               # find only folders with a name that ends in a number
    Group-Object -Property { $_.Name -replace '\d+$'} |    # group these folders by their name without the trailing number
    ForEach-Object {                                       # go through all the groups
        $baseName  = $_.Name                               # the group name is the base name for the new folder

        # get the name of the folder in the group with the highest number
        # create a new folder with the same base name and the next sequence number
        $lastUsed  = ($_.Group | Sort-Object {[int]($_.Name -replace $baseName)} -Descending | Select-Object -First 1).Name
        $nextIndex = [int]([regex]'\d+$').Match($lastUsed).Value + 1
        $newFolder = Join-Path -Path $path -ChildPath ('{0}{1}' -f $baseName, $nextIndex)

        Write-Host "Creating directory '$newFolder'"
        New-Item -Path $newFolder -ItemType Directory | Out-Null
    }

因此,如果您的根路径中包含以下文件夹:

123ABC_1
bar1
foo1
foo2

结果将是:

123ABC_1
123ABC_2
bar1
bar2
foo1
foo2
foo3