Gamble
Gamble

Reputation: 17

How to write a switch statement that continues to prompt a user by pressing a number

First off, I'm a newbie when it comes to scripting. So far I have the first few lines of script running. My log files output to a text file, but I'm having trouble creating switch” statement that continues to prompt a user by pressing a random number. Any help would be appreciated.

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'

Upvotes: 0

Views: 515

Answers (1)

Theo
Theo

Reputation: 61148

As you are new to PowerShell, I suggest you read something about the Get-ChildItem cmdlet to understand what kind of objects it returns.

Reading your code, it makes me think you are expecting a list of file names as strings, but in fact it is a list of FileInfo and/or DirectoryInfo objects.

Having said that, creating a loop to prompt a user for entering a certain value is not that hard to do. Try this:

# 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
}

Hope that helps

Upvotes: 2

Related Questions