powershellwhile-loopregistrynew-item

Search Registry and create New-Item


I want to create a New-Item in the registry with a pre check what already exists.

This code

$items = get-item "HKCU:\SOFTWARE\Microsoft\Office\16.0\Excel\Options" 
$items.Property -match "OPEN"

returns the following

OPEN
OPEN1
OPEN2
OPEN3
OPEN4

Now I know I need to create a New-Item with the name OPEN5, but how do I count through this? Maybe with a While-Loop?


Solution

  • The most robust approach is to extract the embedded numbers, sort them numerically, and add 1 to the highest index to date:

    $nextNdx = 1 +
      ([int[]] ($items.Property -match '^OPEN' -replace '\D') | Sort-Object)[-1]
    

    The above is convenient, but not fast, due to use of the pipeline and the Sort-Object cmdlet.

    If you want to avoid the pipeline for performance reasons:

    $indices = [int[]] ($items.Property -match '^OPEN' -replace '\D')
    [Array]::Sort($indices) # sort in place
    $nextNdx = 1 + $indices[-1]