Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- param (
- [Parameter(Mandatory=$false)]
- $logPath = "C:\Code\CreateUser.txt",
- [Parameter(Mandatory=$false)]
- $csvPath = "C:\Code\ExampleUsers.csv",
- [Parameter(Mandatory=$false)]
- $homeRoot = "\\$env:computerName\home",
- [Parameter(Mandatory=$false)]
- $usvRoot = "\\$env:computerName\usv",
- [Parameter(Mandatory=$false)]
- $profileRoot = "\\$env:computerName\profile"
- )
- #region FunctionDeclaration
- Function Write-Log
- {
- [CmdletBinding()]
- Param(
- [Parameter(Mandatory=$True)]
- [String]$LogFile,
- [Parameter(Mandatory=$False)]
- [switch]$HiddenLogFile,
- [Parameter(Mandatory=$False)]
- [switch]$HiddenLogPath,
- [Parameter(Mandatory=$False)]
- [switch]$ClearLog,
- [Parameter(Mandatory=$False)]
- [ValidateRange(0,2)]
- [Int]$CritLevel,
- [Parameter(Mandatory=$False)]
- [switch]$Start,
- [Parameter(Mandatory=$False)]
- [switch]$Stop,
- [Parameter(Mandatory=$False)]
- [switch]$NewLine,
- [Parameter(Mandatory=$False)]
- [String]$LogMessage
- )
- $Date = Get-Date -Format yyyy-MM-dd
- $Time = Get-Date -Format HH:mm
- $LogPath = Split-Path -Path $LogFile
- #Ordner ueberpruefen und ggf. anlegen
- if (!(Test-Path $LogPath))
- {
- if ($HiddenLogPath -eq $True)
- {
- New-Item $LogPath -type directory | %{$_.Attributes = "hidden"}
- }
- else
- {
- New-Item $LogPath -type directory | Out-Null
- }
- }
- #Logfile ueberpruefen und ggf. anlegen
- if (!(Test-Path $LogFile))
- {
- if ($HiddenLogFile -eq $True)
- {
- New-Item -Path $LogPath -Name (Split-Path -Path $LogFile -Leaf) -ItemType File | %{$_.Attributes = "hidden"}
- }
- else
- {
- New-Item -Path $LogPath -Name (Split-Path -Path $LogFile -Leaf) -ItemType File | Out-Null
- }
- }
- #Start Log
- If ($Start -eq $True)
- {
- If ($ClearLog -eq $True)
- {
- Clear-Content -Path $LogFile
- }
- Add-Content -Path $LogFile -Value "==================================================================================================="
- Add-Content -Path $LogFile -Value "Started processing at [$([DateTime]::Now)]"
- Add-Content -Path $LogFile -Value "==================================================================================================="
- Add-Content -Path $LogFile -Value ""
- }
- # Set critlevel prefix
- switch ($CritLevel)
- {
- 0 {$Prefix = "[$([DateTime]::Now)] Info: "}
- 1 {$Prefix = "[$([DateTime]::Now)] Warning: "}
- 2 {$Prefix = "[$([DateTime]::Now)] Error: "}
- default {$Prefix = "[$([DateTime]::Now)] Info: "}
- }
- #LogMessage
- If ($LogMessage -ne "")
- {
- If ($env:USERNAME -eq "rollem") {Write-Host ($Prefix + $LogMessage)}
- Add-Content -Path $LogFile -Value ($Prefix + $LogMessage)
- }
- #NewLine
- If ($NewLine -eq $True)
- {
- Add-Content -Path $LogFile -Value ""
- }
- #Stop Log
- If ($Stop -eq $True)
- {
- Add-Content -Path $LogFile -Value ""
- Add-Content -Path $LogFile -Value "==================================================================================================="
- Add-Content -Path $LogFile -Value "Finished processing at [$([DateTime]::Now)]"
- Add-Content -Path $LogFile -Value "==================================================================================================="
- Add-Content -Path $LogFile -Value ""
- }
- }
- function Add-NewACE
- {
- # Fügt einem Objekt eine gewünschte ACE hinzu
- param (
- [System.IO.DirectoryInfo]$DirectoryItem,
- [String]$User,
- [System.Security.AccessControl.FileSystemRights]$AccessRule
- )
- $aclObj = Get-Acl $DirectoryItem
- $userpermissions = New-Object System.Security.AccessControl.FileSystemAccessRule($User,$AccessRule, “ContainerInherit, ObjectInherit”, “None”, “Allow”)
- $aclObj.AddAccessRule($userpermissions) | Out-Null
- Set-Acl $DirectoryItem $aclObj
- }
- function Create-BFWUser {
- param (
- [Parameter(Mandatory)]
- [String]$GivenName,
- [Parameter(Mandatory)]
- [String]$SurName,
- [Parameter(Mandatory)]
- [ValidateScript({Get-ADOrganizationalUnit $_})]
- [String]$OrganizationalUnit,
- [Parameter(Mandatory)]
- [String]$Department,
- [Parameter(Mandatory)]
- [String]$UserName
- )
- try
- {
- New-ADUser -Name "$surName, $givenName" -DisplayName "$surName, $givenName" -SamAccountName $userName -Department $department `
- -AccountPassword $password -Path $organizationalUnit -Surname $surName -GivenName $givenName -Enabled $true -ChangePasswordAtLogon $true `
- -Type InetOrgPerson -UserPrincipalName "$UserName@$env:USERDNSDOMAIN"
- }
- catch [Microsoft.ActiveDirectory.Management.ADInvalidOperationException]
- {
- throw "User already exists"
- }
- }
- function Add-BFWUserFolder {
- [CmdletBinding(DefaultParameterSetName="Default")]
- param (
- [Parameter(Mandatory)]
- [String]$RootFolder,
- [Parameter(Mandatory)]
- [String]$UserName,
- [Parameter(Mandatory)]
- [ValidateSet("Profile","HomeDrive","USV")]
- [String]$ItemType,
- [Parameter(Mandatory=$false)]
- [Int]$ProfileVersion = "6"
- )
- try {
- if ($ItemType -eq "Profile") {
- $homeFolder = Join-Path -Path $RootFolder -ChildPath "$userName.V$ProfileVersion"
- $homeObj = New-Item $homeFolder -ItemType Directory -ErrorAction Stop
- }
- else {
- $homeFolder = Join-Path -Path $RootFolder -ChildPath $userName
- $homeObj = New-Item $homeFolder -ItemType Directory -ErrorAction Stop
- }
- Add-NewACE -DirectoryItem $homeObj -User $userName -AccessRule FullControl
- $acl = Get-Acl -Path $homeFolder
- $acl.SetOwner($(New-Object System.Security.Principal.NTAccount("Builtin", "Administrators")))
- Set-Acl -Path $homeFolder -AclObject $acl -ErrorAction Stop
- switch ($ItemType)
- {
- 'Profile' {
- $homeFolder = ($homeFolder -split "\.")[0]
- Get-ADUser $UserName | Set-ADUser -ProfilePath $homeFolder -ErrorAction Stop
- }
- 'HomeDrive' {
- Get-ADUser $UserName | Set-ADUser -HomeDirectory $homeFolder -HomeDrive "H" -ErrorAction Stop
- }
- 'USV' {
- }
- Default {}
- }
- }
- catch [System.Management.Automation.ActionPreferenceStopException] {
- throw "Generic Error"
- }
- }
- function Load-DataFromCsv {
- param (
- [Parameter(Mandatory)]
- [ValidateScript({Test-Path $_})]
- [String]$FilePath
- )
- $objArr = Import-Csv $FilePath -Delimiter ";"
- return $objArr
- }
- #endregion
- #region StartLog
- Write-Log -LogFile $logPath -Start
- #endregion
- #region DataLoader
- Write-Log -LogFile $logPath -LogMessage "Loading Data from $csvPath"
- $userArr = Load-DataFromCsv -FilePath $csvPath
- #endregion
- #region ScriptRun
- foreach ($userObj in $userArr) {
- $givenName = $userObj.Vorname
- $surName = $userObj.Nachname
- $organizationalUnit = $userObj.Pfad
- $department = $userObj.Abteilung
- $userName = $userObj.BenutzerName
- $password = ConvertTo-SecureString -AsPlainText -Force $userObj.Passwort
- Write-Log -LogFile $logPath -CritLevel 0 -LogMessage "Creating user $userName"
- try {
- Create-BFWUser -givenName $givenName -surName $surName -organizationalUnit $organizationalUnit -department $department -userName $userName
- }
- catch {
- Write-Log -LogFile $logPath -CritLevel 0 -LogMessage $error[0].FullyQualifiedErrorId
- }
- try {
- Write-Log -LogFile $logPath -CritLevel 0 -LogMessage "Creating home folder under $homeRoot for user $userName"
- Add-BFWUserFolder -RootFolder $homeRoot -UserName $userName -ItemType HomeDrive
- }
- catch {
- Write-Log -LogFile $logPath -CritLevel 2 -LogMessage $error[0].FullyQualifiedErrorId
- }
- try {
- Write-Log -LogFile $logPath -CritLevel 0 -LogMessage "Creating profile folder under $profileRoot for user $userName"
- Add-BFWUserFolder -RootFolder $profileRoot -UserName $userName -ItemType Profile
- }
- catch {
- Write-Log -LogFile $logPath -CritLevel 2 -LogMessage $error[0].FullyQualifiedErrorId
- }
- try {
- Write-Log -LogFile $logPath -CritLevel 0 -LogMessage "Creating USV folder under $usvRoot for user $userName"
- Add-BFWUserFolder -RootFolder $usvRoot -UserName $userName -ItemType USV
- }
- catch {
- Write-Log -LogFile $logPath -CritLevel 2 -LogMessage $error[0].FullyQualifiedErrorId
- }
- Write-Log -LogFile $logPath -CritLevel 0 -LogMessage "Checking for Department Group existence"
- try {
- Get-ADGroup -Identity $department | Out-Null
- Write-Log -LogFile $logPath -CritLevel 0 -LogMessage "Adding user $userName to group $department"
- $groupAction = Add-ADGroupMember -Identity $department -Members $userName -PassThru
- }
- catch [Microsoft.ActiveDirectory.Management.ADIdentityResolutionException]{
- Write-Log -LogFile $logPath -CritLevel 2 -LogMessage "Group $department does not exist"
- }
- }
- #endregion
- #region EndLog
- Write-Log -LogFile $logPath -Stop
- #endregion
Add Comment
Please, Sign In to add comment