1
我試圖在Powershell的CSV文件中添加幾列,但由於某些原因,變量似乎有空值即使我想填充他們。具體來說,我在與線在Powershell中添加列時出錯:'您無法調用空值表達式的方法「
$Stats2.Columns.Add($colVZA)
這顯然是由
$colVZA = New-Object System.Data.DataColumn VZA,([double])
$colVZA = $filename[0].VZA
傳遞空值心想試圖從數據來填充它的麻煩$ filename中VZA列中的第一個單元格會'un-null',但顯然不是這樣它工作。關於如何讓這些列填充並附加到表的任何想法?這是我的完整代碼:
$i = 1
While ($i -le 211) {
#Set the variable to the filename with the iteration number
$filename = "c:\zMFM\z550Output\20dSummer\fixed20dSum550Output$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 to collect the
statistics for each variable and output them each to a different file
If (Test-Path $filename) {
#Calculate the Standard Deviation
#First get the average of the values in the column
$STDEVInputFile = Import-CSV $filename
#Find the average and count for column 'td'
$STDEVAVG = $STDEVInputFile | Measure-Object td -Average | Select Count, Average
$DevMath = 0
# Sum the squares of the differences between the mean and each value in the array
Foreach ($Y in $STDEVInputFile) {
$DevMath += [math]::pow(($Y.Average - $STDEVAVG.Average), 2)
#Divide by the number of samples minus one
$STDEV = [Math]::sqrt($DevMath/($STDEVAVG.Count-1))
}
#Calculate the basic statistics for column 'td' with the MEASURE-OBJECT cmdlet
$STATS = Import-CSV $Filename |
Measure-Object td -ave -max -min |
#Export the statistics as a CSV and import it back in so you can add columns
Export-CSV -notype "c:\zMFM\z550Output\20dSummer\tempstats$i.csv"
$STATS2 = Import-CSV "c:\zMFM\z550Output\20dSummer\tempstats$i.csv"
#$colSTDDEV = New-Object System.Data.DataColumn StdDev,([double])
$colVZA = New-Object System.Data.DataColumn VZA,([double])
#$colVAZ = New-Object System.Data.DataColumn VAZ,([double])
#Append the standard deviation variable to the statistics table and add the value
$colVZA = $filename[0].VZA
#$colVAZ = $filename[0].VAZ #COMMENTED FOR DEBUGGING
#$colSTDDEV = $STDEV
#$STATS2.Columns.Add($colSTDDEV) #COMMENTED FOR DEBUGGING
#$STATS2[0].StdDev = $STDEV #COMMENTED FOR DEBUGGING
$STATS2.Columns.Add($colVZA) |
#$STATS2[0].VZA = $VZA *****This line may be unnecessary now
#$STATS2.Columns.Add($colVAZ) #COMMENTED FOR DEBUGGING
#$STATS2[0].VZA = $VAZ #COMMENTED FOR DEBUGGING
#Export the $STATS file containing everything you need in the correct folder
Export-CSV -notype "c:\zMFM\z550Output\20dSummer\20dSum550Statistics.csv"
}
$i++
}