Why does my loop only happen once? I want to enter 5 users and add it to a hashtable, but the code runs once then stops. How Do I fix it?
$userID=""
$firstname=""
$lastname="
$personCount = 1
$personHash = #{}
while ($personCount -le 5){
$personCount++
While([string]::IsNullOrWhiteSpace($userID)){
$userID = Read-Host "Enter ID"
}
While([string]::IsNullOrWhiteSpace($firstname)){
$firstname = Read-Host "Enter First Name"
}
While([string]::IsNullOrWhiteSpace($lastname)){
$lastname = Read-Host "Enter Last Name"
}
$user = New-Object PSCustomObject -Property #{
ID = $userID
FirstName = $firstname
LastName = $lastname
}
$personHash.Add($user.ID,$user)
}
}
Output:
Enter ID: 1001
Enter First Name: Charles
Enter Last Name: Whitfield
Name Value
---- -----
1001 #{ID=1001; FirstName=Charles; LastName=Whitfield}
1001 #{ID=1001; FirstName=Charles; LastName=Whitfield}
1001 #{ID=1001; FirstName=Charles; LastName=Whitfield}
1001 #{ID=1001; FirstName=Charles; LastName=Whitfield}
Your loop runs 5 times.
The problem is that once the variables are populated in the first loop, they fail the While condition in the all the subsequent loops. It runs one time, doing a read-host and setting the variables. Then it runs 4 more times, but doesn't find anything to do.
Your updated code is closer. You save the data, but didn't clear the variables for the next loop.
$userID=""
$firstname=""
$lastname=""
$personCount = 1
$personHash = #{}
while ($personCount -le 5){
$personCount++
While([string]::IsNullOrWhiteSpace($userID)){
$userID = Read-Host "Enter ID"
}
While([string]::IsNullOrWhiteSpace($firstname)){
$firstname = Read-Host "Enter First Name"
}
While([string]::IsNullOrWhiteSpace($lastname)){
$lastname = Read-Host "Enter Last Name"
}
$user = New-Object PSCustomObject -Property #{
ID = $userID
FirstName = $firstname
LastName = $lastname}
$personHash.Add($user.ID,$user)
$UserID,$firstname,$lastname = ""
}
Couple of issues here, the while loops need clear variables like mjolinor said. Once that is done, I suggest saving that data in an array, so the data of each user is not lost by the next iteration:
$users = #()
$personCount = 1
while ($personCount -le 5){
$userID=""
$firstname=""
$lastname=""
$personCount++
While([string]::IsNullOrWhiteSpace($userID)){
$userID = Read-Host "Enter ID"
}
While([string]::IsNullOrWhiteSpace($firstname)){
$firstname = Read-Host "Enter First Name"
}
While([string]::IsNullOrWhiteSpace($lastname)){
$lastname = Read-Host "Enter Last Name"
}
$users += New-Object -TypeName PSCustomObject -Property #{
userID = $userID;
firstName = $firstname;
lastName = $lastname
}
}
Once the array $users has all the data, you can output all the values at once with $users or specific users with $users[0],$users[1], etc.
It's clearly not possible that the code you posted would create the output you posted. Even if I discount the two syntax errors you'd still be getting 4 key conflict exceptions, because you're trying to add the same key to the same hashtable 5 times (a key in a hashtable must be unique).
If you want to create 5 user objects in a hashtable and make sure that the user enters a value for all 3 properties you could do something like this if you want a duplicate ID to throw an error:
$personHash = #{}
1..5 | % {
do {
$userID = Read-Host "Enter ID"
$firstname = Read-Host "Enter First Name"
$lastname = Read-Host "Enter Last Name"
} until ( $userID -and $firstname -and $lastname )
$user = New-Object -Type PSCustomObject -Property #{
'ID' = $userID
'FirstName' = $firstname
'LastName' = $lastname
}
$personHash.Add($userID, $user)
}
or like this if you want a duplicate ID to update the current values:
$personHash = #{}
1..5 | % {
do {
$userID = Read-Host "Enter ID"
$firstname = Read-Host "Enter First Name"
$lastname = Read-Host "Enter Last Name"
} until ( $userID -and $firstname -and $lastname )
$user = New-Object -Type PSCustomObject -Property #{
'ID' = $userID
'FirstName' = $firstname
'LastName' = $lastname
}
$personHash[$userID] = $user
}
Related
I've created a script that takes new user data from a CSV file and connects to AzureAd and ExchangeOnline to create their AzureAD account, assigns them an Office license (not shown), and updates their Mailbox Office field.
CSV headers are Name, Department, OfficeLocation. The CSV used to contain a Domain and Company header. I removed those headers and added an if elseif statement to provide the logic to set those variables within the script. Prior to this addition, the script worked without any issues.
Now, the $company and $domain values are only updating for $main_offices and $corporate_offices Contoso and #contoso.com even when the OfficeLocation value is San Francisco or Austin and those values should be West/South Acme and west/south.acme.com.
Why are my $company and $domain values not being updated within the ForEach-Object loop as it iterates through the CSV? I confirmed that $company and $domain update properly when not reading in CSV data with ForEach-Object:
$new_users = Import-Csv -Path .\new-users.csv
...
$main_offices = 'New York','Los Angeles','Houston','Atlanta','Chicago'
$corporate_offices = 'Corporate Office (NY)','Corporate Office (LA)'
$west_office = 'San Francisco'
$south_office = 'Austin'
$new_users | ForEach-Object {
$first, $last = $_.Name.Split()
$mailnickname = $(($first.Substring(0,1) + $last).ToLower())
$password_profile = New-Object -TypeName Microsoft.Open.AzureAD.Model.PasswordProfile
$password_profile.Password = 'XXXXXXXXXXXXXXXXXX'
$password_profile.ForceChangePasswordNextLogin = $false
$off_loc = $_.OfficeLocation
if ($off_loc -in $main_offices -or $corporate_offices) {
$company = 'Contoso'
$domain = '#contoso.com'
} elseif ($off_loc -eq $west_office) {
$company = 'West Acme'
$domain = '#west.acme.com'
} elseif ($off_loc -eq $south_office) {
$company = 'South Acme'
$domain = '#south.acme.com'
} else { $off_loc = Read-Host 'Type an office location' } #CSV OfficeLocation field either missing or has a spelling error
$attr_new_user = #{
AccountEnabled = $true
CompanyName = $company
Department = $_.Department
DisplayName = $_.Name
GivenName = $first
MailNickname = $mailnickname
PasswordProfile = $password_profile
Surname = $last
UsageLocation = 'US'
UserPrincipalName = $mailnickname + $domain
}
try {
Write-Host ('>> Creating account for ' + $attr_new_user.DisplayName) -ForegroundColor Yellow
New-AzureADUser #attr_new_user | Out-Null
$user_upn = Get-AzureADUser -ObjectId $attr_new_user.UserPrincipalName | Select-Object -ExpandProperty UserPrincipalName
Write-Host ('>> ' + $user_upn + ' has been created') -ForegroundColor Green
}
catch {
Write-Host ('>> Something went wrong') -ForegroundColor Red
Write-Warning $Error[0]
}
...
try {
Write-Host ('>> Adding email alias: ' + $alternate_email + ' and office: ' + $off_loc + ' to ' + $user_upn) -ForegroundColor Yellow
Set-Mailbox -Identity $user_upn -EmailAddresses #{ add = $alternate_email } -Office $off_loc
Write-Host ('>> Email Alias: ' + $alternate_email + ' and office: ' + $off_loc + ' added to ' + $user_upn) -ForegroundColor Green
}
catch {
Write-Host ('>> Something went wrong') -ForegroundColor Red
Write-Warning $Error[0]
}
I've run the script and the $off_loc value is being inputted correctly in the Office field of the Mailbox settings. Which is why I am having trouble understanding how to get this information to create the user with the correct the $company and $domain fields.
Any insight into a solution to this issue is appreciated, thank you for taking the time to answer my question.
Per Santiago Squarzon:
This condition $off_loc -in $main_offices -or $corporate_offices will
always be $true because $corporate_offices is not $null or empty
string. It should be $off_loc -in $main_offices -or $off_loc -in
$corporate_offices
Confirmed this resolved the issue.
I have a simple script that I use to create new AD users. The basic script works great and gets me to where I need to be when I create a new user. There is one part that is missing that I would like to have automated so that I wont have to update the info manually. I need to add the address and phone number for a user based on their location. From the code below, I added the if elseif statement. What I have below gives the error - The term 'Austin' is not recognized as the name of a cmdlet, function, script file, or operable program. Obviously the variable $location doesn't work with the script, however, I am not as familar with PowerShell to see where to correct this or if there should be better way to write this out. Should I add Get-ADUser in front of it to pull the user info once its been added? Or add the if, elseif at the end of the script?
#Prompt for user information
$first = Read-Host "First name"
$last = Read-Host "Last name"
$title = Read-Host "Title"
$location = Read-Host "Location (location1,location2)"
$department = Read-Host "Business Practice"
$password = read-host -assecurestring "Password"
if($location = location1) {
Set-ADUser -street "StreetName" -city "City" -state "State" -postalcode "Zip" -officephone "Phone"
}
elseif($location = location2) {
Set-ADUser -street "StreetName" -city "City" -state "State" -postalcode "Zip" -officephone "Phone"
}
#Create new user
$Attributes = #{
Enabled = $true
ChangePasswordAtLogon = $false
UserPrincipalName = $first.substring(0,1)+$last+"#domain.com"
Name = $first + " " + $last
GivenName = $first
Surname = $last
DisplayName = $first + " " + $last
Office = $location
Department = $department
Title = $title
samAccountName = $first.substring(0,1)+$last
emailaddress = $first.substring(0,1)+$last+"#domain.com"
AccountPassword = $password
Path = "OU Path"
}
New-ADUser #Attributes
Set-ADUser needs to know the user for which these properties need to be set through its Identity parameter which is missing
You can simply add these properties to the $Attributes hashtable you use for the New-ADUser cmdlet.
You just need to define some logic as to where these properties come from.
Something like using a switch:
# with '$location' just ask for the city:
$location = Read-Host "City"
# I'm making this up of course
switch ($location) {
'Austin' {
$city = 'Austin'
$state = 'Texas'
$postalcode = '73301'
$officephone = '555-123456'
break
}
'Salt Lake City' {
$city = 'Salt Lake City'
$state = 'Utah'
$postalcode = '84044'
$officephone = '555-654321'
break
}
default { $city = $null }
}
if ($city) {
$Attributes = #{
Enabled = $true
ChangePasswordAtLogon = $false
UserPrincipalName = $first.substring(0,1)+$last+"#domain.com"
Name = $first + " " + $last
GivenName = $first
Surname = $last
DisplayName = $first + " " + $last
Office = $location
Department = $department
Title = $title
samAccountName = $first.substring(0,1)+$last
emailaddress = $first.substring(0,1)+$last+"#domain.com"
AccountPassword = $password
Path = "OU Path"
# these are from the switch() above
City = $city
State = $state
PostalCode = $postalcode
OfficePhone = $officephone
}
New-ADUser #Attributes
}
Or you can create a CSV file like
City,State,PostalCode,OfficePhone
Austin,Texas,73301,555-123456
Salt Lake City,Utah,84044,555-654321
and read that using
$locations = Import-Csv -Path '<PathToTheLocations.csv>'
# with '$location' just ask for the city:
$location = Read-Host "City"
# then get the address info from there based on the given city
$address = $locations | Where-Object { $_.City -eq $location }
if ($address) {
$Attributes = #{
Enabled = $true
ChangePasswordAtLogon = $false
UserPrincipalName = $first.substring(0,1)+$last+"#domain.com"
Name = $first + " " + $last
GivenName = $first
Surname = $last
DisplayName = $first + " " + $last
Office = $location
Department = $department
Title = $title
samAccountName = $first.substring(0,1)+$last
emailaddress = $first.substring(0,1)+$last+"#domain.com"
AccountPassword = $password
Path = "OU Path"
# these are from the CSV
City = $address.City
State = $address.State
PostalCode = $address.PostalCode
OfficePhone = $address.OfficePhone
}
New-ADUser #Attributes
}
Of course, NEVER trust user input from Read-Host and build in some validation checks before creating a new user
I am working on a script creating a new user via PowerShell with user (creator) input. The input I am looking for is for the first name and last name along with some attributes. I would like the samaccountname and the UPN to be auto created from the input. Not sure if this can be done completely but would like to get some input on my current script. I highlighted firstinital as a placeholder to show what I am trying to accomplish.
new-aduser -givenname($givenname = read-host "Input Firstname") -surname($surname = read-host "Input Lastname") -samAccountName ("***firstinitial***"+"$._surname") -userprincipalname "$._surname+"#domain.com" -path "OUName" -whatif
Alrighty thanks for the help below. I was able to do a few more searches and can up with the following. All looks to work except the distingushed name comes up as a single name instead of a space between the first and last name.
#User info entered
$first = Read-Host "First name"
$last = Read-Host "Last name"
$title = Read-Host "Title"
$location = Read-Host "Location"
$department = Read-Host "Business Practice"
$password = read-host -assecurestring "Password"
#Create new user
$Attributes = #{
Enabled = $true
ChangePasswordAtLogon = $false
UserPrincipalName = $first.split(" ")[0]+$last+"#domain.com"
Name = $first+$last
GivenName = $first
Surname = $last
DisplayName = "$first "+" $last"
Office = $location
Department = $department
Title = $title
samAccountName = $first.split(" ")[0] + $last
AccountPassword = $password
}
New-ADUser #Attributes -whatif
You can add this to get the $_.givenName as the first initial:
$gn = (read-host "Input Firstname")
$sn = (read-host "Input Lastname")
new-aduser -givenname $gn -surname $sn -samAccountName $gn.split(" ")[0]+$sn -userprincipalname $sn+"#kfriese.com" -path "OUName" -whatif
Here is a more advanced and robust way to do it: a custom function, that makes use of PowerShell integrated functionality.
It uses attributes that make the parameters mandatory, so user input will automatically be inquired when the function is called. Also a validation attribute to make sure the input is not empty and has no invalid characters (you might want to adjust the regex according to your needs).
The arguments for New-ADUser are passed using splatting. The rest is pretty straight-forward...
function makeuser {
param(
[Parameter(Mandatory, Position = 0)]
[ValidatePattern("[a-z]+")]
[string]$GivenName,
[Parameter(Mandatory, Position = 1)]
[ValidatePattern("[a-z]+")]
[string]$Surname
)
$params = #{
GivenName = $GivenName
Surname = $Surname
SamAccountName = $GivenName[0] + $Surname
UserPrincipalName = $Surname + "#kfriese.com"
Path = "OUName"
}
New-AdUser #params
}
To call the function, just type (parameter values will be inquired automatically)
makeuser
Or specify the values explicitly:
makeuser -GivenName Foo -Surname Bar
# or
makeuser foo bar
I stopped over at Code Review, asking how I could streamline a script and was advised to use a hashtable as it would clean up the code. I was given a very basic example but it wasn't plug-and-play. I've worked up some basic code but it's not doing what I think it should. Knowing the Code Review folks aren't there for support like this, here i am, looking for help with combining a variable from a CSV and a hashtable. I'll leave sample data from my CSV and the Powershell code below.
Sample CSV:
Student First Name,I,Student Last Name,Other ID,Stu Access Login,Student's School Email,School,Grad Year
Johosofat,L,Smith,999999,smithjoh000,smithjoh000#mydomain.org,30,2017
Tome,M,Smith,999998,smithtom000,smithtom000#mydomain.org,40,2021
Sample Powershell:
# Testing simple hash table
$SchoolCodes = #{
20 = "Exeter Township Senior High"
30 = "Exeter Township Junior High"
40 = "Lorane Elementary School"
50 = "Jacksonwald ES"
70 = "Reiffton School"
90 = "Owatin Creek Elementary School"
}
# CSV file being imported.
$CsvFile = "$env:USERPROFILE\Downloads\SampleData.csv"
# Import the contents of the CSV file.
$Users = Import-Csv -Path "$CsvFile"
# Loop through each line of the CSV, creating variables for each field.
ForEach ($User in $Users) {
# Creating the basic variables.
$FirstName = $User.'Student First Name'
$MiddleInitial = $User.'I'
$LastName = $User.'Student Last Name'
$ADUserName = $User.'Stu Access Login'
$StudentID = $User.'Other ID'
$GradYear = $User.'Grad Year'
$CapFInitial = $FirstName.substring(0,1).ToUpper()
$MInitial = $MiddleInitial.substring(0,1).ToLower()
$LInitial = $LastName.substring(0,1).ToLower()
$Password = "$CapFInitial$MInitial$LInitial" + "#" + "$StudentID"
$SchoolCode = $SchoolCodes[$User.School]
If (-Not(Get-ADUser -Filter {SamAccountName -eq $ADUserName})) {
Try {
# Create user.
New-ADUser `
-Name "$FirstName $LastName" `
-SamAccountName "$ADUserName" `
-GivenName "$FirstName" `
-Initials "$MiddleInitial" `
-Surname "$LastName" `
-DisplayName "$FirstName $MiddleInitial. $LastName" `
-UserPrincipalName "$ADUserName#mydomain.k12.pa.us" `
-EmailAddress "$ADUserName#mydomain.k12.pa.us" `
-AccountPassword (ConvertTo-SecureString $Password -AsPlainText -Force) `
-Enabled $false `
-PasswordNeverExpires $true `
-CannotChangePassword $true `
-Path "OU=$GradYear,OU=Students,OU=$SchoolCode,OU=accounts,DC=academic,DC=mydomain,DC=k12,DC=pa,DC=us" `
-WhatIf
}
Catch {
Write-Error "[ERROR] Can't create user [$($ADUserName)] : $_"
}
}
}
My issue:
The script ultimately errors out because of the $SchoolCode variable being set to null, I think. I'm wanting the script to find the number (code) from the school field in the CSV and match that to the name which ends up being an OU in AD - where the User Object will get created. Basically, the code tries to create the User Object in "CN=Tome Smith,OU=2021,OU=Students,OU=,OU=accounts,DC=academic,DC=exeter,DC=k12,DC=pa,DC=us" which shows the $SchoolCode variable is either blank or otherwise not getting set correctly.
As I mentioned in a comment, we're thinking of adding other static data to the hashtable as a (nested?) hashtable. Here's an example of what we're thinking about. As time goes by, the list of AD groups may grow.
Example of the nested hashtable:
$SchoolCodes = #{
20 = #{
Name = "Exeter Township Senior High"
ADGroup1 = "Students"
ADGroup2 = "Secondary Students"
}
30 = #{
Name = "Exeter Township Junior High"
ADGroup1 = "Students"
ADGroup2 = "Secondary Students"
}
40 = #{
Name = "Lorane Elementary School"
ADGroup1 = "Students"
ADGroup2 = "K4 Students"
}
50 = #{
Name = "Jacksonwald ES"
ADGroup1 = "Students"
ADGroup2 = "K4 Students"
}
70 = #{
Name = "Reiffton School"
ADGroup1 = "Students"
ADGroup2 = "Secondary Students"
}
90 = #{
Name = "Owatin Creek Elementary School"
ADGroup1 = "Students"
ADGroup2 = "K4 Students"
}
}
I'm scouring the web and trying to get a better understanding of hashtables. If I can wrap my head around it, nesting them would be my next step.
Unless you're re-using the data, it's not important to turn it into a hashtable. Also, the error is in accessing the $SchoolCodes value. For some reason, the accessor isn't working with a [String], but does work when you cast to an [Int]
Sample dataset:
Student First Name,I,Student Last Name,Other ID,Stu Access Login,Student's School Email,School,Grad Year
Johosofat,L,Smith,999999,smithjoh000,smithjoh000#mydomain.org,30,2017
Tome,M,Smith,999998,smithtom000,smithtom000#mydomain.org,40,2021
Code:
#requires -Version 3
$SchoolCodes = #{
20 = "Exeter Township Senior High"
30 = "Exeter Township Junior High"
40 = "Lorane Elementary School"
50 = "Jacksonwald ES"
70 = "Reiffton School"
90 = "Owatin Creek Elementary School"
}
# CSV file being imported.
$CsvFile = "$env:USERPROFILE\Downloads\SampleData.csv"
# Import the contents of the CSV file.
$Users = Import-Csv -Path "$CsvFile"
# Loop through each line of the CSV, creating variables for each field.
ForEach ($User in $Users)
{
[String]$LoginName = $User.'Stu Access Login'
If (-not (Get-ADUser -Filter {SamAccountName -eq $LoginName}))
{
$FirstName = $User.'Student First Name'
$LastName = $User.'Student Last Name'
$Params = #{
Name = "$FirstName $LastName"
SamAccountName = $LoginName
GivenName = $FirstName
Initials = $User.I
Surname = $LastName
DisplayName = "$FirstName $($User.I) $LastName"
UserPrincipalName = "$LoginName#mydomain.k12.pa.us"
EmailAddress = "$LoginName#mydomain.k12.pa.us"
AccountPassword = ConvertTo-SecureString -String (
'{0}{1}{2}#{3}' -f #(
$FirstName[0].ToString().ToUpper(),
$User.I[0].ToString().ToLower(),
$LastName[0].ToString().ToLower(),
$User.'Other ID')) -AsPlainText -Force
Enabled = $False
PasswordNeverExpires = $True
CannotChangePassword = $True
Path = 'OU={0},OU=Students,OU={1},OU=accounts,DC=academic,DC=mydomain,DC=k12,DC=pa,DC=us' -f #(
$User.'Grad Year',
$SchoolCodes[[Int]$User.School])
WhatIf = $True
}
Try {New-ADUser #Params}
Catch {Write-Error "[ERROR] Can't create user [$LoginName] : $_"}
}
}
Below is the code to an internal tool I was put in charge of setting up. It basically references a spreadsheet based on a known value and uses some of that information for sorting purposes and uses other information to populate the automated email. I've had several versions of it working but it seems that for whatever reason it acts like one of the variables isn't populated or is no longer accepting a string as a valid data type. I'm rather new to stack exchange so if there is any formatting or anything I could do to clear up what seems to be the issue, I'll be happy to oblige.
echo off #hiding my stuff
$Setup = Test-Path "$env:APPDATA\ExcelLocation.txt"
Function Get-FileName($initialDirectory)
{
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.initialDirectory = $initialDirectory
$OpenFileDialog.filter = "XLSX (*.xlsx)| *.xlsx"
$OpenFileDialog.ShowDialog() | Out-Null
$OpenFileDialog.filename
}
if($Setup -eq $False){
Write-Host "Please participate in 1st time setup!"
$FilePath = Get-FileName "$env:USERPROFILE\Downloads\"
$FilePath | Out-File "$env:APPDATA\ExcelLocation.txt"
$Setup -eq $True
}
$FilePath = Get-Content -Path "$env:APPDATA\ExcelLocation.txt"
Write-Host $FilePath
$DealerCodeLookup = Read-Host -Prompt 'Please put in the Dealer code.'
#Specify the path of the excel file
#$FilePath = "C:\Users\LAB\Downloads\2017 02 Custom Cellular Hierarchy.xlsx"
#Specify the Sheet name
$SheetName = "Sheet1"
# Create an Object Excel.Application using Com interface
$objExcel = New-Object -ComObject Excel.Application
# Disable the 'visible' property so the document won't open in excel
$objExcel.Visible = $false
# Open the Excel file and save it in $WorkBook
$Workbook = $objExcel.Workbooks.Open($FilePath, 2, $True)
# Load the WorkSheet 'BuildSpecs'
$WorkSheet = $WorkBook.sheets.item($SheetName)
#$WorkBook.sheet | Select-Object -Property Name
$Row = 1
$Column = 5
$Found = $False
while (($WorkSheet.Cells.Item($Row, $Column).Value() -ne $Null) -and ($Found -eq $False)) {
#^-- looping though the excel list, updating the row. Stop if Cell is Empty or Value is Found
If (($WorkSheet.Cells.Item($Row, $Column).Value()).ToUpper() -eq $DealerCodeLookup.ToUpper()) {
#^-- Cell value equals $Arg
$locale = $WorkSheet.Cells.Item($Row, $Column+1).Value()
$State =$WorkSheet.Cells.Item($Row, $Column+10).Value()
$Adrs = $WorkSheet.Cells.Item($Row, $Column+7).Value(),$WorkSheet.Cells.Item($Row, $Column+9).Value(),
$WorkSheet.Cells.Item($Row, $Column+10).Value(),$WorkSheet.Cells.Item($Row, $Column+11).Value()
$Found = $True
}
$Row += 1 #Continue to the next row
}
Write-Host $State
$LastRow = $WorkSheet.UsedRange.rows.count + 1
if($Row = $LastRow -and $Found -eq $False){
Write-Host "What you put in is not a valid dealer code!"
$objExcel.quit()
exit
}
$objExcel.quit()
#$DealerCode = Read-Host -Prompt 'Please put in the Dealer code.' #stores the dealer code
$DealerName = 'CUSTOM CELLULAR' #Default dealer name (we are custom cellular)
#$Locale = Read-Host -Prompt 'Please put in the Location name.' #This stores the human location name
#$Address = Read-Host -Prompt 'Please put in the Location Address.' #This stores their address and the thing we use to determine the email address that is sent.
$SoftTokenAmount = Read-Host -Prompt 'Please put in the amount of tokens needed.' #This stores the amount of tokens needed
$Reason = Read-Host -Prompt 'Why do you have to order these tokens??' #This stores the reason for our request
#$SoutheastArea = '* MO *','* KS *','* IL *','* WI *','* MN *','* IA *','* IN *','* NE *' <--possible more efficient usage of the determining loop
#Below is the if statement that determes the Region(SoutheastArea,CenteralArea,WesternArea)
#This specific loop is for the SoutheastArea
if($State -like '*MO*' -or ($State -like '*KS*') -or ($State -like '*IL*') - or ($State -like '*WI*') -or ($State -like '*MN*') -or ($State -like '*IA*')-or ($State -like '*IN*') -or ($State -like '*NE*'))
{
$To = "shalasere1#gmail.com"
}
#This loop is for the CentralArea
Elseif($State -like '*TN*' -or ($State -like '*GA*'))
{
$To = "shalasere2#gmail.com"
}
#This loop is for the WesternArea
Elseif($State -like '*CO*' -or ($State -like '*UT*'))
{
$To = "shalasere3#gmail.com"
}
$From = "tokenrequest#ccinational.com" #Default from email, mine.
#$Cc = "YourBoss#YourDomain.com" #Optional CC'd users to said email (possibly yours.)
$Subject = "Token Request" #The subject of the email
#Below is the default contents of the email including the variables entered above.
$Body = "
New/Replacement Token Request:
Dealer Name: $DealerName
Dealer Code: $DealerCodeLookup
Location: $locale
(office name)
Address: $Adrs
Dealer Email:
Amount of Soft Tokens Needed: $SoftTokenAmount
Reason for Request: $Reason"
#This final chuck is the actual sending an email smtp information for gmail
$SMTPServer = "smtp.office.com"
$SMTPPort = "587"
$secpasswd = ConvertTo-SecureString "publicpass" -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential ("TokenRequest#whereiwork.com", $secpasswd)
Send-MailMessage -From $From -to $To -Subject $Subject `
-Body $Body -SmtpServer $SMTPServer -dno onSuccess, onFailure -port $SMTPPort -UseSsl `
-Credential $mycreds
#= New-Object System.Management.Automation.PSCredential ("TokenRequest#whereiwork.com", $secpasswd)
#(new-object System.Net.NetworkCredential("scott","","ccin****.com"))
#(Get-Credential) #<- this line prompts for the outlook login of the default email (mine.) User is jacob#r**** and password is 8888!
Send-MailMessage : A positional parameter cannot be found that accepts argument '='.
At G:\Token Request v2.0.ps1:144 char:1
+ Send-MailMessage -From $From -to $To -Subject $Subject `
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Send-MailMessage], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.SendMailMessage
Seems that it was required to have a single ' around the from subject to be passed correctly.