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

所属分类: 脚本专栏 / PowerShell 阅读数: 1037
收藏 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
您选择的是:
重启

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

Powershell学习笔记--使用正则表达式查找文件

本文介绍PowerShell中使用正则表达式的查找文件的方法,PowerShell的正则表达式与微软其它语言的正则表达式是一样的,使用非常方便。
收藏 0 赞 0 分享

Windows Powershell 介绍和安装

Powershell 是运行在windows机器上实现系统和应用程序管理自动化的命令行脚本环境。微软之所以将Powershell 定位为Power,并不是夸大其词,因为它完全支持对象。其可读性,易用性,可以位居当前所有shell之首。
收藏 0 赞 0 分享

Windows Powershell 自定义控制台

这篇文章主要介绍了Windows Powershell 自定义控制台,包括选项、字体、布局和颜色四个方面的自定义风格,希望对大家有所帮助
收藏 0 赞 0 分享

windows Powershell 快速编辑模式和标准模式

powershell控制台有两种模式,一个是快速编辑模式,一个是标准模式。
收藏 0 赞 0 分享

PowerShell中查找字符串位置的IndexOf函数使用实例

这篇文章主要介绍了PowerShell中查找字符串位置的IndexOf函数使用实例,例子简单明了,容易看懂,需要的朋友可以参考下
收藏 0 赞 0 分享

PowerShell使用正则表达式查找字符串实例

这篇文章主要介绍了PowerShell使用正则表达式查找字符串实例,主要是对match运算符的使用介绍,需要的朋友可以参考下
收藏 0 赞 0 分享

PowerShell中使用正则表达式跨行匹配字符串的方法

这篇文章主要介绍了PowerShell中使用正则表达式跨行匹配字符串的方法,重点在于正则表达式的写法,需要的朋友可以参考下
收藏 0 赞 0 分享

PowerShell中查看当前版本、Windows版本、.NET版本信息的代码

这篇文章主要介绍了PowerShell中查看当前版本、Windows版本、.NET版本信息的代码,需要的朋友可以参考下
收藏 0 赞 0 分享

PowerShell 入门基础教程

Windows PowerShell 是专为系统管理员设计的新 Windows 命令行外壳程序。该外壳程序包括交互式提示和脚本环境,两者既可以独立使用也可以组合使用
收藏 0 赞 0 分享

PowerShell Contains函数查找字符串实例

这篇文章主要介绍了PowerShell Contains函数查找字符串实例,Contains函数的作用是查询一个字符串中是否存在另一个字符串,需要的朋友可以参考下
收藏 0 赞 0 分享
查看更多