SID-500

Home » PowerShell » PowerShell: Using Foreach-Object (Examples)

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.


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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

Categories

Who is the blogger?

My name is Patrick Grünauer (pewa2303). I am from Austria. On sid-500 I write about Windows, Cisco and IT-Security in English and German. Have fun while reading!

Patrick Gruenauer
Follow SID-500 on WordPress.com