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

2019-09-30 14:39:54于海丽

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