Использование 'If' и 'ElseIf' с get-childitem из разных каталогов

Есть 3 каталога, из которых я хочу взять файлы из 20 каталогов. И у меня есть графический интерфейс, настроенный для вывода переменной $year. Возможные варианты: 2017, 2018, 2019 и Выбрать все. С файлами я хочу скопировать их в другую папку, желательно с неповрежденной структурой папок.

$year = '2018'

if ($year = '2017') {
    Get-ChildItem -Path $sourcePath'\Warranty Claims 2017' -Recurse
} elseif ($year = '2018') {
    Get-ChildItem -Path $sourcePath'\Warranty Claims 2018' -Recurse
} elseif ($year = '2019') {
    Get-ChildItem -Path $sourcePath'\Warranty Claims 2019' -Recurse
} elseif ($year = 'Select All') {
    Get-ChildItem -Path $sourcePath'\Warranty Claims 2017'
    Get-ChildItem -Path $sourcePath'\Warranty Claims 2018'
    Get-ChildItem -Path $sourcePath'\Warranty Claims 2019'
} else {
    "This didn'nt work"
}
# = files

Это была идея, это не работает. Я хочу, чтобы результат этого был помещен в переменную $ files из-за приведенного ниже кода. Я более чем открыт для альтернативных способов сделать это, но с точки зрения новичка это показалось наиболее логичным.

foreach ($file in $files){
    $sourcePathFile = $file.FullName
    $destinationPathFile = $file.FullName.Replace($sourcePath,  $destinationPath)

    $exists = Test-Path $destinationPathFile

    if (!$exists) {
        $dir = Split-Path -Parent $destinationPathFile
        if (!(Test-Path($dir))) { New-Item -ItemType Directory -Path $dir }
        Copy-Item -Path $sourcePathFile -Destination $destinationPathFile -Recurse -Force
    } else{
        $isFile = Test-Path -Path $destinationPathFile -PathType Leaf

        if ($isFile) {
            $different = Compare-Object -ReferenceObject $(Get-Content $sourcePathFile) -DifferenceObject $(Get-Content $destinationPathFile)
            if (Compare-Object -ReferenceObject $(Get-Content $sourcePathFile) -DifferenceObject $(Get-Content $destinationPathFile)) {
                $dir = Split-Path -Parent $destinationPathFile
                if (!(Test-Path($dir))) { New-Item -ItemType Directory -Path $dir }
                Copy-Item -Path $sourcePathFile -Destination $destinationPathFile -Recurse -Force
            }
        }
    }
}

person William Brooker    schedule 14.11.2019    source источник
comment
В условных операторах (например, if) равенство представляется оператором -eq, а не =. = выполняет задание.   -  person AdminOfThings    schedule 14.11.2019
comment
Спасибо @AdminOfThings, что сработало, вы знаете, как мне сохранить его как переменную? т.е. вторая часть моего поста   -  person William Brooker    schedule 14.11.2019
comment
Ага. Вы можете установить для переменной весь блок кода if-else. $files = if () {}; else {}   -  person AdminOfThings    schedule 14.11.2019


Ответы (2)


В условных операторах, которые проводят сравнение, вам следует рассмотреть возможность использования Comparison_Operators. Равно представлено оператором -eq. = используется для присвоения переменных. Вы можете преобразовать свой код, чтобы отразить это. Выход блока if-else может быть установлен в переменную ($files).

$files = 
    If ($year -eq '2017') {
        Get-ChildItem -Path $sourcePath'\Warranty Claims 2017'  -Recurse
     } 
    ElseIf ($year -eq '2018') {
        Get-ChildItem -Path $sourcePath'\Warranty Claims 2018'  -Recurse
    }   
    ElseIf ($year -eq '2019') {
        Get-ChildItem -Path $sourcePath'\Warranty Claims 2019'  -Recurse
    }     
    ElseIf ($year -eq 'Select All') {
       Get-ChildItem -Path $sourcePath'\Warranty Claims 2017' 
       Get-ChildItem -Path $sourcePath'\Warranty Claims 2018' 
       Get-ChildItem -Path $sourcePath'\Warranty Claims 2019'  
        }
    Else {    
        "This didn't work"
    }

В вашей конкретной ситуации вы можете получить неожиданные результаты, выходящие за рамки одной проблемы с оператором. Рассмотрим следующий пример:

If ($year = '2017') {
   "It is 2017"
} Else {
    "Wrong year"
}

It is 2017
$year
2017

Если $year может быть успешно присвоено значение, которое обычно оценивается как $true в условии, тогда условие if будет истинным и $year будет обновлено с новым значением.

Рассмотрим следующий пример, когда if не будет оцениваться как $true. Здесь 0 оценивается как $false и назначение было успешным при обновлении $year до 0.

If ($year = 0) {
   "It is 2017"
} Else {
    "Wrong year"
}

Wrong year
$year
0
person AdminOfThings    schedule 14.11.2019

Это также возможность для переключения:

$year = 2017,2018

$files = switch ($year) {  # $year can be an array
  2017 { dir $sourcePath'\Warranty Claims 2017' -R } 
  2018 { dir $sourcePath'\Warranty Claims 2018' -R } 
  2019 { dir $sourcePath'\Warranty Claims 2019' -R } 
  'Select All' {
    dir $sourcePath'\Warranty Claims 2017',
      $sourcePath'\Warranty Claims 2018',
      $sourcePath'\Warranty Claims 2019'
  } 
  default {"This didn't work"}
}

$files
person js2010    schedule 14.11.2019