Home > Blockchain >  Find a better way to get information from a string
Find a better way to get information from a string

Time:09-24

This command $GamCheck = invoke-command -ScriptBlock { C:\GAMADV-XTD3\gam.exe version checkrc} makes a string and inside that string are the current and latest version information.

GAMADV-XTD3 6.07.31 - https://github.com/taers232c/GAMADV-XTD3 - pyinstaller
Ross Scroggs <[email protected]>
Python 3.9.7 64-bit final
Windows 10 10.0.18363 SP0 Multiprocessor Free AMD64
Path: C:\GAMADV-XTD3
Config File: C:\GAMConfig\gam.cfg, Section: DEFAULT, customer_id: C047encoi, domain: sonos.com        
Version Check:
  Current: 6.07.31
   Latest: 6.07.31

I was getting the information like this

$current = $GamCheck.split(":")[20].Trim()
$latest = $GamCheck.split(":")[22].Trim()

recently this failed on different machines and I found that the number 20 and 22 in the lines above needed to be changed sometimes.

Is there a more reliable way to get the current and latest numbers only from that string ?

I need the latest number further down the script so I can download and install the update automatically.

$client = new-object System.Net.WebClient
$client.DownloadFile("https://github.com/taers232c/GAMADV-XTD3/releases/download/v$latest/gamadv-xtd3-$latest-windows-x86_64.msi", "C:\Temp\gamadv-xtd3-$latest-windows-x86_64.msi")
Start-Process -Filepath "C:\Temp\gamadv-xtd3-$latest-windows-x86_64.msi" -ArgumentList "/passive" -Wait | Wait-Process -Timeout 60
Remove-Item "C:\Temp\gamadv-xtd3-$latest-windows-x86_64.msi"

CodePudding user response:

A concise solution is to use a regex-based -replace operation:

# Simulate the input with a here-string that is
# split into individual lines, as output would be received
# from an external program.
$GameCheck = @'
GAMADV-XTD3 6.07.31 - https://github.com/taers232c/GAMADV-XTD3 - pyinstaller
Ross Scroggs <[email protected]>
Python 3.9.7 64-bit final
Windows 10 10.0.18363 SP0 Multiprocessor Free AMD64
Path: C:\GAMADV-XTD3
Config File: C:\GAMConfig\gam.cfg, Section: DEFAULT, customer_id: C047encoi, domain: sonos.com        
Version Check:
  Current: 6.07.31
   Latest: 6.07.32
'@ -split '\r?\n'

$regex = '(?s)^. \bCurrent: ([\d.] ). \bLatest: ([\d.] ).*$'

$currentVersion, $latestVersion = 
  -split (($GameCheck -join "`n") -replace $regex, '$1 $2')
  • The regex is designed to match the entire string and capture the substrings of interest via capture groups ((...)), which the substitution expression can reference by position as $1 and $2.

  • Thus, the two version numbers are effectively returned, separated by a space, which the unary form of -split splits into a 2-element array that is assigned to the 2 output variables by multi-assignment.

For a detailed explanation of the regex and the ability to experiment with it, see this regex101.com page.

  • Related