Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current working directory inside a Cmdlet

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.

like image 215
Hemisphera Avatar asked Jun 17 '15 13:06

Hemisphera


People also ask

How do I get the directory of a file in PowerShell?

Use the Get-ChildItem cmdlet in PowerShell to get the full path of the file in the current directory. Get-ChildItem returns one or more items from the specified location and using the file FullName property, it gets the full path of the file.

How do I change the current working directory in PowerShell?

The Get-Location command is used with the Set-Location command. The Set-Location command allows you to specify your current directory location. The PassThru parameter can be used with many Set commands in Windows PowerShell to return information about the result in cases in which there is no default output.


1 Answers

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?

like image 50
Marco Avatar answered Oct 20 '22 00:10

Marco