2015-12-07 107 views
1

我創建了一個簡單的PowerShell腳本,以便更改一組CSV文件中一列的標題值。當我在包含25個CSV文件的測試文件夾中以.ps1文件啓動腳本時,腳本似乎運行(出現閃爍光標),但它已運行了一個多小時,並且至今沒有輸出文件出現。簡單的腳本似乎永遠無法運行...?

任何人都可以指出這裏可能會出錯嗎?我過去成功地在這臺電腦上編寫並執行了幾個PowerShell腳本,但從未遇到過這個問題,搜索沒有取得任何結果。

#Rename the first Column header in each output file to 'VZA' so you can work 
#with the data 

#Iterate code through 211 possible files 
$i = 1 
While ($i -le 211) { 
    #Set the variable to the filename with the iteration number 
    $filename = "c:\zMFM\z550Output\20dSummer\20dSum550Output$i.csv" 

    #Check to see if that a file with $filename exists. If not, skip to the next 
    #iteration of $i. If so, run the code change the column header 
    If (Test-Path $filename) { 
    #Import the CSV and change the column header to VZA 
    Import-CSV $filename | 
     Select-Object @{ expression={_."550 1587600 VZA"}; label='VZA' } | 
     Export-Csv -NoType "c:\zMFM\z550Output\20dSummer\fixed20dSum550Output$i.csv" 
    } 
} 

編輯: 看來我已經錯過了$i++項和代碼現在正常運行,但輸出僅僅由VZA頭和沒有數據從導入CSV文件。我錯在哪裏,我假設在Select-Object代碼的某個地方?

+3

的Powershell的版本?我看到它初始設置,然後永遠不會改變,這意味着它始終小於211,循環永遠不會停止。 –

+0

啊哈,我肯定錯過了我應該包括在最後兩個大括號之間的$ i ++。問題解決了。謝謝你,先生! – AggroCrag

+0

現在代碼正在運行,結果中出現了另一個問題 - 輸出中只包含'VZA'標題,並且沒有輸入CSV文件中的數據。任何想法我錯了,或者我應該在一個新的線程中提出這個問題? – AggroCrag

回答

3

在粘貼的腳本中,變量$i在循環內從不改變。在每次迭代中,它的初始值都是1,始終小於211,並且while語句永遠不會退出。

要清楚,while語句不會修改循環變量本身。要從1到211進行計數,您需要增加循環內的變量,以便最終達到最終結果。

$i = 1 
while($i -le 211) { 
    write-output "Running iteration $i" 
    # loop stuff here 

    # Increment the counter 
    $i += 1 
} 

或者,你可以在腳本你在哪裏修改`$ i`使用for循環

1..211 | foreach { 
    write-output "Running iteration $_" 
    # loop stuff here 
} 
+0

謝謝,我忘了那件事。然而,我遇到了代碼本身的問題,我已經將它添加到OP中作爲編輯...我應該在新線程中提出這個問題嗎?我在這附近有點新奇。 – AggroCrag

+0

這應該可能會進入一個新的問題,以獲得應有的重視。 –

+0

會做,謝謝。 – AggroCrag