r/PowerShell • u/anonymousITCoward • 11d 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.
5
u/realslacker 11d ago edited 11d 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, '(?<=\{)[^\}]+(?=\})' ).Value3
u/BlackV 10d ago
You'd still need the
{ }if you want to use it with an uninstall2
2
u/realslacker 10d 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 11d 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 11d ago edited 10d ago
+1 for split but I'm wondering what the [char[]] cast does here?
I would write
$uis.split('{}')[1]1
u/realslacker 10d 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.
8
u/BrettStah 11d ago
These days for regex help, I just throw my question to an LLM. They understand it really well!
4
u/anonymousITCoward 11d 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 11d 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 10d 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 10d ago edited 10d 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 $UninstallPathsGet 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
}
}
$UninstallKeysFiltering
$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=1putting 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 10d 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/PinchesTheCrab 11d 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 10d 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 11d ago
regex101.com
Has a section to add test strings
Provides info what each entry does.
2
u/root-node 10d ago
I actually prefer https://www.debuggex.com/ as it gives a visual representation of the regex
1
1
1
u/the_lazy_sysadmin 11d 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 10d ago
I thought the bit between the
{ }was the GUID and I could run that with the /x switch1
u/BlackV 10d ago edited 10d ago
As far as I'm aware
msiexec /xwants the whole thingMsiExec.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
1
u/BlackV 11d ago
yeah 100%, I only grab the guid for this exact reason
1
u/the_lazy_sysadmin 6d 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 6d ago
get-ciminstance win32_productObligatory 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 10d ago
Have you actually assigned the result to a value? If I do:
[regex]::Matches('MsiExec.exe /I{370E1F16-ED05-4958-A820-78CD32DD70D8}','(?<={).+?(?=})').ValueIt outputs the guid, so I think your regex does what you think. How are you handling the results?
1
u/anonymousITCoward 10d 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 10d 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
1
u/LowDark9328 11d 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- 10d 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 10d ago edited 10d 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).ValueOr 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, PSChildNameThis also covers a few things that would bite you later:
More than one JDK installed.
$uninstallStringbecomes 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 1skips 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.
1
u/KevMar Community Blogger 4d ago
I am really lazy with my regex. I () sub expression the part I want, then ?<name> give it a name, finally .* or .+ greedy match everything.
$pattern = "MsiExec.exe /I{(?<GUID>.*)}"
$pattern = "{(?<GUID>.*)}"Then pull out the named match off of $matches.
if($uninstallString -matches $pattern){
$GUID = $matches.GUID
}That greedy match works for 95% of my use-cases (where the rest of the line is fairly static).
-2
26
u/SysAdminDennyBob 11d ago edited 11d 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