构造函数或方法中的Powershell 5类,write-debug或write-verbose输出

时间:2016-09-09 14:02:33

标签: class powershell powershell-v5.0

我有一个powershell类,我在使用新的Powershell 5类时尝试使用write-debug和write-verbose输出。

例如:

class TestWriteDebug
{
    TestWriteDebug()
    {
        Write-Debug "Constructor called"
    }

    verboseOutput()
    {
        Write-Verbose "Method `"verboseOutput()`" was called"
    }
}

我通过[TestWriteDebug] :: new()

调用它
$test = [TestWriteDebug]::new()
$test.verboseOutput()

我似乎无法弄清楚如何在创建对象时传递-debug和-verbose标志,或者在调用它的方法时,有人能告诉我这是如何实现的吗?

感谢您的帮助。

2 个答案:

答案 0 :(得分:4)

因为您将它们作为表达式的一部分进行调用,所以启用它们的最简单方法可能是使用Preference变量:

$DebugPreference = 'Continue'
$VerbosePreference = 'Continue'

$test = [TestWriteDebug]::new()
$test.verboseOutput()

要将它们重置为静音,请退出定义这些首选项的范围,或将值重置为'SilentlyContinue'。如果要在有限的上下文中启用它们,可以在scriptblock中执行它们:

$test = &{$DebugPreference = 'continue'; [TestWriteDebug]::new()}

答案 1 :(得分:0)

类的操作方式与Cmdlet类似(默认情况下,CmdletBinding行为就位)。要显示这些方法,只需在调用使用此类的cmdlet时添加-Verbose-Debug开关

class DemoClass {

    [string]$Name

    DemoClass([string]$Name) {
        Write-Verbose "I'm told my name is $Name"
        $this.Name = $Name
    }

    [string]GetMyName() {
        Write-Verbose "I've been asked my name"
        return "Hello, my name is $($this.Name)"
    }

}

function Invoke-NormalFunction([string]$Name) {
    $myDemo = [DemoClass]::new($Name)
    $myDemo.GetMyName()
}

function Invoke-AwesomeCmdlet {
    [CmdletBinding()]
    param([string]$Name)
    $myDemo = [DemoClass]::new($Name)
    $myDemo.GetMyName()
}

Write-Host "Normal Function:" -ForegroundColor Green
Invoke-NormalFunction('DemoBoy')

Write-Host "Cmdlet Without Verbose Switch" -ForegroundColor Green
Invoke-AwesomeCmdlet('DemoMan')

Write-Host "Cmdlet With Verbose Switch" -ForegroundColor Green
Invoke-AwesomeCmdlet('Captain Demo') -Verbose

<强>输出:

展开以下代码段,然后点击Run Code Snippet查看预期的PS输出。

div {
    background-color: DarkBlue;
    color: LightGray;
    font-weight: Bold;
}
.verbose {color: Cyan;}
.host {color: LightGreen;}
<div class='host'>Normal Function:</div>
<div>Hello, my name is DemoBoy</div>
<div class='host'>Cmdlet Without Verbose Switch</div>
<div>Hello, my name is DemoMan</div>
<div class='host'>Cmdlet With Verbose Switch</div>
<div class='verbose'>VERBOSE: I'm told my name is Captain Demo</div>
<div class='verbose'>VERBOSE: I've been asked my name</div>
<div>Hello, my name is Captain Demo</div>

更多信息

如果您希望这对整个脚本生效;不仅仅是那些使用相关开关调用的cmdlet,请将以下内容添加到脚本文件的顶部。

[CmdletBinding()]
param()