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?


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]
  • $items.Property -match '^OPEN' -replace '\D' returns all property names that start with OPEN and removes all non-digit characters from them (-replace '\D').

  • [int[]] converts the resulting "number strings" to actual numbers ([int]); note that casting '' or $null to [int] in PowerShell yields 0.

  • Sort-Object sorts these numbers, and [-1] grabs the last number from the resulting array, i.e., the highest number.


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]