Powershell Filter doesn't accept comma - powershell

I try to use the Get-User command with a simple Filter.
Get-User -Filter "(Manager -eq 'Max, Mustermann')"
The problem is that i get this exception:
Cannot bind parameter 'Filter' to the target. Exception setting "Filter": "The value "Max, >Mustermann" could not be converted to type
Microsoft.Exchange.Data.Directory.ADObjectId.
"(Manager -eq 'Max, Mustermann')" at position 34."
In C:\Users\JAKO\AppData\Local\Temp\tmp_4vtu0s13.ymv\tmp_4vtu0s13.ymv.psm1:38356 Zeichen:9
$steppablePipeline.End()
~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : WriteError: (:) [Get-User], ParameterBindingException
FullyQualifiedErrorId : >ParameterBindingFailed,Microsoft.Exchange.Management.RecipientTasks.GetUser
As far as I understand the Problem its because of the comma, so i tryed some workaorunds.
Get-User -Filter "(Manager -like 'Max, Mustermann')"
Here I dont get an exception but there are no Users that get returned.
Get-User -Filter "(Manager -eq 'Max"," Mustermann')"
The same as with the other workaround. No exception but no Users are Matching.
I also made sure that i have Users that would match this specift query, by using this command
Get-User -Filter | Format-List Manager
How can I write my Filter input so it matches "Max, Mustermann"?

From the filtering documentation for the Manager attribute:
This filter requires the distinguished name or canonical distinguished name of the manager (a mailbox or mail user). For example, Get-User -Filter "Manager -eq 'CN=Angela Gruber,CN=Users,DC=contoso,DC=com'" or Get-Mailbox -Filter "Manager -eq 'contoso.com/Users/Angela Gruber'".
To find the distinguished name of a manager, replace with the name, alias, or email address of the recipient, and run this command: Get-Recipient -Identity "<RecipientIdentity>" | Format-List Name,DistinguishedName.
So now we know why the filter isn't working (a distinguished name is expected), and how to obtain the correct value (by using Get-Recipient):
# Fetch manager's user account object
$targetUser = Get-Recipient -Filter "SimpleDisplayName -eq 'Max, Mustermann'"
# Fetch reports
Get-User -Filter "Manager -eq '$($targetUser.DistinguishedName)'"

Related

Get AD user properties from Active Directory

I am trying to filter the values of a property in Active Directory.
I tried:
Get-ADUser -filter * -Properties physicalDeliveryOfficeName | Where-Object (($_.physicalDeliveryOfficeName -like "NICE")) | Select-Object physicalDeliveryOfficeName, name
Get-ADUser -filter * -Properties physicalDeliveryOfficeName | Select-Object physicalDeliveryOfficeName, name | Where-Object (($_.physicalDeliveryOfficeName -like "NICE"))
I did not get any errors, but no results either.
I searched all users with physicaldeliverofficename is (myvalue). I would like to display name and office.
You have a syntax problem:
The Where-Object's (positionally implied) -FilterScript parameter expects a script block argument - { ... } - not a parenthesized expression ((...)).[1]
Therefore:
# Note the { ... } around the expression passed to Where-Object
Get-ADUser -Filter * -Properties physicalDeliveryOfficeName |
Where-Object { $_.physicalDeliveryOfficeName -eq "NICE" } # | ...
Note: Since "NICE" is a literal string rather than a wildcard pattern, I've used the -eq instead of the -like operator. If you doe need to find "NICE" as a substring, use something like -like "*NICE*" or, for case-sensitive matching, -clike "*NICE*", as Mathias R. Jessen suggests.
Note that you may alternatively use simplified syntax, which obviates the need for a script block and allows use of individual parameters (also note the absence of $_., which is implied):
Get-ADUser -Filter * -Properties physicalDeliveryOfficeName |
Where-Object physicalDeliveryOfficeName -eq "NICE" # | ...
Taking a step back:
Santiago Squarzon suggests performing the filtering at the source, by using Get-ADUser's -Filter or -LDAPFilter parameter, which is much more efficient; e.g.:
Get-ADUser -Filter 'physicalDeliveryOfficeName -eq "NICE"'
As an aside: There are many examples out there that use script-block syntax with -Filter (-Filter { ... }), but the -Filter parameter accepts a string and that string, even though it supports PowerShell-like syntax, is interpreted by the AD provider, so it's better to pass a string to begin with - see this answer for more information.
[1] If you use (...), the expression's value gets bound to the -Property parameter instead, and is therefore interpreted as a property name whose value - assuming such a property even exists - is interpreted as a Boolean that determines whether the input object at hand should be filtered in or not. If the expression doesn't evaluate to the name of a property that exists on an input object, $false is implied, and the input object is filtered out. In your case, this predictably resulted in no objects being filtered in and therefore no output.
The Select-Object cmdlet is used to select only the columns you want from a larger object or list.
For instance:
C:\git\Core> gsv Spooler | fl
Name : Spooler
DisplayName : Print Spooler
Status : Running
DependentServices : {Fax}
ServicesDependedOn : {RPCSS, http}
CanPauseAndContinue : False
CanShutdown : False
CanStop : True
ServiceType : Win32OwnProcess, InteractiveProcess
Get-Service returns Service Objects which have a lot of properties. If I only want certain ones, I'd use it like so:
C:\git\Core> gsv Spooler | Select Name,Status
Name : Spooler
Status : Running
You're using the cmdlet and probably discarding the columns which have the values you need. Run your one-liner again and remove the Select-Object cmdlet to see all of the columns availble, till you find the one that pertains to the Office.

Issue for import-csv and foreach

I want to import a csv, then delete from AD several objects
$ImportComputer = "C:\Users\deng\Desktop\ComputerLastlogondateformatBis.csv"
Import-Module ActiveDirectory
foreach ($Computer in(Import-Csv -Path C:\Users\deng\Desktop\ComputerLastlogondateformatBis.csv))
{
Remove-ADObject -Identity $Computer.'Computer'
these two object exist in AD, but I cannot seem to find out why it is not working.
see below error message:
Remove-ADObject : Cannot find an object with identity: 'fr-borr-mac' under: 'DC=PII,DC=net'.
At C:\Users\deng\OneDrive - Aptus Health\Script\Export.ps1:7 char:1
+ Remove-ADObject -Identity $Computer.'Computer'
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (fr-borr-mac:ADObject) [Remove-ADObject], ADIdentityNotFoundException
+ FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,Microsoft.ActiveDirectory.Management.Commands.RemoveADObject
Remove-ADObject : Cannot find an object with identity: 'jlinmacfr' under: 'DC=PII,DC=net'.
At C:\Users\deng\OneDrive - Aptus Health\Script\Export.ps1:7 char:1
+ Remove-ADObject -Identity $Computer.'Computer'
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Content of the CSV below:
Computer
--------
fr-borr-mac
jlinmacfr
Could anyone give input on this?
The -Identity parameter on the *-ADObject commands expect either a DistinguishedName or Guid value. If you are wanting to work with SamAccountName or some other attribute, you should consider using the *-ADComputer or using -Filter to find your objects.
# Using Remove-ADObject
Remove-ADObject -Filter "SamAccountName -eq '$($Computer.Computer)'"
# Using Remove-ADComputer
Remove-ADComputer -Identity $Computer.Computer
Alternatively, you can use Get-ADComputer or Get-ADObject to retrieve your object first and then pipe that into Remove-ADObject.
Get-ADObject -Filter "SamAccountName -eq '$($Computer.Computer)'" | Remove-ADObject
See the Remove-ADObject documentation for the following excerpt regarding explicitly binding to -Identity:
Specifies an Active Directory object by providing one of the following
property values. The identifier in parentheses is the Lightweight
Directory Access Protocol (LDAP) display name for the attribute. The
acceptable values for this parameter are:
A distinguished name
A GUID (objectGUID)
For piping an object into Remove-ADObject, the following excerpt applies, which is why you can use a Get-AD* command and pipe the result into the Remove-ADObject:
This parameter can also get this object through the pipeline or you
can set this parameter to an object instance.
Derived types, such as the following, are also accepted:
Microsoft.ActiveDirectory.Management.ADGroup
Microsoft.ActiveDirectory.Management.ADUser
Microsoft.ActiveDirectory.Management.ADComputer
Microsoft.ActiveDirectory.Management.ADServiceAccount
Microsoft.ActiveDirectory.Management.ADFineGrainedPasswordPolicy
Microsoft.ActiveDirectory.Management.ADDomain

How do I fix this script?

I am trying to get this short script to work and I don't understand why, PowerShell gives somewhat garbled and useless error messages!
Script:
$us = Read-Host 'Enter Your User Group Name:' |Get-ADGroup -Filter {name -like "*$us*"} -Properties Description,info | Select Name | Sort Name
Error:
Get-ADGroup : The input object cannot be bound to any parameters for the
command either because the command does not take pipeline input or the input
and its properties do not match any of the parameters that take pipeline input.
At line:1 char:42
+ ... ser Name:' |Get-ADGroup -Filter {name -like "*$us*"} -Properties Desc ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (River:PSObject) [Get-ADGroup], ParameterBindingException
+ FullyQualifiedErrorId : InputObjectNotBound,Microsoft.ActiveDirectory.Management.Commands.GetADGroup
You can't pipe your string definition to the filtered commandlet in that manner. Declare the variable first.
Once you;ve done that, filter as required then select the properties you need (Description property is needed as it isn't returned by default by the commandlet whilst the Name property is).
$us = Read-Host 'Enter Your User Group Name:'
Get-ADGroup -filter "Name -like '*$us*'" -Properties Description | Select-Object Name , Description | Sort-Object Name
The problem is $US is not set until the end of the pipeline, and therefore is empty.
Try:
$us = Read-Host 'Enter Your User Group Name:' | # get the name
%{"*$($_)*"} | # Add the asterisk wildcard.
%{Get-ADGroup -filter {name -like $_}} | # read from AD
Select Name |
Sort Name
This will ask you for the group name, and then save the results to the pipeline (not to $us). The pipeline value is used to then add your asterisks and then again output the value to the pipeline, before the pipeline is then used for the Get-Adgroups commmand.
Once the results of the lookup is returned, it is cleaned up, and reduced to just name, then sorted to give you a list of names in sorted order.
The "-Properties Description,info" isn't needed because all you want is the name, so why requested description or info fields?
I just tested this, and despite what Ansgar Wiechers said, this does work. If this answer helps you, please vote it up.

Use modified property of object as parameter in Powershell for Set-MailPublicFolder

When we create a public folder and mail enable in Exchange Online, the default email address is #domain.onmicrosoft.com
Our folder names are "NNNNN_Folder name" where NNNNN is a 5 digit number.
I would like to set the primary email address of the public folder to NNNNN#domain.com
I have tried many variations of this:
Get-PublicFolder -Recurse -Identity "\X\Y\Z"|
Sort-Object Identity –Descending|
Select-Object -first 4|
Set-MailPublicFolder -PrimarySmtpAddress {$_.name.substring(0,5)+"#domain.com"}
and receive errors about interpreting the resulting email address:
Cannot process argument transformation on parameter 'PrimarySmtpAddress'. Cannot convert value
"$_.name.substring(0,5)+"#domain.com"" to type "Microsoft.Exchange.Data.SmtpAddress". Error: "The email
address "$_.name.substring(0,5)+"#domain.com"" isn't correct. Please use this format: user name, the # sign,
followed by the domain name. For example, tonysmith#contoso.com or tony.smith#contoso.com."
+ CategoryInfo : InvalidData: (:) [Set-MailPublicFolder], ParameterBindin...mationException
+ FullyQualifiedErrorId : ParameterArgumentTransformationError,Set-MailPublicFolder
+ PSComputerName : outlook.office365.com
I also tried setting the EmailAddress of the PublicFolder to NNNNN#domain.com in the same operation.
-EmailAddresses #{$_.name.substring(0,5)+"#domain.com"}
It doesn't seem to be evaluating the argument or I'm missing something else?
If I change Set-MailPublicFolder ... with
% {$_.name.substring(0,5) + "#domain.com"}
I do see the email addresses I am expecting.
Thanks,
Craig.
See this version.
From Microsoft command documentation, the identity parameter is required (see this)
I am also not sure it can take the array and process each individual without specifying a foreach.
See this modified versions.
$PublicFolders = Get-PublicFolder -Recurse -Identity "\X\Y\Z"| Sort-Object Identity –Descending | Select-Object -first 4
$PublicFolders | foreach {
$NewEmail = "$($_.name.substring(0,5))#domain.com"
Write-Host "Settings MailPublicFolder with name $($_.Identity) to $NewEmail" -ForegroundColor Cyan
Set-MailPublicFolder -Identity $_.Identity -PrimarySmtpAddress $NewEmail
}

How to list AD group membership for AD users using input list?

I'm fairly new PS user... Looking for some assistance with a powershell script to obtain list of security groups user is member of.
To describe what I need:
I have input list (txt file) with many users (samaccountnames). Every name is on a new line.
I need the script to search these names in AD - whole forest, not just one single domain
output should look like "samaccountname" and list of groups this account is member of in one line, so I can sort it in excel
This is the script I have:
$users = Get-Content C:\users.txt
ForEach ($User in $users) {
$getmembership = Get-ADUser $User.Users -Properties MemberOf | Select -ExpandProperty memberof
$getmembership | Out-File -Append c:\membership.txt
}
but it throws me an error:
Get-ADUser : Cannot validate argument on parameter 'Identity'. The argument is null. Supply a non-null argument and try the command again.
At line:4 char:28
+ $getmembership = Get-ADUser <<<< $User.Users -Properties MemberOf | Select -ExpandProperty memberof
+ CategoryInfo : InvalidData: (:) [Get-ADUser], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.GetADUser
Anyway, this script wouldn't search the whole forest.
Sample input list:
username1
username2
username3
username4... etc
Sample output list
username1;group1;group2;group3
username2;group1;group2;group3;group4... etc or something similar
Any help would be greatly appreciated.
First: As it currently stands, the $User variable does not have a .Users property. In your code, $User simply represents one line (the "current" line in the foreach loop) from the text file.
$getmembership = Get-ADUser $User -Properties MemberOf | Select -ExpandProperty memberof
Secondly, I do not believe you can query an entire forest with one command. You will have to break it down into smaller chunks:
Query forest for list of domains
Call Get-ADUser for each domain (you may have to specify alternate credentials via the -Credential parameter
Thirdly, to get a list of groups that a user is a member of:
$User = Get-ADUser -Identity trevor -Properties *;
$GroupMembership = ($user.memberof | % { (Get-ADGroup $_).Name; }) -join ';';
# Result:
Orchestrator Users Group;ConfigMgr Administrators;Service Manager Admins;Domain Admins;Schema Admins
Fourthly: To get the final, desired string format, simply add the $User.Name, a semicolon, and the $GroupMembership string together:
$User.SamAccountName + ';' + $GroupMembership;
Get-ADPrincipalGroupMembership username | select name
Got it from another answer but the script works magic. :)
Or add "sort name" to list alphabetically
Get-ADPrincipalGroupMembership username | select name | sort name
Everything in one line:
get-aduser -filter * -Properties memberof | select name, #{ l="GroupMembership"; e={$_.memberof -join ";" } } | export-csv membership.csv
The below code will return username group membership using the samaccountname. You can modify it to get input from a file or change the query to get accounts with non expiring passwords etc
$location = "c:\temp\Peace2.txt"
$users = (get-aduser -filter *).samaccountname
$le = $users.length
for($i = 0; $i -lt $le; $i++){
$output = (get-aduser $users[$i] | Get-ADPrincipalGroupMembership).name
$users[$i] + " " + $output
$z = $users[$i] + " " + $output
add-content $location $z
}
Sample Output:
Administrator Domain Users Administrators Schema Admins Enterprise Admins Domain Admins Group Policy Creator Owners
Guest Domain Guests Guests
krbtgt Domain Users Denied RODC Password Replication Group
Redacted Domain Users CompanyUsers Production
Redacted Domain Users CompanyUsers Production
Redacted Domain Users CompanyUsers Production