powershell - 将 -Verbose 状态传递给模块 cmdlet

标签 powershell powershell-module

我有一个PowerShell模块,封装了一些常用的业务功能。通常不会从控制台调用它;相反,它的功能是由导入模块的自动部署和管理脚本调用的。

该模块包含一个日志记录功能,可以写入集中式日志记录位置。我还想加入 Write-Verbose还可以写入控制台的功能。

#'Start Script.ps1
#'----------------

Import-Module Corporate
Write-Logger 'Foo'

我的限制是 - 从企业 PowerShell 模块内 - 我需要确定是否已使用 -Verbose 参数调用 Script.ps1。理想情况下,我希望确定代码完全在模块本身内。

这是一个例子:

[CmdletBinding()]
Param ()

New-Module -Name TempModule -ScriptBlock {
    function Test-ModuleVerbose() {
        [CmdletBinding()]
        Param ()

        PROCESS {
            $vb = ($PSCmdlet.MyInvocation.BoundParameters['Verbose'] -eq $true)
            Write-Host ("1: Module verbose preference: " + ($PSCmdlet.MyInvocation.BoundParameters['Verbose'] -eq $true))
            Write-Host ("2: Module verbose preference: " + $Script:VerbosePreference)
            Write-Host ("3: Module verbose preference: " + $VerbosePreference)
        }
    }
} | Out-Null

function Test-Verbose() {
    [CmdletBinding()]
    Param ()

    PROCESS {
        Write-Host ("Verbose preference: $VerbosePreference")
        Test-ModuleVerbose
    }
}

Test-Verbose

将以上内容保存为test.ps1。从控制台调用时:

PS C:\temp> .\test.ps1
Verbose preference: SilentlyContinue
1: Module verbose preference: False
2: Module verbose preference:
3: Module verbose preference: SilentlyContinue

PS C:\temp> .\test.ps1 -Verbose
VERBOSE: Exporting function 'Test-ModuleVerbose'.
VERBOSE: Importing function 'Test-ModuleVerbose'.
Verbose preference: Continue
1: Module verbose preference: False
2: Module verbose preference:
3: Module verbose preference: SilentlyContinue

如您所见,$VerbosePreference 变量在模块内不可用。有没有办法从模块内部获取调用脚本是否已使用 -Verbose 标志调用?

最佳答案

可以使用匹配的首选项变量和类似 -Parameter:$ParameterPreference 的语法来传递大多数常用参数。因此,对于详细的特定情况,语法为 -Verbose:$VerbosePreference

有一些异常(exception):

  • Debug :$DebugPreference 的值自动传递,但指定 -Debug < em>切换强制 $DebugPreference 查询
  • WhatIf:自动传递。

我修改了OP代码示例如下:

[CmdletBinding(SupportsShouldProcess=$true)]
param(
    [Switch]$FullPassThru
)

New-Module -Name TempModule -ScriptBlock {
        function Test-ModuleVerbose
        {
            [CmdletBinding(SupportsShouldProcess=$true)]
            param ()

            Write-Host "1: Module: verbose parameter is bound : $($PSCmdlet.MyInvocation.BoundParameters['Verbose'])"
            Write-Host "2: Module: verbose preference         : $VerbosePreference"

            # Write-Verbose will just work without any change
            Write-Verbose "Verbose"

            # Other commands need the $VerbosePreference passed in
            Set-Item -Path Env:\DEMONSTRATE_PASS_THRU `
                     -Value 'You can safely delete this variable' `
                     -Verbose:$VerbosePreference
        }

        function Test-ModulePreferencePassThru
        {
            [CmdletBinding(SupportsShouldProcess=$true)]
            param()

            Write-Debug   "DebugPreference: $DebugPreference"
            Write-Warning "WarningPreference: $WarningPreference"
            Write-Error   "ErrorActionPreference: $ErrorActionPreference"

            Set-Item -Path Env:\DEMONSTRATE_PASS_THRU `
                     -Value 'You can safely delete this variable' `
                     -Verbose:$VerbosePreference `
                     -WarningAction:$WarningPreference `
                     -ErrorAction:$ErrorActionPreference
        }
    } | Out-Null

function Test-Verbose
{
    [CmdletBinding(SupportsShouldProcess=$true)]
    param()

    Write-Host ("Verbose preference: $VerbosePreference")
    Test-ModuleVerbose -Verbose:$VerbosePreference
}

function Test-PreferencePassThru
{
    [CmdletBinding(SupportsShouldProcess=$true)]
    param()

    Test-ModulePreferencePassThru -Verbose:$VerbosePreference
}

try
{
    if ($FullPassThru -eq $false)
    {
        # just demonstrate -verbose pass-through
        Test-Verbose
    }
    else
    {
        # most of the preferences can be explicitly passed-through, however:
        #
        #  -Debug  : $DebugPreference is automatically passed-through
        #            and -Debug forces $DebugPreference to 'Inquire'
        #  -WhatIf : automatically passed-through
        Test-ModulePreferencePassThru -Verbose:$VerbosePreference `
                                        -WarningAction:$WarningPreference `
                                        -ErrorAction:$ErrorActionPreference | Out-Null
    }
}
finally
{
    # cleanup
    Remove-Item -Path Env:\DEMONSTRATE_PASS_THRU -Force | Out-Null
}

将以上内容保存为test.ps1。从控制台调用时:

PS C:\temp> .\test.ps1
Verbose preference: SilentlyContinue
1: Module: verbose parameter is bound : False
2: Module: verbose preference         : SilentlyContinue

PS C:\temp> .\test.ps1 -Verbose
VERBOSE: Exporting function 'Test-ModuleVerbose'.
VERBOSE: Exporting function 'Test-ModulePreferencePassThru'.
VERBOSE: Importing function 'Test-ModulePreferencePassThru'.
VERBOSE: Importing function 'Test-ModuleVerbose'.
Verbose preference: Continue
1: Module: verbose parameter is bound : True
2: Module: verbose preference         : Continue
VERBOSE: Verbose
VERBOSE: Performing the operation "Set Item" on target "Item: DEMONSTRATE_PASS_THRU Value: You can safely delete this variable".

此外,$DebugPreference$WarningPreference$ErrorActionPreference 的传递也有效:

PS C:\temp> $VerbosePreference  = 'Continue'
PS C:\temp> $DebugPreference = 'Continue'
PS C:\temp> $WarningPreference = 'Continue'
PS C:\temp> $ErrorActionPreference = 'Continue'
PS C:\temp> .\test.ps1 -FullPassThru
VERBOSE: Exporting function 'Test-ModuleVerbose'.
VERBOSE: Exporting function 'Test-ModulePreferencePassThru'.
VERBOSE: Importing function 'Test-ModulePreferencePassThru'.
VERBOSE: Importing function 'Test-ModuleVerbose'.
DEBUG: DebugPreference: Continue
WARNING: WarningPreference: Continue
Test-ModulePreferencePassThru : ErrorActionPreference: Continue
At C:\OAASMain\Online\ContainerService\Tools\docker\test.ps1:72 char:9
+         Test-ModulePreferencePassThru -Verbose:$VerbosePreference `
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Test-ModulePreferencePassThru

VERBOSE: Performing the operation "Set Item" on target "Item: DEMONSTRATE_PASS_THRU Value: You can safely delete this variable".

-WhatIf 自动传递:

PS C:\temp> .\test.ps1 -FullPassThru -WhatIf
What if: Performing the operation "Remove Item" on target "Item: DEMONSTRATE_PASS_THRU".

这也处理 -WarningAction-ErrorAction:

PS C:\temp> .\test.ps1 -FullPassThru -WarningAction Ignore -ErrorAction Stop
Test-ModulePreferencePassThru : ErrorActionPreference : Stop
At C:\OAASMain\Online\ContainerService\Tools\docker\test.ps1:72 char:9
+         Test-ModulePreferencePassThru -Verbose:$VerbosePreference `
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Test-ModulePreferencePassThru

关于powershell - 将 -Verbose 状态传递给模块 cmdlet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20961063/

相关文章:

powershell - foreach循环不执行变量

windows - 使用 powershell 写入 excel 时防止覆盖弹出窗口

powershell - 移动项目不移动所有文件

session - 在不退出的情况下刷新/重新启动 PowerShell session

c# - cmdlet 写入控制台而不写入管道

Powershell - Export-ModuleMember 不起作用

powershell - 新模块可以返回一个 psobject 吗?

powershell - Powershell 命令 "Get-DistributionGroup"不起作用