Search code examples
powershellcmdscriptingpowershell-4.0

How to execute a string in a variable in powershell


I have the following string

"C:\ProgramData\Package Cache{6b95042e-f763-4850-9136-d004dd0d0a9b}\AzInfoProtection.exe" /uninstall

I need to execute the above string as below

First-line

cd C:\ProgramData\Package Cache\{6b95042e-f763-4850-9136-d004dd0d0a9b}

The second line (note there is no exe)

AzInfoProtection /uninstall

Variables are generally executed like below in PowerShell

Invoke-Expression $cmd

But how to split the above string into multiple lines for execution. Then I need to remove the quote and then exe.


Solution

  • It's a bit hard to understand the ask here but I think I follow. Let me know if I'm off base or misunderstanding what you're trying to do.

    $commandString = '"C:\ProgramData\Package Cache{6b95042e-f763-4850-9136-d004dd0d0a9b}\AzInfoProtection.exe" /uninstall'
    
    # Get command parent directory
    if( $commandString -match '^".*?"' ) {
      $runInDir = Split-Path -Parent $Matches[0]
    }
    
    # Change directories (use the location stack for easy traversal) 
    Push-Location $runInDir
    
    # Run program
    Invoke-Expression $commandString
    
    # Change back to previous directory
    Pop-Location
    
    

    This works by checking if the string starts with a quote-enclosed string (escaped quotes should not need to be handled within filepaths), and if so gets the first match from the $Matches object. $Matches is an automatic variable which is populated whenever you get a $True result using the [-match operator][1]. With the command path extracted, we use Split-Path to get the parent container relative to the filepath.

    Then use Push-Location to change directories. Push-Location works like Set-Location (aliased to cd) except it tracks the directories you leave and enter as a stack. Its sibling cmdlet Pop-Location is used further on to return to the previous location.

    Finally, we use Invoke-Expression to run your command. After this completes use Pop-Location to return to the previous directory. Keep the following in mind:

    You should take note that the use of Invoke-Expression is often implemented insecurely, and so you should consider heeding the warning on the documentation I've linked to and consider parameterizing your command if your $commandString is actually populated from a generated file, provided by a parameter, or another other outside source.


    Note: You mentioned this in your question:

    The second line (note there is no exe)

    Windows doesn't care if you omit the extension for executable types when executing them. You can run AzInfoProtection.exe with or without the .exe at the end. So unless I'm missing something this detail doesn't have any bearing on how this code works.