【发布时间】:2016-11-07 05:36:45
【问题描述】:
抱歉,我不太确定如何措辞这个问题。
这是上一个问题的后续问题:Take Excel cell content and place it into a formatted .txt file
我使用的 Import-XLS 功能来自这里: https://gallery.technet.microsoft.com/office/17bcabe7-322a-43d3-9a27-f3f96618c74b
我当前的代码如下所示:
. .\Import-XLS.ps1
$OutFile = ".\OutTest$(get-date -Format dd-MM).txt"
$Content = Import-XLS '.\DummyData.xlsx'
$Content | foreach-object{
$field1 = $("{0},{1},{2},{3},{4},{5},{6}" -f "Field1", $_."Value1", $_."Value2", $_."Value3", $_."Value4", $_."Value5", $_."Value6")
$field1.Split(",",[System.StringSplitOptions]::RemoveEmptyEntries) -join ","
$field2 = $("{0},{1}" -f "Field2", $_."Value1")
$field2.Split(",",[System.StringSplitOptions]::RemoveEmptyEntries) -join ","
} | Out-File $OutFile
我的 Dummydata 本质上是这样的(我插入了 $null 来指出空白值)
Entries Value1 Value2 Value3 Value4 Value5 Value6 Value7 Value8
Entry 1 1 2 $null 4 5 6 7 8
Entry 2 $null B A B A B A B
所以我设法让代码“忽略/跳过”集合中的空值。
我的输出是这样的
Field1,1,2,4,5,6
Field2,1
Field1,B,A,B,A,B
Field2
我现在需要帮助的是如何删除“Field2”,因为它没有价值,或者使用 ; 将其注释掉。
所以我的输出看起来像
Field1,1,2,4,5,6
Field2,1
Field1,B,A,B,A,B
或
Field1,1,2,4,5,6
Field2,1
Field1,B,A,B,A,B
;Field2
基本上,如果一行在为该行写入的任何字段中都没有数据,则应将其忽略。
非常感谢您的帮助。
编辑:
我发现我需要删除 {0},{1} 之间的逗号“,”并改用空格。所以我正在使用
$field2 = $("{0} {1}" -f "Field 2", $_."Value1")
$field2 = $field2.Split(" ",[System.StringSplitOptions]::RemoveEmptyEntries)
if ( $field2.Count -le 1) { ";$field2" } else { $field2 -join "`t`t" }
这适用于我的“大部分”领域。
但是,“某些”字段和值中包含空格。 此外还有一些值,例如“TEST TEXT”
所以现在我得到了
Field1 3,B,A,B,A,B
Field 2 TEST TEXT
而不是(为清楚起见而引用)
"Field1" 3,B,A,B,A,B
"Field 2" "TEST TEXT"
我很高兴只对这几个字段使用某种例外。 我尝试了其他一些方法,但最终打破了 IF 语句,它 ;cmets 出具有值的字段,或者不 ;注释出没有值的字段。
【问题讨论】:
-
所以你只需要一个简单的
If声明?If($_.Value1){$Field2.Split...
标签: excel csv powershell null output