Powershell - Set-ADUser after Gridview - powershell

I've very new to PowerShell and just starting learn. I'm very appreciative for any help.
Here is what I'm after: I would like to set several OUs to search for AD users who have the Dial-In tab selected as True or Null (Control access through NPS Network Policy) and display the results in gridview. the first part of my script is working, at least displaying the correct users in gridview. Once user(s) are selected in gridview pass those user to have their setting changed to False (deny access).
The error I have is: Set-ADUser : Cannot validate argument on parameter 'Identity'. The argument is null.
$OUs = 'OU=Test,DC=Test,DC=net'
$users = $OUs | Foreach {
Get-ADUser -Filter {(msNPAllowDialin -eq $True) -or (msNPAllowDialin -notlike "*")} -SearchBase $_ -Properties msNPAllowDialin,description,SamAccountName |
Select-Object Name,#{Name="BT UserID";Expression={$_.SamAccountName}},Description | Sort-Object name |
Out-GridView -Title "Select One or More Users to Change Setting" -PassThru
}
$user = $users | foreach {
Set-ADUser $user -replace #{msnpallowdialin=$False}
Write-Host "$($_.name) Dial-In Setting Changed" -ForegroundColor cyan
}

Related

Powershell GUI How can I add column to GridView

This is part of a much larger script 1443 lines to be exact. it pulls the username from AD based on first and last name. I need to also have it pull the Office name from AD to help better identify users with same name. I am sure I am just missing something simple.
function getacctname {
$fname = $FirstName.Text
$lname = $LastName.Text
Try {
$User.Text = Get-ADUser -Filter "GivenName -eq '$fname' -and SurName -eq '$lname'" |
Select-Object -ExpandProperty 'SamAccountName' |
Out-Gridview -Title 'Windows Logon' -PassThru
$Email.Text = (Get-ADUser $User.text -Properties mail).mail
}
Out-GridView dynamically builds its columns based on the input data you feed to it - so in order to get 3 columns, create an object with 3 properties!
Change the Select-Object statement so that it creates an object with properties corresponding to your desired columns and Out-GridView takes care of the rest:
Get-ADUser -Filter "GivenName -eq '$fname' -and SurName -eq '$lname'" -Properties physicalDeliveryOfficeName |
Select-Object 'SamAccountName',#{Name='Office';Expression={$_.physicalDeliveryOfficeName}} |
Out-Gridview -Title 'Windows Logon' -PassThru
If the office name is stored in a different attribute, replace the two occurrances of physicalDeliveryOfficeName with the ldap display name of the attribute in question

Get-ADUser - Filter child OU's and users where surname is empty

I am trying to run a command where I get all active directory users in the parent OU (Users) and filter out the child OU's (Admin accounts, service accounts, disabled accounts) as well as filter out any user account that does not have a surname in the surname field.
At the moment I have
Get-ADUser -Filter{enabled -eq $true} -SearchBase 'OU=Users,OU=Company,DC=CompanyName,DC=local' | Where-Object { $_.DistinguishedName -notlike "*,$Disabled" } | Where {$_.Surname -notlike "$Null"} | select samAccountName
When I add another child OU after 'Disabled' there is an error
Where-Object : A positional parameter cannot be found that accepts argument 'Where'.
Please may someone advise on how to filter out additional child OU's?
Good day Smoore
The problem is you are using multiple Where-object cmdlets but you only need one and separate them using () and adding the -and option, also to refer to $null value you don't need to use the "" marks
Get-ADUser -Filter {Enabled -eq $true} -SearchBase "OU=Users,OU=Company,DC=CompanyName,DC=local" | Where-Object {($_.DistinguishedName -notlike "*,$Disabled*") -and ($_.Surname -notlike $Null)} | select samAccountName
With this options you should be able to get all the users you want
Have a nice day!
I would use a regex -notmatch so it would be possible to combine all OU Distinguished names in just one variable.
Something like this:
$Admins = 'OU=Administrators,OU=Company,DC=CompanyName,DC=local'
$Service = 'OU=ServiceAccounts,OU=Company,DC=CompanyName,DC=local'
$Disabled = 'OU=DisabledUsers,OU=Company,DC=CompanyName,DC=local'
# build a regex string from the above OU DistinguishedNames
$Exclude = '({0}|{1}|{2})$' -f [regex]::Escape($Admins), [regex]::Escape($Service), [regex]::Escape($Disabled)
Get-ADUser -Filter 'Enabled -eq $true' -SearchBase 'OU=Users,OU=Company,DC=CompanyName,DC=local' |
Where-Object { ![string]::IsNullOrWhiteSpace($_.Surname) -and $_.DistinguishedName -notmatch $Exclude } |
Select-Object SamAccountName
As per your comment:
$Admins = 'OU=Administrators,OU=Company,DC=CompanyName,DC=local'
$Service = 'OU=ServiceAccounts,OU=Company,DC=CompanyName,DC=local'
$Disabled = 'OU=DisabledUsers,OU=Company,DC=CompanyName,DC=local'
# the group you want to add the users to
$TargetGroup = 'Company Team'
# build a regex string from the above OU DistinguishedNames
$Exclude = '({0}|{1}|{2})$' -f [regex]::Escape($Admins), [regex]::Escape($Service), [regex]::Escape($Disabled)
$users = Get-ADUser -Filter 'Enabled -eq $true' -SearchBase 'OU=Users,OU=Company,DC=CompanyName,DC=local' |
Where-Object { ![string]::IsNullOrWhiteSpace($_.Surname) -and $_.DistinguishedName -notmatch $Exclude }
# get the AD group as object
$GroupObject = Get-ADGroup -Filter "Name -eq '$TargetGroup'"
# now add these users that have Surnames to the security group all in one go
try {
Write-Host "Adding $(#($users).Count) users to group $TargetGroup"
$GroupObject | Add-ADGroupMember -Members $users -ErrorAction Stop -Verbose
}
catch {
Write-Warning "Error: $($_.Exception.Message)"
}
# or if you prefer loop through the users and add each one individually then use this instead
# foreach ($user in $users) {
# try {
# Write-Host "Adding user $($users.Name) to group $TargetGroup"
# $GroupObject | Add-ADGroupMember -Members $user -ErrorAction Stop -Verbose
# }
# catch {
# Write-Warning "Error adding user $($users.Name) to group $($TargetGroup): $($_.Exception.Message)"
# }
# }

Power Shell CSV to AD

Maybe someone can to help?
I have a script it take parameters from scv and put them to AD, script work without mistakes but I`m does not have results from some reasone.
Please help!
Import-CSV -Path "$home\desktop\Scripts\test4.scv" | ForEach-Object -process {Write-Host $_ }
{Set-ADuser|]= -Identity $_.DisplayName -extensionattribute5 $_.extensionattribute5}
example scv
According to the docs, the -Identity parameter on Set-ADUser must be one of
A distinguished name
A GUID (objectGUID)
A security identifier (objectSid)
A SAM account name (sAMAccountName)
This means that you cannot use the DisplayName property from the CSV for this parameter.
Try:
Import-CSV -Path "$home\desktop\Scripts\test4.scv" | ForEach-Object {
$user = Get-ADUser -Filter "DisplayName -eq '$($_.DisplayName)'" -Properties DisplayName -ErrorAction SilentlyContinue
if ($user) {
Write-Host "Setting extensionattribute5 property for user $($_.DisplayName)"
$user | Set-ADuser -Add #{extensionattribute5=$_.extensionattribute5}
}
else {
Write-Warning "User $($_.DisplayName) could not be found"
}
}
Instead of -Add #{extensionattribute5=$_.extensionattribute5}, you may rather want -Replace #{extensionattribute5=$_.extensionattribute5}. This isn't clear in the question
Try this:
Import-CSV -Path "$home\desktop\Scripts\test4.scv" | ForEach {
Write-Host $_
Set-ADuser -Identity $_.DisplayName -Add #{extensionattribute5=$_.extensionattribute5}
}
Your code was broken. Bracing was incorrect. Also Extended attributes are added with a hash table using -Add parameter.

how to make this group filter script only for active users

I was wondering if this script could be changed into one for only active users?
import-module ActiveDirectory
Start-Transcript -Path "C:\test\teetest.txt"
$groups = Get-ADGroup -filter {(name -like "runners*") -or (name -like "helpers*")
foreach($group in $groups)
{
$countUser = (Get-ADGroupMember $group.DistinguishedName).count
Write-Host "The group $($group.Name) has $countUser user(s)."
}
Stop-Transcript
Any help would be appreciated.
If I understand your question correctly and by active users you mean groups with at least 1 member(i.e. greater than 0). You could just filter out results using Where-Object cmdlet. Like so:
$groups = Get-ADGroup -filter {(name -like "runners*") -or (name -like "helpers*") -Properties Members | Where-Object { $_.Members.Count –gt 0 }
Yes, you can add a filter to only get the number of active Members in the Group.
Since Get-ADGroupMember doesn't supply all properties for the Users you have to do another lookup for each of them:
$countUser = (Get-ADGroupMember $group.DistinguishedName | % { Get-ADuser -Identity $_ -Property Enabled | Where-Object {$_.Enabled -eq $true}}).count
Explanation:
% { Get-ADuser -Identity $_ -Property Enabled - Get the Informations for each User found in the Group with the Enabled Property added to it
Where-Object {$_.Enabled -eq $true} - Filters the users that are enabled
I think this may be because the Get-ADGroupMember not just returns user objects with a limited set of properties, but can also return groups and computers.
Since you are only looking for users that are direct descendents of the groups 'runners*' or 'helpers*', it is better to limit the objects returned by the Get-ADGroupMember cmdlet to be users only.
Below I do this by adding Where-Object { $_.objectClass -eq "user" }.
Next, to ensure the .Count property can be used I would suggest to enclose the thing in a #() so the returned value actually is an array and therefore has the Count property.
For a script like this, I also suggest NOT to try and put it all in one single line, because that makes spotting mistakes (like forgetting a closing bracket) more difficult.
Try this:
Start-Transcript -Path "C:\test\teetest.txt"
$groups = Get-ADGroup -Filter {(name -like "runners*") -or (name -like "helpers*")}
foreach($group in $groups) {
$countUser = 0
Get-ADGroupMember $group.DistinguishedName | Where-Object { $_.objectClass -eq "user" } |
ForEach-Object {
if ((Get-ADuser -Identity $_.DistinguishedName).Enabled) { $countUser++ }
}
Write-Host "The group $($group.Name) has $countUser user(s)."
}
Stop-Transcript
Replace the $countUser statement alone with below example.
For only Enabled User Accounts
$countUserEnabled = (get-aduser -filter *|where {$_.enabled -eq "True"}).count
For only Disabled User Accounts
$countUserDisabled = (get-aduser -filter *|where {$_.enabled -ne "False"}).count

PowerShell - Adding New User to Selection of AD Groups

I've created a form to create new AD Accounts. Part of the script determines which groups the new user will be added to based on their role (Doctor, Nurse, Admin or Other) which is captured in the following code in the form of a drop down pick box:
Write-Host "Based on this information" $FFN "has been added to the following Active Directory Groups:"
Write-Host
$ADGroup01 = Get-ADGroup "_XA_App_XenApp" |select -expandproperty name -first 1
Write-Host $ADGroup01
$ADGroup02 = Get-ADGroup "Web Proxy Users" |select -expandproperty name -first 1
Write-Host $ADGroup02
if($RadioButton1.Checked -eq $true)
{
$ADGroup03 = Get-ADGroup "allrot" |select -expandproperty name -first 1
Write-Host $ADGroup03
}
Else
{
$ADGroup03 = Get-ADGroup "alltpo" |select -expandproperty name -first 1
Write-Host $ADGroup03
}
if ($Role -eq "Doctor" -Or $Role -eq "Nurse")
{
$ADGroup04 = Get-ADGroup "PACS Web Access" |select -expandproperty name -first 1
Write-Host $ADGroup04
}
if ($Role -eq "Doctor")
{
$ADGroup05 = Get-ADGroup "CH-MFD" |select -expandproperty name -first 1
Write-Host $ADGroup05
$ADGroup06 = Get-ADGroup "ED-MFP" |select -expandproperty name -first 1
Write-Host $ADGroup06
$ADGroup07 = Get-ADGroup "SU-MFD" |select -expandproperty name -first 1
Write-Host $ADGroup07
}
Write-Host
Further on in the script this piece of code is called during the actual account creation process:
Add-ADPrincipalGroupMembership -Identity $UN -memberof $ADGroup01, $ADGroup02, $ADGroup03, $ADGroup04, $ADGroup05, $ADGroup06, $ADGroup07
The issue I'm facing is that if the user selects Nurse, Admin or Other I get the following error:
"Add-ADPrincipalGroupMembership : Cannot validate argument on parameter 'MemberO
f'. The argument is null, empty, or an element of the argument collection conta
ins a null value. Supply a collection that does not contain any null values and
then try the command again."
I know this is because there are no values being captured in the last $ADGroup[x] and short of creating a bunch of if statements to check if each $ADGroup contains data I'm wondering if there is a more elegant solution.
As always, thank you for taking the time review and happy to provide more information if required.
UPDATE - As per #Martin's advice I've implemented the following code into my script
$UN = "zooz"
$Role = "Nurse"
$Department = "Surgical"
If ($Role -eq "Doctor" -and $Department -eq "Surgical")
{
$ADGroups = #(
"PACS Web Access"
"CH-MFD"
"ED-MFP"
"SU-MFD"
)
}
If ($Role -eq "Nurse" -and $Department -eq "Surgical")
{
$ADGroups = #(
"_XA_App_XenApp"
"Web Proxy Users"
"allrot"
)
}
for ($i=0; $i -lt $ADGroups.length; $i++) {
Add-ADPrincipalGroupMembership -Identity $UN -memberof $adgroups[$i]
}
Make an object $adgroups and add your desired groups to it.
$adgroups = #()
At the end use a foreach Loop:
$adgroups | Add-ADPrincipalGroupMembership -Identity $UN or (weather or not the cmdlet likes pipelined Input)
$adgroups | % { Add-ADPrincipalGroupMembership -Identity $UN -memberof $_ }