Good Afternoon
I currently have 2 scripts that i currently use anytime someone new starts at the company
the script below will create a the new user profile
#Script to create new AD user, new mailbox, home directories and dfs links
#Param(
#[Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$false)]
#[ValidateScript({Get-QADUser -samaccountname $_})]
# [String]$username
#,
#[Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$false)]
# [String]$newserver = 'NTFS002'
#,
#[Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$false)]
# [ValidateSet("Americas","Europe")]
#[String]$region = 'Americas'
#,
#[Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$false)]
# [String]$usershare = 'users$'
#,
#[Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$false)]
# [String]$profileshare = 'profiles$'
#)
#
function New-UserServerFolders {
Param(
[Parameter(Position=0,Mandatory=$false,ValueFromPipelineByPropertyName=$false)]
[String]$server
,
[Parameter(Position=0,Mandatory=$false,ValueFromPipelineByPropertyName=$false)]
[String]$usershare
,
[Parameter(Position=1,Mandatory=$false,ValueFromPipelineByPropertyName=$false)]
[String]$user
)
$templateFolder = "\\$server\$usershare\Template"
Copy-Item -Recurse $templateFolder "\\$server\$usershare\$user"
$acl = Get-Acl $templateFolder
$inherit = [system.security.accesscontrol.InheritanceFlags]"ContainerInherit, ObjectInherit"
$propagation = [system.security.accesscontrol.PropagationFlags]"None"
$permission = "dacto\$user","Modify",$inherit, $propagation, "Allow"
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule $permission
$acl.SetAccessRule($accessRule)
$acl | Set-Acl \\$server\$usershare\$user
icacls.exe "\\$server\$usershare\$user\*" /reset /T
}
function New-UserDFSFolders {
Param(
[Parameter(Position=0,Mandatory=$false,ValueFromPipelineByPropertyName=$false)]
[String]$server
,
[Parameter(Position=0,Mandatory=$false,ValueFromPipelineByPropertyName=$false)]
[String]$usershare
,
[Parameter(Position=0,Mandatory=$false,ValueFromPipelineByPropertyName=$false)]
[String]$profileshare
,
[Parameter(Position=1,Mandatory=$false,ValueFromPipelineByPropertyName=$false)]
[String]$user
)
dfscmd /map "\\dactoco.com\users\$user\Backups" "\\$server\$usershare\$user\backups"
dfscmd /map "\\dactoco.com\users\$user\Desktop" "\\$server\$usershare\$user\data\desktop"
dfscmd /map "\\dactoco.com\users\$user\Documents" "\\$server\$usershare\$user\data\documents"
dfscmd /map "\\dactoco.com\users\$user\Favorites" "\\$server\$usershare\$user\data\favorites"
dfscmd /map "\\dactoco.com\users\$user\Music" "\\$server\$usershare\$user\data\music"
dfscmd /map "\\dactoco.com\users\$user\Pictures" "\\$server\$usershare\$user\data\pictures"
dfscmd /map "\\dactoco.com\users\$user\Profile" "\\$server\$profileshare\$user\profile"
dfscmd /map "\\dactoco.com\users\$user\Profile.v2" "\\$server\$profileshare\$user\profile.v2"
dfscmd /map "\\dactoco.com\users\$user\Videos" "\\$server\$usershare\$user\data\videos"
}
$defaultPassword = ConvertTo-SecureString "Welcome1" -AsPlainText –Force
$displayName = Read-Host "Display Name"
$names = $displayName.split(" ")
if($names.count -eq 2) {
$firstName = Read-Host "First Name [$($names[0])]"
$lastName = Read-Host "Last Name [$($names[1])]"
if($firstName -eq "") {$firstName = $($names[0])}
if($lastName -eq "") {$lastName = $($names[1])}
}
else {
$firstName = Read-Host "First Name"
$lastName = Read-Host "Last Name"
}
#Capitalize first letter of firstName and Lastname, rest is lowercase.
$firstName = $firstName.toLower()
$firstName = ([String]$firstName[0]).toUpper() + $firstName.substring(1)
$lastName = $lastName.toLower()
$lastName = ([String]$lastName[0]).toUpper() + $lastName.substring(1)
$defaultUsername = "$($firstName[0])$($lastName)".tolower()
$userName = Read-Host "Username [$defaultUsername]"
if($userName -eq "") {$userName = $defaultUsername}
$userName = $userName.tolower()
$office = Read-Host "Office Location (NY or LN)"
switch($office) {
"NY" {$office = 'New York - 7 WTC'; $userOU = 'dactoco.com/Global/Americas/Users'; $server = 'NTFS002'; $usershare = 'users$'; $profileshare = 'profiles$'}
"LN" {$office = 'London-Great Winchester'; $userOU = 'dactoco.com/Global/Europe/Users'; $server = 'LWFS004'; $usershare = 'usersv2$';$profileshare = 'profilesv2$' }
default {$office = 'New York - 7 WTC'; $userOU = 'dactoco.com/Global/Americas/Users'; $server = 'NTFS002'; $usershare = 'users$'; $profileshare = 'profiles$'}
}
$phone = Read-Host "Phone number"
""
""
""
"*****************************"
"Display Name: $displayName"
"First Name: $firstName"
"Last Name: $lastName"
"Username: $username"
"Phone Number: $phone"
"Server: $server"
"User Share: $usershare"
"Profile Share: $profileshare"
"User OU: $userOU"
"*****************************"
""
""
""
$confirm = Read-Host "Is this information correct (Y or N)"
if($confirm -eq 'Y') {
$foundError = $false
#Pre-req Check
"Checking Pre-requesities..."
$avail = get-module -ListAvailable|? {$_.name -eq 'ActiveDirectory'}
if($avail) {
"`t Active Directory Module [OK]"
}
else {
$foundError = $true
"`t Active Directory Module [FAILED]"
}
if(test-path "c:\windows\system32\dfscmd.exe") {
"`t dfscmd.exe [OK]"
}
else {
$foundError = $true
"`t dfscmd.exe [FAILED]"
}
if(test-path "\\$server\$usershare") {
"`t \\$server\\$usershare [OK]"
}
else {
$foundError = $true
"`t \\$server\$usershare [FAILED]"
}
if(test-path "\\$server\$profileshare") {
"`t \\$server\$profileshare [OK]"
}
else {
$foundError = $true
"`t \\$server\$usershare [FAILED]"
}
if(test-path "\\$server\$usershare\Template") {
"`t \\$server\$usershare\Template [OK]"
}
else {
$foundError = $true
"`t \\$server\$usershare\Template [FAILED]"
}
if(test-path "\\$server\$usershare\$userName") {
$foundError = $true
"`t \\$server\$usershare\$userName [FAILED]"
}
else {
"`t \\$server\$usershare\$userName [OK]"
}
"Connecting to Lync Server (lyncadmin)..."
$lyncsession = New-PSSession -ConnectionUri 'https://lyncadmin.dactoco.com/OcsPowershell' -Authentication Negotiate -Credential (Get-Credential)
if($lyncsession -eq $null) {
$foundError = $true
"`t Lync Session [FAILED]"
}
else {
"`t Lync Session [OK]"
}
"Connecting to Exchange Server (NTEX007)... "
$exchangesession = New-PSSession –ConfigurationName Microsoft.Exchange –ConnectionUri http://ntex007.dactoco.com/PowerShell/ -Authentication Kerberos
if($exchangesession -eq $null) {
$foundError = $true
"`t Exchange Session [FAILED]"
}
else {
"`t Exchange Session [OK]"
}
##
if(-not $foundError) {
#Import Exchange / Lync Management
Import-PSSession $exchangesession
Import-PSSession $lyncsession
#Import AD Commands
"Importing Active Directory Module..."
Import-Module ActiveDirectory
New-Mailbox -Name "$displayName" -Password $defaultPassword -UserPrincipalName "$username@dactoco.com" -DisplayName "$displayName" -FirstName "$firstName" -LastName "$lastName" -Office "$office" -OrganizationalUnit "$userOU" -Phone "$phone" -PrimarySmtpAddress "$firstName.$lastName@dactoco.com" -SamAccountName "$username" -Alias "$username" -ResetPasswordOnNextLogon $false -Room:$false -Database "DB01"
"Sleeping for 30 seconds..."
Sleep -Seconds 30
if($(Get-Aduser $username) -eq $null) {
"User/Mailbox not created"
"Exiting now"
}
else {
$emailaddresses = (Get-Mailbox $username).emailaddresses
$emailaddresses.add("smtp:$username@dactoco.com")
Get-Mailbox $username |Set-Mailbox -EmailAddresses $emailaddresses
Get-Mailbox $username |Set-Mailbox -type Regular
New-UserServerFolders -user "$username" -usershare $usershare -server $server
New-UserDFSFolders -user "$username" -usershare $usershare -server $server -profileshare $profileshare
Set-ADUser -Identity "$username" -ProfilePath "\\dactoco.com\users\$username\Profile" -HomeDirectory "\\dactoco.com\users\$username\Documents" -HomeDrive "H:"
Add-ADGroupMember w7login $username
Get-Mailbox $username |Set-CASMailbox -MAPIBlockOutlookRpcHttp:$true
Enable-Csuser -Identity "dacto\$username" -RegistrarPool "ntlyn005.dactoco.com" -SipDomain "dactoco.com" -SipAddressType EmailAddress
}
}
}
else {
"Exiting..."
}
The below script will create a terminal server
param
(
[Parameter(Mandatory=$true)]
[string]$username = "",
[Parameter(Mandatory=$true)]
[string]$TSProfileServer = "",
[Parameter(Mandatory=$true)]
[string]$TSProfileShare = ""
)
Function Check-PSModules
{
$requiredModules = "ActiveDirectory","NTFSSecurity"
Write-Host -ForegroundColor White " - Checking PowerShell Modules..."
ForEach ($requiredModule in $requiredModules) {
Write-Host -ForegroundColor White " - $requiredModule..."
if( (Get-Module -ListAvailable|? {$_.name -eq $requiredModule}) -eq $null ) {
Write-Host -ForegroundColor Yellow " - Unable to find PowerShell module $requiredModule"
Throw " - Missing PowerShell module"
}
else {
Write-Host -BackgroundColor Blue -ForegroundColor Black "Verified."
}
}
}
Function Import-PSModules
{
$requiredModules = "ActiveDirectory","NTFSSecurity"
Write-Host -ForegroundColor White " - Importing PowerShell Modules..."
ForEach ($requiredModule in $requiredModules) {
Write-Host -ForegroundColor White " - $requiredModule..."
if( (Get-Module |? {$_.name -eq $requiredModule}) -eq $null ) {
Write-Host -ForegroundColor White " - Loading $requiredModule..."
Import-Module $requiredModule
}
else {
Write-Host -ForegroundColor White " - $requiredModule already loaded..."
}
}
}
Function Check-PSSnapin
{
$requiredSnapins = "Quest.ActiveRoles.ADManagement"
Write-Host -ForegroundColor White " - Checking PowerShell Snapins..."
ForEach ($requiredSnapin in $requiredSnapins) {
Write-Host -ForegroundColor White " - $requiredSnapin..."
if( (Get-PSSnapin -Registered |? {$_.name -eq $requiredSnapin}) -eq $null ) {
Write-Host -ForegroundColor Yellow " - Unable to find PowerShell snapin $requiredSnapin"
Throw " - Missing PowerShell snapin"
}
else {
Write-Host -BackgroundColor Blue -ForegroundColor Black "Verified."
}
}
}
Function Import-PSSnapins
{
$requiredSnapins = "Quest.ActiveRoles.ADManagement"
Write-Host -ForegroundColor White " - Importing PowerShell Snapins..."
ForEach ($requiredSnapin in $requiredSnapins) {
Write-Host -ForegroundColor White " - $requiredSnapin..."
if( (Get-PSSNapin |? {$_.name -eq $requiredSnapin}) -eq $null ) {
Write-Host -ForegroundColor White " - Loading $requiredSnapin..."
Add-PSSnapin $requiredSnapin
}
else {
Write-Host -ForegroundColor White " - $requiredSnapin already loaded..."
}
}
}
Function Check-DFSUtil
{
Write-Host -ForegroundColor White " - Checking for dfsutil.exe..."
if (-Not(Test-Path 'c:\windows\system32\dfsutil.exe')) {
Write-Host -ForegroundColor Yellow " - Unable to find dfsutil.exe"
Throw " - Missing dfsutil.exe. Install Command Line DFS utilities."
}
else {
Write-Host -BackgroundColor Blue -ForegroundColor Black "Verified."
}
}
Function Check-AdminRights
{
$requiredGroups = 'dacto\Domain Admins'
$groups = [System.Security.Principal.WindowsIdentity]::GetCurrent().Groups
Write-Host -ForegroundColor White " - Checking AD Group Membership..."
ForEach($requiredGroup in $requiredGroups) {
Write-Host -ForegroundColor White " - $requiredGroup..."
if( ($groups|? { $_.Translate([System.Security.Principal.NTAccount]).value -eq $requiredGroup}) -eq $null) {
Write-Host -ForegroundColor Yellow " - Unable to confirm AD group membership"
Throw " - Missing AD group membership"
}
else {
Write-Host -BackgroundColor Blue -ForegroundColor Black "Verified."
}
}
}
Function Check-Parameters
{
Write-Host -ForegroundColor White " - Checking Script Parameters..."
Write-Host -ForegroundColor White " - Checking $username..."
if ((Get-QADUser $username) -eq $null) {
Write-Host -ForegroundColor Yellow " - Unable to find AD User $username"
Throw " - Unable to find AD User $username"
}
else {
Write-Host -BackgroundColor Blue -ForegroundColor Black "Verified."
}
Write-Host -ForegroundColor White " - Checking \\$TSProfileServer\$TSProfileShare..."
if (-Not(Test-Path "\\$TSProfileServer\$TSProfileShare")) {
Write-Host -ForegroundColor Yellow " - Unable to connect to \\$TSProfileServer\$TSProfileShare"
Throw " - Unable to connect to \\$TSProfileServer\$TSProfileShare"
}
else {
Write-Host -BackgroundColor Blue -ForegroundColor Black "Verified."
}
}
Function Check-TSProfile
{
Write-Host -ForegroundColor White " - Checking if TSProfilePath is empty... "
if ((get-qaduser $username).TSProfilePath -ne $null) {
Write-Host -ForegroundColor Yellow " - TSProfilePath not empty, user has terminal server profile set"
Throw " - TSProfilePath not empty, user has terminal server profile set"
}
else {
Write-Host -BackgroundColor Blue -ForegroundColor Black "Verified."
}
}
Function Create-ServerDirectories
{
if(-Not(Test-Path \\$TSProfileServer\$TSProfileShare\$username)) {
mkdir \\$TSProfileServer\$TSProfileShare\$username
}
if(-Not(Test-Path \\$TSProfileServer\$TSProfileShare\$username\TSProfile)) {
mkdir \\$TSProfileServer\$TSProfileShare\$username\TSProfile
}
if(-Not(Test-Path \\$TSProfileServer\$TSProfileShare\$username\TSProfile.v2)) {
mkdir \\$TSProfileServer\$TSProfileShare\$username\TSProfile.v2
}
}
Function Set-DirectorySecurity
{
#Check top level user directory
if((Get-Inheritance \\$TSProfileServer\$TSProfileShare\$username).InheritanceEnabled) {
Write-Host -ForegroundColor White " - Disabling ntfs inheritance on \\$TSProfileServer\$TSProfileShare\$username... "
Disable-Inheritance \\$TSProfileServer\$TSProfileShare\$username
}
if((Get-Owner \\$TSProfileServer\$TSProfileShare\$username).Account.AccountName -ne "BUILTIN\Administrators") {
dir "\\$TSProfileServer\$TSProfileShare\$username" -Recurse| Set-Owner -Account "BUILTIN\Administrators"
}
$aces = Get-Ace \\$TSProfileServer\$TSProfileShare\$username
$bSystem = $False
$bNTFSUserFolder = $False
$bDomainAdmins = $False
$bUsername = $False
$aces|% {
$ace = $_
switch($_.IdentityReference.AccountName)
{
"NT AUTHORITY\SYSTEM" { $bSystem = $True; if($ace.FileSystemRights -ne "FullControl") {
$ace|Remove-Ace
Add-Ace -Account 'NT AUTHORITY\SYSTEM' -AccessRights FullControl -Path "\\$TSProfileServer\$TSProfileShare\$username" -AccessType Allow -InheritanceFlags "ContainerInherit, ObjectInherit"
}}
"dacto\NTFS_UserFolder_Full" { $bNTFSUserFolder = $True; if($ace.FileSystemRights -ne "FullControl") {
$ace|Remove-Ace
Add-Ace -Account 'dacto\NTFS_UserFolder_Full' -AccessRights FullControl -Path "\\$TSProfileServer\$TSProfileShare\$username" -AccessType Allow -InheritanceFlags "ContainerInherit, ObjectInherit"
}}
"dacto\Domain Admins" { $bDomainAdmins = $True; if($ace.FileSystemRights -ne "FullControl") {
$ace|Remove-Ace
Add-Ace -Account 'dacto\Domain Admins' -AccessRights FullControl -Path "\\$TSProfileServer\$TSProfileShare\$username" -AccessType Allow -InheritanceFlags "ContainerInherit, ObjectInherit"
}}
"dacto\$username" { $bUsername = $True; if($ace.FileSystemRights -ne 'Modify, Synchronize') {
$ace|Remove-Ace
Add-Ace -Account "dacto\$username" -AccessRights Modify -Path "\\$TSProfileServer\$TSProfileShare\$username" -AccessType Allow -InheritanceFlags "ContainerInherit, ObjectInherit"
}}
default {Write-Host -ForegroundColor Yellow " - Unknown Ace, Removing...$ace"; $ace|Remove-Ace}
}
}
if(-Not $bSystem) {
Add-Ace -Account 'NT AUTHORITY\SYSTEM' -AccessRights FullControl -Path "\\$TSProfileServer\$TSProfileShare\$username" -AccessType Allow -InheritanceFlags "ContainerInherit, ObjectInherit"
}
if(-Not $bNTFSUserFolder) {
Add-Ace -Account 'dacto\NTFS_UserFolder_Full' -AccessRights FullControl -Path "\\$TSProfileServer\$TSProfileShare\$username" -AccessType Allow -InheritanceFlags "ContainerInherit, ObjectInherit"
}
if(-Not $bDomainAdmins) {
Add-Ace -Account 'dacto\Domain Admins' -AccessRights FullControl -Path "\\$TSProfileServer\$TSProfileShare\$username" -AccessType Allow -InheritanceFlags "ContainerInherit, ObjectInherit"
}
if(-Not $bUsername) {
Add-Ace -Account "dacto\$username" -AccessRights Modify -Path "\\$TSProfileServer\$TSProfileShare\$username" -AccessType Allow -InheritanceFlags "ContainerInherit, ObjectInherit"
}
if(-Not((Get-Inheritance \\$TSProfileServer\$TSProfileShare\$username\TSProfile).InheritanceEnabled)) {
Write-Host -ForegroundColor White " - Enabling ntfs inheritance on \\$TSProfileServer\$TSProfileShare\$username\TSProfile... "
Enable-Inheritance \\$TSProfileServer\$TSProfileShare\$TSProfile
}
#Remove any explicit aces on tsprofile directories
dir "\\$TSProfileServer\$TSProfileShare\$username\TSProfile" -Recurse|Get-Ace –ExcludeInherited|% {Remove-Ace}
if((Get-Owner \\$TSProfileServer\$TSProfileShare\$username\TSProfile).Account.AccountName -ne "BUILTIN\Administrators") {
dir "\\$TSProfileServer\$TSProfileShare\$username\TSProfile" -Recurse| Set-Owner -Account "builtin\administrators"
}
if(-Not((Get-Inheritance "\\$TSProfileServer\$TSProfileShare\$username\TSProfile.v2").InheritanceEnabled)) {
Write-Host -ForegroundColor White " - Enabling ntfs inheritance on \\$TSProfileServer\$TSProfileShare\$username\TSProfile.v2... "
Enable-Inheritance "\\$TSProfileServer\$TSProfileShare\$TSProfile.v2"
}
#Remove any explicit aces on tsprofile directories
dir "\\$TSProfileServer\$TSProfileShare\$username\TSProfile.v2" -Recurse|Get-Ace –ExcludeInherited|% {Remove-Ace}
if((Get-Owner "\\$TSProfileServer\$TSProfileShare\$username\TSProfile.v2").Account.AccountName -ne "BUILTIN\Administrators") {
dir "\\$TSProfileServer\$TSProfileShare\$username\TSProfile.v2" -Recurse| Set-Owner -Account "builtin\administrators"
}
}
Function Create-DFSDirectories
{
$dfspath = "\\dactoco.com\users"
if(Test-Path $dfspath\$username\tsprofile) {
Write-Host -ForegroundColor White " - DFS TSProfile directory exists... "
$output = dfsutil link $dfspath\$username\tsprofile
#$output -match "Target="".*"""
$dfstarget=([regex]"Target=""(.*)"" State").matches($output)|% {$_.Groups[1].Value}
Write-Host -ForegroundColor White " - Old DFS path is $dfstarget"
Write-Host -ForegroundColor White " - Removing old target..."
dfsutil target remove "$dfspath\$username\tsprofile" "$dfstarget"
}
if(Test-Path "$dfspath\$username\tsprofile.v2") {
Write-Host -ForegroundColor White " - DFS TSProfile.v2 directory exists... "
$output = dfsutil link $dfspath\$username\tsprofile.v2
#$output -match "Target="".*"""
$dfstarget=([regex]"Target=""(.*)"" State").matches($output)|% {$_.Groups[1].Value}
Write-Host -ForegroundColor White " - Old DFS path is $dfstarget"
Write-Host -ForegroundColor White " - Removing old target..."
dfsutil target remove "$dfspath\$username\tsprofile.v2" "$dfstarget"
}
Write-Host -ForegroundColor White " - Creating new dfs target (TSProfile)..."
dfsutil link add "$dfspath\$username\TSProfile" "\\$TSProfileServer\$TSProfileShare\$username\TSProfile"
Write-Host -ForegroundColor White " - Creating new dfs target (TSProfile.v2)..."
dfsutil link add "$dfspath\$username\TSProfile.v2" "\\$TSProfileServer\$TSProfileShare\$username\TSProfile.v2"
}
Function Create-TSADAttributes
{
Write-Host -ForegroundColor White " - Modifying user AD attributes..."
Get-QADUser $username|Set-QADUser -TSProfilePath "\\dactoco.com\users\$username\tsprofile" -TsHomeDirectory "\\dactoco.com\users\$username\documents" -TsHomeDrive "H:"
}
# ===================================================================================
# Func: Pause
# Desc: Wait for user to press a key - normally used after an error has occured or input is required
# ===================================================================================
Function Pause($action)
{
#From http://www.microsoft.com/technet/scriptcenter/resources/pstips/jan08/pstip0118.mspx
Write-Host "Press any key to $action..."
$null = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
}
Try {
Check-PSModules
Check-PSSnapin
Check-DFSUtil
Check-AdminRights
Import-PSModules
Import-PSSnapins
#Module is needed to check parameters
Check-Parameters
#Check-TSProfile
Create-ServerDirectories
Set-DirectorySecurity
Create-DFSDirectories
Create-TSADAttributes
Write-Host -ForegroundColor White " - Script Complete"
}
Catch {
Write-Host -ForegroundColor Yellow " - Script aborted!"
if ($_.FullyQualifiedErrorId -ne $null -and $_.FullyQualifiedErrorId.StartsWith(" - ")) {
# Error messages starting with " - " are thrown directly from this script
Write-Host -ForegroundColor Red $_.FullyQualifiedErrorId
Pause "exit"
}
else {
#Other error messages are exceptions. Can't find a way to make this Red
$_ | Format-List -Force
}
}
I will like to be able to combine both scripts can someone please help thank you