Avatar of Isaiah Melendez
Isaiah Melendez
 asked on

Powershell Script - v3.0 - Assistance

Hello experts,

I am trying to build a conditional statement that does if-else in powershell.

What I want it to do is query a registry path, if it exists print out do nothing

else, create the registry path.

This is what I have...

 $ChkFile = (Get-ItemProperty "HKCU:\SOFTWARE\Progressive Automotive Systems\R.O. Writer") | Select-Object -ExpandProperty DataFile
$FileExists = Test-Path $ChkFile 
If ($FileExists -eq $True) {
Write-Host "This regsitry key exists"
}
else {Write-Host "Hello, World"} 

Open in new window

Powershell

Avatar of undefined
Last Comment
oBdA

8/22/2022 - Mon
footech

For the registry, Test-Path can only be used for keys, not values.  So you could test for the existence of the key "HKCU:\SOFTWARE\Progressive Automotive Systems\R.O. Writer" using the cmdlet, but not any values in the key location.

One way to handle testing for a registry value is to detect the error from Get-ItemProperty.
try {
    $ChkFile = Get-ItemProperty "HKCU:\SOFTWARE\Progressive Automotive Systems\R.O. Writer" -Name "DataFile" -ErrorAction Stop | Select-Object -ExpandProperty DataFile
    Write-Host "This registry value exists"
}
catch {
    "Registry path doesn't exist"
}

Open in new window

ASKER CERTIFIED SOLUTION
oBdA

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Your help has saved me hundreds of hours of internet surfing.
fblack61