Categories

Using the range operator

One of the events in this years scripting games involved creating a set of files.  Many of the entries did something like this

001
002
003
$files = @("file1.txt", "file2.txt", "file3.txt", "file4.txt", "file5.txt", 
"file6.txt", "file7.txt", "file8.txt", "file9.txt", "file10.txt")
foreach ($file in $files) {New-Item -Path c:\test -Name $file -ItemType File}

 

A list of files is created and a foreach is used to call New-Item.  A variant on this used a for loop

for ($i=0; $i –le 9; $i++){New-Item -Path c:\test -Name $files[$i] -ItemType File}

 

There is a much easier way

001
1..10 | foreach {New-Item -Path c:\test -Name "file$_.txt" -ItemType File}

 

Whenever you have to deal with lists of things that are numerically sequential – try to use the range operator. 

Leave a Reply