Modify a SendGoogleForm script v2 - powershell

I am trying to get my SendGoogleForm script to work. The issue I have at the moment is that the message I am sending with the form is including a powershell script, the problem I have is that the send service is breaking the lines in the code which means I have to manually remove all the extra spaces(see example at bottom).
So I thought that there must be a way to print the powershell code to a file instead and attach it to the email that is sent or fix the spaces issue some other way. It would be good if the answers still are displayed as a regular email like they are today but with the powershell code attached somehow.
/* Send Google Form by Email v2.1 */
/* For customization, contact the developer at amit#labnol.org */
/* Tutorial: http://www.labnol.org/?p=20884 */
function Initialize() {
var triggers = ScriptApp.getProjectTriggers();
for(var i in triggers) {
ScriptApp.deleteTrigger(triggers[i]);
}
ScriptApp.newTrigger("SendGoogleForm")
.forSpreadsheet(SpreadsheetApp.getActiveSpreadsheet())
.onFormSubmit()
.create();
}
function SendGoogleForm(e)
{
try
{
//Här fyller du i mailadresserna för resp avdelning.
var it = "test#test.se";
//Ärende på mailet
var subject = "testt Ny/redigerad anställning";
//Slår ihop alla mailadresser till en.
var email = hr +","+ security +","+ it;
//andra variabler
var bukowskis = "test";
var temporarypass = "Provide a Temporary Password for this user";
var semicolon = ";";
// You may replace this with another email address
//var email = Session.getActiveUser().getEmail();
var s = SpreadsheetApp.getActiveSheet();
var columns = s.getRange(1,1,1,s.getLastColumn()).getValues()[0];
var message = "";
// Only include form fields that are not blank
for ( var keys in columns ) {
var key = columns[keys];
if ( e.namedValues[key] && (e.namedValues[key] != "") ) {
message += key + ' :: '+ e.namedValues[key] + "\n\n";
}
if (key == "Förnamn")
var fornamn = e.namedValues[key];
else if (key == "Efternamn")
var efternamn = e.namedValues[key];
else if (key == "Placering")
var placering = e.namedValues[key];
else if (key == "Titel")
var titel = e.namedValues[key];
else if (key == "Avdelning")
var avdelning = e.namedValues[key];
}
//Lägger till eventuellt namn i ämnesraden.
if(typeof fornamn !== 'undefined'&&typeof efternamn !== 'undefined'){
subject += ", " + fornamn + " " + efternamn ;
message +="New-ADUser -SamAccountName '"+fornamn+"."+efternamn+"' -Name '"+fornamn+" "+efternamn+"' -GivenName '"+fornamn+"' -Surname '"+efternamn+"' -Description '"+test+", "+avdelning+", "+titel+"' -OfficePhone ' ' -EmailAddress '"+fornamn+"."+efternamn+"#test.com' -Path 'OU=Users,OU=test,DC=intern,DC=test,DC=se' -Company 'test' -Department '"+avdelning+"' -Title '"+titel+"' "+semicolon+"$NewPassword = (Read-Host -Prompt '"+temporarypass+"' -AsSecureString) "+semicolon+"Set-ADAccountPassword -Identity '"+fornamn+"."+efternamn+"' -NewPassword $NewPassword -Reset "+semicolon+"Set-ADAccountControl -Identity '"+fornamn+"."+efternamn+"' -Enabled $true";
MailApp.sendEmail(email, subject, message);
}
} catch (e) {
Logger.log(e.toString());
}
}
Example of how the output looks today, not able to just copy to Powershell ISE and run it, sadly.
New-ADUser -SamAccountName 'gadfgdafg.sdfgsdfg' -Name 'gadfgdafg sdfgsdfg'
-GivenName 'gadfgdafg' -Surname 'sdfgsdfg' -Description 'Test, Utlämningen, Alternativ 5' -OfficePhone ' '
-EmailAddress 'gadfgdafg.sdfgsdfg#test.com'
-Path 'OU=Users,OU=test,DC=intern,DC=test,DC=se'
-Company 'test' -Department 'Utlämningen' -Title 'Alternativ 5' ;$NewPassword = (Read-Host -Prompt 'Provide a Temporary Password for this user' -AsSecureString) ;Set-ADAccountPassword -Identity 'gadfgdafg.sdfgsdfg' -NewPassword $NewPassword -Reset ;Set-ADAccountControl -Identity 'gadfgdafg.sdfgsdfg' -Enabled $true
Thanks in advance, I have tried everything I can think of at this point.

When sending e-mails, GMail automatically line-wraps your plain-text messages (at around 78 characters per line). In order to avoid this, you can:
Use another client other than Gmail. Of course, probably not your preferred option, but something to consider.
Get the data through the API. The data you get from it will not be line-wrapped.
Send your message as an HTML message. You can do that with a small modification of your code:
Before
message += key + ' :: '+ e.namedValues[key] + "\n\n";
...
subject += ", " + fornamn + " " + efternamn ;
message +="New-ADUser -SamAccountName '"+fornamn+"."+efternamn+"' -Name '"+fornamn+" "+efternamn+"' -GivenName '"+fornamn+"' -Surname '"+efternamn+"' -Description '"+test+", "+avdelning+", "+titel+"' -OfficePhone ' ' -EmailAddress '"+fornamn+"."+efternamn+"#test.com' -Path 'OU=Users,OU=test,DC=intern,DC=test,DC=se' -Company 'test' -Department '"+avdelning+"' -Title '"+titel+"' "+semicolon+"$NewPassword = (Read-Host -Prompt '"+temporarypass+"' -AsSecureString) "+semicolon+"Set-ADAccountPassword -Identity '"+fornamn+"."+efternamn+"' -NewPassword $NewPassword -Reset "+semicolon+"Set-ADAccountControl -Identity '"+fornamn+"."+efternamn+"' -Enabled $true";
MailApp.sendEmail(email, subject, message);
After
message += key + ' :: '+ e.namedValues[key] + "<br><br>";
...
subject += ", " + fornamn + " " + efternamn ;
message +="New-ADUser -SamAccountName '"+fornamn+"."+efternamn+"' -Name '"+fornamn+" "+efternamn+"' -GivenName '"+fornamn+"' -Surname '"+efternamn+"' -Description '"+test+", "+avdelning+", "+titel+"' -OfficePhone ' ' -EmailAddress '"+fornamn+"."+efternamn+"#test.com' -Path 'OU=Users,OU=test,DC=intern,DC=test,DC=se' -Company 'test' -Department '"+avdelning+"' -Title '"+titel+"' "+semicolon+"$NewPassword = (Read-Host -Prompt '"+temporarypass+"' -AsSecureString) "+semicolon+"Set-ADAccountPassword -Identity '"+fornamn+"."+efternamn+"' -NewPassword $NewPassword -Reset "+semicolon+"Set-ADAccountControl -Identity '"+fornamn+"."+efternamn+"' -Enabled $true";
var htmlBody = "<html><p>" + message + "</p></html>";
MailApp.sendEmail(email, subject, message, {'htmlBody': htmlBody});
The main changes are:
Wrapping your text with HTML code, using a paragraph tag.
Replacing the newlines inside your "message" for <br> tags.

Johan. You're not putting any newline characters into the string, so it's all going to output on a single line. For google-apps-script(js) you can use '/n'. See examples here.
Alternatively, to create the powershell file separately and send it as an attachment, you can add the attachment argument to your MailApp function. You'll have to push the output to a file, which will still require '/n' to break up the lines. You'll also have to store the file somewhere that the form has access to. And you'll need to be sure that the recipient email won't flag the .ps1 fine as potentially malicious. (Which it should be doing. Never run scripts from email attachments!) Attachment example here.
Have fun!

Related

Setting variables based on value taken from CSV within a Foreach loop using an if else statement

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.

Create New User via PowerShell

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

Student Script for creating new users error :System.String' to the type 'System.Management.Automation.SwitchParameter

I'm pulling some user info from a .csv to create new users,
I've splatted the New User Params at the suggestion of someone here
but I'm getting this error
New-ADUser : Cannot convert 'System.String' to the type 'System.Management.Automation.SwitchParameter' required by parameter
'Confirm'.
At C:\Users\Administrator\Documents\GitHub\cyclone-internal-user-sync-1\Bamboo Attributes form a csv.ps1:68 char:28
+ New-ADUser #NewUserParms
+ ~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [New-ADUser], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgument,Microsoft.ActiveDirectory.Management.Commands.NewADUser
I have no idea what this is haha, I've tried adding an erroraction stop to the new-aduser but that didn't have any effect
I have added trims and a section to remove spaces from usernames. to deal with multipart names such as Van der.... etc
#Bamboo Attributes from a .csv
#Enter a path to your import CSV file
$ADUsers = Import-csv 'path'
#Bamboo Attributes from a .csv
#Enter a path to your import CSV file
$ADUsers = Import-csv 'C:\Users\Administrator\Documents\GitHub\cyclone-internal-user-sync-1\documentation\SampleUserAttributes.csv'
#$apiRequest = Get-Content -Raw -Path C:\Users\alexh\Documents\GitHub\cyclone-internal-user-sync-1\cyclone-internal-user-sync-1\fake-api-query.json | ConvertFrom-Json
foreach ($User in $ADUsers) {
$firstName = $user.FirstName.Trim()
$surname = $user.Surname.Trim()
$vaildUsernameFormat = "[^a-zA-Z_.]" # identifies anything that's _not_ a-z or underscore or .
$username = "($firstName'.'$surname)" -replace $vaildUsernameFormat, '' #removes anything that isn't a-z
$DefaultPassword = 'Pa$$w0rd'
$NewUserParms = #{
'samAccountName' = $username;
'Name' = "$firstname $surname";
'DisplayName' = "$firstname $surname";
'UserPrincipalName' = "$username#domain.com";
'GivenName' = $firstname;
'Surname' = $surname;
'EmailAddress' = $User.Email;
'AccountPassword' = (ConvertTo-SecureString $DefaultPassword -AsPlainText -Force);
'Enabled' = $true;
'Path' = "OU=Users,DC=domain,DC=com";
'co' = $User.Country;
'company' = $User.CompanyName;
'countryCode' = $user.countryCode;
'department' = $user.OrgDepartmentName;
'Employeeid' = $user.EmployeeId;
'exstentionAttribute1' = $user.ExstentionNumber;
'ipPhone' = $user.ExstentionNumber;
'L' = $user.location;
'mail' = $user.Email;
'mobile' = $user.Mobile;
'Manager' = $user.Manager;
'physicalDeliveryOffice' = $user.Branch;
'postalCode' = $user.PostalCode;
'postOfficeBox' = $user.PostOfficeBox;
'proxyAddresses' = $user.ProxyEmail;
'scriptPath' = $user.scriptPath;
'st' = $user.StreetName;
'Title' = $user.Title
}
write-host "$username this is username value"
#Check if the user account already exists in AD
if (Get-ADUser -F {
sAMAccountName -eq $username
}) {
#If user does exist, output a warning message
Write-Warning "A user account $username has already exist in Active Directory."
}
else {
#If a user does not exist then create a new user account
New-ADUser #NewUserParms
}
}
I've removed some of the user attributes just to make this a bit smaller.
here is the.csv as well in case I've messed something up there
link to .csv file on git
A little known fact about PowerShell is that you don't need to use the whole parameter name. You can use the partial name and as long as it matches only one parameter name, that's what PowerShell assumes you mean.
The one it's choking on is this:
'co' = $User.Country;
If you look at the documentation for New-ADUser, it does not have a parameter called co. So PowerShell assumes it's a partial match to a known parameter, and the closest match is -Confirm. And the value in $User.Country doesn't make any sense for the -Confirm parameter, so it throws the error.
You will have to use the -OtherAttributes parameter to set all the other attributes that New-ADUser doesn't have a dedicated parameter for:
$NewUserParms = #{
...
'OtherAttributes = # {
'co' = $User.Country;
'exstentionAttribute1' = $user.ExstentionNumber;
...
}
...
}
As commented in this and previous questions, you are using New-ADUser $NewUserParms, where it should be New-ADUser #NewUserParms.
Also, to catch errors (you did add -ErrorAction Stop), you need to put that inside a try{..} catch{..} block.
I would also change the syntax you use for the -Filter parameter. Instead of using a scriptblock syntax {something -eq someotherthing}, you should create a string like "something -eq 'someotherthing'"
Try:
# define some 'constants'
$csvFile = 'X:\Folder\NewUsers.csv' # Enter a path to your import CSV file
$invalidCharacters = '[^a-z_.]' # identifies anything that's _not_ a-z or underscore or .
$DefaultPassword = 'Pa$$w0rd'
$securePassword = ConvertTo-SecureString -String $DefaultPassword -AsPlainText -Force
# read the input csv and loop through
Import-Csv -Path $csvFile | ForEach-Object {
$firstName = $_.FirstName.Trim()
$surname = $_.Surname.Trim()
$username = ('{0}.{1}' -f $firstName, $surname) -replace $invalidCharacters
# test if a user with that name already exists
$user = Get-ADUser -Filter "SamAccountName -eq '$username'" -ErrorAction SilentlyContinue
if ($user) {
Write-Warning "A user account $username already exist in Active Directory."
}
else {
Write-Host "Creating user $username"
$NewUserParms = #{
'SamAccountName' = $username
'Name' = "$firstname $surname"
'DisplayName' = "$firstname $surname"
'UserPrincipalName' = "$username#domain.com"
'GivenName' = $firstname
'Surname' = $surname
'EmailAddress' = $_.Email
'AccountPassword' = $securePassword
'Enabled' = $true
'Path' = "OU=Users,DC=domain,DC=com"
# add other properties to set from the CSV here.
# make sure you get the parameter data types correct and always check here:
# https://learn.microsoft.com/en-us/powershell/module/addsadministration/new-aduser?view=win10-ps#parameters
# switch parameters for the cmdlet can also be entered with a value $false or $true
}
try {
# '-ErrorAction Stop' ensures that also non-terminating errors get handled in the catch block
New-ADUser #NewUserParms -ErrorAction Stop
}
catch {
# something bad happened. Change 'Write-Warning' into 'throw' if you want your script to exit here
# inside a catch block, the '$_' automatic variable represents the actual exception object.
Write-Warning "Could not create account $username. $($_.Exception.Message)"
}
}
}

sudent, invalid name for New-ADUser multi user creation script

I'm pulling some user info from a .csv to create new users,
I've splatted the New User Params at the suggestion of someone here
but I'm getting this error
New-ADUser : The name provided is not a properly formed account name
At C:\Users\Administrator\Documents\GitHub\cyclone-internal-user-sync-1\Bamboo Attributes form a csv.ps1:67 char:17
+ New-ADUser $NewUserParms -ErrorAction Stop
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (CN=System.Colle...=Cyclone,DC=com:String) [New-ADUser], ADException
+ FullyQualifiedErrorId : ActiveDirectoryServer:1315,Microsoft.ActiveDirectory.Management.Commands.NewADUser
the username variable seems to be correct as far as I know, when it outputs during running of the script its what I assume to be correct format of "firstname.lastname"
I have added trims and a section to remove spaces from usernames. to deal with multipart names such as Van der.... etc
#Bamboo Attributes from a .csv
#Enter a path to your import CSV file
$ADUsers = Import-csv 'path'
foreach ($User in $ADUsers) {
$firstName = $user.FirstName.Trim()
$surname = $user.Surname.Trim()
$vaildUsernameFormat = "[^a-zA-Z_.]" # identifies anything that's _not_ a-z or underscore or .
$username = "($firstName'.'$surname)" -replace $vaildUsernameFormat, '' #removes anything that isn't a-z
$DefaultPassword = 'Pa$$w0rd'
$NewUserParms = #{
'samAccountName' = $username;
'Name' = "$firstname $surname";
'DisplayName' = "$firstname $surname";
'UserPrincipalName' = "$username#domain.com";
'GivenName' = $firstname;
'Surname' = $surname;
'EmailAddress' = $User.Email;
'AccountPassword' = (ConvertTo-SecureString $DefaultPassword -AsPlainText -Force);
'Enabled' = $true;
'Path' = "OU=Users,DC=domain,DC=com";
}
write-host "$username this is username value"
#Check if the user account already exists in AD
if (Get-ADUser -F {
sAMAccountName -eq $username
}) {
#If user does exist, output a warning message
Write-Warning "A user account $username has already exist in Active Directory."
}
else {
#If a user does not exist then create a new user account
New-ADUser $NewUserParms -ErrorAction Stop
}
}
I've removed some of the user attributes just to make this a bit smaller.
here is the.csv as well in case I've messed something up there
link to .csv file on git
I think it's something simple. When you use splatting, you need to use the # symbol when feeding your hash table to the cmdlet rather than the regular $:
New-ADUser #NewUserParms -ErrorAction Stop
Some more reading About Splatting.

How skip empty values in new-aduser

Hello I write program that will be create user from powershell gui, and i have problem:
Sometimes not all field have values and they empty, but when i try create user with parameter that have empty value i get error
new-aduser server is unwilling to process the request
I can use many if-else blocks foreach field but i think it's not good solution.Please help have can i pass create user with empty parameters.
New-ADUser -AccountPassword (ConvertTo-SecureString -AsPlainText -Force -String ($Password.Text)) `
-GivenName $UserName.Text `
-Company $company.Text `
-EmployeeID $Tabel.Text `
-HomePhone $homephone.Text `
-MobilePhone $mobilephone.Text `
-Enabled $true `
-SamAccountName $Login.Text `
-StreetAddress $street.Text `
-Surname $Surname.Text `
-Title $JobPost.Text `
-UserPrincipalName ($Login.Text + "#domain.com") `
-OfficePhone $phone.Text `
-Office $office.Text `
-Description $SZnumb.Text `
-City $City.Text `
-Department $Departament.Text `
-Division $Division.Text `
-Name ($Surname.Text + " " + $UserName.Text + " " + $FatherName.Text) `
-DisplayName ($Surname.Text + " " + $UserName.Text + " " + $FatherName.Text) `
-Path $OUpicker.Text `
-PasswordNeverExpires $passneverexpires `
-ChangePasswordAtLogon $changepassatlogon `
-CannotChangePassword $cantchangepassword `
-OtherAttributes #{ 'employeeType' = $LevelRuler.Text; 'extensionAttribute4'=$Sektor.Text}
Update
Problem with parameter -OtherAttributes if that two field empty it's throw error
The suggestion by vonPryz sounds like a good one.
You can have something like a radio button defining what account type you are dealing with and based on that disable or hide some of the input boxes.
Anyway, I think you should really consider switching to using Splatting. This makes better readable and maintanable code (no more nasty backticks) AND you can add or leave out properties depending on certain conditions.
Something like:
# build a Hashtable object for splatting, at first with properties all account types have in common
# for instance:
$userParams = #{
AccountPassword = (ConvertTo-SecureString -AsPlainText -Force -String ($Password.Text))
GivenName = $UserName.Text
Company = $company.Text
EmployeeID = $Tabel.Text
HomePhone = $homephone.Text
MobilePhone = $mobilephone.Text
Enabled = $true
SamAccountName = $Login.Text
StreetAddress = $street.Text
Surname = $Surname.Text
Title = $JobPost.Text
UserPrincipalName = ($Login.Text + "#atbmarket.com")
Description = $SZnumb.Text
City = $City.Text
Department = $Departament.Text
Division = $Division.Text
Name = ($Surname.Text + " " + $UserName.Text + " " + $FatherName.Text)
DisplayName = ($Surname.Text + " " + $UserName.Text + " " + $FatherName.Text)
Path = $OUpicker.Text
PasswordNeverExpires = $passneverexpires
ChangePasswordAtLogon = $changepassatlogon
CannotChangePassword = $cantchangepassword
}
Now, you can add certain extra properties, depending on the account type. For instance:
switch ($LevelRuler.Text) {
'Manager' {
$userParams['OtherAttributes'] = #{'employeeType' = 'Manager'; 'extensionAttribute4'=$Sektor.Text}
}
'FloorWalker' {
$userParams['OtherAttributes'] = #{'employeeType' = 'FloorWalker' }
}
# etc.
}
And add other common properties only if they are not blank:
if (!([string]::IsNullOrWhiteSpace($phone.Text))) {
$userParams['OfficePhone'] = $phone.Text.Trim()
}
if (!([string]::IsNullOrWhiteSpace($office.Text))) {
$userParams['Office'] = $office.Text.Trim()
}
# etc.
Finally, create the new user:
New-ADUser #userParams
P.S.1 is this a typo? $Departament.Text
P.S.2 Instead of doing ($Surname.Text + " " + $UserName.Text + " " + $FatherName.Text) twice, I'd create a variable $name first like $name = ('{0} {1} {2}' -f $Surname.Text, $UserName.Text, $FatherName.Text).Trim() -replace '\s+', ' ' and use that for properties Name and DisplayName