class - Powershell 5 类,构造函数或方法中的写入调试或写入详细输出

标签 class powershell powershell-5.0

我有一个 powershell 类,我正在尝试使用新的 Powershell 5 类进行写入调试和详细写入输出。

例如:

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

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

我通过 [TestWriteDebug]::new() 调用它

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

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

感谢您的帮助。

最佳答案

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

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

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

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

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

关于class - Powershell 5 类,构造函数或方法中的写入调试或写入详细输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39413401/

相关文章:

php - 你能帮助我更好地理解 PHP 类吗?

powershell convertfrom-json 选择对象差异

c# - 在 C# 中将派生类向上转换为基类

powershell - 使用 Powershell 监听按键,但不要等待

visual-studio - 如果MSBuild编译从命令行成功,则在 Debug模式下运行解决方案

powershell - 如何在PowerShell 5.1中将命令行应用程序输出输出到后台的变量中?

powershell - DSC:模块文件 *ModuleName* 不包含具有所需版本 1.0 的模块

powershell - 如何强制函数返回单个元素数组而不是包含的对象?

Python:类方法内的变量

javascript - TypeScript:类中动态声明的方法