Get-adcomputer field into variable includes cr/lf - powershell

I am trying to get the computers distinguished name, set it into a variable $dname
Then I can use the disable computer command disable-adaccount -Identity $dname
$hostname is set OK as "WIN10TEST1"
When using this command
$dname = (Get-ADcomputer -Identity "$hostname" | select DistinguishedName | ft -hide)
It fails like this:
disable-adaccount -Identity $dname
Disable-ADAccount : Cannot convert 'System.Object[]' to the type
'Microsoft.ActiveDirectory.Management.ADAccount' required by parameter
'Identity'. Specified method is not supported. At line:1 char:29
+ disable-adaccount -Identity $dname
+ ~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Disable-ADAccount], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgument,Microsoft.ActiveDirectory.Management.Commands.DisableADAccount
If I set the variable manually
$dname=CN=WIN10TEST1,OU=Workstations,DC=somedomain,DC=local
disable-adaccount -Identity $dname
It works OK so its a problem with the variable coming in.
When examining the returned data in $dname it comes back with a cr/lf before and after the data I need. I think this is tripping it up.
$hostname = "WIN10TEST1"
$dname = (Get-ADcomputer -Identity "$hostname" | select DistinguishedName | ft -hide)
disable-adaccount -Identity $dname
Note: Check $dname.....it returns with cr/lf before/after data
I expect to get the distinquishedname string with no other data
CN=WIN10TEST1,OU=Workstations,DC=somedomain,DC=local

As #Lee_Dailey mentions, there is no need to use Select, or Format Table on anything because they are meant for display only, and will mess with your data in unintended ways if you save that formatted data to a variable.
With Active Directory PowerShell module you can simply pass the Computer object to Disable-ADAccount, and it knows how to identify and handle it:
$computer = Get-ADcomputer -Identity "$hostname"
Disable-ADAccount -Identity $computer

Related

Failing to iterate over AdComputer names to get description

I am using ActiveDirectory and Powershell to get the description of computers in the AD Group
However, when I try to get batch output, I get InvalidArgument error in powershell
When I use a single line:
Get-AdComputer -Filter * -Identity **COMPUTERNAME **-Properties * | Select-Object name, description
I get the correct response:
Name Description
---- -----------
COMPUTERNAME Computer description
However, when I use the this code to get a batch of results:
$UL = Get-ADGroupMember -identity "Groupname"| Select-Object name
Foreach ($i in $UL.Name)
{
$i.ToString()
Write-Host $i.GetType()
Get-AdComputer -Filter * -Identity "$i" -Properties * | Select-Object name, description
}
I keep getting this error:
Get-ADComputer : Parameter set cannot be resolved using the specified named parameters.
At C:\apps\ActiveDirectory_UserList.ps1:6 char:1
+ Get-AdComputer -Filter * -Identity "$i" -Properties * | Select-Object ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-ADComputer], ParameterBindingException
+ FullyQualifiedErrorId : AmbiguousParameterSet,Microsoft.ActiveDirectory.Management.Commands.GetADComputer
As commented by Abraham Zinala, you cannot use both -Filter and -Identity together as these parameter sets rule eachother out giving you the error message
Parameter set cannot be resolved using the specified named parameters.
Next, Get-ADGroupMember will not just return computer objects,
but also users and other groups can be members of one particular group.
Therefore, if you want to get output for computer objects only, you will need to filter out the other object types.
Luckily, each group member has a property called objectClass. This is a string containing either 'user', 'computer' or 'group',
so it is realy quite easy to check on that:
# get all members of the group, filter with a Where-Object clause to receive only computer objects
$members = Get-ADGroupMember -Identity "Groupname" | Where-Object {$_.objectClass -eq 'computer'}
foreach ($computer in $members) {
$computer | Get-ADComputer -Properties Description | Select-Object Name, Description
}
By default, Get-ADComputer returns objects with these properties:
DistinguishedName, DNSHostName, Enabled, Name, ObjectClass, ObjectGUID, SamAccountName, SID, UserPrincipalName, so in this case you only have to ask for the extra property Description

Updating Active Directory Manager Attribute from .csv Using PowerShell

I'm not so good at PowerShell. I have this script which worked before that I've have used to update the manager attribute in Active Directory, however, now after just replacing the file its no longer working
$Users = Import-CSV C:\Documents\Managers.csv
ForEach ($User in $Users) {
$user= Get-ADUser -Filter "displayname -eq '$($Users.EmployeeFullName)'"|select -ExpandProperty samaccountname
$manager=Get-ADUser -Filter "displayname -eq '$($Users.'Line Manager Fullname')'"|select -ExpandProperty DistinguishedName
Set-ADUser -Identity $user -Replace #{manager=$manager}
}
when running the script it returns:
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:6 char:22
+ Set-ADUser -Identity $user -Replace #{manager=$manager}
+ ~~~~~
+ CategoryInfo : InvalidData: (:) [Set-ADUser], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.SetADUser
the "EmployeeFullName" and "Line Manager FullName" format in the .csv is set as i.e. joe bloggs, see below CSV file example.
EmployeeFullname Line Manager Fullname
---------------- ---------------------
Kieran Rhodes Tracey Barley
Lewis Pontin Tracey Barley
Lizzy Wilks Rodney Bennett
I also noticed if I remove and try to retype "$Users.EmployeeFullName" it no longer picks up the "EmployeeFullName" from the csv file.
Anyone know what I'm doing wrong here please?
Below would be an example:
$Users = Import-CSV C:\Documents\Managers.csv
ForEach ($User in $Users) {
$user = Get-ADUser -Filter "displayname -eq '$($User.EmployeeFullName)'"
$manager = (Get-ADUser -Filter "displayname -eq '$($User.'Line Manager Fullname')'").DistinguishedName
Set-ADUser -Identity $User -Replace #{manager=$manager}
}
Note: you don't need to dig down to the samAccountName property because Set-ADUser will take the full fidelity object for the -Identity argument. You also don't need to use Select... -ExpandProperty you can just parenthetically dot reference the distinguishedName property.
Also you can use the instancing capability in the AD cmdlets:
$Users = Import-CSV C:\Documents\Managers.csv
ForEach ( $User in $Users )
{
$User = Get-ADUser -Filter "displayname -eq '$($User.EmployeeFullName)'" -Properties Manager
$Manager = (Get-ADUser -Filter "displayname -eq '$($User.'Line Manager Fullname')'").DistinguishedName
$User.Manager = $Manager
Set-ADUser -Instance $User
}
In this case you call back the Manager property set it with a simple assignment statement than give the $User variable as the argument to the -Instance parameter of Set-ADUser

foreach loop gives error CategoryInfo : InvalidData: (:) [Get-ADUser], ParameterBindingValidationException

I am trying to run a cmdlet on each element of a list. but i am getting the error ObjectNotFound: (*#{samAccountName=my_ad_username}*:ADUser) [Get-ADUser], ADIdentityNotFoundException for each element of my list.
Bellow is cmdlet
$users = Get-ADUser -Filter "*" -SearchBase "OU=Europe,DC=myDC,DC=com" | select samAccountName
$fr_all_grp_assigned_to_different_users = Foreach ($user in $users){
#Get-AdUser $user
}
Result
> Get-ADUser : Cannot validate argument on parameter 'Identity'. The
> Identity property on the argument is null or empty. At line:6 char:20
> + Get-aduser $user
> + ~~~~~
> + CategoryInfo : InvalidData: (:) [Get-ADUser], ParameterBindingValidationException
> + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.GetADUser
> Get-ADUser : Cannot validate argument on parameter 'Identity'. The
> Identity property on the argument is null or empty. At line:6 char:20
> + Get-aduser $user
Line 6 refers to #Get-AdUser $user
Can anyone help ?
Inside of your loop, you need to provide the SamAccountName value to the -Identity parameter of Get-ADUser.
Get-ADUser -Identity $user.SamAccountName
Explanation:
You can execute Get-ADUser by providing values manually to parameters or piping objects into the command and let advanced parameter assignment dynamically map values to parameters. Some parameters are positional in that you don't need to specify the parameter name when running the command with a value(s). These features/concepts exists across most PowerShell commands.
In the case of Get-ADUser Value, Value is automatically mapped to parameter -Identity. -Identity expects one of the following values:
A distinguished name
A GUID (objectGUID)
A security identifier (objectSid)
A SAM account name (sAMAccountName)
Get-ADUser has a convenient feature where if you pass it a Microsoft.ActiveDirectory.Management.ADUser object type (returned from a directory server) through a pipe or to the -Identity parameter, it will automatically perform a search based on the provided values. If you provide it any other object type, it will not automatically select property values to pass to -Identity. Piping to Select SamAccountName returns a PSCustomObject rather than an ADUser object and then you lose your convenience.
Once you are dealing with objects that are not ADUser, you must provide -Identity with the actual value you want to query. In your case, that leaves you with two options.
Option 1: Select only SamAccountName values in your initial query
With this option, you can make use of the -ExpandProperty or -Expand parameter of Select-Object to return only the values of the target property.
$users = Get-ADUser -Filter * -SearchBase "OU=Europe,DC=myDC,DC=com" |
Select-Object -ExpandProperty SamAccountName
$fr_all_grp_assigned_to_different_users = Foreach ($user in $users) {
Get-ADUser $user
}
Option 2: Use Member Access operator (.) to directly access the SamAccountName value
With this option you can use the syntax object.Property to retrieve the Property value.
# Using the singular object.Property ($user.SamAccountName)
$users = Get-ADUser -Filter * -SearchBase "OU=Europe,DC=myDC,DC=com" |
Select-Object SamAccountName
$fr_all_grp_assigned_to_different_users = Foreach ($user in $users) {
Get-ADUser $user.SamAccountName
}
Starting with PowerShell v3, you can use the same syntax on a collection to return a collection of values (collection.Property).
# Using collection.Property ($users.SamAccountName)
# $user contains only a SamAccountName value here
$users = Get-ADUser -Filter * -SearchBase "OU=Europe,DC=myDC,DC=com" |
Select-Object -ExpandProperty SamAccountName
$fr_all_grp_assigned_to_different_users = Foreach ($user in $users.SamAccountName) {
Get-ADUser $user
}

Powershell delete all users in OU

I am trying to delete all users within an OU using powershell, I have the below which gets stuck when it comes to the SAMAccount name, I want it to delete all the found users.
What am I doing wrong here please?
$search="OU=Staff,OU=Users,DC=Testing, DC=Local"
$deletes= Get-ADUser -SearchBase $search -filter * -properties SamAccountName | Select-Object SamAccountName
$numusers=($deletes.count)
echo "$numusers Users Found"
foreach ($delete in $deletes)
{
echo "Deleting user account $delete . . . "
remove-aduser -identity $delete -confirm:$false
}
This is the output. Seemingly going wrong here -- Cannot convert the "#{SamAccountName=bbonhomme}"
7 Users Found
Deleting user account #{SamAccountName=bbonhomme} . . .
Remove-ADUser : Cannot bind parameter 'Identity'. Cannot convert value "#{SamAccountName=bbonhomme}" to type
"Microsoft.ActiveDirectory.Management.ADUser". Error: "Cannot convert the "#{SamAccountName=bbonhomme}" value of type
"Selected.Microsoft.ActiveDirectory.Management.ADUser" to type "Microsoft.ActiveDirectory.Management.ADUser"."
At C:\Users\Administrator\Desktop\import\getadusers.ps1:11 char:29
+ remove-aduser -identity #delete -confirm:$false
+ ~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Remove-ADUser], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.ActiveDirectory.Management.Commands.RemoveADUser
Replace the
$deletes= Get-ADUser -SearchBase $search -filter * -properties SamAccountName | Select-Object SamAccountName
by
$deletes= Get-ADUser -SearchBase $search -filter * -properties SamAccountName
Adding Select-Object implies converting ADUser "object" to "Psobject". By consequence subsequent command remove-ADuser does not recognize this type of object.
Replace also :
remove-aduser -identity $deletes -confirm:$false
By
remove-aduser -identity $delete.SamAccountName -confirm:$false
changed $deletes by $delete (you cannot specify a collection in -Identity parameter)

PowerShell script to add computers to group that are not part of another group?

I am trying to pull together a PS script to automatically add computers to a security group that are not part of another group.
In this case, add all computers to group_b that are not part of group_a.
This is what I tried..
#get list of computers from group_a
$tpmobjects = Get-ADGroupMember -Identity "group_a" | Select name
#add computers to group_b that are not in group_a
Get-ADComputer -Filter {SamAccountName -notlike $tpmobjects} | Foreach-Object { Add-ADPrincipalGroupMembership -Identity $_.SamAccountName -MemberOf "group_b" }
The error I get is...
Get-ADComputer : Type: 'System.Object[]' is not supported for extended attribute 'SamAccountName'.
At line:2 char:1
+ Get-ADComputer -Filter {SamAccountName -notlike $tpmobjects}...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-ADComputer], ArgumentException
+ FullyQualifiedErrorId : ActiveDirectoryCmdlet:System.ArgumentException,Microsoft.ActiveDirectory.Management.Commands.GetADComputer
Anyone have a way to do this?
Thanks.
What happens is that Get-ADGroupMember returns multiple objects and the -Filter parameter doesn't support matching against multiple objects.
There are multiple ways around this, but the easiest is to simply filter the output from Get-ADGroupMember with Where-Object:
$Computers = Get-ADGroupMember group_a |Where-Object {$_.objectClass -eq 'computer'}
You also don't need to wrap Add-ADPrincipalGroupMembership in ForEach-Object, it accepts pipeline input, and an ADComputer object can be bound to the -Identity parameter directly without problems:
$Computers |Add-ADPrincipalGroupMembership -MemberOf group_a