Using Start-Process
, when Verb
is used, the Workingdirectory
option does not work, the new powershell always start in C:\WINDOWS\system32
. Why is this? How can I do this without an extra cd
command?
PS C:\> $PSVersionTable
Name Value
---- -----
PSVersion 5.1.14393.0
PSEdition Desktop
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
BuildVersion 10.0.14393.0
CLRVersion 4.0.30319.42000
WSManStackVersion 3.0
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
PS C:\> Start-Process -FilePath powershell.exe -Verb Runas -WorkingDirectory C:\ws\
# the new ps shell always in system32:
Windows PowerShell
Copyright (C) 2016 Microsoft Corporation. All rights reserved.
PS C:\WINDOWS\system32> pwd
Path
----
C:\WINDOWS\system32
As for the why - see the bottom of this answer.
As for an effective workaround (which does, however, require use of cd
(Set-Location
)):
Start-Process -FilePath powershell.exe -Verb Runas `
-ArgumentList '-NoExit -Command "cd C:\ws"'
Venryx points out that if you want to apply this technique to calling a script file that is normally called with -File
rather than -Command
, you must switch to a -Command
approach (given that the two parameters cannot be combined) that changes the location first and then (;
) invokes (&
) the script, script.ps1
in the new location, this example:
Start-Process -FilePath powershell.exe -Verb Runas `
-ArgumentList '-Command', 'cd C:\ws; & .\script.ps1'
For a more complex example involving nested quoting, see this answer.
In practice - and the docs do not mention that - the -WorkingDirectory
parameter is not respected if you start a process elevated (with administrative privileges, which is what -Verb RunAs
- somewhat obscurely - does): the location defaults to $env:SYSTEMROOT\system32
(typically, C:\Windows\System32
).
Note that this is not the -Verb
parameter per se that's the problem, but its specific RunAs
argument.
The only case in which -WorkingDirectory
is respected in combination with -Verb RunAs
is if the program being started is PowerShell (Core) 7, namely pwsh.exe
- whether you call from Windows PowerShell or PowerShell (Core) 7.
Whether there is a good technical reason for this behavior or whether this is a bug, I have no clue. Do let us know if you do.
In all other scenarios:
running as the current user as-is (the default)
impersonating a different user with -Verb RunAsUser
(with an invariably interactive credentials prompt)
running non-interactively as a different user with -Credential <PSCredential>
the -WorkingDirectory
parameter is respected.
However, if the (different) target user lacks the permissions to access the implied (current location) or explicitly specified working directory (via -WorkingDirectory
), the current location defaults to C:\
in case (2), and results in failure of the Start-Process
command in case (3).