2

I am following a tutorial I found on youtube for a file integrity monitor. The code is messy but im trying to add my own twist and clean it up. I just added input validation and now the code won't run any further after the while loop at the top. Im new to powershell scripting so this may seem like a trivial quesiton but i need some help.

here is the input validation portion:

# Inital message to ask user what they would like to do
$initpromptquestion = "What would you like to do?`n`n     A) Collect new baseline.`n`n     B) Begin monitoring files with saved baseline.`n`nSelect 'A' or 'B'"
$errormessage = "Invalid entry. Please select 'A' or 'B'."
$selections = @('A','B')

do {
    $userinput = Read-Host -Prompt $initpromptquestion
    switch($userinput) {
        A { return $userinput }
        B { return $userinput }
        default { Write-Host $errormessage -ForegroundColor DarkRed -BackgroundColor White } 
    }
} while ($userinput -notcontains $selections)

after this portion is done, the code stops after this. can i get some help?

1 Answer 1

2

This looks backwards:

while ($userinput -notcontains $selections)

You want it like this:

while ($selections -notcontains $userinput)

You may also want to .Trim() or add a [0] on the end, to only look at the first character if they enter something longer. But in my mind, that's still a failure.


after this portion is done, the code stops after this.

Well, yeah. We don't see any other code. You'd have to show how this is invoked in order to get help there. But at a guess, the problem is the return statements in the switch are breaking out of the entire file. You could use return if this was its own method or function, but it looks more like this is part of a longer section of code in one place.


Put it all together like this:

# Inital message to ask user what they would like to do
$initpromptquestion = "What would you like to do?`n`n     A) Collect new baseline.`n`n     B) Begin monitoring files with saved baseline.`n`nSelect 'A' or 'B'"
$errormessage = "Invalid entry. Please select 'A' or 'B'."
$selections = @('A','B')

$userinput = Read-Host -Prompt $initpromptquestion
while ($selections -notcontains $userinput)
{
    Write-Host $errormessage -ForegroundColor DarkRed -BackgroundColor White } 
    $userinput = Read-Host -Prompt $initpromptquestion
}
Sign up to request clarification or add additional context in comments.

1 Comment

@mklement0 Oh yeah. I spend so much time in C# I always forget the case thing about powershell :o Cleaned that up from the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.