Get description of second OU/CN - powershell

I have following script:
Get-ADUser -Filter {SamAccountName -like "z*"} -Properties * | select samaccountname, name, Email
Address, #{Name="LastLogonTimeStamp";Expression={([datetime]::FromFileTime($_.LastLogonTimeStamp))}}, #{n='ParentContai
ner';e={$_.distinguishedname -replace '^.+?,(CN|OU.+)','$1'}} | Format-Table
RESULT EXAMPLE
How to get description of second OU|CN container?

Try:
$_.DistinguishedName -replace '^.+?,((CN|OU)=[^,]+).*','$1'
Note the trailing .*, which ensures that the regex matches the entire input string and replaces it with the substring of interest as a whole; without .*, only part of the input would be replaced, followed by whatever part of the original that didn't match.
This assumes that all components are ,-separated (not sure why your images shows a . after the 2nd OU component) and that the CN/OU values have no embedded, escaped , instances.
You could make the inner (...) subexpression - whose match needn't be captured - slightly more efficient with (?:...).

Related

How to find UPN that contains digit?

i would like to know how to find UPN that constain digit with -filter?
Get-ADUser -filter {(UserPrincipalName -contains "I dont know what i should add here #contoso.com")} -properties userprincipalname | select userprincipalname
The -Filter argument of AD cmdlets, which accepts a string, uses PowerShell-like syntax, but with only a limited subset of supported operators, some of which work in subtly different ways than in PowerShell.
The filter language is not sophisticated enough to do the matching you want: the only pattern matching supported is via wildcards, which are limited to use of *, using the -like operator.[1]
Therefore, use -Filter for pre-filtering with -like, then use a Where-Object call to let PowerShell filter the results down, using its regex capabilities:
Get-ADUser -Filter 'UserPrincipalName -like "*#contoso.com"' -Properties UserPrincipalName |
Where-Object UserPrincipalName -match '\d'
Select-Object UserPrincipalName
Note:
-match '\d' matches if at least one digit (\d) is present in the input.
I've used a string rather than a script block ({ ... }) to specify the -Filter argument, because that's what -Filter expects. While seductively convenient, the use of script blocks is conceptually problematic and can lead to misconceptions - see this answer.
[1] By contrast, PowerShell's -like operator supports PowerShell's more fully-featured wildcard expressions. Also, the AD -Filter's language at least situationally interprets * to mean: at least one character, whereas PowerShell's wildcard expression interpret it as zero or more.

How to query the Active Directory using a list of users in a text file for a specific attribute with PowerShell

I'm somewhat basic to Powershell and use one-liner commands only to keep it short and basic.
I would like to do the following: I have a list of users in a text file in the form of UserPrincipalName. I'd like to query this list of users if their accounts are still active/enabled or not. To do so, I'm trying to run the following command, which just reveals nothing in the end (blank output):
gc .\users.txt | foreach {get-aduser -server "corp.xxx.com"
-f 'name -like "$_"' -properties *}| select displayname,enabled
As mentioned, the output is blank with no errors or whatsoever.
I read that aduser doesn't work with pipelines, but I need to find a solution.
Kindly request your support :)
Thanks
Your use of single quotes in your filter is not allowing the expansion of the variable. Double-quotes should be wrapping the filter expression so as to allow the interpolation of the automatic variable $_:
Get-ADUser -Filter "name -like '$_'" ...
Single-quoted strings:
A string enclosed in single quotation marks is a verbatim string. The string is passed to the command exactly as you type it. No substitution is performed.
Also note, you mention in your question that the file has the user's UserPrincipalName attribute, yet you're querying the Name attribute, if that's the case, the filter should be:
Get-ADUser -Filter "UserPrincipalName -eq '$_'" ...
Note the use of -eq instead of -like, for exact matches you should always use this operator, see about_ActiveDirectory_Filter for usage details and examples of each operator.
If you're only interested in DisplayName and Enabled for your output, there is no reason in querying all the user's attributes, -Properties * should be just -Properties DisplayName since Enabled is already part of the default attributes returned by Get-ADUser.
Finally, the -Identity parameter can be bound from pipeline, and this parameter accepts a UserPrincipalName as argument, hence ForEach-Object is not needed in this case:
Get-Content .\users.txt |
Get-ADUser -server "corp.xxx.com" -Properties DisplayName |
Select-Object DisplayName, Enabled

Powershell property select adding whitespace and header

I am trying to write a script to pull all e-mail addresses but I am finding that the output of my first get command is adding alot of white space to the result text file
Get-AdUser -Filter * -Properties * | Select EmailAddress | Out-File "C:\T2\EMailAddresses.txt"
Can anyone tell me what I am doing wrong here?
You are seeing whitespace because not every AD account has a value assigned to that property in your environment so it appears as a blank line, I get the same thing upon a quick test.
This should help.
$Emails = Get-ADUser -Filter * -Properties EmailAddress
$Emails | select EmailAddress | Where {$_.EmailAddress -ne $null} | Out-File "C:\T2\EMailAddresses.txt"
td;dr
The following writes all email addresses to the target file, ignoring AD users that don't have one:
([string[]] (Get-AdUser -Filter * -Properties EmailAddress).EmailAddress) -ne '' |
Set-Content C:\T2\EMailAddresses.txt
By writing just the - non-empty - .EmailAddress property values to the file, you're avoiding the problems that stem from saving for-display formatted object representations, which is what your attempt does (see below).
Note that -ne '' acts as a filter here, because its LHS operand is an array; that is, the result of the operation is the sub-array of those LHS elements that aren't the empty string ('').
As for what you tried:
By using Out-File in combination with objects subject to PowerShell's output formatting system, you're saving a for-display representation of your objects to a file, which, in the case at hand includes a table header, a leading and a trailing blank line and - in Windows PowerShell (but no longer in PowerShell (Core) 7+) - right-space-padding to the full console-line width of each line.
Even though you're only asking for one property - EmailAddress - Select-Object outputs not just that property's value for each input object, but a [pscustomobject] instance with an .EmailAddress property, and the resulting objects are implicitly formatted with Format-Table.
To get just the EmailAddress property values, use Select-Object -ExpandProperty EmailAddress. The resulting string values are not subject to formatting, so your command would work as intended except that it would still include $null values from those AD users who happen not to have a value stored in their .EmailAddress property.
While it often won't matter, for string input it's slightly faster to use Set-Content than Out-File / >; note that in Windows PowerShell you'll end up with different character encodings by default (ANSI vs. UTF-16 LE a.k.a "Unicode") - use the -Encoding parameter as needed; PowerShell Core 7+ fortunately now consistently defaults to BOM-less UTF-8.
The - faster, but more potentially memory-intensive - alternative to using Select-Object -ExpandProperty EmailAddress for extracting the EmailAddress property values is to use member-access enumeration ((...).EmailAddress, as shown above).

Using Variables in Powershell Get-ADUser -Filter

Can someone assist me on proper quoting, I need the wild cards beside the varibles for first and last name in a Get-ADUser -Filter search
I believe I need to escape the single quotes but can't get a successful return.
$LastADname = John
$FistADname = Doe
Get-ADUser -Filter "Name -like `*$LastADname`*$FirstADname`*"
Returns: Get-ADUser : Error parsing query: 'Name -like *Doe*John*' Error Message: 'syntax error' at position 12
This lets me know it did resolve the variable but not the *. If I wrap all in single quote to double quote the variables and *'s it won't resolve variables. Like below
$LastADname = John
$FistADname = Doe
Get-ADUser -Filter 'Name -like "*$LastADname*$FirstADname*"'
I belive this becusae the above resolves but no vaule produced. When I substite the var for text it produces results
Get-ADUser -Filter 'Name -like "*Doe*John*"'
You need to wrap the internal filter string with single quotes:
Get-ADUser -Filter "Name -like '*$LastADname*$FirstADname*'"
You don't need the ` to escape the * character. The second attempt with single-quotes ' wrapping the outer string didn't work because single-quoted strings are rendered literally. Double-quoted " strings allow you to expand variables, use escape-sequences with `, and return sub-expressions within a string.
However, if the target field value contains a ' (or may contain, if controlled by a variable), such as with the name O'Niel, this will break the internal query, as the ' will be parsed as the end of the search term and will result in an error since what follows will almost certainly not be valid expression syntax. Fortunately, escaping quotes is easy and you don't need to worry about using the ` character to escape.
Consider the following example, where we want to find all users whose name field contains the O' string, like with the O'Niel example above. In this example, the search term is provided with a variable, like in the OP's use case. Simply use double-quotes for the -Filter string, and provide "" for the internal quotes as well (this is rendered identically to `"):
$term = "O'Niel"
Get-ADUser -Filter "Name -like ""*$term*"""
This doesn't break the internal query because now " signify the term boundary instead of '.
Note: If your search term contains ", you will need to escape instead for that. If your search term contains both ' and ", you can't use -Filter to search for that specific term. However, you can utilize -LDAPFilter for this since quotes are not used as the search term bounds.
Things get a bit more complicated when you are searching fields that return a DistinguishedName, but I won't clutter this answer with those details. Read the above link for more information, I will eventually be updating my linked answer at the bottom with more information about escape sequences and DN/CN filtering.
See this answer I wrote for more information about using the -Filter parameter effectively with the RSAT AD cmdlets. I have updated that answer with more complete information on filter escapes and handling the "names with quotes" cases.

PowerShell Customer header containing AD query

I am attempting to get these Custom headers to display correctly when bringing in content from Import-CSV
The CSV contains a column titled Surname with a Surname in each row, it also contains a header titled "Email" with no data in any of the cells below.
$csv = Import-csv C:\temp\tester.csv
$csv | select Surname,#{Name='Email';Expression={Get-ADUser -Filter 'Surname -like "$_.Surname"' | Select -ExpandProperty UserPrincipalName}}
executes correctly when I hardcode the surnames in. Any ideas?
You enclose the filter in single quotes, this prevents Powershell from substituting $_.Surname for a value. If a string is enclosed in single quotes, it is treated as is, without any attempts to replace symbols, including escape symbols, prior to passing the string as an argument or an expression result. Replace the expression with this:
Expression={Get-ADUser -Filter "Surname -like `"$_.Surname`"" | Select -ExpandProperty UserPrincipalName}
The backticks are used to escape the quotes that should be passed into AD filter.