PowerShell: Writing your first script
Archived image unavailable: ps.JPG
So let's write a simple script in PowerShell to do the following:
- List network adapters
- Present the user with a choice to select one
- Display information about the selected adapter
Open up the PowerShell ISE as administrator. Then start with this following line:
$adapterList = Get-WMIObject Win32_NetworkAdapter
What this line does is creates an array (if there is more than one network adapter on your machine) of network adapters. If you were to run the command $adapterList it would simply step through this array.
Next let's set the variable $i to 0 by putting:
$i = 0
This is helpful for the next portion of our script which will be a foreach loop to step through each element of the array $adapterList.
Now write the following lines:
foreach ($adapter in $adapterList) {
Now the Write-Host lines simply display the string in quotes that you type. The -fore parameters specifies the color of the text.
The foreach loop starts with foreach ($adapter in $adapterList) {.
What that does is says foreach of the elements, do this for each element. The variable $adapter can be anything you specify, it merely represents that element of the array.
Each an element is there, it displays that element to that host with the value of $i placed before it. We set $i to zero since the array starts with 0. Then we use $i++ to increment $i by 1 so the next element will be 1, the one after that 2, and so on.
Now let's collect the # the user wants to see information on. Write the following line:
$adapterSel = Read-Host "Please select the [#] of the adapter you'd like information on."
Write the followings lines:
if ($adapterSel) {
What this does is says if the variable $adapterSel exists, do the following {.
Then we use Write-Host to display the lines of text as seen above. $adapterList[$adapterSel].Name displays the name of the adapter. Be sure you not how the quotes are used.
Then the final command is Get-WMIObject -Class Win32_NetworkAdapterConfiguration -filter "Index=$adapterIndex". To fun the script press F5 in the ISE, or if you'd like to save the script and run it save it as c:\net.ps1.
Open PowerShell as administrator and use this command if you've never run scripts locally before:
Set-ExecutionPolicy RemoteSigned
Once you set that (which states to allow you to run local scripts, but if they are "remote" or downloaded from the internet, require them to be digitally signed), type:
Set-Location C:\
.\net.ps1
The script should run, allow you to select an adapter, and then once selected, display information.
Archived image unavailable: ps1.PNG
That's what's awesome about PowerShell, lots of ways to do things and all in the name of making it easier once you have a script in place. Please email me if you have any questions or suggestions for this blog.
Comments
No comments yet. Be the first!