Powershell script for bulk action - powershell

I am in need of help making the below script import a CSV of users with their first and last names and then setting the same account expiration inside of AD using the DRA PowerShell extension. The section "CN=User\, Test" would be changed to CN=$LastName\, $FirstName and the account expiration date would need to be set to be the same for all users in the CSV file.
Set-DRAUser -DRARestServer draserver.na.corp.domain.com -draHostServer draserver.na.corp.domain.com -Domain na.corp.domain.com -Identifier 'CN=User\, Test,OU=Users,OU=company,OU=site,OU=city,DC=na,DC=corp,DC=domain,DC=com' -IgnoreCertificateErrors -Force -Properties #{AccountExpirationDate="05/22/2022 23:59:00"}

I was able to solve this with the following code.
foreach ($user in $fileinput){
$name=$user -split ","
$sn=$name[0]
$fn=$name[1]
$dn="CN=$sn\,$fn,OU=Users,OU=company,OU=site,OU=city,DC=na,DC=corp,DC=domain,DC=com"
$dn
Set-DRAUser -DRARestServer draserver.na.corp.domain.com -draHostServer draserver.na.corp.domain.com -Domain na.corp.domain.com -Identifier $dn -IgnoreCertificateErrors -Force -Properties #{AccountExpirationDate="05/24/2022 23:59:00"}
}

Related

How to get Powershell to prompt for input parameter

I am fairly new to PowerShell. There is a command I run many times a day that checks if an AD user account belongs to a couple of AD security groups. Right now, I am pasting the user's account into the command from OneNote and then pasting that command into the PowerShell window. Ideally, I would love to be able to run a .ps1 file that would launch a popup where I could enter in the user's account and the popup would then provide the command output. If that is not possible, run the .ps1 file and have the PowerShell ask for input where I can paste the user's AD account and hit enter. Below is the command I am running. Thank you all in advance.
(Get-ADUser %ADACCOUNT% -Properties MemberOf).MemberOf | findstr /i %ADGROUP%
Here is an idea to get you started using InputBox function to get the input user, MessageBox.Show method in case the user was not part of any group and Out-GridView in case the user was member of at least one of the groups.
Usage is quite simple, you just name this script as whatever you want and then when calling it, you can do .\myScript.ps1 -ADGroups 'somegroup1', 'somegroup2', etc
param([string[]] $ADGroups)
Add-Type -AssemblyName Microsoft.VisualBasic, System.Windows.Forms
# Get user input
$choice = [Microsoft.VisualBasic.Interaction]::InputBox(
'Input User SamAccountName',
'Choose a Title for me'
)
# if the user didn't provide any input, exit script
if([string]::IsNullOrWhiteSpace($choice)) {
return
}
# get user membership and filter
$result = (Get-ADUser $choice -Properties memberOf).memberOf | Where-Object {
# where the DistinguishedName matches any of input AD Groups
foreach($group in $ADGroups) {
if($_ -match $group) { return $true }
}
}
# if no results found
if(-not $result) {
# show this message
[Windows.Forms.MessageBox]::Show(
"$choice was not a member of any AD Group",
'Choose a Title for me',
[Windows.Forms.MessageBoxButtons]::OK,
[Windows.Forms.MessageBoxIcon]::Warning
)
# and exit the script
return
}
# otherwise, show this grid that contains the list of DistinguishedNames
# the user is a member of
$result | Out-GridView

i want to know the life of a custom function in powershell

function delete_Users
{
Import-Module ActiveDirectory
$Users = Import-Csv C:\temp\test.csv
ForEach ($User in $Users)
{
# Retrieve user to make sure they exist.
$ADUser = Get-ADUser -Identity $User.sAMAccountName
If ($ADUser)
{
# Delete the user.
Remove-ADUser -Identity $User.sAMAccountName
}
}
}
I am trying to add this code in custom menu of powershell ISE.Can some one please let me knew how to do this. I tried this piece of code but it didn't worked for me.
#to add the function in custom menu option
$psISE.CustomMenu.Submenus.Add(“Run Custom Function”,{delete_Users},Ctrl+Shift+0)
Moreover what would be the life of that custom function? Would it remain there even after closing the session or after shutting down the server or is there any specific way to achieve this.
Thank you in Advance..

Add User to Exchange In-placeHold/eDiscovery (In-Situ) with powershell

I'm currently encountering some problems with powershell, while creating scripts.
I want to add a User to our In-place-Hold / eDiscovery. I more or less found a workaround to adding a single User to the list, but I'm not sure if it works without losing data of the already existing In-Place-Hold users.
The goal is to add newly created users to an existing In-Place-Hold.
However, maybe its easier to understand with my code:
#All users that are already in the in-situ
$check = Get-MailboxSearch “In situ autotest"
foreach ($User in $ADUsers)
{
$Username = $User.username
$Firstname = $User.firstname
$Lastname = $User.lastname
if (Get-Mailbox -Identity $Username)
{
#If user does exist, output a warning message
Write-Warning "Benutzername $Username already existing on the Exchange Server."
}
else
{
Enable-Mailbox -Identity "$Username" -DomainController 'DC.domain.com'
}
#search for the user
$Add = Get-Mailbox -Identity "$Username"
$check.sources.add("$Add")
}
#write all users back into insitu mailbox
Set-Mailboxsearch -Name "In situ autotest" -Identity "In situ autotest" -SourceMailboxes $check.sources
Does someone know if there is an easier way to add a single user to the sourcemailboxes of Set-Mailboxsearch, without having to aplly everyone again?
Thank you guys very much in advance!

Line break issue when configuring "send on behalf of"

I have a script to set send on behalf of permissions in Exchange Management Shell, but when you try and use it it fails because the output of the first part is too long and truncates over 2 lines.
First thing we do is build our array from lists of people and put them into some variables to pass:
function Add-Send ($mailbox, $target) {
#"Granting send on behalf for $mailbox to $target"
Set-Mailbox -Identity $mailbox -GrantSendOnBehalfTo #{ Add = $target }
}
We pass a long list as the $target and the maibox name is $mailbox and if we output the text we get:
Set-Mailbox -Identity "mr.jeff" -GrantSendOnBehalfTo #{ Add = "alan.alanson", "bob.bobson", "steve.stevenson" }
All fine and good but if there are more than N characters in the output then we get a line break:
Set-Mailbox -Identity "mr.jeff" -GrantSendOnBehalfTo #{ Add = "alan.alanson", "bob.bobson", "steve.stevenson", ...
..., "cath.cathdotir" }
When you run this script with the overlength output, then command fails as the output which should be passed to the CLI is passed over more than one line. PowerShell treats each line as a separate command, and they obviously fail with bad syntax.
Our string is output from an array that we build like this:
function Send-Array ($mailbox) {
$target = Get-Content ".\list\dpt1.txt"
$target += Get-Content ".\list\$mailbox.txt"
$target += Get-Content ".\list\dpt2.txt"
$target = $target | Select-Object -Unique
$separator = '", "'
$target= $target -replace '^|$','"' -join ','
Add-Send $mailbox $target
}
This gives us an array with strings that look like:
"alan.alanson", "bob.bobson", "steve.stevenson"
From here I am at a loss any ideas would be much appreciated.
The obvious solution would be to pass the names one at a time, but due to a gotcha with Exchange Server every time you set send on behalf of permissions with PowerShell it wipes the existing permissions, so you only end up with he last person granted permissions being able to send on behalf of.
See this link for help with your underlying issue.
Very basically, you will have to:
get the DistinguishedName of the user you need to add
store the current value of GrantSendOnBehalfTo in a variable
append the new user's distinguished name to the list
replace GrantSendOnBehalfTo with the new list
Afterwards you should not need to pass endless strings to the EMS (I hope so).

Powershell: How do you set the Read/Write Service Principal Name AD Permissions?

In Powershell, how do you set the Read/Write Service Principal Name AD user permissions?
Normally during my build process, I use ADSIedit to navigate to that object, and then go through all the security tabs to get down to put a checkmark next to:
Read Service Principal Name
Write Service Principal Name
But navigating through ADSIedit can take a long time so I'm trying to script the process. If I have a PowerShell LDAP bind with a new user created, how can I use PowerShell to set both of these properties for this user account?
The following is a hacked out code-snippet of the possible pertinent portions of my install script:
$strDomain = "dc=my,dc=com"
$objDomain = [ADSI] "LDAP://" + strDomain
$strSCCMSQLPW = Read-Host -assecurestring "Please enter a password for the " + $strSCCMSQL + " account: "
New-ADUser -SamAccountName $strSCCMSQL + -Name $strSCCMSQL -AccountPassword $strSCCMSQLPW -Enabled $true -Path $strUsersOU + "," + $strDomain -PasswordNeverExpires $true
You need to add an ActiveDirectoryAccessRule object to the ACL of the target object. For setting property specific rigths the trick is to pass in the schemaIDGUID to the attribute. So first we need to find the schemaIDGUID from the Service-Principal-Name schema entry. In the sample code i statically refer to the Service-Principal-Name, better yet would have been to search for the ldapDisplayname to find the entry but I'm sure you can sort that out. In any case this code should do the job:
Function Set-SpnPermission {
param(
[adsi]$TargetObject,
[Security.Principal.IdentityReference]$Identity,
[switch]$Write,
[switch]$Read
)
if(!$write -and !$read){
throw "Missing either -read or -write"
}
$rootDSE = [adsi]"LDAP://RootDSE"
$schemaDN = $rootDSE.psbase.properties["schemaNamingContext"][0]
$spnDN = "LDAP://CN=Service-Principal-Name,$schemaDN"
$spnEntry = [adsi]$spnDN
$guidArg=#("")
$guidArg[0]=$spnEntry.psbase.Properties["schemaIDGUID"][0]
$spnSecGuid = new-object GUID $guidArg
if($read ){$adRight=[DirectoryServices.ActiveDirectoryRights]"ReadProperty" }
if($write){$adRight=[DirectoryServices.ActiveDirectoryRights]"WriteProperty"}
if($write -and $read){$adRight=[DirectoryServices.ActiveDirectoryRights]"readproperty,writeproperty"}
$accessRuleArgs = $identity,$adRight,"Allow",$spnSecGuid,"None"
$spnAce = new-object DirectoryServices.ActiveDirectoryAccessRule $accessRuleArgs
$TargetObject.psbase.ObjectSecurity.AddAccessRule($spnAce)
$TargetObject.psbase.CommitChanges()
return $spnAce
}
Sample lines for calling the function...
$TargetObject = "LDAP://CN=User,OU=My User Org,DC=domain,DC=net"
$Identity = [security.principal.ntaccount]"domain\user"
Set-SpnPermission -TargetObject $TargetObject -Identity $Identity -write -read
Here is an example using Quest to set the permissions on the service principal name attributes.
First, add Quest:
Add-PSSnapin Quest.ActiveRoles.ADManagement;
Set the permission (using Add-QADPermission):
Get-QADUser UserName | Add-QADPermission -Account 'SELF' -Rights 'ReadProperty,WriteProperty' -Property 'servicePrincipalName' -ApplyTo 'ThisObjectOnly';
You can use Quest AD cmdlets. It makes AD permission stuff very easy in PowerShell.
Read this blog for some examples on how to add AD permissions or even copy the AD permissions.
Just lookup Add-QADPermission and it should do your job.