Loggin on GUI script - powershell

I was wondering if someone could assist me in an issue with logging. I created a account tool which uses a gui to unlock accounts, reset password and check groups etc. I put in the details to Transcript log but it doesn't log any actions other than running the tool then closing it. I wanted to know the best way to go about getting this to either log all and add to a file for each user who runs it or log actions as they are done in a folder for each user or one log for all changes.
Script below is long but for the reference.
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()
$ADAccountTool = New-Object system.Windows.Forms.Form
$ADAccountTool.ClientSize = '687,189'
$ADAccountTool.text = "AD Account Tool For Helpdesk"
$ADAccountTool.TopMost = $false
$CheckLocked = New-Object system.Windows.Forms.Button
$CheckLocked.BackColor = "#fabc47"
$CheckLocked.text = "Check Locked"
$CheckLocked.width = 100
$CheckLocked.height = 30
$CheckLocked.location = New-Object System.Drawing.Point(200,39)
$CheckLocked.Font = 'Microsoft Sans Serif,8'
$CheckLocked.ForeColor = "#000000"
$User = New-Object system.Windows.Forms.TextBox
$User.multiline = $false
$User.width = 174
$User.height = 25
$User.location = New-Object System.Drawing.Point(14,46)
$User.Font = 'Microsoft Sans Serif,10'
$Header = New-Object system.Windows.Forms.Label
$Header.text = "Enter User"
$Header.AutoSize = $true
$Header.width = 25
$Header.height = 10
$Header.location = New-Object System.Drawing.Point(12,26)
$Header.Font = 'Microsoft Sans Serif,10'
$UnlockAccount = New-Object system.Windows.Forms.Button
$UnlockAccount.BackColor = "#81b772"
$UnlockAccount.text = "Unlock Account"
$UnlockAccount.width = 100
$UnlockAccount.height = 30
$UnlockAccount.location = New-Object System.Drawing.Point(310,39)
$UnlockAccount.Font = 'Microsoft Sans Serif,8'
$LockAccount = New-Object system.Windows.Forms.Button
$LockAccount.BackColor = "#e55d5d"
$LockAccount.text = "Lock Account"
$LockAccount.width = 100
$LockAccount.height = 30
$LockAccount.visible = $false
$LockAccount.enabled = $false
$LockAccount.location = New-Object System.Drawing.Point(201,152)
$LockAccount.Font = 'Microsoft Sans Serif,8'
$Header2 = New-Object system.Windows.Forms.Label
$Header2.text = "Set New Password"
$Header2.AutoSize = $true
$Header2.width = 25
$Header2.height = 10
$Header2.location = New-Object System.Drawing.Point(14,87)
$Header2.Font = 'Microsoft Sans Serif,10'
$Password = New-Object system.Windows.Forms.TextBox
$Password.multiline = $false
$Password.width = 174
$Password.height = 20
$Password.location = New-Object System.Drawing.Point(12,109)
$Password.Font = 'Microsoft Sans Serif,10'
$SetPassword = New-Object system.Windows.Forms.Button
$SetPassword.text = "Set Password"
$SetPassword.width = 100
$SetPassword.height = 30
$SetPassword.location = New-Object System.Drawing.Point(200,100)
$SetPassword.Font = 'Microsoft Sans Serif,8'
$DIsableAccount = New-Object system.Windows.Forms.Button
$DIsableAccount.text = "Disable Account"
$DIsableAccount.width = 100
$DIsableAccount.height = 30
$DIsableAccount.location = New-Object System.Drawing.Point(310,100)
$DIsableAccount.Font = 'Microsoft Sans Serif,8'
$EnableAccount = New-Object system.Windows.Forms.Button
$EnableAccount.text = "Enable Account"
$EnableAccount.width = 100
$EnableAccount.height = 30
$EnableAccount.location = New-Object System.Drawing.Point(420,100)
$EnableAccount.Font = 'Microsoft Sans Serif,8'
$GroupMembership = New-Object system.Windows.Forms.Button
$GroupMembership.BackColor = "#f8e71c"
$GroupMembership.text = "Group Membership"
$GroupMembership.width = 100
$GroupMembership.height = 30
$GroupMembership.location = New-Object System.Drawing.Point(423,37)
$GroupMembership.Font = 'Microsoft Sans Serif,8'
$O365Membership = New-Object system.Windows.Forms.Button
$O365Membership.BackColor = "#8cf61f"
$O365Membership.text = "O365 Membership"
$O365Membership.width = 100
$O365Membership.height = 30
$O365Membership.location = New-Object System.Drawing.Point(537,38)
$O365Membership.Font = 'Microsoft Sans Serif,8'
$WS1Membership = New-Object system.Windows.Forms.Button
$WS1Membership.BackColor = "#1c29f8"
$WS1Membership.text = "WS1 Membership"
$WS1Membership.width = 100
$WS1Membership.height = 30
$WS1Membership.location = New-Object System.Drawing.Point(536,100)
$WS1Membership.Font = 'Microsoft Sans Serif,8'
$ADAccountTool.controls.AddRange(#($CheckLocked,$User,$Header,$UnlockAccount,$LockAccount,$Header2,$Password,$SetPassword,$DIsableAccount,$EnableAccount,$GroupMembership,$O365Membership,$WS1Membership))
$CheckLocked.Add_Click({ CheckLocked })
$UnlockAccount.Add_Click({ UnlockAccount })
$SetPassword.Add_Click({ SetPassword })
$DIsableAccount.Add_Click({ DisableAccount })
$EnableAccount.Add_Click({ EnableAccount })
$GroupMembership.Add_Click({ GroupMembership })
$LockAccount.Add_Click({ LockAccount })
$O365Membership.Add_Click({ O365Membership })
$WS1Membership.Add_Click({ WS1Membership })
#Write your logic code here
#Logging is defined here to begin soon as tool is loaded
#New File is created for logging
New-Item -Path "FOLDERPATH\PowerShell Script Logs\AD Account Tool for SD" -Name "$Env:USERNAME.log"
$LogPath = Join-Path -Path "folderName" -ChildPath "$Env:USERNAME.log"
#Function is created to define the file name and parameters
Function Add-Log ($Message) {
$Timestamp= $((Get-Date).ToString("yyyyMMdd_HHmmss"))
Add-Content -Path $LogPath -Value ($Timestamp + ": " + $Message)
}
#Function sets the users password as per input in the password box
function SetPassword {
Try {
Set-ADAccountPassword -Identity $User.text -NewPassword (ConvertTo-SecureString -AsPlainText $Password.text -Force)
[System.Windows.MessageBox]::Show('Password Changed')
}
Catch {
Add-Log -Message ("Error changing password for " + $user.text)
# Add the trapped error to log
Add-Log -Message $_
}
}
#Function checks whether a user is locked in Active Directory
function CheckLocked {
Try {
$Result = Get-ADUser -Identity $User.text -Properties Name, LastLogonDate, LockedOut, AccountLockOutTime, Enabled | select-Object Name, LastLogonDate, LockedOut, AccountLockOutTime, Enabled
$Result | Out-GridView -Title 'Locked Accounts'
}
Catch {
Add-Log -Message ("Error changing password for " + $user.text)
# Add the trapped error to log
Add-Log -Message $_
}
}
#Function Unlocks Active Directory account of user.
function UnlockAccount {
Try {
Unlock-ADAccount -Identity $User.text
$Result = Get-ADUser -Identity $User.text -Properties Name, LastLogonDate, LockedOut, AccountLockOutTime, Enabled | select-Object Name, LastLogonDate, LockedOut, AccountLockOutTime, Enabled
$Result | Out-GridView -Title 'Unlocked Account'
}
Catch {
Add-Log -Message ("Error changing password for " + $user.text)
# Add the trapped error to log
Add-Log -Message $_
}
}
#Function locks a users account and resets password as well
function LockAccount {
Try {
if ($LockoutBadCount = ((([xml](Get-GPOReport -Name "Default Domain Policy" -ReportType Xml)).GPO.Computer.ExtensionData.Extension.Account |
Where-Object name -eq LockoutBadCount).SettingNumber)) {
$Password = ConvertTo-SecureString 'NotMyPassword' -AsPlainText -Force
Get-ADUser -Identity $User.text -Properties SamAccountName, UserPrincipalName, LockedOut |
ForEach-Object {
for ($i = 1; $i -le $LockoutBadCount; $i++) {
Invoke-Command -ComputerName dc01 {Get-Process
} -Credential (New-Object System.Management.Automation.PSCredential ($($_.UserPrincipalName), $Password)) -ErrorAction SilentlyContinue
}
$Result = Get-ADUser -Identity $User.text -Properties Name, LastLogonDate, LockedOut, AccountLockOutTime, Enabled | Select-Object Name, LastLogonDate, LockedOut, AccountLockOutTime, Enabled
$Result | Out-GridView -Title 'Unlocked Account'
}
}
}
Catch {
Add-Log -Message ("Error changing password for " + $user.text)
# Add the trapped error to log
Add-Log -Message $_
}
}
#Function enables a disbaled Active Directory account.
function EnableAccount {
Try {
Enable-ADAccount -Identity $User.text
$Result = Get-ADUser -Identity $User.text -Properties Name, LastLogonDate, LockedOut, AccountLockOutTime, Enabled | select-Object Name, LastLogonDate, LockedOut, AccountLockOutTime, Enabled
$Result | Out-GridView -Title 'Enabled Account'
}
Catch {
Add-Log -Message ("Error changing password for " + $user.text)
# Add the trapped error to log
Add-Log -Message $_
}
}
#Function Disabled an Active Directory account.
function DisableAccount {
Try {
Disable-ADAccount -Identity $User.text
$Result = Get-ADUser -Identity $User.text -Properties Name, LastLogonDate, LockedOut, AccountLockOutTime, Enabled | Select-Object Name, LastLogonDate, LockedOut, AccountLockOutTime, Enabled
$Result | Out-GridView -Title 'Disabled Account'
}
Catch {
Add-Log -Message ("Error changing password for " + $user.text)
# Add the trapped error to log
Add-Log -Message $_
}
}
#Function will pull all groups a user is a member off.
function GroupMembership {
Try {
$Result = GET-ADPrincipalGroupMembership -Identity $User.text | Select-Object DistinguishedName, GroupCategory, sAMAccountName, Name
$Result | Out-GridView -Title 'User Group Membership'
}
Catch {
Add-Log -Message ("Error changing password for " + $user.text)
# Add the trapped error to log
Add-Log -Message $_
}
}
#Function Checks if users are part of the required groups for Workspace 1
function WS1Membership {
Try {
$Result = GET-ADPrincipalGroupMembership -Identity $User.text |Where-Object {$_.name -like "*GG-View_app*"} | Select-Object DistinguishedName, GroupCategory, sAMAccountName, Name
$Result | Out-GridView -Title 'Workspace1 Membership'
}
Catch {
Add-Log -Message ("Error changing password for " + $user.text)
# Add the trapped error to log
Add-Log -Message $_
}
}
#Function Checks if users are part of for Office365 Licence's
function O365Membership {
Try {
$Result = GET-ADPrincipalGroupMembership -Identity $User.text |Where-Object {$_.name -like "*sg-lic_*"} | Select-Object DistinguishedName, GroupCategory, sAMAccountName, Name
$Result | Out-GridView -Title 'Office Licence Membership'
}
Catch {
Add-Log -Message ("Error changing password for " + $user.text)
# Add the trapped error to log
Add-Log -Message $_
}
}
#Logging ends here
#Write-Output
[void]$ADAccountTool.ShowDialog()
Thanks all for the help in advance.

Here's the above, implemented in your code for the first two functions. Works fine.
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()
$ADAccountTool = New-Object system.Windows.Forms.Form
$ADAccountTool.ClientSize = '687,189'
$ADAccountTool.text = "AD Account Tool For Helpdesk"
$ADAccountTool.TopMost = $false
$CheckLocked = New-Object system.Windows.Forms.Button
$CheckLocked.BackColor = "#fabc47"
$CheckLocked.text = "Check Locked"
$CheckLocked.width = 100
$CheckLocked.height = 30
$CheckLocked.location = New-Object System.Drawing.Point(200,39)
$CheckLocked.Font = 'Microsoft Sans Serif,8'
$CheckLocked.ForeColor = "#000000"
$User = New-Object system.Windows.Forms.TextBox
$User.multiline = $false
$User.width = 174
$User.height = 25
$User.location = New-Object System.Drawing.Point(14,46)
$User.Font = 'Microsoft Sans Serif,10'
$Header = New-Object system.Windows.Forms.Label
$Header.text = "Enter User"
$Header.AutoSize = $true
$Header.width = 25
$Header.height = 10
$Header.location = New-Object System.Drawing.Point(12,26)
$Header.Font = 'Microsoft Sans Serif,10'
$UnlockAccount = New-Object system.Windows.Forms.Button
$UnlockAccount.BackColor = "#81b772"
$UnlockAccount.text = "Unlock Account"
$UnlockAccount.width = 100
$UnlockAccount.height = 30
$UnlockAccount.location = New-Object System.Drawing.Point(310,39)
$UnlockAccount.Font = 'Microsoft Sans Serif,8'
$LockAccount = New-Object system.Windows.Forms.Button
$LockAccount.BackColor = "#e55d5d"
$LockAccount.text = "Lock Account"
$LockAccount.width = 100
$LockAccount.height = 30
$LockAccount.visible = $false
$LockAccount.enabled = $false
$LockAccount.location = New-Object System.Drawing.Point(201,152)
$LockAccount.Font = 'Microsoft Sans Serif,8'
$Header2 = New-Object system.Windows.Forms.Label
$Header2.text = "Set New Password"
$Header2.AutoSize = $true
$Header2.width = 25
$Header2.height = 10
$Header2.location = New-Object System.Drawing.Point(14,87)
$Header2.Font = 'Microsoft Sans Serif,10'
$Password = New-Object system.Windows.Forms.TextBox
$Password.multiline = $false
$Password.width = 174
$Password.height = 20
$Password.location = New-Object System.Drawing.Point(12,109)
$Password.Font = 'Microsoft Sans Serif,10'
$SetPassword = New-Object system.Windows.Forms.Button
$SetPassword.text = "Set Password"
$SetPassword.width = 100
$SetPassword.height = 30
$SetPassword.location = New-Object System.Drawing.Point(200,100)
$SetPassword.Font = 'Microsoft Sans Serif,8'
$DIsableAccount = New-Object system.Windows.Forms.Button
$DIsableAccount.text = "Disable Account"
$DIsableAccount.width = 100
$DIsableAccount.height = 30
$DIsableAccount.location = New-Object System.Drawing.Point(310,100)
$DIsableAccount.Font = 'Microsoft Sans Serif,8'
$EnableAccount = New-Object system.Windows.Forms.Button
$EnableAccount.text = "Enable Account"
$EnableAccount.width = 100
$EnableAccount.height = 30
$EnableAccount.location = New-Object System.Drawing.Point(420,100)
$EnableAccount.Font = 'Microsoft Sans Serif,8'
$GroupMembership = New-Object system.Windows.Forms.Button
$GroupMembership.BackColor = "#f8e71c"
$GroupMembership.text = "Group Membership"
$GroupMembership.width = 100
$GroupMembership.height = 30
$GroupMembership.location = New-Object System.Drawing.Point(423,37)
$GroupMembership.Font = 'Microsoft Sans Serif,8'
$O365Membership = New-Object system.Windows.Forms.Button
$O365Membership.BackColor = "#8cf61f"
$O365Membership.text = "O365 Membership"
$O365Membership.width = 100
$O365Membership.height = 30
$O365Membership.location = New-Object System.Drawing.Point(537,38)
$O365Membership.Font = 'Microsoft Sans Serif,8'
$WS1Membership = New-Object system.Windows.Forms.Button
$WS1Membership.BackColor = "#1c29f8"
$WS1Membership.text = "WS1 Membership"
$WS1Membership.width = 100
$WS1Membership.height = 30
$WS1Membership.location = New-Object System.Drawing.Point(536,100)
$WS1Membership.Font = 'Microsoft Sans Serif,8'
$ADAccountTool.controls.AddRange(#($CheckLocked,$User,$Header,$UnlockAccount,$LockAccount,$Header2,$Password,$SetPassword,$DIsableAccount,$EnableAccount,$GroupMembership,$O365Membership,$WS1Membership))
$CheckLocked.Add_Click({ CheckLocked })
$UnlockAccount.Add_Click({ UnlockAccount })
$SetPassword.Add_Click({ SetPassword })
$DIsableAccount.Add_Click({ DisableAccount })
$EnableAccount.Add_Click({ EnableAccount })
$GroupMembership.Add_Click({ GroupMembership })
$LockAccount.Add_Click({ LockAccount })
$O365Membership.Add_Click({ O365Membership })
$WS1Membership.Add_Click({ WS1Membership })
#Write your logic code here
#Logging is defined here to begin soon as tool is loaded
#New File is created for logging
New-Item -Path "c:\temp" -Name "$Env:USERNAME.log"
$LogPath = Join-Path -Path "c:\temp" -ChildPath "$Env:USERNAME.log"
#Function is created to define the file name and parameters
Function Add-Log ($Message) {
$Timestamp= $((Get-Date).ToString("yyyyMMdd_HHmmss"))
Add-Content -Path $LogPath -Value ($Timestamp + ": " + $Message)
}
#Function sets the users password as per input in the password box
function SetPassword {
Try {
Set-ADAccountPassword -Identity $User.text -NewPassword (ConvertTo-SecureString -AsPlainText $Password.text -Force) -ErrorAction Stop
[System.Windows.MessageBox]::Show('Password Changed')
}
Catch {
Add-Log -Message ("Error changing password for " + $user.text)
# Add the trapped error to log
Add-Log -Message $_
}
}
#Function checks whether a user is locked in Active Directory
function CheckLocked {
Try {
$Result = Get-ADUser -Identity $User.text -Properties Name, LastLogonDate, LockedOut, AccountLockOutTime, Enabled -ErrorAction Stop | select-Object Name, LastLogonDate, LockedOut, AccountLockOutTime, Enabled
$Result | Out-GridView -Title 'Locked Accounts'
}
Catch {
Add-Log -Message ("Error finding locked user " + $user.text)
# Add the trapped error to log
Add-Log -Message $_
}
}
[void]$ADAccountTool.ShowDialog()

You can create your own log file.
Create a file:
New-Item -Path "folderName" -Name "$Env:USERNAME.log"
$LogPath = Join-Path -Path "folderName" -ChildPath "$Env:USERNAME.log"
Create a function to add entry to log with timestamp:
Function Add-Log ($Message) {
$Timestamp= $((Get-Date).ToString("yyyyMMdd_HHmmss"))
Add-Content -Path $LogPath -Value ($Timestamp + ": " + $Message)
}
Then as part of every function, append a log entry e.g.
function SetPassword {
Try {
Set-ADAccountPassword -Identity $User.text -NewPassword (ConvertTo-SecureString -AsPlainText $Password.text -Force) -ErrorAction Stop
[System.Windows.MessageBox]::Show('Password Changed')
Add-Log -Message ("Changed password for " + $user.text)
}
Catch {
Add-Log -Message ("Error changing password for " + $user.text)
# Add the trapped error to log
Add-Log -Message $_
}
}

Related

Powershell Gui not releasing form Data entered into textboxes

I have a powershell form that pulls active directory information. 1 section get the account name from entering the First and Last Names into textboxes. after the results are displayed and I attempt to find another username I get the same results as the previous search or I get an error. Is there a line of code I need to clear the cache so to speak.
<#
.NAME
AD Account Tool
.SYNOPSIS
Check User by SamAccountName . Can Unlock User and lock user. Reset Password, enable nad disable user
.DESCRIPTION
Checks user by SamAccountName. Returns Name, Last LogonDate, LockedOut Status, LockedoutTime, and Enabled Status. Allows User to be unlocked and locked. Locking of user is by increasing badpasswordcount. User is able to reset password for account. Enabling and disabling of Users are allowed.
#>
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()
$fname= $FirstName.Text
$lname= $LastName.Text
$CheckLockTool = New-Object system.Windows.Forms.Form
$CheckLockTool.ClientSize = New-Object System.Drawing.Point(700,200)
$CheckLockTool.text = "User Account Administration Tool"
$CheckLockTool.TopMost = $false
$CheckLocked = New-Object system.Windows.Forms.Button
$CheckLocked.text = "Check Locked"
$CheckLocked.width = 100
$CheckLocked.height = 30
$CheckLocked.location = New-Object System.Drawing.Point(200,60)
$CheckLocked.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',8)
$CheckGroups = New-Object system.Windows.Forms.Button
$CheckGroups.text = "Check Groups"
$CheckGroups.width = 100
$CheckGroups.height = 30
$CheckGroups.location = New-Object System.Drawing.Point(200,89)
$CheckGroups.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',8)
$FirstName = New-Object system.Windows.Forms.TextBox
$FirstName.Text = ""
$FirstName.multiline = $false
$FirstName.width = 100
$FirstName.height = 20
$FirstName.location = New-Object System.Drawing.Point(10,30)
$FirstName.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',10)
$Lbl_FirstName = New-Object system.Windows.Forms.Label
$Lbl_FirstName.text = "First Name"
$Lbl_FirstName.AutoSize = $true
$Lbl_FirstName.width = 25
$Lbl_FirstName.height = 10
$Lbl_FirstName.location = New-Object System.Drawing.Point(10,10)
$Lbl_FirstName.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',10)
$LastName = New-Object system.Windows.Forms.TextBox
$LastName.Text = ""
$LastName.multiline = $false
$LastName.width = 100
$LastName.height = 20
$LastName.location = New-Object System.Drawing.Point(150,30)
$LastName.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',10)
$Lbl_LastName = New-Object system.Windows.Forms.Label
$Lbl_LastName.text = "Last Name"
$Lbl_LastName.AutoSize = $true
$Lbl_LastName.width = 25
$Lbl_LastName.height = 10
$Lbl_LastName.location = New-Object System.Drawing.Point(150,10)
$Lbl_LastName.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',10)
$User = New-Object system.Windows.Forms.TextBox
$User.Text = ""
$User.multiline = $false
$User.width = 174
$User.height = 25
$User.location = New-Object System.Drawing.Point(14,96)
$User.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',10)
$Header = New-Object system.Windows.Forms.Label
$Header.text = "Enter Users 6+2"
$Header.AutoSize = $true
$Header.width = 25
$Header.height = 10
$Header.location = New-Object System.Drawing.Point(12,76)
$Header.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',10)
$UnlockAccount = New-Object system.Windows.Forms.Button
$UnlockAccount.text = "Unlock Account"
$UnlockAccount.width = 100
$UnlockAccount.height = 30
$UnlockAccount.location = New-Object System.Drawing.Point(310,60)
$UnlockAccount.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',8)
$LockAccount = New-Object system.Windows.Forms.Button
$LockAccount.text = "Lock Account"
$LockAccount.width = 100
$LockAccount.height = 30
$LockAccount.location = New-Object System.Drawing.Point(310,89)
$LockAccount.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',8)
$LastLogon = New-Object system.Windows.Forms.Button
$LastLogon.text = "Last Logon"
$LastLogon.width = 100
$LastLogon.height = 30
$LastLogon.location = New-Object System.Drawing.Point(425,89)
$LastLogon.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',8)
$Header2 = New-Object system.Windows.Forms.Label
$Header2.text = "Set New Password"
$Header2.AutoSize = $true
$Header2.width = 25
$Header2.height = 10
$Header2.location = New-Object System.Drawing.Point(14,137)
$Header2.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',10)
$Password = New-Object system.Windows.Forms.TextBox
$Password.multiline = $false
$Password.width = 174
$Password.height = 20
$Password.location = New-Object System.Drawing.Point(12,159)
$Password.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',10)
$SetPassword = New-Object system.Windows.Forms.Button
$SetPassword.text = "Set Password"
$SetPassword.width = 100
$SetPassword.height = 30
$SetPassword.location = New-Object System.Drawing.Point(200,150)
$SetPassword.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',8)
$DIsableAccount = New-Object system.Windows.Forms.Button
$DIsableAccount.text = "Disable Account"
$DIsableAccount.width = 100
$DIsableAccount.height = 30
$DIsableAccount.location = New-Object System.Drawing.Point(310,150)
$DIsableAccount.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',8)
$EnableAccount = New-Object system.Windows.Forms.Button
$EnableAccount.text = "Enable Account"
$EnableAccount.width = 100
$EnableAccount.height = 30
$EnableAccount.location = New-Object System.Drawing.Point(420,150)
$EnableAccount.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',8)
$getacctname = New-Object system.Windows.Forms.Button
$getacctname.text = "Get 6+2"
$getacctname.width = 100
$getacctname.height = 30
$getacctname.location = New-Object System.Drawing.Point(300,25)
$getacctname.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',10)
$CheckLockTool.controls.AddRange(#($Lbl_FirstName,$Lbl_LastName,$FirstName,$LastName,$getacctname,$LastLogon,$CheckGroups,$CheckLocked,$User,$Header,$UnlockAccount,$LockAccount,$Header2,$Password,$SetPassword,$DIsableAccount,$EnableAccount))
$CheckLocked.Add_Click({ CheckLocked })
$CheckGroups.Add_Click({ CheckGroups })
$UnlockAccount.Add_Click({ UnlockAccount })
$LockAccount.Add_Click({ LockAccount })
$SetPassword.Add_Click({ SetPassword })
$DIsableAccount.Add_Click({ DisableAccount })
$EnableAccount.Add_Click({ EnableAccount })
$LastLogon.Add_Click({ LastLogon })
$getacctname.Add_Click({getacctname})
#region Logic
#Write your logic code here
function SetPassword {
Set-ADAccountPassword -Identity $User.text -NewPassword (ConvertTo-SecureString -AsPlainText $Password.text -Force)
[System.Windows.MessageBox]::Show('Password Changed')
}
function CheckLocked {
$Result = Get-ADUser -Identity $User.text -Properties Name, LastLogonDate, LockedOut, AccountLockOutTime, Enabled | select Name, LastLogonDate, LockedOut, AccountLockOutTime, Enabled
$Result | Out-GridView -Title 'Locked Accounts'
}
function CheckGroups {
$Result = Get-ADUser –Identity $User.text -Properties Name, Memberof | Select-Object -ExpandProperty MemberOf
$Result | Out-GridView -Title 'Group Memberships'
}
function LastLogon {
$Result = Get-ADUser -Identity $User.text -Properties Name, LastLogonDate| Select-Object -ExpandProperty LastLogonDate
$Result | Out-GridView -Title 'Last Logon'
}
function getacctname {
$Result = Get-ADUser -Filter "GivenName -eq '$fname' -and SurName -eq '$lname'"| Select-Object -ExpandProperty 'SamAccountName'
$Result | Out-Gridview -Title 'Windows Logon'
}
function UnlockAccount {
Unlock-ADAccount -Identity $User.text
$Result = Get-ADUser -Identity $User.text -Properties Name, LastLogonDate, LockedOut, AccountLockOutTime, Enabled | select Name, LastLogonDate, LockedOut, AccountLockOutTime, Enabled
$Result | Out-GridView -Title 'Unlocked Account'
}
function LockAccount {
if ($LockoutBadCount = ((([xml](Get-GPOReport -Name "Default Domain Policy" -ReportType Xml)).GPO.Computer.ExtensionData.Extension.Account |
Where-Object name -eq LockoutBadCount).SettingNumber)) {
$Password = ConvertTo-SecureString 'NotMyPassword' -AsPlainText -Force
Get-ADUser -Identity $User.text -Properties SamAccountName, UserPrincipalName, LockedOut |
ForEach-Object {
for ($i = 1; $i -le $LockoutBadCount; $i++) {
Invoke-Command -ComputerName dc01 {Get-Process
} -Credential (New-Object System.Management.Automation.PSCredential ($($_.UserPrincipalName), $Password)) -ErrorAction SilentlyContinue
}
$Result = Get-ADUser -Identity $User.text -Properties Name, LastLogonDate, LockedOut, AccountLockOutTime, Enabled | select Name, LastLogonDate, LockedOut, AccountLockOutTime, Enabled
$Result | Out-GridView -Title 'Unlocked Account'
}
}
}
function EnableAccount {
Enable-ADAccount -Identity $User.text
$Result = Get-ADUser -Identity $User.text -Properties Name, LastLogonDate, LockedOut, AccountLockOutTime, Enabled | select Name, LastLogonDate, LockedOut, AccountLockOutTime, Enabled
$Result | Out-GridView -Title 'Enabled Account'
}
function DisableAccount {
Disable-ADAccount -Identity $User.text
$Result = Get-ADUser -Identity $User.text -Properties Name, LastLogonDate, LockedOut, AccountLockOutTime, Enabled | select Name, LastLogonDate, LockedOut, AccountLockOutTime, Enabled
$Result | Out-GridView -Title 'Disabled Account'
}
# Disable other types of close/exit
#$form.add_FormClosing({$_.Cancel=$true})
#Write-Output
#endregion
[void]$CheckLockTool.ShowDialog()
Solved. I had a malfunction in a function.
the correct function is below.
function getacctname {
$fname= $FirstName.Text
$lname= $LastName.Text
$Result = Get-ADUser -Filter "GivenName -eq '$fname' -and SurName -eq '$lname'"| Select-Object -ExpandProperty 'SamAccountName'
$Result | Out-Gridview -Title 'Windows Logon'
}

Powershell script to display a list of users and respective permissions of a shared mailbox

I thought I'd post this here just in case I'm barking up the wrong tree. I'm looking to put together a Powershell script that can list all of the members of a shared mailbox and their respective permissions (Limited to "UserName", "Name", "Mailbox", "Full Access", "Send As", "SOBO"). My plan is for the script to ask for an email address and output to look something like this:
User Name Mailbox Full Access Send As SOBO Success
---- ---- ------- ----------- ------- ----- --------
ACB123 Smith, James Examplebox Yes Yes No Success
ABC213 Smith, Pete Examplebox Yes No Yes Success
I was surprised when I couldn't find anything online that is even similar to this.
My script, so far, grabs a list of users that have Full Access (well, it's supposed to, it seems to grab the lesser permissions too, but this actually serves my purpose). The script then strips the collected info down to usernames, then runs a for each to gather information to complete the table above. It runs an AD query for the display names as running Get-ADPermission is not an option.
I haven't got as far as to do the Send As and SoBo parts of the table because I can't get the table to be bigger than 4 columns before it turns into a list, instead of a table. I know there's the Format-Table command but I can't seem to integrate it into my current pscustomobject setup - which is currently set up to split successful queries from failed ones.
This is what I have so far, it's pretty dirty, but this is just my best guess to how something like this should work:
import-moduleactivedirectory
Install-ModuleExchangeOnlineManagement
Connect-ExchangeOnline-ShowBanner:$false
Clear-Host
$ErrorActionPreference='Stop'
$status=[System.Collections.Generic.List[pscustomobject]]::new()
$Entered_email=$Entered_email.trim()
$Collect_SendAs=Get-Mailbox$Entered_email-resultsizeunlimited|Get-RecipientPermission|where {($_.trustee -ne"NT AUTHORITY\SELF")} |where {($_.trustee -match"#")} |selectTrustee
$Collect_users=Get-Mailbox-Identity$Entered_email-ResultSize:Unlimited|Get-MailboxPermission|?{($_.IsInherited -eq$False) -and-not ($_.User -match"NT AUTHORITY")} #|select -ExpandProperty user
$status=foreach($Aliasin$Collect_users)
{
try
{
$User= ($Alias.User.Split("#")[0])
$Access=$Alias.AccessRights
$User_name=Get-ADUser-identity$User-propertiesDisplayName|select-expandpropertyDisplayName
# $Has_SendAs = ($Collect_SendAs.Split("#")[0])
# if ($User -like "*Has_SendAs*") {$User_SendAs = "yes"
# }else{$User_SendAs = "No"}
[pscustomobject]#{
User =$user
Name =$user_name.Split(',')[1..0]-join' '
Mailbox =$Entered_email
'Access Rights'=$Access.Trim("{","}")
'Has Send As'=$User_SendAs
Status ='SUCCESS'
}
}
catch
{
[pscustomobject]#{
User =$user
Status ='FAILED'
Message =$_.Exception.Message
}
}
}
$success,$failed=$status.Where({$_.Status -eq'SUCCESS'},'Split')
$success|selectUser,Name,Mailbox,'Access Rights','Has Send As'|Format-Table|Out-String|Write-Host-ForegroundColorGreen
$failed |selectUser,Message|Out-String|Write-Host-ForegroundColorRed
$SoBo=Get-Mailbox$Entered_email|select #{l='SendOnBehalfOf';e={$_.GrantSendOnBehalfTo -join"`n"}}
$Sobo_Output=$SoBo-replace"#{SendOnBehalfOf=",''-replace"}",''
If ($Sobo_Output-ge1) {
Write-Host"Users With Send on Belhalf Permissions"-ForegroundColorGreen
Write-Host"--------------------------------------"-ForegroundColorGreen
Write-Host$SoBo_Output-ForegroundColorGreen
Write-Host""
}else{
Write-Host"Users With Send on Belhalf Permissions"-ForegroundColorGreen
Write-Host"--------------------------------------"-ForegroundColorGreen
Write-Host"No users found with this permission level"-ForegroundColorGreen
Write-Host""
}
Disconnect-ExchangeOnline-Confirm:$false-InformationActionIgnore-ErrorActionSilentlyContinue
Pause
Any advice would be appreciated at this stage, I definitely could use help with the table, I could probably figure out how to add the Send As and SoBo searches, but if anyone knows some really efficient ones please let me know.
Thanks in advance.
UPDATED
I've amended the script above, because I couldn't figure out how toadd another message.
I've taken on board the changes suggested by #TheMadTechnician, and abandoned the idea of adding SoBo to the table as the SoBo users information is saved as some weird string of names and usernames, so I've rigged it so that this information pops out on a separate table below the access level table.
I've added line 10 ($Collect_SendAs), this is a line that can pull the email addresses (username#domain.com) of all users that have Send As access to the mailbox, I'm looking to get this integrated into the access level table and have made a few wrong turns trying to do this (lines 22-24 are my latest failed attempts to do this).
What I would like to do with the info collected in line 10 is to strip out the #domain part, then compare it with the usernames extracted in line 11, if there match, add a "yes" to the Send As column for the user, and if there is no match, add a "No".
If anyone can help with this, that would be amazing.
UPDATE
Think I've got it:
Import-Module ActiveDirectory
Install-Module ExchangeOnlineManagement
Connect-ExchangeOnline -ShowBanner:$false
Clear-Host
$ErrorActionPreference = 'Stop'
$status = [System.Collections.Generic.List[pscustomobject]]::new()
$Entered_email = Read-host "Enter a mailbox address"
$Entered_email = $Entered_email.trim()
$Collect_SendAs = Get-Mailbox $Entered_email -resultsize:unlimited | Get-RecipientPermission | where {($_.trustee -ne "NT AUTHORITY\SELF")} | where {($_.trustee -match "#")} | select -ExpandProperty Trustee
$Collect_users = Get-Mailbox -Identity $Entered_email -ResultSize:Unlimited | Get-MailboxPermission | ?{($_.IsInherited -eq $False) -and -not ($_.User -match "NT AUTHORITY")}
$status = foreach ($Alias in $Collect_users)
{
try
{
$User = ($Alias.User.Split("#")[0])
$User_name = Get-ADUser -identity $User -properties DisplayName | select -expandproperty DisplayName
if ($Collect_SendAs -match $User) {$User_SendAs = "yes"
}else{$User_SendAs = "No"}
$Access = $Alias.AccessRights
[pscustomobject]#{
User = $user
Name = $user_name.Split(',')[1..0]-join' '
Mailbox = $Entered_email
'Access Rights' = $Access.Trim("{","}")
'Has Send As' = $User_SendAs
Status = 'SUCCESS'
}
}
catch
{
[pscustomobject]#{
User = $user
Status = 'FAILED'
Message = $_.Exception.Message
}
}
}
$success, $failed = $status.Where({$_.Status -eq 'SUCCESS'},'Split')
$success | select User, Name, Mailbox,'Access Rights','Has Send As' | Format-Table | Out-String | Write-Host -ForegroundColor Green
$failed | select User, Message | Out-String | Write-Host -ForegroundColor Red
$SoBo = Get-Mailbox $Entered_email |select #{l='SendOnBehalfOf';e={$_.GrantSendOnBehalfTo -join"`n"}}
$Sobo_Output = $SoBo -replace "#{SendOnBehalfOf=",'' -replace"}",''
If ($Sobo_Output -ge 1) {
Write-Host "Users With Send on Behalf Permissions" -ForegroundColor Green
Write-Host "--------------------------------------" -ForegroundColor Green
Write-Host $SoBo_Output -ForegroundColor Green
Write-Host ""
}else{
Write-Host "Users With Send on Behalf Permissions" -ForegroundColor Green
Write-Host "--------------------------------------" -ForegroundColor Green
Write-Host "No users found with this permission level" -ForegroundColor Green
Write-Host ""
}
Disconnect-ExchangeOnline -Confirm:$false -InformationAction Ignore -ErrorAction SilentlyContinue
Pause
Thanks a lot to everyone who posted.
You are duplicating efforts a LOT with this. Line 9 would return you all the users that have access and the access they have, but you discard everything but the user's account name, and then later loop through those users and get their access one at a time. Here I keep that info, then use it inside the loop to reduce calls to Exchange to get perms again and again. I also changed a variable name since you re-used $User for different things which can be very confusing.
import-module activedirectory
Install-Module ExchangeOnlineManagement
Connect-ExchangeOnline -ShowBanner:$false
Clear-Host
$ErrorActionPreference='Stop'
$status=[System.Collections.Generic.List[pscustomobject]]::new()
$Entered_email = Read-host "Enter a mailbox address"
$Collect_users = Get-Mailbox -Identity $Entered_email -ResultSize:Unlimited|Get-MailboxPermission|?{($_.IsInherited -eq $False) -and -not ($_.User -match"NT AUTHORITY")} #|select -ExpandProperty user
$status=foreach($Alias in $Collect_users)
{
try
{
$User= ($Alias.User.Split("#")[0])
$Access=$Alias.AccessRights
if ($Access -like "*FullAccess*") {$Access_Result="yes"
}else{$Access_Result="No"}
$User_name = Get-ADUser -identity $User -properties DisplayName|select -expandproperty DisplayName
[pscustomobject]#{
User = $user
Name = $user_name
Mailbox = $Entered_email.Split("#")[0]
'Full Access'= $Access_Result
Status ='SUCCESS'
}
}
catch
{
[pscustomobject]#{
User = $user.user
Status ='FAILED'
Message = $_.Exception.Message
}
}
}
$success,$failed=$status.Where({$_.Status -eq'SUCCESS'},'Split')
$success|Out-String|Write-Host-ForegroundColorGreen
$failed |Out-String|Write-Host-ForegroundColorRed
Pause
I started making a "mailbox manager" gui last year and never got around to finishing it, but maybe there's some useful stuff you could pull from it. The last thing I was trying to add was who has access/sendas TO the selected account (bottom part of the gui), which isn't quite working...but the first part (see what accounts/sendas an account has permission for) is working.
The eventual idea was to add a "save" button in so you could check/uncheck the tickboxes as you'd like in the gui and it'd adjust the permissions.
#Init
$logpath = "C:\Scripts\Logs\MailboxPermissions.log"
#Create session on 365 Exchange server
if ((Get-PSSession).Computername -notmatch "outlook.office365.com"){Connect-365}#or: Connect-ExchangeOnline -ShowBanner:$false
$UPNs = Get-Mailbox -Identity * | select -ExpandProperty UserPrincipalName
$AccToDatasource = [System.Collections.ArrayList]::new()
$BS1 = [System.Windows.Forms.BindingSource]::new()
$BS1.DataSource = $AccToDatasource
$AccByDatasource = [System.Collections.ArrayList]::new()
$BS2 = [System.Windows.Forms.BindingSource]::new()
$BS2.DataSource = $AccByDatasource
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()
$get_permissions={
$AccToDatasource.Clear()
$AccByDatasource.Clear()
$user = $ComboBox1.Text
write-host "Checking $($user)"
Get-EXOMailboxPermission -Identity $user | ?{$_.User -ne "NT AUTHORITY\SELF"} | %{
$tablerow = New-Object psobject
$data = #{Email="$($_.User)";Inbox=1;SendAs=0}
$tablerow | Add-Member -NotePropertyMembers $data -TypeName tablerow
$AccToDatasource.Add($tablerow)
}
Get-EXORecipientPermission -Identity $user | ?{$_.Trustee -ne "NT AUTHORITY\SELF"} | %{
$indx = [array]::IndexOf($AccToDatasource.Email,$_.Trustee)
if($indx -ne -1){
$AccToDatasource[$indx].SendAs = 1
}else{
$tablerow = New-Object psobject
$data = #{Email="$($_.Trustee)";SendAs=1}
$tablerow | Add-Member -NotePropertyMembers $data -TypeName tablerow
$AccToDatasource.Add($tablerow)
}
}
$BS1.ResetBindings($true)
<##Attempt 1
Get-EXOMailbox -MailboxPlan "ExchangeOnlineEnterprise" -Properties UserPrincipalName | select -ExpandProperty UserPrincipalName | %{
Start-ThreadJob {
Get-EXOMailboxPermission -Identity $using:_ -User $using:user -ErrorAction SilentlyContinue
} | Wait-Job | Receive-Job | %{
$tablerow = New-Object psobject
$data = #{Email="$($_.Trustee)";Inbox=1;SendAs=0}
$tablerow | Add-Member -NotePropertyMembers $data -TypeName tablerow
$AccByDatasource.Add($tablerow)
}
}
$BS2.ResetBindings($true)
#>
#Attempt 2
Get-EXOMailbox -MailboxPlan "ExchangeOnlineEnterprise" -Properties UserPrincipalName | select -ExpandProperty UserPrincipalName | %{Start-ThreadJob {Get-EXOMailboxPermission -Identity $using:_ -User $using:user -ErrorAction SilentlyContinue}} | Wait-Job | Receive-Job | %{
$tablerow = New-Object psobject
$data = #{Email="$($_.Trustee)";Inbox=1;SendAs=0}
$tablerow | Add-Member -NotePropertyMembers $data -TypeName tablerow
$AccByDatasource.Add($tablerow)
}
$BS2.ResetBindings($true)
}
#Form Init
$Form = New-Object system.Windows.Forms.Form
$Form.ClientSize = New-Object System.Drawing.Point(600,650)
$Form.text = "Mailbox Manager"
$Form.TopMost = $false
$ComboBox1 = New-Object system.Windows.Forms.ComboBox
$ComboBox1.width = 370
$ComboBox1.height = 30
$ComboBox1.location = New-Object System.Drawing.Point(137,25)
$ComboBox1.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',10)
$ComboBox1.Items.AddRange($UPNs)
$ComboBox1.AutoCompleteSource = "ListItems"
$ComboBox1.AutoCompleteMode = "SuggestAppend"
#$ComboBox1.add_SelectedIndexChanged({
# if ($ComboBox1.Text.Length -gt 10){
# get-permissions -user $ComboBox1.Text
# }
#})
$Label1 = New-Object system.Windows.Forms.Label
$Label1.text = "Select 365 User:"
$Label1.AutoSize = $true
$Label1.width = 25
$Label1.height = 30
$Label1.location = New-Object System.Drawing.Point(14,25)
$Label1.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',10)
$Label2 = New-Object system.Windows.Forms.Label
$Label2.text = "Has access to:"
$Label2.AutoSize = $true
$Label2.width = 25
$Label2.height = 30
$Label2.location = New-Object System.Drawing.Point(14,55)
$Label2.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',10)
$Label3 = New-Object system.Windows.Forms.Label
$Label3.text = "Accessible by:"
$Label3.AutoSize = $true
$Label3.width = 25
$Label3.height = 30
$Label3.location = New-Object System.Drawing.Point(14,358)
$Label3.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',10)
$DataGridView1 = New-Object system.Windows.Forms.DataGridView
$DataGridView1.text = "Emails"
$DataGridView1.width = 560
$DataGridView1.height = 250
$DataGridView1.AutoGenerateColumns = $false
$DataGridView1.Columns.Add((new-object -TypeName System.Windows.Forms.DataGridViewTextBoxColumn -Property #{"Name"="Email"})) | Out-Null
$DataGridView1.Columns['Email'].DataPropertyName = "Email"
$DataGridView1.Columns.Add((new-object -TypeName System.Windows.Forms.DataGridViewCheckBoxColumn -Property #{"Name"="Inbox"})) | Out-Null
$DataGridView1.Columns['Inbox'].DataPropertyName = "Inbox"
$DataGridView1.Columns.Add((new-object -TypeName System.Windows.Forms.DataGridViewCheckBoxColumn -Property #{"Name"="SendAs"})) | Out-Null
$DataGridView1.Columns['SendAs'].DataPropertyName = "SendAs"
$DataGridView1.Columns.Add((new-object -TypeName System.Windows.Forms.DataGridViewTextBoxColumn -Property #{"Name"="Start"})) | Out-Null
$DataGridView1.Columns['Start'].DataPropertyName = "Start"
$DataGridView1.Columns.Add((new-object -TypeName System.Windows.Forms.DataGridViewTextBoxColumn -Property #{"Name"="End"})) | Out-Null
$DataGridView1.Columns['End'].DataPropertyName = "End"
$DataGridView1.ColumnHeadersVisible = $true
$DataGridView1.AutoSizeColumnsMode = 10
$DataGridView1.DataSource = $BS1
$DataGridView1.location = New-Object System.Drawing.Point(11,82)
$DataGridView1.BackColor = [System.Drawing.ColorTranslator]::FromHtml("#e0dede")
$DataGridView1.add_DataError({write-host "hit error"})
$DataGridView2 = New-Object system.Windows.Forms.DataGridView
$DataGridView2.width = 560
$DataGridView2.height = 250
$DataGridView2.location = New-Object System.Drawing.Point(9,383)
$DataGridView2.AutoGenerateColumns = $false
$DataGridView2.Columns.Add((new-object -TypeName System.Windows.Forms.DataGridViewTextBoxColumn -Property #{"Name"="Email"})) | Out-Null
$DataGridView2.Columns['Email'].DataPropertyName = "Email"
$DataGridView2.Columns.Add((new-object -TypeName System.Windows.Forms.DataGridViewCheckBoxColumn -Property #{"Name"="Inbox"})) | Out-Null
$DataGridView2.Columns['Inbox'].DataPropertyName = "Inbox"
$DataGridView2.Columns.Add((new-object -TypeName System.Windows.Forms.DataGridViewCheckBoxColumn -Property #{"Name"="SendAs"})) | Out-Null
$DataGridView2.Columns['SendAs'].DataPropertyName = "SendAs"
$DataGridView2.Columns.Add((new-object -TypeName System.Windows.Forms.DataGridViewTextBoxColumn -Property #{"Name"="Start"})) | Out-Null
$DataGridView2.Columns['Start'].DataPropertyName = "Start"
$DataGridView2.Columns.Add((new-object -TypeName System.Windows.Forms.DataGridViewTextBoxColumn -Property #{"Name"="End"})) | Out-Null
$DataGridView2.Columns['End'].DataPropertyName = "End"
$DataGridView2.ColumnHeadersVisible = $true
$DataGridView2.AutoSizeColumnsMode = 10
$DataGridView2.DataSource = $BS2
$DataGridView2.BackColor = [System.Drawing.ColorTranslator]::FromHtml("#e0dede")
$loadButton = New-Object system.Windows.Forms.Button
$loadButton.text = "Load"
$loadButton.width = 60
$loadButton.height = 30
$loadButton.location = New-Object System.Drawing.Point(509,25)
$loadButton.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',10)
$loadButton.Add_Click($get_permissions)
$saveButton = New-Object system.Windows.Forms.Button
$saveButton.text = "Save"
$saveButton.width = 60
$saveButton.height = 30
$saveButton.location = New-Object System.Drawing.Point(509,341)
$saveButton.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',10)
$Form.controls.AddRange(#($Label1,$Label2,$Label3,$ComboBox1,$DataGridView1,$DataGridView2,$saveButton, $loadButton))
[void]$Form.ShowDialog()

Powershell if else statement

I am having some difficulties with my Powershell script. With this script I am able to enable disabled AD accounts. It works, but I am receiving the wrong output. Accounts got enabled, but still receive the output from the else statement 'Account has not been enabled'. Anyone who can help me? Thanks!
Add-Type -AssemblyName System.Windows.Forms
$SystemInfoForm = New-Object System.Windows.Forms.Form
$SystemInfoForm.ClientSize = "300,100"
$SystemInfoForm.Text = "Enable AD Accounts"
$SystemInfoForm.BackColor = "#ffffff"
$SystemInfoForm.StartPosition = "CenterScreen"
$objIcon = New-Object system.drawing.icon ("C:\Temp\System Info.ico")
$SystemInfoForm.Icon = $objIcon
$label = New-Object System.Windows.Forms.Label
$label.Location = New-Object System.Drawing.Point(10,20)
$label.Size = New-Object System.Drawing.Size(280,20)
$label.Text = 'Please enter the disabled AD account below:'
$SystemInfoForm.Controls.Add($label)
$textBox = New-Object System.Windows.Forms.TextBox
$textBox.Location = New-Object System.Drawing.Point(10,40)
$textBox.Size = New-Object System.Drawing.Size(260,20)
$textBox.Text = "Enter AD account..."
$SystemInfoForm.Controls.Add($textBox)
$okButton = New-Object System.Windows.Forms.Button
$okButton.Location = New-Object System.Drawing.Point(10,70)
$okButton.Size = New-Object System.Drawing.Size(75,23)
$okButton.Text = 'OK'
$okButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
$okButton.Add_Click(
{
$Username = $textBox.Text
if (Search-ADAccount -AccountDisabled | Where-Object {($_.SamAccountName -eq "$Username")} | Enable-ADAccount)
{
[System.Windows.MessageBox]::Show("$Username has been enabled.")
}
else
{
[System.Windows.MessageBox]::Show("$Username has not been enabled.")
}
}
)
$SystemInfoForm.Controls.Add($okButton)
[void]$SystemInfoForm.ShowDialog()
Regards,
Ralph
Enable-ADAccount doesn't return any output by default, so the entire pipeline expression:
Search-ADAccount -AccountDisabled | Where-Object {($_.SamAccountName -eq "$Username")} | Enable-ADAccount
... will evaluate to nothing - and all of that nothing evaluates to $false in your if condition.
Use a try/catch block to catch errors from Enable-ADAccount and then alert the based on that:
try {
Search-ADAccount -AccountDisabled | Where-Object {($_.SamAccountName -eq "$Username")} | Enable-ADAccount -ErrorAction Stop
# We got this far because Enable-ADAccount didn't throw any errors
[System.Windows.MessageBox]::Show("$Username has been enabled.")
}
catch {
[System.Windows.MessageBox]::Show("$Username has not been enabled.")
}
Alternatively use the -PassThru switch with Enable-ADAccount to have it return the account, then inspect that:
$enabledAccount = Search-ADAccount -AccountDisabled | Where-Object {($_.SamAccountName -eq "$Username")} | Enable-ADAccount -PassThru
if($enabledAccount.Enabled){
[System.Windows.MessageBox]::Show("$Username has been enabled.")
}
else {
[System.Windows.MessageBox]::Show("$Username has not been enabled.")
}

Powershell: How to get powershell to give you the option to select the right user when you search with Known name

I have creates a Powershell script that takes a display name from a CSV looks up there username and then adds them to a security group in AD.
The problem is people with the same Display name. My script when it hits the same display name it will just add every user name with that display name.
I would like an option when it hits a name that returns multiple username that it displays an option that allows someone to pick the right username then add them to the security group.
I am fairly new to PowerShell and have come a bit stuck at this point so any help is greatly appreciated.
Import-Module ActiveDirectory
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
$Form = New-Object System.Windows.Forms.Form
$Form.Text = "Security Group Tool"
$Form.Size = New-Object System.Drawing.Size(390,150)
$Form.StartPosition = "CenterScreen"
$Form.KeyPreview = $True
$Form.MaximumSize = $Form.Size
$Form.MinimumSize = $Form.Size
$Icon = New-Object System.Drawing.Icon("H:\test\favicon.ico")
$Form.Icon = $Icon
$label = New-Object System.Windows.Forms.Label
$label.Location = New-Object System.Drawing.Size(10, 10)
$label.Size = New-Object System.Drawing.Size(400, 15)
$label.Text = "Please enter The name of the Security Group You want to add users too"
$Form.Controls.Add($label)
$textbox = New-Object System.Windows.Forms.TextBox
$textbox.Location = New-Object System.Drawing.Size(10,50)
$textbox.Size = New-Object System.Drawing.Size(240,40)
$Form.Controls.Add($textbox)
$test = {
$secgrp = $textbox.Text
$Sam = #()
$names = Import-Csv "H:\test\Groups2.csv"
foreach ($name in $names.DisplayName) {
$Sam += Get-ADUser -Filter { Name -like $name } -Properties SamAccountName | Select-Object SamAccountName
}
$User = $Sam
foreach ($User in $User) {
Add-ADGroupMember -Identity $secgrp -Members $User
}
}
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Size(260,45)
$OKButton.Size = New-Object System.Drawing.Size(75,30)
$OKButton.Text = "OK"
$OKButton.Add_Click($test)
$Form.Controls.Add($OKButton)
$Form.Add_KeyDown({
if ($_.KeyCode -eq "Enter") {
& $test
}
})
$Form.Add_KeyDown({
if ($_.KeyCode -eq "Escape") {
$Form.Close()
}
})
$Form.TopMost = $True
$Form.Add_Shown({ $Form.Activate() })
[void] $Form.ShowDialog()
You can check the number of Users returned by Get-ADUser by using the Count property. This will tell you how many objects (users) were returned.
If there is more than 1 user, you can use Out-GridView to display a popup dialogue to select the result you want from the list:
By default this allows multiple selections, but adding -OutputMode Single will then only allow a single selection to be chosen.
Your script can be updated like this:
$test = {
$secgrp = $textbox.Text
$Users = New-Object System.Collections.ArrayList
$names = Import-Csv "H:\test\Groups2.csv"
foreach ($name in $names.DisplayName) {
$ReturnedUser = Get-ADUser -Filter { Name -like $name } -Properties SamAccountName | Select-Object -ExpandProperty SamAccountName
if ($ReturnedUser.count > 1) {
$SelectedUser = $ReturnedUser | Out-GridView -Title "Multiple Users have matched, select User to process" -OutputMode Single
$null = $Users.Add($SelectedUser) #this syntax surpresses the .Add() from displaying the index of each item added
}
else {
$null = $Users.Add($ReturnedUser)
}
}
foreach ($User in $Users) {
Add-ADGroupMember -Identity $secgrp -Members $User
}
}

Login to another domain from powershell

I wrote a script to logout the citrix user and it is working fine, if I am accessing it with same domain, but if I try to run that script from some other computer where the local domain is different from the one citrix connects to it is failing, please let me know how I can connect to the citrix domain from the other local domain.
To give context I am attaching the code below,
Please help.
Regards,
AVs
Code:
# Import the Active Directory module for the Get-ADComputer CmdLet
Import-Module ActiveDirectory
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.DirectoryServices.AccountManagement
#Form to take username and password
$objForm = New-Object System.Windows.Forms.Form
$objForm.Text = "Citrix User Session Disconnection"
$objForm.Size = New-Object System.Drawing.Size(300,200)
$objForm.StartPosition = "CenterScreen"
#Data Label
$Label = New-Object System.Windows.Forms.Label
$Label.Location = New-Object System.Drawing.Size(10,130)
$Label.Size = New-Object System.Drawing.Size(250,150)
$Label.ForeColor = "White"
$Label.BackColor = "Blue"
$Label.Text = "***Give your Citrix username and password to logoff the user from the server.***"
$objForm.Controls.Add($Label)
#Username Label
$userLabel = New-Object System.Windows.Forms.Label
$userLabel.Location = New-Object System.Drawing.Size(10,20)
$userLabel.Size = New-Object System.Drawing.Size(80,30)
$userLabel.Text = "User Name"
$objForm.Controls.Add($userLabel)
#Username Textbox
$userTextBox = New-Object System.Windows.Forms.TextBox
$userTextBox.Location = New-Object System.Drawing.Size(130,20)
$userTextBox.Size = New-Object System.Drawing.Size(150,20)
$objForm.Controls.Add($userTextBox)
#Password Label
$PassLabel = New-Object System.Windows.Forms.Label
$PassLabel.Location = New-Object System.Drawing.Size(10,60)
$PassLabel.Size = New-Object System.Drawing.Size(80,30)
$PassLabel.Text = "Password"
$objForm.Controls.Add($PassLabel)
#Password Textbox
$PassTextBox2 = New-Object System.Windows.Forms.MaskedTextBox
$PassTextBox2.PasswordChar = '*'
$PassTextBox2.Location = New-Object System.Drawing.Size(130,60)
$PassTextBox2.Size = New-Object System.Drawing.Size(150,20)
$objForm.Controls.Add($PassTextBox2)
#Disconnect Button
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Size(200,100)
$OKButton.Size = New-Object System.Drawing.Size(75,23)
$OKButton.ForeColor = "Red"
$OKButton.Text = "Disconnect"
$OKButton.Add_Click({$username=$userTextBox.Text;$objForm.Close()})
$OKButton.Add_Click({$Password=$PassTextBox2.Text;$objForm.Close()})
$objForm.Controls.Add($OKButton)
$objForm.ShowDialog()
Read-Host "DOMAIN\USERNAME" -AsSecureString | ConvertFrom-SecureString | Out-File C:\SecureData\SecureString.txt
#SharePoint Admin Account
$SPAdmin = "DOMAIN\ADMIN"
$Password = Get-Content C:\SecureDate\securestring.txt | convertto-securestring
$Credential = new-object -typename System.Management.Automation.PSCredential -argumentlist $SPAdmin, $Password
Get-WmiObject -Class Win32_Service -ComputerName "Server" -Filter "Name='ServiceName'" -Credential $Credential
#Authenticaton
$Domain = $env:USERDOMAIN
$ct = [System.DirectoryServices.AccountManagement.ContextType]::Domain
$pc = New-Object System.DirectoryServices.AccountManagement.PrincipalContext $ct,$Domain
$auth = $pc.ValidateCredentials($userName,$Password)
# Get today's date for the report
$today = Get-Date
#Setup email parameters
#$subject = "ACTIVE SERVER SESSIONS REPORT - " + $today
#$priority = "Normal"
#$smtpServer = "mail.itechnologies.com.au"
#$emailFrom = "rayithy#itechnologies.com.au"
#$emailTo = "rayithy#itechnologies.com.au"
# Create a fresh variable to collect the results. You can use this to output as desired
$SessionList = "ACTIVE SERVER SESSIONS REPORT - " + $today + "`n`n"
# Query Active Directory for computers running a Server operating system
#$Servers = Get-ADComputer -Filter {OperatingSystem -like "*server*"}
$Servers = Import-Csv C:\powershell\Test.csv
if ($auth -eq "True")
{
# Loop through the list to query each server for login sessions
ForEach ($Server in $Servers) {
$ServerName = $Server.Name
# When running interactively, uncomment the Write-Host line below to show which server is being queried
# Write-Host "Querying $ServerName"
# Run the qwinsta.exe and parse the output
$queryResults = (qwinsta /SERVER:$ServerName | foreach { (($_.trim() -replace "\s+",","))} | ConvertFrom-Csv)
# Pull the session information from each instance
ForEach ($queryResult in $queryResults) {
$RDPUser = $queryResult.USERNAME
$sessionType = $queryResult.SESSIONNAME
# We only want to display where a "person" is logged in. Otherwise unused sessions show up as USERNAME as a number
If (($RDPUser -match $username) -and ($RDPUser -ne $NULL)) {
# When running interactively, uncomment the Write-Host line below to show the output to screen
# Write-Host $ServerName logged in by $RDPUser on $sessionType
$SessionList = $SessionList + "`n`n" + $ServerName + " logged in by " + $RDPUser + " on " + $sessionType
logoff $sessionType /server:$ServerName
Write-Host $RDPUser "LoggedOff"
}
}
}
}
else {
$Font = New-Object System.Drawing.Font("Times New Roman",14,[System.Drawing.FontStyle]::Italic)
#Form to display the error
$objForm2 = New-Object System.Windows.Forms.Form
$objForm2.Text = "Citrix User Session Disconnection"
$objForm2.Size = New-Object System.Drawing.Size(300,200)
$objForm2.StartPosition = "CenterScreen"
$objForm2.BackColor = "Yellow"
#Error message
$errorLabel = New-Object System.Windows.Forms.Label
$errorLabel.Location = New-Object System.Drawing.Size(10,20)
$errorLabel.Size = New-Object System.Drawing.Size(250,150)
$errorLabel.Text = "'Username/Password is not correct' Or 'User Not Logged in the Server'"
$errorLabel.Font = $Font
$errorLabel.forecolor = "Red"
$objForm2.Controls.Add($errorLabel)
$objForm2.ShowDialog()
}
In the Authentication section of your script:
#Authenticaton
$Domain = $env:USERDOMAIN
$ct = [System.DirectoryServices.AccountManagement.ContextType]::Domain
$pc = New-Object System.DirectoryServices.AccountManagement.PrincipalContext $ct,$Domain
$auth = $pc.ValidateCredentials($userName,$Password)
You're passing in $Domain as the current user's Domain. If you modify this to specify the domain Citrix auths against, you should be able to connect