PowerShell

PowerShell: Using Foreach-Object (Examples)

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 $_}

10.PNG

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)}

1.PNG

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}

2.PNG

10 users with the name Student1 to Student10 are created. The password for all students is Pa$$w000rd.

Categories: PowerShell

Tagged as: ,

1 reply »

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.