首页 > 解决方案 > 检查列的数量和名称,如果错误则停止脚本

问题描述

我想检查我的 csv 的名称和列数,如果列名或列数之一不正确,请停止我的脚本。这将是我开始播放脚本之前的第一次检查

COL1;COL2;COL3;COL4

所以我想检查一下我有 4 列,如果 COL1 的名称 = COL1,COL2 的名称 = COL2 等等...

这是我的 addlog 函数,我想在其中实现我的检查我尝试使用 -error 操作停止,但我肯定犯了一个错误

#Fonction LOG
 
$date = get-date -Format dd-MM-yyyy
$script:fichierlogencours = "Log_$($date).log"
 
function AddLog([string] $TYPE, [string] $TEXT) 
    {
    $LINE = (Get-Date).ToString("dd/MM/yyyy %H:mm:ss") + "`t" + $TYPE + "`t" + $TEXT
    write-output $LINE | out-file -append -filepath  "$pathlog $fichierlogencours" -force
    if (($TYPE -eq "[Warn]") -or ($TYPE -eq "[INFO]")) {$COLOR="Yellow"}
    elseif ($TYPE -eq "[Err]") {$COLOR="Red"}
    else {$COLOR="Green"}
    Write-Host $LINE -ForegroundColor $COLOR
    } 
 
#Variables Fonction LOG
 

$PathLog = "C:\Temp\"
$FilePath = "C:\Temp\TestH.csv"
$rejets = "C:\Temp\ScriptGenXML_LignesEnErreur.txt"

$liste = Import-Csv -path 'c:\temp\testH.csv' -Delimiter ';'
$countColonne = ($liste | get-member -type NoteProperty).count


Try{
      
    AddLog [INFO] "Traitement du fichier $filepath"
    $TestLog = Get-Content -Path $filepath -ErrorAction Stop    
    AddLog [OK] "Traitement du fichier $filepath OK"
}
Catch{

    AddLog [Err] "Erreur dans le traitement du fichier $filepath"
    AddLog [Err] "ERREUR : $($error[0].Exception.Message)"
    
}
 
### I tried implementing my if/else in my try but couldn't find a way to stop the script as soon as the number of column not equal to 4

 if ($countColonne -eq 4) 
    {AddLog [OK] "nombre do colonne OK"}
    else 
    {AddLog [Err] "Erreur dans le traitement du fichier $filepath, nombre de colonne incorrect devrait être égal à 4"}

我确实喜欢这个,但我的脚本一直在继续,关于如何做到这一点的任何想法

Try{
      
    AddLog [INFO] "Traitement du fichier $filepath"
    $TestLog = Get-Content -Path $filepath -ErrorAction Stop    
    AddLog [OK] "Traitement du fichier $filepath OK"
     if ($countColonne -eq 4) 
    {AddLog [OK] "nombre do colonne OK"}
    else 
    {AddLog [Err] "Erreur dans le traitement du fichier $filepath, nombre de colonne incorrect devrait être égal à 4"}

}
Catch{

    AddLog [Err] "Erreur dans le traitement du fichier $filepath"
    AddLog [Err] "ERREUR : $($error[0].Exception.Message)"
    
}

我还需要检查名称有什么建议吗?

标签: powershellcsvloggingtry-catch

解决方案


我认为你根本不需要try{..} catch{..}这里。
此外,应该不需要同时使用Import-CsvGet-Content在同一个文件上

一种方法是:

function Add-Log([string] $type, [string] $text) {
    $line = (Get-Date).ToString('dd/MM/yyyy HH:mm:ss') + "`t" + $type + "`t" + $text
    $line | Out-File -FilePath  $script:fichierLog -Force -Append
    $color = switch ($type) {
        '[Err]' { 'Red'; break }
        '[OK]'  { 'Green'; break }
        default { 'Yellow' }
    }
    Write-Host $line -ForegroundColor $color
} 

#Variables Fonction LOG

$PathLog          = "C:\Temp"
$filepath         = "C:\Temp\TestH.csv"
$fichierLog       = Join-Path -Path $PathLog -ChildPath ("Log_{0:dd-MM-yyyy}.log" -f (Get-Date))
$expectedColonnes = 'COL1', 'COL2', 'COL3', 'COL4'

# read the Csv file
$liste   = Import-Csv -Path $filepath -Delimiter ';'
# get the header names as string array
$colonnesArray = $liste[0].PSObject.properties.name

$continueScript = $true
if ($colonnesArray.Count -eq $expectedColonnes.Count) {
    Add-Log '[OK]' "Traitement du fichier $filepath OK: No. de colonnes:  $($colonnesArray.Count)"

    # join the headers into a string for output in the log file
    $colonnesString = "'{0}'" -f ($colonnesArray -join "';'")

    # test if the headers are as expected (same names, same order)
    if (@(Compare-Object -ReferenceObject $expectedColonnes -DifferenceObject $colonnesArray -SyncWindow 0).Length -eq 0) {
        Add-Log '[OK]' "Traitement du fichier $filepath OK: Colonnes: $colonnesString."
    }
    else {
        Add-Log '[Err]' "Erreur dans le traitement du fichier $filepath Colonnes: $colonnesString."
        $continueScript = $false
    }
}
else {
    Add-Log '[Err]' "Erreur dans le traitement du fichier $filepath, nombre de colonne incorrect devrait être égal à $($expectedColonnes)"
    $continueScript = $false
}

if (!$continueScript) { exit }

另一种测试标头是否相同且顺序相同的替代方法,因此不使用Compare-Object可能是为找到的标头(已经在上面的代码中)创建一个字符串,并对$expectedColonnes数组执行相同的操作。然后简单地测试两个字符串是否相等:

    # join the headers into a string for output in the log file
    $colonnesString = "'{0}'" -f ($colonnesArray -join "';'")
    $expectedString = "'{0}'" -f ($expectedColonnes -join "';'")

    # test if the headers are as expected (same names, same order)
    if ($colonnesString -eq $expectedString) {
        # rest of code
    }

推荐阅读