7

I am writing a Cmdlet for PowerShell in C#. I am subclassing a Cmdlet and NOT a PSCmdlet.

Is there a way to get the current directory from PowerShell? I could do so with the PSCmdlet using GetVariableValue("pwd"). But in the Cmd class I do not have that available.

Environment.CurrentDiretory points me to the path where powershell was started from, not where PowerShell itself is currently positioned.

edit

Example:

I fire up powershell via - say - powershell_ise.exe. It starts up in C:\Windows\System32\WindowsPowerShell\v1.0. I then change path using cd c:\my\folder and run my command Do-Something. Inside the implementation of "Do-Something" (C#-side) I'd like to be able to retrieve the current path => c:\my\folder.

If possible, I would like to avoid using PSCmdlet.

Hemisphera
  • 816
  • 6
  • 23
  • You should really be using `PSCmdlet` or pass the location as parameter argument from the invoking cmdlet. – Mathias R. Jessen Jun 17 '15 at 14:05
  • I am currently rewriting my code to derive from ``PSCmdlet``. Looks good so far. I was a bit scared of it because I really don't need much of it, except access to it's internals. And on the other hand ... that's exactly what it's for I guess... – Hemisphera Jun 17 '15 at 14:23
  • Exactly, you have a runtime dependecy (current location) = use PSCmdlet – Mathias R. Jessen Jun 17 '15 at 14:35

1 Answers1

4

I am starting in C:\Users\<myusername>. If I know enter cd.. I am in C:\Users\

Entering (Get-Location).Path returns C:\Users. Thats what you want, isnt it?

Altrnativly try:

WriteObject(this.SessionState.Path.CurrentFileSystemLocation);

Reference: How can I get the current directory in PowerShell cmdlet?

Community
  • 1
  • 1
Marco
  • 22,856
  • 9
  • 75
  • 124
  • I updated my original answer with an example. I would like to avoid running further cmdlets to get my current path. Unless I have no other way. – Hemisphera Jun 17 '15 at 13:43
  • @Hemisphera I've updated my answer. I don't have access to LinqPad or Visual Studio right now, so I can't confirm this works, – Marco Jun 17 '15 at 14:44
  • It only works because I now use ``PSCmdlet``. ``Cmdlet`` alone does not provide access to ``SessionState``. But since I ended up using ``PSCmdlet`` I'll mark this as answered. It's cleaner than ``GetVariableValue("pwd")`` anway. Thanks! – Hemisphera Jun 17 '15 at 15:38