Createing multiple files in existing folders at time

sns 9,246 Reputation points
2021-12-19T07:21:24.74+00:00

I have created multiple files in Directory7 Folder, however I want to create multiple files in other 6 folders at a time (Director1,2....7 folders), How can I achieve it, Please help. PFA 158744-filescouldcreatedinthefolder.png158717-wanttocreatefilesinotherfolders.png

Windows for business Windows Server User experience PowerShell
0 comments No comments
{count} votes

Accepted answer
  1. MotoX80 36,291 Reputation points
    2021-12-19T17:34:38.89+00:00

    No, no, no. You don't want to hardcode all of those New-Item's, that's what the ForEach loops are for.

    And you changed the directory structure. From: names like D:\Test\Directory7\1.txt where you asked how to replace the "7" with the numbers 1-6. Now you've got everything in folder1, with subfolders that are just a number.

    Look at this.

    1..7 | ForEach-Object {
        ""
        $Dir = "D:\Test\Directory{0}" -f $_
        $Dir                                             # Show the directory name 
    
        # Create the directory here. 
    
        1..10 | ForEach-Object {
           $File = "{0}\{1}.txt" -f $Dir, $_ 
           $File                                         # Show the file name
    
           # Create the file here 
    
        }    
    }
    

2 additional answers

Sort by: Most helpful
  1. MotoX80 36,291 Reputation points
    2021-12-19T15:44:05.657+00:00

    Is this homework? Because while I can write it for you, you will be better off if you write it yourself, even if you have to fumble through it. You will learn more.

    Hint: what is wrong with line 4? Compare it to line 9.

    Another hint: "dollar underscore" refers to the current foreach object. So, if you have 2 loops, you can't reference both "dollar underscore"'s at the same time. So you have to build the ..........


  2. Rich Matheisen 47,901 Reputation points
    2021-12-19T19:15:07.36+00:00

    Why not download this PDF (it's free) and work your way through its first half? Do the exercises. Once you've established an understanding of PowerShell you'll find doing something trivial (as you're trying to do) is a lot easier.

    Windows-PowerShell-4

    As to your last question, think about what you said: because we have provided objects as 1 to 10 before for each loop

    What do think will happen if you provided an array of ten subdirectory names instead?


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.