【问题标题】:Script argument as private scope variable脚本参数作为私有范围变量
【发布时间】:2019-12-21 04:11:30
【问题描述】:

我可以在脚本中有一个参数,默认情况下它会变成一个全局变量,像这样

param (
    [string]$argument
)

但似乎我无法像这样控制该变量的范围

param (
    [string]$private:argument
)

在一个复杂的脚本中,主脚本中有很多函数,加上模块中的其他函数,将参数限制为 Private 似乎是一种好习惯,但我似乎不知道该怎么做。

【问题讨论】:

  • 您到底想完成什么? $argument 不是全局的,顺便说一句,它的范围仅限于定义它的脚本
  • 是的,应该说脚本不是全局的。但我想要的是让参数是私有的,所以我不必担心在脚本中的函数中使用相同的名称。我倾向于使用多个别名和像$argumentFromCommandLineBecauseReasons 这样的变量名。这很愚蠢,但它会起作用。我什至可以稍后设置一个实际的$private:argument = $argumentFromCommandLineBecauseReasons,然后设置Remove-Variable argumentFromCommandLineBecauseReasons,但这有点傻。
  • 你不必担心 :) 当你分配给嵌套范围内的变量时,它会默认创建一个新的局部变量

标签: powershell scope command-line-arguments


【解决方案1】:

如果我正确理解了您的担忧,您的脚本中有许多脚本块或函数,您担心重复使用变量名(在本例中为 argument)会导致混淆脚本级参数。

您不必担心!

至少如果你明智地设计你的功能:)

让我们看一个示例脚本:

param(
  $argument
)

function innerFunction 
{
  param(
    $innerArgument
  )

  # Now let's write to a new variable, the name of which collides with the script parameter
  $argument = $innerArgument + " and some more stuff"

  Write-Host "`$argument inside innerFunction: '$argument'"
}

Write-Host "`$argument in script: '$argument'"
innerFunction -innerArgument $argument
Write-Host "`$argument in script: '$argument'"

现在,如果我们将其存储在 test.ps1 中并像这样运行:

.\test.ps1 -argument "original argument"

我们将看到脚本级别的$argument 变量完全不受我们分配给innerFunction 内的同名变量的影响:

$argument in script: 'original argument'
$argument inside innerFunction: 'original argument and some more stuff'
$argument in script: 'original argument'

这是设计使然。当您尝试为 reading 解析变量时(例如,引用成员:$argument.Length),PowerShell 将向上遍历作用域层次结构,直到找到适当命名的变量,或者到达顶部-大多数范围内没有找到任何东西(在非严格模式下有效地解析对$null 的变量引用)。

另一方面,当您尝试写入到变量时,PowerShell 将创建一个具有相同名称的新局部变量(如果不存在),除非您限定它的范围($script:argument = ... 将覆盖此写时复制行为)。

【讨论】:

  • 啊,读写之间的细微差别。我已经理解它在两个方向上都是相同的行为。
猜你喜欢
  • 2017-11-18
  • 2013-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-14
  • 1970-01-01
  • 1970-01-01
  • 2015-04-18
相关资源
最近更新 更多