PowerShell脚本,在csv文件中的单元格中的文本位置

所以,从这里继续我可爱的旅程通过PowerShell: 循环两个variables

我有一个ps1,为一堆事务和一堆节点运行一个循环,并将它们发送到一个csv文件。

$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 -k -u user@pass $url$transaction$node | findstr "<value>" | out-file -Append ATM.csv } } 

在excel中打开这个文件,最后在列A下输出:

  transaction1;node1 (in the first row, left-most cell) value1 (from the curl. It's actually a number and it sits in the row right under the first entry) 

等2,3等等等等。 只有最左边的列(列A)被填充。

我想得到的是将值放在三列中的方法,这样csv将如下所示:

 Column A | Column B | Column C transaction1| node1 | valueX transaction2| node2 | valueY 

等等。 脚本或其他脚本必须这样做,运行脚本的这个工作的最终用户不会每天打开excel并开始运行macros,他需要从脚本中准备好最终的csv。

我该怎么办?

像这样的东西可以解决你的问题,唯一没有包含的是从Invoke-WebRequest(curl)中select值本身,因为这将取决于返回的内容。

 foreach($transaction in $transactions) { foreach($node in $nodes) { $value = Invoke-WebRequest -Uri $url$transaction$node -UseBasicParsing | Select-Object -Expand Content Add-Content -Path ATM.csv -Value "$transaction,$node,$value" } } 

您目前正在将您的输出写入两行。 一种解决scheme可能是使用Out-File中的NoNewLine参数:

 "$transaction;$node" |out-file -Append ATM.csv -nonewline curl -k -u user@pass $url$transaction$node | findstr "<value>" | out-file -Append ATM.csv 

我个人会创build一个Powershell对象,并在最后创buildcsv:

 $array = @() foreach($node in $nodes) { $obj = New-Object psobject $obj | Add-Member -MemberType NoteProperty -Name 'Transaction' -Value $transaction $obj | Add-Member -MemberType NoteProperty -Name 'Node' -Value $node $obj | Add-Member -MemberType NoteProperty -Name 'Value' -Value (curl -k -u user@pass $url$transaction$node | findstr "<value>") $array += $obj 

}