【问题标题】:Powershell Cmdlet: Determine actual filepath of file in local directoryPowershell Cmdlet:确定本地目录中文件的实际文件路径
【发布时间】:2012-04-12 10:31:30
【问题描述】:

我有一个可以这样调用的自定义 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。由于某种原因,我的 cmdlet 没有检测到工作目录,所以像这样的本地文件不起作用。在 C# 中,当提供本地“.\”文件路径时,推荐的检测正确文件路径的方法是什么?

【问题讨论】:

标签: c# powershell filepath cmdlets


【解决方案1】:

你试过了吗:

File.Open(Path.GetFullPath(FilePath))

【讨论】:

  • 是的,我有,它得到的完整路径是'C:\Users\Philip\somefile.txt'
【解决方案2】:

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

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

如果您继承自 PSCmdlet 而不是 CmdletSource

或者,类似:

this.SessionState.Path

可能会起作用。

【讨论】:

    【解决方案3】:

    查看 SessionState 属性的 Path 属性。它具有一些通常用于解析相对路径的实用程序功能。选择取决于您是否要支持通配符。这个forum post 可能有用。

    【讨论】:

      【解决方案4】:

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

      【讨论】:

        【解决方案5】:
            /// <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);
            }
        

        【讨论】:

          猜你喜欢
          • 2021-08-04
          • 1970-01-01
          • 1970-01-01
          • 2020-10-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-07-12
          相关资源
          最近更新 更多