是否删除PowerShell会话变量?
我正在尝试设置并清除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
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