Can you loop if statements in PowerShell? - powershell

First off, let me apologize if this is a stupid simple solution. I am currently in college and I am working on a project to create an AD enviroment with users, OUs, GPOs etc. I am hoping there's a way to loop the if statement asking if you want to create an Organizational Unit so instead of repeating the same lines, it would look cleaner and be more usable in a real world scenario.
Currently, I am using: But, if you wanted to create more than the two prompts, you couldn't.
#Create OUs
$Create_OU1= Read-Host -Prompt "Do you want to create any Organizational Units? Y/N"
if ($Create_OU1 -eq "Y" -or $Create_OU1 -eq "Yes") {
New-ADOrganizationalUnit
}
$Create_OU2= Read-Host -Prompt "Do you want to create any additional Organizational Units? Y/N"
if ($Create_OU2 -eq "Y" -or $Create_OU2 -eq "Yes") {
New-ADOrganizationalUnit
}
Read-Host -Prompt "Do you want to create any additional Organizational Units? Y/N"

Doing it with a do loop and PromptForChoice Method the code would look like this:
$prompt = {
param($message)
$Host.UI.PromptForChoice($null, $message, ('&Yes', '&No'), 0)
}
$message1 = 'Do you want to create any Organizational Units?'
$message2 = 'Do you want to create any additional Organizational Units?'
if((& $prompt $message1) -eq 0) {
do {
New-ADOrganizationalUnit
}
while((& $prompt $message2) -eq 0)
}

Related

If not empty jump to somewhere in PS

Hello and good morning(:
I'm looking to see if I'm able to jump to somewhere in PS without wrapping it in a ScriptBlock; hell, I'd even be okay with that but, I'm just unsure on how to go about it.
What I'm trying to do is: add a Parameter Set to a function and if something is supplied to the parameter -GrpSelec(I know imma change it), then just skip the rest of the script and go to my $swap variable to perform the switch.
$Group1 = #("1st Group", "2nd Group")
$Group2 = #("3rd Group", "4th Group")
Function Test-Group{
param(
[ValidateSet("Group1","group2")]
[array]$GrpSelec)
if($GrpSelec){ &$swap }
$AllGroups = #("Group1", "Group2")
for($i=0; $i -lt $AllGroups.Count; $i++){
Write-Host "$($i): $($AllGroups[$i])"}
$GrpSelec = Read-Host -Prompt "Select Group(s)"
$GrpSelec = $GrpSelec -split " "
$swap = Switch -Exact ($GrpSelec){
{1 -or "Group1"} {"$Group1"}
{2 -or "Group2"} {"$Group2"}
}
Foreach($Group in $swap){
"$Group"}
}
Is something like this even possible?
I've googled a couple of similar questions which point to the invocation operator &(as shown above), and/or, a foreach which is definitely not the same lol.
take it easy on me, im just experimenting(:
How about a simple if statement?
function Test-Group {
param(
[string[]]$GrpSelec
)
if(!$PSBoundParameters.ContainsKey('GrpSelect')){
# no argument was passed to -GrpSelec,
# populate $GrpSelec in here before proceeding with the rest of the script
}
# Now that $GrpSelec has been populated, let's do the work
$swap = Switch -Exact ($GrpSelec){
{1 -or "Group1"} {"$Group1"}
{2 -or "Group2"} {"$Group2"}
}
# rest of function
}

How can I allow only Y/N to be input in Read-Host without having to press Enter in Powershell?

I'm trying to find a way to have something like a Read-Host to ask the user if they want to output to the file listed or not. With this I want them to either press y or n and then the code continues rather than then pressing y/n then pressing enter as well. At the moment this all works well but again it's not quite what I'm wanting.
I've tried looking into Readkey and SendKeys (to push Enter for the user) but neither work as they seem to only execute after the user has pushed Enter on the Read-Host. I'm still very new to Powershell so I'm not entirely sure whether it's actually possible or not and I've spent too much time googling/testing to find an answer that works. If I was to use Write-Host or something to do this, it needs to not show up in the log.
I've included the necessary part of my script below. It basically asks the user if the file location is correct. If it is they press y and it uses it for the output, otherwise if they push n then it loads the FolderBrowserDialog for them to select the folder they want.
I should also note this is all within a Tee-object as this code is what determines where the Tee-object output goes to.
$OutputYN = Read-Host "Do you want the output file generated to $startDirectory\FolderList.txt? (Y/N)"
If (“y”,”n” -notcontains $OutputYN) {
Do {
$OutputYN = Read-Host "Please input either a 'Y' for yes or a 'N' for no"
} While (“y”,”n” -notcontains $OutputYN)
}
if ($OutputYN -eq "Y") {
$OutputLoc = $startDirectory
}
elseif ($OutputYN -eq "N") {
$OutputLocDir = New-Object System.Windows.Forms.FolderBrowserDialog
$OutputLocDir.Description = "Select a folder for the output"
$OutputLocDir.SelectedPath = "$StartDirectory"
if ($OutputLocDir.ShowDialog() -eq "OK") {
$OutputLoc = $OutputLocDir.SelectedPath
$OutputLoc = $OutputLoc.TrimEnd('\')
}
}
EDIT:
I should have been a little more clear. I had already tried message box type stuff as well but I'd really prefer if there is a way that the user types in a y or a n. I'm not really interested in a popup box that the user has to click. If it's not possible then so be it.
Readkey is the right way.
Use the following as template.
:prompt while ($true) {
switch ([console]::ReadKey($true).Key) {
{ $_ -eq [System.ConsoleKey]::Y } { break prompt }
{ $_ -eq [System.ConsoleKey]::N } { return }
default { Write-Error "Only 'Y' or 'N' allowed!" }
}
}
write-host 'do it' -ForegroundColor Green
:prompt gives the outer loop (while) a name which can be used in the switch statement to directly break out entirely via break prompt (and not within the switch statement).
Alternative (for Windows):
Use a MessageBox.
Add-Type -AssemblyName PresentationFramework
$messageBoxResult = [System.Windows.MessageBox]::Show("Do you want the output file generated to $startDirectory\FolderList.txt?" , 'Question' , [System.Windows.MessageBoxButton]::YesNo , [System.Windows.MessageBoxImage]::Question)
switch ($messageBoxResult) {
{ $_ -eq [System.Windows.MessageBoxResult]::Yes } {
'do this'
break
}
{ $_ -eq [System.Windows.MessageBoxResult]::No } {
'do that'
break
}
default {
# stop
return # or EXIT
}
}
Not sure if this is possible in the console. But when I need the user to write one answer of a specified set, I use a do-until-loop like:
Do {
$a = Read-Host "Y / N"
} until ( 'y', 'n' - contains $a )
try this:
$title = 'Question'
$question = 'Do you want the output file generated to $startDirectory\FolderList.txt?'
$choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription]
$choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes'))
$choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&No'))
$decision = $Host.UI.PromptForChoice($title, $question, $choices, 1)
if ($decision -eq 0) {
Write-Host 'Yes'
} else {
Write-Host 'No'
}
If you are on Windows, you can do it :
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null
$result = [System.Windows.Forms.MessageBox]::Show('Do you want the output file generated to $startDirectory\FolderList.txt?' , "Question" , [System.Windows.Forms.MessageBoxButtons]::YesNo, [System.Windows.Forms.MessageBoxIcon]::Question)
if ($result -eq 'Yes') {
"Yes"
}
else
{
"No"
}

Automatically Adding a Number to variable in Powershell

I have looked at some sites online and browsed a few answers here and I have had no luck with my question.
I have a PowerShell script to automate account creations using information entered in the host. My question is this, how can I set my script to automatically add a number at the end of the submitted data if it already exists? Code block is below:
$Username = Read-host "Enter Desired Username"
#Test
IF(!(Get-ADUser -Identity $Username))
{ Write-Host "$username exists. Adding number.
HERE IS THE CODE I AM LOOKING FOR TO TAKE THE $Username and automatically add the number at the end.
}
If this was already answered, please send me the link and I'll mark this as answered but if not, any suggestions would be great.
Thanks!
Since this script isn't being automatically run and there is user input, I would suggest just re-prompting the user if the name is taken:
Do
{
$Username = Read-Host -Prompt 'Enter desired username'
} While (Get-ADUser -Identity $Username)
Alternatively:
$Username = Read-Host -Prompt 'Enter desired username'
While (Get-ADUser -Identity $Username)
{
"Username '$Username' taken!"
$Username = Read-Host -Prompt 'Enter desired username'
}
To supplement the other answer, you could also do something like this to determine the next available username:
$Username = Read-Host -Prompt 'Enter desired username'
$TestUsername = $Username
$i = 1
While (Get-ADUser -Identity $TestUsername)
{
Write-Warning "$TestUsername is taken"
$TestUsername = $Username + $i++
}
"The next available username is $TestUsername"
Within the loop the ++ operator is used to increment the counter variable $i and appends that to the original username each time the loop repeats. Note that it is appended first then incremented second, so we start at 1.
I've written such a script. My logic is:
Before creating an account, query this account firstly
If the account exists, suffix a 2 digits number (from 01, format by "{0:d2}" -f
Query the suffixed account, repeat step 1 and 2, till the account doesn't exist (use recursive function).
It's the code:
$seq = 1
Function Check-Existing {
param(
[Parameter(Mandatory=$true)]
[string]$Account
)
while (Get-ADUser $Account){
$suffix = "{0:d2}" -f $seq
$Account = $Account + $suffix
$seq++
return $Account
}
Check-Existing -Account $Account
}
(I'll double check the code on Monday)

Powershell while loop

The below code keeps getting stuck in a loop when it gets to
$choice = read-host "Are you sure you want to disable the following user? (Y/N)" "$name"
I type in y and it keeps looping that question.
I've tried a do while & single IF statement. Any ideas on how to stop this loop?
$choice = ""
$User = read-host "enter username"
$Name = Get-ADuser -Identity $Username | Select-Object Name
while ($choice -notmatch "y/n"){
$choice = read-host "Are you sure you want to disable the following user? (Y/N)" "$name"
If ($Choice -eq"Y"){
Disable-ADAccount $Username
}
}
You need to use the pipe for an or statement to work not a slash
This...
while ($choice -notmatch "y/n"
...should be this...
while ($choice -notmatch "y|n"
This is wrong, because you do not have a populated variable in the posted code to use...
Disable-ADAccount $Username
... based on your code, it should be this...
Disable-ADAccount $User
No need to seperate the variable in the choice statment. Just do this.
$choice = read-host "Are you sure you want to disable the following user? (Y or N) $name"
Example:
$choice = ""
$User = read-host "enter username"
$Name = $User
while ($choice -notmatch "y|n")
{
$choice = read-host "Are you sure you want to disable the following user? (Y/N) $Name"
If ($Choice -eq "y")
{ $User }
}
enter username: test
Are you sure you want to disable the following user? (Y/N) test: u
Are you sure you want to disable the following user? (Y/N) test: u
Are you sure you want to disable the following user? (Y/N) test: y
test
enter username: test1
Are you sure you want to disable the following user? (Y/N) test1: h
Are you sure you want to disable the following user? (Y/N) test1: h
Are you sure you want to disable the following user? (Y/N) test1: n

Checking if Distribution Group Exists in Powershell

I am writing a script to quickly create a new distribution group and populate it with a CSV. I am having trouble testing to see if the group name already exists.
If I do a get-distributiongroup -id $NewGroupName and it does not exist I get an exception, which is what I expect to happen. If the group does exist then it lists the group, which is also what I expect. However, I can not find a good way to test if the group exists before I try to create it. I have tried using a try/catch, and also doing this:
Get-DistributionGroup -id $NewGroupName -ErrorAction "Stop"
which makes the try/catch work better (as I understand non-terminating errors).
Basically, I need to have the user enter a new group name to check if it is viable. If so, then the group gets created, if not it should prompt the user to enter another name.
You can use SilentlyContinue erroraction so that no exception/error shows:
$done = $false
while(-not $done)
{
$newGroupName = Read-Host "Enter group name"
$existingGroup = Get-DistributionGroup -Id $newGroupName -ErrorAction 'SilentlyContinue'
if(-not $existingGroup)
{
# create distribution group here
$done = $true
}
else
{
Write-Host "Group already exists"
}
}
This should do the trick:
((Get-DistributionGroup $NewGroupName -ErrorAction 'SilentlyContinue').IsValid) -eq $true