Get-ChildItem -File-Исключить проблему - PullRequest
0 голосов
/ 21 сентября 2018

Issue

Я обернул Get-ChildItem в универсальную функцию, чтобы добавить проверки и иметь возможность ее повторного использования.При объединении -File с -Exclude функция, кажется, выходит из строя, даже если тот же вызов Get-ChildItem вне ее работает, как и ожидалось.

Вопрос

Что происходит не так?Как это исправить?

Связанные

Параметры Get-ChildItem Exclude и File не работают вместе

MWE

function Get-Object {
  [CmdletBinding ()]
  param (
    [Parameter (
      Position    = 1,
      Mandatory   = $true,
      HelpMessage = "Path to the object"
    )]
    [String]
    $Path,
    [Parameter (
      Position    = 2,
      Mandatory   = $false,
      HelpMessage = "Type of object"
    )]
    [ValidateSet ("All", "File", "Folder")]
    [String]
    $Type = "All",
    [Parameter (
      Position    = 3,
      Mandatory   = $false,
      HelpMessage = "Filter to apply"
    )]
    [String]
    $Filter = "*",
    [Parameter (
      Position    = 4,
      Mandatory   = $false,
      HelpMessage = "Pattern to exclude"
    )]
    [String]
    $Exclude = $null
  )
  begin {
    if (-Not (Test-Path -Path $Path)) {
      Write-Host "$Path does not exists."
      exit 1
    }
    $ObjectType = [ordered]@{
      "All"     = "items"
      "File"    = "files"
      "Folder"  = "folders"
    }
  }
  process {
    # Get files
    switch ($Type) {
      "File"    {
        $Files = Get-ChildItem -Path $Path -Filter $Filter -Exclude $Exclude -File
      }
      "Folder"  {
        $Files = Get-ChildItem -Path $Path -Filter $Filter -Exclude $Exclude -Directory
      }
      default   {
        $Files = Get-ChildItem -Path $Path -Filter $Filter -Exclude $Exclude
      }
    }
    # If no files are found, print hints
    if ($Files.Count -eq 0) {
      if ($Filter -ne "*") {
        Write-Host "No $($ObjectType[$Type]) were found in $Path matching the filter ""$Filter""."
      } elseif ($Exclude) {
        Write-Host "No $($ObjectType[$Type]) corresponding to the criterias were found in $Path."
      } else {
        Write-Host "No $($ObjectType[$Type]) were found in $Path."
      }
      # exit 1
    } else {
      return $Files
    }
  }
}

$Path         = Split-Path -Path $MyInvocation.MyCommand.Definition
$RelativePath = "\test"
$AbsolutePath = Join-Path -Path $Path -ChildPath $RelativePath
$Filter       = "*"
$Exclude      = $null

Get-ChildItem -Path $RelativePath -Filter $Filter -Exclude $Exclude -File

Get-ChildItem -Path $AbsolutePath -Filter $Filter -Exclude $Exclude -File

Get-Object -Path $RelativePath -Filter $Filter -Exclude $Exclude -Type "File"

Get-Object -Path $AbsolutePath -Filter $Filter -Exclude $Exclude -Type "File"

Вывод

PS C:\> .\test.ps1


    Directory: C:\test


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----       21/09/2018     18:42              0 text.txt
-a----       21/09/2018     18:42              0 text.txt
No files were found in \test.
No files were found in C:\test.

PS: Любая конструктивная критика синтаксиса / лучших практик приветствуется.

1 Ответ

0 голосов
/ 25 сентября 2018

Похоже, что это известная проблема для этой проблемы в репозитории PowerShell GIT.

Решение

При использовании -Filter возникает конфликт, -Exclude и -File одновременно.Удаляя один или добавляя -Recurse, функция работает как ожидалось.

  1. Get-ChildItem -Path $Path -Filter $Filter -File
  2. Get-ChildItem -Path $Path -Filter $Filter -Exclude $Exclude -File -Recurse

Очевидно, что это не оптимальнои должен рассматриваться как обходной путь до устранения проблемы.

Полный рабочий пример

function Get-Object {
  [CmdletBinding ()]
  param (
    [Parameter (
      Position    = 1,
      Mandatory   = $true,
      HelpMessage = "Path to the items"
    )]
    [String]
    $Path,
    [Parameter (
      Position    = 2,
      Mandatory   = $false,
      HelpMessage = "Type of object"
    )]
    [ValidateSet ("All", "File", "Folder")]
    [String]
    $Type = "All",
    [Parameter (
      Position    = 3,
      Mandatory   = $false,
      HelpMessage = "Filter to apply"
    )]
    [String]
    $Filter = "*",
    [Parameter (
      Position    = 4,
      Mandatory   = $false,
      HelpMessage = "Pattern to exclude"
    )]
    [String]
    $Exclude = $null
  )
  begin {
    if (-Not (Test-Path -Path $Path)) {
      Write-Host "$Path does not exists."
      exit 1
    }
    $ObjectType = [ordered]@{
      "All"     = "items"
      "File"    = "files"
      "Folder"  = "folders"
    }
  }
  process {
    # Get files
    switch ($Type) {
      "File"    {
        $Files = Get-ChildItem -Path $Path -Filter $Filter -Exclude $Exclude -File -Recurse
      }
      "Folder"  {
        $Files = Get-ChildItem -Path $Path -Filter $Filter -Exclude $Exclude -Directory
      }
      default   {
        $Files = Get-ChildItem -Path $Path -Filter $Filter -Exclude $Exclude
      }
    }
    # If no files are found, print hints
    if ($Files.Count -eq 0) {
      if ($Filter -ne "*") {
        Write-Host "No $($ObjectType[$Type]) were found in $Path matching the filter ""$Filter""."
      } elseif ($Exclude) {
        Write-Host "No $($ObjectType[$Type]) corresponding to the criterias were found in $Path."
      } else {
        Write-Host "No $($ObjectType[$Type]) were found in $Path."
      }
      # exit 1
    } else {
      return $Files
    }
  }
}

$Path         = Split-Path -Path $MyInvocation.MyCommand.Definition
$RelativePath = "\test"
$AbsolutePath = Join-Path -Path $Path -ChildPath $RelativePath
$Filter       = "*"
$Exclude      = $null

Get-ChildItem -Path $RelativePath -Filter $Filter -Exclude $Exclude -File

Get-ChildItem -Path $AbsolutePath -Filter $Filter -Exclude $Exclude -File

Get-Object -Path $RelativePath -Filter $Filter -Exclude $Exclude -Type "File"

Get-Object -Path $AbsolutePath -Filter $Filter -Exclude $Exclude -Type "File"

Вывод

PS C:\> .\test.ps1


    Directory: C:\test


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----       21/09/2018     18:42              0 text.txt
-a----       21/09/2018     18:42              0 text.txt
-a----       21/09/2018     18:42              0 text.txt
-a----       21/09/2018     18:42              0 text.txt
...