How to retrieve value of pwd from powershell in c# code

631 Views Asked by At

I was looking for the answer at least 3 hours, but without success.
Everywhere are just pieces of code and I have no idea how to connect them together.

What I want to achieve:
I am creating dotnet-tool in which I need to process current working directory (value which is printed using pwd command in PS). Dotnet tool will be installed in default directory C:\Users\Samuel\.dotnet\.store\myTool... but command can be invoked in any directory in PS using dotnet tool run myTool.

For example:
In PS I am in: C:\Users\Samuel\AxisRepos> and I run dotnet tool run myTool
In this case I want to retrieve C:\Users\Samuel\AxisRepos in C# code to find out, in which directory command was invoked.

So simply put, I want to do something like this in my dotnet tool:

class Program
{
    static void Main(string[] args)
    {
        var pwd = GetPwdFromPowerShell();
    }

    static string GetPwdFromPowerShell()
    {
        string pwd = "";

        // Retrieve current working directory from PS in which dotnet tool was invoked

        return pwd;
    }
}
1

There are 1 best solutions below

2
On BEST ANSWER

pwd is just an alias for Get-Location which shows the current directory...

From c# you can use the built-in .net class System.IO.Directory specifically the method GetCurrentDirectory

So just update your code to:

static string GetPwd()
{
    return System.IO.Directory.GetCurrentDirectory();
}

And from powershell this will have the same results:

[System.IO.Directory]::GetCurrentDirectory()