Windows Powershell方法(对象能做什么)

所属分类: 脚本专栏 / PowerShell 阅读数: 1100
收藏 0 赞 0 分享

方法定义了一个对象可以做什么事情。当你把一个对象输出在控制台时,它的属性可能会被转换成可视的文本。但是它的方法却不可见。列出一个对象的所有方法可是使用Get-Member命令,给“MemeberType”参数 传入“Method”:

复制代码 代码如下:

PS C:Powershell> $Host | Get-Member -MemberType Method

   TypeName: System.Management.Automation.Internal.Host.InternalHost

Name                     MemberType Definition
----                     ---------- ----------
EnterNestedPrompt       Method     System.Void EnterNestedPrompt()
Equals                   Method     bool Equals(System.Object obj)
ExitNestedPrompt        Method     System.Void ExitNestedPrompt()
GetHashCode             Method     int GetHashCode()
GetType                  Method     type GetType()
NotifyBeginApplication  Method     System.Void NotifyBeginApplication()
NotifyEndApplication    Method     System.Void NotifyEndApplication()
PopRunspace             Method     System.Void PopRunspace()
PushRunspace            Method     System.Void PushRunspace(runspace runspace)
SetShouldExit            Method     System.Void SetShouldExit(int exitCode)
ToString                 Method     string ToString()

过滤内部方法

Get-Memeber列出了一个对象定义的所有方法,但并不是所有的方法都有用,有些方法的的用处非常有限。

Get_ 和 Set_ 方法

所有名称以”get_”打头的方法都是为了给对应的属性返回一个值。例如”get_someInfo()”方法的作用就是返回属性someInfo的值,因此可以直接通过属性调用。

复制代码 代码如下:

PS C:Powershell> $Host.Version

Major  Minor  Build  Revision
-----  -----  -----  --------
2      0      -1     -1

PS C:Powershell> $Host.get_Version()

Major  Minor  Build  Revision
-----  -----  -----  --------
2      0      -1     -1

类似的象”set_someinfo”一样,该方法只是为了给属性someinfo赋值,可以直接通过属性赋值调用。如果一个对象中只有”get_someinfo”,没有对应的”set_someinfo”,说明someinfo这个属性为只读属性。

标准方法

几乎每个对象都有一些继承自父类的方法,这些方法并不是该对象所特有的方法,而是所有对象共有的方法。
Equals 比较两个对象是否相同
GetHashCode 返回一个对象的数字格式的指纹
GetType 返回一个对象的数据类型
ToString 将一个对象转换成可读的字符串

过滤包含了下划线的方法可是使用操作符 -notlike 和 通配符 *

复制代码 代码如下:

PS C:Powershell> $Host.UI.RawUI | Get-Member -me method | where {$_.Name -notlike '*_*'}

   TypeName: System.Management.Automation.Internal.Host.InternalHostRawUserInterface

Name                 MemberType Definition
----                 ---------- ----------
Equals               Method     bool Equals(System.Object obj)
FlushInputBuffer      Method     System.Void FlushInputBuffer()
GetBufferContents    Method     System.Management.Automation.Host.BufferCell[,] GetBufferCo
GetHashCode           Method     int GetHashCode()
GetType               Method     type GetType()
LengthInBufferCells  Method     int LengthInBufferCells(string str), int LengthInBufferCell
NewBufferCellArray  Method     System.Management.Automation.Host.BufferCell[,] NewBufferCe
ReadKey               Method     System.Management.Automation.Host.KeyInfo ReadKey(System.Ma
ScrollBufferContents Method     System.Void ScrollBufferContents(System.Management.Automati
SetBufferContents    Method     System.Void SetBufferContents(System.Management.Automation.
ToString              Method     string ToString()

调用方法

一定要注意,在调用一个方法前,必须知道这个方法的功能。因为有的命令可能比较危险,例如错误地修改环境变量。调用一个方法,通过圆点加圆括号:
$Host.GetType()

调用带参数的方法

UI对象有很多实用的方法,可以通过get-member预览

复制代码 代码如下:

PS C:Powershell> $Host.UI | Get-Member -MemberType method

   TypeName: System.Management.Automation.Internal.Host.InternalHostUserInterface

Name                   MemberType Definition
----                   ---------- ----------
Equals                 Method     bool Equals(System.Object obj)
GetHashCode            Method     int GetHashCode()
GetType                Method     type GetType()
Prompt                 Method     System.Collections.Generic.Dictionary[string,psob
PromptForChoice        Method     int PromptForChoice(string caption, string messag
PromptForCredential    Method     System.Management.Automation.PSCredential PromptF
ReadLine                Method     string ReadLine()
ReadLineAsSecureString Method     System.Security.SecureString ReadLineAsSecureStri
ToString                Method     string ToString()
Write  Method     System.Void Write(string value), System.Void Writ
WriteDebugLine        Method     System.Void WriteDebugLine(string message)
WriteErrorLine          Method     System.Void WriteErrorLine(string value)
WriteLine               Method     System.Void WriteLine(), System.Void WriteLine(Sy
WriteProgress           Method     System.Void WriteProgress(long sourceId, System.M
WriteVerboseLine      Method     System.Void WriteVerboseLine(string message)
WriteWarningLine      Method     System.Void WriteWarningLine(string message)

哪一个参数是必须的
从列表中筛选出一个方法,再通过Get-Member得到更多的信息。

复制代码 代码如下:

PS C:Powershell> $info=$Host.UI |  Get-Member WriteDebugLine
PS C:Powershell> $info

   TypeName: System.Management.Automation.Internal.Host.InternalHostUserInterface

Name           MemberType Definition
----           ---------- ----------
WriteDebugLine Method     System.Void WriteDebugLine(string message)

PS C:Powershell> $info.Definition
System.Void WriteDebugLine(string message)

Definition属性告诉你怎样调用一个方法,每一个方法的定义都会返回一个Objec对象,System.Void 是一个特殊的类型,代表什么都没有,即返回值为空。
接下来就可以根据函数的定义,给它传进合适的参数调用了。

复制代码 代码如下:

PS C:Powershell> $Host.UI.WriteDebugLine("Hello 2012 !")
调试: Hello 2012 !

低级函数

上述的WriteDebugLine()函数并没有什么特别。事实上所谓的$Host中的很多方法只不过是一些简单的Cmdlets命令。例如使用如下cmdlet输出一条调试通知

复制代码 代码如下:

PS C:Powershell> Write-Debug "Hello 2012 !"
PS C:Powershell> Write-Debug -Message "Hello 2012 !"

上述的命令并没有输出黄色的调试信息,这和$DebugPreference配置有关,因为$DebugPreference的默认值为:SilentlyContinue。
当$DebugPreference为Stop,Continue,Inquire时就会输出调试消息:

复制代码 代码如下:

PS C:Powershell> [System.Enum]::GetNames([System.Management.Automation.ActionPreference])
SilentlyContinue
Stop
Continue
Inquire
PS C:Powershell> $DebugPreference="stop"
PS C:Powershell> Write-Debug "Hello 2012"
调试: Hello 2012
Write-Debug : 已停止执行命令,因为首选项变量“DebugPreference”或通用参数被设置为 Stop。
所在位置 行:1 字符: 12
+ Write-Debug <<<<  "Hello 2012"     + CategoryInfo          : OperationStopped: (:) [Write-Debug], ParentContainsErrorRecordException     + FullyQualifiedErrorId : ActionPreferenceStop,Microsoft.PowerShell.Commands.WriteDebugCommand PS C:Powershell> $DebugPreference="continue"
PS C:Powershell> Write-Debug "Hello 2012"
调试: Hello 2012

WriteErrorLine,WriteVerboseLine,WriteWarningLine的情况也类似。如果你不想受$DebugPreference配置的依赖,输出错误消息可以直接使用 $host.UI.WriteDebugLine()方法。

多个方法的签名

有些方法名相同,可以接受不同类型或者不同个数的参数,如何查看一个方法支持的所有签名 ,使用Get-Member获取方法对象,然后查看Definition属性。

复制代码 代码如下:

PS C:Powershell> $method
PS C:Powershell> $method=$Host.UI | Get-Member WriteLine
PS C:Powershell> $method.Definition
System.Void WriteLine(), System.Void WriteLine(System.ConsoleColor foregroundColor, System.ConsoleColor backgroundColor
, string value), System.Void WriteLine(string value)

但是Definition的输出阅读不方便,可是稍加润色。

复制代码 代码如下:

PS C:Powershell> $method.Definition.Replace("),",")`n")
System.Void WriteLine()
System.Void WriteLine(System.ConsoleColor foregroundColor, System.ConsoleColor backgroundColor, string value)
System.Void WriteLine(string value)

创建选择菜单

这里需要使用$host.UI.PromptForChoice()方法,先查看方法的定义:

复制代码 代码如下:

PS C:Powershell> $host.ui.PromptForChoice

MemberType          : Method
OverloadDefinitions : {int PromptForChoice(string caption, string message, System.Collections.ObjectModel.Collection[Sy
                      stem.Management.Automation.Host.ChoiceDescription] choices, int defaultChoice), System.Collection
                      s.ObjectModel.Collection[int] PromptForChoice(string caption, string message, System.Collections.
                      ObjectModel.Collection[System.Management.Automation.Host.ChoiceDescription] choices, System.Colle
                      ctions.Generic.IEnumerable[int] defaultChoices)}
TypeNameOfValue     : System.Management.Automation.PSMethod
Value               : int PromptForChoice(string caption, string message, System.Collections.ObjectModel.Collection[Sys
                      tem.Management.Automation.Host.ChoiceDescription] choices, int defaultChoice), System.Collections
                      .ObjectModel.Collection[int] PromptForChoice(string caption, string message, System.Collections.O
                      bjectModel.Collection[System.Management.Automation.Host.ChoiceDescription] choices, System.Collec
                      tions.Generic.IEnumerable[int] defaultChoices)
Name                : PromptForChoice
IsInstance          : True

下面的脚本演示如何创建选择菜单:

复制代码 代码如下:

$SwitchUser = ([System.Management.Automation.Host.ChoiceDescription]"&Switchuser")
$LoginOff = ([System.Management.Automation.Host.ChoiceDescription]"&LoginOff")
$Lock= ([System.Management.Automation.Host.ChoiceDescription]"&Lock")
$Reboot= ([System.Management.Automation.Host.ChoiceDescription]"&Reboot")
$Sleep= ([System.Management.Automation.Host.ChoiceDescription]"&Sleep")

$selection = [System.Management.Automation.Host.ChoiceDescription[]]($SwitchUser,$LoginOff,$Lock,$Reboot,$Sleep)
$answer=$Host.UI.PromptForChoice('接下来做什么事呢?','请选择:',$selection,1)
"您选择的是:"
switch($answer)
{
0 {"切换用户"}
1 {"注销"}
2 {"锁定"}
3 {"重启"}
4 {"休眠"}
}

复制代码 代码如下:

PS C:PowerShell> .test.ps1
接下来做什么事呢?
请选择:
[S] Switchuser  [L] LoginOff  [L] Lock  [R] Reboot  [S] Sleep  [?] 帮助 (默认值为“L”): Reboot
您选择的是:
重启

更多精彩内容其他人还在看

Windows Powershell 管道和重定向

这篇文章主要介绍了Windows Powershell 管道和重定向,需要的朋友可以参考下
收藏 0 赞 0 分享

Windows Powershell 进行数学运算

在Windows PowerShell中, 使用数学运算符来进行数学运算,数学运算符允许你在命令参数中计算数值. 你可以使用一个或者多个运算符进行加减乘除法, 也可以返回除法的余数(模). 包含这些计算的参数, 将计算结果作为参数值. 命令就像处理其他类型参数一样, 来处理参数值
收藏 0 赞 0 分享

Windows Powershell 执行外部命令

Windows PowerShell 在使用方面与 Cmd.exe 并无多大不同,只是 Windows PowerShell 的功能更为强大。与 Cmd.exe 一样,Windows PowerShell 具有内置的脚本编写语言,不过它比 Cmd.exe 原始的批处理语言更为灵活
收藏 0 赞 0 分享

Windows Powershell 命令集 cmdlets

在Windows PowerShell中,需要使用cmdlet执行指令。一个cmdlet代表着可操作某一对象的功能命令,cmdlet可使用"动词-名词"形式的语法:一个动词和一个名词,中间使用连字符连接,例如get-service和start-service。
收藏 0 赞 0 分享

Windows Powershell 别名

简单的说在Windows PowerShell中, 别名就是cmdlets或其他命令的替代名称.为什么要替代cmdlets呢,因为cmdlets命令说实话有点麻烦。
收藏 0 赞 0 分享

Windows Powershell 通过函数扩展别名

这篇文章主要介绍了Windows Powershell 通过函数扩展别名,需要的朋友可以参考下
收藏 0 赞 0 分享

Windows Powershell 执行文件和脚本

PowerShell脚本提供了一个方便的方法来自动化各种琐事。下面是关于PowerShell的一些基本概念,对于PowerShell初学者,掌握这些概念有助于加深对PowerShell脚本的理解。
收藏 0 赞 0 分享

Powershell小技巧之系统运行时间

本文主要教你如何使用powershell计算系统运行时间,其实很简单,因为Windows每次启动都有一个高进度计数器并且当系统运行这个计数器将返回一个毫秒,我们把这个毫秒计算下就得到系统运行时间了
收藏 0 赞 0 分享

Powershell小技巧之使用WMI测试服务响应

这篇文章主要介绍了Powershell小技巧之使用WMI测试服务响应,需要的朋友可以参考下
收藏 0 赞 0 分享

Powershell小技巧之使用WMI查询插上的U盘

本文主要讲诉了如何使用WMI查询当前插在你电脑上的USB设备,非常简单,学习powershell的同学可以参考下
收藏 0 赞 0 分享
查看更多