无法将字符串设置为我的标题
我正在尝试将此字符串设置为我的键:
a -long " string that - has. double and single quotes and dashes and dots
此字符串是字符串构建器ToString()方法的产物。
像这样初始化了hashtable:$ myhashtable = @{}
这是错误:无法将值“ stringabove”转换为type“ system.int32”。错误:“输入字符串不是正确的格式。”
我尝试用回答逃脱双引号。但仍然有同样的错误。
$resultFromToString = $myBuilder.ToString()
$myHashtable[$resultFromToString] = @{
One = $one;
Two = $two;
}
I'm trying to set this string as my key:
a -long " string that - has. double and single quotes and dashes and dots
This string is the product of String Builder ToString() method.
The Hashtable is initialized like this: $myHashtable = @{ }
This is the error: Cannot convert value "stringAbove" to type "System.Int32". Error: "Input string was not in a correct format."
I tried escaping the double quotation marks with a backtick. But got still the same error.
$resultFromToString = $myBuilder.ToString()
$myHashtable[$resultFromToString] = @{
One = $one;
Two = $two;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
错误消息暗示
$ myhashtable
包含一个 array ,而不是 hashtable 。要确定
$ myhashtable
的实际类型,执行$ myhashtable.getType()
或鉴于 任何值的字符串 - 甚至
''
- 可以用作hashtable键:uppute value 值: :
至于您尝试过的:
相比之下,如果
$ myhashtable
是 array (无论其 elements的类型),您的症状表面,具有 字符串值(不能转换为整数),鉴于只有 integers 可以用作数组索引:错误输出:
请注意,当错误消息提示时,PowerShell会自动尝试转换为整数的字符串索引,以便以下 die 工作,也许令人惊讶:
The error message implies that
$myHashtable
contains an array, not a hashtable.$myHashtable
, execute$myHashtable.GetType()
orGet-Member -InputObject $myHashtable
This example shows that there's no problem with your string, given that a string with any value - even
''
- can serve as a hashtable key:Output:
As for what you tried:
By contrast, if
$myHashtable
is an array (irrespective of the type of its elements), your symptom surfaces, with any string value (that can't be converted to an integer), given that only integers can serve as array indices:Error output:
Note that, as the error message hints at, PowerShell automatically tries to convert a string index to an integer, so that something like the following does work, perhaps surprisingly: