David
David

Reputation: 33

Powershell and regex variables

I am having issues with regex in powershell. I want it to read the file and set a variable with a counter next to it to the value of the location. the number afterwards is how long it takes for the program to open.

If you have a better idea for this, please let me know.

here's the section that isn't working:

$count = 1
Get-Content programs.txt | ForEach-Object{
    Set-Variable -Name raw_program -Value $_    
    if ($raw_program -match '.+?(?=,)'){
        Set-Variable -Name $program_$count -Value $matches[1]
        write-host "Result : $program_$count"
        $count += 1
    }
}

and programs.txt:

C:\Program Files (x86)\Telephony\CTI\bin\desktop.exe,7
C:\Program Files (x86)\Cisco Systems\Cisco IP Communicator\communicatork9.exe,6
C:\Program Files\Microsoft Office 15\root\office15\OUTLOOK.EXE,7
~\AppData\Roaming\Microsoft\Internet Explorer\Quick Launch\User Pinned\StartMenu\CaseTemplateWPF,9
C:\Program Files (x86)\Google\Chrome\Application\chrome.exe,3
C:\Program Files (x86)\Internet Explorer\iexplore.exe,6

Upvotes: 2

Views: 364

Answers (1)

briantist
briantist

Reputation: 47792

Your file is essentially a CSV with no headers, so why not treat it as such?

$programs = Import-Csv -Path programs.txt -Header Program,ProgramCount

Now $programs is an array of objects, each with a .Program property and .ProgramCount property.

Upvotes: 3

Related Questions