1

Hi I need to run a variable process as elevated using powershell. The following code don't work because for some reason Powershell don't expand the variable:

$exe = "C:\$var.exe"
Start-Process $exe -Verb runas

But I get this error

Start-Process : This command cannot be run due to the error: The system cannot find the file specified

+Start-Process $exe -Verb runas;

2
  • If you output $var and $exe before running Start-Process do they have the expected values? Commented Mar 30, 2018 at 14:01
  • @Vittorio Vaselli Some code is missing, just paste all the code related to the different variables otherwise it's not understandable Commented Mar 30, 2018 at 14:14

2 Answers 2

2

The $var-variable expanded when you declared $exe-string as long as you use double-quotes like you have in the question. Single quotes however $exe = 'c:\$var.exe' would not work as single quotes makes a literal string.

Output $exe to verify the path. Your $var value is probably wrong.

The error just says which line it ran, not which path it actually used except for that it's stored in the $exe-variable.

$var = "nonexistingfile"
$exe = "c:\$var.exe"
$exe
c:\nonexistingfile.exe

Start-Process $exe
Start-Process : This command cannot be run due to the error: The system cannot find the file specified.
At line:1 char:1
+ Start-Process $exe
+ ~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Start-Process], InvalidOperationException
    + FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand

However with a valid path:

$var = "windows\system32\notepad"
$exe = "c:\$var.exe"
$exe
c:\windows\system32\notepad.exe

Start-Process $exe
#Starts notepad
Sign up to request clarification or add additional context in comments.

Comments

-1

I like to combine strings using arrays and -join:

$exe = 'C:\',$var,'.exe' -join ''

next I would test if the executable exists and run it or write an error

if(Test-Path -LiteralPath $exe) {
    Start-Process $exe -Verb runas
} else {
    Write-Error "the executable could not be found"
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.