简体   繁体   English

Powershell脚本从CSV删除空白列

[英]Powershell Script to Delete Blank Columns from CSV

Powershell Script to Delete Blank Columns from CSV Powershell脚本从CSV删除空白列

I have a spread sheet which I'm importing into a MySQL database, the import fails because of blank columns in the spread sheet. 我有一个要导入到MySQL数据库的电子表格,由于电子表格中的空白列,导入失败。

Is there a powershell script I can run / create that will check any given CSV file and remove blank columns? 我是否可以运行/创建一个Powershell脚本,该脚本将检查任何给定的CSV文件并删除空白列?

Col1,Col2,Col3,Col4,,,, Val1,Val2,Val3,Val4 Col1,Col2,Col3,Col4 、、、 Val1,Val2,Val3,Val4

How about something like this: 这样的事情怎么样:

$x = Import-Csv YourFile.csv
$f = $x[0] | Get-Member -MemberType NoteProperty | Select name
$f | Add-Member -Name count -Type NoteProperty -Value 0
$f | %{
  $n = $_.Name
  $_.Count = @($x | Select $n -ExpandProperty $n | ? {$_ -ne ''}).count
}
$f = @($f | ? {$_.count -gt 0} | Select Name -expandproperty Name)

$x | Select $f | Export-Csv NewFile.csv -NoTypeInformation

It uses Get-Member to get the column names, cycles though each one to check how many are not blank and then uses the results in a select. 它使用Get-Member获取列名,循环遍历每个列以检查有多少不为空,然后在选择中使用结果。

When I run Dave Sexton's code, I get: 当我运行Dave Sexton的代码时,我得到:

Select-Object : Cannot convert System.Management.Automation.PSObject to one of the following 
types {System.String, System.Management.Automation.ScriptBlock}.
At line:15 char:12
+ $x | Select <<<<  $f  | Export-Csv ColsRem.test.$time.csv -NoTypeInformation
+ CategoryInfo          : InvalidArgument: (:) [Select-Object], NotSupportedException
+ FullyQualifiedErrorId : 
                  DictionaryKeyUnknownType,Microsoft.PowerShell.Commands.SelectObjectCommand

I corrected this issue by adding one more line, to force each array element to be a string. 我通过增加一行来纠正此问题,将每个数组元素强制为字符串。

$x = Import-Csv YourFile.csv
$f = $x[0] | Get-Member -MemberType NoteProperty | Select name
$f | Add-Member -Name count -Type NoteProperty -Value 0
$f | %{
  $n = $_.Name
  $_.Count = @($x | Select $n -ExpandProperty $n | ? {$_ -ne ''}).count
}
$f = @($f | ? {$_.count -gt 0} | Select Name -expandproperty Name)

# I could get the select to work with strings separated by commas, but the array would 
# always produce the error until I added the following line, explicitly changing the 
#values to strings.
$f = $f | Foreach-Object { "$_" } 

$x | Select $f | Export-Csv NewFile.csv -NoTypeInformation

My import CSV contains a few hundred columns and about half likely won't be populated, so getting rid of the extra columns was necessary. 我的导入CSV包含几百列,并且大约一半可能不会被填充,因此有必要消除多余的列。 Now I just need to figure out how to counteract the unintended re-ordering of the columns into alphabetical order by name, without changing the names. 现在,我只需要弄清楚如何在不更改名称的情况下按名称抵消列的意外重新排序为字母顺序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM