Update Custom Attributes in Powershell - powershell

I am trying to write a script that will import a csv file and update a set of custom attributes that were built into our AD Schema.
Here is the basic code:
Import-Module ActiveDirectory
$USERS = Import-Csv c:\temp\test2.csv
foreach ($user in $users) {
Get-ADComputer -filter {dnsname -eq $user.ComputerName} |
Set-ADComputer -replace #{bSBPrimaryUser = $user.bSBPrimaryUser}
}
Here is my Error Message:
Set-ADComputer : Cannot bind parameter 'Replace' to the target. Exception setting "Replace": "Object reference not set to an instance of an object."
At C:\Users\nwatson\Documents\Update Computers.ps1:7 char:24
Set-ADComputer -replace <<<< #{bSBPrimaryUser = $user.bSBPrimaryUser}}
CategoryInfo : WriteError: (:) [Set-ADComputer], ParameterBindingException
FullyQualifiedErrorId : ParameterBindingFailed,Microsoft.ActiveDirectory.Management.Commands.SetADComputer
For some reason if I write a basic command like below it works, but not in the array.
Set-ADComputer as-001 -replace #{ bSBPrimaryUser = "Joe Smith";}

First, the property you are looking for isn't dnsname but dnshostname or name. (If just using name, then skip using filter and pass it in as the identity)
Second, the filters on the AD cmdlets aren't straight forward. If using curly braces, then you can't use an expression. Double quotes then single quotes seems to work fine though.
Get-ADComputer -filter "dnshostname -eq '$($user.ComputerName)'"
Alternatively, define the expression as a variable.
$ComputerName = $user.ComputerName
Get-ADComputer -filter {dnshostname -eq $Computername}

Related

Active directory delete description and office fields through powershell

I have a list of users in active directory to which I have to remove the description and office fields. how can i do through poweshell? I try this but not work.
My code path is ok
Import-Module ActiveDirectory
$Users = Import-csv C:\Users\xxxx\Desktop\test.csv
foreach($User in $Users){
Set-ADUser $User.SamAccountName -Description $User.NewDescription
}
my csv
SamAccountName;NewDescription;EmailAddress
xxxxxxxxxx;xxxxxxxxxxx;xxxxxxxxxxxxx#libero.it
Powershell answer
Set-ADUser : Cannot validate argument on parameter 'Identity'. The argument is null. Provide a valid value for the
argument, and then try running the command again.
At line:4 char:12
+ Set-ADUser $User.SamAccountName -Description $User.NewDescription
+ ~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Set-ADUser], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.SetADUs
er
Help will be appreciated
You need to specify your delimiter on your import-csv statement. The default is comma separated, so you can define it like so
$Users = Import-csv C:\Users\xxxx\Desktop\test.csv -Delimiter ';'
Without this, then it's importing as one single column instead of three.
See Import-CSV for more.
It might work?
$users = Import-Csv -Path C:\users1.csv
foreach ($user in $users) {
#Search in specified OU and Update existing attributes
Get-ADUser -Filter “SamAccountName -eq ‘$($user.samaccountname)'” -Properties * -SearchBase “cn=Users,DC=**********,DC=*****” |
Set-ADUser -Clear description, Office
}

Cannot Search AD from CSV using Powershell

Trying to search AD account properties pulling from a CSV. The Import-CSV line works by itself. I cannot for the life of me figure out why it is asking for a filter. I took this from another script I found where they said it worked. Others were using a For-Each statement.
PS C:\Users\XXXXX> Import-CSV .\listofnames.csv | Get-ADUser $_.DisplayName -properties displayname
Get-ADUser : Cannot validate argument on parameter 'Identity'. The argument is null or an element of the argument
collection contains a null value.
At line:1 char:43
+ Import-CSV .\listofnames.csv | Get-ADUser $_.DisplayName -properties ...
+ ~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Get-ADUser], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.GetADUser
Its prompting you for the 'Identity' because that is how it identifies what user you are searching for.
Try this:
$users = get-content C:\Temp\test.csv
foreach ($user in $users){Get-ADUser -Identity $user -Properties displayname}
The CSV file just has the user IDs for the users who you would like to find info for.
Or if you can try the following:
Import-Csv C:\Temp\users.csv | ForEach-Object { Get-ADUser -identity $_.Name -Properties displayname }

Change Active Directory titles for all csv users

I would like to change 150 employees their job title.
I have a csvfile called Titletest.csv with columns UserPrincipalName [the user.name under it] and Title [job title under it]
The PowerShell script:
Import-Module ActiveDirectory
$users = Import-Csv -Path c:\scripts\Titlestest.csv | Foreach-Object {
$user = $_.user
$title = $_.title
#Selects the specified user and sets Job Title
Get-ADUser -Filter {(UserPrincipalName -eq $user)} | Set-ADUser -Title $title
}
I get errors saying:
Get-ADUser : Variable: 'user' found in expression: $user is not defined.
At line:14 char:1
+ Get-ADUser -Filter {(UserPrincipalName -eq $user)} | Set-ADUser -Titl ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-ADUser], ArgumentException
+ FullyQualifiedErrorId : ActiveDirectoryCmdlet:System.ArgumentException,Microsoft.ActiveDirectory.Management.Commands.GetADUser
Can someone please advise?
Thank you.
The reason for your error is because $user has no assignment. You are attempting to assign $user the value of a property that does not exist. The header user apparently does not exist in your CSV file. See below for how to convert a csv into PowerShell objects and access their properties.
# Sample CSV TitleTest.csv
UserPrincipalName,Title
covid19#domain.com,Usurper
jsmith#domain.com,CEO
bossman#domain.com,CFO
Import-Csv -Path c:\scripts\TitleTest.csv | Foreach-Object {
$user = $_.UserPrincipalName
$title = $_.Title
Get-ADUser -Filter 'UserPrincipalName -eq $user' | Set-ADUser -Title $title
}
Explanation:
When using Import-Csv on a proper CSV file, the first row of delimited data will be converted to the properties of all input objects. All succeeding rows will be converted to individual objects with the header properties and output as a collection (array) of those objects. If the -Header parameter is used, then values passed into the parameter will become the properties of the objects. It is important to have the same number of delimited items on each row to ensure proper mapping.
Once you are dealing with objects, you can access their property values using the member access operator .. The syntax is object.property. So since you have headers UserPrincipalName and Title, you will need to use $_.UserPrincipalName and $_.Title to access the associated values.
$_ is the current pipeline object within your Foreach-Object {} script block.
Note that you don't technically need to define $user and $title here. You can just access the properties directly from the current object:
Import-Csv -Path c:\scripts\TitleTest.csv | Foreach-Object {
Get-ADUser -Filter "UserPrincipalName -eq '$($_.UserPrincipalName)'" |
Set-ADUser -Title $_.Title
}

How to query ManagedBy property of ADComputer in a Foreach loop?

I'm trying to generate a list of computers owned by a particular PDL and I'm encountering some syntax issues:
$group = Get-ADGroupMember -Identity "pdl" | Select-Object -ExpandProperty DistinguishedName
Foreach($item in $group) { Get-ADComputer -Filter "ManagedBy -eq "$item"" -Property managedby | Select Name }
The second part is based on another code snippet that I found elsewhere (I think on StackOverflow as well) which worked just fine:
Get-ADComputer -Filter "ManagedBy -eq 'CN=user#company.com,OU=US,OU=Users,OU=Accounts,DC=americas,DC=company,DC=com'" -Property ManagedBy
But the difference is I could use '' in this one, but adding in $item prevents me from using that.
The syntax error I get back with the first snippet:
Get-ADComputer : A positional parameter cannot be found that accepts argument 'CN=user#company.com,OU=US,OU=Users,OU=Accounts,DC=americas,DC=company,DC=com'.
At D:\Documents\Scripts\uatgroup.ps1:2 char:31
+ Foreach($item in $UATgroup) { Get-ADComputer -Filter "ManagedBy -eq "$item"" -Pr ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-ADComputer], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.ActiveDirectory.Management.Commands.GetADComputer
Anyone know a way to fix the syntax here? Or an alternate method of running this?
This:
"ManagedBy -eq "$item""
Is parsed as three separate strings. Only the first one (ManagedBy -eq) will be bound to the -Filter parameter, the rest will be treated as separate tokens, causing PowerShell to complain that you can't just leave the string CN=... there in the middle of everything.
You can either use single-quotes inside the double-quoted string, to avoid terminating the string early:
Get-ADComputer -Filter "ManagedBy -eq '$item'"
Escape the inline double-quotes with a backtick ( ` ):
Get-ADComputer -Filter "ManagedBy -eq `"$item`""
Or escape them by doubling them:
Get-ADComputer -Filter "ManagedBy -eq ""$item"""

powershell, Variable: '_' found in expression: $_

I am fairly new to powershell and I am currently employing it to work around a few administration tasks for the Helpdesk.
I have a problem with trying to move an AD object (forgive me if the following terminology is used incorrectly) based on the property of on object from an imported CSV.
The CSV is:
UserPrincipalname,UserToAccess,DaysToLive
joe#company.com,dave#company.com,90
and so on...
I then pass the array through a ForEach loop to move the AD account:
foreach ($line in $import) {Get-ADUser -filter {userPrincipalName -eq $_.UserToAccess} -SearchBase "DistinguishedName of OU" | Move-ADObject -TargetPath 'DistinguishedName of OU'}
Subsequently I am getting the following error:
Get-ADUser : Variable: '' found in expression: $.UserToAccess is not
defined. At D:\jason\EnableArchiveAccess.ps1:17 char:29
+ foreach ($line in $import) {Get-ADUser -filter {userPrincipalName -eq $.UserToA ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-ADUser], ArgumentException
+ FullyQualifiedErrorId : Variable: '' found in expression: $_.UserToAccess is not defined.,Microsoft.ActiveDirec
tory.Management.Commands.GetADUser
I have been able to use the above logic to unhide users from the GAL and I have checked the array and the properties are there as noteproperties.
I assume it's because I am using not AD variables in the command but any help would be much appreciated but if I find the answer sooner I will post back.
Just looking at that, I think you need to change
$_.UserToAccess
to
$line.UserToAccess
The other alternative would be:
$import | foreach{
Get-ADUser -filter {userPrincipalName -eq $_.UserToAccess} `
-SearchBase "DistinguishedName of OU" `
| Move-ADObject -TargetPath 'DistinguishedName of OU'}
This is one of the common mixups in PowerShell. There are in fact two foreach "keywords". One is alias of the Foreach-Object cmdlet and is used as such:
$Items = 1,2,3
$Items | foreach { $_ }
The $_ in the example means the current object. That is 1 on first pass, 2 on second pass and 3 on the third.
The second foreach is keyword and is used as such
$Items = 1,2,3
foreach ($item in $items) {
$item
}
In this example the $item represents the current object.
So in your example you have to use $list instead of $_.