-1

Given a uninstallString of "C:\ProgramData\Package Cache\{56e11d69-7cc9-40a5-a4f9-8f6190c4d84d}\VC_redist.x86.exe" /uninstall I can successfully extract the quoted text with ([Regex]::Match($uninstallString, '^\".*\"').Value). however, if I test to see if the string has the required /uninstall bit, then try to extract the quoted bit, like this...

if ([Regex]::Match($uninstallString, '^\".*\" +/uninstall').Succes) {
    ([Regex]::Match($uninstallString, '^\".*\"').Value)
}

Instead of the value being the full string, it's only returning "C:\ProgramData\Package. Now, My understanding is that . is everything but a line break, so it should be OK with the space. But, if I replace the space with an underscore in the string it works as expected, so it's definitely the space causing the issue. Also, I am confused why it works outside of the If, but not inside. I was under the impression that using [Regex]::Match() creates individual objects with each use, that wouldn't interact with each other, but here it seems they are.

Gordon
  • 6,257
  • 6
  • 36
  • 89
  • FYI, you don't need to escape quotes in regex. They don't have special meaning. Also, you should be using `[Regex]::IsMatch` – Maximilian Burszley Aug 19 '18 at 19:52
  • Unable to reproduce this, is this the actual code you're using? (there's a typo in your example btw, it's `Success`, not `Succes`) – Mathias R. Jessen Aug 19 '18 at 19:52
  • As a best-practice, I'd suggest using the `-match` comparison operator and the `$matches` automatic variable. – Maximilian Burszley Aug 19 '18 at 19:53
  • @TheIncorrigible1 I have been using -match, but I find needing multiple lines to extract one bit of data "annoys" me. Curious what the reason for -match being best practice is? That said, the named captures approach Theo mentions is really interesting. Good stuff to learn! – Gordon Aug 19 '18 at 20:49

1 Answers1

0

Since you want to see if the quoted string (path) is found AND if it contains a switch '/uninstall' or not, I'd do something like this:

$uninstallString = '"C:\ProgramData\Package Cache\{56e11d69-7cc9-40a5-a4f9-8f6190c4d84d}\VC_redist.x86.exe"'

if ($uninstallString -match '^(?<path>".*")(?:\s+(?<switch>/uninstall))?') {
    $uninstallPath   = $matches['path']    # at least the path (quoted string) is found
    $uninstallSwitch = $matches['switch']  # if '/uninstall' switch is not present, this will result in $null
}
Theo
  • 57,719
  • 8
  • 24
  • 41