简体   繁体   中英

Powershell script to copy files based on filename

I have a folder that contains several thousand files. I would like to write a Powershell script that loops through the files and copies each file whose filename contains a specific keyword. In pseudocode:

For each file in C:\[Directory]
    If filename contains "Presentation" Then
        copy file in C:\[Directory 2]

Simply like this ?

copy-item "C:\SourceDir\*Presentation*" "C:\DestinationDir"

or like this :

copy-item "C:\SourceDir\*" "C:\DestinationDir" -Filter "*rrrr*"

But a risk exist if you have a directory with "presentation" in his name into the source directory. Then take all method proposed here and add -file in get-childitem command. Like in this short version of Robdy code :

gci "C:\SourceDir" -file | ? Name -like "*Presentation*" | cpi -d "C:\DestinationDir"

That code should do the trick:

$files = Get-ChildItem -Path "C:\path\to\source\folder"
$files | Where-Object Name -Like "*Presentation*" | Copy-Item -Destination "C:\path\to\destination\folder"

Of course can be written in one line but I put in two for visibility.

Edit: as Esperento57 pointed out, you might want to add -ItemType File to Get-ChildItem cmdlet to not include folders with 'Presentation' in their name. Also, depending on your needs you might also want to use -Recurse param to include files in subfolders.

If you have files in subfolders and you want to keep the path in destination folder you'll have to change the script a bit to something like:

Copy-Item -Destination $_.FullName.Replace('C:\path\to\source\folder','C:\path\to\destination\folder')

And for the above you'll have to make sure that folders are actually created (eg by using -Force for Copy-Item .

This seems to work:

$src = "Dir1"
$dst = "Dir2"

Get-ChildItem $src -Filter "*Presentation*" -Recurse | % {
    New-Item -Path $_.FullName.Replace($src,$dst) -ItemType File -Force
    Copy-Item -Path $_.FullName -Destination $_.FullName.Replace($src,$dst) -Force
}

Try something like this:

Get-ChildItem "C:\Your\Directory" -File -Filter *YourKeyWordToIsolate* | 
Foreach-Object { Copy-Item $_.FullName -Destination "C:\Your\New\Directory" }

... but, of course, you'll need to fill in some of the blanks left open by your pseudocode example.

Also, that's a one-liner, but I inserted a return carriage for easier readability.

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