2015-02-24 136 views
0

PowerShell腳本刪除空白列從CSVPowerShell腳本從CSV

我有一個散熱片,我導入到MySQL數據庫刪除空白列,導入失敗,因爲在傳播空白列片。

是否有PowerShell腳本我可以運行/創建,將檢查任何給定的CSV文件,並刪除空白列?

Col1中,col2的,COL3,COL4 ,,,, VAL1,VAL2,VAL3,VAL4

+0

你應該舉例說明你有什麼和你需要什麼。目前爲止您測試的一個簡短例子也不錯。的我有什麼 – JPBlanc 2015-02-24 11:37:02

+0

例子: Col1中,col2的,COL3,COL4 ,,,, VAL1,VAL2,VAL3,VAL4的我想要什麼 例子: Col1中,col2的,COL3,COL4 VAL1,VAL2,VAL3, Val4 – James 2015-02-24 14:13:39

回答

1

怎麼是這樣的:

$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 

它使用Get-Member來獲得列名,循環雖然每一個檢查有多少不是空白,然後在選擇使用結果。

+0

我收到幾條錯誤消息: 1.無法處理參數,因爲參數「name」的值無效。 據我所知,這是因爲PS正試圖在最後導入帶空白列的CSV。 使用您的答案後: 2.不能索引到一個空數組。 3.添加成員:無法將參數綁定到參數'InputObject',因爲它爲空。 – James 2015-02-24 14:19:24

+0

如果您的文件不是有效的CSV文件,那麼您需要先做一些預處理來清理它們。第一步是找出爲什麼Powershell無法加載它們,是因爲每一列沒有唯一的標題,或者某些行缺少列,您的列是否包含帶有嵌入逗號和沒有引號的文本。然後你可以用Get-Content加載一個文件,用一個正則表達式/替換來清除它,然後使用ConvertFrom = Csv轉換成一個對象。如果您可以將CSV的示例添加到您的問題中,我可以爲您提供更多幫助。 – 2015-02-24 16:14:51

0

當我運行戴夫塞克斯頓的代碼,我得到:

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 

我通過增加一個線,迫使每個數組元素是一個字符串,糾正了這個問題。

$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 

我的導入CSV包含幾百列,大約一半可能不會填充,所以擺脫額外的列是必要的。現在我只需要弄清楚如何在不改變名稱的情況下,通過名稱按字母順序抵消列的意外重新排序。