循环两个variables

我有以下ps1文件(下面的脚本,不幸的是它必须是PowerShell,没有什么更容易的),运行一个curl请求,把它的一部分,文件,然后运行一些文本replace。

 $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个不同的事务的数组或列表。

我的问题是为两个variables设置一个循环,我需要运行OUTPUT部分40次(4个事务X 10个节点)。 我已经在Python中完成了类似的东西,但是我发现自己在PowerShell中感到困惑,并且没有时间。 我花了几个小时在networking上运行,并尝试了非工作的例子。

你可以给我一只手吗?

Solutions Collecting From Web of "循环两个variables"

我已经添加了一个s到你的变量,然后假定第一个“交易”将需要在外圈:

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

我仍然认为处理curl输出的最好方法是解析返回的对象类型(html / xml / json)。

解析文本输出时,我会使用正则表达式。 PowerShell支持周转,所以这个脚本(与颠倒的节点事务顺序):

 ## 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"