首页 > 解决方案 > 强制导入值为整数

问题描述

我正在尝试在运行的脚本实例之间保存值。

我通过在脚本开头读取一个文本文件,然后在脚本末尾用新值覆盖该文件来做到这一点。

跟踪器.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

解决方案


为了保存值,请考虑使用 Powershell 自己的对象序列化。也就是说,Export-Clixml还有Import-Clixmlcmdlet。当一个对象被序列化时,它的内容被写入一个文件。除了值之外,还有数据类型。

如果将多个变量存储在诸如哈希表之类的集合中,则处理多个变量会更容易。像这样,

# 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。否则,序列化只保存两层嵌套,这会破坏复杂的对象。


推荐阅读