powershell - 强制导入值为整数
问题描述
我正在尝试在运行的脚本实例之间保存值。
我通过在脚本开头读取一个文本文件,然后在脚本末尾用新值覆盖该文件来做到这一点。
跟踪器.txt:
x=1
y=4
z=3
我正在阅读脚本:
Get-Content "$Root\tracker.txt" | Foreach-Object{
$Position = $_.Split("=")
New-Variable -Name $Position[0] -Value $Position[1]
}
不幸的是,我的 $x $y 和 $z 变量被解释为字符串而不是整数。
查找 New-Variable 参数,我似乎无法指定值类型。
我也试过:
New-Variable -Name $Position[0] -Value [int]$Position[1]
和:
New-Variable -Name $Position[0] -Value ($Position[1] + 0)
但两者都没有按预期工作。
如何将这些变量设置为整数?我试图稍后在循环中使用它们,但由于变量不能是字符串,所以一直失败。
解决方案
为了保存值,请考虑使用 Powershell 自己的对象序列化。也就是说,Export-Clixml
还有Import-Clixml
cmdlet。当一个对象被序列化时,它的内容被写入一个文件。除了值之外,还有数据类型。
如果将多个变量存储在诸如哈希表之类的集合中,则处理多个变量会更容易。像这样,
# Save some values in a hash table
$myKeys =@{ "a" = 1; "b" = 2 }
$myKeys["a"]
1
# Check variable a's type. Int32 is as expected
$myKeys["a"].gettype()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Int32 System.ValueType
# Serialize the hash table
Export-Clixml -Path keys.xml -InputObject $myKeys
# Create a new hash table by deserializing
$newKeys = Import-Clixml .\keys.xml
# Check contents
$newkeys["a"]
1
# Is the new a also an int32? Yes, it is
$newkeys["a"].gettype()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Int32 System.ValueType
keys.xml
正如预期的那样,它是一个 XML 文件。用记事本检查它的内容,看看对象是如何存储的。处理复杂对象时,-Depth
需要使用 switch。否则,序列化只保存两层嵌套,这会破坏复杂的对象。
推荐阅读
- r - R/Shiny - 将复选框标签转移到功能字段
- autodesk - EAGLE:是否可以使用“print-inductor.ulp”文件创建 90 度轨迹转弯?
- c# - for 循环内的异步 HTTP 请求,没有同时等待异步操作
- macos - 在 macOS 上,为什么 'docker system df' 显示总共 18 个 * 和 * 活动容器,但 'docker ps' 是空的
- ruby-3 - montrose gem 在使用期间不工作
- c++ - 尝试使用带有 arduino ide 的 esp32 制作自定义快捷键
- google-chrome - 如何自定义 Chromium(Windows 平台)
- c++ - 替换 gtk_dialog_get_action_area?
- spring-boot - 我可以为我的执行器基本路径设置多级路径吗?
- android - 在回收器视图上滚动并使文本视图与回收器视图中的特定项目一起移动,而文本可能比项目视图的宽度长