Viewing Object Structure (Get-Member)

07/25/2009

Because objects play such a central role in Windows PowerShell, there are several native commands designed to work with arbitrary object types. The most important one is the Get-Member command.

The simplest technique for analyzing the objects that a command returns is to pipe the output of that command to the Get-Member cmdlet. The Get-Member cmdlet shows you the formal name of the object type and a complete listing of its members. The number of elements that are returned can sometimes be overwhelming. For example, a process object can have over 100 members.

To see all of the members of a Process object and page the output so you can view all of it, type:

PS> Get-Process | Get-Member | Out-Host -Paging

The output from this command will look something like this:

TypeName: System.Diagnostics.Process

Name MemberType Definition

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

Handles AliasProperty Handles = Handlecount

Name AliasProperty Name = ProcessName

NPM AliasProperty NPM = NonpagedSystemMemorySize

PM AliasProperty PM = PagedMemorySize

VM AliasProperty VM = VirtualMemorySize

WS AliasProperty WS = WorkingSet

add_Disposed Method System.Void add_Disposed(Event...

...

We can make this long list of information more usable by filtering for elements we want to see. The Get-Member command lets you list only members that are properties. There are several forms of properties. The cmdlet displays properties of any type if we set the Get-MemberMemberType parameter to the value Properties. The resulting list is still very long, but a bit more manageable:

PS> Get-Process | Get-Member -MemberType Properties

TypeName: System.Diagnostics.Process

Name MemberType Definition

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

Handles AliasProperty Handles = Handlecount

Name AliasProperty Name = ProcessName

...

ExitCode Property System.Int32 ExitCode {get;}

...

Handle Property System.IntPtr Handle {get;}

...

CPU ScriptProperty System.Object CPU {get=$this.Total...

...

Path ScriptProperty System.Object Path {get=$this.Main...

...

Note:

The allowed values of MemberType are AliasProperty, CodeProperty, Property, NoteProperty, ScriptProperty, Properties, PropertySet, Method, CodeMethod, ScriptMethod, Methods, ParameterizedProperty, MemberSet, and All.

There are over 60 properties for a process. The reason Windows PowerShell often shows only a handful of properties for any well-known object is that showing all of them would produce an unmanageable amount of information.

Note:

Windows PowerShell determines how to display an object type by using information stored in XML files that have names ending in .format.ps1xml. The formatting data for process objects, which are .NET System.Diagnostics.Process objects, is stored in PowerShellCore.format.ps1xml.

If you need to look at properties other than those that Windows PowerShell displays by default, you will need to format the output data yourself. This can be done by using the format cmdlets.

Posted in: Software| Tags: PowerShell Handle Alias Object Structure Get-Member out-Hosting Paging Process Property ProcessName Allowed MemberType Determine

Understanding the Windows PowerShell Pipeline

07/25/2009

Piping works virtually everywhere in Windows PowerShell. Although you see text on the screen, Windows PowerShell does not pipe text between commands. Instead, it pipes objects.

The notation used for pipelines is similar to that used in other shells, so at first glance, it may not be apparent that Windows PowerShell introduces something new. For example, if you use the Out-Host cmdlet to force a page-by-page display of output from another command, the output looks just like the normal text displayed on the screen, broken up into pages:

PS> Get-ChildItem -Path C:\WINDOWS\System32 | Out-Host -Paging

Directory: Microsoft.Windows PowerShell.Core\FileSystem::C:\WINDOWS\system32

Mode LastWriteTime Length Name

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

-a--- 2005-10-22 11:04 PM 315 $winnt$.inf

-a--- 2004-08-04 8:00 AM 68608 access.cpl

-a--- 2004-08-04 8:00 AM 64512 acctres.dll

-a--- 2004-08-04 8:00 AM 183808 accwiz.exe

-a--- 2004-08-04 8:00 AM 61952 acelpdec.ax

-a--- 2004-08-04 8:00 AM 129536 acledit.dll

-a--- 2004-08-04 8:00 AM 114688 aclui.dll

-a--- 2004-08-04 8:00 AM 194048 activeds.dll

-a--- 2004-08-04 8:00 AM 111104 activeds.tlb

-a--- 2004-08-04 8:00 AM 4096 actmovie.exe

-a--- 2004-08-04 8:00 AM 101888 actxprxy.dll

-a--- 2003-02-21 6:50 PM 143150 admgmt.msc

-a--- 2006-01-25 3:35 PM 53760 admparse.dll

<SPACE> next page; <CR> next line; Q quit

...

The Out-Host -Paging command is a useful pipeline element whenever you have lengthy output that you would like to display slowly .It is especially useful if the operation is very CPU-intensive. Since processing is transferred to the Out-Host cmdlet when it has a complete page ready to display, cmdlets that proceed it in the pipeline halt operation until the next page of output is available. You can see this if you use the Windows Task Manager to monitor CPU and memory use by Windows PowerShell.

Run the following command: Get-ChildItem C:\Windows -Recurse. Compare the CPU and memory usage to this command: Get-ChildItem C:\Windows -Recurse | Out-Host -Paging. What you see on the screen is text, but that is because it is necessary to represent objects as text in a console window. This is really just a representation of what is really going on inside Windows PowerShell. For example, consider the Get-Location cmdlet. If you type Get-Location while your current location is the root of the C drive, you would see the following output:

PS> Get-Location

Path

----

C:\

If Windows PowerShell pipelined text, issuing a command such as Get-Location | Out-Host, would pass from Get-Location to Out-Host a set of characters in the order they are displayed onscreen. In other words, if you were to ignore the heading information, Out-Host would first receive the character 'C', then the character ':', then the character '\'. The Out-Host cmdlet could not determine what meaning to associate with the characters output by the Get-Location cmdlet.

Instead of using text to let commands in a pipeline communicate, Windows PowerShell uses objects. From the standpoint of a user, objects package related information into a form that makes it easier to manipulate the information as a unit, and extract specific items that you need.

The Get-Location command does not return text that contains the current path. It returns a package of information called a PathInfo object that contains the current path along with some other information. The Out-Host cmdlet then sends this PathInfo object to the screen, and Windows PowerShell decides what information to display and how to display it based on its formatting rules.

In fact, the heading information output by the Get-Location cmdlet is added only at the end of the process, as part of the process of formatting the data for onscreen display. What you see onscreen is a summary of information, and not a complete representation of the output object.

Given that there may be more information output from a Windows PowerShell command than what we see displayed in the console window, how can you retrieve the non-visible elements? How do you view the extra data? And what if you want to view the data in a format different than the one Windows PowerShell normally uses?

The rest of this chapter discusses how you can discover the structure of specific Windows PowerShell objects, selecting specific items and formatting them for easier display, and how to send this information to alternative output locations such as files and printers.

Posted in: Software| Tags: Windows PowerShell Understanding Windows PowerShell Pipeline System32 Access Acctres Accwiz Acelnder

Using Tab Expansion

07/25/2009

Command-line shells often provide a way to complete the names of long files or commands automatically, speeding up command entry and providing hints. Windows PowerShell allows you to fill in file names and cmdlet names by pressing the Tab key.

Note:

Tab expansion is controlled by the internal function TabExpansion. Since this function can be modified or overridden, this discussion is a guide to the behavior of the default Windows PowerShell configuration.

To fill in a filename or path from the available choices automatically, type part of the name and press the Tab key. Windows PowerShell will automatically expand the name to the first match that it finds. Pressing the Tab key repeatedly will cycle through all of the available choices.

The tab expansion of cmdlet names is slightly different. To use tab expansion on a cmdlet name, type the entire first part of the name (the verb) and the hyphen that follows it. You can fill in more of the name for a partial match. For example, if you type get-co and then press the Tab key, Windows PowerShell will automatically expand this to the Get-Command cmdlet (notice that it also changes the case of letters to their standard form). If you press Tab key again, Windows PowerShell replaces this with the only other matching cmdlet name, Get-Content.

You can use tab expansion repeatedly on the same line. For example, you can use tab expansion on the name of the Get-Content cmdlet by entering:

PS> Get-Con<Tab>

When you press the Tab key, the command expands to:

PS> Get-Content

You can then partially specify the path to the Active Setup log file and use tab expansion again:

PS> Get-Content c:\windows\acts<Tab>

When you press the Tab key, the command expands to:

PS> Get-Content C:\windows\actsetup.log

Note:

One limitation of the tab expansion process is that tabs are always interpreted as attempts to complete a word. If you copy and paste command examples into a Windows PowerShell console, make sure that the sample does not contain tabs; if it does, the results will be unpredictable and will almost certainly not be what you intended.

Posted in: Software| Tags: PowerShell Expansion Control Internal Function TabExpansion Configuration Sligntly actsetup Intend

Getting Detailed Help Information

07/25/2009

Windows PowerShell has detailed help documentation for all cmdlets. To display the help topics, use the Get-Help cmdlet. For example, to get help for the Get-Childitem cmdlet, type:

get-help get-childitem

or

get-childitem -?

You can also display one page of each help topic at a time by using the man and help functions. To use them, type man or help followed by the cmdlet name. For example, to display help for the Get-Childitem cmdlet, type

man get-childitem

or

help get-childitem

The Get-Help cmdlet also displays information about conceptual topics in Windows PowerShell. Conceptual help topics begin with the "about_" prefix, such as about_line_editing. (The name of the conceptual topic must be entered in English even on non-English versions of Windows PowerShell.)

To display a list of conceptual topics, type:

get-help about_*

To display a particular help topic, type the topic name, for example:

get-help about_line_editing

Using Familiar Command Names

Using a mechanism called aliasing, Windows PowerShell allows users to refer to commands by alternate names. Aliasing allows users with experience in other shells to reuse common command names that they already know to perform similar operations in Windows PowerShell. Although we will not discuss Windows PowerShell aliases in detail, you can still use them as you get started with Windows PowerShell.

Aliasing associates a command name that you type with another command. For example, Windows PowerShell has an internal function named Clear-Host that clears the output window. If you type either the cls or clear command at a command prompt, Windows PowerShell interprets that this is an alias for the Clear-Host function and runs the Clear-Host function.

This feature helps users to learn Windows PowerShell. First, most Cmd.exe and UNIX users have a large repertoire of commands that users already know by name, and although the Windows PowerShell equivalents may not produce identical results, they are close enough in form that users can use them to do work without having to first memorize the Windows PowerShell names. Second, the major source of frustration in learning a new shell when the user is already familiar with another shell, is the errors that are caused by "finger memory". If you have used Cmd.exe for years, when you have a screen full of output and want to clean it up, you would reflexively type the cls command and press the ENTER key. Without the alias to the Clear-Host function in Windows PowerShell, you would simply get the error message "'cls' is not recognized as a cmdlet, function, operable program, or script file." and be left with no idea of what to do to clear the output.

The following is a brief listing of the common Cmd.exe and UNIX commands that you can use inside Windows PowerShell:

cat

dir

mount

rm

cd

echo

move

rmdir

chdir

erase

popd

sleep

clear

h

ps

sort

cls

history

pushd

tee

copy

kill

pwd

type

del

lp

r

write

diff

ls

ren

 

If you find yourself using one of these commands reflexively and want to learn the real name of the native Windows PowerShell command, you can use the Get-Alias command:

PS> Get-Alias cls

CommandType Name Definition

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

Alias cls Clear-Host

To make examples more readable, the Windows PowerShell Primer generally avoids using aliases. However, knowing more about aliases this early can still be useful if you are working with arbitrary snippets of Windows PowerShell code from another source or wish to define your own aliases. The rest of this section will discuss standard aliases and how to define your own aliases.

Posted in: Software| Tags: PowerShell Information Childitem get-childitem man Get Sleep Write rm rmdir echo cat dir

Getting Detailed Help Information in Powershell

05/27/2009

Windows PowerShell has detailed help documentation for all cmdlets. To display the help topics, use the Get-Help cmdlet. For example, to get help for the Get-Childitem cmdlet, type:

get-help get-childitem

or

get-childitem -?

You can also display one page of each help topic at a time by using the man and help functions. To use them, type man or help followed by the cmdlet name. For example, to display help for the Get-Childitem cmdlet, type

man get-childitem

or

help get-childitem

The Get-Help cmdlet also displays information about conceptual topics in Windows PowerShell. Conceptual help topics begin with the "about_" prefix, such as about_line_editing. (The name of the conceptual topic must be entered in English even on non-English versions of Windows PowerShell.)

To display a list of conceptual topics, type:

get-help about_*

To display a particular help topic, type the topic name, for example:

get-help about_line_editing

Posted in: Software| Tags: Windows Type PowerShell Help Information Childitem man example cmdlet detailed

Displaying available command types

05/27/2009

The Get-Command command does not list every command that is available in Windows PowerShell. Instead, the Get-Command command lists only the cmdlets in the current shell. Windows PowerShell actually supports several other types of commands. Aliases, functions, and scripts are also Windows PowerShell commands, although they are not discussed in detail in the Windows PowerShell Primer. External files that are executables, or have a registered file type handler, are also classified as commands.

You can return a listing of all items that can be invoked by entering the following command:

PS> Get-Command *

Because this list includes external files in your search path, it may contain thousands of items. It is more useful to look at a reduced set of commands. To find native commands of other types, you can use the CommandType parameter of the Get-Command cmdlet. Although we have not talked about these other command types yet, you can still display them if you know the name of the CommandType for a class of commands.

Note:

Although we have not discussed it yet, the asterisk (*) is used for wildcard matching in Windows PowerShell command arguments. The * means "match one or more of any characters". You can type Get-Command a* to find all commands that begin with the letter "a". Unlike wildcard matching in Cmd.exe, Windows PowerShell's wildcard will also match a period.

To display the special command category aliases (these are nicknames used as alternatives to standard command names), enter the following command:

PS> Get-Command -CommandType Alias

To display all Windows PowerShell functions, enter the following command:

PS> Get-Command -CommandType Function

To display external scripts in Windows PowerShell's search path, enter the following command:

PS> Get-Command -CommandType ExternalScript

Posted in: Software| Tags: Windows PowerShell Command Display Get external displaying primer detail aliases shell

Getting Summary Command Information

05/27/2009

The Windows PowerShell Get-Command cmdlet retrieves the names of all available commands. When you type Get-Command at a Windows PowerShell prompt, you will see output similar to the following:

PS> Get-Command

CommandType Name Definition

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

Cmdlet Add-Content Add-Content [-Path] <String[...

Cmdlet Add-History Add-History [[-InputObject] ...

Cmdlet Add-Member Add-Member [-MemberType] <PS...

...

This output looks a lot like the Help output of Cmd.exe: a tabular summary of internal commands. In the extract of the Get-Command command output shown above, every command shown has a CommandType of Cmdlet. A Cmdlet is Windows PowerShell's intrinsic command type that corresponds roughly to the dir and cd commands of Cmd.exe and to built-ins in UNIX shells such as BASH.

In the output of the Get-Command command, all of the definitions end with ellipses (...) to indicate that PowerShell cannot display all of the content in the available space. When Windows PowerShell displays output, it formats the output as text and then arranges it to make the data fit cleanly into the window. We will talk about this later in the section on formatters.

The Get-Command cmdlet has a Syntax parameter that allows you to retrieve just the syntax of each cmdlet. Enter the Get-Command -Syntax command to display the full output:

PS> Get-Command -Syntax

Add-Content [-Path] <String[]> [-Value] <Object[]> [-PassThru] [-Filter <String>] [-Include <String[]>] [-Exclude <String[]>] [-Force] [Credential <PSCredential>] [-Verbose] [-Debug] [-ErrorAction <ActionPreference>] [-ErrorVariable <String>] [-OutVariable <String>] [-OutBuffer <Int32>] [-WhatIf] [-Confirm] [-Encoding <FileSystemCmdletProviderEncoding>]

Add-History [[-InputObject] <PSObject[]>] [-Passthru] [-Verbose] [-Debug] [-ErrorAction <ActionPreference>] [-ErrorVariable <String>] [-OutVariable <String>][-OutBuffer <Int32>]...

Posted in: Software| Tags: Windows Type PowerShell Command Information Get summary cmdlet output

Cmdlets Use Verb-Noun Names to Reduce Command Memorization

05/27/2009

Windows PowerShell uses a "verb-noun" naming system, where each cmdlet name consists of a standard verb hyphenated with a specific noun. Windows PowerShell verbs are not always English verbs, but they express specific actions in Windows PowerShell. Nouns are very much like nouns in any language, they describe specific types of objects that are important in system administration. It is easy to demonstrate how these two-part names reduce learning effort by looking at a few examples of verbs and nouns.

Nouns are less restricted, but they should always describe what a command acts upon. Windows PowerShell has commands such as Get-Process, Stop-Process, Get-Service, and Stop-Service.

In the case of two nouns and two verbs, consistency does not simplify learning that much. However, if you look at a standard set of 10 verbs and 10 nouns, you then have only 20 words to understand, but those words can be used to form 100 distinct command names.

Frequently, you can recognize what a command does by reading its name, and it is usually apparent what name should be used for a new command. For example, a computer shutdown command might be Stop-Computer. A command that lists all computers on a network might be Get-Computer. The command that gets the system date is Get-Date.

You can list all commands that include a particular verb with the -Verb parameter for Get-Command (We will discuss Get-Command in detail in the next section). For example, to see all cmdlets that use the verb Get, type:

PS> Get-Command -Verb Get

CommandType Name Definition

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

Cmdlet Get-Acl Get-Acl [[-Path] <String[]>]...

Cmdlet Get-Alias Get-Alias [[-Name] <String[]...

Cmdlet Get-AuthenticodeSignature Get-AuthenticodeSignature [-...

Cmdlet Get-ChildItem Get-ChildItem [[-Path] <Stri...

...

The -Noun parameter is even more useful because it allows you to see a family of commands that affect the same type of object. For example, if you want to see which commands are available for managing services, type following command:

PS> Get-Command -Noun Service

CommandType Name Definition

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

Cmdlet Get-Service Get-Service [[-Name] <String...

Cmdlet New-Service New-Service [-Name] <String>...

Cmdlet Restart-Service Restart-Service [-Name] <Str...

Cmdlet Resume-Service Resume-Service [-Name] <Stri...

Cmdlet Set-Service Set-Service [-Name] <String>...

Cmdlet Start-Service Start-Service [-Name] <Strin...

Cmdlet Stop-Service Stop-Service [-Name] <String...

Cmdlet Suspend-Service Suspend-Service [-Name] <Str...

...

A command is not necessarily a cmdlet, just because it has a verb-noun naming scheme. One example of a native Windows PowerShell command that is not a cmdlet but has a verb-noun name, is the command for clearing a console window, Clear-Host. The Clear-Host command is actually an internal function, as you can see if you run Get-Command against it:

PS> Get-Command -Name Clear-Host

CommandType Name Definition

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

Function Clear-Host $spaceType = [System.Managem...

Posted in: Software| Tags: PowerShell Names Verb-Noun Command Script

Hot Posts

Latest posts

Tags

Others

Sponsors

asp.net interview questions