I am confused with the behavior of the conditional statements in my Powershell script - control-flow

I was testing the control flow of my script to see what direction I was going with it, and got some strange results. At first it all seemed to be working correctly, but I decided to test the other if statement first, and after this run I ran the script again and followed the other IF statement which now will not work. I did not change anything in the script. I think there must be something up with one of my statements. The first conditional statement uses a nested IF statement and the second does not. Both ways work on the first run. A link is below to see the output.Script runs
$Optcmd = Read-Host -Prompt "Does the User/s require permissions set to the whole [M]ailbox or to a specific [F]older within the mailbox?[M/F]"
if ($Optcmd -like "m"){
$confmailbox = Read-Host -Prompt "The permission you set here will give the User/s the same level of access to the other folders and calendar within the mailbox. Continue?[Y/N]"
}
else {
$confmfoldper = Read-Host -Prompt "You have selected to apply permissions to a specific folder continue? [Y/N]?"
}
if ($confmailbox -like "y"){
Write-Host -ForegroundColor Yellow "What access rights does the user/s require? "
Write-Host -ForegroundColor Green "[1] ChangeOwner - "-NoNewline
Write-Host -ForegroundColor Yellow " The user who can change the mailbox owner permission"
Write-Host -ForegroundColor Green "[2] DeleteItem - " -NoNewline
Write-Host -ForegroundColor Yellow " The user who can only delete items in the mailbox"
Write-Host -ForegroundColor Green "[3] ExternalAccount - " -NoNewline
Write-Host -ForegroundColor Yellow " The user is not in the same organization"
Write-Host -ForegroundColor Green "[4] FullAccess - " -NoNewline
Write-Host -ForegroundColor Yellow " The user who can do everything in this mailbox"
Write-Host -ForegroundColor Green "[5] ReadPermission - " -NoNewline
Write-Host -ForegroundColor Yellow " The user who can only read everything in the mailbox"
$Boxperm = Read-Host -prompt "Enter corresponding number"
if ($Boxperm -eq 1){$Boxperm = 'ChangeOwner'}
if ($Boxperm -eq 2){$Boxperm = 'DeleteItem'}
if ($Boxperm -eq 3){$Boxperm = 'ExternalAccount'}
if ($Boxperm -eq 4){$Boxperm = 'FullAccess'}
if ($Boxperm -eq 5){$Boxperm = 'ReadPermission'
}
$Boxperm
}
Elseif ($confmfoldper -like 'y') {
Write-Host -ForegroundColor Yellow "Select a role to assign to the User/s "
Write-Host -ForegroundColor Green "[1] Author - "-NoNewline
Write-Host -ForegroundColor Yellow "CreateItems, DeleteOwnedItems, EditOwnedItems, FolderVisible, ReadItems"
Write-Host -ForegroundColor Green "[2] Contributor - " -NoNewline
Write-Host -ForegroundColor Yellow "CreateItems, FolderVisible"
Write-Host -ForegroundColor Green "[3] Editor - " -NoNewline
Write-Host -ForegroundColor Yellow "CreateItems, DeleteAllItems, DeleteOwnedItems, EditAllItems, EditOwnedItems, FolderVisible, ReadItems"
Write-Host -ForegroundColor Green "[4] NonEditingAuthor - " -NoNewline
Write-Host -ForegroundColor Yellow "CreateItems, DeleteOwnedItems, FolderVisible, ReadItems"
Write-Host -ForegroundColor Green "[5] Owner - " -NoNewline
Write-Host -ForegroundColor Yellow "CreateItems, CreateSubfolders, DeleteAllItems, DeleteOwnedItems, EditAllItems, EditOwnedItems, FolderContact, FolderOwner, FolderVisible, ReadItems"
Write-Host -ForegroundColor Green "[6] PublishingAuthor - " -NoNewline
Write-Host -ForegroundColor Yellow "CreateItems, CreateSubfolders, DeleteOwnedItems, EditOwnedItems, FolderVisible, ReadItems"
Write-Host -ForegroundColor Green "[7] PublishingEditor - " -NoNewline
Write-Host -ForegroundColor Yellow "CreateItems, CreateSubfolders, DeleteAllItems, DeleteOwnedItems, EditAllItems, EditOwnedItems, FolderVisible, ReadItems"
Write-Host -ForegroundColor Green "[8] Reviewer - " -NoNewline
Write-Host -ForegroundColor Yellow "FolderVisible, ReadItems"
$Folderperm = Read-Host -prompt "Enter corresponding number"
$Folderperm
}
Updated Script:
param(
[String]$Useremail,
[String]$ImportPath
)
$confmailbox = $null
$Folderperm = $null
$confmfoldper = $null
$Folder = $null
$Mailbox = Read-Host “Enter Mailbox ID “
$Displayname = Get-Mailbox -Identity $Mailbox
$Optcmd = Read-Host -Prompt "Does the User/s require permissions set to the whole [M]ailbox or to a specific [F]older within the mailbox?[M/F]"
if ($ImportPath -ne "") {
$ImportCSV = Import-Csv $ImportPath
}
if ($Optcmd -like "m"){
$confmailbox = Read-Host -Prompt "The permission you set here will give the User/s the same level of access to the other folders and calendar within the mailbox. Continue?[Y/N]"
}
elseif ($Optcmd -like "f") {
$confmfoldper = Read-Host -Prompt "You have selected to apply permissions to a specific folder continue? [Y/N]?"
}
if ($confmailbox -like "y"){
Write-Host -ForegroundColor Yellow "What access rights does the user/s require? "
Write-Host -ForegroundColor Green "[1] ChangeOwner - "-NoNewline
Write-Host -ForegroundColor Yellow " The user who can change the mailbox owner permission"
Write-Host -ForegroundColor Green "[2] DeleteItem - " -NoNewline
Write-Host -ForegroundColor Yellow " The user who can only delete items in the mailbox"
Write-Host -ForegroundColor Green "[3] ExternalAccount - " -NoNewline
Write-Host -ForegroundColor Yellow " The user is not in the same organization"
Write-Host -ForegroundColor Green "[4] FullAccess - " -NoNewline
Write-Host -ForegroundColor Yellow " The user who can do everything in this mailbox"
Write-Host -ForegroundColor Green "[5] ReadPermission - " -NoNewline
Write-Host -ForegroundColor Yellow " The user who can only read everything in the mailbox"
$Boxperm = Read-Host -prompt "Enter corresponding number"
}
switch($Boxperm)
{
{$_ -eq 1} {$Boxperm = 'ChangeOwner' ; break;}
{$_ -eq 2} {$Boxperm = 'DeleteItem' ; break;}
{$_ -eq 3} {$Boxperm = 'ExternalAccount' ; break;}
{$_ -eq 4} {$Boxperm = 'FullAccess' ; break;}
{$_ -eq 5} {$Boxperm = 'ReadPermission' ; break;}
}
if ($confmfoldper -like 'y') {
Write-Host -ForegroundColor Yellow "Select a role to assign to the User/s "
Write-Host -ForegroundColor Green "[1] Author - "-NoNewline
Write-Host -ForegroundColor Yellow "CreateItems, DeleteOwnedItems, EditOwnedItems, FolderVisible, ReadItems"
Write-Host -ForegroundColor Green "[2] Contributor - " -NoNewline
Write-Host -ForegroundColor Yellow "CreateItems, FolderVisible"
Write-Host -ForegroundColor Green "[3] Editor - " -NoNewline
Write-Host -ForegroundColor Yellow "CreateItems, DeleteAllItems, DeleteOwnedItems, EditAllItems, EditOwnedItems, FolderVisible, ReadItems"
Write-Host -ForegroundColor Green "[4] NonEditingAuthor - " -NoNewline
Write-Host -ForegroundColor Yellow "CreateItems, DeleteOwnedItems, FolderVisible, ReadItems"
Write-Host -ForegroundColor Green "[5] Owner - " -NoNewline
Write-Host -ForegroundColor Yellow "CreateItems, CreateSubfolders, DeleteAllItems, DeleteOwnedItems, EditAllItems, EditOwnedItems, FolderContact, FolderOwner, FolderVisible, ReadItems"
Write-Host -ForegroundColor Green "[6] PublishingAuthor - " -NoNewline
Write-Host -ForegroundColor Yellow "CreateItems, CreateSubfolders, DeleteOwnedItems, EditOwnedItems, FolderVisible, ReadItems"
Write-Host -ForegroundColor Green "[7] PublishingEditor - " -NoNewline
Write-Host -ForegroundColor Yellow "CreateItems, CreateSubfolders, DeleteAllItems, DeleteOwnedItems, EditAllItems, EditOwnedItems, FolderVisible, ReadItems"
Write-Host -ForegroundColor Green "[8] Reviewer - " -NoNewline
Write-Host -ForegroundColor Yellow "FolderVisible, ReadItems"
$Folderperm = Read-Host -prompt "Enter corresponding number"
$Folder = Read-Host “Enter the FOLDER NAME ( Examplles : Inbox,calendar…)”
$foldername = $Displayname.WindowsEmailAddress + “:\” + $Folder
}
switch($Folderperm)
{
{$Folderperm -eq 1} {$Folderperm = 'Author' ; break; }
{$Folderperm -eq 2} {$Folderperm = 'Contributor' ; break;}
{$Folderperm -eq 3} {$Folderperm = 'Editor' ; break;}
{$Folderperm -eq 4} {$Folderperm = 'NonEditingAuthor' ; break;}
{$Folderperm -eq 5} {$Folderperm = 'Owner' ; break;}
{$Folderperm -eq 6} {$Folderperm = 'PublishingAuthor' ; break;}
{$Folderperm -eq 7} {$Folderperm = 'PublishingEditor' ; break;}
{$Folderperm -eq 8} {$Folderperm = 'Reviewer' ; break;}
}
if ($confmailbox -like 'y' -and $ImportPath -eq "") {
Add-MailboxPermission -identity $Displayname.Name -user $Useremail -AccessRights $Boxperm -InheritanceType All -Automapping $false
}
If ($Folder -ne “” -and $ImportPath -ne "") {
Add-MailboxFolderPermission $foldername -User $Useremail -AccessRights $Foldperm -confirm:$true
}
if ($confmailbox -like 'y' -and $ImportPath -ne "") {
foreach ($User in $ImportCSV){
Add-MailboxPermission -identity $Displayname.Name -user $User.Email -AccessRights $Boxperm -InheritanceType All -Automapping $false
}
}
If ($Folder -ne “” -and $ImportPath -ne "") {
foreach ($User in $ImportCSV) {
Add-MailboxFolderPermission $foldername -User $User -AccessRights $Foldperm -confirm:$true
}
}
I have had a chance to test out the ImportCSV parameter with the nested ForEach statements yet. However, the script works using
-Useremail parameter.

Related

Powershell send out email to users expiration of access

Okay so I have these users in a MSSQL database and I have the last time they logged in epoc time, does anybody know how to script something in powershell to notify user if they have not logged in for more than 30 days? I also have their email addresses stored in the database as well. If anybody could give me some guidance.
# clear log file
"######ERROR LOG File######" | Out-File $ErrorFileName
Get-Date -Format G | Add-Content $ErrorFileName
"####################" | Add-Content $ErrorFileName
#For loop giving variables to the objects
$objs = $Json.users
foreach($obj in $objs)
{
Try {
$userID = $obj.userID
$shortName = $obj.shortName
$firstname = $obj.firstName
$lastname = $obj.lastName
$email = $obj.email
$active =$obj.active
$lastActivationTimestamp = $obj.lastActivationTimestamp
Write-Host ($obj.userID) -BackgroundColor White -ForegroundColor darkblue
Write-Host ($obj.shortName) -BackgroundColor White -ForegroundColor darkblue
Write-Host ($obj.firstName) -BackgroundColor White -ForegroundColor red
Write-Host ($obj.lastName) -BackgroundColor White -ForegroundColor red
Write-Host ($obj.email) -BackgroundColor White -ForegroundColor red
Write-Host ($obj.active) -BackgroundColor White -ForegroundColor black
Write-Host ($obj.lastActivationTimestamp) -BackgroundColor White -ForegroundColor black
#Inserting into MYSQL database
$cmd = $connection.CreateCommand()
$insert_stmt = "INSERT INTO [dbo].[Users]([userID],[userName],[firstName],[lastName],[email],[Active],[lastActivationTimestamp])
VALUES ('$userID','$shortName','$firstname','$lastname','$email','$active','$lastActivationTimestamp')" -replace "\s+"," "
$cmd.CommandText = $insert_stmt
write-host $insert_stmt -BackgroundColor White -ForegroundColor DarkBlue
$cmd.ExecuteNonQuery()
} Catch {
# Error TYPE
"[$($_.Exception.GetType().FullName)]" | Add-Content $ErrorFileName
# Error MESSAGE
$_.Exception.Message | Add-Content $ErrorFileName
$ROW[0] | Add-Content $ErrorFileName
}
}

Need assistance incorporating multiple variables in a foreach against this script

I'm new to powershell and trying to modify an existing script to run multiple variables (domains) in a foreach loop. Snip of script below.
$DomainIdentities is the variable that will determine the $TargetDomain the script is running against. Let's say I have a couple domains, domainA.lab.local and domainB.lab.local, what's the best way to loop these two in a foreach to run against both domains?
Write-Host 'Gathering and analyzing target domain information...'
Import-Module ActiveDirectory
Import-Module GroupPolicy
$TargetDomain = Get-AdDomain -Identity $DomainIdentities | Select Name,DNSRoot,NetBIOSName,DomainMode,PDCEmulator
Write-Host ''
Write-Host ' Domain NetBIOS name: ' -NoNewline; Write-Host -ForegroundColor Cyan $TargetDomain.NetBIOSName
Write-Host ' Domain DNS name: ' -NoNewline; Write-Host -ForegroundColor Cyan $TargetDomain.DNSRoot
Write-Host ' PDC emulator: ' -NoNewline; Write-Host -ForegroundColor Cyan $TargetDomain.PDCEmulator
Write-Host ' DomainMode: ' -NoNewline; Write-Host -ForegroundColor Cyan $TargetDomain.DomainMode
Write-Host ' Checking domain functional mode is ''Windows2008Domain'' or higher.....' -NoNewline
$Status | Add-Member -MemberType NoteProperty -Name 'DomainModePassed' -Value (!(($TargetDomain.DomainMode -eq 'Windows2000Domain') -or ($TargetDomain.DomainMode -eq 'Windows2003InterimDomain') -or ($TargetDomain.DomainMode -eq 'Windows2003Domain')))
If ($Status.DomainModePassed) {Write-Host -ForegroundColor Green 'PASSED'}
Else {Write-Host -ForegroundColor Red 'FAILED'}
Write-Host ''
Declare Domains as a parameter that takes multiple string values at the top of your script:
param(
[string[]]$Domains
)
Write-Host 'Gathering and analyzing target domain information...'
Import-Module ActiveDirectory
Import-Module GroupPolicy
foreach($Domain in $Domains){
$TargetDomain = Get-ADDomain -Identity $Domain | Select Name,DNSRoot,NetBIOSName,DomainMode,PDCEmulator
Write-Host ''
Write-Host ' Domain NetBIOS name: ' -NoNewline; Write-Host -ForegroundColor Cyan $TargetDomain.NetBIOSName
Write-Host ' Domain DNS name: ' -NoNewline; Write-Host -ForegroundColor Cyan $TargetDomain.DNSRoot
Write-Host ' PDC emulator: ' -NoNewline; Write-Host -ForegroundColor Cyan $TargetDomain.PDCEmulator
Write-Host ' DomainMode: ' -NoNewline; Write-Host -ForegroundColor Cyan $TargetDomain.DomainMode
Write-Host ' Checking domain functional mode is ''Windows2008Domain'' or higher.....' -NoNewline
$Status | Add-Member -MemberType NoteProperty -Name 'DomainModePassed' -Value (!(($TargetDomain.DomainMode -eq 'Windows2000Domain') -or ($TargetDomain.DomainMode -eq 'Windows2003InterimDomain') -or ($TargetDomain.DomainMode -eq 'Windows2003Domain')))
If ($Status.DomainModePassed) {Write-Host -ForegroundColor Green 'PASSED'}
Else {Write-Host -ForegroundColor Red 'FAILED'}
Write-Host ''
}
Then pass the domain names to the script like so:
.\path\to\script.ps1 -Domains ad.contoso.com,ad.fabrikam.com

powershell multiple user input branching

I am a newbie when it comes to programming and powershell. I do have high ambition so I tasked myself to create something a lot more difficult than it should have been. Works great so far but it could be better.
My objective:
Create a powershell script that will copy an existing user to create a new user with similar functions with some bell and whistle.
The script functions:
Ask the admin which AD User to copy
Ask the admin to name the new AD User
Output some writings and then ask the user for confirmation before proceeding with choice Y or N
If the admin enter Y, proceed with the script.
If the admin enter N, restart the script over.
If the admin enter something else, ask the question again.
My Question:
How do I implement some sort of error checking in case the admin enter the wrong AD User to copy from, which doesn't exist and throws out an error code? I would like the console to alert them that it was wrong and to reenter it.
Code below. Any tip to perfect it would be much appreciated as well.
PS: I just started working with powershell and coding in general so I went over the top in doing something this simple, but I learned quite a bit. I plan to clean up the codes too. Perhaps this code may be useful to someone out there looking for something similar
Write-Host "****************************************************************"
Write-Host "**" -nonewline
Write-Host " New User Creation Script " -ForegroundColor yellow -nonewline
Write-Host "**"
Write-Host "****************************************************************`n"
Do {
Write-Host "Enter an AD Username to copy: " -ForegroundColor Green -NoNewline
$InputUser = Read-Host
$User = Get-AdUser -Identity $InputUser -Properties OfficePhone, Title, Department, State, Streetaddress, City, Country, Office, HomePage, Fax, Description, co, OfficePhone, PostalCode
$DN = $User.distinguishedName
$OldUser = [ADSI]"LDAP://$DN"
$Parent = $OldUser.Parent
$OU = [ADSI]$Parent
$OUDN = $OU.distinguishedName
Write-Host "Enter New Username: " -ForegroundColor Green -NoNewline
$NewUser = Read-Host
Write-Host "Enter First Name: " -ForegroundColor Green -NoNewline
$FirstName = Read-Host
Write-Host "Last Name: " -ForegroundColor Green -NoNewline
$LastName = Read-Host
$NewName = "$firstname $lastname"
Write-Host "Domain Name such as `"" -ForegroundColor Green -NoNewline
Write-Host "Datamartinc.net" -ForegroundColor Yellow -NoNewline
Write-Host "`": " -ForegroundColor Green -NoNewline
$Domain = Read-Host
$upn = $NewUser+"#$Domain"
Write-Host "`n---------------------------------------------------------------`n"
Write-Host "`Username: " -ForegroundColor Yellow -NoNewline
Write-Host "$NewUser"
Write-Host "First Name: " -ForegroundColor Yellow -NoNewline
Write-Host "$FirstName"
Write-Host "Last Name: " -ForegroundColor Yellow -NoNewline
Write-Host "$LastName"
Write-Host "UPN: " -ForegroundColor Yellow -NoNewline
Write-Host "$upn"
Write-Host "Copied User: " -ForegroundColor Yellow -NoNewline
Write-Host "$InputUser"
Do {
Write-Host "`nPress " -NoNewline
Write-Host "Y " -ForegroundColor Yellow -NoNewline
Write-Host "to confirm and " -NoNewline
Write-Host "N " -ForegroundColor Yellow -NoNewline
Write-Host "to redo: " -NoNewline
$confirm = Read-Host
} until (($Confirm -eq 'y') -or ($Confirm -eq 'n'))
if($Confirm -eq 'y')
{
New-ADUser -SamAccountName $NewUser -userPrincipalName $upn -Name $NewName -GivenName $firstname -Surname $lastname -Instance $DN -Path "$OUDN" -AccountPassword (Read-Host "New Password: " -AsSecureString) –ChangePasswordAtLogon $false
Get-ADUser -Identity $InputUser -Properties memberof | Select-Object -ExpandProperty memberof | Add-ADGroupMember -Members $NewUser
Set-ADUser -Identity "$NewUser" -CannotChangePassword:$true -PasswordNeverExpires:$True
Enable-ADAccount -Identity $NewUser
$Completed = "y"
; $Confirm ="n"}
else {Clear-Host
}
}
Until ($Completed -eq "y")
Write-Host "AD User Creation Completed Successfully"
Answer to your question:
try
{
get-aduser $InputUser -Properties * -ErrorAction Stop
}
catch
{
write-host $_.Exception.Message
}
imho powershell script is meant to save the time and have as less as possible read-hosts.

Powershell Multi-choice Menu and Sub menu

I coming from a vb script back ground in to the world of powershell
currently i am in the process of developing a console application with
a main menu and multiple-sub main menus.
i would like the menu system to work like a cascade effect for example:
---------------------------------------------------------------------
Main Menu
clear
write-host "A"
write-host "B"
write-host "C"
write-host "D"
#When the user choose a letter the use would then
#forwarded to the letter A menu
$Choice = read-host ''"Please enter your Choice"
--------------------------------------------------------
Menu A
#If the user selects any of the options available from (A-Test1 to A-Test3) in #Menu A for example A-Test1:
#The menu A-Test1 will show up and display a menu of a list of
#actions to perform or return the user back to the menu A.
write-host "A-Test1"
write-host "A-Test2"
write-host "A-Test3"
write-host "A-Test4"
write-host "Exit " # Exit will return the user back to the main menu
# To select another choice.
$select = read-host ''"Please select from menu A:"
There are several ways you could create a menu system. Personally, I have used this format in the past for a menu driven, TUI script:
function mainMenu {
$mainMenu = 'X'
while($mainMenu -ne ''){
Clear-Host
Write-Host "`n`t`t My Script`n"
Write-Host -ForegroundColor Cyan "Main Menu"
Write-Host -ForegroundColor DarkCyan -NoNewline "`n["; Write-Host -NoNewline "1"; Write-Host -ForegroundColor DarkCyan -NoNewline "]"; `
Write-Host -ForegroundColor DarkCyan " Submenu1"
Write-Host -ForegroundColor DarkCyan -NoNewline "`n["; Write-Host -NoNewline "2"; Write-Host -ForegroundColor DarkCyan -NoNewline "]"; `
Write-Host -ForegroundColor DarkCyan " Submenu2"
$mainMenu = Read-Host "`nSelection (leave blank to quit)"
# Launch submenu1
if($mainMenu -eq 1){
subMenu1
}
# Launch submenu2
if($mainMenu -eq 2){
subMenu2
}
}
}
function subMenu1 {
$subMenu1 = 'X'
while($subMenu1 -ne ''){
Clear-Host
Write-Host "`n`t`t My Script`n"
Write-Host -ForegroundColor Cyan "Sub Menu 1"
Write-Host -ForegroundColor DarkCyan -NoNewline "`n["; Write-Host -NoNewline "1"; Write-Host -ForegroundColor DarkCyan -NoNewline "]"; `
Write-Host -ForegroundColor DarkCyan " Say hello"
Write-Host -ForegroundColor DarkCyan -NoNewline "`n["; Write-Host -NoNewline "2"; Write-Host -ForegroundColor DarkCyan -NoNewline "]"; `
Write-Host -ForegroundColor DarkCyan " Say goodbye"
$subMenu1 = Read-Host "`nSelection (leave blank to quit)"
$timeStamp = Get-Date -Uformat %m%d%y%H%M
# Option 1
if($subMenu1 -eq 1){
Write-Host 'Hello!'
# Pause and wait for input before going back to the menu
Write-Host -ForegroundColor DarkCyan "`nScript execution complete."
Write-Host "`nPress any key to return to the previous menu"
[void][System.Console]::ReadKey($true)
}
# Option 2
if($subMenu1 -eq 2){
Write-Host 'Goodbye!'
# Pause and wait for input before going back to the menu
Write-Host -ForegroundColor DarkCyan "`nScript execution complete."
Write-Host "`nPress any key to return to the previous menu"
[void][System.Console]::ReadKey($true)
}
}
}
function subMenu2 {
$subMenu2 = 'X'
while($subMenu2 -ne ''){
Clear-Host
Write-Host "`n`t`t My Script`n"
Write-Host -ForegroundColor Cyan "Sub Menu 2"
Write-Host -ForegroundColor DarkCyan -NoNewline "`n["; Write-Host -NoNewline "1"; Write-Host -ForegroundColor DarkCyan -NoNewline "]"; `
Write-Host -ForegroundColor DarkCyan " Show processes"
Write-Host -ForegroundColor DarkCyan -NoNewline "`n["; Write-Host -NoNewline "2"; Write-Host -ForegroundColor DarkCyan -NoNewline "]"; `
Write-Host -ForegroundColor DarkCyan " Show PS Version"
$subMenu2 = Read-Host "`nSelection (leave blank to quit)"
$timeStamp = Get-Date -Uformat %m%d%y%H%M
# Option 1
if($subMenu2 -eq 1){
Get-Process
# Pause and wait for input before going back to the menu
Write-Host -ForegroundColor DarkCyan "`nScript execution complete."
Write-Host "`nPress any key to return to the previous menu"
[void][System.Console]::ReadKey($true)
}
# Option 2
if($subMenu2 -eq 2){
$PSVersionTable.PSVersion
# Pause and wait for input before going back to the menu
Write-Host -ForegroundColor DarkCyan "`nScript execution complete."
Write-Host "`nPress any key to return to the previous menu"
[void][System.Console]::ReadKey($true)
}
}
}
mainMenu
You can nest as many menus deep as you need or put your code to execute at any level. I have since switched to using WinForms when I need a user-friendly tool, but this format has served me well for a while (and I still use it for some scripts in my lab where I don't feel like creating a full GUI).
The only part that might be confusing is the pause I have in there after your code executes waiting for a user to press any key. If you don't have that in there, the script will clear the console and go back to the menu after your code executes. I put that in so that I can review the output before returning to the menu system.

Change background/foreground color of powershell variable

So i have a powershell script that checks if an IP is available or not, and at the end it counts how many is available and how many not.
Would i be able to change the background/foreground color of the $used & $avail variables?
Clear-Host
$Ping = New-Object System.Net.Networkinformation.ping
$IP = Read-Host 'What ip range you want to scan (eg. 192.168.0.)?'
$pused = 0
$pavail = 0
for ($i=1; $i -le 254; $i++)
{
$Status = $Null
$IPAddress = $IP + $i
$Status = ($Ping.Send("$IPAddress", 1)).Status
if ($Status -eq "TimedOut")
{
Write-Host "$IPAddress is available!" -BackgroundColor Green
$avail = $pavail++
} else {
Write-Host "$IPAddress is in USE!" -BackgroundColor Red
$used = $pused++
}
}
Write-Host ""
Write-Host $used -BackgroundColor Red "IPs currently in use" -foregroundcolor "black"
Write-Host ""
Write-Host $avail "IPs currently available" -BackgroundColor Green -foregroundcolor "black"
The only way I can think to do what you want is by using multiple Write-Host lines.
Write-Host ""
Write-Host -NoNewline $pused -ForegroundColor Black -BackgroundColor Red
Write-Host " IPs currently in use"
Write-Host ""
Write-Host -NoNewline $pavail -ForegroundColor Black -BackgroundColor Green
Write-Host " IPs currently available"
You can use the -NoNewline parameter so that the ouput will still print to the same line in the console.