2016-08-30 62 views
1

我有一個時間赫克嘗試導入CSV和運行調用-的WebRequest獲取數據添加到一個新的列..進口CSV添加數據導出

$username = "Username" 
$password = cat C:\Password.txt | convertto-securestring 
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $password 

$csv = Import-Csv -Path C:\users\Desktop\ImportTest.csv 

foreach($c in $csv){ 

     $link = "https://MyURlToCallforData" 
     $uri= $link + $c.stuff 

     Invoke-WebRequest -Uri $uri -Credential $cred -UseBasicParsing| ConvertFrom-Json | Select-Object -Property lastIdReportTime 
} 

Export-Csv -Path C:\Users\Desktop\TestOutput.csv -NoTypeInformation 

沒有我可以導入它很好,我打電話,我看到ISE上的結果,但我無法導出到CSV或追加當前的文件。

我已經試過各種東西,嘗試添加新的內容嘗試添加psObject和無論我做什麼我就不行了,..

希望有人能在這裏給我一隻手。

CSV基本上是這樣的。

Date,Description 
Text1,text2 
text3,text4 

,我想將它導出這樣

Date,Description,NewInfo 
Text1,text2,new5 
text3,text4,new6 
+0

https://powershell.org/forums/topic/adding-columns-to-an-existing-csv/ – wOxxOm

回答

1

有幾種辦法,解決問題。 這裏有一個:

$username = "Username" 
$password = cat C:\Password.txt | convertto-securestring 
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $password 

$csv = Import-Csv -Path C:\users\username\Desktop\ImportTest.csv 
$link = "https://MyURlToCallforData" 
foreach($c in $csv){ 

     $uri= $link + $c.stuff 
     $result = Invoke-WebRequest -Uri $uri -Credential $cred -UseBasicParsing| ConvertFrom-Json 
     $c | Add-Member -name "NewInfo" -MemberType NoteProperty -value $($result | Select-Object -ExpandProperty lastIdReportTime) 
     $c | Add-Member -name "SecondField" -MemberType NoteProperty -value $($result | Select-Object -ExpandProperty SomeOtherField) 

} 

$csv | Export-Csv -Path C:\Users\username\Desktop\TestOutput.csv -NoTypeInformation 

編輯:我只是意識到有一個與你的代碼的問題:出口-CSV並不導出什麼
第二個編輯:「-ExpandProperty」可能是強制性的,以避免某些類型mix-一團糟。

這是第二種可能的解決方案。選擇你最喜歡的;)

$username = "Username" 
$password = cat C:\Password.txt | ConvertTo-SecureString 
$cred = New-Object -typename System.Management.Automation.PSCredential -argumentlist $username, $password 

$csv = Import-Csv -Path C:\users\username\Desktop\ImportTest.csv 

$link = "https://MyURlToCallforData" 
$csv = $csv | Select-Object -Property *,@{name="NewInfo";expression = { 

    $uri= $link + $c.stuff 
    Invoke-WebRequest -Uri $uri -Credential $cred -UseBasicParsing| ConvertFrom-Json | Select-Object -expandProperty lastIdReportTime 
}} 

$csv | Export-Csv -Path C:\Users\username\Desktop\TestOutput.csv -NoTypeInformation 
+0

現在,我要測試這些..第一個是字面上我以前但我認爲我有它格式錯誤:(.. 你介意刪除路徑上的用戶名嗎?忘記我已經離開那裏。 – JonnyBoy

+0

完成,還沒有看到它:p – Poorkenny

+0

讓我我知道你是否有問題,顯然我無法測試整個事情,所以我只測試了一些位。 – Poorkenny