gpt4 book ai didi

带 if 语句的 powershell foreach-object

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

我正在尝试运行这个脚本,它基本上从文本文件中读取/解释文本并将“键”和“值”存储到哈希表中。现在我想在读取文本文件中的文本时更改特定的键和值。

以下是我文件中的文本:

line1 = apple  
line2 = firetruck
line3 = cricket
line4 = gorilla
line5 = elephant
line6 = banana
line7 = jumper
line8 = hat
line9 = deer
line10 = igloo

这是我的代码:

param
(
[Parameter(Mandatory=$true, HelpMessage="Please specify the text filename.")]$fileName
)


$hashTable = @{}
$textFile = Get-Content $filename | ForEach-Object `
{
$equalindex = $_.IndexOf("=")
$key = $_.Substring(0,$equalindex)

if($key -like "line2")
{
$key = "line2 has been changed"
}

$remainingLen = (($_.Length - 1) -$equalindex)
$value = $_.Substring($equalindex +1, $remainingLen)

if($value -like "value2")
{
$value = "value2 has been changed"
}

$hashtable.Add($key,$value)
}

$hashtable.Set_Item("line5","line5 value has been changed")
$hashtable.GetEnumerator() | Sort-Object name

当我运行我的代码时,它会输出哈希表,但不会更改我的“line2”键或“value2”值。这是完成我想要完成的任务的正确/最合乎逻辑的方法吗?

最佳答案

您需要删除前导和(或)尾随空格。试试这个:

$ht=@{}

Get-Content $filename | foreach{

$key,$value = $_.Split('=') | foreach {$_.Trim()}

if($key -like "line2")
{
$key = "line2 has been changed"
}

if($value -like "value2")
{
$value = "value2 has been changed"
}

$ht.Add($key,$value)
}

$ht.GetEnumerator() | Sort-Object name


Name Value
---- -----
line1 apple
line10 igloo
line2 has been changed firetruck
line3 cricket
line4 gorilla
line5 elephant
line6 banana
line7 jumper
line8 hat
line9 deer

关于带 if 语句的 powershell foreach-object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11090137/

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