当前位置 博文首页 > Windows Powershell方法(对象能做什么)

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

    作者:admin 时间:2021-02-11 18:27

    方法定义了一个对象可以做什么事情。当你把一个对象输出在控制台时,它的属性可能会被转换成可视的文本。但是它的方法却不可见。列出一个对象的所有方法可是使用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
    您选择的是:
    重启

    js
    下一篇:没有了