简体   繁体   中英

PowerShell - Copy files to all folders matching a certain pattern

I'm trying to copy certain files to all folders in a directory that end with .com. For example, lets say my file structure was like this:

Folder: SourceDirectory
    File: FileToDeploy.txt
    Folder: Server1.com
    Folder: Server2.com

The file structure after the PowerShell script runs should look like this:

Folder: SourceDirectory
   File: FileToDeploy.txt
   Folder: Server1.com
      File:FileToDeploy.txt
   Folder: Server2.com
      File:FileToDeploy.txt

Thanks

You can discover all immediate subfolders matching the naming pattern with the -Filter parameter with Get-ChildItem :

$file = Get-Item .\path\to\SourceDirectory\FileToDeploy.txt

Get-ChildItem -Path .\path\to\SourceDirectory -Directory -Filter *.com | ForEach-Object {
    $file |Copy-Item -Destination $_.FullName
}

As per requirements, you can either store the path of file in a variable or directly use the filepath in second line of the code itself. Adjust the paths to fit your requirements. The following code works for you :)

$FileToMovePath = 'C:\FileToDeploy.txt'
Get-ChildItem C:\PathToMainDirectory\*.com | ForEach-Object {Copy $FileToMovePath $_.FullName}

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