locked
Help creating for loop script RRS feed

  • Question

  • Hi all,

    I am trying to create what I think is a simple script, however I'm a powershell novice so it's giving me a bit of difficulty.

    I need to create many files that basically have no content.  Because there are many files created, I need them to have different names because they will be in the same location.  I found a script online to create the files I need, but I can't figure out how to have the script create many of these files and increment the name each time.

    Below is what I have tried, so you may see where I'm trying to go with this.  Any help is appreciated.  Thanks!

    for ($i = 1; $i -lt 101; $i++) {$out = new-object byte[] 1073741824; (new-object Random).NextBytes($out); [IO.File]::WriteAllBytes('D:\newfile.'$i, $out) }

    Wednesday, March 25, 2020 3:42 PM

Answers

  • $bytes = [byte[]]::new(1073741824)
    1..100 |
        ForEach-Object{
            [random]::new().NextBytes($bytes)
            [IO.File]::WriteAllBytes("D:\newfile.$_", $bytes)
        }


    \_(ツ)_/


    • Edited by jrv Wednesday, March 25, 2020 3:57 PM
    • Marked as answer by Magnus Knight Wednesday, March 25, 2020 4:07 PM
    Wednesday, March 25, 2020 3:56 PM

All replies

  • $bytes = [byte[]]::new(1073741824)
    1..100 |
        ForEach-Object{
            [random]::new().NextBytes($bytes)
            [IO.File]::WriteAllBytes("D:\newfile.$_", $bytes)
        }


    \_(ツ)_/


    • Edited by jrv Wednesday, March 25, 2020 3:57 PM
    • Marked as answer by Magnus Knight Wednesday, March 25, 2020 4:07 PM
    Wednesday, March 25, 2020 3:56 PM
  • Please when you post code or sample data or console output or error messages format it as code: How to Use the Code Feature in a TechNet Forum Post

    As a beginner you may start with a little cleaner Powershell code ...  like this:

    1..100 |
        ForEach-Object {
            New-Item -Path 'C:\sample' -Name ("File_{0:000}.ext" -f $_)
        }


    Live long and prosper!

    (79,108,97,102|%{[char]$_})-join''

    Wednesday, March 25, 2020 3:59 PM
  • Thanks jrv!  That script worked perfectly.  It seems that I was very far off in the one I was trying to do.

    BOfH-666, I'll be more careful about how I post code in the future.  Thanks for the feedback.

    Wednesday, March 25, 2020 4:07 PM