Хотя вы, возможно, не показываете нам достаточно возможных заголовков, я думаю, что вы пытаетесь использовать -match
практически на всей первой строке.
Кроме того, в вашем коде вы разбиваете строки и даже команды совершенно случайно, делая код и регулярные выражения действительно ненадежными.Было бы более разумно сосредоточиться только на различиях , которые отличают один файл от другого и совпадают с ними.
Посмотрите на код ниже:
$RootDirectory = 'C:\temp\Move by header'
$InputDirectory = Join-Path -Path $RootDirectory -ChildPath 'input'
$OutputPathHeat = Join-Path -Path $RootDirectory -ChildPath 'HeatMeter'
$OutputPathWater = Join-Path -Path $RootDirectory -ChildPath 'WaterMeter'
$OutputPathOther = Join-Path -Path $RootDirectory -ChildPath 'Other'
# get an array of Full path and filenames of the files in the input directory.
# because you want files only, add the '-File' switch.
# if you're on PowerShell version below 3.0, use:
# (Get-ChildItem $InputDirectory | Where-Object { !$_.PSIsContainer })
foreach ($FilePath in (Get-ChildItem $InputDirectory -File) | Select-Object -ExpandProperty FullName) {
$Header = Get-Content $FilePath -First 1
# test for a string in the header line that distincts it from the other files
if ($Header -match ';energy,Wh,') {
# the substring ';energy,Wh,' defines this file as a 'HeatMeter' file
Move-Item -Path $FilePath -Destination $OutputPathHeat
}
elseif ($Header -match ';fabrication-no,,') {
# the substring ';fabrication-no,,' defines this file as a 'WaterMeter' file
Move-Item -Path $FilePath -Destination $OutputPathWater
}
else {
# if both key substrings above did not match, move to the 'Other' directory
Move-Item -Path $FilePath -Destination $OutputPathOther
}
}
Вместо использования конструкции if..elseif..else
, как описано выше, использование команды switch
может сделать ваш код более читабельным, а также упростить добавление дополнительных тестов между ними.
Кроме того, switch
также имеетпараметр -Regex
, поэтому нет необходимости каждый раз записывать if ($Header -match ...
.Вы можете прочитать все об этом здесь: about_Switch
Блок if..elseif..else
выше может быть записан как:
# test for a string in the header line that distincts it from the other files
switch -Regex ($Header) {
# the substring ';energy,Wh,' defines this file as a 'HeatMeter' file
';energy,Wh,' { Move-Item -Path $FilePath -Destination $OutputPathHeat; break }
# the substring ';fabrication-no,,' defines this file as a 'WaterMeter' file
';fabrication-no,,' { Move-Item -Path $FilePath -Destination $OutputPathWater; break }
# if both key substrings above did not match, move to the 'Other' directory
default { Move-Item -Path $FilePath -Destination $OutputPathOther }
}
Примечание: если подстроки вы хотитеу совпадений есть символы, которые имеют особое значение в регулярных выражениях, убедитесь, что вы Escape их используя синтаксис [Regex]::Escape(the string to match against)