Thursday, January 5, 2012

Powershell (v2) - Quick File/Folder Generation

Problem: how do I quickly create bulk folders and/or files?


Quick Answer: use a for loop to repeat New-Item and specify whether you want File or Directory in the New-Item call.

Long Answer: I often am in a hurry, and, to test things, don't have time to go create dummy files (or folders) for validation some data management script.  To quickly generate 100 files use this approach,
$path = "C:\testing\powershell\testfiles"
if((Test-Path $path) -ne $true) {
  for($i=1;$i -le 100;$i++) {
    New-Item -Path $path -Name "$i.txt" -ItemType File -Value $i -Force
  }
}
This script will generate 100 files in just a few seconds, where each file has a numeric name (with .txt extension) and the value in the .txt file matches the name.  I use this in a pinch to have something I can manipulation where the test is really more about the file/folder management than the file content.  In short, I just need something, nothing really, to work with.

To take this one step further, I wrote the following script to test out some folder/file management logic which I perfected in a post I made earlier today,
$path = "C:\testing\powershell\testfiles"
if((Test-Path $path) -ne $true) {
for($i=1;$i -le 100;$i++) {
New-Item -Path $path -Name "$i.txt" -ItemType File -Value $i -Force
}
}

# Split files into subdirectories
$files = Get-ChildItem -Path $path | Where-Object {$_.PSIsContainer -ne $true};
for($i = 1; $i -lt (($files).Count); $i++) {
  $minifileset = $files | Select-Object -First 10;
  $newpath = $files.fullname;
  New-Item -Path $newpath -Name $i -ItemType Container -Force;
  foreach($file in $minifileset) {
    move $file.fullname "$newpath\$i"
  }
}
The link I posted earlier can be found here,
Splitting up very large file sets into subfolders

0 comments:

Post a Comment