Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
是否删除PowerShell会话变量?_Powershell - Fatal编程技术网

是否删除PowerShell会话变量?

是否删除PowerShell会话变量?,powershell,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 ses

我正在尝试设置并清除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
以及:


有什么方法可以做到这一点吗?

如果您想使用
$PSCmdlet
@MathiasR.Jessen,可以将
[CmdletBinding()]param()
添加到
删除变量
函数中。如果您想使用
$PSCmdlet
@MathiasR.Jessen,可以将
[CmdletBinding()]param()
添加到
删除变量
函数中。
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