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

所属分类: 脚本专栏 / PowerShell 阅读数: 1117
收藏 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时隐藏自己的窗口、在PowerShell启动其它进程时隐藏窗口、使用PowerShell隐藏其它进程的窗口三种方法,需要的朋友可以参考下
收藏 0 赞 0 分享

PowerShell启用winrm失败:拒绝访问 0x80070005 -2147024891

这篇文章主要介绍了PowerShell启用winrm失败:拒绝访问 0x80070005 -2147024891,本文给出了详细的排查步骤和解决方法,需要的朋友可以参考下
收藏 0 赞 0 分享

Powershell目录文件夹管理权限的继承和指定方法

这篇文章主要介绍了Powershell目录文件夹管理权限的继承和指定方法,本文给出了创建文件夹、获取当前权限、添加新的权限、添加管理员权限等,需要的朋友可以参考下
收藏 0 赞 0 分享

PowerShell查看本机文件关联程序和默认打开程序的方法

这篇文章主要介绍了PowerShell查看本机文件关联程序和默认打开程序的方法,本文给出了查看方法,同时给出了一份读取结果,需要的朋友可以参考下
收藏 0 赞 0 分享

PowerShell脚本反引号用法实例:随时随地给代码换行

这篇文章主要介绍了PowerShell脚本反引号用法实例:随时随地给代码换行,在遇到一些超长代码行时非常有用,一般编程代码一行的字符数不超过80个哦,需要的朋友可以参考下
收藏 0 赞 0 分享

PowerShell 数组的多种录入方法

这篇文章主要介绍了PowerShell 数组的多种录入方法,需要的朋友可以参考下
收藏 0 赞 0 分享

PowerShell String对象方法小结

这篇文章主要介绍了PowerShell String对象方法,需要的朋友可以参考下
收藏 0 赞 0 分享

使用PowerShell获取当前主机内存使用量和总量的方法

这篇文章主要介绍了使用PowerShell获取当前主机内存使用量和总量的方法,需要的朋友可以参考下
收藏 0 赞 0 分享

PowerShell批量修改AD用户密码属性的代码

这篇文章主要介绍了PowerShell批量修改AD用户密码属性的代码,需要的朋友可以参考下
收藏 0 赞 0 分享

PowerShell 自动备份oracle并上传到ftp

我这里有这样一个需求:有一个数据库,每天使用SQL Server Agent自动生成备份文件。然后,这个数据库非常重要,需要把每天的备份上传一个远程的FTP服务器上去。下面我们来看看如何使用Powershell来实现吧
收藏 0 赞 0 分享
查看更多