When i try to run invoke-command for every computer in Active-Directory , i will encounter the following error : "Invoke-Command : One or more computer names are not valid. If you are trying to pass a URI, use the -ConnectionUri parameter, or pass URI objects instead of strings. "
```
$Hosts_Array=Get-ADComputer -Properties CN -Filter * | Sort-Object | Select-Object CN
foreach ($i in $Hosts_Array) {
Invoke-Command -ComputerName $i -ScriptBlock { Get-Service -Name "sysmon64"}
}
```
I use the For loop to run the command for every computer that fetch from the AD.
As commented, Select-Object
returns objects, in this case objects with just one property called 'CN'.
In fact, you don't need to ask for the CN at all, because Get-ADComputer
returns these properties by default:
DistinguishedName, DNSHostName, Enabled, Name, ObjectClass, ObjectGUID, SamAccountName, SID, UserPrincipalName
You can simplify your code by doing:
$Hosts_Array = (Get-ADComputer -Filter *).Name | Sort-Object
foreach ($computer in $Hosts_Array) {
Invoke-Command -ComputerName $computer -ScriptBlock { Get-Service -Name "sysmon64" }
}
(Get-ADComputer -Filter *).Name
returns a string array of just the computer names, which can also be done using Get-ADComputer -Filter * | Select-Object -ExpandProperty Name
P.S. I have changed the variable name to iterate with from $i
(usually used in numbered loops) into $computer
to make it clearer
Each object in AD has a Relative Distinguished Name
(RDN). This is the name of the object in it's parent OU/Container. For user, group, computer, and container objects, the RDN is the value of the cn
attribute (Common Name). For OU objects, the RDN is the value of the ou
attribute. For domain component objects, it's the dc
attribute.
The Name
property returns the RDN of any object.