Копировать файлы в другое место на основе заголовков файлов - PullRequest
0 голосов
/ 21 марта 2019

Я пытаюсь достичь того же результата, но получаю странное поведение, которое не могу решить самостоятельно.

Он только отфильтровывает первое if, а остальное обрабатывает как else.Неважно, сколько разных if...else я положил туда, тогда он все равно только отфильтровывает первые if, а затем обрабатывает других как else.

Я также пытался перемещать заголовки, поэтомуодин раз, который обычно обрабатывается как else, будет первым if, но все еще выполняется только первый if.

[string] $FileDirectory = "C:\temp\Move by header\input";
[string] $OutputPathHeat = "C:\temp\Move by header\HeatMeter";
[string] $OutputPathWater = "C:\temp\Move by header\WaterMeter";
[string] $OutputPathOther = "C:\temp\Move by header\Other";

foreach ($FilePath in Get-ChildItem $FileDirectory | Select-Object -     
ExpandProperty                 
FullName)
{
    [string] $Header = Get-Content $FilePath -First 1

    if ($Header -match '#serial-number;device-identification;created;value- 
                   data- 
                   count;act-duration,second(s),inst-value,0,0,0;avg- 
                   duration,second(s),inst-value,0,0,0;energy,Wh,inst- 
                   value,0,0,0;volume,m3,inst-value,0,0,0.*') {
        Move-Item $FilePath $OutputPathHeat
    } elseif ($Header -match '#serial-number;device- 
     identification;created;value-data- 
                       count;fabrication-no,,inst- 
     value,0,0,0;datetime,,inst- 
                       value,0,0,0;volume,m3,inst-value,0,0,0.*') {
        Move-Item $FilePath $OutputPathWater
    } else {
        Move-Item $FilePath $OutputPathOther
    }
}

1 Ответ

1 голос
/ 21 марта 2019

Хотя вы, возможно, не показываете нам достаточно возможных заголовков, я думаю, что вы пытаетесь использовать -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)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...