r/PowerShell • • 5d ago

Question RegEx help...

I have never been able to wrap my head around regex... I have no idea why... anyways... I'm just trying to get the string between 2 braces (curly brackets). Here's what I've mangled together googling up... One of the many regex checking tools online said this should work but.. it doesn't

$uninstallString = (Get-ChildItem -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall | Get-ItemProperty | Where-Object { $_.DisplayName -like "*jdk*" }).UninstalLString$uninstallString = (Get-ChildItem -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall | Get-ItemProperty | Where-Object { $_.DisplayName -like "*jdk*" }).UninstalLString
$pattern = '(?<={).+?(?=})'
[Regex]::($uninstallString,$pattern).Value

<#
$uninstallString outputs the below
MsiExec.exe /I{370E1F16-ED05-4958-A820-78CD32DD70D8}
#>

The above code actually outputs nothing...

My head is so frazzled I'm not sure where to begin with it

Any help, or a point in the right direction would be appreciated.

19 Upvotes

43 comments sorted by

26

u/SysAdminDennyBob 5d ago edited 5d ago

If you are trying to uninstall multiple flavors of Java with powershell I highly suggest you not reinvent the wheel here. You can do about four tiny lines of code and remove 483 different JREs and JDKs if you take a peek at the Powershell Application Deployment Toolkit. It is amazing for this task.

PSAppDeployToolkit

edit: also Regex LOL

5

u/anonymousITCoward 5d ago

While I'm not trying to reinvent the wheel here I do work for some cheep asses, and have a pretty shitty RMM ... tried to uninstall from there but all it did was hide it from the applist, and in some cases it just deleted the registry entry...

I'll take a look at appdeploy tho thanks...

8

u/SysAdminDennyBob 5d ago

The toolkit is completely free. I used to clean out a huge swath of probably 50+ unique Java MSI installs. The thing with Java is that you can have 6 flavors of it installed on one device, they all sit side-by-side.

Uninstall-ADTApplication · PSAppDeployToolkit

These 4 lines will rip out pretty much 20 years of Oracle Java installs, these strings likely need to be modified, it's been four years since I gutted Oracle out of this environment.

Uninstall-ADTApplication -Name 'Java 8 Update'

Uninstall-ADTApplication -Name 'Java SE Development Kit'

Uninstall-ADTApplication -Name 'Java(TM) 6'

Uninstall-ADTApplication -Name 'Java(TM) SE Development Kit'

1

u/sammavet 4d ago

Really nice little tool I've used a few times.

1

u/Schmatter_Raphiqui 3d ago

how does that handle the portable zip builds of the JDK that dont actually register an msi uninstall string in HKLM?

1

u/SysAdminDennyBob 3d ago

I am very familiar with the "file copy install" of java. You are correct that Java does not need an installer at all. This tool does nothing for that, I mean you could use it to detect the process but it has no way to report that. This script did the majority of the heavy lifting.

When we removed Oracle Java we had a wide approach. First was this removal script sent out to known installs from inventory. 2nd step was detecting the Java processes spawning and reporting that up to a central repository(SCCM Software Metering in our case). Third was a search of all file shares for the Oracle installers exe\msi. 4th step was blocking all of Oracle's URLs for Java downloads. After cleanup we kept in place the process detection based on the publisher from the exe's header. If it was Oracle, an incident got created in Service Now. We also had an intense messaging campaign with our Developers "Do NOT install Oracle java!!!". We had three incidents post cleanup. Those culminated in the developer's manager and VP having to visit the Chief Security Officer's suite for a conversation with our feisty ass Australian CSO(I really like that guy). Word got out very fast after that.

We also made available 8 different OpenJDK installers in our software deployment portal. For a while I had a fake Oracle java install in there that simply popped a dialog explaining the per-employee cost but my boss thought that was a bit over the top.

It took us a full year to clear Oracle Java from everything; it was a grind. But I saved us shy of a $400k dollars. Eat a dick Larry Ellison!

5

u/realslacker 5d ago edited 5d ago

If you know there is only one guid patten you can simplify by using [string]::Split...

$UninstallString.Split([char[]]'{}',3)[1]

This will do what you were originally trying to do:

[regex]::Match( $UninstallString, '(?<=\{)[^\}]+(?=\})' ).Value

3

u/BlackV 5d ago

You'd still need the { } if you want to use it with an uninstall

2

u/anonymousITCoward 5d ago

Thank you!!! that worked

1

u/BlackV 5d ago

Good as gold

2

u/realslacker 5d ago

If you want to include the brackets you can either cast to [guid] (which will include the brackets when casting to string) or use the regex patten "\{[^\}]+\}".

2

u/anonymousITCoward 5d ago

Hmmm I hadn't thought about using split, not sure why... I think my brain thought it the string might be different from version to version of the jdk's or some thing.

Thank you for that...

1

u/jimb2 5d ago edited 5d ago

+1 for split but I'm wondering what the [char[]] cast does here?

I would write

$uis.split('{}')[1]

1

u/realslacker 5d ago

That would split a string like "this{}that", but not "this{or}that". The char cast converts the string to a char array and then split will split on either char.

2

u/jimb2 5d ago

In PS 5.1 I get

$uis = 'MsiExec.exe /I{370E1F16-ED05-4958-A820-78CD32DD70D8}'
$uis.split('{}')[1]

370E1F16-ED05-4958-A820-78CD32DD70D8

8

u/BrettStah 5d ago

These days for regex help, I just throw my question to an LLM. They understand it really well!

4

u/anonymousITCoward 5d ago

I'm not a fan of LLM's I know I could just say 'Hey GPT do this for me' and it does it... but I'd rather try to learn it... TBH its pretty much a futile action, this is the second time I've tried regex in 8 years... last time Google did me solid, this time I'm burnt out and have to pee really badly =\

8

u/BrettStah 5d ago

I understand but… imagine trying to learn Portuguese because you have to learn how to say a couple of sentences every 8 years! 😀

1

u/anonymousITCoward 5d ago

I know the feeling, I need to know a few words in Japanese and Korean... In stead of learning the language, I memorized the phrases

3

u/BlackV 5d ago edited 5d ago

You are trying to do too much on 1 command line, break it down to bits first, and use your properties rather than flat objects

that is the best way to understand it

also you dont need the Get-ChildItem on top of the Get-ItemProperty as it also supports the -path parameter

When you are building it I'd do the following

$UninstallPaths = @(
    'HKLM:\Software\wow6432node\microsoft\Windows\Currentversion\uninstall\*'
    'HKLM:\Software\microsoft\Windows\Currentversion\uninstall\*'
)
$UnunstallPath = Get-ItemProperty -Path $UninstallPaths

Get all your keys first, note I am looking at the 64bit key AND the 32bit Key (you are not), this can be especially painful via an RMM tools that might run as a 32bit process (I've also ignored current user)

then you can filter

$UnunstallPath | Where-Object displayname -match 'jdk'

what does that return?

or build a custom object for cleaner validation maybe

$UninstallKeys = $UnunstallPath | ForEach-Object {
    [PSCustomObject]@{
        Parent          = $_.PSChildname
        DisplayName     = $_.displayname
        Publisher       = $_.Publisher
        DisplayVersion  = $_.DisplayVersion
        UninstallString = $_.Uninstallstring
    }
}
$UninstallKeys

Filtering

$Singlejdk = $UnunstallPath | Where-Object displayname -Match 'jdk'
$Singlejdk 

Is it a single object or multiple?

Then depending on how complex you want to go

$UninstallGuid = ($Singlejdk.UninstallString -split 'x')[-1]
$UninstallGuid = ($Singlejdk.UninstallString -split 'i')[-1]

$pattern = '\{.+?\}'
$UninstallGuid = [regex]::Match($Singlejdk.Uninstallstring, $pattern ).Value

&msiexec /x $UninstallGuid /qb ALLUSERS=1

putting it all to variables let you test over and over to get it how you want

Also note the parent path should be the same uninstall guid as the installer if its a MSI install, which could save all your string manipulation (I think i've used that when bad apps dont publish the uninstall string)

2

u/anonymousITCoward 5d ago

You are trying to do too much on 1 command line, break it down to bits first, and use your properties rather than flat objects

I think you once told me that just because I can do it in one line, doesn't mean I should lol.

I do that a lot because I don't want to have to define 4 variables unless i have to. I think I'm going to build a new thing from what you got it seems to run faster than my spaghetti at the wall technique

2

u/BlackV 5d ago

I think you once told me that just because I can do it in one line, doesn't mean I should lol.

Ha have I, very possible

I think 1 liners are fine sometimes, but when building and iterating, never, when creating a reusable script, mostly never

2

u/PinchesTheCrab 5d ago

I don't think regex is the path of least resistance here. Does this work?

$appList = Get-ChildItem -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall -Recurse -PipelineVariable item | 
    Get-itemProperty | select-object DisplayName, UninstallString, @{ n = 'ID'; e = { $item.PSChildName -replace '{|}' } }

$appList | where-object { $_.DisplayName -match 'jdk' }

For a regex approach there's a ton of different ways you could do it, here's two:

'MsiExec.exe /X{D5FC86EF-1345-42F1-8C61-EE5BC9ECDED1}' -replace '.*{|}.*'
'MsiExec.exe /X{D5FC86EF-1345-42F1-8C61-EE5BC9ECDED1}' -replace '.+{(.*)}','$1'

2

u/anonymousITCoward 5d ago

It's not, i was reminded of replace and split... regex is just the form of punishment I chose for myself today.

12

u/crypticsage 5d ago

regex101.com

Has a section to add test strings
Provides info what each entry does.

2

u/root-node 4d ago

I actually prefer https://www.debuggex.com/ as it gives a visual representation of the regex

1

u/Goldarr85 5d ago

Came here to say this. That site is super helpful.

1

u/sysiphean 5d ago

Regexr.com as well. Each has strengths and weaknesses.

1

u/the_lazy_sysadmin 5d ago

so, the thing with pulling the 'uninstall string' from the registry, is sometimes it will be thrown in there with the /I switch listed, and not the /x switch (which is for uninstalling with msiexec). The entries placed in there are whatever the devs of whatever application decided to throw in there. Another example would be some Dell bloatware, which will often have a quiet uninstall string listed in the registry, conveniently omits a 'no reboot' option, which does in fact exist, if you look up Dell's documentation and test it.

What you can do instead, for msi packages, is pull the LocalPackage property. You can feed that into a variable, and slap that in a line calling msiexec.exe /x $variablename, along with whatever msiexec.exe options you'd want.

1

u/anonymousITCoward 5d ago

I thought the bit between the { } was the GUID and I could run that with the /x switch

1

u/BlackV 5d ago edited 5d ago

As far as I'm aware msiexec /x wants the whole thing

MsiExec.exe /x {DE540882-68F6-4A5E-888D-7E7902BB4CE7}

have a look at all of the existing uninstall values, they should confirm that for you

for example

Microsoft Visual C++ 2013 x64 Minimum Runtime - 12.0.40664                MsiExec.exe /X{53CF6934-A98D-3D84-9146-FC4EDF3D5641}
PowerShell 7-x64                                                          MsiExec.exe /X{5417B253-1A6D-4638-BC94-743A6EC2E6F4}
Microsoft Windows Desktop Runtime - 8.0.34 (x64)                          MsiExec.exe /X{5F1EBCB8-3C24-4C04-9BD7-4EB654E2D559}
Microsoft Visual C++ 2008 Redistributable - x64 9.0.30729.6161            MsiExec.exe /X{5FCE6D76-F5DC-37AB-B2B8-22AB8CEDB1D4}

2

u/anonymousITCoward 5d ago

Yeah, tested and confirmed it wants the whole kit-n-kaboodle.

1

u/BlackV 5d ago

yeah 100%, I only grab the guid for this exact reason

1

u/the_lazy_sysadmin 16h ago

iirc, that GUID can get changed up on you, if a piece of software has gone through some major updates since you last updated an uninstall script with a hard-coded GUID.

msiexec.exe, for uninstalling, will work with either the GUID or the localpackage path property found in the registry, or through a get-ciminstance win32_product command.

1

u/BlackV 16h ago

get-ciminstance win32_product

Obligatory Win32_product is evil

https://gregramsey.net/2012/02/20/win32_product-is-evil/

that's why I'd query the registry key for the guid and not hard code it (or the package manager cmdlets)

1

u/purplemonkeymad 5d ago

Have you actually assigned the result to a value? If I do:

[regex]::Matches('MsiExec.exe /I{370E1F16-ED05-4958-A820-78CD32DD70D8}','(?<={).+?(?=})').Value

It outputs the guid, so I think your regex does what you think. How are you handling the results?

1

u/anonymousITCoward 5d ago

Code to current looks like this

$uninstallString = (Get-ChildItem -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall | Get-ItemProperty | Where-Object { $_.DisplayName -like "*jdk*" }).UninstalLString
$pattern = '(?<=\{)[^\}]+(?=\})'
$guid = [Regex]::Match($uninstallString,$pattern).Value

Start-Process -FilePath "$env:SystemRoot\system32\msiexec.exe" -ArgumentList " /quiet /norestart /x $($guid)"

It doesn't work MSIEXEC can't find the package. =\

1

u/purplemonkeymad 5d ago

msiexec expects the package guid to include the braces, your guid does not include them:

Start-Process -FilePath "$env:SystemRoot\system32\msiexec.exe" -ArgumentList " /quiet /norestart /x {$($guid)}"

1

u/anonymousITCoward 5d ago

Yep u/BlackV pointed that out thanks for the response tho..

1

u/LowDark9328 5d ago

I like replace with a regex the matches the whole string "^....$" and named groups.

'MsiExec.exe /I{370E1F16-ED05-4958-A820-78CD32DD70D8}' -replace '^.*?{(?<guid>.+?)}.*$','${guid}'

1

u/Modify- 5d ago

Not sure about Java, but something like this works fairly well.

$LatestVersion = [System.Version]'1.1.0.0'

$Packages = Get-Package -name *Java* | Where-Object {[System.Version]$_.Version -lt $LatestVersion}

If ($Packages) 
{   
    Write-Output "Old Package found! Uninstall started."
    Foreach ($Package in $Packages)
    {
        $UninstallArguments = "/X $($Package.FastPackageReference) /qn"
        Start-Process MsiExec.exe -Wait -ArgumentList $UninstallArguments
    }
}

1

u/uptimefordays 5d ago edited 5d ago

Your regex is actually fine! The problem is the line calling it. [Regex]::(...) is missing the method name, so it should be:

[regex]::Match($uninstallString, $pattern).Value

Or the more PowerShell-y way, using -match. Keep the braces in the match, since msiexec /x needs them (thanks for testing that):

if ($uninstallString -match '\{[0-9A-Fa-f-]{36}\}') { $Matches[0] }

That said, you don't need to parse the string at all. For MSI installs, the registry key name under Uninstall is the product code, braces included, and Get-ItemProperty gives it to you as PSChildName:

$paths = @(
    'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall'
    'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall'
)

Get-ChildItem -Path $paths |
    Get-ItemProperty |
    Where-Object { $_.DisplayName -like '*jdk*' -and $_.WindowsInstaller -eq 1 } |
    Select-Object DisplayName, DisplayVersion, PSChildName

This also covers a few things that would bite you later:

  • More than one JDK installed. $uninstallString becomes an array, and the regex quietly returns only the first match. The pipeline above gives you one object per install.
  • 32-bit installs live under WOW6432Node.
  • Non-MSI installers. WindowsInstaller -eq 1 skips entries whose key name isn't a product code.
  • Vendor uninstall strings sometimes use /I (modify/repair) instead of /x, or leave out switches like no-reboot. Building the command yourself avoids both.

To uninstall, swap the Select-Object for:

ForEach-Object {
    $p = Start-Process msiexec.exe -ArgumentList "/x $($_.PSChildName) /qn /norestart" -Wait -PassThru
    '{0}: exit {1}' -f $_.DisplayName, $p.ExitCode   # 0 = success, 3010 = reboot needed, 1605 = not installed
}

Edit: fixed the -match example to keep the braces, and added the WindowsInstaller filter, /norestart, and exit codes.

-2

u/Incrediblecodeman 5d ago

Dude just ask ai wtf?

Typewriter ahh comment .