I'm trying to remove orphaned user objects from all mailboxes in our Exchange server.
When I execute this command:
get-mailboxpermission * | where {$_.User -like "S-1-5-21*"} | foreach {$_.Identity.Name}
It correctly returns a list with all the mailboxes that still have orphaned user account permissions set on them.
However, when I try to remove them by doing this:
get-mailboxpermission * | where {$_.User -like "S-1-5-21*"} | remove-mailboxpermission -identity $_.Identity.Name -user $_.User -accessrights $_.AccessRights -deny:$_.Deny
It returns this error:
Cannot bind argument to parameter 'Identity' because it is null.
+ CategoryInfo : InvalidData: (:) [Remove-MailboxPermission], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Remove-MailboxPermission
What am I doing wrong?
Thanks for any help.
$_ doesn't work like that, you need to wrap the Remove-MailboxPermission statement in ForEach-Object {}:
Get-MailboxPermission * | Where-Object {$_.User -like "S-1-5-21*"} | ForEach-Object {
Remove-MailboxPermission -Identity $_.Identity.Name -User $_.User -AccessRights $_.AccessRights -Deny:$_.Deny
}
Since Exchange doesn't seem to like nested pipelines very much, you could simply to away with the parameter arguments altogether (Remove-MailboxPermission will automatically bind the permissions from the pipeline):
Get-MailboxPermission * | Where-Object {$_.User -like "S-1-5-21*"} | Remove-MailboxPermission
Related
I have a problem importing phone numbers from a CSV file based on email addresses to Active directory using a PowerShell script.
The table contains:
mail;telephoneNumber
toto#domaine.com;88888888
tata#domaine.com;99999999
here’s the code I’m running but it shows me an error message, or I don’t see why there’s this message:
Import-module ActiveDirectory
Import-CSV E: scripts list.csv |
ForEach-Object {
Write-Host "telephoneNumber $($_.telephoneNumber)"
Get-ADUser -Filter "mail -like '$($_.mail)'" |
Set-ADUser -telephoneNumber $_. telephoneNumber}
Here is the error message:
telephoneNumber
Set-ADUser: Unable to find a parameter corresponding to the name «telephoneNumber».
Character E: scripts employeeid.ps1:6: 14
+ Set-ADUser -telephoneNumber $_. telephoneNumber}
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Set-ADUser], ParameterBindingException
+ FullyQualifiedErrorId: NamedParameterNotFound,Microsoft.ActiveDirectory.Management.Commands.SetADUser
NB: I am a beginner in the subject
Thank you well in advance for your help
I tried this code too but still the same problem.
Import-module ActiveDirectory
Import-CSV "E:\scripts\liste.csv" | % {
$telephoneNumber = $_.telephoneNumber
$mail= $ail_.m
Set-ADUser $telephoneNumber -mail $mail
}
The LDAP property telephoneNumber is known as OfficePhone in PowerShell and LDAP property mail has a PowerShell equivalent called EmailAddress.
Cmdlet Set-ADUser does not have a parameter called telephoneNumber, but it does have OfficePhone, so a rewrite of your code would be
Import-Module ActiveDirectory
Import-Csv -Path 'E:\scripts\list.csv' | ForEach-Object {
$user = Get-ADUser -Filter "mail -eq '$($_.mail)'" # or use PS equivalent 'EmailAddress'
if ($user) {
Write-Host "Setting telephoneNumber $($_.telephoneNumber) for $($user.Name)"
$user | Set-ADUser -OfficePhone $_.telephoneNumber
# if you do want to use LDAP property telephoneNumber, you can use below
# $user | Set-ADUser -replace #{telephoneNumber = $($_.telephoneNumber)}
}
else {
Write-Warning "Could not find user with EmailAddress $($_.mail)"
}
}
P.S. you made some typos when posting:
E: scripts list.csv is missing the backslashes
$_. telephoneNumber has a space between the dot and the property name
start-transcript -path c:\docs\MyTranscript.txt
$WhenChangedDate = ((get-date).addmonths(-12)) #has not been modified in over a year
$domain = "Domain1"
$emptygroups = Get-ADGroup -Filter * -Properties members, whenchanged -server $domain| Where-Object {($_.members.count -eq 0) -and ($_.whenchanged -le $WhenChangedDate)} | Select-Object -last 10
#$emptygroups = Get-ADGroup -Filter * -Properties members, whenchanged -server $domain | Where-Object { ($_.members.count -eq 0) -and ($_.whenchanged -le $WhenChangedDate) -and ($_.name -notlike '*CTX*')} | Select-Object -last 10
$emptygroups.name | %{REmove-adgroup $_ -Confirm:$false -WhatIf}
Stop-transcript
I'm getting the below error for Domain1. However, it runs successfully on Domain2. Any ideas?
Remove-ADGroup : Cannot validate argument on parameter 'Identity'. The argument is null. Provide a valid value for the argument, and then try running the command again. At line:1 char:38
+ $emptygroups.name | %{REmove-adgroup $_ -Confirm:$false -WhatIf}
+ ~~
+ CategoryInfo : InvalidData: (:) [Remove-ADGroup], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.
Commands.RemoveADGroup
What you're trying to do can be accomplished using the following LDAPFilter:
"(&(!member=*)(whenChanged<=$date)(!name=*CTX*))"
& All conditions must be met.
!member=* Group without members.
whenChanged<=$date WhenChanged lower than a specified date.
!name=*CTX* Name not like CTX.
$domain = "Domain1"
$date = [datetime]::Today.AddYears(-1).ToString('yyyyMMddHHmmss.sZ')
Get-ADGroup -LDAPFilter "(&(!member=*)(whenChanged<=$date)(!name=*CTX*))" -Server $domain |
Select-Object -Last 10 |
Remove-ADGroup -Confirm:$false -WhatIf
I am trying to retrieve the membership for a specific office of one specific security group in our working environment, instead of Get-ADGroupMember which is slow and always get time-out when there is a huge user list.
My code is as below:
Import-module ActiveDirectory
**$groupinfo** = Get-ADGroup -identity "vip"
Get-ADuser -LDAPFilter '(&(objectcategory=user)(memberof='**$groupinfo.DistinguishedName**'))' -Properties office,title | where {$_.office -like 'New York'} | select name,samaccountname,office,title |Export-csv -NoTypeInformation c:\tmp\NY.csv -Delimiter ";"
I get the following error
Get-ADUser : A positional parameter cannot be found that accepts argument '**CN=vip,OU=Groups,DC=contoso,DC=com**'.
At line:2 char:2
+ Get-ADuser -LDAPFilter '(&(objectcategory=user)(memberof='$group.Dis ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-ADUser], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.ActiveDirectory.Management.Commands.GetADUser
Can anyone advise me how to use this variable $groupinfo in LDAPFilter?
Do I need a junction?
Get-ADuser -LDAPFilter '(&(objectcategory=user)(memberof=**CN=vip,OU=Groups,DC=contoso,DC=com**))' -Properties office,title | where {$_.office -like 'New York'} | select name,samaccountname,office,title |Export-csv -NoTypeInformation c:\tmp\NY.csv -Delimiter ";"
This one does work when no variable.
If you use double-quotes around the LDAPFilter, the content of the variable is used instead of the variable name literal.
Try:
Get-ADuser -LDAPFilter "(&(objectCategory=person)(objectClass=user)(memberOf=$($groupinfo.DistinguishedName)))" -Properties office,title |
Where-Object {$_.office -like '*New York*'} |
Select-Object name,samaccountname,office,title |
Export-Csv -NoTypeInformation c:\tmp\NY.csv -Delimiter ";"
Note: I have not tried to put all this in a single ling, because doing that just askes for mistakes that are hard to spot. Also, I changed (objectcategory=user) to (objectCategory=person)(objectClass=user) to make sure only user objects are returned. See Filter on objectCategory and objectClasO
Somewhat new to exchange shell. I'm wanting to run a query to return exchange resource/equipment mailboxes that matches certain conditions
Get-mailbox -RecipientTypeDetails RoomMailbox, EquipmentMailbox | foreach-object {Get-CalendarProcessing $_.alias | select identity, AllowConflicts, ConflictPercentageAllowed, MaximumConflictInstances | where {($_.MaximumConflictInstances >=1) -and ($_.AllowConflicts -eq $true) -and ($_.ConflictPercentageAllowed >=1)}} | export-csv h:\test12346.csv
But I'm getting this below error
out-file : Access to the path 'C:\Windows\System32\=1' is denied.
At line:1 char:212
+ ... nces | where {($_.MaximumConflictInstances >=1) -and ($_.AllowConflicts -eq $tru ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (:) [Out-File], UnauthorizedAccessException
+ FullyQualifiedErrorId : FileOpenFailure,Microsoft.PowerShell.Commands.OutFileCommand
I know potentially or my condition syntaxes are incorrect for the MaximumConflictInstances and or AllowConflicts paramters because when I ran the below command (partially of initial command), it works fine as expected
Get-mailbox -RecipientTypeDetails RoomMailbox, EquipmentMailbox | foreach-object {Get-CalendarProcessing $_.alias | select ide
ntity, AllowConflicts, ConflictPercentageAllowed, MaximumConflictInstances | where {($_.AllowConflicts -eq $true)}} | export-csv h:\allowC.csv
I've tried the below and now appears I'm missing something. Is someone able to help me review my code and advise what I'm missing?
Get-mailbox -RecipientTypeDetails RoomMailbox, EquipmentMailbox | foreach-object {Get-CalendarProcessing $_.alias | select identity, AllowConflicts, ConflictPercentageAllowed, MaximumConflictInstances | where {($_.AllowConflicts -eq $true) -and {($_.MaximumConflictInstances -gt 1) -OR ($_.ConflictPercentageAllowed -gt 1)}} | export-csv h:\test12346.csv
Long story short, im just trying to export all exchange room objects and equipment objects if their paramters - allowconflicts is set to TRUE, and MaximumConflictInstances & ConflictPercentageAllowed is equals to OR greater than 1 for both
Thanks
Rob
When doing a comparison, PowerShell does not use the ">=" comparison operator. It should look like this:
where-object { ($_.MaximumConflictInstances -ge 1) -and ($_.AllowConflicts -eq $true) -and ($_.ConflictPercentageAllowed -ge 1)}
You can review the PowerShell comparison operators here: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_comparison_operators?view=powershell-6
I have a requirement to create and update a distribution list for a specific manager and 2 levels down of direct reports. I admit I am not a creative person so I used powershell and did it the best way I could think to do it. The problem is this will be scheduled to run every couple weeks to update the list so it needs to see if a user exists, if not then add him. in the "If" statement to do this I am running into errors when running the script, but if I pull the section of code out and just run manually in powershell it works.
My Execution policy is set to unrestricted so I do not think that is the issue.
We are running Powershell 2 and Unfortunately I can't change that.
Here is my script and the error I am getting.I realize two strings do not match in the lower part of the code, even though they both do the same thing to different files. If I ever get past errors in the first one I should be able to put the same code in both for it to work. Any help would be greatly appreciated.
$Identity="User"
$Listname="Global-Leader"
# This Script will work from a specified Manager and get his direct reports down 2 Levels then #add them to a specified list. This Script works in the AD Module.
# ====================
#| My Company
#| SCRIPT NAME: Leader
#| VERSION: 1
#| VERSION DATE: 3/24/2015
#| AUTHOR: Powershell Rookie
#====================
#load ActiveDirectory module If not already loaded.
if (!(Get-Module -Name ActiveDirectory)) {import-module ActiveDirectory}
Get-AdUser $Identity -properties DirectReports | Select-Object -ExpandProperty DirectReports | Get-ADUser -Property * | Select SamAccountName, DisplayName, Office | Export-csv c:\work\leaders.csv
Import-Csv c:\work\Leaders.csv | ForEach-Object {Get-AdUser $_.SamAccountName -Property DirectReports | Select-Object -ExpandProperty DirectReports | Get-Aduser -Property * | Select SamAccountName, DisplayName, Office} | Export-csv c:\work\leaders1.csv
Import-csv C:\work\leaders.csv | Foreach-Object If (!(Get-ADUser $_.SamAccountName –properties MemberOf).MemberOf –like “$listname”) {Add-ADGroupMember $listname –member $_.samAccountName}
Import-csv C:\work\leaders1.csv | Foreach-Object If ((Get-ADUser $_.SamAccountName –properties MemberOf).MemberOf –like “$listname”) {Add-ADGroupMember $listname –member $_.samAccountName}
if ((Get-ADUser $user -Properties MemberOf).memberOf -like "$listName") {
Write-Host -ForegroundColor Green "$user is already a member of $listName"
} else {
Write-Host -ForegroundColor Yellow "Adding $user to $listName"
Add-ADGroupMember $ListName -member $user
}
And here is the error I keep getting:
[PS] C:\work>.\leader.ps1
Unexpected token '{' in expression or statement.
At C:\work\leader.ps1:25 char:143
+ Import-csv C:\work\leaders.csv | Foreach-Object If (!(Get-ADUser $_.SamAccountName â?"properties MemberOf).MemberOf â?"like â?o$listnameâ
??) { <<<< Add-ADGroupMember $listname â?"member $_.samAccountName}
+ CategoryInfo : ParserError: ({:String) [], ParseException
+ FullyQualifiedErrorId : UnexpectedToken
Quick answer when using -like you need to be less specific with your criteria.
-like "*$Listname*"
Like is looking for that specific text at the beginning of the item to be
searched. If that item can appear anywhere in the memberof then you need to either add the wildcards or use -match instead. -match implies * around your search item.
Since most responses from that command should start with
CN=
Your member group will not be the first thing it finds
Hope that helps
Difference between -like and -match