Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Question
Monday, November 8, 2010 9:15 PM
gc C:\temp\running_servs.txt | Select-String -Pattern "MSS" -quiet
gc C:\temp\running_servs.txt | Select-String -Pattern $serv -quiet
gc = Get-Content
Running the first example I get back TRUE - as expected. The file contains two lines with 'MSSQL$SERV1' and 'MSSQL$SERV1' in it. I cannot get the second example to work - when I use a variable in the pattern search I always get FALSE, the value of $serv is also MSS. I have also tried this:
Select-String C:\temp\running_servs.txt -Pattern "MSS" -quiet
also to no avail. Is it possible to use a variable in the -Pattern?
MM
All replies (5)
Tuesday, November 9, 2010 3:39 PM âś…Answered
If "MSSQL$DEV" is the value of the variable you're using for the pattern match, I think that may be the problem.
The default pattern type in select-string is a regex, and $ is a reserved character in regex (eol) , that has to be escaped in the regex if you want to use it as a literal match.
Does it work if you add the -simplematch switch to your select-string?
gc C:\temp\running_servs.txt | Select-String -Pattern $serv -simplematch -quiet
[string](0..33|%{[char][int](46+("686552495351636652556262185355647068516270555358646562655775 0645570").substring(($_*2),2))})-replace " "
Monday, November 8, 2010 9:31 PM
Are you sure about the value of that variable? I just tested against a test file, and using a variable for the pattern match seems to work fine.
$serv
$serv.length
gc C:\temp\running_servs.txt | Select-String -Pattern "MSS" -quiet
gc C:\temp\running_servs.txt | Select-String -Pattern $serv -quiet
[string](0..33|%{[char][int](46+("686552495351636652556262185355647068516270555358646562655775 0645570").substring(($_*2),2))})-replace " "
Monday, November 8, 2010 10:57 PM
Yea, I do not repro this issue either:
PS C:\> 'MSSQL$SERV1','MSSQL$SERV1' | Out-File Test.txt
PS C:\> type .\Test.txt
MSSQL$SERV1
MSSQL$SERV1
PS C:\> gc .\Test.txt | select-string "MSS" -quiet
True
PS C:\> $serv = "MSS"
PS C:\> gc .\Test.txt | select-string $serv -quiet
True
Make double sure of the value of $serv, maybe it is an array and you didn't notice?
PS C:\> $serv,$serv.gettype()
MSS
IsPublic IsSerial Name BaseType
True True String System.Object
-Lincoln
Tuesday, November 9, 2010 3:16 PM
gettype returns the below - MSSQL$DEV is the value of the variable.
MSSQL$DEV
MemberType : Method
OverloadDefinitions : {type GetType()}
TypeNameOfValue : System.Management.Automation.PSMethod
Value : type GetType()
Name : GetType
IsInstance : True
Tuesday, November 9, 2010 3:29 PM
You need to include the trailing parens on gettype
$serv.gettype()
[string](0..33|%{[char][int](46+("686552495351636652556262185355647068516270555358646562655775 0645570").substring(($_*2),2))})-replace " "