我正在嘗試格式化json并進行動態變數分配,但是一旦分配了布林值,powershell就會將第一個字母的casetype更改為大寫。我仍然想保持我的輸入值的大小寫型別,因為它在我的 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"
uj5u.com熱心網友回復:
通常,您不能將$input其用作自定義變數,因為它是由 PowerShell 管理的自動變數。
撇開這一點不談,ConvertFrom-Json將trueJSON 值 - 一個布林值 - 轉換為等效的.NET 布林值( System.Boolean,[bool]在 PowerShell 中表示)。此值在 PowerShell 中的表示形式為$true.
將此值列印到控制臺(主機)有效地呼叫其.ToString()方法以獲得字串表示,并且該字串表示恰好以大寫字母開頭:
PS> $true
True
如果你需要一個全小寫的表示, call.ToString().ToLower(),或者,為了簡潔,使用一個可擴展的字串并呼叫.ToLower()它:
PS> "$true".ToLower() # In this case, the same as $true.ToString().ToLower()
true
如果您想將全小寫表示自動應用于所有 Booleans,您有兩個選擇:
通過將布林值替換為所需的字串表示來修改資料:
- 此答案顯示了如何遍歷
[pscustomobject]由回傳的物件圖ConvertFrom-Json并更新其(葉)屬性。
- 此答案顯示了如何遍歷
最好只修改值的顯示格式,
[bool]而不需要修改資料,如zett42建議的那樣。- 見下文。
(暫時)覆寫.ToString()type 的方法[bool]:
Update-TypeData可用于覆寫任意 .NET 型別的成員,但由于存在錯誤(在GitHub 問題 #14561中報告)存在限制,但至少存在 PowerShell 7.2.2:
- 當您將實體強制轉換為(例如,)或在可擴展字串(例如,)中使用它時,不
.ToString()支持覆寫[string][string] $true"$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 }
Note: You cannot scope Update-TypeData calls, which invariably take effect session-globally, so it's best to remove the override again with Remove-TypeData and restore any preexisting type data, if any, as shown above.
- zett42 has generalized the approach above to create a general-purpose
Invoke-WithTemporaryTypeDatafunction that scopes type-data modifications to a given piece of code (script block): see this Gist.
Output (note the all-lowercase property values):
TrueValue FalseValue
--------- ----------
true false
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/450866.html
標籤:视窗 电源外壳 powershell-7.0 PowerShell-7.2
上一篇:如何使批處理腳本檔案靜音
下一篇:Firebase云存盤定價混亂
