Saturday, February 19, 2011

What can I do ... part11 System Administration Tasks

System Administration Tasks


The following articles provide a brief introduction to carrying out system administration tasks by using Windows PowerShell; these tasks include such things as starting and stopping services, retrieving data using WMI, and managing event logs and event log events. As is so often the case with Windows PowerShell, the code snippets found in these articles can either be included within a Windows PowerShell script or typed directly into the Windows PowerShell console.

Using the Get-Service Cmdlet

Listing Service Information

This will probably shock you, but - just in case - you better sit down: the Get-Service cmdlet is designed to retrieve information about the services installed on your computer. (And to think that some people say Windows PowerShell is too complicated!) Do you want information about all the services installed on your computer? Then just call Get-Service without any additional parameters:
Get-Service
Here’s the kind of information you’ll get back:
Status   Name               DisplayName
------   ----               -----------
Running  AdobeActiveFile... Adobe Active File Monitor V4
Stopped  Alerter            Alerter
Running  ALG                Application Layer Gateway Service
Stopped  AppMgmt            Application Management
Running  ASChannel          Local Communication Channel
Alternatively, you can take advantage of the Windows PowerShell filtering capabilities to return just a subset of the services installed on your computer. For example, this command takes the data returned by Get-Service and pipes it through the Where-Object cmdlet. In turn, Where-Object filters out everything except those services that are stopped:
Get-Service | Where-Object {$_.status -eq "stopped"}
In the preceding command, the $_. represents the object passed across the pipeline (that is, the collection of services and their properties), while status is simply the service property we want to filter on. And because we’re interested only in services that are stopped, we use the syntax -eq “stopped”. What if we were interested only in services that were running? In that case, we’d use this command:
Get-Service | Where-Object {$_.status -eq "running"}
So what kind of data will we get back when we request only services that are currently stopped? This kind of data:
Status   Name               DisplayName
------   ----               -----------
Stopped  Alerter            Alerter
Stopped  AppMgmt            Application Management
Stopped  aspnet_state       ASP.NET State Service
Stopped  BITS               Background Intelligent Transfer Ser...
Stopped  Browser            Computer Browser
By default Windows PowerShell returns services sorted in alphabetical order. By using the Sort-Object cmdlet, however, you can sort that returned data any way you want. For example, this command sorts services first by Status, and then by DisplayName:
Get-Service | Sort-Object status,displayname
Get-Service Aliases
  • gsv

Using the Get-Eventlog Cmdlet

Managing Event Logs and Event Log Events

The Get-EventLog cmdlet actually serves two purposes: it enables you to manage your event logs, and it also enables you to get at the events contained within those event logs.
For example, suppose you’d like some basic information about the event logs on your computer. In that case, make sure you include the -list parameter when calling Get-EventLog:
Get-EventLog -list
In return, you’ll get back information similar to this:
Max(K) Retain OverflowAction        Entries Name
  ------ ------ --------------        ------- ----
  15,168      0 OverwriteAsNeeded       5,279 Application
     512      7 OverwriteOlder            145 Credential Manager
     512      7 OverwriteOlder             12 MNP Toc Editor
  15,360      0 OverwriteAsNeeded          88 MonadLog
  15,360      0 OverwriteAsNeeded         324 PowerShell
  30,016      0 OverwriteAsNeeded      51,510 Security
  15,168      0 OverwriteAsNeeded       6,457 System
If you only want information about a specific event log then use the Where-Object cmdlet to limit data retrieval to the log whose LogDisplayName is equal to, say, System:
Get-EventLog -list | Where-Object {$_.logdisplayname -eq "System"}
As you can see, all you’ll get back is information about the System event log:
Max(K) Retain OverflowAction        Entries Name
  ------ ------ --------------        ------- ----
  15,168      0 OverwriteAsNeeded       6,458 System
But that’s just the beginning; as we noted, you can also use Get-EventLog to look at the events in your event log. For example, this command retrieves all the events in the System event log:
Get-EventLog system
That’s going to result in (depending on the number of records in your event log) a long scrolling list similar to this:
Windows PowerShell
More information than you really wanted, or needed? Then use the -newest parameter, and get back only the last x number of events recorded in the log. For example, this command retrieves the last three events written to the System event log:
Get-EventLog system -newest 3
Here’s the kind of data you’ll get back:
Index Time          Type Source                EventID Message
----- ----          ---- ------                ------- -------
 5811 May 13 09:42  Erro W32Time                    29 The time provider Ntp...
 5810 May 13 09:42  Warn W32Time                    14 The time provider Ntp...
 5809 May 13 09:13  Warn DnsApi                  11194 The system failed to ...
To get more detailed information, just pipe the returned data through the Format-List cmdlet:
Get-EventLog system -newest 3 | Format-List
That will bring back information like this:
Index              : 5811
EntryType          : Error
EventID            : 29
Message            : The time provider NtpClient is configured to acquire time from one or more
                     time sources, however none of the sources are currently accessible.
                     No attempt to contact a source will be made for 59 minutes.
                     NtpClient has no source of accurate time.
Category           : (0)
CategoryNumber     : 0
ReplacementStrings : {59}
Source             : W32Time
TimeGenerated      : 5/13/2006 9:42:22 AM
TimeWritten        : 5/13/2006 9:42:22 AM
You can also pipe data through the Where-Object cmdlet to return a subset of events. For example, this command retrieves only those events in the Windows PowerShell event log that have an EventID equal to 403:
Get-EventLog "Windows PowerShell" | Where-Object {$_.EventID -eq 403}
As you might expect, all we get back are events with an EventID equal to 403:
Index Time          Type Source                EventID Message
----- ----          ---- ------                ------- -------
   58 May 12 09:09  Info Windows PowerShell                403 Engine state is chang...
   34 May 10 15:39  Info Windows PowerShell                403 Engine state is chang...
   16 May 09 15:28  Info Windows PowerShell                403 Engine state is chang...
Here’s a nifty little command, one that retrieves all the events in the Windows PowerShell event log, then uses the Group-Object cmdlet to group those events by EventID. In other words, the command tallies up the total number of events for each ID (for example, two events with the EventID 300 occurred, six events with the EventID 400 occurred, etc.). That data is then piped through the Sort-Object cmdlet to provide results sorted by EventID. Here’s the command:
Get-EventLog "Windows PowerShell" | Group-Object eventid | Sort-Object Name
And here’s the results of running that command:
Count Name                      Group
----- ----                      -----
    2 300                       {TVSFRANK, TVSFRANK}
    6 400                       {TVSFRANK, TVSFRANK, TVSFRANK, TVSFRANK...}
    3 403                       {TVSFRANK, TVSFRANK, TVSFRANK}
   42 600                       {TVSFRANK, TVSFRANK, TVSFRANK, TVSFRANK...}
   21 601                       {TVSFRANK, TVSFRANK, TVSFRANK, TVSFRANK...}


Using the Set-Service Cmdlet

Modifying the Properties of a Service

What can you do with the Set-Service cmdlet? We’re glad you asked. Set-Service provides a way for you to change the Description, StartupType, or DisplayName of a service. All you have to do is call Set-Service, followed by the name of the service you’d like to modify and the appropriate parameter (-description, -startup, -displayname). For example, this command changes the start mode for the ClipBook service to Manual:
Set-Service clipsrv -startuptype "manual"
Note. Other valid settings for StartupType are Automatic and Disabled.
This command changes the description of the ATI HotKey Poller service:
Set-Service "ati hotkey poller" -description "This is ATI HotKey Poller service."
As you can see, Windows PowerShell makes it possible for you to change the description; however, it doesn’t guarantee that you’ll come up with a good description!


Using the Resume-Service Cmdlet

Resuming a Paused Service

The Resume-Service cmdlet is used for resuming a service that is currently paused. (What’s the difference between a paused service and a stopped service? A stopped service drops all existing connections and refuses to take any new connections. A paused service will typically continue to service existing connections, but will not accept any new connections.)
To resume a paused service call Resume-Service followed by the service name (that is, the name of the service as stored in the registry):
Resume-Service tapisrv
Alternatively, you can add the -displayname parameter and resume the service using the service display name, the name that appears in the Services snap-in:
Resume-Service -displayname "telephony"

Using the Get-WMiObject Cmdlet

Retrieving Data Using WMI

At this point in time there are only a few cmdlets (Get-Process, Get-Service, and Get-EventLog) designed for carrying out system administration tasks. Because of that, WMI remains the primary automation technology for system administration, so system administrators will likely rely heavily on Get-WmiObject to help them with their routine management tasks.
And there’s an added bonus, too: unlike most cmdlets, Get-WmiObject can be run against remote computers. That means you really can use Windows PowerShell as a management tool.
By default, Get-WmiObject binds to the root\cimv2 namespace on the local computer, making it extremely easy to return property values for any class found in cimv2. For example, suppose you need information from the Win32_BIOS class. OK:
Get-WmiObject win32_bios
You get the idea: just call Get-WmiObject followed by the class name. Ah, you say, but what if that class is located on a remote computer? No problem; just add the -computername parameter followed by - you guessed it - the name of the remote computer (atl-fs-01):
Get-WmiObject win32_bios -computername atl-fs-01
Still not convinced? Good point: we did say that, by default, Get-WmiObject connects to the root\cimv2 namespace. Is there any way to connect to a class found in a different namespace? Of course there is: just include the -namespace parameter followed by the complete namespace path (e.g., root\ccm, not just ccm). For example, this command returns information from the SMS_Client class, which resides in the root\ccm namespace:
Get-WmiObject -namespace root\ccm -class sms_client -computername atl-fs-01
It should go without saying that you can use other cmdlets in conjunction with Get-WmiObject (although we seem to have said it anyway). For example, this command retrieves information from the CCM_InstalledComponent class on the remote computer atl-fs-01. The command then pipes that data to Select-Object, which filters out all properties except three: DisplayName, Name, and Version. In turn, that filtered data is passed to Sort-Object, which sorts the information by DisplayName. Here’s what the command looks like:
get-wmiobject -namespace root\ccm -class ccm_installedcomponent -computername atl-fs-01 | Select-Object displayname,name,version | Sort-Object displayname
And here’s the kind of data you get back:
displayname                name                       version
-----------                ----                       -------
CCM Framework              CcmFramework               2.50.4160.2000
CCM Policy Agent           CcmPolicyAgent             2.50.4160.2000
CCM Status Agent           CcmStatusAgent             2.50.4160.2000
SMS Client Core Components SmsClient                  2.50.4160.2000
SMS Inventory Agent        SmsInventory               2.50.4160.2000
SMS Remote Control Agent   SmsRemoteTools             2.50.4160.2000
SMS Shared Components      SmsCommon                  2.50.4160.2000
SMS Software Distributi... SmsSoftwareDistribution    2.50.4160.2000
SMS Software Metering A... SmsSoftwareMetering        2.50.4160.2000
SMS Software Update Agent  SmsSoftwareUpdate          2.50.4160.2000
SMS Source List Update ... SmsSourceUpdateAgent       2.50.4160.2000
On the other hand, there will likely be times when you don’t want a filtered set of properties and their values; instead, you’d just like to see everything Win32_BIOS has to offer. To ensure that you get back information on all the properties (and their values) your best bet is to pipe the data returned by Get-WmiObject to Select-Object, then use the wildcard character * to indicate that you want back all the property values:
Set-WmiObject win32_bios | Select-Object *
If you don’t want all the system properties (like __SUPERCLASS and __RELPATH) then add the -excludeproperty parameter and use the wildcard character to filter out any properties whose name begins with an underscore character:
Get-WmiObject win32_bios | Select-Object -excludeproperty "_*"
Bonus tip. WMI itself is actually pretty easy to use; what isn’t always so easy is figuring out the properties and methods for a specific WMI class. Check that: that’s what used to be difficult. With Windows PowerShell you can simply use Get-WmiObject to connect to the class in question (for example, Win32_BIOS), and then pipe that information through the Get-Member cmdlet:
Get-WmiObject win32_bios | get-member
And what will that do for you? That will show you the properties and methods of Win32_BIOS, including:
BiosCharacteristics       Property              System.UInt16[] BiosCharacte...
BIOSVersion               Property              System.String[] BIOSVersion ...
BuildNumber               Property              System.String BuildNumber {g...
Etc.
Get-WmiObject Aliases
  • gwmi

Using the Get-Process Cmdlet

Retrieving Process Information

The Get-Process cmdlet provides a quick and easy way to retrieve information about the processes running on your computer. To get a quick overview of all the processes currently running on your machine simply call Get-Process without any parameters:
Get-Process
By default, you’ll get back data similar to this:
Windows PowerShell
Believe it or not, that’s all it takes. Only interested in the instances of Microsoft Word that are running on your computer? Then call Get-Process followed by the executable file name (without the file extension). In other words:
Get-Process winword
That results in output similar to this:
Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
-------  ------    -----      ----- -----   ------     -- -----------
    565      25    48760      77744   537   241.34   3116 WINWORD
Want to get back more than one process? Then just specify more than one executable name, separating the names with commas:
Get-Process winword,explorer
This time around your output will return information about both Word and Windows Explorer:
Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
-------  ------    -----      ----- -----   ------     -- -----------
    497      16    18524      28264    96     8.30   1080 explorer
    565      25    48760      77744   537   241.34   3116 WINWORD
Alternatively, you can use a wildcards to retrieve information about, say, all the running processes whose executable file name starts with the letter w:
Get-Process w*
With this command you get back pretty much what you’d expect to get back:
Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
-------  ------    -----      ----- -----   ------     -- -----------
     65       2     1628       1836    15     0.03   2024 wdfmgr
    557      65     8184       3824    57     1.06   1220 winlogon
    569      26    48748      77912   542   282.86   3116 WINWORD
    149       4     2024       5288    37     0.17    808 wmiprvse
     48       2      916       3404    29     0.06   2820 WZQKPICK
Although the functionality of the Get-Process cmdlet overlaps with the functionality of the WMI class Win32_Process, Get-Process can retrieve additional information not exposed through WMI, including properties such as company, file version, and product version. For example, this command pipes Get-Process through the Select-Object cmdlet, filtering out everything except the process name and the properties just mentioned:
Get-Process | Select-Object name,fileversion,productversion,company
Here’s the kind of information you can expect to get back:
Name                FileVersion         ProductVersion      Company
----                -----------         --------------      -------
alg                 5.1.2600.2180 (x... 5.1.2600.2180       Microsoft Corpor...
apdproxy            3.0.0.53237         3.0.0.53237         Adobe Systems In...
asghost             1.5.0.035           1.5                 Cognizance Corpo...
ati2evxx            6.14.10.4118        6.14.10.4118.02     ATI Technologies...
Note. Because of the length of some of these property values, you might want to pipe the output through the Format-List cmdlet.
So how do you know which process properties are available through Get-Process? Probably the easiest way to determine that is to simply call Get-Process and then pipe the returned information through the Get-Member cmdlet:
Get-Process | Get-Member
That will return a list of all of the cmdlet’s properties and methods.
Get-Process Aliases
  • gps
  • ps

Using the Stop-Service Cmdlet

Stopping a Running Service

The Stop-Service cmdlet is used for stopping a service that is currently running. To stop a service, simply call Stop-Service followed by the service name (that is, the name of the service as stored in the registry):
Stop-Service btwdins
Alternatively, you can add the -displayname parameter and stop the service using the service display name, the name that appears in the Services snap-in:
Stop-Service -displayname "Bluetooth service"
Stop-Service Aliases
  • spsv
Using the Start-Service Cmdlet

Starting a Stopped Service

The Start-Service cmdlet is used for starting a service that is currently stopped. To start a service, simply call Start-Service followed by the service name (that is, the name of the service as stored in the registry):
Start-Service btwdins
Alternatively, you can add the -displayname parameter and start the service using the service display name, the name that appears in the Services snap-in:
Start-Service -displayname "Bluetooth service"
Start-Service Aliases
  • sasv
Using the Stop-Process Cmdlet

Terminating a Process

Stop-Process enables you to terminate a process (or processes). You can indicate the processes you want to kill either by specifying the process ID or by specifying the process name. For example, this command stops the process with the process ID 3512:
Stop-Process 3512
To stop a process by process name, use the -processname parameter followed by the process name (minus the file extension). For example, to terminate all instances of Notepad use this command:
Stop-Process -processname notepad
And, yes, Stop-Process accepts wildcard characters, too. For example, this command terminates any instances of Notepad, as well as any other processes whose names start with note:
Stop-Process -processname note*
Stop-Process Aliases
  • spps
  • kill

No comments:

Post a Comment