Parsing ImagePath paths from parameters

0

I have a powershell script that iterates through all the services listed under HKLM:\Systemn\ControlSet001\services\ looking for the ImagePath to see if it has any spaces but no quotes.

e.g.

C:\this is\very bad\but people\do it\anyways.exe

But, these may contain switches/parameters like:

C:\this is\very bad\but people\do it\anyways.exe -foo -bar -ray:JkLmOpQ -or- C:\this is\very bad\but people\do it\anyways.exe /foo /bar /ray:JkLmOpQ

It's simple enough to just wrap things without parameters in quotes,

e.g.

$foo = "`"$bar`""

However, I'd like to handle things that may have parameters properly, e.g.

"C:\this is\very bad\but people\do it\anyways.exe" -foo -bar -ray:JkLmOpQ
"C:\this is\very bad\but people\do it\anyways.exe" /foo /bar /ray:JkLmOpQ

Considering using RegEx or splitting the string on / or - but those might have edge cases I'm missing.

Jaigene Kang

Posted 2013-02-09T02:26:36.823

Reputation: 21

Answers

0

Easiest way to do it would just be a string replacement. I used this for a similar image path issue.

if(($Temp.ImagePath -notlike "*`"*") -AND ($Temp.ImagePath -like "*.exe*")) `
   {
      if($Temp.ImagePath -like "*D:\*") (repeat for "*C:\*")
         {
             $Temp.ImagePath = $Temp.ImagePath.Replace("D:\", "`"D:\")
         }

      $NewPath = $Temp.ImagePath -replace ".exe", ".exe`""

      Set-ItemProperty -Path "HKLM:\SYSTEM\currentControlSet\Services\$currentService" -Name ImagePath -Value $NewPath
   }

mj626

Posted 2013-02-09T02:26:36.823

Reputation: 1

0

I had a look at this problem and it seems that it was spaces in Program Files that caused the problem.

This a PowerShell script I created to investigate.

Clear-Host
$keys = Get-ChildItem HKLM:\System\ControlSet001\services
$items = $keys | Foreach-Object {Get-ItemProperty $_.PsPath }
ForEach ($item in $items) {
If ($item.ImagePath -match " " -and $item.ImagePath -notmatch "`"" -and $item.ImagePath -match "Program Files") {
"{0,-28} {1,-120} " -f $Item.PSChildName, $item.ImagePath 
}
}

[For my information, what problem does the space cause as I found two Nvidia images with no quotes around their path]

Guy Thomas

Posted 2013-02-09T02:26:36.823

Reputation: 3 160