powershell - 检查列的数量和名称,如果错误则停止脚本
问题描述
我想检查我的 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)"
}
我还需要检查名称有什么建议吗?
解决方案
我认为你根本不需要try{..} catch{..}
这里。
此外,应该不需要同时使用Import-Csv
和Get-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
}
推荐阅读
- javascript - 如何强制从另一个 Vue 组件重新渲染一个 Vue 组件
- java - jar 文件在命令行创建时不起作用
- java - 如何在 play-framework 2.6 中从 CompletionStage 获取 json 对象
- android - 应用多个 ForegroundColorSpan
- vb.net - Try - Catch - End Try 用法
- go - 如何将 Unicode 字符更改为简单形式?
- pandas - Pandas/MLP :: 仅在 3 年期间绘制 36 个月而不是 12 个月
- r - 在 R 中,如何根据另一列添加具有 0/1 计数的多列?
- php - 第一次用户登录,上传图片 mkdir() 工作完美,但同一用户上传照片警告:mkdir():文件存在?
- javascript - Adyen 在 React 应用中的 Checkout SDK 集成