Powershell - проблема с передачей параметров Validateset в ForEach-Object, получение приглашения

Итак, я новичок в PowerShell, и я пытаюсь заставить эту функцию работать. У меня есть 2 массива ValidateSet с 3 параметрами. Эти параметры должны изменять путь к файлу и копировать их с одного сервера на другой. По какой-то причине я продолжаю получать командную строку для параметров вместо их прохождения. Я предполагаю, что это проблема с ForEach-Object, но я не понимаю. Однако он работает для $ArchivePath. Я новенький, так что будьте нежны... TIA


param(

    [Parameter(Mandatory = $true)]
    [ValidateSet("One", "Two", "Three")]
    [string[]]$Channel

    ,[Parameter(Mandatory = $true)]
    [Alias('Phase')]
    [ValidateSet("Devl", "Test", "Prod")]
    [string[]]$Phase

    ,[Parameter(Mandatory = $false)]
    [string]$FilenameFilter = '.csv'

    ,[Parameter(Mandatory = $false)]
    [switch]$CreateTrigger
    )


function ExitWithCode { param($exitcode) $host.SetShouldExit($exitcode); exit $exitcode }

$exitcode = 0

try {

    # Get a list of files on the host server.
    #
   $files = Get-ChildItem -File -Path "\\ServerName\d\Extract\$Phase\FileTransfer\$Channel\Outbound"        

    # Destination directory.
    #
    $LocalPath = "\\ServerName\d\Extract\$Phase\FileTransfer\$Channel\Outbound"     #for testing


    # Set up folder name for Archive server. Formated as YYYYMMDDTHHMMSS  YYYYMMDD --> Var_Date, 'T' --> Var_Constant & HHMMSS --> Var_Time
    #
    $Var_Date = get-date -UFormat "%Y-%m-%d"
    $Var_Constant = 'T'
    $Var_Time = get-date -UFormat "%H-%M-%S"
    $Var_Fulldate = $Var_Date + $Var_Constant + $Var_Time

    $ArchivePath = $env:USERPROFILE + "\Desktop\$Channel\$Var_Fulldate"     #For testing
    New-Item -Type Directory -Path $ArchivePath


    if (-not (Test-Path -Path $ArchivePath -ErrorAction SilentlyContinue)) { $ArchivePath = $Env:TEMP }

    #Look for files in Outbound directory and remove
    Get-ChildItem -File -Path $LocalPath | ForEach-Object { Copy-Item $_.FullName } #Using copy instead of remove for test
    $FileCount = 0

Write-Output Try2   #for testing
pause               #for testing

    foreach ($file in $files) {
        if ((-not $file.IsDirectory) -and ($File.FullName -match $FilenameFilter)) {

            $localfilename = $LocalPath + $file.Name

            if (Test-Path $localfilename) { Copy-Item $localfilename }

            try {

                Copy-Item -Path $(Join-Path -Path $LocalPath -ChildPath $file.Name) -Destination $ArchivePath
    #Remove files from outbound since they've been archived
    #
                #Remove-Item -Path $file.FullName

            "Retrieved file $file"

                $FileCount++
            }
            catch {
                Write-Output Try13  #for testing
                $exitcode = 13
                "failed to retrieve $file"
            }
            finally {
                $error.Clear()
            }
        }
    }

}
catch {
Write-Output Try3
    $exitcode = 14
}
finally {
Write-Output Try4
    $error.Clear()
}

if ($CreateTrigger -and ($exitcode -eq 0) -and ($FileCount -gt 0)) {
    New-Item -Path "$LocalPath\Trigger_File.trg" -ItemType File | Out-Null
}

#ExitWithCode $exitcode     # take out for testing

Выход:

PS C:\Users\me> \\Server\blah\USERS\me\My Documents\Folder\Get-FileName_t4.ps1
cmdlet Get-FileName_t4.ps1 at command pipeline position 1
Supply values for the following parameters:
Channel[0]: Three
Channel[1]: 
Phase[0]: Devl
Phase[1]: 


    Directory: C:\Users\me\Desktop\Three


Mode                LastWriteTime         Length Name                                                                                                
----                -------------         ------ ----                                                                                                
d-----       11/22/2019  12:17 PM                2019-11-22T12-17-23                                                                                 
Try2
Press Enter to continue...: 
Retrieved file File1_20191122080912.csv
Retrieved file File2_20191122080922.csv
Retrieved file File3_20191122080925.csv
Retrieved file File4_20191122080932.csv
Retrieved file File5_20191122080933.csv
Retrieved file File6_20191122080933.csv
Try4

1 ответ

Вы получаете запрос, потому что вы не передаете эти параметры, но Mandatory=$trueустанавливается для аргументов, которые вас просят. Поскольку ваш сеанс интерактивный, он просит вас ввести правильные значения. Если вы не хотите получать запросы, укажите обязательные аргументы:

"\\Server\blah\USERS\me\My Documents\Folder\Get-FileName_t4.ps1" -Channel Three -Phase Dev1

Я заметил еще пару вещей:

  • Вам не нужно предоставлять Mandatory=$false, в качестве Mandatory является $false по умолчанию
  • Установка псевдонима Phase для -Phase аргумент также избыточен
Другие вопросы по тегам