Note: This is a non-credit bonus lab, with no direct marks assigned. However ...
remote systems to run scripts and cmdlets on your system. Every system that will
...
SRT210 – Bonus Lab PowerShell Scripting This lab looks at Windows Management Instrumentation, Remoting, Active Directory and Credential Management There is a lot of stuff here. Please read the commentary and instructions and work through all of the examples and exercises. Note: This is a non-credit bonus lab, with no direct marks assigned. However, concepts introduced and practised here are part of the curriculum and you will be tested on that knowledge. Please make sure to complete this lab before the Midterm Test.
Powershell Remoting and WMI We are going to look at some WMI scripting. None of the scripts will do any damage, as they will get information only. Also, we will look at how to remotely run commands on other computers. This latter topic will take up most of the lab. Before we get into more WMI stuff, let’s set up your systems to allow remote commands to be executed. We can then run WMI on local and remote systems.
Remote Functionalty When you initially installed PowerShell, you also installed WinRm (you did, didn’t you?). This service allows remote systems to run scripts and cmdlets on your system. Every system that will allow remote scripts to be executed must have WinRM. So, let’s assume you have it installed. If you don’t, go back to lab 1. NOTE: In order for remoting to work smoothly, all systems should be running the same version of Powershell and WinRm. By default, WinRM functionality is turned off. Here is how to get it going.
1) You need to open the non-graphical PowerShell shell as an Administrator. You can do this by right-clicking Powershell and selecting ‘Run as Administrator’.
2) At the command Prompt type ‘winrm quickconfig’ and press enter.
You see a confirmation that WinRm has been set up to automatically start. The next set is to allow the ‘listener’ to be activated and a firewall exception be established to allow remote scripts to executed on this computer.. Answer ‘Y’ when asked if you want to enable the ‘Remote Listener’ on this system.
1
The following illustration has all of the text for the setup of WinRM. By default, communication between client and remote systems is done through HTTP.
Checking the Setup PowerShell remoting works best on systems that are part of a domain. Domain systems have a higher level of security and authentication is easier to establish between systems. Workgroups are a bit trickier to work with. Below I’ve listed the steps required to configure two Workgroup machines so that
you can remotely access one from the other using PowerShell. The computer you’re sitting in front of is called the client machine, while the computer you’re trying to remotely access is called the server machine. Note: If you have a Domain set up, you will not have to go through all of this. Just make sure the Username and password of the admin accounts are the same on the systems you want to control). First, configure the server machine to allow access. To do this, open a PowerShell command prompt (be sure to run as Administrator) and run the following cmdlet:
2
Enable-PSRemoting –force Make sure that the password for your Administrator account is not empty! If it is, you won’t be able to log in remotely. Setting Up the Client Now you’ll need to configure your client machine. First you’ll have to enable WinRM local access so that you can modify the proper settings. To do this, start the WinRM service and enable the local account token filter policy (see this Microsoft support article for details on this machine-wide policy). Run these commands in an elevated PowerShell prompt: Note: Both of the following steps are unnecessary if you’ve already run the Enable-PSRemoting cmdlet on your client machine. They are here just in case you need to execute them manually. Start-Service WinRM Set-ItemProperty –Path KLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System –Name LocalAccountTokenFilterPolicy –Value 1
Now that WinRM local access is enabled, you’ll need to add the name of your server machine to the TrustedHosts setting in the WinRM configuration, which enables your client machine to connect to your server machine using an authentication mechanism that does not authenticate the server (like Kerberos does): Set-Item WSMan:\localhost\Client\TrustedHosts –Value -Force Note: This command replaces any previous value that was stored in TrustedHosts! If there is an existing list of servers and you don’t want to remove then, use the –Concatenate parameter to append the new name to the list.
Set-Item WSMan:\localhost\Client\TrustedHosts –Value -Force -Concatenate Note: You can use the ‘*’ wildcard to specify all computers. If you want to use your server machine’s IP address instead of its name, you must specify explicit credentials when you connect. A word of caution: by adding a server to the TrustedHosts list, you are allowing your credential information to be sent to a server without verifying its identity. Only add a server to this list if you know that the network path from your client machine to the server machine is secure. You should now be able to manage your server machine using PowerShell remoting! Just in case things don’t work out perfectly the first time, here are some useful commands to check on the relevant configuration settings.
3
Checking the Software Let’s run some tests to see if the remote functionality is working; To check if the WinRM service is running:
Get-Service WinRM
To check the version of WinRM that’s installed:
Test-WSMan –Auth default
To check the remoting configuration for PowerShell: To verify that local WinRM access is working:
Get-PSSessionConfiguration
New-PSSession
If it’s working, you should get output that looks like this PS C:\Users\Administrator> New-PSSession Id Name
ComputerName
State
Configuration
---- -- ----
- --------------------
-------
-------------
1 Session1
To check the WinRM listener settings:
localhost Opened Microsoft.PowerShell
winrm enumerate winrm/config/listener
For additional help and troubleshooting steps:
Get-Help about_remote_troubleshooting
Exercise 1 Using the ‘start-Transcript’ cmdlet, complete all of the above commands (except the get-help command). Make sure everything is working before you show it to your lab assistant.
Testing out a command OK, now that you have configured remoting, let’s try out a few things. First you will want to establish a connection to the remote server. In your client system,(using either the GUI or non-GUI shell) enter the following;
enter-pssession computername Note: Use the actual name of the computer you a connecting to. If you have trouble, try the IP address.
To get out of a session, type ‘Exit’. 4
Questions Before you executed this command, what did the Shell prompt show?
________________________________________________________________________ After executing the command, what did the prompt show? ________________________________________________________________________________
More stuff Let’s find out something about the network adapter, on the remote system. If you exited from the ‘PSSession’ then open a new session. On the client type the following
Get-process –computername RemoteComputerName Now try this Invoke-command –computername computer1 –scriptblock {Get-process}
Questions What, if any, difference(s) were there in the output of the two preceding remote commands? _____________________________________________________________________________________ A noticeable feature, when using these two commands, is that the ‘Invoke-command’ allows you to execute more complicated commands and scripts, inside the curly braces. Try this example;
Invoke-command –computername computer1 –scriptblock { $colItems = get-wmiobject -class "Win32_NetworkAdapterConfiguration" $colItems } The output should show the network adapter information of the remote system.
Exercise 2: The previous script received network adapter information from a remote system. This exercise asks you to read computer names from an array and execute the Invoke-command for each computer listed in the array. Use the computers you have on your system (local and virtual) or connect to the computer of another student (remote computer). Note: You may have to have your instructor switch to “POD MODE” as the Seneca firewall may black your attempts to access the other machine. 5
More WMI Let’s look at some more WMI objects, This is such an extensive topic, we can only scratch the surface.
Example: This script displays information on all of the network adapters in your system.
$netconfig = get-wmiobject Win32_NetworkAdapterConfiguration $Netconfig There is a filter (-filter) option available when using get-wmiobject Win32_NetworkAdapterConfiguration. To limit the output to only those adapters that have an IP address This script displays information on all of the network adapters in your system. There is a filter (-filter) option available when using get-wmiobject Win32_NetworkAdapterConfiguration. This script returns the list of network adapters that are IP Enabled.
$netconfig = get-wmiobject Win32_NetworkAdapterConfiguration -filter ` “IPEnabled = True”
$netconfig Try executing it as a remote command.
Example: Here is an interesting script. It employs the WIN32_PingStatus class. This object returns values from the normal Ping operation.
$i =1 $Ip = "192.168.0." Write-Host "IP Address" Write-Host "----------------------------------------" Do { $Ip4th = $Ip + $i $Pingstat = get-WmiObject Win32_PingStatus -f "Address='$Ip4th'" if($Pingstat.StatusCode -eq 0) { "{0,0} {1,5} {2,5}" -f $Pingstat.Address, $Pingstat.StatusCode," IP address is being used"} else {"{0,0} {1,5} {2,5}" -f $Pingstat.Address, $Pingstat.StatusCode, " xxxxxxxxx" } $i++ } until ($i -eq 20)
Breaking down the script: 6
Line 5 – This is the start of a Do...Until loop. At each cycle, the variable $lp4th has the IP address increased by 1 Line 6 – Ping the IP address in $lp4th and assign values to $Pingstat Line 7 – Test the Ping values to see if the status code = 0 (valid IP address) Line 8 – Just some output formatting Line 9 – Output the data using the Address and Statuscode properties of W32_PinStatus Line 15 – Stop Loop when it reaches 20 IP addresses.
Exercise 3 The script outputs all IP addresses in a range. Change the script so that it only outputs IP addresses that do not respond to a PING. Submit the exercise.
Something to play with First make sure you do not have anything open on your system that you want to save. If so, save it now. You are about to restart your local computer. It’s very simple to do (if you don’t want to, use –whatif)
Restart-Computer Now, let’s restart a remote system
Restart-Computer –computername computer1 Note: Your remote command may not work if someone if logged into the system. You can try the -force option to override this.
Restart-Computer –computername computer1 -force
To restart multiple systems restart-computer -computername Computer1, Computer2, Computer3
Play with this one $j = restart-computer -computername Server01, Server02 -asjob $results = $j | receive-job $results
7
Understanding how to remotely manage a server is essential to all administrators. Often, servers are not physically at the same location or there are too many servers to handle individually. Therefore, having the ability to remotely manage, configure and receive data from server is a real timesaver for IT staff. In general, the commands/scripts you would run against a local machines are basically the same as you would use when dealing with remote systems. This lab will allow you to play with a series of operations that an administrator could use.
Let’s start out with the local Firewall. Before contacting the Server firewall, you have to create a new object that will interact with the ‘Firewall Manager’. This .com object is called HNetCfg.FWMgr.
$fwmgr = (new-object -com hnetcfg.fwmgr) Once created, this Object will allow you to connect to and interact with the Firewall. Before doing that, let’s look at all of the available properties and methods for the firewall manager. $fwmgr = (new-object -com hnetcfg.fwmgr) $fwmgr | get-member OK, now let’s check to see if the Firewall is enabled.
$fwmgr = (new-object -com hnetcfg.fwmgr).localpolicy.currentprofile If ($fwmgr.Firewallenabled –eq $true) { Write-Host “Firewall is on” –fore “green” }else{ Write-host “Firewall is off” –fore “red” } Running this remotely is just a matter of ‘Invoking’ the script.
Invoke-command –computername -scriptblock { $fwmgr = (new-object -com hnetcfg.fwmgr).localpolicy.currentprofile If ($fwmgr.Firewallenabled –eq $true) { Write-Host “Firewall is on” –fore “green” }else{ Write-host “Firewall is off” –fore “red” } }
Exercise 4 Using the servers that you have installed on your hard-drive, create a text file with each computer name on a separate line. Save this file. Now create a script that will read this file and execute the above script for each computer. Make sure your output places the computer name next to the Firewall status.
8
Turning on The Firewall Turn It on First, manually turn off the firewall and run this script $fwmgr = (New-Object –Com HnetCfg.FwMgr) $fwmgr.LocalPolicy.CurrentProfile.FirewallEnabled = $True
NOTE: If you have software installed that is designed to prevent exactly what we are trying to do, you would have to turn it off. If you get a message that a program is trying to mess with your firewall, at least you know the security works.
$fwmgr = (New-Object –Com HnetCfg.FwMgr) $fwmgr.LocalPolicy.CurrentProfile.RemoteAdminSettings.Enabled = $False Note: The Firewall does not like to be turned off so you will get an error.
And More Firewall Stuff Ever wonder which programs have been given exception status through your firewall. It would be nice to know if software is getting through your server’s firewall. Here is a function that will report these privileged programs.
$fw = (new-object -com HNetCfg.FwMgr) $profile = $fw.LocalPolicy.CurrentProfile $profile.GloballyOpenPorts | ft name, port $profile.AuthorizedApplications | ? {$_.Enabled} | ft name Note: There may not be any applications to report, as none have been authorized on your system. You can test this by going to your server firewall settings and adding, for example, Internet explorer as an authorized application. Then run the script again
Running this function remotely is easy with Invoke-command.
Invoke-command –computername server2008beta –scriptblock { $fw = (new-object -com HNetCfg.FwMgr) $profile = $fw.LocalPolicy.CurrentProfile $profile.GloballyOpenPorts | ft name, port $profile.AuthorizedApplications | ? {$_.Enabled} | ft name }
Active Directory 9
PowerShell can interact directly with Active Directory reading into its database, extracting information and displaying it for you. For example, with the following cmdlet, you can display all users that have logged in least once. This will just be a taste of Active directory scripting.
$strFilter = "(&(objectCategory=User)(logonCount>=1))" $objDomain = New-Object System.DirectoryServices.DirectoryEntry $objSearcher = New-Object System.DirectoryServices.DirectorySearcher $objSearcher.SearchRoot = $objDomain $objSearcher.PageSize = 1000 $objSearcher.Filter = $strFilter
Try changing the ‘logonCount’ to