We help IT Professionals succeed at work.

Powershell Script - v3.0 - Assistance

sj77
sj77 asked
on
120 Views
Last Modified: 2018-01-17
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

Comment
Watch Question

CERTIFIED EXPERT
Top Expert 2014

Commented:
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

CERTIFIED EXPERT
Most Valuable Expert 2019
Most Valuable Expert 2018
Commented:
This problem has been solved!
(Unlock this solution with a 7-day Free Trial)
UNLOCK SOLUTION

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions