代码改变世界

如何用帮助系统获取PowerShell可用命令信息

2010-12-04 01:07  @天行健中国元素  阅读(4835)  评论(0编辑  收藏  举报

真正能让读者尽快掌握一门语言的文档应该是官方的帮助文档,利用帮助文档,并且理解好每个技术细节中存在的编程思想,能让用户遇到任何问题举一反三,最终解决问题。

PowerShell中的帮助系统是一个互交式的环境,其中所有的一切均以对象形式出现。可以根据命令任何部分的字面意思找出其所有的属性和方法原型,而忽略其是否为Shell、.NET、COM或者其他部分。本文将介绍如何在PowerShell中获取任何命令的参数和使用方法,以及如何使用内置的帮助获取详细的参数信息,并且使用网络上搜索的信息创建自己的帮助文档。

1 帮助系统

PowerShell的设计者在设计帮助系统的过程中尝试使其简单易用,适应尽可能多的用户使用。所有针对内置命令的帮助内容均用英语做了详细的说明,用户可以使用Get-Help这个cmdlet来查询任何命令的帮助信息。PowerShell也提供了help命令,这是一个调用Get-Help的函数。执行后将输出管道传输到more.com,这样用户即可分页阅读有关的帮助内容。

1.1 基础知识

在控制台提示符下键入help,按回车键后提示help的相关信息,从中可以看到help是Get-Help重新封装过的:

PS C:\Documents and Settings\Administrator> help
TOPIC
    Get-Help

SHORT DESCRIPTION
    Displays help about Windows PowerShell cmdlets and concepts.

LONG DESCRIPTION

SYNTAX
    get-help {<CmdletName> | <TopicName>}
    help {<CmdletName> | <TopicName>}
    <CmdletName> -?
    Examples:
      get-help get-process   : Displays help about the Get-Process cmdlet.
      get-help about_signing : Displays help about the signing and execution pol
icies.
      help where-object      : Displays help about the Where-Object cmdlet.
      help about_foreach     : Displays help about foreach loops in PowerShell.
      set-service -?         : Displays help about the Set-Service cmdlet.
……

可以尝试使用通配符过滤主题,下例中显示所有以“about_”开头的cmdlet的帮助:

PS C:\> help about_*

Name                              Category  Synopsis
----                              --------  --------
about_aliases                     HelpFile  Describes how to use alternate n...
about_Arithmetic_operators        HelpFile  Describes the operators that per...
about_arrays                      HelpFile  A compact data structure for sto...
about_Assignment_operators        HelpFile  Describes how to use operators t...
about_Automatic_variables         HelpFile  Describes variables that store s...
about_break                       HelpFile  A statement for immediately exit...
about_install_wsman               HelpFile  Installs the required version of...
-- More  --

可以调用help并传递需要显示的主题名:

PS C:\> help ac

NAME
    Add-Content

SYNOPSIS
Adds content to the specified items, such as adding words to a file.
……

上例将Add-Content的别名ac传递给help,相当于获取Add-Content的帮助:

PS C:\> help  Add-Content

NAME
    Add-Content

SYNOPSIS
Adds content to the specified items, such as adding words to a file.
……

PowerShell为所有已经声明的别名自动添加帮助主题,用户不必知道别名指向的cmdlet,即可同时获取别名及其对应的cmdlet的帮助。

在上述帮助主题中的每个主题都有个关联分类,为所有的内置主题获取分类值可以使用Get-Help cmdlet。下例将集合用管道传递给select获取唯一的分类值:

PS C:\> Get-Help * | select Category -Unique

Category
--------
Alias
Cmdlet
Provider
HelpFile

从中可以看到以下分类值。

(1)Alias:为所有别名自动创建的主题。

(2)Cmdlet:如何使用cmdlet、内置或第三方管理单元的主题文档。

(3)Provider:所有已安装提供程序的主题文档,PowerShell提供的内置提供程序的文档包括Alias、Environment、FileSystem、Function、Registry、Variable和Certificate,完整的自定义提供程序应该添加主题到这个分类中。

(4)HelpFile:概念主题,所有讨论特定语言特性,如分支、循环及变量的about_*主题均属于该分类。

(5)Get-Help:找回基于分类名的主题,下例获取特定语言的主题或者HelpFile分类:

PS C:\> Get-Help -Category HelpFile

Name                              Category  Synopsis
----                              --------  --------
about_aliases                     HelpFile  Describes how to use alternate n...
about_Arithmetic_operators        HelpFile  Describes the operators that per...
about_arrays                      HelpFile  A compact data structure for sto...
about_Assignment_operators        HelpFile  Describes how to use operators t...

Get-Help和help支持的另外一个重要参数是控制为用户输出的文本数量,可以通过使用-detailed、-full和-example开关来控制。可能的配置如下。

(1)无(默认值):返回值是关于命令简短的介绍,其中包含支持的参数、简短的描述及一两个实例。

(2)-detailed:返回值是较为详细的解释,包括所有参数作用的详细描述,同时附带一系列命令操作的实例。

(3)-full:返回值是所有的帮助信息,包括所有参数的完整信息,以及实例的详细信息。

(4)-example:返回值是完整的实例描述,包括标题、描述和示例代码, 不会返回其他命令的信息。

1.2 参数的详细信息

很多情况下,用户可能只对命令中的一个参数感兴趣,使用Get-Help的-parameter参数获取特定参数的信息。下例获取Get-ChildItem的-filter参数的信息:

PS C:\> Get-Help Get-ChildItem -Parameter filter

-Filter <string>
    Specifies a filter in the provider's format or language. The value of this
    parameter qualifies the Path parameter. The syntax of the filter, including
     the use of wildcards, depends on the provider. Filters are more efficient
    than other parameters, because the provider applies them when retrieving th
    e objects, rather than having Windows PowerShell filter the objects after t
    hey are retrieved.

    Required?                    false
    Position?                    2
    Default value
    Accept pipeline input?       false
    Accept wildcard characters?  False

其中的内容是参数的简短描述和格式化后的参数规格清单,包括是否必需、位置(如果是与位置相关的参数)、默认值、管道输入是否被解释为参数值,以及是否支持通配符等。

下例获取Get-Help的parameter参数的信息:

PS C:\> Get-Help Get-Help -Parameter Parameter

-Parameter <string>
    Displays a detailed description of the specified parameter. These descripti
    ons are included in the Full view of help. Wildcards are permitted.

    Required?                    false
    Position?                    named
    Default value
    Accept pipeline input?       false
    Accept wildcard characters?  False

有时可以通过这个特性来查看PowerShell的内部结构,掌握一门语言的关键是理解其运行方式。上例说明可以使用通配符获取多个参数的信息,这样即可通过传递*作为参数名获取所有参数,如:

PS C:\> Get-Help Get-ChildItem -Parameter *

-Exclude <string[]>
    Omits the specified items. The value of this parameter qualifies the Path p
    arameter. Enter a path element or pattern, such as "*.txt". Wildcards are p
    ermitted.

    This parameter does not work properly in this cmdlet.

    Required?                    false
    Position?                    named
    Default value
    Accept pipeline input?       false
Accept wildcard characters?  False
……

如果对不明确或记不清参数名,即可在参数名中使用通配符来获取,如:

PS C:\> Get-Help Get-ChildItem -Parameter fo*

-Force [<SwitchParameter>]
    Overrides restrictions that prevent the command from succeeding, just so th
    e changes do not compromise security. For example, Force adds hidden files
    and directories to the output, but it does not display object that the user
     is not permitted to see.

    Required?                    false
    Position?                    named
    Default value
    Accept pipeline input?       false
    Accept wildcard characters?  false

1.3 高级技巧

PowerShell的帮助系统依靠一种基于Windows Vista的技术,帮助内容保存为基于XML的文件格式。即MAML(Microsoft Assistive Markup Language)中,后期被更名为“AML”(Assistive Markup Lanage)。

根据惯例,PowerShell需要以DLL文件形式命名的管理单元DLL,这样所有cmdlet的开发人员需要遵循这个惯例。下例演示包含处理文件和项目的Microsoft.PowerShell.Management管理单元的帮助文件,首先要获取管理单元:

PS C:\> Get-PSSnapin Microsoft.PowerShell.Management


Name        : Microsoft.PowerShell.Management
PSVersion   : 2.0
Description : This Windows PowerShell snap-in contains management cmdlets used
              to manage Windows components.

.NET编译后,为查看cmdlet类所在宿主DLL文件的位置,执行如下命令:

PS C:\> (Get-PSSnapin Microsoft.PowerShell.Management).ModuleName
C:\WINDOWS\system32\WindowsPowerShell\v1.0\Microsoft.PowerShell.Commands.Management.dll

根据惯例,帮助文件名为“Microsoft.PowerShell.Commands.Management.dll-Help.xml”,它会被区域化并且保存在DLL文件所在的目录或者子区域化子目录中。默认情况下32位Windows Vista操作系统en-US版本的帮助文件在C:\WINDOWS\system32\

WindowsPowerShell\v1.0\en-US中。

为查看典型的帮助文件包含的内容,打开上例中的文档,并查找Add-Contentcmdlet的部分。在XML标签标签中包含的内容如下:

<command:command xmlns:maml=http://schemas.microsoft.com/maml/2004/10 
xmlns:command="http://schemas.microsoft.com/maml/dev/command/2004/10" 
xmlns:dev="http://schemas.microsoft.com/maml/dev/2004/10">
	<command:details>
		<command:name>
                   Add-Content
		</command:name>
		<maml:description>
<maml:para>Adds content to the specified items, such as adding words to a file.</maml:para>
		</maml:description>
		<maml:copyright>
			<maml:para></maml:para>
		</maml:copyright>
		<command:verb>Add</command:verb>
		<command:noun>Content</command:noun>
		<dev:version></dev:version>
	</command:details>
	<maml:description>
		<maml:para>The Add-Content cmdlet appends content to a specified item or file. You can specify the content by typing the content in the command or by specifying an object that contains the content.</maml:para>
	</maml:description>
...
</command:command>

PowerShell作用于对象,而Get-Help返回用户可用的对象。最后得到的对象结构基于AML文档,并且通过XML类型适配器过滤。这就意味着可以访问任何目标属性的详细信息,查询并不直接由Get-Help cmdlet来实现。下例使用Get-Help获取帮助主题:

PS C:\> $h = Get-Help Add-Content
PS C:\> $h

NAME
    Add-Content

SYNOPSIS
Adds content to the specified items, such as adding words to a file.
……

Get-Help并没有格式化文本,而返回MamlCommandHelpInfo对象,而此对象的底层机制会实现相应的功能。MamlCommandHelpInfo已经关联自定义格式化视图,与之前文章中提到的自定义对象视图使用的方法相同。如果读者对自定义视图的具体细节感兴趣,可以查看PowerShell安装目录下面的Help.format.ps1xml文件以获取更多的信息。

下面获取Add-Content帮助主题的detail和description属性:

PS C:\> $h.details

NAME
    Add-Content

SYNOPSIS
    Adds content to the specified items, such as adding words to a file.



PS C:\> $h.description

The Add-Content cmdlet appends content to a specified item or file. You can spe
cify the content by typing the content in the command or by specifying an objec
t that contains the content.

如果需要参数,则通过属性取值:

PS C:\> $h.parameters

    -Credential <PSCredential>
        Specifies a user account that has permission to perform this action. Th
        e default is the current user.

        Type a user-name, such as "User01" or "Domain01\User01", or enter a PSC
        redential object, such as one generated by the Get-Credential cmdlet. I
        f you type a user name, you will be prompted for a password.
……

用户可以获得关于参数的统计值并通过索引值访问:

PS C:\> $h.parameters.parameter.length
12
PS C:\> $h.parameters.parameter[4]

-Force [<SwitchParameter>]
    Overrides the read-only attribute, allowing you to add content to a read-on
    ly file.

    Required?                    false
    Position?                    named
    Default value
    Accept pipeline input?       false
    Accept wildcard characters?  False

使用$h.parameter.parmeter的原因为AML文件是如此解析的,下面的代码段是这个参数的声明部分:

<command:parameters>
<command:parameter required="true" variableLength="true" globbing="false" pipelineInput="true (ByPropertyName)" position="1">
			<maml:name>Path</maml:name>
			<maml:description>
				<maml:para>Specifies the path to the items that receive the additional content. Wildcards are permitted. If you specify multiple paths, use commas to separate the paths.</maml:para>
								
			</maml:description>
			<command:parameterValue required="true" 			variableLength="true">string[]</command:parameterValue>
			<dev:type>
				<maml:name>string[]</maml:name>
				<maml:uri/>
			</dev:type>
			<dev:defaultValue></dev:defaultValue>
		</command:parameter>
......
</command:parameters>

XML对象适配器将标签转换为parameter属性,并将所有的标签转换为一个集合。

下面查看保存在AML文件中的例子,其中的代码是Add-Content的首个例子:

<command:examples>


		<command:example>
			<maml:title>
				-------------------------- EXAMPLE 1 --------------------------
			</maml:title> 
			<maml:introduction>
				<maml:para>C:\PS></maml:para>
			</maml:introduction> 
  			<dev:code>add-content -path *.txt -exclude help* -value 			&quot;END&quot;</dev:code>
  			<dev:remarks>
  			        <maml:para>This command adds &quot;END&quot; to all text 		files in the current directory, except for those with file names that begin with 			&quot;help&quot;.</maml:para>
	                        <maml:para></maml:para>
	                        <maml:para></maml:para>
	                        <maml:para></maml:para>
	                        <maml:para></maml:para>
  			</dev:remarks>
			<command:commandLines>
				<command:commandLine>
					<command:commandText></command:commandText>
				</command:commandLine>
			</command:commandLines>
		</command:example>

		<command:example>
......
</command:examples>

通过下面实例能够确认可以将通过索引值访问参数的方法用于访问帮助信息中的例子,注意数组的下标从0开始编号,所以访问目标实例的索引值一定要小心:

PS C:\> $h.examples.example.Length
4
PS C:\> $h.examples.example[2]

-------------------------- EXAMPLE 3 --------------------------

C:\PS>add-content -path monthly.txt -value (get-content c:\rec1\weekly.txt)

This command adds the contents of the Weekly.txt file to the end of the Monthly
.txt file. It uses the Get-Content cmdlet to get the contents of the Weekly.txt
 file and the Value parameter to pass the content of weekly.txt to Add-Content.
 The parentheses ensure that the Get-Content command is complete before the add
-content command begins.

You can also copy the content of Weekly.txt to a variable, such as $w, and then
 use the Value parameter to pass the variable to Add-Content. In that case, the
 command would be "add-content -path monthly.txt -value $w".

能够访问不同帮助主题的子对象是一种强大的功能,可以用其来创建能够搜索所有包含特定字符串或关于Get-Content/Set-Content的cmdlet帮助实例脚本。下面的脚本使用foreach来遍历一系列的文件:

param ($Name = "*", $Query = { $true })
$topics = Get-Help $Name
foreach ($topic in $topics)
{
	$matchingExamples = $topic.examples.example | where $Query
	if ($matchingExamples)
	{
		#output the found examples
		$matchingExamples
	}
}

将上述代码保存为“Search-Examples.ps1”文件,并使用Get-ExecutionPolicy查看本机当前的执行策略。为了避免出现签名问题,务必通过Set-ExecutionPolicy remotesigned命令将执行策略改为remotesigned,并且传递参数给这个脚本并执行。在执行的过程中声明了两个参数,其中$Name用于过滤cmdlet名;$Query是一个脚本块,用于逐个验证每个例子,并且按照要求找出目标例子。上述代码根据传递的$Name过滤参数获取Get-Help返回的所有帮助主题,然后把查询脚本块作用于所有已经传递过来的例子,并返回执行后为$true的例子。脚本块中获取Get-Content和Set-Content cmdlet的语句通过foreach语句遍历满足通配符“*content*”集合:

PS C:\PowerShell> Get-ExecutionPolicy
Restricted
PS C:\PowerShell> Get-Help Set-ExecutionPolicy -Examples
PS C:\PowerShell> Set-ExecutionPolicy remotesigned
PS C:\PowerShell> .\Search-Examples.ps1 -Name *content* -Query `
>> {$_.code -like "*foreach*"}
>>

-------------------------- EXAMPLE 3 --------------------------

C:\PS>(get-content Notice.txt) | foreach-object {$_ -replace "Warning", "Cautio
n"} | set-content Notice.txt

This command replaces all instances of "Warning" with "Caution" in the Notice.t
xt file.

It uses the Get-Content cmdlet to get the content of Notice.txt. The pipeline o
perator sends the results to the ForEach-Object cmdlet, which applies the expre
ssion to each line of content in Get-Content. The expression uses the "$_" symb
ol to refer to the current item and the Replace parameter to specify the text t
o be replaced.

Another pipeline operator sends the changed content to Set-Content which replac
es the text in Notice.txt with the new content.

The parentheses around the Get-Content command assure that the Get operation is
 complete, before the Set operation begins. Otherwise, command will fail becaus
e the two functions will be trying to access the same file.

查看输出的返回信息可知最后获取的是Get-Content帮助主题的第3个实例,这是唯一一个代码中使用了foreach语句的实例。

传递脚本块作为查询条件允许用户设置灵活的查询标准。如果在查询时忘记了实例名,而记得其中有notice.txt文件,则可以使用这个脚本块作为查询条件来找到目标实例:

PS C:\PowerShell> .\Search-Examples.ps1 -Name *content* -Query `
>> {$_.remarks -like "*notice.txt*"}
>>

-------------------------- EXAMPLE 3 --------------------------

C:\PS>(get-content Notice.txt) | foreach-object {$_ -replace "Warning", "Cautio
n"} | set-content Notice.txt

This command replaces all instances of "Warning" with "Caution" in the Notice.t
xt file.

It uses the Get-Content cmdlet to get the content of Notice.txt. The pipeline o
perator sends the results to the ForEach-Object cmdlet, which applies the expre
ssion to each line of content in Get-Content. The expression uses the "$_" symb
ol to refer to the current item and the Replace parameter to specify the text t
o be replaced.

Another pipeline operator sends the changed content to Set-Content which replac
es the text in Notice.txt with the new content.

The parentheses around the Get-Content command assure that the Get operation is
 complete, before the Set operation begins. Otherwise, command will fail becaus
e the two functions will be trying to access the same file.

2 获取命令信息

PowerShell能够调用各种类型的命令,如cmdlet、函数、别名、脚本文件、外部程序,甚至在Windows中注册的默认打开方式的外部文件。与程序互交的重要工具Get-Command cmdlet提供关于已注册cmdlet、可用的外部程序和文件信息,用户可以用其归类相关命令或发现不曾注意的程序。如果知道cmdlet作用于特定类型的对象,则可获取所有相同名词部分命令,这样可涵盖目标对象的所有操作。例如,Rename-Item和Move-Item分别用于重命名和移动文件。要查看它们的其他操作,则可使用下例来实现:

PS C:\PowerShell> Get-Command -noun *item*

CommandType     Name                            Definition
-----------     ----                            ----------
Cmdlet          Clear-Item                      Clear-Item [-Path] <String[]...
Cmdlet          Clear-ItemProperty              Clear-ItemProperty [-Path] <...
Cmdlet          Copy-Item                       Copy-Item [-Path] <String[]>...
Cmdlet          Copy-ItemProperty               Copy-ItemProperty [-Path] <S...
Cmdlet          Get-ChildItem                   Get-ChildItem [[-Path] <Stri...
Cmdlet          Get-Item                        Get-Item [-Path] <String[]> ...
Cmdlet          Get-ItemProperty                Get-ItemProperty [-Path] <St...
Cmdlet          Invoke-Item                     Invoke-Item [-Path] <String[...
Cmdlet          Move-Item                       Move-Item [-Path] <String[]>...
Cmdlet          Move-ItemProperty               Move-ItemProperty [-Path] <S...
Cmdlet          New-Item                        New-Item [-Path] <String[]> ...
Cmdlet          New-ItemProperty                New-ItemProperty [-Path] <St...
Cmdlet          Remove-Item                     Remove-Item [-Path] <String[...
Cmdlet          Remove-ItemProperty             Remove-ItemProperty [-Path] ...
Cmdlet          Rename-Item                     Rename-Item [-Path] <String>...
Cmdlet          Rename-ItemProperty             Rename-ItemProperty [-Path] ...
Cmdlet          Set-Item                        Set-Item [-Path] <String[]> ...
Cmdlet          Set-ItemProperty                Set-ItemProperty [-Path] <St...

PS C:\PowerShell> (Get-Command -noun *item*).length
18

共存在18个相关命令,其中涵盖了创建、删除和修改该项目及其子项目的操作。接下来回顾每个cmdlet的帮助主题,就可以逐个掌握相关的操作。

可以获取动词部分的cmdlet,下例返回所有涉及stop的cmdlet:

PS C:\PowerShell> Get-Command -Verb *stop*

CommandType     Name                            Definition
-----------     ----                            ----------
Cmdlet          Stop-Computer                   Stop-Computer [[-ComputerNam...
Cmdlet          Stop-Job                        Stop-Job [[-Id] <Int32[]>] [...
Cmdlet          Stop-Process                    Stop-Process [-Id] <Int32[]>...
Cmdlet          Stop-Service                    Stop-Service [-Name] <String...
Cmdlet          Stop-Transcript                 Stop-Transcript [-Verbose] [...

PS C:\PowerShell> (Get-Command -Verb *stop*).Length
5

通过上面的相关cmdlet可以知道如何关闭计算机、计划任务、进程或者服务,具体的操作方法和参数可以查看相应的帮助。Transcript(抄本)是一种记录控制台线程的方法,关闭它使用Stop-Transcript这个cmdlet;启动使用Start-Transcript这个cmdlet。

Name参数为默认,可以省略,下例获取所有与证书处理相关的命令:

PS C:\PowerShell> Get-Command *certificate*

CommandType     Name                            Definition
-----------     ----                            ----------
Application     Certificate.Format.ps1xml       C:\WINDOWS\system32\WindowsP...
Cmdlet          Get-PfxCertificate              Get-PfxCertificate [-FilePat...

这里获得了Get-PfxCertificate cmdlet和外部程序文件Certificate.Format.ps1xml。对于PowerShell来说,应用程序类型只是代表任何能够被操作系统打开的文件,其中也包括可执行的程序和任何已经在Windows资源管理器中注册打开方式的文件。在控制台执行Certificate.Format.ps1xml命令,操作系统会用默认的打开方式notepad.exe打开该文件。

在控制台提示符下输入Get-Command help命令:

PS C:\PowerShell> Get-Command help

CommandType     Name                            Definition
-----------     ----                            ----------
Function        help                            ...
PS C:\PowerShell> Get-Command c:

CommandType     Name                            Definition
-----------     ----                            ----------
Function        C:                              Set-Location C:

PS C:\PowerShell> Get-Command ps

CommandType     Name                            Definition
-----------     ----                            ----------
Alias           ps                              Get-Process

可以看出help和 C:命令均为函数,前者用于获取帮助信息;后者用于定向到操作系统中。ps命令是Get-Process的别名。

Definition属性对于外部命令很有用,如果不记得外部命令的位置,可以使用如下方法查找:

PS C:\PowerShell> (Get-Command ping ).Definition
C:\WINDOWS\system32\ping.exe
PS C:\PowerShell> (Get-Command tracert).Definition
C:\WINDOWS\system32\tracert.exe
PS C:\PowerShell> (Get-Command calc).Definition
C:\WINDOWS\system32\calc.exe
PS C:\PowerShell> (Get-Command winword).Definition
Get-Command : The term 'winword' is not recognized as a cmdlet, function, opera
ble program, or script file. Verify the term and try again.
At line:1 char:13
+ (Get-Command <<<<  winword).Definition
    + CategoryInfo          : ObjectNotFound: (winword:String) [Get-Command],
   CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException,Microsoft.PowerShell.Co
   mmands.GetCommandCommand

3 获取对象信息

为了获取从cmdlet得到未经确认对象(如前面的实例中操作AML对象)的更多信息,可以使用Get-Member cmdlet命令列出对象成员、属性、方法及字段等。使用该命令的简便方法是通过管道为其传递对象,下例获取文件属性:

PS C:\PowerShell> Get-Item .\test.txt | Get-Member


   TypeName: System.IO.FileInfo

Name                      MemberType     Definition
----                      ----------     ----------
Mode                      CodeProperty   System.String Mode{get=Mode;}
AppendText                Method         System.IO.StreamWriter AppendText()
CopyTo                    Method         System.IO.FileInfo CopyTo(String de...
Create                    Method         System.IO.FileStream Create()
CreateObjRef              Method         System.Runtime.Remoting.ObjRef Crea...
CreateText                Method         System.IO.StreamWriter CreateText()
Decrypt                   Method         System.Void Decrypt()
Delete                    Method         System.Void Delete()
Encrypt                   Method         System.Void Encrypt()
……

输出为对象类型名及不同的成员,可以限制只输出属性,这是常用的部分:

PS C:\PowerShell> Get-Item .\test.txt | Get-Member -MemberType Property


   TypeName: System.IO.FileInfo

Name              MemberType Definition
----              ---------- ----------
Attributes        Property   System.IO.FileAttributes Attributes {get;set;}
CreationTime      Property   System.DateTime CreationTime {get;set;}
CreationTimeUtc   Property   System.DateTime CreationTimeUtc {get;set;}
Directory         Property   System.IO.DirectoryInfo Directory {get;}
DirectoryName     Property   System.String DirectoryName {get;}
Exists            Property   System.Boolean Exists {get;}
……

同样可以使用-static开关参数获取静态成员,下例获取DateTime类型的静态属性:

PS C:\PowerShell> [datetime] | Get-Member -Static -MemberType Property


   TypeName: System.DateTime

Name     MemberType Definition
----     ---------- ----------
MaxValue Property   static System.DateTime MaxValue {get;}
MinValue Property   static System.DateTime MinValue {get;}
Now      Property   System.DateTime Now {get;}
Today    Property   System.DateTime Today {get;}
UtcNow   Property   System.DateTime UtcNow {get;}

当需要静态成员时可以同时传递类型和对象实例,Get-Member会自动获取其类型,如:

PS C:\PowerShell> [datetime]::Now | Get-Member -Static -MemberType Property

   TypeName: System.DateTime

Name     MemberType Definition
----     ---------- ----------
MaxValue Property   static System.DateTime MaxValue {get;}
MinValue Property   static System.DateTime MinValue {get;}
Now      Property   System.DateTime Now {get;}
Today    Property   System.DateTime Today {get;}
UtcNow   Property   System.DateTime UtcNow {get;}

可以使用Get-Member作为低成本浏览器获取对象方法的签名,下例验证[datetime]::Parse静态方法接收字符串参数并返回DateTime对象:

PS C:\PowerShell> [datetime] | Get-Member -Name Parse -Static

   TypeName: System.DateTime

Name  MemberType Definition
----  ---------- ----------
Parse Method     static System.DateTime Parse(String s), static System.DateT...
PS C:\PowerShell> [datetime]::Parse("1/1/2010")

2010年1月1日 0:00:00

4 利用Internet获得帮助

很多.NET对象在PowerShell中没有说明文件,这些参考资料在MSDN(Microsoft Developer Network)网站上可以查到,在PowerShell中很容易创建可以用于打开浏览器窗口获取对象帮助的全局函数。

【提示】

MSDN(网址是http://msdn.microsoft.com)是微软专门为管理其相关软件开发创建的网站,其中提供软件工具分发、blog、在线社区,以及开发工具和产品的大量文档资源库。PowerShell操作的很多对象是.NET对象,这些内容都在MSDN中存档。

在PowerShell中有多种打开网站的方法,常见方法是运行浏览器实例并将URL作为基于命令行的参数传递。也可以创建Internet Explorer COM对象并用其方法浏览,最简单的方法是使用Windows脚本宿主(WSH)Shell.Application COM对象的Open()方法打开URL。从而使用默认浏览器打开指定的网站地址,如

PS C:\PowerShell> function Open-Url($url)
>> {
>>     $shell = New-Object -ComObject Shell.Application
>>     if($url -notlike "http://*")
>>     {
>>         $url= "http://"+$url
>>     }
>>     $shell.Open($url)
>> }
>>

函数会在用户未指明URL地址的http://前缀时自动添加:

PS C:\PowerShell> Open-Url "msdn.microsoft.com"

接下来会创建一个带有单个参数的Search-Msdn函数,用于为MSDN提交参数;

PS C:\PowerShell> function Search-Msdn($query)
>> {
>>     $encodeQuery = Encode-Url $query
>>     Open-Url ("http://search.msdn.microsoft.coom/search/"+ `
>>                 "Default.aspx?query=$encodeQuery")
>> }
>>

传递所有类型的字符串到URL中需要用标准的URL-encode算法编码的,这里通过使用System.Web.HttpUtility这个.NET类实现。下面的代码导入System.Web并调用类:

PS C:\PowerShell> function Encode-Url($inputString)
>> {
>>     $null = [Reflection.Assembly]::LoadWithPartialName("System.Web")
>>     return [Web.HttpUtility]::UrlEncode($inputString)
>> }
>>

用搜索函数查找关于String.Split方法的帮助:

PS C:\PowerShell> Search-Msdn "String Split"

在使用对象的情况下经常需要获取对象的类型并查找对应类型的用法,为此可以使用如下Show-MsdnHelp函数获取对象并打开MSDN的帮助页面:

PS C:\PowerShell> function Show-MsdnHelp($object)
>> {
>>     $typeName = $object.GetType().FullName
>>     Open-Url "http://msdn2.microsoft.com/en-us/library/$typeName.aspx"
>> }
>>

使用该函数获取的Get-Process cmdlet返回的对象信息如下:

PS C:\PowerShell> Show-MsdnHelp(Get-Process)[0]

如果需要更广泛的搜索,则可以创建使用基于Google或者live.com搜索的函数,下面的函数即基于第三方搜索引擎的函数:

PS C:\> function Search-Google($query)
>> {
>>     $encodeQery = Encode-Url $query
>> cd \
PS C:\> function Search-Google($query)
>> {
>>     $encodedQery = Encode-Url $query
>>     Open-Url "www.google.com/search?hl=en&q=$encodedQuery"
>> }
>>
PS C:\> Search-Google '"Windows PowerShell"'

在执行Search-LiveCom函数时将会触发Live.com搜索:

PS C:\> function Search-LiveCom($query)
>> {
>>        $encodedQuery = Encode-Url $query
>>        Open-Url "http://search.live.com/results.aspx?q=$encodedQuery"
>> }
>>
PS C:\> Search-LiveCom '"Windows PowerShell"'

可在Help-SearchWeb.ps1脚本文件中找到与网络相关的函数,最好能够复制一份到自己的Shell配置脚本中,这样这些命令在任何时候均可用。

5 总 结

在任何出现问题的情况下获取解决问题的信息是一项很重要的技能。本文说明了如何使用帮助系统获取PowerShell中可用命令的信息,并且叙述了如何发现新命令、如何检查运行中的对象并获取属性和方法信息。最后讲述了如何使用网络获取帮助,这样即可创建从在线论坛和脚本知识库中搜索答案的函数。出现问题时完全可以通过网络获取他人的经验,节省自己的时间。好的脚本程序员知道如何编写好的代码,优秀的脚本程序员充分使用之前已经写好的代码。

本人参与“2010年度中国十大杰出IT博客”评选,请大家帮忙投票,每天单个IP可投一票,谢谢!http://2010blog.51cto.com/274616

赛迪网地址:http://tech.ccidnet.com/art/302/20100715/2116051_1.html

 

作者: 付海军
出处:http://fuhj02.cnblogs.com
版权:本文版权归作者和博客园共有
转载:欢迎转载,为了保存作者的创作热情,请按要求【转载】,谢谢
要求:未经作者同意,必须保留此段声明;必须在文章中给出原文连接;否则必究法律责任
个人网站: http://txj.shell.tor.hu/