fluter fluter - 4 months ago 16
PowerShell Question

workingdirectory does not work when verb is used

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

Answer

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"'

To avoid quoting headaches you can also pass the arguments individually, except for the command string itself:

Start-Process -FilePath powershell.exe -Verb Runas `
  -ArgumentList '-NoExit', '-Command', 'cd C:\ws'

In practice, as of PSv5 - 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.

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:

  1. running as the current user as-is (the default)

  2. impersonating a different user with -Verb RunAsUser (with an invariably interactive credentials prompt)

  3. 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).

Comments