Reputation: 2596
As part of a larger script I have implemented the switch
detailed below. The intention is that when the script is executed a user can choose to either
If the import from file option is selected - I want to test the file is present - if not I want to break out and go back to the switch label :choose
. However when I select the import from file option and provide a non-existent path the script continues and does not break or return to the label. Where am I going wrong?
$chooseInputMethod = @"
This script migrates one or more user accounts between two trusted domains in a forest e.g. from domain1 to domain2 (or vice versa)
Select method to specify user(s) to migrate:
1. Enter name(s) on-screen (default)
2. Import name(s) from file
Enter selection number
"@
$choosePath = @"
Enter path to file..
Notes
- Filename:
If file is located in script directory ($pwd) you can enter the filename without a path e.g. users.txt
- No quotation marks:
DO NOT put any quotes around the path even if it contains spaces e.g. e:\temp\new folder\users.txt
Enter path or filename
"@
$enterUsernames = @"
Enter username(s) seperate each with a comma e.g. test1 or test1,test2,test3`n`nEnter name(s)
"@
cls
:choose switch (Read-Host $chooseInputMethod) {
1 { cls; $usersFromScreen = Read-Host $enterUsernames }
2 {
cls;
$usersFromFile = Read-Host $choosePath;
if (-not (Test-Path $usersFromFile -PathType Leaf)) {
break choose
}
}
default { cls; $usersFromScreen = Read-Host $enterUsernames }
}
Write-Host "hello"
Upvotes: 3
Views: 887
Reputation: 27491
A break to the switch will exit it. There's only one loop (switch, which works on arrays), so there's no difference between a plain break and breaking to the switch. You seem to want the switch inside another loop to repeat it.
# only runs once
:outer while (1) {
'outer'
while (1) {
'inner'
break outer
}
}
outer
inner
Demo of switch with a label and looping. The documentation isn't perfect.
# only runs once
:outer switch (1..10) {
default {
'outer'
foreach ($i in 1..10) {
'inner'
break outer
}
}
}
outer
inner
Another switch demo.
switch (1..4) {
{ $_ % 2 } { "$_ is odd" }
default { "$_ is even" }
}
1 is odd
2 is even
3 is odd
4 is even
Upvotes: 1
Reputation: 354694
From the documentation for break
:
In PowerShell, only loop keywords, such as Foreach, For, and While can have a label.
So, switch
, even though it has looping capabilities, is not considered a loop in this case.
However, in this case I don't see why break
without a label would not suffice.
Upvotes: 5