Reputation: 3
I have a Powershell script that reads content from JSON file and adds registry values. My script works well if the key in the registry exists. How can I make it to create the key if it doesn't exist, and then insert a value to it?
Powershell:
$jsonFile = "c:\temp\story\test2.json"
$customObject = Get-Content $jsonFile | ConvertFrom-Json
$customObject.PSObject.Properties | ForEach-Object {
[void]( New-ItemProperty -LiteralPath $_.Value.path -Name $_.Value.name -Value $_.Value.value -PropertyType $_.Value.type -Force)
}
Json:
{
"reg1": {
"path": "HKLM:\\SOFTWARE\\Clients\\test",
"name": "test",
"value": "0000",
"type": "String"
},
"reg2": {
"path": "HKLM:\\SOFTWARE\\Clients\\test",
"name": "test2",
"value": "111",
"type": "String"
}
}
Upvotes: 0
Views: 1201
Reputation: 61013
You can use Test-Path
to test if the registry path exists or not.
Get-Content -Path 'c:\temp\story\test2.json' -Raw | ConvertFrom-Json | ForEach-Object {
foreach ($reg in $_.PSObject.Properties.value) {
if (!(Test-Path -Path $reg.path)) { $null = New-Item -Path $reg.path -Force }
$null = New-ItemProperty -Path $reg.path -Name $reg.name -Value $reg.value -PropertyType $reg.type -Force
}
}
Upvotes: 1