如果在“foreach”中find空值,则使用导出的Excel / CSV数据更改输出

对不起,我不太确定如何提出这个问题。

这是上一个问题的后续内容 :将Excel单元格内容放入格式化的.txt文件中

我使用的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 BABABAB 

所以我设法让代码在一个集合中“忽略/跳过”一个空值。

我的输出看起来像这样

 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语句,并且注释掉了带有值的字段,或者不注释掉没有值的字段。

下一个代码片段可以帮助:

 ### … … … ### $Content | foreach-object{ $field1 = $("{0},{1},{2},{3},{4},{5},{6}" -f "Field1", $_."Value1", $_."Value2", $_."Value3", $_."Value4", $_."Value5", $_."Value6") $auxarr = $field1.Split(",",[System.StringSplitOptions]::RemoveEmptyEntries) if ( $auxarr.Count -le 1) { ";$auxarr" } else { $auxarr -join "," } $field2 = $("{0},{1}" -f "Field2", $_."Value1") $auxarr = $field2.Split(",",[System.StringSplitOptions]::RemoveEmptyEntries) if ( $auxarr.Count -le 1) { ";$auxarr" } else { $auxarr -join "," } } | Out-File $OutFile 

编辑回答额外(扩展)的子问题, 我需要删除{0},{1}之间的逗号“,”而不是使用空格

  $field2 = $("{0},{1}" -f "Field 2", $_."Value1") ### keep comma ↑ ↓ or any other character not contained in data $field2 = $field2.Split(",",[System.StringSplitOptions]::RemoveEmptyEntries) if ( $field2.Count -le 1) { ";$field2" } else { $field2 -join "`t`t" } 

如果您的数据包含 重要的逗号,则使用String.Split方法的Split(String(), StringSplitOptions)forms ,如下所示:

  $burstr = [string[]]'#-#-#' $field2 = $("{0}$burstr{1}" -f "Field 2", $_."Value1") $field2 = $field2.Split($burstr,[System.StringSplitOptions]::RemoveEmptyEntries) if ( $field2.Count -le 1) { ";$field2" } else { $field2 -join "`t`t" }