Extracting string values from ps1 file [regex]

Hi everyone,

I’m trying to extract 3 strings from “Deploy-application.ps1” file, which is part of PowerSHell App Deployment Toolkit (PSADT), the file inside looks like this and I’m trying to retrieve values of “$appVendor”, "$appName " and “$appVersion”, to extract this information I’m using regex.
The regex, that I came up with, seems to work well on regex101, but it doesn’t work that well in PowerShell :slight_smile:

This is how my PowerShell code looks like (just for $appVendor ):

$InstallFile = Get-Content "C:\temp\Deploy-Application.ps1"
$AppVendorREGEX = "(?<=\[string]\`$appVendor = ')(.*)(?='')"
select-string -inputobject $InstallFile -Pattern $AppNameREGEX -AllMatches | ForEach-Object { $_.Matches } | ForEach-Object { $_.Value }

So the code extracts the correct value, but it doesn’t stop on the second single quote, but it continues to extract more text. It looks to me like the single quote is being ignored (I tried using two single quotes as an excape method).

In the code you shared you define the variable $AppVendorREGEX but you’re using the variable $AppNameREGEX. Then you’re looking for -AllMatches. If I got it right you only need the first appearance.
Despite I don’t understand why you’re trying to parse a ps1 file I’d use another approach here:

$InstallFile = 'C:\temp\Deploy-Application.ps1'

$NamePattern    = [REGEX]::Escape('[string]$appName = ')
$VersionPattern = [REGEX]::Escape('[string]$appVersion = ')
$VendorPattern  = [REGEX]::Escape('[string]$appVendor = ')

$VendorLine, $NameLine, $VersionLine = Select-String -Path $InstallFile -Pattern $VendorPattern, $NamePattern, $VersionPattern

$Vendor  = ($VendorLine.Line -split '=')[1].trim().trim("'")
$Name    = ($NameLine.Line -split '=')[1].trim().trim("'")
$Version = ($VersionLine.Line -split '=')[1].trim().trim("'")


Hi Olaf,

thank you very much for your help, you code does exactly what I need :slight_smile:
You are also right, I made a copy paste error, I should have used the “$AppVendorREGEX” variable in 2nd and 3rd line of the code, that I pasted in.

I’m trying to parse a PowerShell file, to try to automate partially an application creation process in Config Manager and also to learn PowerShell a bit more.

That’s a perfectly good reason. Keep on! :wink: :+1:t4: