Search code examples
c#powershellfilepathpowershell-cmdlet

Powershell Cmdlet: Determine actual filepath of file in local directory


I have a custom cmdlet that can be called like this:

Get-Info ".\somefile.txt"

My commandlet code looks something like this:

[Parameter(Mandatory = true, Position = 0)]
public string FilePath { get; set; }

protected override void ProcessRecord()
{
    using (var stream = File.Open(FilePath))
    {
        // Do work
    }
}

However when I run the command, I get this error:

Could not find file 'C:\Users\Philip\somefile.txt'

I'm not executing this cmdlet from C:\Users\Philip. For some reason my cmdlet doesn't detect the working directory so local files like this don't work. In C#, what is the recommended way of detecting the correct filepath when a local ".\" filepath is provided?


Solution

  • For now I am using GetUnresolvedProviderPathFromPsPath. However I could design my cmdlet a little more according to Microsoft guidelines with the help of this stackoverflow question, which is exactly what I am looking for. The answer there is extremely comprehensive. I don't want to delete this quesion, but I have voted to close it as this question is an exact duplicate and the answer there is better.