Get-PEB: getting current directory works for cmd.exe, but not for powershell.exe
On my Windows 10 box I opened a Powershell session and a Cmd session in both of which I changed the current working directory with "cd Desktop". Now I do this:
PS C:\Users\XXX\Desktop> (Get-PEB -Id (ps powershell).Id).ProcessParameters.CurrentDirectory
C:\Users\XXX\
PS C:\Users\XXX\Desktop> (Get-PEB -Id (ps cmd).Id).ProcessParameters.CurrentDirectory
C:\Users\XXX\Desktop\
As you can see, the output is correct for Cmd, but wrong for Powershell. Is this a known problem?
Update: SysInternals Process Explorer shows the same discrepancy, so at least the two of them behave in the same way - but still unexpectedly.
Update 2: In the command line help there is a little bug in an example:
C:\PS>$NotepadPEB = Get-PEB -Id (ps notepad)
C:\PS> $NotepadPEB.InInitializationOrderModuleList
You forgot .Id. So in the first line it sould be: Get-PEB -Id (ps notepad).Id.
There is the Win32 concept of current directory, and the PowerShell concept, and they are not related. When you realize that the PowerShell working directory could be in some non-filesystem provider (such as "HKLM:\SYSTEM\CurrentControlSet"), it makes sense that they can't be the same.
This is why you also have to be careful to Resolve-Path relative paths before passing them to non-PowerShell things (like a [System.IO.File] method--because .NET will resolve a relative path against the current Win32 directory, not the current PS directory).
Thanks for your expertise, I appreciate it. If I am not asking too much, would you mind advising me about how I could try and get the PowerShell CWD from an external PS process, assuming that I find a way to deal with the fact the it could be a virtual path and not a filesystem path?
Unfortunately, I am not aware of any place where this information might "leak" out... so you'd either have to be able to run code in the target process, act as a debugger and figure out the right memory to read, or arrange with the PowerShell team to provide a way to get it. :(
Also note that a single win32 process can be hosting multiple PowerShell runspaces... so you could actually have many different (and equally valid) CWDs for PowerShell...