Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the current directory in PowerShell cmdlet?

I am developing a PowerShell 3.0 cmdlet using C#/.Net 4.0 in Visual Studio 2010. I'd like to get the current directory in PowerShell where the user executes the cmdlet. But Directory.GetCurrentDirectory() doesn't work as expected. In the code below, the result is C:\Users\Administrator.

Question: What cmdlet code is used to get PowerShell's current directory?

[System.Management.Automation.Cmdlet(System.Management.Automation.VerbsCommon.Get, "StatusBar")]
public class GetStatusBarCommand : System.Management.Automation.PSCmdlet
{
    /// <summary>
    /// Provides a record-by-record processing functionality for the cmdlet.
    /// </summary>
    protected override void ProcessRecord()
    {
        this.WriteObject(Directory.GetCurrentDirectory());
        return;
    }
}
like image 478
Bill Noble Avatar asked Dec 16 '12 01:12

Bill Noble


1 Answers

A PowerShell process can have multiple Runspaces so a single global directory doesn't work for PowerShell. Besides that, in PowerShell your current directory might be within the Registry and not within the file system. However, you can access the file system dir with the PowerShell API like so:

this.SessionState.Path.CurrentFileSystemLocation
like image 59
Keith Hill Avatar answered Sep 24 '22 10:09

Keith Hill