New-LocalUser/LocalGroup Path? - powershell

My boss gave me a task to do in PowerShell, he wanted me to write a script.
The script should make a folder and ask for foldername then make 2 groups with read write, then make 2 users, one in each group and ask what user should be in what group. And after that, make rights for the groups to the folders.
I already have the first part in place, make a folder and make it ask for what name:
$foldername1 = read-host -Prompt 'input folder name'
new-item "c:\temp\$foldername1" -type Directory
The problem is when I'm making groups and users. There is no path?
The syntax reads:
New-LocalUser [-Name] <String> [-AccountExpires <DateTime>] [-AccountNeverExpires] [-Confirm] [-Description <String>] [-Disabl
ed] [-FullName <String>] -NoPassword [-UserMayNotChangePassword] [-WhatIf] [<CommonParameters>]
And the same for new-localgroup
How do I choose the path for the user/group I am making?
I'm new to Powershell and new in my internship.

There is no such thing as a path for a local user.
You will see local user using either PowerShell or the GUI: Start => Computer Management => System Tools => Local Users and Groups

This sample might be aligned with what you're looking for.
$foldername1 = read-host -Prompt 'input folder name'
new-item "c:\temp\$foldername1" -type Directory
$group1 = read-host -Prompt 'input first group name'
$group2 = read-host -Prompt 'input second group name'
New-LocalGroup -Name $group1
New-LocalGroup -Name $group2
$user1 = read-host -Prompt 'input first user name'
$user2 = read-host -Prompt 'input second user name'
New-LocalUser -Name $user1
New-LocalUser -Name $user2
$addGroup1 = read-host "Which user in" $group1
if ($addGroup1 -match $user1)
{
Add-LocalGroupMember -Group $group1 -Member $user1
}
if ($addGroup1 -match $user2)
{
Add-LocalGroupMember -Group $group1 -Member $user2
}
$addGroup2 = read-host "which user in" $group2
if ($addGroup2 -match $user1)
{
Add-LocalGroupMember -Group $group2 -Member $user1
}
if ($addGroup2 -match $user2)
{
Add-LocalGroupMember -Group $group2 -Member $user2
}
write-host "Current members in" $group1 $group2
Get-LocalGroupMember -Group $group1
Get-LocalGroupMember -Group $group2
$rule1 = New-Object System.Security.AccessControl.FileSystemAccessRule
("$group1","ReadAndExecute","Allow")
$rule2 = New-Object System.Security.AccessControl.FileSystemAccessRule
("$group2","ReadAndExecute","Allow")
$acl = get-acl "c:\temp\$foldername1"
$acl.SetAccessRule($rule1)
$acl.SetAccessRule($rule2)
$acl | select -ExpandProperty access

Related

Power Shell issue with create user

what is here wrong with create a local user?
$user New-LocalUser -Name "test" -NoPassword -AccountNeverExpires -UserMayNotChangePassword -FullName "Test Admin" -Description "Test User Admin " | Set-LocalUser -PasswordNeverExpires $true
Because you pipe the returned object of New-LocalUser directly through to Set-LocalUser, the capturing variable $user will be $null.
As you can see in the docs, the Set-LocalUser cmdlet returns no output
The fix is easy: seperate these two commands in two separate lines.
Also, I would recommend using Splatting on cmdlets that take a lot of parameters to help keep the code readable as opposed to using extremely long code lines.
# create a Hashtable with all parameters and their values
# for use with the New-LocalUser cmdlet
$userParams = #{
Name = "test"
FullName = "Test Admin"
Description = "Test User Admin"
AccountNeverExpires = $true
NoPassword = $true
UserMayNotChangePassword = $true
}
# create the user and afterwards set another property to the user object
$user = New-LocalUser #userParams
$user | Set-LocalUser -PasswordNeverExpires $true
Add-LocalGroupMember -Group "Administrators" -Member $user
Add-LocalGroupMember -Group "Remote Desktop Users" -Member $user
Setting -PasswordNeverExpires $true shouldn't be necessary anyway, because you created the user with option -NoPassWord AND UserMayNotChangePassword
It is not working because of set-Localuser is added in user creation itself.
$user = New-LocalUser -Name "test" -NoPassword -AccountNeverExpires -UserMayNotChangePassword -FullName "Test Admin" -Description "Test User Admin "
$user | Set-LocalUser -PasswordNeverExpires $true
Add-LocalGroupMember -Group "Administrators" -Member $user
Add-LocalGroupMember -Group "Remote Desktop Users" -Member $user

Create a user on premise based on firstname and lastname

I am in a hybrid environment and I would like to create a user from exchange using a script.
Goals:
Create an account (Last name + first character of first name). If an account exists, add a number at the end. For example, King, John (Samaccountname should be KingJ1.. if exists, KingJ2...)
The UPN must be the first name.last name... If the last name already exists add a number to the last name. For example, King, John (UPN should be john.king1#contoso, if exists john.king2#contoso.com...)
If anyone can help me it would be really appreciated so that I can save some time. Thanks in advance
Connect-ExchangeOnline
$UserCredential = Get-Credential
$SessionEX2016 = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri .../PowerShell/ -Authentication Kerberos -Credential $UserCredential
Import-PSSession $SessionEX2016 -DisableNameChecking
$FirstName = Read-Host "Please enter the Firstname"
$LastName = Read-Host "Please enter the Lastname"
$NewUserLoginID = Read-Host "Please enter a new Login ID" #if the samaccountname exists add a digit
$Manager = Read-Host "Please enter the Login ID of the manager"
$Name = "$($LastName), $($FirstName)"
$DisplayName = $Name
$UPN = "$($FirstName).$($LastName)#contoso.com" #if the upn exists, add a digit to the last name
$PW = "Welcome$(Get-Random -minimum 0001 -maximum 9999)!"
$OU = "OU=Users,OU=Accounts,DC=com,DC=contoso" # it will creates the user in this OU by default and will move the user to OU where the manager is.
#Check to see if the user already exists in AD
if (Get-ADUser -F {SamAccountName -eq $NewUserLoginID})
{
#If user does exist, add a digit to samccountname and upn."
}
else
{
#Create User On-Premise
New-RemoteMailbox -Name $Name -FirstName $FirstName -LastName $LastName -SamAccountName $NewUserLoginID -OnPremisesOrganizationalUnit $OU -UserPrincipalName $UPN -Password (ConvertTo-SecureString -AsPlainText $PW -Force) -ResetPasswordOnNextLogon:$true -Archive
$ManagerOU = ((Get-ADUser -Identity $Manager).DistinguishedName -split '(?<!\\),', 2)[-1]
# next, get the user object of the user you want to move
$NewUser = Get-ADUser -Identity $NewUserLoginID
# now move NewUser to the OU where Manager is in
$NewUser | Move-ADObject -TargetPath $ManagerOU
}
You can add while loops to check if a name already exists or not and if so, append a sequence counter to it.
I would also use Splatting for the New-RemoteMailbox cmdlet to make the code more readable (no need for those very long lines of code)
Something like this:
Connect-ExchangeOnline
$UserCredential = Get-Credential
$SessionEX2016 = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri .../PowerShell/ -Authentication Kerberos -Credential $UserCredential
Import-PSSession $SessionEX2016 -DisableNameChecking
$OU = "OU=Users,OU=Accounts,DC=com,DC=contoso"
$PW = "Welcome$(Get-Random -minimum 0001 -maximum 9999)!"
$FirstName = Read-Host "Please enter the Firstname for the new user"
$LastName = Read-Host "Please enter the Lastname for the new user"
$AccountName = $LastName + $FirstName[0] # Last name + first character of first name
# test if a user with that accountname already exists and if so, append a sequence number
$count = 1
while (Get-ADUser -Filter "SamAccountName -eq '$AccountName'") {
$AccountName = '{0}{1}{2}' -f $LastName, $FirstName[0], $count++
}
$UPN = "$($FirstName).$($LastName)#contoso.com" #if the upn exists, add a digit to the last name
# test if a user with that UserPrincipalName already exists and if so, append a sequence number
$count = 1
while (Get-ADUser -Filter "UserPrincipalName -eq '$UPN'") {
$UPN = '{0}.{1}{2}#contoso.com' -f $FirstName, $LastName, $count++
}
# create a Hashtable for splatting parameters
$userParams = #{
Name = "$($LastName), $($FirstName)"
DisplayName = "$($LastName), $($FirstName)"
FirstName = $FirstName
LastName = $LastName
SamAccountName = $AccountName
OnPremisesOrganizationalUnit = $OU
UserPrincipalName = $UPN
Password = $PW | ConvertTo-SecureString -AsPlainText -Force
ResetPasswordOnNextLogon = $true
Archive = $true
}
# Create User On-Premise and move to the managers OU if possible
try {
New-RemoteMailbox #userParams -ErrorAction Stop
# now check if we can get a managers OU
$Manager = Read-Host "Please enter the Login ID of the manager"
$adManager = Get-ADUser -Filter "SamAccountName -eq '$Manager'"
if ($adManager) {
$ManagerOU = ($adManager.DistinguishedName -split '(?<!\\),', 2)[-1]
# next, get the user object of the new user and move it to the managers OU
Get-ADUser -Identity $AccountName | Move-ADObject -TargetPath $ManagerOU
}
else {
Write-Error "Could not find a manager with SamAccountName '$Manager'"
}
}
catch {
Write-Error $_.Exception.Message
}

Error mapping home directory with a PowerShell script

I'm using a script to create new users and everything is working fine. However, when I try to log in with a user created with this script, I get the following error:
A Problem has occurred and your network home directory is not available.
This may be because a network file server is offline.
You have been logged on with a temporary home drive (H:) which may be shared
with other users.
The script creates the user and applies the correct permissions as far as I can tell.
Here's the script:
# Import active directory module for running AD cmdlets
Import-Module activedirectory
#Store the data from ADUsers.csv in the $ADUsers variable
$ADUsers = Import-csv .\Create_Staff_Accounts.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
$Username = $User.username
$Password = $User.password
$Firstname = $User.firstname
$Lastname = $User.lastname
$OU = $User.ou #This field refers to the OU the user account is to be created in
$group = $User.group
$title = $User.title
$start = $User.start
$Homedrive = "H:"
$UserRoot = "\\servername\st$\"
$HomeDirectory = $UserRoot + $Username
#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 exists in Active Directory."
}
else
{
#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 `
-SamAccountName $Username `
-Name "$Firstname $Lastname" `
-UserPrincipalName "$($username)#domain.local" `
-GivenName $Firstname `
-Surname $Lastname `
-Enabled $True `
-DisplayName "$Firstname $Lastname" `
-Path $OU `
-AccountPassword (convertto-securestring $Password -AsPlainText -Force) `
-Homedrive $Homedrive `
-HomeDirectory $HomeDirectory `
-ScriptPath "logonscript.bat" `
-Description "Staff Account: $($title) from: $($start)"
#-ChangePasswordAtLogon $True `
#Now create the home folder and set modify permissions
Add-ADGroupMember -Identity $group -Members $Username
Add-ADGroupMember -Identity groupname -Members $Username
Add-ADGroupMember -Identity groupname -Members $Username
New-Item -ItemType Directory -Path "\\servername\st$\$($User.username)"
$path = Get-Item -Path "\\servername\st$\$($User.username)"
$acl = (Get-Item $path).GetAccessControl('Access')
$AR = New-Object System.Security.AccessControl.FileSystemAccessRule($Username, 'Modify', 'ContainerInherit,ObjectInherit', 'None', 'Allow')
$acl.SetAccessRule($AR)
Set-Acl -Path $Path -AclObject $acl
}
}
Thank you for your help and support.

Ask user to choose option from stored list (AD OU Path)

I modified a PowerShell script to create AD and Office 365 accounts automatically, it works fine but helpdesk need to manually type out the OU path.
Is there a way to pre-define OU path & assign number to it so if the helpdesk press 1 it chooses the OU path assigned to number 1 and so on?
Name DistinguishedName
---- -----------------
Departments OU=Departments,OU=Users,OU=Test Enviorment,OU=New Zealand,OU=BNZ,DC=BNZTEST,DC=COM
Operational OU=Operational,OU=Departments,OU=Users,OU=Test Enviorment,OU=New Zealand,OU=BNZ,DC=BNZTEST,DC=COM
Normal OU=Normal,OU=Operational,OU=Departments,OU=Users,OU=Test Enviorment,OU=New Zealand,OU=BNZ,DC=BNZTE..
Sales OU=Sales,OU=Departments,OU=Users,OU=Test Enviorment,OU=New Zealand,OU=BNZ,DC=BNZTEST,DC=COM
Finance OU=Finance,OU=Departments,OU=Users,OU=Test Enviorment,OU=New Zealand,OU=BNZ,DC=BNZTEST,DC=COM
IT OU=IT,OU=Departments,OU=Users,OU=Test Enviorment,OU=New Zealand,OU=BNZ,DC=BNZTEST,DC=COM
Application OU=Application,OU=IT,OU=Departments,OU=Users,OU=Test Enviorment,OU=New Zealand,OU=BNZ,DC=BNZTEST,D..
Infrastructure OU=Infrastructure,OU=IT,OU=Departments,OU=Users,OU=Test Enviorment,OU=New Zealand,OU=BNZ,DC=BNZTES..
Marketing OU=Marketing,OU=Departments,OU=Users,OU=Test Enviorment,OU=New Zealand,OU=BNZ,DC=BNZTEST,DC=COM
NewBusiness OU=NewBusiness,OU=Departments,OU=Users,OU=Test Enviorment,OU=New Zealand,OU=BNZ,DC=BNZTEST,DC=COM
ExisitingBusiness OU=ExisitingBusiness,OU=Departments,OU=Users,OU=Test Enviorment,OU=New Zealand,OU=BNZ,DC=BNZTEST,D..
Underwritter OU=Underwritter,OU=Departments,OU=Users,OU=Test Enviorment,OU=New Zealand,OU=BNZ,DC=BNZTEST,DC=COM
#Import needed module.
Import-Module ActiveDirectory
#Prompt for needed information to use as variables below
$fullname = Read-Host "Enter Full Name"
$first = Read-Host "First name"
$last = Read-Host "Last name"
$user = Read-Host "Username"
$title = Read-Host "Title"
Get-ADOrganizationalUnit -Filter * -Properties * -SearchBase "OU=Departments,OU=Users,OU=Test Enviorment,OU=New Zealand,OU=BNZ,DC=BNZTEST,DC=COM" |
Select-Object -Property Name
$department = Read-Host "Enter department from above list"
$manager = Read-Host "Manager userame"
$srcuser = Read-Host "Username to copy"
Get-ADOrganizationalUnit -Filter * -Properties * -SearchBase "OU=Departments,OU=Users,OU=Test Enviorment,OU=New Zealand,OU=BNZ,DC=BNZTEST,DC=COM" |
Select-Object -Property Name, DistinguishedName |
Format-Table -Auto
$OU = Read-Host "Select OU from above list"
#Create a new user with the provided information and some static information
New-ADUser -Name "$fullname" -GivenName "$first" -Surname "$last" -DisplayName "$first $last" -Description "$title" -EmailAddress "$first.$last#bnztest.com" -SamAccountName "$user" -UserPrincipalName "$user#bnztest.com" -Manager "$manager" -Title "$title" -AccountPassword (Read-Host -AsSecureString "Please enter the desired password") -Enabled $true -Path $OU
#Add multiple ProxyAddresses if needed
Set-ADUser "$user" -Add #{ProxyAddresses="smtp:$first.$last#bnztest.com"}
#Copy group membership of the source user above
Get-ADUser -Identity "$srcuser" -Properties memberof |
Select-Object -ExpandProperty memberof |
Add-ADGroupMember -Members "$user" -PassThru |
Select-Object -Property SamAccountName >$null
Write-Host 'CHECK AD REPLICATION BEFORE CONTINUING!'
pause
#Sync user to Office 365 using Dir Sync on a remote server
Import-Module ADSync
Start-ADSyncSyncCycle -PolicyType Initial
Start-Sleep -s 100
#License user in Office 365
$AdminName = "admin#testbnz.onmicrosoft.com"
$Pass = Get-Content "C:\Users\Administrator\Desktop\CreateUser\Cred.txt" |
ConvertTo-SecureString
$Cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $AdminName, $Pass
Import-Module MSOnline
Connect-MsolService -Credential $cred
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $cred -Authentication Basic -AllowRedirection
Import-PSSession $Session
Start-Sleep -s 15
Set-MsolUser -UserPrincipalName "$user#bnztest.com" -UsageLocation 'US'
Set-MsolUserLicense -UserPrincipalName "$user#bnztest.com" -AddLicenses "TESTBNZ:O365_BUSINESS_PREMIUM"
Start-Sleep 90
Write-Host 'ENSURE THERE ARE NO ERRORS AND THAT THE MAILBOX HAS BEEN CREATED BEFORE CONTINUING!'
pause
You could add a simple menu like this:
$yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes",
"Exits the loop."
$no = New-Object System.Management.Automation.Host.ChoiceDescription "&No",
"Allows to add another user."
$options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)
do
{
$user = New-Object System.Management.Automation.Host.ChoiceDescription "&User", "User"
$it = New-Object System.Management.Automation.Host.ChoiceDescription "&IT", "IT"
$sales = New-Object System.Management.Automation.Host.ChoiceDescription "&Sales", "Sales"
$OUoptions = [System.Management.Automation.Host.ChoiceDescription[]]($user, $it, $sales)
$OU = $host.ui.PromptForChoice("Which OU", "Which OU", $OUoptions, 0)
switch ($OU)
{
0 {Write-Host "The choise is User."}
1 {Write-Host "IT"}
2 {Write-Host "Sales"}
default {Write-Host "The color could not be determined."}
}
$result = $host.ui.PromptForChoice("Continue?", "Do you want to add another user?", $options, 1)
}
while ($result -eq 1)
You can use Out-GridView -OutputMode Single to present the helpdesk with a GUI to select from an object. eg:
$SearchBase = "OU=Departments,OU=Users,OU=Test Enviorment,OU=New Zealand,OU=BNZ,DC=BNZTEST,DC=COM"
$OUList = Get-ADOrganizationalUnit -SearchBase $SearchBase -Filter * -Properties Name,DistinguishedName | Select-Object -Property Name,DistinguishedName
$OU = $OUList | Out-GridView -Title "Select OU and Click OK" -OutputMode Single
Then you can use the OU with your New-ADUser command:
New-ADUser [...] -OU $OU.DistinguishedName

Trying to add global security groups to a folder

I wrote a script to create a new folder based on some company variables and later on add a group with users to handle the permissions on this folder.
I can not find a decent way to add one, or more, AD groups to a folder in the same script.
Here is my script:
$parentfolder = Read-Host -Prompt "Please enter the name of the parent folder (i.e. FOLDER1234)"
$folder = Read-Host -Prompt "Please enter the name of the new network folder"
New-Item \\DC02\product\$parentfolder\$folder -type directory
Write-Host "Folder has been created!"
Start-Sleep -s 2
$newgroup = Read-Host -Prompt "Please enter the new group name for this folder (1234-1234-12xx format)"
$description = Read-Host -Prompt "Please enter the abbreviation of the product (i.e. PDPROD)"
NEW-ADGroup -Name $newgroup -GroupScope Global -Description $description -Path "OU=Project Groups,DC=ourdomain,DC=nl"
do {
$stringquit = Read-Host -Prompt "Please enter the member username's to add or press Q if you are done."
$userfilter3 = Get-ADUser -Filter {sAMAccountName -eq $stringquit}
if ($userfilter3 -eq $Null,"Q") {
Write-Host = "User does not exist in AD, please try again"
Start-Sleep -s 1
} else {
if ($stringquit -ne "Q") {
Write-Output -InputObject $stringquit | Out-File -Append c:\userlist.csv
} else {
Write-Host "You pressed Q, moving on."
}
}
} until ($stringquit -eq "Q")
$addgroup = "cn=$newgroup,ou=Project Groups,dc=ourdomain,dc=nl"
$list = Get-Content c:\userlist.csv
foreach ($user in $list) {
Add-ADGroupMember -Identity $addgroup -Member $user
}
#set permissions
$acl = Get-Acl \\DC02\product\$parentfolder\$folder
$ar = New-Object System.Security.AccessControl.FileSystemAccessRule("1234-all","Modify"."ContainerInherit,ObjectInherit","None","Allow")
$acl.SetAccessRule($ar)
Set-Acl \\DC02\product\$parentfolder\$folder $acl
Replace SetAccessRule() with AddAccessRule().