Bill Noble
Bill Noble

Reputation: 227

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;
    }
}

Upvotes: 11

Views: 4645

Answers (1)

Keith Hill
Keith Hill

Reputation: 201622

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

Upvotes: 26

Related Questions