How to check for String inside Path variable ?

by chz013 at 2013-01-30 16:19:57

Hi All

We are trying to check the system Path variable if it contains JAVA_HOME.

$path = [Environment]::GetEnvironmentVariable("path", "machine")
$jdkPath = [environment]::GetEnvironmentVariable("JAVA_HOME", "machine")

if (! $path.Value.Contains($jdkPath))
{

}


We got the following error:
You cannot call a method on a null-valued expression.
At C:\software_installations\scripts\auto-install.ps1:56 char:27
+ if (! $path.Value.Contains <<<< ($jdkPath))
+ CategoryInfo : InvalidOperation: (Contains:String) , RuntimeE
xception
+ FullyQualifiedErrorId : InvokeMethodOnNull

How do we check for string of JAVA_HOME in PATH variable ? (eg checking for C:\jdk1.6 in Path’s C:\jdk\1.6;C:\Windows;…)

Thanks
by Klaas at 2013-01-31 00:29:16
Just look at the $path variable:
PS> $pathYou see a string?
PS> $path.valueWhat do you see? Probably nothing, because
PS> $path | Get-Membershows me no ‘value’ property.
Do the same with the $Jdkpath, I don’t seem to have one.

If they both are filled with what you expected, you can use the -match operator. "-Contains" searches for members of a collection, but $path is just one string.
PS> $path -match $jdkpathshould do it.
by nohandle at 2013-01-31 00:59:14
Replied to your previous thread: viewtopic.php?f=2&t=1139

[quote="Klaas"]If they both are filled with what you expected, you can use the -match operator. "-Contains" searches for members of a collection, but $path is just one string.
?
1
PS> $path -match $jdkpath
should do it.[/quote]
I doubt this will work properly, the match operator will try to interpret all the backshlashes and the next characters since it expects the string on the right to be a regular expression. Like should do the trick:
if ($env:java_home){ $env:path -like "$env:java_home" }else {$False}
Checking if the variable is set is important because otherwise you get false-positives when the variable does not exist.