2016-09-20 49 views
2

我试图拉$IOC从阵列中的项目,然后对每个项目替换$ API下面的字符串的$ 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一次没有更换。

回答

1

$IMPORT将会在here-string被分配到$API后立即进行评估和扩展。

将其更改为文字下面的字符串('而不是"),并记住逃脱\$-replace模式参数:

$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 
} 
+0

两个真正帮助,不幸的是我不能给点还没有,但它是非常赞赏。! –

3

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

+0

最初我也这么认为。除了字符串中的'{}'文字干扰格式占位符: - \ –

+0

两个外部对象和'tests' –

+0

@ MathiasR.Jessen再次感谢内部对象。我感到很傻,因为我知道这可能会发生,但当我回答时却没有找到他们。 – Matt