Как написать оператор switch, который продолжает запрашивать пользователя нажатием цифры - PullRequest
0 голосов
/ 01 июня 2019

Во-первых, я новичок в сценарии.Пока у меня запущены первые несколько строк скрипта.Мои файлы журнала выводятся в текстовый файл, но у меня возникают проблемы при создании оператора switch », который продолжает запрашивать пользователя нажатием случайного числа.Любая помощь будет оценена.

Clear-Host

$Dir = Get-ChildItem C:\Users\rtres\Downloads\ -Recurse
$List = $Dir | where {$_.Extension -eq ".log"} | Out-File 'C:\Users\rtres\Downloads\Log.txt'

Clear-Host

$Dir = Get-ChildItem C:\Users\rtres\Downloads\ -Recurse
$List = $Dir | where {$_.Extension -eq ".log"} | Out-File 'C:\Users\rtres\Downloads\Log.txt'

1 Ответ

2 голосов
/ 01 июня 2019

Поскольку вы новичок в PowerShell, я предлагаю вам прочитать кое-что о командлете Get-ChildItem , чтобы понять, какие объекты он возвращает.

При чтении вашего кода я думаю,вы ожидаете список имен файлов в виде строк, но на самом деле это список FileInfo и / или DirectoryInfo объектов.

Сказав это, создаваяЦикл, чтобы предложить пользователю ввести определенное значение, не так сложно сделать.Попробуйте это:

# create variables for the folder to search through and the complete path and filename for the output
$folder = 'C:\Users\rtres\Downloads'
$file   = Join-Path -Path $folder -ChildPath 'Log.txt'

# enter an endless loop
while ($true) {
    Clear-Host
    $answer = Read-Host "Press any number to continue. Type Q to quit."
    if ($answer -eq 'Q') { break }  # exit the loop when user wants to quit
    if ($answer -match '^\d+$') {   # a number has been entered
        # do your code here.

        # from the question, I have no idea what you are trying to write to the log..
        # perhaps just add the file names in there??

        # use the '-Filter' parameter instead of 'where {$_.Extension -eq ".log"}'
        # Filters are more efficient than other parameters, because the provider applies them when
        # the cmdlet gets the objects rather than having PowerShell filter the objects after they are retrieved.
        Get-ChildItem $folder -Recurse -File -Filter '*.log' | ForEach-Object {
            Add-Content -Path $file -Value $_.FullName
        }
    }
    else {
        Write-Warning "You did not enter a number.. Please try again."
    }
    # wait a little before clearing the console and repeat the prompt
    Start-Sleep -Seconds 4
}

Надеюсь, что поможет

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