Loop to clone a file 10 times

Welcome Forums General PowerShell Q&A Loop to clone a file 10 times

This topic contains 3 replies, has 3 voices, and was last updated by

 
Participant
3 months, 2 weeks ago.

  • Author
    Posts
  • #105407

    Participant
    Points: 0
    Rank: Member

    Hi,

    I am looking for a way in PS to clone a file in the same folder and rename it.
    For example if the file is .\Windows10_1.vhd i want to copy it 10x in the same folder but have it named _2, _3 etc.
    I tried this with a For and For Each loop but got the error the same file exists.

    I can do xcopy filename1.vhd filename2.vhd but need to script it so i can do this x50 x100 etc.

  • #105416
    Jon

    Participant
    Points: 23
    Rank: Member

    Something like this

    
    $numbers = (2..11)
    
    $source = "C:\scripts\file1.txt"
    $dest = "C:\scripts"
    
    foreach ($number in $numbers)
    {
    
    copy-item -Path $source -Destination "$dest\file$number.txt"
    
    
    }
    
    
  • #105434

    Participant
    Points: 206
    Helping Hand
    Rank: Participant

    How about this approach..

    Get-ChildItem -Path 'd:\vhdfolder'
    
    # Results
    
        Directory: D:\vhdfolder
    
    
    Mode                LastWriteTime         Length Name
    ----                -------------         ------ ----
    -a----        28-Aug-16     15:23        4194304 Win10_1.vhdx
    -a----        28-Aug-16     15:23        4194304 Win10_2.vhdx
                                                                                                          
    
    
    ForEach($VHdFile in (Get-ChildItem -Path 'd:\vhdfolder'))
    {
        1..3 | 
        ForEach {
                    $VHdFileCopy = ("$($VHdFile.BaseName){0:d2}" -f $_ + '.vhdx')
                    copy-item -Path $VHdFile.FullName -Destination "d:\vhdfolder\$VHdFileCopy"
                }
    }
    
    Get-ChildItem -Path 'd:\vhdfolder'
    
    # Results
    
        Directory: D:\vhdfolder
    
    
    Mode                LastWriteTime         Length Name
    ----                -------------         ------ ---- 
    -a----        28-Aug-16     15:23        4194304 Win10_1.vhdx
    -a----        28-Aug-16     15:23        4194304 Win10_101.vhdx
    -a----        28-Aug-16     15:23        4194304 Win10_102.vhdx
    -a----        28-Aug-16     15:23        4194304 Win10_103.vhdx
    -a----        28-Aug-16     15:23        4194304 Win10_2.vhdx
    -a----        28-Aug-16     15:23        4194304 Win10_201.vhdx
    -a----        28-Aug-16     15:23        4194304 Win10_202.vhdx
    -a----        28-Aug-16     15:23        4194304 Win10_203.vhdx
    

    You can add more leading zeros by changing this to a higher number.

    :d2
    
  • #105704

    Participant
    Points: 0
    Rank: Member

    Both methods worked for me.
    Excellent thank you.

The topic ‘Loop to clone a file 10 times’ is closed to new replies.