2015-12-07 71 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