gpt4 book ai didi

parsing - 从 [string] 解析输入参数-值对的 native 机制

转载 作者:行者123 更新时间:2023-12-02 23:13:29 25 4
gpt4 key购买 nike

是否有一个原生的内置构造,​​可以使用与 cmdlet 参数相同的规则自动将控制台输入解析为变量?

例如,许多 cmdlet 接受 -parameter1 unspaced-value1 -parameter2:"spaced value2" 形式的参数-值对。 .

我想使用 Read-Host 读取字符串,然后将字符串解析为参数值对并将它们存储到$variables ,类似于 int main(argv, argc) ,但可能在关联数组或类似的东西中。

最佳答案

不确定我是否完全理解你想要的,但你肯定在描述一个哈希表,它可以简单地定义为

@{Name="Value";AnotherName="AnotherValue"}

或者更具可读性

@{
Name="Value"
AnotherName="AnotherValue"
}

两者都会输出以下内容,可以将其分配给可用于 splatting 的变量(稍后会详细介绍)

Name        Value       
---- -----
Name Value
AnotherName AnotherValue

好的,这很好,但您正在寻找一种方法来将此 adhoc 与 Read-Host 一起使用也许?这可能是 ConvertFrom-StringData 节省一天。以最简单的形式:

PS C:\Users\Cameron> $data = "Data=Awesome"

PS C:\Users\Cameron> $data | ConvertFrom-StringData

Name Value
---- -----
Data Awesome

好的……那太好了……但是 Read-Host 呢? .现在让我们试试吧!

PS C:\Users\Cameron> Read-Host | ConvertFrom-StringData
Something=Blah

Name Value
---- -----
Something Blah

如果您想要从 Read-Host 开始执行多个键/值对,这可能会变得复杂。似乎不喜欢在提示中插入新行。为了作弊,我使用 -Split-Join .拆分拆分对并连接最终创建一个换行符分隔的字符串 ConvertFrom-StringData玩得更好。 旁注有一个帖子有一个用于创建 multiline input from Read-Host 的片段但这更简单。

PS C:\Users\Cameron> ((Read-Host) -Split ";") -Join "`r`n" | ConvertFrom-StringData
Key1=Value1;Key2=Value2;Key3=Value3 <---- That is what I typed in as a response to Read-Host

Name Value
---- -----
Key1 Value1
Key2 Value2
Key3 Value3

如果您仍在阅读,请使用 splatting 并给出使用此逻辑的实际理由。

PS C:\Users\Cameron>  $results = ((Read-Host) -Split ";") -Join "`r`n" | ConvertFrom-StringData
Get-ChildItem @results

Filter=*.txt;Path=C:\\temp <---- That is what I typed in as a response to `Read-Host`

LastWriteTime : 10/22/2014 11:43:38 PM
Length : 653018
Name : out1.txt

....output truncated....

注:您应该注意到我在第二个反斜杠中键入的路径 Path=C:\\temp .原因来自 ConvertFrom-StringData 的 TechNet 文章

ConvertFrom-StringData supports escape character sequences that are allowed by conventional machine translation tools. That is, the cmdlet can interpret backslashes (\) as escape characters in the string data by using the Regex.Unescape Method, instead of the Windows PowerShell backtick character (`) that would normally signal the end of a line in a script. Inside the here-string, the backtick character does not work. You can also preserve a literal backslash in your results by escaping it with a preceding backslash, like this: \\. Unescaped backslash characters, such as those that are commonly used in file paths, can render as illegal escape sequences in your results.



小更新

((Read-Host) -Split ";") -Join "`r`n" | ConvertFrom-StringData作品我确信以下内容要简单得多。

(Read-Host).Replace(";","`r`n") | ConvertFrom-StringData

关于parsing - 从 [string] 解析输入参数-值对的 native 机制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27630925/

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