Search code examples
powershellget-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. At line: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.


Solution

  • Your problem is the use of | Out-String which is not only unnecessary in your case, but appends a trailing newline, which is the cause of the problem.

    Use just:

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

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


    Optional troubleshooting tips:

    To verify that get-date -uformat "%Y-%m-%d" outputs a [string] instance:

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

    To verify that ... | Out-String appends a newline:

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