【问题标题】:Get-ChildItem vs. direct use of the .NET Framework's [System.IO.Directory]::GetFiles() method with UNC pathsGet-ChildItem 与直接使用 .NET Framework 的 [System.IO.Directory]::GetFiles() 方法与 UNC 路径
【发布时间】:2017-07-30 23:39:13
【问题描述】:

当使用 UNC 路径(例如:\\machine\share\dir)时,我可以从 UNC 路径中使用dir 命令 (Get-ChildItem) 获取文件列表,但如果我尝试使用 [System.IO.Directory]::GetFiles,我会得到一个空列表(不是错误,只是没有项目)。我认为 PS 是建立在 .NET 框架上的。有谁知道为什么 Get-ChildItem 可以使用 UNC 路径,而 .NET GetFiles 方法返回一个空列表?

【问题讨论】:

  • GetFileSystemEntries 方法将是您正在寻找的模拟方法。此外,不同之处在于 NET 类更快,尤其是 UNC 部分。

标签: .net powershell filesystems


【解决方案1】:

[System.IO.Directory]::GetFiles() 仅返回文件,而Get-ChildItem(及其内置别名dir)默认返回文件目录。

因此,在只有子目录(没有文件)的目录上调用[System.IO.Directory]::GetFiles() 会产生“无”(空字符串数组)) .

另一种说法,松散地说:Get-ChildItem[System.IO.Directory]::GetFiles()(类似于Get-ChildItem -File,PSv3+)和[System.IO.Directory]::GetDirectories()(类似于Get-ChildItem -Directory,PSv3+),或者更直接地,对应于[System.IO.Directory]::GetFileSystemEntries()

另一种选择是使用 .NET 4+(在 PSv3+ 中可用)文件系统项 枚举 API,例如 [System.IO.Directory]::EnumerateFileSystemInfos()。举个例子,见我的this answer

Get-ChildItem 和直接使用 [System.IO.Directory] 类型之间有许多具体的区别,但值得注意的是 Get-ChildItem 返回 对象 而不是字符串,而 Get-ChildItem 跳过 默认隐藏项(必须使用-Force)。

通常情况下,在使用 PowerShell 自己的 cmdlet 和直接使用 .NET Framework 之间进行选择是在便利性和性能之间进行权衡。
后者通常会更快,在当前情况下,PowerShell 版本 1 和 2 中的 UNC 路径尤其如此 - 请参阅 this blog post

提示 wOxxOmMike Sherrill 'Cat Recall' 获取补充信息。

【讨论】:

    猜你喜欢
    • 2013-11-15
    • 2010-10-15
    • 1970-01-01
    • 2020-06-16
    • 1970-01-01
    • 2011-08-07
    • 2012-08-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多