Change AD user attributes of users in group - powershell

I copied and pasted together this script that looks at all the member in a certain group, and then changes all of their company names. I would now like to expand this script to be able to ask for which attribute of the users you want to change.
Clear-Host
$GPNAME = Read-Host 'Provide the Group Name here'
#$whatwhat = Read-Host 'Which Attribute do you want to change | Put a - infront'
$attrib = Read-Host 'Give new company name here' #This should later change to "Give new info of Attribute you want to change"
$description = "-description"
$offeece = "-office"
$department = "-department"
$company = "-company"
$Userslist = Get-ADGroupMember $GPNAME
ForEach($User in $Userslist)
{
$user1 = $User.name
#Write-Host $user1
get-aduser -filter { name -eq $User1 } | set-aduser -company $attrib
}
at the end of the script i would like to change the -company with $whatwhat.
I have tried it, but no matter how, with the - or without, with ' and " around the - or the $whatwhat, it keeps on giving me this error.
Set-ADUser : A positional parameter cannot be found that accepts argument 'newly'
can anyone assist my to expand this script a little bit by giving the user options to choose from, or allowing him/her to type: company or description or office

you could use invoke-expression cmdlet
$cmd="get-aduser -filter { name -eq $User1 } | set-aduser $whatwhat $attrib -whatif"
invoke-expression $cmd
test :
PS>$what=read-host "attribute to change :" attribute to change ::
company
PS>$c="set-aduser test -$what 'testcpny' -whatif"
PS>iex $c
WhatIf : Opération « Set » en cours sur la cible « CN=TEST,CN=Users,DC=....,DC=com ».

Related

Variable not passing to Where-Object in Powershell

I have tried the "filter" and "param" options from the post
-- In powershell passing variable to where-object not working -- with no luck. I am fairly new to powershell since I have not used it since 2014. Can anyone assist me in finding out why the $UName variable is not being passed to the Where-Object command?
cls
$UName = Read-Host -Prompt "Name or part of name to search"
Write-Output "Searching for: $UName, please wait"
Get-ADUser -Filter * -Properties * | Where-Object {
$_.name -like "*$UName*" -and
$_.company -like "*XYZ Corp*"
} | select Name, title, company, Country, mailnickname
Pause
My only output is:
Name or part of name to search: Justin
Searching for: Justin, please wait
Press Enter to continue...
I have even tried using -Contains $UName and -Contains "$UName" yet still get the same results as above.
I have searched, and searched but cannot figure this out. Any assistance would really help!
Your script can be simplified as follows, you really shouldn't query all Domain Users (-Filter *) to then filter them with PowerShell (Where-Object). Instead, you should use the Active Directory Filter. Same goes for querying all users properties (-Properties *) when you actually only need some of them (Name, title, company, Country, mailnickname).
# using Trim() to remove any excess whitespace (trailing and leading)
$UName = (Read-Host -Prompt "Name or part of name to search").Trim()
# if there was no input or input was purely whitespace
if(-not $UName) {
# exit this script
return
}
# if input was valid
Write-Output "Searching for: $UName, please wait"
# try to search for the user
$props = 'Name', 'title', 'company', 'Country', 'mailnickname'
Get-ADUser -LDAPFilter "(&(name=*$UName*)(company=*XYZ Corp*))" -Properties $props |
Select-Object $props | Format-Table -AutoSize

How to reference a property from another command?

So im trying to setup a script for unlocking users accounts.
Right now this is what i have:
function unlocktm
{
$user = read-host "Who is the user?"
Unlock-ADAccount -Identity $user -Credential adminaccount
Write-host "Account for $user has been unlocked!"
}
now here is the difficult part, our users usernames are based off their email. and we switched email formats like last year. So some peoples emails are jdoe#company.com and others are john.doe#company.com
So when that script i have now asks "who is the user?" i have to put in and know that users username style (either first.lastname or flastname). Well with 1500 users, i dont exactly know every ones emails off the top of my head.
So what im trying to do is make it so that when it asks for "who is this user?" i can just put in John Doe, itll run a second script i have setup that can search for that user in AD, pull the attribute and apply it into the first script. Let me explain better. For the time being i have a second script that is this:
function findtm
{
$Firstname = Read-Host "What is the users Firstname?"
$Lastname = Read-Host "What is the Users Lastname?"
Get-ADUser -Filter "Surname -like '$Lastname*' -and GivenName -like '$Firstname*'"
}
and that pulls the info about that user and shows me what their email style is. That email style is under the "samaccountname".
So ultimately, what i need it to do is:
I run the function, it asks me for the user.
I can just put in "John Doe"
and it will then run that second script in the background that searches for "John Doe" and then if it finds a John Doe, its grabs the "samaccountname" property (either john.doe or jdoe), attaches that to the answer in replace of the "john doe" and then the script runs the unlockad command for john doe and unlocks his account.
Im probably over thinking this by a large margin, but i was thinking a If-else could do it but i have no clue how to to set it up to pull that "samaccountname" property.
In my opinion you should think of your functions as independent units, that take in the information they need as parameters. I would typically leave prompting or user interaction to the outermost layer.
Consider that Get-ADUser returns an object that can be used with Unlock-ADAccount as well.
function unlocktm
{
param($Identity)
Unlock-ADAccount -Identity $Identity -Credential adminaccount
Write-host "Account for $($Identity.SamAccountName) has been unlocked!"
}
function findtm
{
param($Firstname, $Lastname)
Get-ADUser -Filter "Surname -like '$Lastname*' -and GivenName -like '$Firstname*'"
}
# the outer script area
$Firstname = Read-Host "What is the users Firstname?"
$Lastname = Read-Host "What is the Users Lastname?"
$Id = findtm -Firstname $Firstname -Lastname $Lastname
unlocktm -Identity $id
Now, if you want to make it a little more fancy:
function unlocktm
{
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline=$true)]
$Identity
)
Process {
Unlock-ADAccount -Identity $Identity -Credential adminaccount
Write-host "Account for $($Identity.SamAccountName) has been unlocked!"
}
}
function findtm
{
param($Firstname, $Lastname)
Get-ADUser -Filter "Surname -like '$Lastname*' -and GivenName -like '$Firstname*'"
# by simply calling this, the value returned becomes the return value of your function
}
# the outer script area
$Firstname = Read-Host "What is the users Firstname?"
$Lastname = Read-Host "What is the Users Lastname?"
findtm -Firstname $Firstname -Lastname $Lastname | unlocktm
There are lots of possibilities, but perhaps this is a good start?

Check and Update multiple attributes of AD users

I am trying to do an update to Active Directory from a CSV.
I want to check each value to see if the AD and CSV values match.
If the AD value and CSV values don't match, then I want to update the AD value.
finally I want to create a log of the values changed, which would eventually be exported to a CSV report.
Now there is about 30 values I want to check.
I could do an if statement for each value, but that seems like the hard way to do it.
I am try to use a function, but I cant seem to get it working.
I am getting errors like:
set-ADUser : replace
At line:94 char:9
+ set-ADUser -identity $ADUser -replace #{$ADValue = $DIAccount ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (JDoe:ADUser) [Set-ADUser], ADInvalidOperationException
+ FullyQualifiedErrorId : ActiveDirectoryServer:0,Microsoft.ActiveDirectory.Management.Commands.SetADUser
set-ADUser : The specified directory service attribute or value does not exist
Parameter name: Surname
At line:94 char:9
+ set-ADUser -identity $ADUser -replace #{$ADValue = $DIAccount ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (JDoe:ADUser) [Set-ADUser], ArgumentException
+ FullyQualifiedErrorId : ActiveDirectoryCmdlet:System.ArgumentException,Microsoft.ActiveDirectory.Management.Commands.SetADUser
Any suggestions would be welcome
Code I am using:
Function AD-Check ($ADValue, $ADUser, $ADAccount, $UpdateAccount)
{
If ($ADAccount -ne $UpdateAccount)
{
set-ADUser -identity $ADUser -replace #{$ADValue = $UpdateAccount}
$Change = "Updated"
}
Else
{
$Change = "No Change"
}
Return $Change
}
$Import = get-content C:\temp\ADUpdates.csv
Foreach ($user in $Import)
{
$Account = get-aduser $User.Samaccountname -Properties *
#First Name Check
$Test = AD-Check "GivenName" $Account.samaccountname $Account.givenname $user.givenname
$ChangeGivenName = $Test
#Initials Check
$Test = AD-Check "Initials" $Account.samaccountname $Account.Initials $user.Initials
$ChangeInitials = $Test
#Last Name Check
$Test = AD-Check "Surname" $Account.samaccountname $Account.SurnameSurname $user.Surname
$ChangeSurname = $Test
}
Reply to Theo, cant seem to add this any other way...
Thanks Theo, it seems to make sense, but getting an error.
Select-Object : Cannot convert System.Collections.Specialized.OrderedDictionary+OrderedDictionaryKeyValueCollection to one of the following types {System.String,
System.Management.Automation.ScriptBlock}.
changed the following to get all properties for testing and it works.
$Account = Get-ADUser -Filter "SamAccountName -eq '$sam'" -ErrorAction SilentlyContinue -Properties $propsToCheck
Left the following and it kicks the error
$oldProperties = $Account | Select-Object $propsToCheck
Using the following just for testing:
$propertiesMap = [ordered]#{
SamAccountName = 'sAMAccountName'
mail = 'mail'
GivenName = 'givenName'
Initials = 'initials'
Surname = 'sn'
Office = 'physicalDeliveryOfficeName'
MobilePhone = 'mobile'
DistinguishedName = 'DistinguishedName'
}
Starting of with a WARNING:
Replacing user attributes is not something to be taken lightly and you
need to check any code that does that on a set of testusers first.
Keep the -WhatIf switch to the Set-ADUser cmdlet so you
can first run this without causing any problems to the AD.
Only once you are satisfied all goes according to plan, remove the -WhatIf switch.
Please carefully read all inline comments in the code.
In your code you use an input CSV file, apparently with properties and values to be checked/updated, but instead of using Import-Csv, you do a Get-Content on it, so you'll end up with just lines of text, not an array of parsed properties and values..
Next, as Mathias already commented, you need to use the LDAP attribute names when using either the -Add, -Remove, -Replace, or -Clear parameters of the Set-ADUser cmdlet.
To do what you intend to do, I would first create a hashtable to map the PowerShell attribute names to their LDAP equivalents.
To see which property name maps to what LDAP name, you can use the table here
# create a Hashtable to map the properties you want checked/updated
# the Keys are the PowerShell property names as they should appear in the CSV
# the Values are the LDAP AD attribute names in correct casing.
$propertiesMap = [ordered]#{
SamAccountName = 'sAMAccountName'
GivenName = 'givenName'
Initials = 'initials'
Surname = 'sn'
Office = 'physicalDeliveryOfficeName'
Organization = 'o'
MobilePhone = 'mobile'
# etcetera
}
# for convenience, store the properties in a string array
$propsToCheck = $propertiesMap.Keys | ForEach-Object { $_.ToString() }
# import your CSV file that has all the properties you need checked/updated
$Import = Import-Csv -Path 'C:\temp\ADUpdates.csv'
# loop through all items in the CSV and collect the outputted old and new values in variable $result
$result = foreach ($user in $Import) {
$sam = $user.SamAccountName
# try and find the user by its SamAccountName and retrieve the properties you really want (not ALL)
$Account = Get-ADUser -Filter "SamAccountName -eq '$sam'" -ErrorAction SilentlyContinue -Properties $propsToCheck
if (!$Account) {
Write-Warning "A user with SamAccountName '$sam' does not exist"
continue # skip this one and proceed with the next user from the CSV
}
# keep an object with the current account properties for later logging
$oldProperties = $Account | Select-Object $propsToCheck
# test all the properties and create a Hashtable for the ones that need changing
$replaceHash = #{}
foreach ($prop in $propsToCheck) {
if ($Account.$prop -ne $user.$prop) {
$ldapAttribute = $propertiesMap[$prop] # get the LDAP name from the $propertiesMap Hash
# If any of the properties have a null or empty value Set-ADUser will return an error.
if (![string]::IsNullOrWhiteSpace($($user.$prop))) {
$replaceHash[$ldapAttribute] = $user.$prop
}
else {
Write-Warning "Cannot use '-Replace' with empty value for property '$prop'"
}
}
}
if ($replaceHash.Count -eq 0) {
Write-Host "User '$sam' does not need updating"
continue # skip this one and proceed with the next user from the CSV
}
# try and do the replacements
try {
##########################################################################################################
# for safety, I have added a `-WhatIf` switch, so this wll only show what would happen if the cmdlet runs.
# No real action is performed when using '-WhatIf'
# Obviously, there won't be any difference between the 'OLD_' and 'NEW_' values then
##########################################################################################################
$Account | Set-ADUser -Replace $replaceHash -WhatIf
# refresh the account data
$Account = Get-ADUser -Identity $Account.DistinguishedName -Properties $propsToCheck
$newProperties = $Account | Select-Object $propsToCheck
# create a Hashtable with the old and new values for log output
$changes = [ordered]#{}
foreach ($prop in $propsToCheck) {
$changes["OLD_$property"] = $oldProperties.$prop
$changes["NEW_$property"] = $newProperties.$prop
}
# output this as object to be collected in variable $result
[PsCustomObject]$changes
}
catch {
Write-Warning "Error changing properties on user '$sam':`r`n$($_.Exception.Message)"
}
}
# save the result as CSV file so you can open with Excel
$result | Export-Csv -Path 'C:\temp\ADUpdates_Result.csv' -UseCulture -NoTypeInformation

Searching for User in Powershell. Allow Choice for Duplicate User

I wrote a PowerShell script that searches for a user based on given input and then removes said user from all groups (except for Domain Users). However, while you can't have a user with the same name in an OU group, you can have a user with the same name in a different OU group in the organization. Would it be possible to search for a user (John Smith), and allow one to select which user to remove from all groups if a duplicate user is returned? Here is my script so far. It works, but this is the functionality I would like to add.
#Requires -Module ActiveDirectory
Import-Module ActiveDirectory
function Disable-ADUser{
$msg = "Do you want to remove a user from all Security groups? [Y/N]"
do {
$response = Read-Host -Prompt $msg
if ($response -eq "y") { # Beginning of if statment
#Asks user via a text prompt to ender the firstname and lastname of the end user to remove
$firstName = Read-Host "Please provide the First name of the User"
$lastName = Read-Host "Please provide the Last name of the User"
#The user's samaccoutname is found by searching exactly for the user's first name and lastname given in the above prompts
$samName = Get-ADUser -Filter "GivenName -eq '$firstName' -and Surname -eq '$lastName'"| Select-Object -ExpandProperty "SamAccountName"
#All of the user's groups are queried based on their sam name
$listGroups = Get-ADUser -Identity $samName -Properties MemberOf | Select-Object -ExpandProperty MemberOf
#All of the user's groups are placed in an array
[System.Collections.ArrayList]$groupsArray = #($listGroups)
#Every group in the groupsArray is cycled through
foreach ($group in $groupsArray) {
#A text output is displayed before the user is removed from each group listed in the above array
#Once all groups have been cycled through, the for loop stops looping
Write-Host "Removing $samName " -f green -NoNewline
Write-Host "from $group" -f red
$OutputLine="Removing $samName from $group"
Out-File -FilePath remove_user_groups.log -InputObject $OutputLine -Append
Remove-ADGroupMember -Identity $group -Members $samName
}
} # End of if statement
} until ($response -eq "n")
}
Disable-ADUser
I use Out-GridView. It allows me to select user(s) with mouse, or to select no one. See -OutputMode parameter.
<# Example part #>
$data = #'
[
{displayName: "Don Pedro Fizikello", employeeNumber: "Emp001", phone: "+888888888" },
{displayName: "Don Pedro Gonzalez", employeeNumber: "Emp002", phone: "+77777777777" },
{displayName: "Natalia Marisa Oreiro", employeeNumber: "Emp456", phone: "+987654321" },
{displayName: "Juan Carlos Rodrigez", employeeNumber: "Emp123", phone: "+1234567890"}
]
'# | ConvertFrom-Json
$userList = #($data | Where-Object { $_.displayName -like 'Don*' })
#Real-world case from Active Directory: $userList = #( Get-ADUser -Filter "(displayName -like 'Don*')" -Properties #('displayName', 'phone') )
<# /Example part #>
$user = $null
if ($userList.Count -eq 1) {
$user = $userList[0] # // The only entry
} elseif ($userList.Count -gt 1) {
$user = $userList | Out-GridView -OutputMode Single -Title 'Select User you want co tall to or press cancel'
}
if ($null -eq $user) {
# // There is no users found or selected by human
Write-Host "Nothing to do" -f Yellow
} else {
# // Work with User
Write-Host "Call $($user.displayName) : $($user.phone)" -f Green
}
The negative option is that Out-GridView can not hide parameters that it will display. There are some workarounds depending on task. Example: I show only DisplayName and some ID in Out-GridView (no phone property), but I use returned ID to take full user (with phone) from cache I've created before.
This allows me not to break the original object ( if it's from Get-ADUser, it contains tons of human-useless data like SID, GUID, ObjectClass, ObjectCategory, etc. )
<# Example part #>
Same as previous
<# /Example part #>
$user = $null
$userCacheOriginal = #{}
$userCacheCut = #{}
for ($i = 0; $i -lt $userList.Count; $i++)
{
# !! Here I assign some entryUniqueId to two collections -
# - userCacheOriginal - Original user object with Phone field ( and others )
# - userCacheCut - Transformed objects that contains only ID and info I want to show in Out-GridView
$entryUniqueId = "Idx$($i)"
$userCacheOriginal[$entryUniqueId] = $userList[$i]
$userCacheCut[$entryUniqueId] = [PSCustomObject]#{ID = $entryUniqueId; displayName = $userList[$i].DisplayName;}
}
if ($userList.Count -eq 1) {
$user = $userList[0] # // The only entry
} elseif ($userList.Count -gt 1) {
$userChoice = $userCacheCut.Values | <# Set order of columns this way#> Select #('ID', 'DisplayName') | Out-GridView -OutputMode Single -Title 'Select User or press cancel'
if (($null -ne $userChoice.ID) -and ($userCacheOriginal.ContainsKey($userChoice.ID))) # Check if returned value contains ID,
{ # And select original user object from userCacheOriginal
$user = $userCacheOriginal[$userChoice.ID]
}
}
if ($null -eq $user) {
# // There is no users found or selected by human
Write-Host "Nothing to do" -f Yellow
} else {
# // Work with User
Write-Host "Call $($user.displayName) : $($user.phone)" -f Green
}
If you want to keep it console based, you can add a while loop that requires further input from the user.
#The user's samaccoutname is found by searching exactly for the user's first name and lastname given in the above prompts
$samName = Get-ADUser -Filter "GivenName -eq '$firstName' -and Surname -eq '$lastName'"|
Select-Object -ExpandProperty "SamAccountName"
if ($samname.count -gt 1) {
$newsamname = $null
while ($newsamname -notin $samname) {
$newsamname = Read-Host "Multiple names were found:`n$($samname -join ""`n"")`nPlease type the SamAccountName of the target user"
}
$samname = $newsamname
}
The idea is if multiple user objects are found, then $samname will initially be a collection of count greater than one. Here the executor will be required to enter a valid SamAccountName value from the presented list. Otherwise, the loop will go on forever until the program is manually halted. You could build in a counter to automatically exit the program after a certain number of retries or exit when no value is entered. You could implement a menu system where a number can be entered, which corresponds to the index of the list.

Powershell Script to query Active Directory

I am trying to query all users in multiple OUs of the same name. Get the SamAccountName attribute and then check for a file at a specific location with that name.
Here is what I have so far:
$ous = Get-ADOrganizationalUnit -Filter "Name -eq 'Admin-User-Accounts'"
$ous | ForEach-Object {
$AccountName = Get-ADUser -Filter * -SearchBase $_.DistinguishedName |
Select SamAccountName
Test-Path "\\domain.net\SYSVOL\domain.net\IA\$AccountName.pdf"
}
If a file is not found. I want to add the user to a group, however here is the kicker. The account has to be added to the non-compliance group for the organization that the account belongs to.
I.E an admin account found under:
OU=Admin-User-Accounts,OU=Administration,OU=ORG1,OU=ORGS,DC=domain,DC=net
would be added to the group named 'ORG1 IA - Non-Compliant Users' located under:
OU=Groups,OU=ORG1,OU=Information Assurance,OU=ORGS,DC=domain,DC=net
Well your post is a bit confusing, and no way to really validate because I have nothing setup like this.
Yet, querying for users in all OU or the enterprise is a common everyday thing.
However, an OU name, just like any other AD object name, must be unique. So, querying for the same OU name is not a thing, in a single AD forest / domain. If you meant querying every OU for the same username, then alrighty then.
By stepping thru how you are explanation for your use case, that you have laid out.
(though maybe you want to edit your post to make it's more clear, well to me anyway...)
Using pseudo code, then trying to map that out... and with no real way to determine what you mean by several things in your post/sample. So, the below is a rough first example of how I'd do approach this... again this is untested, so, I leave that homework to you.
# query all users in multiple OUs
(Get-ADOrganizationalUnit -Filter *).DistinguishedName |
ForEach{
# Collect all members of the current OU
$AccountNames = Get-ADUser -SearchBase $PSItem -Filter *
# Process each member in the current OU collection
ForEach($AccountName in $AccountNames)
{
"Processing $($AccountName.SamAccoutnName)`n"
# Initialize properties needed for processing
$UserOrg = $AccountName.DistinguishedName.split(",")[1]
$MemberCheckOU = "OU=Admin-User-Accounts,OU=Administration,OU=ORG1,OU=$UserOrg,DC=domain,DC=net"
$NonCompliantOU = "OU=Groups,OU=ORG1,OU=Information Assurance,OU=$UserOrg,DC=domain,DC=net"
# Validate user file existence for the current user
If(-Not (Test-Path -LiteralPath "\\domain.net\SYSVOL\domain.net\IA\$($AccountName.SamAccoutnName).pdf)"))
{
# if no file Process the user groupmebership modification
"Processing $($AccountName.SamAccoutnName)"
# Notify that the file was not found and processing is required
Write-Warning -Message "$($($AccountName.SamAccoutnName).pdf) not found. Process group modify actions"
# If the current user is in the MemberCheckOU, add to the NonCompliantOU
If(Get-ADPrincipalGroupMembership -Identity $($AccountName.SamAccoutnName) | Where-Object -Property DistinguishedName -Match $MemberCheckOU )
{ Add-ADGroupMember -Identity $NonCompliantOU -Members $($AccountName.SamAccoutnName) }
Else
{
# Do something else
}
}
Else
{
# Notify that the file was found and no processing required
Write-Host "$($AccountName.pdf) found. No further actions taken" -ForegroundColor Green }
}
}
It seems that one of the variables is incorrect because PowerShell is giving me the following:
Get-ADPrincipalGroupMembership : Cannot validate argument on parameter 'Identity'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command
again.
Okay, so here is what I have so far based on your post above Postanote:
# query all users in multiple OUs
(Get-ADOrganizationalUnit -Filter "Name -eq 'Admin-User-Accounts'") |
ForEach{
# Collect all members of the current OU
$AccountNames = Get-ADUser -SearchBase $PSItem -Filter *
# Process each member in the current OU collection
ForEach($AccountName in $AccountNames)
{
"Processing $($AccountName.SamAccoutnName)`n"
# Initialize properties needed for processing
$UserOrg = $AccountName.DistinguishedName.split(",")[1]
$MemberCheckOU = "OU=Admin-User-Accounts,OU=Administration,OU=$UserOrg,OU=ORGS,DC=domain,DC=net"
$NonCompliantOU = "OU=Groups,OU=$UserOrg,OU=Information Assurance,OU=ORGS,DC=domain,DC=net"
# Validate user file existence for the current user
If(-Not (Test-Path -LiteralPath "\\domain.net\SYSVOL\domain.net\IA\$($AccountName.SamAccoutnName).pdf)"))
{
# if no file Process the user groupmebership modification
"Processing $($AccountName.SamAccoutnName)"
# Notify that the file was not found and processing is required
Write-Warning -Message "$($($AccountName.SamAccoutnName).pdf) not found. Process group modify actions"
# If the current user is in the MemberCheckOU, add to the NonCompliantOU
If(Get-ADPrincipalGroupMembership -Identity $($AccountName.SamAccoutnName) | Where-Object -Property DistinguishedName -Match $MemberCheckOU )
{ Add-ADGroupMember -Identity "$UserOrg IA - Non-Compliant Users" -Members $($AccountName.SamAccoutnName) }
Else
{
# Do something else
}
}
Else
{
# Notify that the file was found and no processing required
Write-Host "$($AccountName.pdf) found. No further actions taken" -ForegroundColor Green }
}
}
Looking at the original script fragment:
$ous = Get-ADOrganizationalUnit -Filter "Name -eq 'Admin-User-Accounts'"
$ous | ForEach-Object {
$AccountName = Get-ADUser -Filter * -SearchBase $_.DistinguishedName |
Select SamAccountName # note 1
Test-Path "\\domain.net\SYSVOL\domain.net\IA\$AccountName.pdf" # note 2
}
Note 1: Your going to end up with $accountname.accountname holding your value. I think your going to want to expand this instead.
Note2: Powershell may be getting confused and thinking your looking for the variable $accountname.pdf
Instead, try this...
$ous = Get-ADOrganizationalUnit -Filter "Name -eq 'Admin-User-Accounts'"
$ous | ForEach-Object {
$AccountName = $(Get-ADUser -Filter * -SearchBase $_.DistinguishedName).SamAccountName
Test-Path "\\domain.net\SYSVOL\domain.net\IA\$($AccountName).pdf"
}
here, we save the value of just .SamAccountName for the query to the $AccountName, and by adding $($accountname) we make clear the variable we want, and that .pdf is not part of the variable name.
Now, note as well, this doesn't save the results anywhere, it will just flash them to screen.