如何使用 Get-ChildItem 获取特定文件
How to get specific files using 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*
,因为文件扩展名可能不同。
试试这个:
#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 + ".*"
$webclient = New-Object System.Net.WebClient
$webclient.UseDefaultCredentials = $true
Get-ChildItem -File -path $source -Filter $file
按照您目前的方式,PowerShell 正在尝试将名为 $file*
的变量传递给 Get-ChildItem
。
您的 问题是 | Out-String
的使用,这在您的情况下不仅没有必要,而且 附加了一个尾随换行符 ,这就是问题的原因。
仅使用:
$date = get-date -uformat "%Y-%m-%d" # Do NOT use ... | Out-String
get-date -uformat "%Y-%m-%d"
直接returns一个[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
我正在尝试获取文件名中包含今天日期的所有文件。但是,当我 运行 这样做时,出现以下错误:
#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*
,因为文件扩展名可能不同。
试试这个:
#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 + ".*"
$webclient = New-Object System.Net.WebClient
$webclient.UseDefaultCredentials = $true
Get-ChildItem -File -path $source -Filter $file
按照您目前的方式,PowerShell 正在尝试将名为 $file*
的变量传递给 Get-ChildItem
。
您的 问题是 | Out-String
的使用,这在您的情况下不仅没有必要,而且 附加了一个尾随换行符 ,这就是问题的原因。
仅使用:
$date = get-date -uformat "%Y-%m-%d" # Do NOT use ... | Out-String
get-date -uformat "%Y-%m-%d"
直接returns一个[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