2017-09-13 93 views
1

因此,要通過PowerShell的繼續從這裏我可愛的旅程: Loop for two variablesPowerShell腳本,在細胞中的文本放置在csv文件

我有一個運行了一堆交易和一堆節點和環路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 [email protected] $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。

我該怎麼辦?

+0

一個CSV使用'''作爲分隔符而不是';'所以Excel不會在沒有人工干預的情況下正確顯示列,除非您更改此設置。 –

回答

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

因爲Invoke-WebRequest需要IE設置,所以我最終將curl與curl一起使用,並且這些在客戶的機器中很難改變。隨着一些價值。更換電話它做了這份工作,謝謝! –

1

您目前正在將輸出寫入兩行。一種解決方案可能是使用NoNewLine參數,輸出文件:

"$transaction;$node" |out-file -Append ATM.csv -nonewline 
curl -k -u [email protected] $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 [email protected] $url$transaction$node | findstr "<value>") 
$array += $obj 

}

+0

我試過這個但是捲曲|在添加成員調用下findstr將無法正常運行。嘆息 –

+0

然後你可以在添加成員之前運行它,比如$ curl = curl ...並使用Add-Member中的$ curl變量 –