powershell - 如何在此处字符串中进行变量替换

标签 powershell

我试图从 $IOC 中的数组中提取项目,然后对于每个项目替换 $API here-string 中的 $IMPORT 并将结果回显到控制台,然后对 $IOC 数组中的每个项目执行此操作。

#put IOC's into array
$IOC= ‘c:\Users\powershell_array.txt'
#api curl script with variable to be replaced
$API = @"
curl --insecure 'https://192.168.1.1:3000/hx/api/v2/indicators/Custom/Powershell_AD/conditions/execution' -X 'POST' --data-binary "
{  
   \"tests\":[  
       {  
         \"token\":\"processEvent/ActiveDirectory\",
         \"type\":\"text\",
         \"operator\":\"contains\",
         \"preservecase\":false,
         \"value\":\"$IMPORT\"
      }
   ]
}" -H 'X-FeApi-Token:   IAOaiq1s2' -H 'Accept: application/json' -H 'Content-Type: application/json'"
"@

ForEach ($i in Get-Content $IOC) {$API -replace $IMPORT, $i} echo $API

我没有收到错误,但它只是打印数组的内容,然后当然会回显一次 $API 而不进行替换。

最佳答案

Mathias has it right关于何时评估变量。另一种允许与您想要的逻辑相同的方法是使用 format operator 。更新您的字符串以包含各种变量(在本例中为 1)的占位符,然后我们可以在循环中替换这些变量。我们使用 {n}(在本例中为 {0})并提供一个大小与占位符数量相等的数组。

$API = @'
curl --insecure 'https://192.168.1.1:3000/hx/api/v2/indicators/Custom/Powershell_AD/conditions/execution' -X 'POST' --data-binary "
{{  
   \"tests\":[  
       {{  
         \"token\":\"processEvent/ActiveDirectory\",
         \"type\":\"text\",
         \"operator\":\"contains\",
         \"preservecase\":false,
         \"value\":\"{0}\"
      }}
   ]
}}" -H 'X-FeApi-Token:   IAOaiq1s2' -H 'Accept: application/json' -H 'Content-Type: application/json'"
'@

ForEach ($i in Get-Content $IOC){$API -f $i}

不需要正则表达式开销,但是要使这种方法起作用,您需要将字符串中已存在的任何花括号加倍。有点尴尬,因为我忘记了I had that problem in the past

关于powershell - 如何在此处字符串中进行变量替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39599523/

相关文章:

powershell - 如何防止 Powershell 中的 Write-Error CategoryReason 截断?

powershell - 无法发送Powershell电子邮件-您无法在空值表达式上调用方法

powershell - 为什么按 "Enter"相当于数字0?

c# - 有没有办法在 Excel 或 PowerBI 之外调用 PowerQuery/M?

PowerShell 排序数组

powershell - 在Powershell中为.dat文件保存查找和替换文本功能

powershell - 使 arraylist 上的 select -unique 返回 arraylist 而不是字符串

PowerShell Tee-Object 不覆盖文件

Powershell - 命令在界面中有效,但在脚本中无效

powershell - 如何使用 $_ 自动变量调用 powershell 脚本 block