gpt4 book ai didi

powershell - 如何使用PowerShell从字符串读取特定变量?

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

有一个包含此内容的文件

   SomeText1

SomeCommand -parameterName abc -login def -password geh

SomeText2

您能否建议使用什么PowerShell才能将数组的变量和值(例如键/值对)读入数组
 login=def
password=geh

关于该问题的具体之处在于,登录名和密码参数的顺序可能不同,因此我需要找到基于已知键名来定位键/值的方法。另外,我知道我只需要登录名和密码参数以及相关值。

提前非常感谢您的帮助!

附言我打算使用以下命令来读取文件内容,但是可以更改:
$GetFileName = "$env:userprofile\Desktop\Folder\Input.txt" 

$content = [IO.File]::ReadAllText($GetFileName)

最佳答案

Select-String cmdlet提供了使用正则表达式从文件中提取信息的便捷方法:

$inputFile = "$env:userprofile\Desktop\Folder\Input.txt"

# Extract the information of interest and output it as a hashtable.
# Use $ht = Select-String ... to capture the hashtable in a variable.
Select-String -Allmatches '(?<=-(login|password) +)[^ ]+' $inputFile |
ForEach-Object {
foreach ($match in $_.Matches) {
@{ $match.Groups[1] = $match.Value }
}
}

使用示例输入,输出是单个哈希表(如果多行匹配,则将为每行获得一个哈希表):
Name                           Value
---- -----
login def
password geh
  • -AllMatches告诉Select-String在每一行上搜索多个匹配项。
  • 正则表达式'(?<=-(login|password) +)[^ ]+'捕获与参数-login-password相关联的参数,同时在捕获组中捕获参数名称。
  • 注意,正则表达式假定参数值没有嵌入空格,但这通常是用户名和密码中的安全假设。
  • foreach ($match in $_.Matches)处理每个匹配项,并构造并输出一个哈希表(@{ ... }),该哈希表的键是捕获的参数名称,其值是捕获的参数。
  • 关于powershell - 如何使用PowerShell从字符串读取特定变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53110215/

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