Windows Server 2008 R2 Unleashed (147 page)

Cmdlet Clear-Item Clear-Item [-Path]

Cmdlet Clear-ItemProperty Clear-ItemProperty [-Path] <...

Cmdlet Clear-Variable Clear-Variable [-Name]

Cmdlet Compare-Object Compare-Object [-ReferenceOb...

...

PS C:\>

Next, to retrieve basic information about a particular cmdlet, you would then include that

cmdlet’s name and argument. For example:

ptg

PS C:\> Get-Command Get-Process

CommandType Name Definition

----------- ---- ----------

Cmdlet Get-Process Get-Process [[-Name]

PS C:\>

The Get-Command cmdlet is more powerful than Get-Help because it lists all available

commands (cmdlets, scripts, aliases, functions, and native applications) in a PowerShell

session, as shown in this example:

PS C:\> get-command note*

CommandType Name Definition

----------- ---- ----------

Application NOTEPAD.EXE C:\WINDOWS\NOTEPAD.EXE

Application notepad.exe C:\WINDOWS\system32\notepad.exe

PS C:\>

When using Get-Command with elements other than cmdlets, the information returned

is a little different from information you see for a cmdlet. For example, with an existing

736

CHAPTER 21

Automating Tasks Using PowerShell Scripting

application, the value of the Definition property is the path to the application. However,

other information about the application is also available, as shown here:

PS C:\> get-command ipconfig | format-list *

FileVersionInfo : File: C:\WINDOWS\system32\ipconfig.exe

InternalName: ipconfig.exe

OriginalFilename: ipconfig.exe

FileVersion: 5.1.2600.2180 (xpsp_sp2_rtm.040803-2158)

FileDescription: IP Configuration Utility

Product: Microsoftr Windowsr Operating System

ProductVersion: 5.1.2600.2180

Debug: False

Patched: False

PreRelease: False

PrivateBuild: False

SpecialBuild: False

Language: English (United States)

Path : C:\WINDOWS\system32\ipconfig.exe

Extension : .exe

ptg

Definition : C:\WINDOWS\system32\ipconfig.exe

Name : ipconfig.exe

CommandType : Application

With a function, the Definition property is the body of the function:

PS C:\> get-command Prompt

CommandType Name Definition

----------- ---- ----------

Function prompt Write-Host (“PS “ + $(Get-Lo...

PS C:\>

With an alias, the Definition property is the aliased command:

PS C:\> get-command write

CommandType Name Definition

----------- ---- ----------

Alias write Write-Output

PS C:\>

With a script file, the Definition property is the path to the script. With a non-PowerShell

script (such as a .bat or .vbs file), the information returned is the same as other existing

applications.

Using Windows PowerShell

737

Managing Services

21

In PowerShell, a number of cmdlets can be used to manage services on a local machine. A

list of these cmdlets is as follows:

.
Get-Service—
Used to gather service information from Windows.

.
New-Service—
Used to create a new service in Windows.

.
Restart-Service—
Used to restart services.

.
Resume-Service—
Used to resume suspended services.

.
Set-Service—
Used to modify service configurations.

.
Start-Service—
Used to start services.

.
Stop-Service—
Used to stop services.

.
Suspend-Service—
Used to suspend services.

Getting Service Information

When the Get-Service cmdlet is executed, it returns a collection of objects that contains

information about all the services that are present on a Windows system. A representation

of that object collection is then outputted into a formatted table, as shown in the follow-

ptg

ing example:

PS C:\> get-service

Status Name DisplayName

------ ---- -----------

Running AeLookupSvc Application Experience

Stopped ALG Application Layer Gateway Service

Running AppHostSvc Application Host Helper Service

Stopped Appinfo Application Information

Stopped AppMgmt Application Management

Stopped aspnet_state ASP.NET State Service

Stopped AudioEndpointBu... Windows Audio Endpoint Builder

Stopped AudioSrv Windows Audio

...

To filter the information returned based on the service status, the object collection can be

piped to the Where-Object cmdlet, as shown in the following example:

PS C:\> get-service | where-object {$_.Status -eq “Stopped”}

Status Name DisplayName

------ ---- -----------

Stopped ALG Application Layer Gateway Service

Stopped Appinfo Application Information

738

CHAPTER 21

Automating Tasks Using PowerShell Scripting

Stopped AppMgmt Application Management

Stopped aspnet_state ASP.NET State Service

Stopped AudioEndpointBu... Windows Audio Endpoint Builder

Stopped AudioSrv Windows Audio

...

As shown in the preceding example, the Where-Object object cmdlet is used in conjunc-

tion with a code block {...}, which is executed as the filter. In this case, the code block

contained an expression that filtered the object collection based on services that were

“Stopped.” The same type of logic can also be applied to return information about a

particular service. For example:

PS C:\> get-service | where-object {$_.Name -eq “DNS”} | fl

Name : DNS

DisplayName : DNS Server

Status : Running

DependentServices : {}

ServicesDependedOn : {Afd, Tcpip, RpcSs, NTDS}

ptg

CanPauseAndContinue : True

CanShutdown : True

CanStop : True

ServiceType : Win32OwnProcess

PS C:\>

In the preceding example, the object collection from the Get-Service cmdlet is piped to

the Where-Object cmdlet. The filter statement defined script block then instructs the

Where-Object cmdlet to return an object for the DNS service. The object that is returned

by this cmdlet is then piped to the Format-List cmdlet, which writes a formatted list

(containing information about the object) back to the console session.

NOTE

A shorter method for performing the preceding action is to use the name switch, as

shown in the following command: get-service –name DNS.

Managing Service Statuses

To stop a service in PowerShell, the Stop-Service cmdlet is used, as shown in this example:

PS C:\> stop-service -name dns

Using Windows PowerShell

739

Notice that when the cmdlet has finished executing, no status information about the

service’s status is returned. To gather that information, the passthru switch parameter can

21

be used to pass the object created by a cmdlet through to the pipeline. For example:

PS C:\> start-service -name dns -pass | ft

Status Name DisplayName

------ ---- -----------

Running DNS DNS Server

In the preceding example, the passthru switch parameter is used in conjunction with the

Start-Service cmdlet. When the cmdlet has finished executing, thus starting the DNS

service, the object is piped to the Format-Table cmdlet, which then displays status infor-

mation about the DNS service.

Modifying Services

The Set-Service cmdlet is used to change a service’s properties (such as its description,

display name, and start mode). To use this cmdlet, either pass it a service object or specify

the name of the service to be modified, plus the property to be modified. For example, to

modify the startup type of the DNS service, use the following command:

ptg

PS C:\> set-service -name DNS -start “manual”

A startup type can be defined as Automatic, Manual, or Disabled. To change a service’s

description, a command might look as follows:

PS C:\> set-service -name DNS -description “My Important DNS Service”

NOTE

The service management cmdlets in PowerShell are not end-alls for managing Windows

services. There are a number of areas in which these cmdlets are lacking—for example,

not being able to define a service’s logon account or report on its startup type. Luckily,

if a more in-depth interface is needed, an administrator can always fall back onto WMI.

Gathering Event Log Information

In PowerShell, the Get-EventLog cmdlet can be used to gather information from a Windows

event log and list the event logs that are present on a system. To gather event log informa-

tion, the name of the event log must be specified, as shown in the following example:

PS C:\> get-eventlog -logname application

740

CHAPTER 21

Automating Tasks Using PowerShell Scripting

Index Time Type Source EventID Message

----- ---- ---- ------ ------- -------

1778 Oct 05 19:44 Info MSExchangeFBPublish 8280 When initializing ses...

1777 Oct 05 19:38 Info MSExchangeIS 9826 Starting from 10/5/20...

1776 Oct 05 19:38 Info MSExchange ADAccess 2080 Process MSEXCHANGEADT...

1775 Oct 05 19:16 Info MSExchange ADAccess 2080 Process MAD.EXE (PID=...

...

To create a list of all the event logs on the local system, use the list switch parameter, as

shown in the following command:

PS C:\> get-eventlog -list

Max(K) Retain OverflowAction Entries Name

------ ------ -------------- ------- ----

20,480 0 OverwriteAsNeeded 1,778 Application

15,168 0 OverwriteAsNeeded 44 DFS Replication

512 0 OverwriteAsNeeded 1,826 Directory Service

16,384 0 OverwriteAsNeeded 38 DNS Server

20,480 0 OverwriteAsNeeded 0 Hardware Events

ptg

512 7 OverwriteOlder 0 Internet Explorer

20,480 0 OverwriteAsNeeded 0 Key Management Service

512 7 OverwriteOlder 155 PowerShell

131,072 0 OverwriteAsNeeded 9,596 Security

20,480 0 OverwriteAsNeeded 3,986 System

15,360 0 OverwriteAsNeeded 278 Windows PowerShell

PS C:\>

To gather in-depth information about a particular set of events or event, the information

returned from the Get-EventLog cmdlet can be further filtered. For example:

PS C:\> $Errors = get-eventLog -logname application | where {$_.eventid -eq 8196}

PS C:\> $Errors[0] | fl -Property *

EventID : 8196

MachineName : dc01.companyabc.com

Data : {}

Index : 1772

Category : (0)

CategoryNumber : 0

EntryType : Information

Message : License Activation Scheduler (SLUINotify.dll) was not able

to automatically activate. Error code:

0x8007232B

Using Windows PowerShell

741

Source : Software Protection Platform Service

ReplacementStrings : {0x8007232B}

21

InstanceId : 1073750020

TimeGenerated : 10/5/2009 6:56:36 PM

TimeWritten : 10/5/2009 6:56:36 PM

UserName :

Site :

Container :

PS C:\>

In the preceding example, the Get-EventLog cmdlet is used in conjunction with the

Where-Object cmdlet to create a collection of objects that all have an EventID equal to

8196. This collection is then defined as the variable $Errors. In the next command, the

first object in the $Errors variable is passed to the Format-List cmdlet, which then writes

a list of all the object’s properties to the console.

Managing the Files and Directories

As mentioned earlier in this chapter, specifically in the section “Providers and Drives,” a

set of core cmdlets can be used to access and manipulate PowerShell data stores. Because

ptg

the Windows file system is just another PowerShell data store, it is accessed through the

FileSystem provider. Each mounted drive or defined location is represented by a PSDrive

and can be managed by using the core cmdlets. Details about how these core cmdlets are

used are discussed in the following sections.

Listing Directories of Files

In PowerShell, you can use several cmdlets to explore the file system. The first cmdlet,

Get-Location, is used to display the current working location:

PS C:\> get-location

Path

Other books

Trial by Fury (9780061754715) by Jance, Judith A.
El amor en los tiempos del cólera by Grabriel García Márquez
Blue Skies by Helen Hodgman
Poe shadow by Matthew Pearl
Freelancer by Jake Lingwall
Yaccub's Curse by Wrath James White