2

Trying to create dummy files, directories, and sub-directories that are randomly N levels deep.

There should be files in each directory/sub-directory.

I was able to provide a directory and get random folders created with random files inside, but having trouble with the loop to go N levels deep.

Here's what I have:

    function New-DemoData ($Path)
    {
      # Usage: New-DemoData “D:\Company”
      Push-Location
      1..10 | % { Set-Location -Path (New-Item -ItemType directory -Name $([System.Guid]::NewGuid().ToString()) -path "$path\").fullname -ErrorAction SilentlyContinue
      for ( $i=1; $i -le (Get-Random -Minimum 10 -Maximum 200); $i++ )
        {

          #2147483648 bytes = 2GB  
          #20971520 = 20MB
          fsutil file createnew ($([System.Guid]::NewGuid().ToString()) + ".txt") (Get-Random -Minimum 1024 -Maximum 20971520)
        }
      }
      Pop-Location
    }
1

There are a couple tricks let you simplify your code.

You can create nested folders as deeply as necessary all in one command, as long as the path is fully specified. For example, if you have c:\scratch but nothing below it, New-Item -Type Directory c:\scratch\foo\bar\baz will create the foo\bar\baz subdirectories.

This will allow you to remove the logic for pushing and popping the location, and your loop can simply create directory names in a string by repetitively appending to the string, and creating files in each directory as before.

A second minor tip is to use PowerShell's numeric units. Instead of comments specifying what your "magic numbers" are for the random size of the file, you can instead use: (Get-Random -Minimum 1KB -Maximum 20MB)

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.