Powershell Get-Service report wrong information - windows

I've created a powershell script to list all domain controllers under current trusted forest, and than check each individual server for specific services if it's running or not and send an email with report.
I found 2 issues so far.
Get-Service -name "MyService" -ComputerName $myComputer "will say no service is found with that name, but if I list all the services : Get-Service -ComputerName $myComputer it will say "This operation might require other privileges." This is a problem because I'm reporting that the service doesn't exist but it is actually there.
For some reason if I just run the powershell script from command line manually it lists way more servers and most of the info is correct. But I schedule the powershell script from windows task manager with that same account the information is all wrong and it reports way less servers.
Script:
#$domain = [system.directoryservices.activedirectory.domain]::GetCurrentDomain().Name
#$numerOfDomainControlers= nslookup $domain
Clear-Content .\log.txt
$startTime = Get-Date
$allDCs = ((Get-ADForest).Domains | %{ Get-ADDomainController -Filter * -Server $_ } | Where-Object { $_.hostname -notlike '*root*' }).hostname
foreach( $allDC in $allDCs){
$testConnection = Test-Connection $allDC -Quiet -Count 1 -ErrorAction SilentlyContinue
Write-Host
if($testConnection -like "true") {
$SyncStatus = Get-Service -name "MyServicesName" -ComputerName $allDC -ErrorAction SilentlyContinue
if($SyncStatus.length -eq 0) {
Write-Host "MyServicesName doesn't exists on:"$allDC
$SyncStatus = "MyServicesName doesn't exists on:" + $allDC
$logs = $SyncStatus |Out-File .\log.txt -Append
}
else{
write-host "MyServicesName on "$allDC "is: " $SyncStatus.status
$SyncStatus = "MyServicesName on " + $allDC + "is: " + $SyncStatus.status
$logs = $SyncStatus |Out-File .\log.txt -Append
}
}
else
{
Write-Host "Test Connection to Server failed:"$allDC
$SyncStatus = "Test Connection to Server failed:" + $allDC
$logs = $SyncStatus |Out-File .\log.txt -Append
}
}
$endTime = Get-Date
$totalTime = New-TimeSpan -start $startTime -end $endTime
Write-Host $totalTime
$logs = "Total Time in Seconds:" + $totalTime |Out-File .\log.txt -Append
#send Email
$logs = Get-Content .\log.txt
$serverName = $env:computername
$LogTime = Get-Date -Format "MM/dd/yyyy hh:mm:ss"
$FromAddress = "email.com"
$ToAddress = "email.com"
foreach($log in $logs)
{
$Messagebody = $messagebody + $log + "`r`n" |Out-String
}
[string] $MessageSubject ="Status Report runing on " + $serverName +" " + $endTime
$SendingServer = "server"
Send-MailMessage -to $ToAddress -from $FromAddress -subject $MessageSubject -smtpServer $SendingServer -body $Messagebody -Attachments .\log.txt

Related

How to collect system monitor information remotly using powershell?

I have code to collect system information remotely and create a csv file ,below,
Param(
[Parameter(Mandatory=$true, position=0)][string]$infile,
[Parameter(Mandatory=$true, position=1)][string]$outfile
)
#Column header in input CSV file that contains the host name
$ColumnHeader = "ComputerName"
$HostList = import-csv $infile | select-object $ColumnHeader
$out = #()
foreach($object in $HostList) {
$os = Get-WmiObject -computername $object.("ComputerName") -class win32_operatingsystem
$vol = Get-WmiObject -computername $object.("ComputerName") -class Win32_Volume
$net = Get-WmiObject -computername $object.("ComputerName") -class Win32_NetworkAdapterConfiguration | where-object { $_.IPAddress -ne $null }
$DeviceInfo= #{}
$DeviceInfo.add("Operating System", $os.name.split("|")[0])
$DeviceInfo.add("Version", $os.Version)
$DeviceInfo.add("Architecture", $os.OSArchitecture)
$DeviceInfo.add("Serial Number", $os.SerialNumber)
$DeviceInfo.add("Organization", $os.Organization)
$DeviceInfo.add("Disk Capacity", "$([math]::floor($vol.Capacity/ (1024 * 1024 * 1024 )) )" + " GB" )
$DeviceInfo.add("Free Capacity", "$([math]::floor($vol.FreeSpace/ (1024 * 1024 * 1024 )))" + " GB" )
$DeviceInfo.add("System Name", $vol.SystemName)
$DeviceInfo.add("File System", $vol.FileSystem)
$DeviceInfo.add("IP Address", ($net.IPAddress -join (", ")))
$DeviceInfo.add("Subnet", ($net.IPSubnet -join (", ")))
$DeviceInfo.add("MAC Address", $net.MACAddress )
$out += New-Object PSObject -Property $DeviceInfo | Select-Object `
"System Name", "Organization", "Serial Number","Operating System", `
"Version","Architecture","File System","Disk Capacity", `
"Free Capacity","MAC Address","IP Address","Subnet"
Write-Verbose ($out | Out-String) -Verbose
$out | Export-CSV $outfile -NoTypeInformation
}
and i have a script to get monitor information
function Decode {
If ($args[0] -is [System.Array]) {
[System.Text.Encoding]::ASCII.GetString($args[0])
}
Else {
"Not Found"
}
}
ForEach ($Monitor in Get-WmiObject WmiMonitorID -Namespace root\wmi) {
$Manufacturer = Decode $Monitor.ManufacturerName -notmatch 0
$Name = Decode $Monitor.UserFriendlyName -notmatch 0
$Serial = Decode $Monitor.SerialNumberID -notmatch 0
$ManufactureWeek = (Get-WmiObject WmiMonitorID -Namespace root\wmi).WeekofManufacture
$ManufactureYear = (Get-WmiObject WmiMonitorID -Namespace root\wmi).YearOfManufacture
echo "Manufacturer: $Manufacturer`nName: $Name`nSerial Number: $Serial"
echo "Week of Manufacture: $ManufactureWeek"
echo "Year of Manufacture: $ManufactureYear"
}
how can i combine these codes to get monitor information remotly,
how can i get monitor information remotely???????????
You may also update your monitor script. With more than one monitor, it will not work correctly.
function Decode {
If ($args[0] -is [System.Array]) {
[System.Text.Encoding]::ASCII.GetString($args[0])
}
Else {
"Not Found"
}
}
ForEach ($Monitor in Get-WmiObject WmiMonitorID -Namespace root\wmi) {
$Manufacturer = Decode $Monitor.ManufacturerName -notmatch 0
$Name = Decode $Monitor.UserFriendlyName -notmatch 0
$Serial = Decode $Monitor.SerialNumberID -notmatch 0
$ManufactureWeek = $Monitor.WeekofManufacture
$ManufactureYear = $Monitor.YearOfManufacture
echo "Manufacturer: $Manufacturer`nName: $Name`nSerial Number: $Serial"
echo "Week of Manufacture: $ManufactureWeek"
echo "Year of Manufacture: $ManufactureYear"
}

How can I get results from Get-ADUser Filter in my Powershell script so I can validate if that user exists or not correctly?

FIXED: I did have to change if ($null -eq $FoundUser) and then if essentiall NULL -eq NULL, that user doesn't exist...
SORRY
I would really love some help as I've on/off been struggling with this logic with Get-ADUser for user creation.
I'm using Powershell 7.0 - 7.2.1 (latter currently) and having this problem with VSCode and running it in "console". We have a 2008 R2 forest but 2016 and 2019 DCs.
Essentially "Get-ADUser -Filter" doesn't return any value. I'm trying to use an if statement for if $null -ne $SamAccountName.
Any thoughts?
I thought I found the answer here but no luck for me.
$Users = Import-Csv -delimiter "`t" -Path "C:\Users\michel_m\Documents\Scripts\PowerShell\Staff\StaffData.txt"
#$sam = ""
#Generate data to use in creating user below
foreach ($User in $Users) {
$SAMAccount = $User.Username
$Filter = "sAmAccountname -eq '$SamAccount'
$FoundUser = Get-ADUser -Filter $Filter
Write-Host "HERE IS" $FoundUser
$results = $FoundUser.SamAccountName
#if ($null -ne $FoundUser)
if ($null -ne $results)
{
Write-Host $results "Are the results"
Write-Host $User "is the user"
Write-Host $SAMAccount "Is the SAM user"
Write-Host $FoundUser "Is the found user"
#NewUser_Function
($Dates + " - " + $user.username + " has been created") | out-file -filepath $OutputFile1 -append
#Write-Host "Pause 15 seconds"
Start-Sleep 15
Write-Host $user.username + " Has been created"
$Body = $user.username + " Has been created"
#schtasks.exe /run /s "OHDC01" /tn "GADS Sync - Users"
}
else
{
Write-Host $Filter
Write-Host $results "Are the results"
Write-Host $User "is the user"
Write-Host $SAMAccount "Is the SAM user"
Write-Host $FoundUser "Is the found user"
Write-Host $null is null
write-host $user.username + " already exists"
($Dates + " - " + $user.username + " already exists") | out-file -filepath $OutputFile2 -append
$Body = $user.username + " already exists",
"\\OHDC01\C$\Scripts\StaffCreation\NewStaff\",
"\\OHDC01\C$\Scripts\StaffCreation\NewStaff\"
}
}
Output
HERE IS
sAmAccountname -like 'mangold_m' | Select-object SamAccountName
Are the results
#{FirstName=Michelle; LastName=Mangold; BuildingName=OAK; Position=Aide; Username=mangold_m; Email=mangold_m#Wonderfullife.org} is the user
mangold_m Is the SAM user
Is the found user
is null
mangold_m + already exists
HERE IS
sAmAccountname -like 'metzner_m' | Select-object SamAccountName
Are the results
#{FirstName=Melissa; LastName=Metzner; BuildingName=OHHS; Position=Aide; Username=metzner_m; Email=metzner_m#Wonderfullife.org} is the user
metzner_m Is the SAM user
Is the found user
is null
metzner_m + already exists
Thank you for updating you got your solution.
Here I also have tried from my side you can also use this small PowerShell script for validating the user existance.
$Users = Import-Csv -Path "C:\Users\RahulShaw\test.csv"
Foreach ($User in $Users){
$Username = $User.Username
$FoundUser = Get-ADUser -Filter "sAmAccountName -eq '$Username'"
$results = $FoundUser.SamAccountName
Write-Host $results
if($null -eq $FoundUser){
write-host "Username '$Username' does not yet exist in active directory"
}
else{
write-host "Username '$Username' exist in active directory"
}
}

How to check Time synchronization for domain controllers?

I am trying to write a PowerShell script to alert me if one of the domain controllers goes out of sync via an email, I tried to run the script, but I had a problem with sending the email, here is the code. Could you please help me and tell me what is missing in my code? I did not receive any email, so how can I send the script results to my email?
function Get-Time {
<#
.SYNOPSIS
Gets the time of a windows server
.DESCRIPTION
Uses WMI to get the time of a remote server
.PARAMETER ServerName
The Server to get the date and time from
.EXAMPLE
PS C:\> Get-Time localhost
.EXAMPLE
PS C:\> Get-Time server01.domain.local -Credential (Get-Credential)
#>
[CmdletBinding()]
Param(
[Parameter(Position=0, Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[System.String]
$ServerName,
$Credential
)
try {
if ($Credential) {
$DT = Get-WmiObject -Class Win32_LocalTime -ComputerName $servername -Credential $Credential
} else {
$DT = Get-WmiObject -Class Win32_LocalTime -ComputerName $servername
}
} catch {
throw
}
$w32tm = Invoke-Command -Computer $Servers -ArgumentList $Servers -Scriptblock {
Param ($Servers)
foreach ($Server in $Servers) {
$Check = w32tm /monitor /computers:$Server /nowarn
$ICMP = (($Check | Select-String "ICMP")-Replace "ICMP: " , "").Trim()
$ICMPVal = [int]($ICMP -split "ms")[0]
$Source = w32tm /query /source
$Name = Hostname
switch ($ICMPVal) {
{$ICMPVal -le 0} {$Status = "Optimal time synchronisation"}
#you probably need another value here since you'll get no status if it is between 0 and 2m
{$ICMPVal -lt 100000} {$Status = "0-2 Minute time difference"}
{$ICMPVal -ge 100000} {$Status = "Warning, 2 minutes time difference"}
{$ICMPVal -ge 300000} {$Status = "Critical. Over 5 minutes time difference!"}
}
$String = $Name + " - $Status " + "- $ICMP " + " - Source: $Source"
Write-Output $String
}
}
$Servers = "localhost","DC001"
$Servers | Foreach {
Get-Time $_
$results = foreach ($Server in $Servers) {
Get-Time $Server
}
$Servers = "localhost","DC001"
$From = "abc#company.com"
$To = "abc#company.com"
$Cc = ""
$Subject = "Time Skew Results"
$Body = $Servers | ConvertTo-Html | Out-String
$SMTPServer = "imail.company.com"
Send-MailMessage -From $From -To $To -Subject $Subject -Body $Body -SmtpServer $SMTPServer -BodyAsHTML
}
}
I wrote the code again and it works now, here is the code:
$w32tm = Invoke-Command -Computer $Servers -ArgumentList $Servers -Scriptblock {
Param ($Servers)
Foreach ($Server in $Servers)
{
$Check = w32tm /monitor /computers:$Server /nowarn
$ICMP = (($Check | Select-String "ICMP")-Replace "ICMP: " , "").Trim()
$ICMPVal = [int]($ICMP -split "ms")[0]
$Source = w32tm /query /source
$Name = Hostname
Switch ($ICMPVal)
{
#{$ICMPVal -le 0} {$Status = "Optimal time synchronisation"}
#{$ICMPVal -lt 100000} {$Status = "0-2 Minute time difference"}
{$ICMPVal -ge 100000} {$Status = "Warning, 2 minutes time difference"}
{$ICMPVal -ge 300000} {$Status = "Critical. Over 5 minutes time difference!"}
}
if ($ICMPVal -gt 100000)
{
$String = "The Domain Controller: " + $Name + " has " + " - $Status " + " - $ICMP " + " - Source: $Source"
$From = "abc#company.com"
$To = "abc#company.com"
$Cc = ""
$Subject = "Time Synchronization Alert "
$Body = Write-Output $String
$SMTPServer = "imail.company.com"
Send-MailMessage -From $From -To $To -Subject $Subject -Body $Body -SmtpServer $SMTPServer -BodyAsHTML
}
}
}
$w32tm

'Run a program' option in windows service pannel for failure recovery

I am trying to run a perl script whenever there is a service crash. The perl script intends to restart the service and send a mail to all the developers.
I have used windows recovery options for that, where it has an option to run a program . I have filled the required details in the command line option but the script doesn't seem to get executed. Can you please help me by sharing your knowledge on this?
Recovery tab configuration
I have tried with Restart service option and that is working fine but the run a program isn't executing the script. Am I missing something?
Any comment on this will be helpful.
I recently implemented a recovery option to run a powershell script that attempts to restart the service a defined number of times and sends an email notification at the conclusion, it also attaches a txt file with recent relevant logs.
After several attempts (and despite all the other things I have seen) The configuration of fields on the recovery tab in services is as follows:
Program: Powershell.exe
**Not C:\Windows\System32\WindowsPowerShell\v1.0\Powershell.exe
Command line parameters: -command "& {SomePath\YourScript.ps1 '$args[0]' '$args[1]' '$args[n]'}"
eg: -command "& {C:\PowershellScripts\ServicesRecovery.ps1 'Service Name'}"
**The $args are parameters that will be passed to your script. These are not required.
here is the powershell script:
cd $PSScriptRoot
$n = $args[0]
function CreateLogFile {
$events = Get-EventLog -LogName Application -Source SomeSource -Newest 40
if (!(Test-Path "c:\temp")) {
New-Item -Path "c:\temp" -Type directory}
if (!(Test-Path "c:\temp\ServicesLogs.txt")) {
New-Item -Path "c:\temp" -Type File -Name "ServicesLogs.txt"}
$events | Out-File -width 600 c:\temp\ServicesLogs.txt
}
function SendEmail {
$EmailServer = "SMTP Server"
$ToAddress = "Name#domain.com"
$FromAddress = "Name#domain.com"
CreateLogFile
$Retrycount = $Retrycount + 1
send-mailmessage -SmtpServer $EmailServer -Priority High -To $ToAddress -From $FromAddress -Subject "$n Service failure" `
-Body "The $n service on server $env:COMPUTERNAME has stopped and was unable to be restarted after $Retrycount attempts." -Attachments c:\temp\ServicesLogs.txt
Remove-Item "c:\temp\ServicesLogs.txt"
}
function SendEmailFail {
$EmailServer = "SMTP Server"
$ToAddress = "Name#domain.com"
$FromAddress = "Name#domain.com"
CreateLogFile
$Retrycount = $Retrycount + 1
send-mailmessage -SmtpServer $EmailServer -Priority High -To $ToAddress -From $FromAddress -Subject "$n Service Restarted" `
-Body "The $n service on server $env:COMPUTERNAME stopped and was successfully restarted after $Retrycount attempts. The relevant system logs are attached." -Attachments c:\temp\ServicesLogs.txt
Remove-Item "c:\temp\ServicesLogs.txt"
}
function StartService {
$Stoploop = $false
do {
if ($Retrycount -gt 3){
$Stoploop = $true
SendEmail
Break
}
$i = Get-WmiObject win32_service | ?{$_.Name -imatch $n} | select Name, State, StartMode
if ($i.State -ne "Running" -and $i.StartMode -ne "Disabled") {
sc.exe start $n
Start-Sleep -Seconds 35
$i = Get-WmiObject win32_service | ?{$_.Name -imatch $n} | select State
if ($i.state -eq "Running"){
$Stoploop = $true
SendEmailFail}
else {$Retrycount = $Retrycount + 1}
}
}
While ($Stoploop -eq $false)
}
[int]$Retrycount = "0"
StartService

Powershell Script to Add New Users in AD for HR Department

I'm trying to come up with a powershell script to add new users in AD that our HR department can use instead of sending me emails about that.
My script will ask for which department they wanna add the new user, username and the full name:
# ##########################################
# Determine if we have Administrator rights
Write-Host 'Checking user permissions... '
$windowsID = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$windowsSecurityPrincipal = New-Object System.Security.Principal.WindowsPrincipal($windowsID)
$adminRole = [System.Security.Principal.WindowsBuiltInRole]::Administrator
If (!($windowsSecurityPrincipal.IsInRole($adminRole))) {
Write-Warning 'Current user does not have Administrator rights'
Write-Host 'Attempting to copy files to temporary location and restarting script'
# Get random file name
Do {
$temp = [System.IO.Path]::GetTempPath() + [System.IO.Path]::GetRandomFileName()
} Until (!(Test-Path -LiteralPath "$temp"))
# Create directory
Write-Host 'Creating temp directory... ' -NoNewLine
New-Item -Path "$temp" -ItemType 'Directory' | Out-Null
Write-Host 'done.'
# Copy script to directory
Write-Host 'Copying script to temp directory... ' -NoNewLine
Copy-Item -LiteralPath "$($myInvocation.MyCommand.Path)" "$temp" | Out-Null
Write-Host 'done.'
$newScript = "$($temp)\$($myInvocation.MyCommand.Name)"
# Start new script elevated
Write-Host 'Starting script as administrator... ' -NoNewLine
$adminProcess = New-Object System.Diagnostics.ProcessStartInfo
$adminProcess.Filename = ([System.Diagnostics.Process]::GetCurrentProcess()).Path
$adminProcess.Arguments = " -File `"$newScript`""
$adminProcess.Verb = 'runas'
Try {
[System.Diagnostics.Process]::Start($adminProcess) | Out-Null
}
Catch {
Write-Error 'Could not start process'
Exit 1
}
Write-Host 'done.'
Exit 0
}
#Change the execution policy
Set-ExecutionPolicy bypass
#Import the AD module
Import-Module ActiveDirectory
#Set variables
$title = "Add Users To The Domain"
$message = "For which department do you wanna add this user to?"
$rn = New-Object System.Management.Automation.Host.ChoiceDescription "&RN", `
"RN"
$callcenter = New-Object System.Management.Automation.Host.ChoiceDescription "&Call Center", `
"Call Center"
$management = New-Object System.Management.Automation.Host.ChoiceDescription "&Management", `
"Management"
$billing = New-Object System.Management.Automation.Host.ChoiceDescription "&Billing", `
"Billing"
$options = [System.Management.Automation.Host.ChoiceDescription[]]($rn, $callcenter, $management, $billing)
$result = $host.ui.PromptForChoice($title, $message, $options, 0)
switch ($result)
{
0 {"You selected RN."}
1 {"You selected Call Center."}
2 {"You selected Management."}
3 {"You Selected Billing."}
}
$UName = Read-Host "What is the username you wanna give? Make sure it matches the username in the email."
$FName = Read-Host "What is the Full Name of the user?"
New-ADUser `
-Name $FName `
-Path "CN=Users,OU=$result,DC=Domain,DC=com" `
-SamAccountName $UName `
-DisplayName $FName `
-AccountPassword (ConvertTo-SecureString "password1" -AsPlainText -Force) `
-ChangePasswordAtLogon $true `
-Enabled $true
Add-ADGroupMember "Users" "$UName";
Each time I try I run it I get this error message:
New-ADUser : Directory object not found At
C:\Users\youssef\AppData\Local\Temp\ofit4gnq.1lp\AddUserHR.ps1:84
char:1
+ New-ADUser `
+ ~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (CN=TYoussef Tes...diatrics,DC=Com:String) [New-ADUser], ADIdentityNotFo
undException
+ FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,M
icrosoft.ActiveDirectory.Management.Commands.NewADUser
Add-ADGroupMember : Cannot find an object with identity: 'yousseft'
under: 'DC=TribecaPediatrics,DC=com'. At
C:\Users\youssef\AppData\Local\Temp\ofit4gnq.1lp\AddUserHR.ps1:92
char:1
+ Add-ADGroupMember "Users" "$UName";
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (yousseft:ADPrincipal) [Add-ADGroupMember], ADIdentityNotFoundException
+ FullyQualifiedErrorId : SetADGroupMember.ValidateMembersParameter,Microsoft.ActiveDirectory.Management.Commands.
AddADGroupMember
$result comes back as an integer so the path you're giving to New-ADUser looks like this:
"CN=Users,OU=0,DC=Domain,DC=com"
Which is why you're getting that error message, because more than likely there is no OU with the name "0" or any of the other options "1","2" or "3".
In your switch statement you should declare what each departments OU is called so you can put the new user into that OU.
you were very close, here's how i would modify your switch statement:
# ##########################################
# Determine if we have Administrator rights
Write-Host 'Checking user permissions... '
$windowsID = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$windowsSecurityPrincipal = New-Object System.Security.Principal.WindowsPrincipal($windowsID)
$adminRole = [System.Security.Principal.WindowsBuiltInRole]::Administrator
If (!($windowsSecurityPrincipal.IsInRole($adminRole))) {
Write-Warning 'Current user does not have Administrator rights'
Write-Host 'Attempting to copy files to temporary location and restarting script'
# Get random file name
Do {
$temp = [System.IO.Path]::GetTempPath() + [System.IO.Path]::GetRandomFileName()
} Until (!(Test-Path -LiteralPath "$temp"))
# Create directory
Write-Host 'Creating temp directory... ' -NoNewLine
New-Item -Path "$temp" -ItemType 'Directory' | Out-Null
Write-Host 'done.'
# Copy script to directory
Write-Host 'Copying script to temp directory... ' -NoNewLine
Copy-Item -LiteralPath "$($myInvocation.MyCommand.Path)" "$temp" | Out-Null
Write-Host 'done.'
$newScript = "$($temp)\$($myInvocation.MyCommand.Name)"
# Start new script elevated
Write-Host 'Starting script as administrator... ' -NoNewLine
$adminProcess = New-Object System.Diagnostics.ProcessStartInfo
$adminProcess.Filename = ([System.Diagnostics.Process]::GetCurrentProcess()).Path
$adminProcess.Arguments = " -File `"$newScript`""
$adminProcess.Verb = 'runas'
Try {
[System.Diagnostics.Process]::Start($adminProcess) | Out-Null
}
Catch {
Write-Error 'Could not start process'
Exit 1
}
Write-Host 'done.'
Exit 0
}
#Change the execution policy
Set-ExecutionPolicy bypass
#Import the AD module
Import-Module ActiveDirectory
#Set variables
$title = "Add Users To The Domain"
$message = "For which department do you wanna add this user to?"
$rn = New-Object System.Management.Automation.Host.ChoiceDescription "&RN", `
"RN"
$callcenter = New-Object System.Management.Automation.Host.ChoiceDescription "&Call Center", `
"Call Center"
$management = New-Object System.Management.Automation.Host.ChoiceDescription "&Management", `
"Management"
$billing = New-Object System.Management.Automation.Host.ChoiceDescription "&Billing", `
"Billing"
$options = [System.Management.Automation.Host.ChoiceDescription[]]($rn, $callcenter, $management, $billing)
$result = $host.ui.PromptForChoice($title, $message, $options, 0)
switch ($result)
{
0
{
"You selected RN."
$OU = "RN"
}
1
{
"You selected Call Center."
$OU = "CallCenter"
}
2
{
"You selected Management."
$OU = "Management"
}
3
{
"You Selected Billing."
$OU = "Billing"
}
}
$UName = Read-Host "What is the username you wanna give? Make sure it matches the username in the email."
$FName = Read-Host "What is the Full Name of the user?"
New-ADUser `
-Name $FName `
-Path "CN=Users,OU=$OU,DC=Domain,DC=com" `
-SamAccountName $UName `
-DisplayName $FName `
-AccountPassword (ConvertTo-SecureString "password1" -AsPlainText -Force) `
-ChangePasswordAtLogon $true `
-Enabled $true
Add-ADGroupMember "Users" "$UName";

Resources