简体   繁体   中英

Match file name and copy using PowerShell

I am struggling to get this simple PowerShell script to work. I have googled, but I can't find the answer.

As you can see, I am specifying the source and destination location.

The $filedate variable is doing a dateadd to get yesterdays date as the filename contains the date.

The $filter variable has the string I am searching on, including the date part.

The Get-ChildItem command works on its own, but when I apply the filter it returns nothing. What am I missing to get this to work?

$source = "C:\MSSQL.1\Backup\"
$destination = "D:\MSSQL.2\Backup\"
$filedate = (get-date).AddDays(-1).tostring('yyyyMMdd')
$filter = "FULL_(local)_Product_" + $filedate + "*"
Get-ChildItem -Path $source -filter $filter | Copy-Item -Destination $destination

Try filtering the list of files by using the Where-Object cmdlet and the -match operator:

$source = "C:\MSSQL.1\Backup\"
$destination = "D:\MSSQL.2\Backup\"
$filedate = (Get-Date).AddDays(-1).ToString("yyyyMMdd")
$filter = "FULL_(local)_Product_$filedate"
Get-ChildItem -Path $source | Where-Object { $_.Name -match $filter } | Copy-Item -Destination $destination

If you're still not getting any results, then we need to look at the filter itself.

Related resources:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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