Powershell Script - v3.0 - Assistance

sj77 used Ask the Experts™
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

Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2014

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

Most Valuable Expert 2018
Distinguished Expert 2018
This will test and create both the key and the new value:
$Key = "HKCU:\SOFTWARE\Progressive Automotive Systems\R.O. Writer"
$Name = 'DataFile'
$Value = "C:\Temp\test.txt"

If (Test-Path -Path $Key) {
	"Key '$Key' found." | Write-Host
} Else {
	"Key '$Key' not found, will create ..." | Write-Host
	New-Item -Path $Key -Force | Out-Null
$DataFile = Get-ItemProperty -Path $Key -ErrorAction SilentlyContinue | Select-Object -ExpandProperty $Name
If ([string]::IsNullOrEmpty($DataFile)) {
	"Registry value '$($Name)' not found, will create and set to '$($Value)' ..." | Write-Host
	New-ItemProperty -Path $Key -Name $Name -Value $Value -Force | Out-Null
	$DataFile = $Value
} Else {
	"Found registry value '$($Name): '$($DataFile)'" | Write-Host
"DataFile: '$($DataFile)'" | Write-Host

Open in new window

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial