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
1to the highest index to date:$items.Property -match '^OPEN' -replace '\D'returns all property names that start withOPENand removes all non-digit characters from them (-replace '\D').[int[]]converts the resulting "number strings" to actual numbers ([int]); note that casting''or$nullto[int]in PowerShell yields0.Sort-Objectsorts 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-Objectcmdlet.If you want to avoid the pipeline for performance reasons: