删除PowerShell会话变量?

时间:2016-11-11 15:17:06

标签: powershell

我试图在PowerShell模块中设置和清除会话变量:

function Set-Variable
{
    [CmdletBinding()]
    param(
        [string]$Value = $PSCmdlet.SessionState.PSVariable.Get('Value').Value
    )

    # if `Value` not supplied on the command line and not available in the session, prompt for it
    if (!$PSCmdlet.SessionState.PSVariable.Get('Value') -And !$Value) {
        $Value = Read-Host "Value"
    }

    # if `Value` has been supplied on the command line, save it in the session
    if ($Value) {
        $PSCmdlet.SessionState.PSVariable.Set('Value',$Value)

    }

}
Export-ModuleMember Set-Variable

function Remove-Variable { 
    $PSCmdlet.SessionState.PSVariable.Remove('Value')

    # also throws an exeception
    # $PSCmdlet.SessionState.PSVariable.Set('Value',$null)
}
Export-ModuleMember Remove-Variable

设置值按预期工作,但是,删除变量或将其值设置为null会产生错误:

PS> Remove-Variable
You cannot call a method on a null-valued expression.At
C:\Users\XXXX\Documents\WindowsPowerShell\Modules\foo\foo.psm1:39 char:5
+     $PSCmdlet.SessionState.PSVariable.Remove('Value')
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

You cannot call a method on a null-valued expression.At
C:\Users\XXXX\Documents\WindowsPowerShell\Modules\foo\foo.psm1:37 char:5
+     $PSCmdlet.SessionState.PSVariable.Set('Value',$null)
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

有办法做到这一点吗?

0 个答案:

没有答案