You can use the Foreach-Object Cmdlet to loop through items. In this post I demonstrate several practical examples, from the bulk import of users to the creation of dummy files with fsutil and more.
Example 1 – Write Host
1,2,3 | Foreach-Object {Write-Host $_}
By using a pipe (|) the values (1,2,3) are passed to the Foreach-Object command and Write-Host is used to output the values. $_ is a special variable which processes any value that is passed through the pipe.
Example 2 – Create Dummyfiles
1..20 | ForEach-Object {fsutil file createnew c:\temp\file$_.txt (Get-Random -Maximum 100)}
In this example, 20 dummy files are created using fsutil. These dummy files are of different size with a maximum of 100 bytes.
Example 3 – Add multiple local users
1..10 | Foreach-Object {net user Student$_ 'Pa$$w0rd' /add}
10 users with the name Student1 to Student10 are created. The password for all students is Pa$$w000rd.
Categories: PowerShell
1 reply »