Set-Variable foo -Scope Global -Value“bar”和$ global:foo =“bar”

时间:2017-06-26 21:43:15

标签: powershell

有什么区别     Set-Variable foo -Scope Global -Value“bar” 和     $ global:foo =“bar”

我已经看到Set-Variable实现了-WhatIf / -Confim,所以只有在没有设置或确认动作的情况下才会发生赋值,而无论如何都会发生赋值。还有什么东西在潜伏吗?

更新

以下是在-Whatif / -Confirm存在时2如何不同的示例:

Clear-Variable foo -ErrorAction:SilentlyContinue # just in case
Function repro {
    [CmdletBinding(SupportsShouldProcess)] Param()
    Set-Variable foo -Scope Global -Value "bar"
}
repro -WhatIf
Write-Host "`$global:foo=$($global:foo)"

您应该看到:

What if: Performing the operation "Set variable" on target "Name: foo Value: bar".
$global:foo=

然而:

Clear-Variable foo -ErrorAction:SilentlyContinue # just in case
Function repro {
    [CmdletBinding(SupportsShouldProcess)] Param()
    $global:foo = "bar"
}
repro -WhatIf
Write-Host "`$global:foo=$($global:foo)"

现在你得到:

$global:foo=bar

1 个答案:

答案 0 :(得分:3)

差异并不大,但Set-Variable除了常规赋值表达式之外还有更多可用选项。这只是一个问题,你想要用你的语法以及你想要实现的目标是多么冗长。

分配表达式

这些是简单,快速的变量分配,并不多见。

$foo = "bar"
# If you want to change scope, add it
$global:foo = "bar"
$script:foo = "bar"

Set-Variable CmdLet

正如您所指出的,Set-Variable Cmdlet还有更多选项,例如-WhatIf-Confirm。它还有一些其他选项,例如使用-Option-PassThru设置变量类型。 -Option允许设置常量,只读变量或私有范围变量。 -PassThru非常有用,我将在下面举例说明。还可以使用其他几个参数来审核here

为什么PassThru很酷

# PassThru executes your Set-Variable and then continues to
# pass the variable through the pipeline so with it you can 
# assign your variable and then immediately start working with it
Set-Variable -Name "FooArr" -Value @("bar", "baz", "boom") -PassThru | ForEach-Object {
    $_.Value
}
$FooArr # Still assigned
bar
baz
boom

使用常量

# Constant
Set-Variable -Name "ImAConstant" -Value "Try to delete me" -Option Constant
Remove-Variable -Name "ImAConstant"
# Error
Remove-Variable : Cannot remove variable ImAConstant because it is constant or 
read-only. If the variable is read-only, try the operation again specifying the Force 
option.
At line:2 char:1
+ Remove-Variable -Name "ImAConstant"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : WriteError: (ImAConstant:String) [Remove-Variable], Ses 
   sionStateUnauthorizedAccessException
    + FullyQualifiedErrorId : VariableNotRemovable,Microsoft.PowerShell.Commands.Remo 
   veVariableCommand

使用只读

Set-Variable -Name "ImReadOnly" -Value "Delete me" -Option ReadOnly
Remove-Variable -Name "ImReadOnly" -Force # Removed

这些只是几个例子。很酷的东西。

更新至OP更新

在您的repro函数中,您在SupportsShouldProcess中使用CmdLetBinding(),但仍需要使用某些代码阻止它,以便按照您的想法运行。

Function repro {
    [CmdletBinding(SupportsShouldProcess)] Param()
    if ($pscmdlet.ShouldProcess('$global:foo', "Sets Variable")){
        $global:foo = "bar"
    }
}

这将产生与原始Set-Variable来电-WhatIf相同的结果。