如果使用Windows批处理或PowerShell在CSV文件中为空,则需要打印字段名称

时间:2017-07-26 11:29:21

标签: powershell batch-file

我有一个分隔文件,如下所示:

Field 0|Field 1|Field 2|Field 3|Field 4|Field 5
June 27 2017|5466|28998|52|3175507|1144121044

我的要求是,如果上述任何字段在.csv文件中为空,我需要打印空字段的名称,然后通过电子邮件发送输出详细信息,说明此字段为空。

我尝试了下面的代码,但在最后一步失败,检查是否为空/ NULL,将值传递给另一个变量。

setlocal enabledelayedexpansion
@echo off
for /f "tokens=*" %%X in (TEMP.csv) do (
  set "work=%%X"
  :: fill empty fields with "#NUL#" ...
  :: but do it twice, just in case consecutive fields are empty
  for /l %%j in (1,1,2) do set "work=!work:||=|#NUL#|!"
  for /F "tokens=1,2,3,4,5,6* delims=|" %%i in ("!work!") do (
    echo first is %%i
    echo second is %%j
    echo third is %%k
    echo fourth is %%l
    echo fifth is %%m
    echo sixth is %%n
    echo -------------  
  )
)

1 个答案:

答案 0 :(得分:1)

要识别哪个字段为空,您需要使最内层循环中的输出成为条件。此外,使用金丝雀字符串填充空白字段的例程并不能解释空的第一个或最后一个字段。

...
rem Add delimiters to beginning and end of line to allow detection of empty
rem first/last fields.
set "work=|%%X|"
rem Insert canary into empty fields (run twice to take care of consecutive empty
rem fields).
set "work=!work:||=|#NUL#|!"
set "work=!work:||=|#NUL#|!"
rem Remove additional delimiters from beginning/end of line.
set "work=!work:~1,-1!"
for /F "tokens=1,2,3,4,5,6* delims=|" %%i in ("!work!") do (
    if "%%i"=="#NUL#" echo Field 0 is empty
    if "%%j"=="#NUL#" echo Field 1 is empty
    if "%%k"=="#NUL#" echo Field 2 is empty
    if "%%l"=="#NUL#" echo Field 3 is empty
    if "%%m"=="#NUL#" echo Field 4 is empty
    if "%%n"=="#NUL#" echo Field 5 is empty
)
...

在PowerShell中执行此操作会更容易:

Import-Csv 'C:\path\to\input.csv' -Delimiter '|' | ForEach-Object {
    $_.PSObject.Properties |
        Where-Object { -not $_.Value } |
        Select-Object -Expand Name
}