如何停止 powershell 表单将布尔值的变量赋值转换为大写字母

How to Stop powershell form Converting the variable assigment of a boolean to Uppercase letter

我正在尝试格式化 json 并进行动态变量分配,但是一旦分配了布尔值,powershell 就会将第一个字母的大小写类型更改为大写。 我仍然想为我的输入值保留大小写类型,就像在我的 json 文件中一样。

有什么帮助吗?

      {

          "input": true,
          "variable": "Relative path",
       }

  $path= "L:\test\parameter.json"
  $json = Get-Content $path | ConvertFrom-Json
  foreach ($data in $json.PSObject.Properties) { New-Variable -name $($data.name) -value $($data.value) -Force}
  
  echo $input
  True   ->>> I want it to be "true" and the value of variable to still be "Relative Path"

通常,您不能将 $input 用作自定义变量,因为它是由 PowerShell 管理的 automatic variable

撇开这个不谈,ConvertFrom-Json converts a true JSON value - a Boolean - into the equivalent .NET BooleanSystem.Boolean,在 PowerShell 中表示为 [bool])。此值在 PowerShell 中的表示形式为 $true.

将此值打印到控制台(主机)有效地调用其 .ToString() 方法以获得 string 表示,并且该字符串表示恰好以大写字母:

PS> $true
True 

如果需要 all-lowercase 表示,请调用 .ToString().ToLower(),或者为简洁起见,使用 expandable string 并调用 .ToLower() 就可以了:

PS> "$true".ToLower() # In this case, the same as $true.ToString().ToLower()
true

如果您想将all-lowercase表示自动应用到所有布尔值,您有两个选择:

  • 修改数据,将布尔值替换为所需的字符串表示形式:

    • This answer 展示了如何遍历 ConvertFrom-Json 返回的 [pscustomobject] 对象图并更新其(叶)属性。
  • 最好只修改显示格式[bool]值,不需要修改数据,如 zett42 所建议。

    • 见下文。

(暂时)覆盖 [bool] 类型的 .ToString() 方法:

Update-TypeData can be used to override the members of arbitrary .NET types, but there is a limitation due to a bug - reported in GitHub issue #14561 - 至少存在 PowerShell 7.2.2:

  • 当您一个实例[string](例如,[string] $true) 或当您在 expandable string 中使用它时(例如,"$true"

然而,隐式 布尔值字符串化,就像在 for-display 格式化期间发生的那样,它确实有效:

# Override the .ToString() method of [bool] (System.Boolean) instances:
# Save preexisting type data, if any.
$prevTypeData = Get-TypeData -TypeName System.Boolean
# Add a ScriptMethod member named 'ToString' that outputs an
# all-lowercase representation of the instance at hand. ('true' or 'false')
Update-TypeData -TypeName System.Boolean `
                -MemberType ScriptMethod -MemberName ToString `
                -Value { if ($this) { 'true' } else { 'false' } } `
                -Force

# Output a sample custom object with two Boolean properties.
[pscustomobject] @{ 
  TrueValue = $true
  FalseValue = $false
}

# Restore the original behavior:
# Note: In production code, it's best to put this in the `finally`
#       block of try / catch / finally statement.
# Remove the override again...
Remove-TypeData -TypeName System.Boolean
# ... and restore the previous data, if any.
if ($prevTypeData) { Update-TypeData -TypeData $prevTypeData }

注意:不能scopeUpdate-TypeData调用,它总是生效session-globally,所以最好使用 Remove-TypeData 再次删除覆盖并恢复任何预先存在的类型数据(如果有),如上所示。

  • zett42 概括了上述方法以创建一个 general-purpose
    Invoke-WithTemporaryTypeData 函数,该函数将 type-data 修改范围限定为给定代码段(脚本块):请参阅this Gist.

输出(注意 all-lowercase 属性 值):

TrueValue FalseValue
--------- ----------
     true      false