【问题标题】:Replace string in variable from data in a text file in Powershell从Powershell中文本文件中的数据替换变量中的字符串
【发布时间】:2017-12-16 17:39:09
【问题描述】:

我有一个 powershell 脚本,它返回将由 Splunk 摄取其信息的行,以监控 DHCP 空闲地址。

输出已经经过大量“处理”,看起来像这样(&&& 是 Splunk 事件断路器):

Subnet=10.31.3.0
AddressesInUse=0
AddressesFree=249
&&&
Subnet=10.31.4.0
AddressesInUse=0
AddressesFree=249
&&&
Subnet=10.31.9.0
AddressesInUse=0
AddressesFree=249
&&&
Subnet=10.32.1.0
AddressesInUse=32
AddressesFree=177
&&&
Subnet=10.34.1.0
AddressesInUse=98
AddressesFree=111
&&&

不过,我有一个例外列表,其中包含必须忽略的子网值。我打算将它们写入一个文本文件,从中获取内容,并将变量中的子网值(来自命令结果)替换为 -eq 到任何文本文件行,将其转换为“”(然后我打算在 Splunk 中使用“IfNull(SubnetValue) then ignore event”忽略它们。

预期结果应如下所示:

文件 SubnetExceptions.txt 内容示例:

10.32.1.0
10.34.1.0

预期结果:

Subnet=10.31.3.0
AddressesInUse=0
AddressesFree=249
&&&
Subnet=10.31.4.0
AddressesInUse=0
AddressesFree=249
&&&
Subnet=10.31.9.0
AddressesInUse=0
AddressesFree=249
&&&
Subnet=
AddressesInUse=32
AddressesFree=177
&&&
Subnet=
AddressesInUse=98
AddressesFree=111
&&&

所以我想忽略的那些会作为 Splunk 的“空”值,解决我的问题 :)

我在生活中做了一些替换,但从来没有从文本文件中替换。我的测试惨遭失败。有人可以帮我做吗?

谢谢!

  • 大卫

【问题讨论】:

    标签: powershell variables replace


    【解决方案1】:

    此代码将以正则表达式格式加入您的 ip 以替换 ip

    "$((Get-Content 'C:\Vincent\Test\IP.txt') -join '$|')$"
    10.32.1.0$|10.34.1.0$  
    

    "Subnet=$((Get-Content 'C:\Vincent\Test\IP.txt') -join '$|Subnet=')$",'Subnet='
    Subnet=10.32.1.0$|Subnet=10.34.1.0$
    

    替换IP的代码:

    (Get-Content 'C:\Vincent\Test\Test.txt') -replace "$((Get-Content 'C:\Vincent\Test\IP.txt') -join '$|')$`"
    

    (Get-Content 'C:\Vincent\Test\Test.txt') -replace "Subnet=$((Get-Content 'C:\Vincent\Test\IP.txt') -join '$|Subnet=')$",'Subnet='
    

    【讨论】:

      【解决方案2】:

      这样的?

      $ExceltpionList=get-content C:\temp\SubnetExceptions.txt
      
      Get-Content C:\temp\spunkfile.txt | %{
      
      $CurrentRow=$_
      
      $ExceltpionList | %{
      
          if ($CurrentRow -eq "Subnet=$_")
          {
              $CurrentRow=$CurrentRow -replace "Subnet=$_", "Subnet="
      
          }
      }
      
      $CurrentRow
      
      }
      

      【讨论】:

        【解决方案3】:

        如果您的输出在文件 result.txt 中,您可以这样做:

        $content = Get-Content "result.txt"
        cat "subnetexceptions.txt" | %{ $content = $content -replace $_,"IGNORE"} 
        

        如果你需要保存到文件,只需添加

        $content > newfile.txt
        

        我测试了它,它可以工作。

        【讨论】:

        • 感谢您的回答。我觉得我没看懂哈哈。让我告诉你我是怎么做的: > Out-File -InputObject $Result -filepath "c:\Scripts\Result.txt" > Get-Content "c:\Scripts\Result.txt" | cat SubnetExceptions.txt | %{ $子网 = $_; | {$_ -replace $Subnet,"IGNORE"} }
        • 也尝试使用变量本身,而不将其输出到“结果”文件中。
        • 我已经编辑了我的答案。第一个有点仓促。
        猜你喜欢
        • 2022-07-12
        • 2014-10-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多