I want to check if PATH in windows server contains some string. If it doesn't I wish to add it to the PATH. I want to add this "CommonLib" folder. I try to do it immediately in IF clause:
> $CommonLib="C:\Program Files\Front\CommonLib"
> if (($env:Path -split ";").NotContains($CommonLib)) {Write-Host "executing the code"}
InvalidOperation: Method invocation failed because [System.String] does not contain a method named 'NotContains'.
Contains is recognized (I can do it probably by executing the code in ELSE clause) but NotContains isn't. How can I resolve this? Thanks!!!
CodePudding user response:
The else
branch is a solid option. It's simple to write and understand. Like so,
if (($env:Path -split ";").Contains($CommonLib)) {
Write-Host "$CommonLib is in path"
} else {
Write-Host "$CommonLib is NOT in path"
}
It's also possible to do the test and store the result in a variable. Logic operators like -not
can be used to invert its value. It's usually much more clear to test if something is something
than someting is not someting
. Like so,
$CLInPath = ($env:Path -split ";").Contains($CommonLib)
if(-not $CLInPath) {
Write-Host "$CommonLib is NOT in path"
}
This avoids if..else
branching, which is desired if the other branch doesn't do anything.
CodePudding user response:
You can use the not
operator with the Contains
function.
if (!($env:Path -split ";").Contains($CommonLib)) {Write-Host "executing the code"}
CodePudding user response:
The other answers here provide viable alternatives to your issue and arguably better approaches, but to answer your specific question, you need to use the -NotContains
operator as so:
if (($env:Path -split ";") -NotContains $CommonLib) {
Write-Host "executing the code"
}