Troubles with substring, trim, trimend - powershell

I'm trying to take an array of email addresses (in the form of username#company.com) which is generated from:
$users = get-MSOLUser -All | where {$_.isLicensed -eq "TRUE" -and $_.Licenses.AccountSKUID -eq "my_license"} | select userprincipalname
And get just the username from each. I start with username#company.com and want to end up with username. I have tried various ways using substring, Trim, TrimEnd, etc and can't get any of them working.
$username = $users | %{$_.substring(0,$users.length - 12)}
$users | %{$_.trimend("#company.com")}
$users | %{$_.trimend(12)}
All of the above give errors including the two below.
Method invocation failed because [Selected.Microsoft.Online.Administration.User] does not
contain a method named substring.
Method invocation failed because [Selected.Microsoft.Online.Administration.User] does not
contain a method named trimend.
What am I doing wrong with the syntax, or is there something else, like a module I haven't imported, or how my syntax is trying to work with an array?

This will return you a list of all usernames (without domain) that fulfills your conditions:
$users = Get-MSOLUser -All |
Where-Object {$_.isLicensed -eq "TRUE" -and $_.Licenses.AccountSKUID -eq "my_license"} |
ForEach-Object { $_.userprincipalname -replace '#.*' }

Well, you need to work with the property, not with the object, so you would probably want to do something like:
select -expandproperty userprincipalname
but that would create an array of userprincipalnames, so no other attributes.
When you run get-MSOLUser you get back an object, with a bunch of properties. When you do select -expandproperty you are getting back only certain property, but not an object itself. You are getting back a system.string object. And that object has all those methods you are trying to invoke.

Related

Powershell - Issues to test a value in a list

I have a 2 variables:
$Listgivenname = Get-aduser -filter * | Select-Object givenname
$Usergivenname = "Tom"
Actually, Tom is in $Listgivenname, so I decided to make an if statement like:
If($Listgivenname -contains $Usergivenname) {Write-Host "blablabla"}
But actually this command outputs false, even with $Usergivenname -in $Listgivenname.
The weird part comes when I choose to manually write the list in $Listgivenname, like "Tom", "Jerry". It actually works, so I believe there's a thing that I need to understand about a command witch I assign to a variable.
Get-aduser -filter * | Select-Object givenname doesn't seem to work like a manually written list.
I don't ask for solutions but I'm trying to understand why this happens.
try add -ExpandProperty (to get the values of each object):
$Listgivenname = Get-aduser -filter * | Select-Object -ExpandProperty givenname

Filter Records on Multiple Values

I have to get a list of AD users where the Manager field contains one of the following names on my FilterValues list.
I see that someone recommended to use the Where-Object, however when I run the script nothing gets returned. I have tried many approaches but I can't seem to find where I am going wrong. Any advise will be greatly appreciated, TIA.
$FilterValues = $('Williams', 'Smith', 'Johnson')
Get-ADUser -Filter "extensionAttribute10 -like '1.0'" -Properties *
| Where-Object {$_.Manager -contains $FilterValues}
| Format-Table Name, Manager
*** If I run the script without the Where-Object portion I get values back.
The -contains is for testing values in an array, unlike the string .Contains() method. In this case, I'd suggest using the regex -match operator like this:
# an array of manager names
$FilterValues = 'Williams', 'Smith', 'Johnson'
# create a regular expression of the manager names by combining them with the regex OR symbol '|'
# the [regex]::Escape() is there to make sure characters that have special meaning in regex are escaped.
$regexManagers = ($FilterValues | ForEach-Object { [regex]::Escape($_) }) -join '|'
Get-ADUser -Filter "extensionAttribute10 -like '1.0'" -Properties Name, Manager |
Where-Object {$_.Manager -match $regexManagers } |
Format-Table
P.S. It is always a bad idea to search for ALL properties with -Properties * when you only want two properties returned.

Unable to pass formatted Get-ADOrganizationlUnit output into function in script

I'm unable to pass the results of Get-ADOrganizationalUnit into a function in a script.
I am storing the results in a variable that is being used to add the canonical name of the OUs returned by the cmdlet, to a dropdown list on a form.
I'm then attempting to use the same variable in a function that when called, will determine the distinguished of the OU based on the canonical name selected.
Since the variable is being set when the form loads so that the drop down in question will be populated with the various OUs, I added in a write-output $myVar just to make sure nothing strange was going on prior to being passed into the function. I've attempted to make $myVar global with $Global:varName and I've attempted to pass in the variable when calling the function: myFunction $myVar $myVar1. If I then use write-output $myVar within the function, there is no output, but I can use write-host $myVar and it will return a string of just the distinguishedNames of all the OUs in $myVar.
I tested this in the shell directly as well and I didn't have any issues with associating the canonical name back to the DN of the OU, but don't know what I'm doing incorrectly to cause it to not work when used in a script.
I'm using this to get the OU data for the dropdown list and function:
$userOUs = Get-ADOrganizationalUnit -SearchBase $ouRoot -Filter * -Properties CanonicalName | Where-Object {$_.Name -like '*user*'}
Note: The dropdown list is populated successfully using $userOUs.
I call the function with a button:
$myBtn.Add_Click({ myFunction $userID $userOUs})
The function I'm trying to pass it to:
function myFunction($userID, $userOUs) {
Write-Output $userOUs #returns nothing
Write-Host $userOUs #returns the string containing all of the OUs' distinguished names
$selectedOU = $OUList.SelectedItem
$targetOUCanonicalName = "$domainPrefix$selectedOU" #I remove the domain name from the canonical name for display in the dropdown but add it back here
$targetOu = $userOUs | Where-Object {$_.CanonicalName -eq $targetCanonicalName} | select -ExpandProperty distinguishedName
Get-ADUser -Identity $userID | Move-ADObject -TargetPath $targetOU
}
Ultimately, the goal is to be able to use the $userOus variable to determine the DN of the OU based on the selection made in a drop down of OU canonical names. I'd like to try and keep this more dynamic without having to define everything in a switch statement.
I expect once I get a bump in the right direction regarding why the variable is not passing into the function the way that I need it to, I'll be able to accomplish that.
Edit: I don't intend to use write-host or write-output since the script will have a form, I'm just using that to try and figure out what's going on.
I've tried your version and it seems to work just fine:
function myFunction($userID, $userOUs) {
Write-Output $userOUs #returns nothing
Write-Host $userOUs #returns the string containing all of the OUs' distinguished names
#$selectedOU = $OUList.SelectedItem
#$targetOUCanonicalName = "$domainPrefix$selectedOU" #I remove the domain name from the canonical name for display in the dropdown but add it back here
#$targetOu = $userOUs | Where-Object {$_.CanonicalName -eq $targetCanonicalName} | select -ExpandProperty distinguishedName
# Get-ADUser -Identity $userID | Move-ADObject -TargetPath $targetOU
}
$userOUs = Get-ADOrganizationalUnit -Filter * -Properties CanonicalName | Where-Object {$_.Name -like '*user*' }
$userOUs
myFunction -userID $UserID -userOUs $userOUs
$UserOus display data for me, when I execute your function as above I also get output. The only thing that comes to mind is that the issue is somewhere else.

Multiple rows in a grid [duplicate]

This question already has answers here:
Export hashtable to CSV with the key as the column heading
(2 answers)
Closed 4 years ago.
I'm trying to list all ad group memberships of specific users. The input would be a string of logins split with a comma 'login1,login2'.
So I go over each user and list their memberships with the username as title. Somehow it only shows the first entry. Also it shows the user groups in one row and I don't know how to change that.
Code below:
$users = $logon -split ','
$q = #()
foreach ($user in $users) {
$usernm = Get-ADUser -Filter 'samAccountName -like $user' | select Name
$useraccess = Get-ADPrincipalGroupMembership $user | Select-Object Name
$userobj = New-Object PSObject
$userobj | Add-Member Noteproperty $usernm.Name $useraccess.Name
$q += $userobj
}
Expected output would be something like:
fullnameuser1 fullnameuser2 list of users goes on...
------------- ------------- ------------------------
adgroup1 adgroup3 ...
adgroup2 adgroup4
... ...
In principle this would also mean that if i typed $q.'fullnameuser1' output would be:
fullnameuser1
-------------
adgroup1
adgroup2
...
Whenever the code is ran, it will only ever add the first user's access, also returning all groups on one row. So somehow I need to go over all the group memberships and add a row for each one.
First and foremost, PowerShell does not expand variables in single-quoted strings. Because of that Get-ADUser will never find a match unless you have a user with the literal account name $user. Also, using the -like operator without wildcards produces the same results as the -eq operator. If you're looking for an exact match use the latter. You probably also need to add nested quotes.
Get-ADUser -Filter "samAccountName -eq '${user}'"
Correction: Get-ADUser seems to resolve variables in filter strings by itself. I verified and the statement
Get-ADUser -Filter 'samAccountName -eq $user'
does indeed return the user object for $user despite the string being in single quotes.
If you want a fuzzy match it's better to use ambiguous name resolution.
Get-ADUser -LDAPFilter "(anr=${user})"
You may also want to avoid appending to an array in a loop, and adding members to custom objects after creation. Both are slow operations. Collect the loop output in a variable, and specify the object properties directly upon object creation.
$q = foreach ($user in $users) {
...
New-Object -Type PSObject -Property {
$usernm.Name = $useraccess.Name
}
}
Lastly, I'd consider using the user's name as the property name bad design. That would be okay if you were building a hashtable (which is mapping unique keys to values), but for custom objects the property names should be identical for all objects of the same variety.
New-Object -Type PSObject -Property {
Name = $usernm.Name
Group = $useraccess.Name
}
Basily query all the users and store it in $users, example:
Get-ADUser -Filter * -SearchBase "dc=domain,dc=local"
And then you can export the results as csv or a table.
To Export as CSV :
Get-ADPrincipalGroupMembership <Username> | select name, groupcategory, groupscope | export-CSV C:\data\ADUserGroups.csv`
To Format the result as Table in the console itslef :
Get-ADPrincipalGroupMembership <Username> | select name, groupcategory, groupscope | Format-Table

How to use the "-notcontains" conditional parameter when querying a BlockedSendersAndDomains list in PowerShell?

I am trying to make a list of all mailboxes who DO NOT have "conostco.com" domain on their BlockedSendersAndDomains list.
by using
$test= Get-MailboxJunkemailconfiguration -Identity * | fl Displayname, BlockedSendersAndDomains
I can get a list of all the names and the Blocked domains/email addresses associated to those names but for my purpose I want to get a list of all of the names of the mailboxes that DO NOT contain the domain "conostco.com". Is there such way to do it?
Based on the sample data you have given I am "assuming" BlockSendersAndDomains is an array.
So maybe you could do something like this then
$test= Get-MailboxJunkemailconfiguration -Identity * | % { $domains = $_.BlockedSendersAndDomains.GetEnumerator() | ? {$_ -notmatch 'conostco.com'}; $name = $_.displayname ; new-object PSObject -Property #{name=$displayname;domains=$domains} }
Again, there is no way for me to test, so see if that gives you a $test object collection which you can then re-use or just display, if you like.
Get-MailboxJunkEmailConfiguration -Identity * |
Where-Object {$_.BlockedSendersAndDomains -notlike '*conostco.com*' }