Author Posts

July 26, 2018 at 9:17 pm

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.

July 26, 2018 at 10:27 pm

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"


}

July 26, 2018 at 11:57 pm

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

July 31, 2018 at 9:39 pm

Both methods worked for me.
Excellent thank you.