gpt4 book ai didi

powershell - 从ConvertFrom-StringData飞溅单行字符串时出错

转载 作者:行者123 更新时间:2023-12-03 01:16:49 24 4
gpt4 key购买 nike

在尝试回答this question时,我试图显示使用Read-Host中的字符串数据进行喷溅的示例,该示例确实起作用。

PS C:\temp> $results = (Read-Host) -Split ";" | ConvertFrom-StringData
Get-ChildItem @results

Filter=*.txt;Path="C:\\temp" <--- This was typed in for Read-host

哈希表已成功创建,所以我假设是这样,但是在尝试对其进行splat时,出现以下错误:
Get-ChildItem : Cannot find path 'C:\temp\System.Collections.Hashtable' because it does not exist.
At line:2 char:1
+ Get-ChildItem @results
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (C:\temp\System.Collections.Hashtable:String) [Get-ChildItem], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand

似乎问题出在我不是得到 hashtable而是 System.Object[]
$results.GetType().Fullname
System.Object[]

我的问题的根源是 ConvertFrom-StringData没有像我期望的那样返回哈希表。

如何将字符串“Filter = *。txt; Path = C:\ temp”转换为哈希表?我知道我通常可以在这里使用字符串,但是这是从读取主机输入的,因此单行字符串是我试图转换的字符串。

可能的答案

由于 ConvertFrom-StringData喜欢换行,所以我可以破解它。
PS C:\temp> $hashFromStringData = ("Filter=*.txt;Path=C:\\temp" -Split ";") -Join "`r`n" | ConvertFrom-StringData
$hashFromStringData.GetType().FullName

System.Collections.Hashtable

不知道是否有更好的方法。

最佳答案

我已经接近自己的解决方案,但是直到Micky实际写出我有任何哈希表数组时才了解确切的问题(似乎我只是在盯着[]System.Object[])。就像史蒂文·潘尼(Steven Penny)引用的ConvertFrom-StringData在每一行上都使用键/值对一样。

-Split ";" | ConvertFrom-StringData

这将通过几行来创建哈希表数组。它必须是一条连续线。我能够解决的两种方法是:
("Filter=*.txt;Path=C:\\temp" -Split ";") -Join "`r`n"

或更简单
"Filter=*.txt;Path=C:\\temp".Replace(";","`r`n")

关于powershell - 从ConvertFrom-StringData飞溅单行字符串时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27631834/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com