如果在'foreach'中发现空值,则使用导出的Excel/CSV数据更改输出



对不起,我不太确定这个问题该怎么说。

这是上一个问题的后续:获取Excel单元格内容并将其放入格式化的。txt文件

我使用的Import-XLS功能是从这里:https://gallery.technet.microsoft.com/office/17bcabe7 - 322 - 43 - d3 - 9 - a27 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语句,它注释掉了带值的字段,或者不注释掉了没有值的字段。

下一段代码可以提供帮助:

### … … … ###
$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)形式,例如:

    $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" }

最新更新