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..
Related
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"}
}
I have a list of potential account ids. I would like to use Get-ADUser to query if the account or a variation of it exists in the environment. I would then like to capture the data including which accounts ids from my original list don't have any accounts in the environment.
I have successfully captured data for account ids that have an account or a variation of the account id in the AD environment. I am having difficultly with capturing the account ids from my original list that do not produce any results using Get-ADUser
foreach ($user in $inputdata)
{$user = $user + "*"
$(try {Get-ADUser -filter {SamAccountName -like "$user"} -properties Description} catch {$null}) | % {if ($_ -ne $null) {[pscustomobject]#{"ID"=$_.SamAccountName;"DN"=$_.DistinguishedName;"Desc"=$_.Description}}
else {$noaccount += $user}
}
My pscustomobject populates properly with data from everyone that does have an account. But there are no values in $noaccount even though there are ids in my list that do not have accounts in the environment. What should I do to capture the instances which do not have accounts using Get-ADUser?
Also, no error is outputted.
The following should achieve what you want.
$noaccount = [Collections.Generic.List[String]] #()
foreach ($user in $inputdata) {
$userToCheck = Get-ADUser -Filter "SamAccountName -like '$user*'" -properties Description
if ($userToCheck) {
[pscustomobject]#{"ID"=$userToCheck.SamAccountName
"DN"=$userToCheck.DistinguishedName
"Desc"=$userToCheck.Description
}
}
else {
$noaccount.Add($user)
}
}
Explanation:
$noaccount is initialized as a generic list of strings so that we can use the .Add() method rather than the inefficient += operator.
$userToCheck will contain a found user object or $null depending on whether the query found a result. If a user is found, the if condition is $true and your custom object is output. If no user is found, the else condition is triggered and the data stored in $user is added to the $noaccount collection.
I changed the -Filter slightly to remove the script block notation because it is not a script block. The online documentation of the command teaches bad habits by demonstrating the use of script block notation. Instead the filter should be surrounded by double quotes with the values on the inside surrounded by single quotes. The double quotes will allow for PowerShell interpolation to expand variable within. The single quotes will be passed in literally so that the value is interpreted as a string by Get-ADUser.
With your attempt, the try {} block would rarely throw an error and would not throw an error just because an account was not found. You would have to remove the -Filter in favor of the -Identity parameter to produce errors when no object is found. You will still see errors if there are connectivity issues between your session and the domain server though. When your Get-ADUser command produced no output, nothing would get piped into the the foreach {} script block. Therefore, your if {} else {} would never be evaluated.
Enhancement Considerations:
Following some insight provided by Lee_Dailey, instead of adding the not found accounts to a separate collection, you could incorporate them into your custom object output. Maybe you could add a new property that states whether or not they are found. See below for an example:
$noaccount = [Collections.Generic.List[String]] #()
foreach ($user in $inputdata) {
$userToCheck = Get-ADUser -Filter "SamAccountName -like '$user*'" -properties Description
if ($userToCheck) {
[pscustomobject]#{"User" = $user
"ID"=$userToCheck.SamAccountName
"DN"=$userToCheck.DistinguishedName
"Desc"=$userToCheck.Description
"In_AD" = "Yes"
}
}
else {
[pscustomobject]#{"User" = $user
"ID"=$null
"DN"=$null
"Desc"=$null
"In_AD" = "No"
}
}
}
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!
A trivial question, but hopefully really obvious for those who know.
Search constructor:
$Search = New-Object System.DirectoryServices.DirectorySearcher
(([adsi]"LDAP://ou=Domain Users,dc=example,dc=pri"),'(objectCategory=person)',
('name','employeeID'))
I want to exclude results where the employeeID attribute does not exist.
This works:
$users = $Search.FindAll()
ForEach ($u in $users) {
If ($u.properties.employeeid) {
Write-Host $($u.properties.name)
}
}
The following does not work - no output. However, when the IF statement is omitted, results are output.
ForEach ($user in $($Search.FindAll())) {
If ($user.properties.employeeID) {
Write-Host $($user.properties.name)
}
}
Is it a syntax issue in the second example, or do I just need to temporarily store results in an object before running conditional statements on them?
(To circumvent any discussion on why not use the ActiveDirectory module and Get-ADUser, it's for a user that cannot have the module installed on their workstation, nor be granted perms to invoke it via a PSSession on a host where it is installed.)
Update: found a slightly nicer way of doing the where clause:
$searcher.FindAll() | where { ($_.properties['employeeid'][0]) }
Just remove if statement and filter search results:
$users = $Search.FindAll() | Where-Object {-not [string]::IsNullOrEmpty($_.properties.employeeID)}
I'm writing a script to bulk add users from a CSV, then add groups from another user.
It's working fine, except that some groups i'm not able to add (I get access denied when using the AD MMC - we have to get a different group to add them for us). The problem is that Add-QADGroupMember silently fails. I would like to somehow catch the error and list the groups that I have to get added by the different group.
I've tried try/catch, but it doesn't work... i'm at a loss.
Here is the code at the moment:
$users = Import-Csv .\UserList.csv
foreach ($user in $users) {
$SameAs = $user.SameAs
$UserGroups = (Get-QADUser $SameAs).MemberOf
foreach ($group in $UserGroups) {
Add-QADGroupMember $group -Member $user.SamAccountName |Out-Null
}
}
I'm just not able to get it to throw an error or exception when it fails to add a group.
Thanks for any help.
You have to set the erroraction to "stop".
I had the same problem with PowerCLI and all commands from there.
Try it so:
Add-QADGroupMember $group -Member $user.SamAccountName -ErrorAction Stop |Out-Null
or you can set the ErrorActionPreference global with
$ErrorActionPreference = "Stop"