2

我有一个可以像这样调用的自定义 cmdlet:

Get-Info ".\somefile.txt"

我的命令行开关代码如下所示:

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

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

但是,当我运行命令时,出现此错误:

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

我没有从C:\Users\Philip. 出于某种原因,我的 cmdlet 没有检测到工作目录,所以像这样的本地文件不起作用。在 C# 中,当提供本地“.\”文件路径时,推荐的检测正确文件路径的方法是什么?

4

5 回答 5

1

查看 SessionState 属性的 Path 属性。它具有一些通常用于解析相对路径的实用功能。选项因您是否要支持通配符而异。这个论坛帖子可能有用。

于 2012-03-29T07:24:31.847 回答
1

现在我正在使用GetUnresolvedProviderPathFromPsPath但是,我可以在这个 stackoverflow question的帮助下根据 Microsoft 指南设计我的 cmdlet ,这正是我正在寻找的。那里的答案非常全面。我不想删除这个问题,但我已经投票关闭它,因为这个问题是完全重复的,而且答案更好。

于 2012-04-01T13:19:18.693 回答
0

你有没有尝试过:

File.Open(Path.GetFullPath(FilePath))
于 2012-03-28T19:23:23.923 回答
0

你应该能够使用类似的东西:

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

如果您继承自PSCmdlet而不是Cmdlet. 资源

或者,类似:

this.SessionState.Path

可能会奏效。

于 2012-03-28T19:28:15.570 回答
0
    /// <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);
    }
于 2013-02-07T20:19:43.690 回答