jemiss
jemiss

Reputation: 1

Powershell IF ELSE will not run ELSE statement

I have the following code that I need to use to switch windows 7 themes between standard and high contrast. The IF runs fine but it will not run the ELSE condition, can someone please point out the error of my ways?

IF     ((Get-ItemProperty -path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Themes").CurrentTheme = "%SystemRoot%\resources\Ease of Access Themes\hcblack.theme") 
       {
       C:\scripts\Themetool.exe changetheme "c:\Windows\resources\Themes\MyTheme.theme"
       } 
ELSE   {
       C:\scripts\Themetool.exe changetheme "C:\Windows\resources\Ease of Access Themes\hcblack.theme"
       }

Upvotes: 0

Views: 120

Answers (1)

Stefan
Stefan

Reputation: 14880

You are assigning the current theme in the registry.

You need to use -eq for equality comparison. = is the assign operator in powershell.

List of powershell operators

What happens in detail is that your code is first assigning the value .../hcblack.theme to CurrentTheme and then uses this value for the boolean condition in the if statement. PowerShell treats non empty strings as $true. You can try this yourself: !!"" -eq $false. That's why the if part is matched.

What you are doing could be written as:

$prop = Get-ItemProperty -path HKCU:\Software\Microsoft\Windows\CurrentVersion\Themes"
$prop.CurrentTheme = "%SystemRoot%\resources\Ease of Access Themes\hcblack.theme"
if ($prop.CurrentTheme) { ... }

What you should do:

if ((Get-ItemProperty -path "<path>").CurrentTheme -eq "<value>") { ... } 

Upvotes: 5

Related Questions