New to PS and need some help with $null values, I want to ask the user to set a OU path but if the user enters nothing then it will revert to the default which is in the if statement.
$OU = Read-Host -Prompt "Enter the new users OU path"
if($null -eq $OU)
{
$OU="CN=Users,DC=de,DC=ing,DC=kus,DC=tb"
}
else
{
}
Replaced the $null with "" as I was detecting a string.
$OU = Read-Host "Enter the new users OU path"
if ($OU -eq "")
{
$OU = "CN=Users,DC=**,DC=***,DC=***,DC=**"
}
else
{
}
Related
I have a GUI in my .ps1, and I declared what I think of as an arraylist, $choice = #() to store selected options. Whenever you select anything in the GUI, it adds "Option [#]" to the list. The first time, it does it correctly. each entry you select makes a new line. however, if you deselect one, and reselect it, it appends the string. so instead of the list being:
$choice = (
Option 1
Option 3
)
It is now
$choice= (
Option 1Option 3
)
Here is the full script.
# Set the initial choices
$choice = #()
# Use a while loop to keep the menu open until the user selects the "Exit" option
while ($true) {
# Clear the screen
Clear-Host
# Use a foreach loop to display each menu option, including an asterisk on the selected options
foreach ($option in "Option 1", "Option 2", "Option 3", "Option 0", "Exit") {
if ($choice -contains $option) {
Write-Host "$option *"
} elseif ($option -eq "Option 0") {
# "Option 0" is not a selectable option, so always display it as deselected
Write-Host $option
} else {
Write-Host $option
}
}
# Prompt the user to enter their selection
$userInput = Read-Host "Enter your selection"
# Use a switch statement to execute the selected options
switch -regex ($userInput)
{
"0" {
# Code for Option 0
# Print the selected options and exit the script
Write-Warning "Choices variable: $choice"
Write-Host "Selected options: "
switch ($choice) {
"Option 1" {
Write-Host "1"
}
"Option 2" {
Write-Host "2"
}
"Option 3" {
Write-Host "3"
}
default {
Write-Host "No selected options."
}
}
# Return to exit the current iteration of the while loop
return
}
"1" {
# Code for Option 1
# Check if the user has already selected this option
if ($choice -contains "Option 1") {
# Remove the option from the $choice variable
$choice = $choice | Where-Object {$_ -ne "Option 1"}
} else {
# Add the option to the $choice variable
$choice += "Option 1"
}
}
"2" {
# Code for Option 2
# Check if the user has already selected this option
if ($choice -contains "Option 2") {
# Remove the option from the $choice variable
$choice = $choice | Where-Object {$_ -ne "Option 2"}
} else {
# Add the option to the $choice variable
$choice += "Option 2"
}
}
"3" {
# Code for Option 3
# Check if the user has already selected this option
if ($choice -contains "Option 3") {
# Remove the option from the $choice variable
$choice = $choice | Where-Object {$_ -ne "Option 3"}
} else {
# Add the option to the $choice variable
$choice += "Option 3"
}
}
"4" {
# Code for Exit
# Break out of the while loop to end the script
break
}
default {
# Code for invalid selection or deselection
# Check if the user has deselected an option
if ($choice -contains $userInput) {
# Remove the option from the $choice variable
$choice = $choice | Where-Object {$_ -ne $userInput}
} else {
# The user has entered an invalid selection
Write-Host "Invalid selection"
}
}
}
}
I for the life of me can't figure out why removing something from the list breaks the ability to add new items to the list.
Continuing from my comment.
If you are trying to add/remove from a list, then you should avoid using this: $choice = #(). Instead, use $arrlist = New-Object -TypeName System.Collections.ArrayList, and instead of +=, use $arrlist.Add("SomeValue") and $arrlist.Remove("SomeValue").
Example:
$arrlist = New-Object -TypeName System.Collections.ArrayList
$arrlist.Add("One")
$arrlist.Add("Two")
$arrlist
# Results
<#
0
1
One
Two
#>
$arrlist.Add("Three")
# Results
<#
2
#>
$arrlist
# Results
<#
One
Two
Three
#>
$arrlist.Remove("Two")
$arrlist
# Results
<#
One
Three
#>
So, a refactor of your code might look like this:
$choice = New-Object -TypeName System.Collections.ArrayList
while ($true)
{
Clear-Host
foreach ($option in 'Option 1', 'Option 2', 'Option 3', 'Option 0', 'Exit')
{
if ($choice -contains $option)
{"$option *"}
elseif ($option -eq 'Option 0')
{$option}
else {$option}
}
$userInput = Read-Host 'Enter your selection'
switch -regex ($userInput)
{
'0'
{
Write-Warning -Message 'Choices variable: $choice'
'Selected options: '
switch ($choice) {
'Option 1' {'1'}
'Option 2' {'2'}
'Option 3' {'3'}
default {'No selected options.'}
}
return
}
'1' {
if ($choice -contains 'Option 1')
{
$choice = $choice |
Where-Object {$PSItem -ne 'Option 1'}
}
else {$choice.Add('Option 1')}
}
'2'
{
if ($choice -contains 'Option 2')
{
$choice = $choice |
Where-Object {$PSItem -ne 'Option 2'}
}
else {$choice.Add('Option 2')}
}
'3'
{
if ($choice -contains 'Option 3')
{
$choice = $choice |
Where-Object {$PSItem -ne 'Option 3'}
}
else {$choice.Remove('Option 3')}
}
'4' {break}
default
{
if ($choice -contains $userInput)
{
$choice = $choice |
Where-Object {$PSItem -ne $userInput}
}
else {Write-Warning -Message 'Invalid selection'}
}
}
}
I need help with PowerShell code. I have to update a couple of programs using PowerShell, but I am getting errors while running the script.
Inputs to the code are 1 and 0 for Switch condition and other inputs are foo, boo, Oracle to be updated, based on condition software will be updated.
$param = Read-Host -Prompt "Enter the input 1 or 0"
[bool]$upg = $true
$sftp = Read-Host "Please Enter the softwre to update"
switch ($param)
{
0{
Write-Output "Today is monday"
}
1
{
$prm_prd = Read-Host -Prompt "Are you going for operation upgrade"
if ($prm_prd -eq $upg)
{
Write-Output "System upgrade"
if ($sftp -eq 'foo')
{
Write-Output "foo upgrade"
}
elseif ( $sftp -eq 'boo')
{
Write-output "boo upgrade"
}
elseif ( $sftp -eq 'Oracle')
{
Write-output "oracle upgrade"
}
}
}
}
Didn't you post some form of this before? Elseif not else-if.
I'm finding that I have the following Generic List, and I can see it has items in it, but when I try to run the code, it's not hitting inside the foreach. This is my code:
function SQLQueryWriteToFile([string]$SQLquery, [string]$extractFile)
{
$sqlConnection = New-Object System.Data.SqlClient.SqlConnection
$sqlConnection.ConnectionString = "Server=blah;Database=blah;User ID=blah;Password=blah" #production #I have an error in this so it doesn't connect
$sqlConnection.Open()
if($sqlConnection.State -ne 'Open'){
$global:ErrorStrings.Add("Exception: $("Couldn't connect to DB with connection string given");; ") #this gets hit
}
###
$global:ErrorStrings = New-Object System.Collections.Generic.List[System.String] #System.Object]
$query = "Select blah"
$dir = "C:\blah"
SQLQueryWriteToFile $query $dir
$errorCodeAsString = ""
foreach ($item in $global:ErrorStrings.Members){
$errorCodeAsString += $item #this isn't hit
}
Any idea why it's not finding the error string in my list for the foreach loop, when I can see it's in there looking at $global:ErrorStrings? Based on this foreach list, I'm doing it correctly. I'm having trouble finding examples like what I'm doing. Thanks!
try this:
function SQLQueryWriteToFile([string]$SQLquery, [string]$extractFile)
{
[System.Data.SqlClient.SqlConnection] $sqlConnection=$null
[System.Data.SqlClient.SqlCommand] $command=$null
try
{
$sqlConnection = New-Object System.Data.SqlClient.SqlConnection
$sqlConnection.ConnectionString = "Server=blah;Database=blah;User ID=blah;Password=blah"
$command = New-Object System.Data.SqlClient.SqlCommand
$command.Connection=$sqlConnection
$command.CommandText=$SQLquery
$sqlConnection.Open()
$command.ExecuteNonQuery()
}
catch
{
$global:ErrorStrings.Add($_.Exception.Message)
}
finally
{
if ($sqlConnection -ne $null)
{
$sqlConnection.Close()
$sqlConnection.Dispose()
}
if ($command -ne $null)
{
$command.Dispose()
}
}
}
$global:ErrorStrings = New-Object System.Collections.Generic.List[System.String]
$query = "Select blah"
$dir = "C:\blah"
$global:ErrorStrings.Clear()
SQLQueryWriteToFile $query $dir
$errorCodeAsString=""
for ($i = 0; $i -lt $global:ErrorStrings.Count; $i++)
{
$errorCodeAsString +=$global:ErrorStrings.Item($i)
}
$errorCodeAsString
I am building a script that'll check if ArchiveStatus for an Office 365 mailbox is active or not. I am able to pull the data, but my if/else statement doesn't seem to work. This is what I have so far:
$Data = Get-Mailbox -Identity "MailboxName" | ft name,*Archive*
$Data
if ($_.ArchiveStatus -eq $true) {
Write-Host "Archive Enabled"
} else{
Write-Host "Archiving Disabled"
}
No matter what mailbox I search up, the result is always "Archiving Disabled" even if the console shows user enabled.
The current object variable ($_) is only available in a pipeline context. Your if statement is outside a pipeline, so $_ doesn't exist, meaning that $_.ArchiveStatus evaluates to $null, which is interpreted as $false in the comparison.
Change this:
$Data = Get-Mailbox -Identity "MailboxName" | ft name,*Archive*
$Data
if ($_.ArchiveStatus -eq $true) {
Write-Host "Archive Enabled"
} else {
Write-Host "Archiving Disabled"
}
into this:
$Data = Get-Mailbox -Identity "MailboxName"
$Data | ft name,*Archive*
if ($Data.ArchiveStatus -eq $true) {
Write-Host "Archive Enabled"
} else {
Write-Host "Archiving Disabled"
}
and the problem should disappear.
So I was able to figure it out with help from #Ansgar Wiechers. The -eq $true wasn't working because it was either Active or None. When i created the variable for this it worked. The working code is below:
$Data = Get-Mailbox -Identity "MailboxName"
$Data | ft name, ArchiveStatus
$Status = "Active"
if($Data.ArchiveStatus -eq $Status) {
Write-Host "Archive Enabled"
} Else {
Write-Host "Archiving Disabled"
}
Thank you for your help!!
I'm working on a PowerShell script to make it easier to create Active Directory users including some attributes. For now I need to process the "Manager" field. We have 4 departments, 4 managers. I want to create this using logic like "if department is 1 of the 4 departments then give 1 of the 4 managers."
How can I process this?
Import-Module activedirectory
#Store the data from ADUsers.csv in the $ADUsers variable
$ADUsers = Import-csv "c:\temp\scripts\ADUsers.csv"
#Loop through each row containing user details in the CSV file
foreach ($User in $ADUsers)
{
#Read user data from each field in each row and assign the data to a variable as below
$Firstname = $User.firstname
$Lastname = $User.lastname
$Username = $User.username
$Password = $User.password
$OU = $User.ou #This field refers to the OU the user account is to be created in
$userprincipalname = $user.userprincipalname
$displayname = $user.displayname
$title = $user.jobtitle
$department = $user.department
#Check to see if the user already exists in AD
if (Get-ADUser -F {SamAccountName -eq $Username})
{
#If user does exist, give a warning
Write-Warning "A user account with username $Username already exist in Active Directory."
}
else
{
Write-host
#User does not exist then proceed to create the new user account
#Account will be created in the OU provided by the $OU variable read from the CSV file
New-ADUser -Name $displayname -SamAccountName $Username -UserPrincipalName $userprincipalname -GivenName $Firstname -Surname $Lastname -Enabled $True -DisplayName $displayname -AccountPassword (convertto-securestring $Password -AsPlainText -Force)
}
} #end function
Something like this?
if ($department -eq "A")
{
$manager = "ManagerA"
}
else if ($department -eq "B")
{
$manager = "ManagerB"
}
else if ($department -eq "C")
{
$manager = "ManagerC"
}
else if ($department -eq "D")
{
$manager = "ManagerD"
}
New-ADUser -Name $displayname -SamAccountName $Username -UserPrincipalName $userprincipalname -GivenName $Firstname -Surname $Lastname -Enabled $True -DisplayName $displayname -AccountPassword (convertto-securestring $Password -AsPlainText -Force) -Manager $manager
"ManagerA/B/C/D" are SAM account name of user objects of managers.
I have solved the problem with a Switch like below.
Switch ($department) {
"dept 1" {$manager = "cn=jim smith,ou=west,dc=domain,dc=com"}
"dept 2" {$manager = "cn=sally wilson,ou=east,dc=domain,dc=com"}
"dept 3" {$manager = "cn=frank johnson,ou=east,dc=domain,dc=com"}
"dept 4" {$manager = "cn=mary tutle,ou=west,dc=domain,dc=com"}