powershell - 如何使用 Get-ChildItem 获取特定文件

标签 powershell get-childitem

我正在尝试获取文件名中包含今天日期的所有文件。但是,当我运行此命令时,出现以下错误:

#Share location
$source = "U:\Data\*"
#Sharepoint file location
$prefix = "file_name_"

#Date Info
$date = get-date -uformat "%Y-%m-%d" | Out-String

$file = $prefix + $date 

Get-ChildItem -File -path $source -Filter $file*

Get-ChildItem : Illegal characters in path. At line:2 char:1 + Get-ChildItem -File -path $source -Filter $file*

如有任何帮助,我们将不胜感激。我在过滤器中使用 $file* 因为文件扩展名可能不同。

最佳答案

您的问题是使用| Out-String 这不仅在您的情况下是不必要的,而且附加尾随换行符,这是问题的原因。

仅使用:

$date = get-date -uformat "%Y-%m-%d"  # Do NOT use ... | Out-String

get-date -uformat "%Y-%m-%d" 直接返回一个[string]


可选的故障排除提示:

要验证 get-date -uformat "%Y-%m-%d" 是否输出 [string] 实例:

PS> (get-date -uformat "%Y-%m-%d").GetType().FullName
System.String

验证... | Out-String 附加换行符:

PS> (get-date -uformat "%Y-%m-%d" | Out-String).EndsWith("`n")
True

关于powershell - 如何使用 Get-ChildItem 获取特定文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48890112/

相关文章:

Powershell 使用远程连接返回不同的信息

powershell - Get-ChildItem为Assembly。*。dll添加排除筛选器,但包括Assembly.Some。*。dll

powershell - Get-ChildItem零结果输出

regex - 使用 “Matches”的不区分大小写的正则表达式匹配

powershell - 大文本文件的匹配操作速度问题

Powershell - 无法验证参数 'Name' 的参数。参数中的字符数 (0) 太少

function - Powershell 函数字符串输出作为基于文件的函数的输入

powershell - 选择对象上的空格和带省略号的截断

powershell - Powershell:无法读取/设置ExecutionPolicy

powershell - 将 get-ChildItem 与 A​​CL powershell 相结合