powershellvariablesquotesvariable-expansion

PowerShell using a variable in quotes within a command


I have this which works (triple double quotes are not a mistake; it works exactly like this)—concentrate on the Start-Process part:

Start-Process powershell -Credential $cred -WorkingDirectory "$lettre_disque" -ArgumentList '-noprofile -command &{Start-Process """D:\WD Drive Unlock.exe""" -verb runas}'

Now I'm simply trying to replace the string D:\WD Drive Unlock.exe with a variable named $chemin_fichier which contains the exact same text (D:\WD Drive Unlock.exe).

I'm trying:

"""$chemin_fichier"""

""$chemin_fichier""

"$chemin_fichier"

""""$chemin_fichier""""

Nothing works...

How do I get that variable to show up? This command is pretty confusing. What is the right combination? Do I have to escape something or?


Solution

  • I'd break your command into pieces using splatting:

    $chemin_fichier = 'D:\WD Drive Unlock.exe'
    
    $ArgList = @{
        FilePath = 'powershell'
        Credential = $cred
        WorkingDirectory = $lettre_disque
        ArgumentList = @(
            '-NoProfile'
            '-Command'
            "`"Start-Process -FilePath '$chemin_fichier' -Verb runas`""
        )
    }
    Start-Process @ArgList
    

    Wrapping your command in a script block was unnecessary.