首页 > 解决方案 > 在 Powershell 的 CSV 文件数字列中查找文本数据

问题描述

我是PowerShell的新手。我试图通过找出我的数字字段中是否有任何文本值来验证我的 CSV 文件。我可以用列定义为数字。

这是我这样的源数据

ColA      ColB    ColC      ColD
23        23       ff       100
2.30E+01  34    2.40E+01    23
df        33      ss        df
34        35      36       37

我需要这样的输出(如果在任何列中找到,则只有文本值)

ColA         ColC       ColD
2.30E+01      ff        df
df           2.40E+01   
              ss    

我尝试了一些代码但没有得到任何结果,只得到一些输出,如下所示

System.Object[]


---------------                                                                                                                                                                      
                                                        xxx fff' ddd 3.54E+03 

                                                                                                ...

这就是我正在尝试的

#
cls

function Is-Numeric ($Value) {
    return $Value -match "^[\d\.]+$"
}

$arrResult = @()
$arraycol = @()

$FileCol = @("ColA","ColB","ColC","ColD")

$dif_file_path = "C:\Users\$env:username\desktop\f2.csv"

#Importing CSVs

$dif_file = Import-Csv -Path $dif_file_path -Delimiter ","

############## Test Datatype (Is-Numeric)##########

 foreach($col in $FileCol)
  {
  foreach ($line in $dif_file) {

    $val = $line.$col

     $isnum = Is-Numeric($val)

    if ($isnum -eq $false) {
   $arrResult +=  $line.$col
   $arraycol += $col

    }
 }
 }
   [pscustomobject]@{$arraycol = "$arrResult"}| out-file "C:\Users\$env:username\Desktop\Errors1.csv" 
####################

有人可以指导我正确的方向吗?谢谢

标签: powershell

解决方案


你可以试试这样的

function Is-Numeric ($Value) {
    return $Value -match "^[\d\.]+$"
}

$dif_file_path = "C:\Users\$env:username\desktop\f2.csv"

#Importing CSVs

$dif_file = Import-Csv -Path $dif_file_path -Delimiter ","

#$columns = $dif_file | Get-member -MemberType 'NoteProperty' | Select-Object -ExpandProperty 'Name'
# Use this to specify certain columns
$columns = "ColB", "ColC", "ColD"

foreach($row in $dif_file) {
  foreach ($col in $columns) { 
    if ($col -in $columns) {
      if (!(Is-Numeric $row.$col)) { 
        $row.$col = "" 
      }
    }
  } 
} 

$dif_file | Export-Csv C:\temp\formatted.txt 
  1. 随时查找列的名称
  2. 查找每行中每个列的值,如果不是数字,则更改为“”
  3. 导出的更新文件。

推荐阅读