简体   繁体   English

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

[英]How to get specific files using Get-ChildItem

I am trying to get all files with today's date in the file name. 我正在尝试获取文件名中具有今天日期的所有文件。 However, when I run this, I get the following error: 但是,当我运行此命令时,出现以下错误:

#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. Get-ChildItem:路径中的非法字符。 At line:2 char:1 + Get-ChildItem -File -path $source -Filter $file* 在第2行:char:1 + Get-ChildItem -File -path $ source -Filter $ file *

Any help would be appreciated. 任何帮助,将不胜感激。 I am using $file* in the filter because the file extension could be different. 我在过滤器中使用$file* ,因为文件扩展名可能不同。

Your problem is the use of | Out-String 您的问题是使用| Out-String | Out-String which is not only unnecessary in your case, but appends a trailing newline , which is the cause of the problem. | Out-String不仅在您的情况下是不必要的,而且还会附加结尾的换行符 ,这是导致问题的原因。

Use just: 仅使用:

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

get-date -uformat "%Y-%m-%d" directly returns a [string] . get-date -uformat "%Y-%m-%d"直接返回[string]


Optional troubleshooting tips : 可选的故障排除技巧

To verify that get-date -uformat "%Y-%m-%d" outputs a [string] instance: 要验证get-date -uformat "%Y-%m-%d"输出一个[string]实例:

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

To verify that ... | Out-String 验证... | Out-String ... | Out-String appends a newline: ... | Out-String追加一个换行符:

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

Try This: 尝试这个:

#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

The way you currently have it, PowerShell is trying to pass a variable called $file* to Get-ChildItem . 目前,PowerShell正在尝试将名为$file*的变量传递给Get-ChildItem

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM