【问题标题】:powershell script, text placement in cells in csv filepowershell脚本,csv文件中单元格中的文本放置
【发布时间】:2018-02-22 08:50:31
【问题描述】:

所以,从这里继续我通过 powershell 的可爱旅程: Loop for two 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 并开始运行宏,他需要从脚本中准备好最终的 csv。

我该怎么办?

【问题讨论】:

  • CSV 使用, 而非; 作为分隔符,因此除非您更改此设置,否则如果没有手动干预,Excel 将无法正确显示列。

标签: excel powershell csv


【解决方案1】:

这样的事情可以解决您的问题,唯一不包括的部分是从 Invoke-WebRequest (curl) 中选择值本身,因为它会根据返回的内容而改变。

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

【讨论】:

  • 我最终将它与 curl 一起使用,因为 Invoke-WebRequest 需要 IE 设置,而这些设置在这个客户的机器上很糟糕而且很难更改。除了一些价值。替换调用它完成了工作,谢谢!
【解决方案2】:

您目前正在将您的输出写在两个不同的行中。一种解决方案是在 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

我个人会创建一个 Powershell 对象并在最后创建 csv:

$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

}

【讨论】:

  • 我试过了,但是 curl | findstr 在 Add-Member 调用下无法正常运行。叹息
  • 然后你可以在 Add-Member 之前运行它,比如 $curl = curl ... 并在 Add-Member 中使用 $curl 变量
猜你喜欢
  • 2017-04-25
  • 1970-01-01
  • 1970-01-01
  • 2011-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-24
  • 1970-01-01
相关资源
最近更新 更多