How do you execute an arbitrary native command from a string?

前端 未结 4 1457
小鲜肉
小鲜肉 2020-11-27 09:44

I can express my need with the following scenario: Write a function that accepts a string to be run as a native command.

It\'s not too far fetched

4条回答
  •  爱一瞬间的悲伤
    2020-11-27 09:56

    The accepted answer wasn't working for me when trying to parse the registry for uninstall strings, and execute them. Turns out I didn't need the call to Invoke-Expression after all.

    I finally came across this nice template for seeing how to execute uninstall strings:

    $path = 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall'
    $app = 'MyApp'
    $apps= @{}
    Get-ChildItem $path | 
        Where-Object -FilterScript {$_.getvalue('DisplayName') -like $app} | 
        ForEach-Object -process {$apps.Set_Item(
            $_.getvalue('UninstallString'),
            $_.getvalue('DisplayName'))
        }
    
    foreach ($uninstall_string in $apps.GetEnumerator()) {
        $uninstall_app, $uninstall_arg = $uninstall_string.name.split(' ')
        & $uninstall_app $uninstall_arg
    }
    

    This works for me, namely because $app is an in house application that I know will only have two arguments. For more complex uninstall strings you may want to use the join operator. Also, I just used a hash-map, but really, you'd probably want to use an array.

    Also, if you do have multiple versions of the same application installed, this uninstaller will cycle through them all at once, which confuses MsiExec.exe, so there's that too.

提交回复
热议问题