Home > OS >  Variable after select string does not show any value
Variable after select string does not show any value

Time:09-23

I am trying to perform a regex check on a macos log file called systemextensions.txt. The content of the file, as an example, is the following:

2 extension(s) 

--- com.apple.system_extension.endpoint_security enabled active teamID bundleID (version) name [state] 

GT8P3H7SPW com.mcafee.CMF.networkextension (10.7.6/1) McAfee Network Extension [terminated waiting to uninstall on reboot]

D3U2N4A6J7 com.protection.agent (02.00.07.1001/1.5.0) com.protection.agent [activated enabled]

What I am trying, after checking that the file size is greater than 0, is to select the extension(s) line , extract the numerical value from it and see if it is greater than 0. In case it is not, I will show a message that no system extensions have been found, and if it is, I try to get the value of those that are enabled. The problem is that when with the select-string I try to get the numeric value in a variable, it does not return anything, although the line without variable does.

If ($systemext.Length -gt 0)
{
    $numext = Select-String $systemext.FullName -Pattern 'extension(s)' -SimpleMatch | Select-String -Pattern '\d'
    If ($numext.Matches.value -eq 0) {Write-host = "No system extensions found"}
    else {$extenabled = Select-String $systemext.FullName -Pattern 'activated enabled'}
}

I have tried with the following lines (modifying the subsequent if) and the variables turn out to be empty:

1-.

$numext = Select-String $systemext.FullName -Pattern 'extension(s)' -SimpleMatch | Select-String -Pattern '\d' | foreach {$_.Matches.Value}

and 2-.

changing $numext to

$numext = Select-String $systemext.FullName -Pattern 'extension(s)' -SimpleMatch

and then :

$test = ($numext | Select-String -Pattern '\d').Matches.Value

CodePudding user response:

Given the file content you mention, this should get you the number from the 2 extension(s) line:

(Select-String -Path $systemext.FullName -Pattern '^(?:\d ) (?=extension\(s\))').Matches.Groups[0].Value

In your example, it should simply output: 2

If there is no match at all (e.g. the line is missing or changed format), then you'll likely get an error when accessing Groups[0], so you might want to split this single line into multiple steps to check it worked before trying to access the result.

  • Related