I can open my mailbox in exchange online with EWS and Powershell
$service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService
$service.Credentials = New-Object System.Net.NetworkCredential -ArgumentList $mail, $password
$service.URL = New-Object Uri("https://outlook.office365.com/EWS/Exchange.asmx")
$view = New-Object Microsoft.Exchange.WebServices.Data.ItemView($numOfEmailsToRead, $index)
$folderview = New-Object Microsoft.Exchange.WebServices.Data.FolderView(10)
$folderview.PropertySet = New-Object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.Webservices.Data.BasePropertySet]::FirstClassProperties)
$folderview.PropertySet.Add([Microsoft.Exchange.Webservices.Data.FolderSchema]::DisplayName)
$folderview.Traversal = [Microsoft.Exchange.Webservices.Data.FolderTraversal]::Deep
$folderfindResults = $service.FindFolders([Microsoft.Exchange.Webservices.Data.WellKnownFolderName]::Inbox, $folderview)
$SearchFilterContainsSubString = New-Object Microsoft.Exchange.WebServices.Data.SearchFilter+ContainsSubstring([Microsoft.Exchange.WebServices.Data.ItemSchema]::Subject, $Paramerter)
$SearchFilterNot = New-Object Microsoft.Exchange.WebServices.Data.SearchFilter+Not($SearchFilterContainsSubString)
foreach ($InboxFolder in $folderfindResults) {
$findResultsItems = $InboxFolder.findItems($SearchFilterNot,$view)}
How do I change the code to open a mailbox to which I have full access?
In your example you need to use the Mailbox overload for Folder id so change
$folderfindResults = $service.FindFolders([Microsoft.Exchange.Webservices.Data.WellKnownFolderName]::Inbox, $folderview)
$SearchFilterContainsSubString = New-Object Microsoft.Exchange.WebServices.Data.SearchFilter+ContainsSubstring([Microsoft.Exchange.WebServices.Data.ItemSchema]::Subject, $Paramerter)
$SearchFilterNot = New-Object Microsoft.Exchange.WebServices.Data.SearchFilter+Not($SearchFilterContainsSubString)
foreach ($InboxFolder in $folderfindResults) {
$findResultsItems = $InboxFolder.findItems($SearchFilterNot,$view)}
To
$MailboxToAccess = "blah#blah.com"
$folderid = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$MailboxToAccess)
$folderfindResults = $service.FindFolders($folderid, $folderview)
$SearchFilterContainsSubString = New-Object Microsoft.Exchange.WebServices.Data.SearchFilter+ContainsSubstring([Microsoft.Exchange.WebServices.Data.ItemSchema]::Subject, $Paramerter)
$SearchFilterNot = New-Object Microsoft.Exchange.WebServices.Data.SearchFilter+Not($SearchFilterContainsSubString)
foreach ($InboxFolder in $folderfindResults) {
$findResultsItems = $InboxFolder.findItems($SearchFilterNot,$view)}
Here is a simple example of connecting to a different mailbox
$MailboxName = New-Object Microsoft.Exchange.WebServices.Data.Mailbox("support#domain.com") #specifies which mailbox EWS should connect to
$folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$MailboxName)
$Inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)
For more detailed info please read this blog: https://gsexdev.blogspot.com/2016/10/ews-basics-accessing-and-using-shared.html
Thank you for your support.
I was able to do it with the line
$service.ImpersonatedUserId = New-Object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress,$Mailbox);
Resolve.
I was getting a 401 error. The error was because I had overwritten the credentials. Now everything works.
In Exchange the executing user needs the role
"ApplicationImpersonation"
Related
i have built a little powershell gui for creating local computer accounts. i have a problem with my code creating accounts, where i am not asked for changing the password after login. maybe someone can help. i want a further checkbock i can mark, where i am not been asked for changing my password after windows login
$ErrorActionPreference = "Stop"
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
# restart elevated if needed
if(!(new-object System.Security.Principal.WindowsPrincipal([System.Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole(544)){
start powershell -Verb runas -ArgumentList '-File',$MyInvocation.MyCommand.Definition
exit
}
#####################################################################################################################################################
#create form
$form = New-Object System.Windows.Forms.Form
$form.Width = 500
$form.Height = 700
$form.MaximizeBox = $false
$form.TopMost = $true
#####################################################################################################################################################
$objLabel = New-Object System.Windows.Forms.label
$objLabel.Location = New-Object System.Drawing.Size(10,20)
$objLabel.Size = New-Object System.Drawing.Size(130,15)
$objLabel.BackColor = "Transparent"
$objLabel.ForeColor = "Black"
$objLabel.Text = "Username"
$Form.Controls.Add($objLabel)
#textbox with choosen user name
$txtBox = New-Object System.Windows.Forms.TextBox
$txtBox.Location = New-Object System.Drawing.Point (180, 20)
$txtBox.Size = New-Object System.Drawing.Size(280,100)
$form.Controls.Add($txtBox)
#####################################################################################################################################################
$objLabel2 = New-Object System.Windows.Forms.label
$objLabel2.Location = New-Object System.Drawing.Size(10,50)
$objLabel2.Size = New-Object System.Drawing.Size(130,15)
$objLabel2.BackColor = "Transparent"
$objLabel2.ForeColor = "Black"
$objLabel2.Text = "Password"
$Form.Controls.Add($objLabel2)
#textbox with choosen password
$txtBox2 = New-Object Windows.Forms.MaskedTextBox
$txtBox2.PasswordChar = '*'
$txtBox2.Location = New-Object System.Drawing.Point (180, 50)
$txtBox2.Size = New-Object System.Drawing.Size(280,100)
$form.Controls.Add($txtBox2)
#####################################################################################################################################################
#create checkbox1
$checkBox = New-Object System.Windows.Forms.CheckBox
$checkBox.Location = New-Object System.Drawing.Point (10, 100)
$checkBox.Size = New-Object System.Drawing.Size(350,30)
$checkBox.Text = "PasswordNeverExpires"
$form.Controls.Add($checkBox)
#create checkbox2
$checkBox2 = New-Object System.Windows.Forms.CheckBox
$checkBox2.Location = New-Object System.Drawing.Point (10, 150)
$checkBox2.Size = New-Object System.Drawing.Size(350,30)
$checkBox2.Text = "UserMayChangePassword"
$form.Controls.Add($checkBox2)
#create checkbox3
$checkBox3 = New-Object System.Windows.Forms.CheckBox
$checkBox3.Location = New-Object System.Drawing.Point (10, 200)
$checkBox3.Size = New-Object System.Drawing.Size(350,30)
$checkBox3.Text = "AccountNeverExpires"
$form.Controls.Add($checkBox3)
#create checkbox4
$checkBox4 = New-Object System.Windows.Forms.CheckBox
$checkBox4.Location = New-Object System.Drawing.Point (10, 250)
$checkBox4.Size = New-Object System.Drawing.Size(350,30)
$checkBox4.Text = "AdminAccount"
$form.Controls.Add($checkBox4)
#create checkbox5
$checkBox5 = New-Object System.Windows.Forms.CheckBox
$checkBox5.Location = New-Object System.Drawing.Point (10, 300)
$checkBox5.Size = New-Object System.Drawing.Size(350,30)
$checkBox5.Text = "noPassword"
$checkbox5.Add_Click({
# disable/enable other controls depending on state of current checkbox
$checkBox.Enabled = !$checkBox5.Checked
$txtBox2.Enabled = !$checkBox5.Checked
$checkbox4.Enabled = !$checkBox5.Checked
})
$form.Controls.Add($checkBox5)
#create checkbox6
$checkBox6 = New-Object System.Windows.Forms.CheckBox
$checkBox6.Location = New-Object System.Drawing.Point (10, 350)
$checkBox6.Size = New-Object System.Drawing.Size(350,30)
$checkBox6.Text = "ChangePasswordAtLogon"
$form.Controls.Add($checkBox6)
#create user button
$Button = New-Object System.Windows.Forms.Button
$Button.Location = New-Object System.Drawing.Size(10,450)
$Button.Size = New-Object System.Drawing.Size(150,50)
$Button.Text = "create user"
$Button.Add_Click({
# Admin or Users Group
$group = #{$true='S-1-5-32-544';$false='S-1-5-32-545'}[$checkbox4.checked]
try{
# define options to create user
$useroptions = #{
Name = $txtbox.Text
Description = $txtbox.Text
Fullname = $txtbox.Text
AccountNeverExpires = $checkbox3.Checked
UserMayNotChangePassword = !$checkbox2.Checked
ChangePasswordAtLogon = $checkbox6.Checked
}
# if the "noPassword" checkbox is not checked
if (!$checkbox5.Checked){
$useroptions.Password = ConvertTo-SecureString $txtbox2.Text -AsPlainText -Force
$useroptions.PasswordNeverExpires = $checkbox.Checked
}else{
# "noPassword" checkbox is checked
$useroptions.NoPassword = $true
$group = 'S-1-5-32-545'
}
# create user and assign to administrators group
New-LocalUser #useroptions | Add-LocalGroupMember -Group (Get-Localgroup | ? Sid -eq $group)
[System.Windows.Forms.MessageBox]::Show("User has been created successfully.","User created",0,64)
}catch{
[System.Windows.Forms.MessageBox]::Show("Error creating new user account:`n $($_.Exception.Message)","Exception",0,48)
}
})
$form.Controls.Add($Button)
#end
[void]$form.ShowDialog()
Hi i make some changes from middle to end part of your code, i think you need this:
$group = #{$true='Administrators';$false='Users'}[$checkbox4.checked]
try{
# define options to create user
$useroptions = #{
Name = $txtbox.Text
Description = $txtbox.Text
Fullname = $txtbox.Text
AccountNeverExpires = $checkbox3.Checked
UserMayNotChangePassword = !$checkbox2.Checked
#ChangePasswordAtLogon = $checkbox6.Checked
}
# if the "noPassword" checkbox is not checked
if (!$checkbox5.Checked){
$useroptions.Password = ConvertTo-SecureString $txtbox2.Text -AsPlainText -Force
$useroptions.PasswordNeverExpires = $checkbox.Checked
}else{
# "noPassword" checkbox is checked
$useroptions.NoPassword = $true
}
# create user and assign to administrators group
New-LocalUser #useroptions | Set-LocalUser -PasswordNeverExpires $checkbox.Checked
Add-LocalGroupMember -Group $group -Member $useroptions.Name
[System.Windows.Forms.MessageBox]::Show("User has been created successfully.","User created",0,64)
}catch{
[System.Windows.Forms.MessageBox]::Show("Error creating new user account:`n $($_.Exception.Message)","Exception",0,48)
}
})
$form.Controls.Add($Button)
this will add new user in Adminsitrators or in Users group (depends if admin is flagged) and if "PasswordNeverExpires" is flagged, will not ask for prompt new password on the first login.
this is not recognized as parameter for New-LocalUser, so i comment it, you decide what to do.
#ChangePasswordAtLogon = $checkbox6.Checked
CODE TESTED AND WORKING
hope this help you
Active Directory looks at the pwdLastSet attribute to see if the account needs to change a password or not. Open AD Users and Computer and look at a perfectly good user account for the "User must change password at next login" box on the Accounts tab. Check the box, and this attribute will be cleared. Uncheck the box again, and it is set to the current timestamp, regardless of what was there originally.
I haven't done this in PowerShell, but I have similar C# code with a UserPrincipal object that uses userPrincipalInstance.LastPasswordSet.HasValue to see is this box would be checked or not, and set (or clear) the userPrincipalInstance.LastPasswordSet to change it's status.
Of course, this is for Active Directory's UserPrincipal, but it's possible WindowsPrincipal for local accounts is similar.
here there is a simple script to send an email.
If I run it using Gmail settings (ie smtp.gmail.com on port 465 or 587) the script doesn't work returning the error
Server error response: 5.7.0 Authentication Required
# graphical stuff
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
Add-Type -AssemblyName PresentationFramework
# import modules
$workdir = Get-Location
Import-Module -Name "$workdir\Modules\Forms.psm1" # module for windows forms
$answ = [System.Windows.MessageBox]::Show("Configure for sending mail alerts?",'ALERTS','YesNo','Info')
if ($answ -eq "Yes") {
# dialog box
$formail = New-Object System.Windows.Forms.Form
$formail.Text = "CONFIG"
$formail.Size = "500,300"
$formail.StartPosition = 'CenterScreen'
$formail.Topmost = $true
$address = New-Object System.Windows.Forms.Label
$address.Location = New-Object System.Drawing.Size(10,20)
$address.Size = New-Object System.Drawing.Size(120,20)
$address.Text = "Mail address:"
$formail.Controls.Add($address)
$addressbox = New-Object System.Windows.Forms.TextBox
$addressbox.Location = New-Object System.Drawing.Point(130,20)
$addressbox.Size = New-Object System.Drawing.Size(300,20)
$formail.Add_Shown({$addressbox.Select()})
$formail.Controls.Add($addressbox)
$passwd = New-Object System.Windows.Forms.Label
$passwd.Location = New-Object System.Drawing.Size(10,50)
$passwd.Size = New-Object System.Drawing.Size(120,20)
$passwd.Text = "Password:"
$formail.Controls.Add($passwd)
$passwdbox = New-Object System.Windows.Forms.MaskedTextBox
$passwdbox.PasswordChar = '*'
$passwdbox.Location = New-Object System.Drawing.Point(130,50)
$passwdbox.Size = New-Object System.Drawing.Size(300,20)
$formail.Add_Shown({$passwdbox.Select()})
$formail.Controls.Add($passwdbox)
$smtp = New-Object System.Windows.Forms.Label
$smtp.Location = New-Object System.Drawing.Size(10,80)
$smtp.Size = New-Object System.Drawing.Size(120,20)
$smtp.Text = "SMTP server:"
$formail.Controls.Add($smtp)
$smtpbox = New-Object System.Windows.Forms.TextBox
$smtpbox.Location = New-Object System.Drawing.Point(130,80)
$smtpbox.Size = New-Object System.Drawing.Size(300,20)
$formail.Add_Shown({$smtpbox.Select()})
$formail.Controls.Add($smtpbox)
$port = New-Object System.Windows.Forms.Label
$port.Location = New-Object System.Drawing.Size(10,110)
$port.Size = New-Object System.Drawing.Size(120,20)
$port.Text = "Port:"
$formail.Controls.Add($port)
$portbox = New-Object System.Windows.Forms.TextBox
$portbox.Location = New-Object System.Drawing.Point(130,110)
$portbox.Size = New-Object System.Drawing.Size(300,20)
$portbox.Text = '587'
$formail.Add_Shown({$portbox.Select()})
$formail.Controls.Add($portbox)
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = "150,160"
$OKButton.Size = '100,30'
$OKButton.Text = "Ok"
$OKButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
$formail.AcceptButton = $OKButton
$formail.Controls.Add($OKButton)
$result = $formail.ShowDialog()
# setting credentials
$usr = $addressbox.Text
$pwd = ConvertTo-SecureString $passwdbox.Text -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($usr, $pwd)
# define email content
$subject = 'TestMail.ps1'
$body = "Questa mail è stata mandata da uno script PowerShell"
# sending email
$ErrorActionPreference= 'Stop'
Try {
Send-MailMessage -From $addressbox.Text `
-To $addressbox.Text `
-Subject $subject `
-Body $body `
-SmtpServer $smtpbox.Text `
-UseSsl `
-Port $portbox.Text `
-Credential $credential
$ErrorActionPreference= 'Inquire'
}
Catch {
Write-Output "`nError: $($error[0].ToString())"
$answ = [System.Windows.MessageBox]::Show("Sending alert email failed",'WARNING','Ok','Warning')
}
}
In the cmdlet Send-MailMessage I haven't found any parameter to force authentication. How can I effectively send an email?
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required:
Solutions in order of likely hood to help.
Check if the user has 2fa enabled if so you will need an apps password
Check your Captcha loc
Look into Xoauth2
I solved the issue. As stated here, I have to:
1 - Force the script to use TLS 1.2
2 - Turn off two-factor authentication and allow access to insecure apps
Thank you DaImTo for the inspiration
I'm trying to build a little app to help admins swap powerapps ownership around in PowerShell. I'm sure this is me misunderstanding how scopes work in PowerShell but I'm stumped and need a little help.
The app is pretty simple, it queries the PowerApp environment for a list of apps, their owners, and their GUIDs and presents them in a datagridview. Users select the app they're going to change, click a button, put an email address in, and then click another button. On that click, the app grabs the user's GUID from AAD and then runs a command to flip ownership of the app to that user's GUID.
But for some reason, the second function keeps reporting that the GUID and App Name I collected in the first screen are empty strings.
Here's the whole thing (minus credential info, natch):
#Get Apps on environment
$apps = Get-AdminPowerApp -EnvironmentName $powerAppEnv
#Form Details
$ChangePowerAppOwnership = New-Object system.Windows.Forms.Form
$ChangePowerAppOwnership.ClientSize = New-Object System.Drawing.Point(500,300)
$ChangePowerAppOwnership.text = "Change PowerApp Ownership"
$ChangePowerAppOwnership.TopMost = $false
$appsLabel = New-Object system.Windows.Forms.Label
$appsLabel.text = "Available Apps"
$appsLabel.AutoSize = $true
$appsLabel.width = 25
$appsLabel.height = 10
$appsLabel.location = New-Object System.Drawing.Point(15,20)
$appsLabel.Font = New-Object System.Drawing.Font('Segoe UI',10)
$availableApps = New-Object system.Windows.Forms.DataGridView
$availableApps.width = 470
$availableApps.height = 200
$availableApps.location = New-Object System.Drawing.Point(15,40)
$availableApps.MultiSelect = $false
$availableApps.SelectionMode = "FullRowSelect"
$availableApps.ColumnCount = 3
$availableApps.ColumnHeadersVisible = $true
$availableApps.Columns[0].Name = "App Name"
$availableApps.Columns[1].Name = "Current Owner"
$availableApps.Columns[2].Name = "GUID"
foreach($app in $apps){
$availableApps.Rows.Add(#($app.DisplayName,($app.Owner | Select-Object -Expand displayName),$app.AppName))
}
$promptForAdmin = New-Object system.Windows.Forms.Button
$promptForAdmin.text = "Next"
$promptForAdmin.width = 60
$promptForAdmin.height = 30
$promptForAdmin.location = New-Object System.Drawing.Point(424,260)
$promptForAdmin.Font = New-Object System.Drawing.Font('Segoe UI',10)
$promptForAdmin.Add_Click({ GetNewAdmin $availableApps.SelectedRows})
$adminLabel = New-Object system.Windows.Forms.Label
$adminLabel.text = "New Administrator"
$adminLabel.AutoSize = $true
$adminLabel.width = 25
$adminLabel.height = 10
$adminLabel.location = New-Object System.Drawing.Point(14,13)
$adminLabel.Font = New-Object System.Drawing.Font('Segoe UI',10)
$adminEmailField = New-Object system.Windows.Forms.TextBox
$adminEmailField.multiline = $false
$adminEmailField.width = 200
$adminEmailField.height = 20
$adminEmailField.location = New-Object System.Drawing.Point(135,12)
$adminEmailField.Font = New-Object System.Drawing.Font('Segoe UI',10)
$changeAppAdmin = New-Object system.Windows.Forms.Button
$changeAppAdmin.text = "Go"
$changeAppAdmin.width = 60
$changeAppAdmin.height = 30
$changeAppAdmin.location = New-Object System.Drawing.Point(424,260)
$changeAppAdmin.Font = New-Object System.Drawing.Font('Segoe UI',10)
$ChangePowerAppOwnership.controls.AddRange(#($appsLabel,$availableApps,$promptForAdmin))
$ChangePowerAppOwnership.ShowDialog()
function GetNewAdmin {
param($selectedRows)
$selectedAppGuid = $selectedRows | ForEach-Object{ $_.Cells[2].Value }
$selectedAppName = $selectedRows | ForEach-Object{ $_.Cells[0].Value }
Write-Host "Selected App GUID: $selectedAppGuid" #this and the following command show values
Write-Host "Selected App Name: $selectedAppName"
$appsLabel.Visible = $false
$availableApps.Visible = $false
$promptForAdmin.Visible = $false
$changeAppAdmin.Add_Click( { AssignNewAdmin $selectedAppGuid $selectedAppName $adminEmailField.Text} )
$ChangePowerAppOwnership.controls.AddRange(#($adminLabel,$adminEmailField,$changeAppAdmin))
}
function AssignNewAdmin {
param(
$selectedAppGuid,
$selectedAppName,
$newAdminEmail
)
Write-Host "AppID: $selectedAppGuid" #this is always empty
Connect-AzureAD -Credential $credentials
$user = Get-AzureADUser -ObjectId $newAdminEmail
$newAppOwnerGuid = $user | select ObjectId
$newAppOwnerName = $user | select DisplayName
$msgBoxMessage = "Are you sure you want to grant ownership of $selectedAppName to $newAppOwnerName`?"
$msgBoxInput = [System.Windows.Forms.MessageBox]::Show($msgBoxMessage,"Confirm","YesNo","Error")
switch ($msgBoxInput){
'Yes'{
Set-AdminPowerAppOwner -AppName $selectedAppGuid -EnvironmentName $powerAppEnv -AppOwner $newAppOwnerGuid
# try{
# $ChangePowerAppOwnership.Close()
# }
# catch{
# Write-Host "Could not update this app's administrator role."
# }
}
'No' {
$ChangePowerAppOwnership.Close()
}
}
}
Move the functions to the top or at least higher than $ChangePowerAppOwnership.ShowDialog() or the script wont find them(the execution stops till you close the Form...).
The same goes for the function AssignNewAdmin as it is used in GetNewAdmin but defined later.
Courtesy of Jeroen Mostert's comment, adding GetNewClosure to my second Add_Click function did the trick.
I have a PowerShell command that will get an output of how many CAL's I have installed and how many are used. I would like to instead of write-host, change it to a variable so that I can add it to the body of an email and have it run on a schedule, to email me weekly reports on usage, I would like to have the variable something like $report as shown in the $body of the email, this is what I have so far..
$fileName = (Invoke-WmiMethod Win32_TSLicenseReport -Name GenerateReportEx).FileName
$summaryEntries = (Get-WmiObject Win32_TSLicenseReport|Where-Object FileName -eq $fileName).FetchReportSummaryEntries(0,0).ReportSummaryEntries
$summaryEntries|ForEach {Write-Host $_.ProductVersion $_.TSCALType "Installed:" $_.InstalledLicenses "Issued:" $_.IssuedLicenses}
$EmailTo = "itgroup#contonso.com"
$EmailFrom = "admin#contonso.com"
$user = 'admin#contonso.com'
$password = Unprotect-CmsMessage -Path C:\Scripts\Powershell\EncryptedSecret.txt
$Subject = "Alert: CAL USAGE "
$Body = "Alert; $Report"
$SMTPServer = "smtp#contonso.com"
$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 25)
$SMTPClient.EnableSsl = $false
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($user, $password)
$SMTPClient.Send($SMTPMessage)
I have used both parts of this script separately, but I would like to join them together, to make more useful. Thanks in advance PowerShell newbie..
Here is the full code that I used to get this to work, simply changing 'Write-Host' to 'Write-Output'
$fileName = (Invoke-WmiMethod Win32_TSLicenseReport -Name GenerateReportEx).FileName
$summaryEntries = (Get-WmiObject Win32_TSLicenseReport|Where-Object FileName -eq $fileName).FetchReportSummaryEntries(0,0).ReportSummaryEntries
$Report = $summaryEntries|ForEach {Write-Output $_.ProductVersion $_.TSCALType "Installed:" $_.InstalledLicenses "Issued:" $_.IssuedLicenses}
$EmailTo = "itgroup#contonso.com"
$EmailFrom = "admin#contonso.com"
$user = 'admin#contonso.com'
$password = Unprotect-CmsMessage -Path C:\Scripts\Powershell\EncryptedSecret.txt
$Subject = "RDS CAL USAGE REPORT"
$Body = "Alert; $Report"
$SMTPServer = "smtp#contonso.com"
$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 25)
$SMTPClient.EnableSsl = $false
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($user, $password)
$SMTPClient.Send($SMTPMessage)
I am trying to create a GUI that can create new AD Users.
My Problem: When I press the Button "Speichern" it does not use the Data in the textboxs to create the AD User. Instead this text comes in the command console:
New ADUser cmdlet at command pipeline location 1
Specify values for the following parameters:
Surname:
If I enter the Surname it will create the User with this Surname.
This is my Powershell script:
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
Import-Module ActiveDirectory
#GUI Oberfläche
$Form = New-Object System.Windows.Forms.Form
$Form.Size = New-Object System.Drawing.Size(500,500)
$Form.Text = "Benutzer hinzufügen"
#-------Labels-----------
#Label Benutzer hinzufügen
$labeladduser = New-Object System.Windows.Forms.Label
$labeladduser.Location = New-Object System.Drawing.Size(200,10)
$labeladduser.Size = New-Object System.Drawing.Size(200,30)
$labeladduser.Text = "Benutzer hinzufügen"
$labeladduser.Name = "Benutzer hinzufügen"
$Form.Controls.Add($labeladduser)
#Label Vorname
$Labelvorname = New-Object System.Windows.Forms.Label
$Labelvorname.Location = New-Object System.Drawing.Size(10,50)
$Labelvorname.Size = New-Object System.Drawing.Size(100,20)
$Labelvorname.Text = "Vorname"
$Labelvorname.Name = "Vorname"
$Form.Controls.Add($Labelvorname)
#Label Nachname
$Labelnachname = New-Object System.Windows.Forms.Label
$Labelnachname.Location = New-Object System.Drawing.Size(10,80)
$Labelnachname.Size = New-Object System.Drawing.Size(100,20)
$Labelnachname.Text = "Nachname"
$Labelnachname.Name = "Nachname"
$Form.Controls.Add($Labelnachname)
#Label Vollständigername
$LabelVn = New-Object System.Windows.Forms.Label
$LabelVn.Location = New-Object System.Drawing.Size(10,110)
$LabelVn.Size = New-Object System.Drawing.Size(100,20)
$LabelVn.Text = "Vollständigername"
$LabelVn.Name = "Vollständigername"
$Form.Controls.Add($LabelVn)
#Label Benutzeranmeldename
$LabelBa = New-Object System.Windows.Forms.Label
$LabelBa.Location = New-Object System.Drawing.Size(10,140)
$LabelBa.Size = New-Object System.Drawing.Size(150,20)
$LabelBa.Text = "Benutzeranmeldename"
$LabelBa.Name = "Benutzeranmeldename"
$Form.Controls.Add($LabelBa)
#-------Buttons-------
#Close GUI Button
$BTcancel = New-Object System.Windows.Forms.Button
$BTcancel.Location = New-Object System.Drawing.Size(400,180)
$BTcancel.Size = New-Object System.Drawing.Size(75,23)
$BTcancel.Text = "Cancel"
$BTcancel.Name = "Cancel"
$BTcancel.Add_Click({$Form.Close()})
$Form.Controls.Add($BTcancel)
#Speichern Button
$BTsave = New-Object System.Windows.Forms.Button
$BTsave.Location = New-Object System.Drawing.Size(320,180)
$BTsave.Size = New-Object System.Drawing.Size(75,23)
$BTsave.Text = "Speichern"
$BTsave.Name = "Speichern"
$Form.Controls.Add($BTsave)
#------Textfields------
#Textfeld Vorname
$Textboxvorname = New-Object System.Windows.Forms.TextBox
$Textboxvorname.Location = New-Object System.Drawing.Size(200,50)
$Textboxvorname.Size = New-Object System.Drawing.Size(200,20)
$addv = $Textboxvorname.Text
$Form.Controls.Add($Textboxvorname)
#Textfeld Nachname
$Textboxnachname = New-Object System.Windows.Forms.TextBox
$Textboxnachname.Location = New-Object System.Drawing.Size(200,80)
$Textboxnachname.Size = New-Object System.Drawing.Size(200,20)
$addn = $Textboxnachname.Text
$Form.Controls.Add($Textboxnachname)
#Textfeld Vollständigername
$TextboxVa = New-Object System.Windows.Forms.TextBox
$TextboxVa.Location = New-Object System.Drawing.Size(200,110)
$TextboxVa.Size = New-Object System.Drawing.Size(200,20)
$addVa = $TextboxVa.Text
$Form.Controls.Add($TextboxVa)
#Textfeld Benutzeranmeldename
$TextboxBa= New-Object System.Windows.Forms.TextBox
$TextboxBa.Location = New-Object System.Drawing.Size(200,140)
$TextboxBa.Size = New-Object System.Drawing.Size(200,20)
$addBa = $TextboxBa.Text
$Form.Controls.Add($TextboxBa)
#------Funktionen--------
#Add User
$BTsave.Add_Click({
New-ADuser
-Name $addVa
-Path "Ou=Users, DC=domain, DC=com"
-Givenname = $addv
-Surname =$addn
-SamAccountName $addBa
-AccountPassword (ConvertT0-SecureString "<redacted>" -AsPlainText -Force)
})
[void] $Form.ShowDialog()
Does someone have a solution for my problem?
I believe the problem is when you are assigning values.
taking this as an example:
#Textfeld Benutzeranmeldename
$TextboxBa= New-Object System.Windows.Forms.TextBox
$TextboxBa.Location = New-Object System.Drawing.Size(200,140)
$TextboxBa.Size = New-Object System.Drawing.Size(200,20)
$addBa = $TextboxBa.Text
$Form.Controls.Add($TextboxBa)
when you're assigning a value to $addBa the value of $TextboxBa.Text is most likely empty!
So you should probably change your $BTsave.Add_Click event to directly access the textbox value(s) rather than the empty variable.
Also worth noting is that PowerShell doesn't take kindly to line breaks. If you want to avoid long lines you have to add a back-tick character.
#Add User
$BTsave.Add_Click({
New-ADuser `
-Name $TextboxVa.Text `
-Path "Ou=Users, DC=domain, DC=com" `
-Givenname $Textboxvorname.Text `
-Surname $Textboxnachname.Text `
-SamAccountName $TextboxBa.Text `
-AccountPassword (ConvertTo-SecureString "<redacted>" -AsPlainText -Force)
})
Below has a full form.
Create User and add to groups.
NewUserForm PowershellGUI
https://github.com/jcvnstdn/jcvnstdn/blob/main/UserCreationForm.PS1