Question

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?

Was it helpful?

Solution 2

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.

OTHER TIPS

Look at the Path property of the SessionState property. It has some utility functions commonly used to resolve a relative path. The choices vary depending on whether you want to support wildcards. This forum post might be useful.

Have you tried:

File.Open(Path.GetFullPath(FilePath))

You should be able to use something like:

var currentDirectory = ((PathInfo)GetVariableValue("pwd")).Path;

If you inherit from PSCmdlet instead of Cmdlet. Source

Alternatively, something like:

this.SessionState.Path

might work.

    /// <summary>
    /// The member variable m_fname is populated by input parameter
    /// and accepts either absolute or relative path.
    /// This method will determine if the supplied parameter was fully qualified, 
    /// and if not then qualify it.
    /// </summary>
    protected override void InternalProcessRecord()
    {
        base.InternalProcessRecord();

        string fname = null;
        if (Path.IsPathRooted(m_fname))
            fname = m_fname;
        else
            fname = Path.Combine(this.SessionState.Path.CurrentLocation.ToString(), m_fname);

        // If the file doesn't exist
        if (!File.Exists(fname))
            throw new FileNotFoundException("File does not exist.", fname);
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top