Passing a password into -Credential

Hi Guys,

I’ve been trying to rack my brains figuring this out and after Googling I’ve still not found a solution.

I have a script that will loop through a group in Active Directory and pull all the members from that group. Some of the members in that group are on a different domain to the one the group is located.

I’ve got it working fine without any issue my problem is, is if there is a group with 20 members in it and 8 of those members are on the other domain I have to type in the credentials maunally for each user. I have to go through about 40 groups so this could be a bit tedious after a while. There is only one other domain so the username and password will always be the same.

A snippet of my current code is:

$accountQuery = Get-ADGroup $group -Properties Member | Select -Expand Member | Get- ADObject -Properties * | Select -Expand Name Foreach($name in $accountQuery){ $i++ if($name -match "S-1"){ $sidName = Get-ADUser -Server 2ndDomain.local -Credential 2ndDomainadmin -Identity $name -Properties * | Select-Object -Expand SamAccountName Write-Host $sidName } 

The code works fine, a box pops up asking for a username for each user.

I have tried this:

$accountQuery = Get-ADGroup $group -Properties Member | Select -Expand Member | Get-ADObject -Properties * | Select -Expand Name $2ndUsername = "2ndDomainadmin" $secPassword = ConvertTo-SecureString "password" -AsPlainText -Force $myCreds = New-Object System.Management.Automation.PSCredential ("$2ndUsername","$secPassword") Foreach($name in $accountQuery){ $i++ if($name -match "S-1"){ $sidName = Get-ADUser -Server 2ndDomain.local -Credential $myCreds -Identity $name -Properties * | Select-Object -Expand SamAccountName Write-Host $sidName } 

However I get the error: New-Object : Cannot find an overload for “PSCredential” and the argument count: “2”.

Is there a way I can just pass the password through the -Credential to save me the time typing it.

And if case anyone was wondering I am using this odd query:

$accountQuery = Get-ADGroup $group -Properties Member | Select -Expand Member | Get-ADObject -Properties * | Select -Expand Name 

Because querying just for that group errors due to the fact it can’t the users in another domain, so it’s a bit long winded.

Any help would be awesome!

submitted by /u/HappyHitman
[link] [comments]

Leave a Reply