Issue for import-csv and foreach - powershell

I want to import a csv, then delete from AD several objects
$ImportComputer = "C:\Users\deng\Desktop\ComputerLastlogondateformatBis.csv"
Import-Module ActiveDirectory
foreach ($Computer in(Import-Csv -Path C:\Users\deng\Desktop\ComputerLastlogondateformatBis.csv))
{
Remove-ADObject -Identity $Computer.'Computer'
these two object exist in AD, but I cannot seem to find out why it is not working.
see below error message:
Remove-ADObject : Cannot find an object with identity: 'fr-borr-mac' under: 'DC=PII,DC=net'.
At C:\Users\deng\OneDrive - Aptus Health\Script\Export.ps1:7 char:1
+ Remove-ADObject -Identity $Computer.'Computer'
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (fr-borr-mac:ADObject) [Remove-ADObject], ADIdentityNotFoundException
+ FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,Microsoft.ActiveDirectory.Management.Commands.RemoveADObject
Remove-ADObject : Cannot find an object with identity: 'jlinmacfr' under: 'DC=PII,DC=net'.
At C:\Users\deng\OneDrive - Aptus Health\Script\Export.ps1:7 char:1
+ Remove-ADObject -Identity $Computer.'Computer'
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Content of the CSV below:
Computer
--------
fr-borr-mac
jlinmacfr
Could anyone give input on this?

The -Identity parameter on the *-ADObject commands expect either a DistinguishedName or Guid value. If you are wanting to work with SamAccountName or some other attribute, you should consider using the *-ADComputer or using -Filter to find your objects.
# Using Remove-ADObject
Remove-ADObject -Filter "SamAccountName -eq '$($Computer.Computer)'"
# Using Remove-ADComputer
Remove-ADComputer -Identity $Computer.Computer
Alternatively, you can use Get-ADComputer or Get-ADObject to retrieve your object first and then pipe that into Remove-ADObject.
Get-ADObject -Filter "SamAccountName -eq '$($Computer.Computer)'" | Remove-ADObject
See the Remove-ADObject documentation for the following excerpt regarding explicitly binding to -Identity:
Specifies an Active Directory object by providing one of the following
property values. The identifier in parentheses is the Lightweight
Directory Access Protocol (LDAP) display name for the attribute. The
acceptable values for this parameter are:
A distinguished name
A GUID (objectGUID)
For piping an object into Remove-ADObject, the following excerpt applies, which is why you can use a Get-AD* command and pipe the result into the Remove-ADObject:
This parameter can also get this object through the pipeline or you
can set this parameter to an object instance.
Derived types, such as the following, are also accepted:
Microsoft.ActiveDirectory.Management.ADGroup
Microsoft.ActiveDirectory.Management.ADUser
Microsoft.ActiveDirectory.Management.ADComputer
Microsoft.ActiveDirectory.Management.ADServiceAccount
Microsoft.ActiveDirectory.Management.ADFineGrainedPasswordPolicy
Microsoft.ActiveDirectory.Management.ADDomain

Related

Powershell Filter doesn't accept comma

I try to use the Get-User command with a simple Filter.
Get-User -Filter "(Manager -eq 'Max, Mustermann')"
The problem is that i get this exception:
Cannot bind parameter 'Filter' to the target. Exception setting "Filter": "The value "Max, >Mustermann" could not be converted to type
Microsoft.Exchange.Data.Directory.ADObjectId.
"(Manager -eq 'Max, Mustermann')" at position 34."
In C:\Users\JAKO\AppData\Local\Temp\tmp_4vtu0s13.ymv\tmp_4vtu0s13.ymv.psm1:38356 Zeichen:9
$steppablePipeline.End()
~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : WriteError: (:) [Get-User], ParameterBindingException
FullyQualifiedErrorId : >ParameterBindingFailed,Microsoft.Exchange.Management.RecipientTasks.GetUser
As far as I understand the Problem its because of the comma, so i tryed some workaorunds.
Get-User -Filter "(Manager -like 'Max, Mustermann')"
Here I dont get an exception but there are no Users that get returned.
Get-User -Filter "(Manager -eq 'Max"," Mustermann')"
The same as with the other workaround. No exception but no Users are Matching.
I also made sure that i have Users that would match this specift query, by using this command
Get-User -Filter | Format-List Manager
How can I write my Filter input so it matches "Max, Mustermann"?
From the filtering documentation for the Manager attribute:
This filter requires the distinguished name or canonical distinguished name of the manager (a mailbox or mail user). For example, Get-User -Filter "Manager -eq 'CN=Angela Gruber,CN=Users,DC=contoso,DC=com'" or Get-Mailbox -Filter "Manager -eq 'contoso.com/Users/Angela Gruber'".
To find the distinguished name of a manager, replace with the name, alias, or email address of the recipient, and run this command: Get-Recipient -Identity "<RecipientIdentity>" | Format-List Name,DistinguishedName.
So now we know why the filter isn't working (a distinguished name is expected), and how to obtain the correct value (by using Get-Recipient):
# Fetch manager's user account object
$targetUser = Get-Recipient -Filter "SimpleDisplayName -eq 'Max, Mustermann'"
# Fetch reports
Get-User -Filter "Manager -eq '$($targetUser.DistinguishedName)'"

I created a new custom attribute in ActiveDirectory. How can I modify it in PowerShell?

I created a new custom attribute like: newattribute1, but when I want to change the value in PowerShell, I got an error.
Set-ADUser -Identity test1 -newattribute1 123as
The error message:
Set-ADUser : A parameter cannot be found that matches parameter name
'newattribute1'.
At line:1 char:29
+ Set-ADUser -Identity test1 -newattribute1 123as
+ ~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Set-ADUser], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.ActiveDirectory.Management.Commands.SetADUser
I always use:
Set-ADUser -identity <username> -replace #{CustomAttribute="YourData"}
By using the replace function, you can specify the custom attribute that you created. It an easy way to change attributes which cannot be specified by the cmdlet itself. This doesn't only work for custom attributes, you can use the replace function for attributes such as phone number. Anything that the cmdlet doesn't let you modify by default.
On a bit of a side note, you can't just make up parameters to add to an existing cmdlet like you had -newattribute1 123as.
You will need to modify a copy of the ADUser object, then write the copy back using the -Instance parameter of Set-ADUser:
$user = Get-ADUser -Identity $samaccountname -Properties *
$user.YourCustomAttribute = $NewCustomAttributeValue
Set-ADUser -Instance $User
See Get-Help Set-ADUser.

PowerShell - Return value of AD User's First and Last name

I am attempting to pull a users first and last name from AD using PowerShell.
The commands:
$GivenName = Get-ADUser -Identity $User | select GivenName
Write-Host $GivenName
returns a value of: #{GivenName=Bruce}
I then tried to reduce the string down to just the part i need with the following commands:
$First = $GivenName.Replace("#{GivenName=","")
$First = $First.Replace("}","")
This should strip away all except for the string 'Bruce'
Instead I get this following error:
Method invocation failed because [Selected.Microsoft.ActiveDirectory.Management.ADUser] does not contain a method named 'Replace'.
At C:\Users\john.ring\Documents\Scripts\UpdateADUsers.ps1:10 char:5
+ $First = $GivenName.Replace("#{GivenName=","")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (Replace:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
My Google-fu has failed to find a solution. Any suggestion on how to correct the error or a better way to pull the users first name would be greatly appreciated.
When you pipe objects to Select-Object [propertyname(s)], the Select-Object cmdlet creates a new object for you, with the properties from the input object that you specified. This object in turn ends up being rendered as #{PropertyName1=PropertyValue1[;PropertyNameN=PropertyValue2]} when converted to a string.
To grab the value of a single property, and nothing else, use the -ExpandProperty parameter:
$GivenName = Get-ADUser -Identity $user |Select-Object -ExpandProperty GivenName
Since you need multiple properties from the same user, better store the the user in a variable and use the . dereference operator to access the GivenName and Surname properties:
$UserObject = Get-ADUser -Identity $user
$GivenName = $UserObject.GivenName
$Surname = $UserObject.Surname
GivenName is a user object attribute in Active Directory. You're storing the results of your query in a PowerShell object called $GivenName, however the two are not the same. To reference the user's given name, you need to reference the GivenName property of the PowerShell object. $GivenName.GivenName is what you are looking for.
It might be less confusing if you store the results of your AD query in an object named $User instead, so $User.GivenName is how you would reference the given name property.

PowerShell Newb - Cannot convert

I'm learning Powershell and I'm trying to understand why this isn't working. I verified that -Identity accepts pipeline so I'm guessing its the type of value its passing but I don't understand why this doesn't work
Get-ADUser -Identity (Import-Csv .\GROUP.csv)
GROUP.csv is a file on my desktop which contains a list of SIDs. I can read it with no issues when just doing an Import-Csv .\GROUP.csv. Here is the result
S-1-5-21-583907252-1979792683-725345543-112088
S-1-5-21-583907252-1979792683-725345543-48881
S-1-5-21-583907252-1979792683-725345543-48880
S-1-5-21-583907252-1979792683-725345543-53776
S-1-5-21-583907252-1979792683-725345543-125569
S-1-5-21-583907252-1979792683-725345543-120374
S-1-5-21-583907252-1979792683-725345543-48882
S-1-5-21-583907252-1979792683-725345543-183175
S-1-5-21-583907252-1979792683-725345543-183136
S-1-5-21-583907252-1979792683-725345543-183130
S-1-5-21-583907252-1979792683-725345543-183112
S-1-5-21-583907252-1979792683-725345543-176034
S-1-5-21-583907252-1979792683-725345543-176023
S-1-5-21-583907252-1979792683-725345543-176022
S-1-5-21-583907252-1979792683-725345543-176002
S-1-5-21-583907252-1979792683-725345543-175974
S-1-5-21-583907252-1979792683-725345543-175931
S-1-5-21-583907252-1979792683-725345543-175889
S-1-5-21-583907252-1979792683-725345543-175836
S-1-5-21-583907252-1979792683-725345543-175804
S-1-5-21-583907252-1979792683-725345543-183195
S-1-5-21-583907252-1979792683-725345543-183180
S-1-5-21-583907252-1979792683-725345543-31219
S-1-5-21-583907252-1979792683-725345543-176037
S-1-5-21-583907252-1979792683-725345543-82576
S-1-5-21-583907252-1979792683-725345543-175905
S-1-5-21-583907252-1979792683-725345543-175777
S-1-5-21-583907252-1979792683-725345543-175765
On top of that I can use the Get-ADUser -Identity and that works fine.
Why do I get the following when trying piping the one to the other?
Cannot convert 'System.Object[]' to the type 'Microsoft.ActiveDirectory.Management.ADUser' required by parameter 'Identity'.
Specified method is not supported.
At line:1 char:22
+ Get-ADUser -Identity (Get-Content .\group.txt)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-ADUser], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgument,Microsoft.ActiveDirectory.Management.Commands.GetADUser
The -identity parameter doesn't accept array as input but it accept pipeline input by value than you can do:
Import-Csv .\GROUP.csv | Get-ADUser
If the name of the first column in .csv file is sid then you can try this option too
(Import-CSV .\Group.csv) | foreach-object { get-aduser -Identity $_.sid }

Add bulk computer membership

Im trying to add multiple compuers (from a txt file) to be part of a certain security group.
sample from input.txt
COL7DM2CP1
COLC5RNDP1
using the following powershell input:
Get-Content C:\Scripts\input.txt | Add-ADPrincipalGroupMembership -MemberOf 'AMATU.SCCM.Office2010.Std'
however im getting the following outpout error:
Add-ADPrincipalGroupMembership : Cannot find an object with identity: 'COL7DM2CP1' under: 'DC=actuant,DC=pri'.
At C:\Scripts\Add bulk ADcomputer to group.ps1:1 char:36
+ Get-Content C:\Scripts\input.txt | Add-ADPrincipalGroupMembership -MemberOf 'AMA ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (COL7DM2CP1:ADPrincipal) [Add-ADPrincipalGroupMembership], ADIdentityN
otFoundException
+ FullyQualifiedErrorId : SetADPrincipalGroupMembership:ProcessRecordOverride,Microsoft.ActiveDirectory.Manageme
nt.Commands.AddADPrincipalGroupMembership
The issue is that the Add-PrinicpalGroupMembership does not know what object you are looking for. It does not query AD for the simple computername, it assumes the FQDN. If you wanted to pass it just a name, you'll need to give it's full AD Distinguished Name.
An easy way around this is to use Get-ADcomputer and pass that to Add-PrinicpalGroupMembership
Get-Content C:\Scripts\input.txt | Get-ADComputer | Add-ADPrincipalGroupMembership -MemberOf 'AMATU.SCCM.Office2010.Std'