国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > PowerShell > 正文

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

2020-03-26 19:16:09
字體:
來源:轉載
供稿:網友

方法定義了一個對象可以做什么事情。當你把一個對象輸出在控制臺時,它的屬性可能會被轉換成可視的文本。但是它的方法卻不可見。列出一個對象的所有方法可是使用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
您選擇的是:
重啟
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 舞钢市| 方城县| 万州区| 佛冈县| 东至县| 洪雅县| 图木舒克市| 黄骅市| 清徐县| 江油市| 亳州市| 门头沟区| 梅州市| 永寿县| 土默特右旗| 平安县| 观塘区| 什邡市| 信宜市| 肇庆市| 济源市| 金乡县| 菏泽市| 惠州市| 龙口市| 霸州市| 乳山市| 繁昌县| 普定县| 讷河市| 郁南县| 英超| 唐山市| 镇赉县| 卢湾区| 松江区| 汉川市| 温泉县| 冕宁县| 嘉黎县| 康乐县|