Are you working on a task that involves processing multiple files or a list of items? For instance, imagine you need to check connectivity to ten different websites. You can achieve this by utilizing PowerShell's `ForEach-Object` cmdlet to iterate through an array containing the website URLs. Here's a simple example to help you get started:
ping geauxitsystems.com
ping rubyred.media
ping scriptfreaks.com
But isn't there an easier way to get through this list? For our example, we only have three websites, but you would not want to update your code 100 times if you had hundreds of websites. Nor would you want to deal with this if you were doing more advanced work like port checking, organizing the data for validation, and other requirements.
So let's first convert our data into a variable. Organizing out data this way will make it easier for updating later. We will write this code so you can learn a little PowerShell secret called split.
# This will create the variable list.
$WebsiteListRaw = "geauxitsystems.com, rubyred.media, scriptfreaks.com"
# Now we will clean up this list so it can be used as an array. We will use "split"
$WebsiteList = $WebsiteListRaw =split(",")
Next, let's create our foreach code. The first variable we mentioned can be named anything you wish. We will call it CurrentWebsite for our example.
foreach($CurrentWebsite in $WebsiteList)
{ # Bracket for starting this snippit
ping $CurrentWebsite
} # Bracket for closing this snippit
Now the script will look at our array, in this case, our website list, and attempt to ping each server. Once it completes the ping test on one site, it will start pinging the next site until it is finished.
Komentar