我有以下ps1文件(不幸的是,它必须是PowerShell,而不是更简单),运行curl
请求,将其中的一部分发送到文件,然后运行一些文本替换。< / p>
$url = "https://someserver/trans="
$transaction = "1" #There are 4 transactions
$node = "node1" #There are 10 nodes
Remove-Item ATM.csv -Force
# So far so good
# Below is what I'd use as a function in bash. No sure what/how to do in PS:
#OUTPUT:
echo $transaction";"$node >> ATM.csv
curl -v -k -u user@pass $url$transaction$node | findstr "<value>" >> ATM.csv
(Get-Content ATM.csv) -replace "<value>"," " | Out-File ATM.csv
(Get-Content ATM.csv) -replace "</value>"," " | Out-File ATM.csv
(Get-Content ATM.csv) -replace " ","" | Out-File ATM.csv
脚本原样为我提供了一个事务值(csv中的三行:事务,节点和数字)。在实践中,我需要使用包含10台机器和4种不同交易的阵列或列表。
我的问题是为两个变量设置一个循环,我需要运行OUTPUT部分40次(4个事务X 10个节点)。我已经在Python中使用了similair的东西,bash但我发现自己在PowerShell中感到困惑和时间不足。我花了好几个小时在网上跑步并尝试了非工作的例子。
你能帮我一把吗?
答案 0 :(得分:2)
我已经为你的变量添加了一个s,然后假设第一个“事务”需要在outerloop中:
$url = "https://someserver/trans="
$transactions = '1','2','3','4' #There are 4 transactions
$nodes = 'node1','node2','node3','node4','node5','node6' #There are 10 nodes
Remove-Item ATM.csv -Force
# So far so good
# Below is what I'd use as a function in bash. No sure what/how to do in PS:
#OUTPUT:
foreach($transaction in $transactions)
{
foreach($node in $nodes)
{
"$transaction;$node" |out-file -Append ATM.csv
curl -v -k -u user@pass $url$transaction$node | findstr "<value>" | out-file -Append ATM.csv
(Get-Content ATM.csv) -replace "<value>"," " | Out-File -Append ATM.csv
(Get-Content ATM.csv) -replace "</value>"," " | Out-File -Append ATM.csv
(Get-Content ATM.csv) -replace " ","" | Out-File -Append ATM.csv
}
}
答案 1 :(得分:1)
我仍然认为处理curl输出的最佳方法是使用它返回的对象类型进行解析(html / xml / json)。
解析文本输出时,我会使用正则表达式。 PowerShell支持lookarounds所以这个脚本(具有反向节点事务顺序):
## Q:\Test\2017\09\13\SO_46179493.ps1
$url = "https://someserver/trans="
$transactions = 1..4|ForEach-Object{"$_"} #There are 4 transactions
$nodes = 1..10|ForEach-Object{"node{0}" -f $_} #There are 10 nodes
$RE = [RegEx]'(?<=\<value\>).+(?=\<\/value\>)'
# The RE uses lookbehind and lookahead to assert the captured value is surrounded by
# the tags <value> and </value>
$ATM = ForEach($node in $nodes){
ForEach($transaction in $transactions) {
curl -v -k -u user@pass $url$transaction$node | Where-Object {$_ -match $RE}|
ForEach-Object {[pscustomobject]@{
node = $node
transaction = $transaction
value = $Matches[0]}
}
}
}
$ATM
$ATM | Export-Csv '.\ATM.csv' -NoTypeInformation
将生成此(模拟)显示:
node transaction value
---- ----------- -----
node1 1 79719
node1 2 77829
node1 3 90337
node1 4 39470
...
node10 1 17294
node10 2 62468
node10 3 70542
node10 4 46147
和文件输出:
> cat .\ATM.csv
"node","transaction","value"
"node1","1","79719"
"node1","2","77829"
"node1","3","90337"
"node1","4","39470"
...
"node10","1","17294"
"node10","2","62468"
"node10","3","70542"
"node10","4","46147"