Csv 新创建的列为空。。。。为什么?
我正在尝试在PowerShell中执行一项简单的任务,其中将为CSV文件中的许多列计算一些基本统计信息。我几乎完成了,但是我不断得到一个错误,我创建的新列显示为空。在这里,我看不出我错在哪里 具体来说,导致错误的代码行是Csv 新创建的列为空。。。。为什么?,csv,powershell,Csv,Powershell,我正在尝试在PowerShell中执行一项简单的任务,其中将为CSV文件中的许多列计算一些基本统计信息。我几乎完成了,但是我不断得到一个错误,我创建的新列显示为空。在这里,我看不出我错在哪里 具体来说,导致错误的代码行是 $STATS2.Columns.Add($colVZA) | 导入$filename时创建的表确实有名为VZA、VAZ等的列,所以这不是问题所在 似乎添加和填充列应该是一项简单的任务,所以我确信我在这里遗漏了一些简单的东西。这是我的密码: ##################
$STATS2.Columns.Add($colVZA) |
导入$filename
时创建的表确实有名为VZA、VAZ等的列,所以这不是问题所在
似乎添加和填充列应该是一项简单的任务,所以我确信我在这里遗漏了一些简单的东西。这是我的密码:
#######################
function Get-Type
{
param($type)
$types = @(
'System.Boolean',
'System.Byte[]',
'System.Byte',
'System.Char',
'System.Datetime',
'System.Decimal',
'System.Double',
'System.Guid',
'System.Int16',
'System.Int32',
'System.Int64',
'System.Single',
'System.UInt16',
'System.UInt32',
'System.UInt64')
if ( $types -contains $type ) {
Write-Output "$type"
}
else {
Write-Output 'System.String'
}
} #Get-Type
#######################
<#
.SYNOPSIS
Creates a DataTable for an object
.DESCRIPTION
Creates a DataTable based on an objects properties.
.INPUTS
Object
Any object can be piped to Out-DataTable
.OUTPUTS
System.Data.DataTable
.EXAMPLE
$dt = Get-psdrive| Out-DataTable
This example creates a DataTable from the properties of Get-psdrive and assigns output to $dt variable
.NOTES
Adapted from script by Marc van Orsouw see link
Version History
v1.0 - Chad Miller - Initial Release
v1.1 - Chad Miller - Fixed Issue with Properties
v1.2 - Chad Miller - Added setting column datatype by property as suggested by emp0
v1.3 - Chad Miller - Corrected issue with setting datatype on empty properties
v1.4 - Chad Miller - Corrected issue with DBNull
v1.5 - Chad Miller - Updated example
v1.6 - Chad Miller - Added column datatype logic with default to string
v1.7 - Chad Miller - Fixed issue with IsArray
.LINK
http://thepowershellguy.com/blogs/posh/archive/2007/01/21/powershell-gui-scripblock-monitor-script.aspx
#>
function Out-DataTable
{
[CmdletBinding()]
param([Parameter(Position=0, Mandatory=$true, ValueFromPipeline = $true)] [PSObject[]]$InputObject)
Begin
{
$dt = new-object Data.datatable
$First = $true
}
Process
{
foreach ($object in $InputObject)
{
$DR = $DT.NewRow()
foreach($property in $object.PsObject.get_properties())
{
if ($first)
{
$Col = new-object Data.DataColumn
$Col.ColumnName = $property.Name.ToString()
if ($property.value)
{
if ($property.value -isnot [System.DBNull]) {
$Col.DataType = [System.Type]::GetType("$(Get-Type $property.TypeNameOfValue)")
}
}
$DT.Columns.Add($Col)
}
if ($property.Gettype().IsArray) {
$DR.Item($property.Name) =$property.value | ConvertTo-XML -AS String -NoTypeInformation -Depth 1
}
else {
$DR.Item($property.Name) = $property.value
}
}
$DT.Rows.Add($DR)
$First = $false
}
}
End
{
Write-Output @(,($dt))
}
$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
Export-CSV -notype "c:\zMFM\z550Output\20dSummer\tempstats$i.csv"
$GetColumns = Import-CSV $filename
#Append the standard deviation variable to the statistics table and add the value
$STATS2 = Import-CSV "c:\zMFM\z550Output\20dSummer\tempstats$i.csv"
$StatsTable = Get-PSDrive | Out-DataTable
#$colSTDDEV = New-Object System.Data.DataColumn StdDev,([double])
$colVZA = New-Object System.Data.DataColumn VZA,([double])
#$colVAZ = New-Object System.Data.DataColumn VAZ,([double])
$colVZA = $GetColumns[0].VZA
#$colVAZ = $GetColumns[0].VAZ #COMMENTED FOR DEBUGGING
#$colSTDDEV = $STDEV
#$StatsTable.Columns.Add($colSTDDEV) #COMMENTED FOR DEBUGGING
#$StatsTable[0].StdDev = $STDEV #COMMENTED FOR DEBUGGING
$StatsTable.Columns.Add($colVZA) |
#$StatsTable[0].VZA = $VZA
#$StatsTable.Columns.Add($colVAZ) #COMMENTED FOR DEBUGGING
#$StatsTable[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++
}
#####################
函数获取类型
{
参数($type)
$types=@(
'System.Boolean',
'系统字节[]',
'System.Byte',
'System.Char',
“System.Datetime”,
“十进制系统”,
'系统双',
“System.Guid”,
'System.Int16',
'System.Int32',
'System.Int64',
"系统.单一",,
“System.UInt16”,
“System.UInt32”,
‘System.UInt64’)
如果($types-包含$type){
写入输出“$type”
}
否则{
写入输出“System.String”
}
}#获取类型
#######################
函数输出数据表
{
[CmdletBinding()]
param([参数(位置=0,必需=$true,ValueFromPipeline=$true)][PSObject[]]$InputObject)
开始
{
$dt=新对象数据.datatable
$First=$true
}
过程
{
foreach($InputObject中的对象)
{
$DR=$DT.NewRow()
foreach($object.PsObject.get_properties()中的属性)
{
如果($第一)
{
$Col=新对象数据.DataColumn
$Col.ColumnName=$property.Name.ToString()
如果($property.value)
{
如果($property.value-isnot[System.DBNull]){
$Col.DataType=[System.Type]::GetType($(Get Type$property.TypeNameOfValue)”)
}
}
$DT.Columns.Add($Col)
}
如果($property.Gettype().IsArray){
$DR.Item($property.Name)=$property.value |转换为XML-作为字符串-NoTypeInformation-深度1
}
否则{
$DR.Item($property.Name)=$property.value
}
}
$DT.Rows.Add($DR)
$First=$false
}
}
终点
{
写入输出@(,($dt))
}
$i=1
而($i-LE211){
#将变量设置为具有迭代编号的文件名
$filename=“c:\zMFM\z550Output\20dSummer\fixed20dSum550Output$i.csv”
#检查是否存在带有$filename的文件。如果不存在,请跳到$i的下一个迭代。如果存在,请运行代码以收集每个变量的统计信息,并将它们输出到不同的文件
If(测试路径$filename){
#计算标准偏差
#首先获取列中值的平均值
$stDeviceInputFile=导入CSV$filename
#查找列“td”的平均值和计数
$STDEVAVG=$STDEVInputFile |测量对象td-平均值|选择计数,平均值
$DevMath=0
#求平均值与数组中每个值之差的平方和
Foreach($STDEVInputFile中的Y){
$DevMath+=[数学]::pow($Y.Average-$STDEVAVG.Average),2)
#除以样本数减去一
$STDEV=[Math]::sqrt($DevMath/($STDEVAVG.Count-1))
}
#使用MEASURE-OBJECT cmdlet计算列“td”的基本统计信息
$STATS=导入CSV$Filename|
测量对象td-平均-最大-最小|
#将统计数据导出为CSV
导出CSV-notype“c:\zMFM\z550Output\20dSummer\tempstats$i.CSV”
$GetColumns=导入CSV$filename
#将标准偏差变量附加到统计表中并添加值
$STATS2=导入CSV“c:\zMFM\z550Output\20dSummer\tempstats$i.CSV”
$StatsTable=获取PSDrive |输出数据表
#$COLSTDEV=新对象System.Data.DataColumn StdDev,([double])
$colVZA=新对象System.Data.DataColumn VZA,([double])
#$colVAZ=新对象System.Data.DataColumn VAZ,([double])
$colVZA=$GetColumns[0]。VZA
#$colVAZ=$GetColumns[0]。VAZ#已注释以进行调试
#$colSTDDEV=$STDEV
#$StatsTable.Columns.Add($colSTDDEV)#已注释以进行调试
#$StatsTable[0]。StdDev=$STDEV#已注释以进行调试
$StatsTable.Columns.Add($colVZA)|
#$StatsTable[0]。VZA=$VZA
#$StatsTable.Columns.Add($colVAZ)#已注释以进行调试
#$StatsTable[0]。VZA=$VAZ#已注释以进行调试
#导出$STATS文件,该文件包含正确文件夹中所需的所有内容
导出CSV-notype“c:\zMFM\z550Output\20dSummer\20dSum550Statistics.CSV”
}
$i++
}
即使$STATS2
中的每个对象都有相同的属性,$STATS2
对象本身只是一个简单的数组,一个非结构化的对象列表-它没有带有Add()方法的Columns
属性:
$STATS2.Colums.Add($colVZA)
^ ^ ^
[array] | |
$null |
this fails
您可以将从Import Csv
获取的数组从数组转换为DataTable
对象(具有列)通过检查数组中第一个对象中的每个属性,如technet脚本库中的中的,您的代码看起来像是希望Import Csv
returnSystem.Data.DataTable
返回给您。我的印象是这样做了……这是否意味着我需要创建一个DataTable来加载新列,并将其作为CS导出五、 然后导入它以将新列追加到表中?这个直观的示例使问题非常清楚,谢谢!我可以将Out Datatable函数实现到我的脚本中,就像我在导入Csv之后立即调用函数$STATS2.Colums.Add($colVZA)之前一样吗?可以,但请注意,$colVZA
本身只是列名,不会向每行添加任何数据。感谢您提供的信息。不过,我继续使用了代码行“$StatsTable=Get PSDrive | Ou”