0

I am trying to run the following script on a DC from a server and i keep getting the error

Cannot bind parameter 'Identity'. Cannot convert value "1" to type "Microsoft.ActiveDirectory.Management.ADComputer". Error: 
"Invalid cast from 'System.Char' to 'Microsoft.ActiveDirectory.Management.ADComputer'."
    + CategoryInfo          : InvalidArgument: (:) [Get-ADComputer], ParameterBindingException
    + FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.ActiveDirectory.Management.Commands.GetADComputer
    + PSComputerName        : dc-test.com

Script code:

$Credentials = New-Object System.Management.Automation.PSCredential -ArgumentList $UserName, $password
$list = gc c:\test.txt
#example of what i would contain $i= Workstation1-"ou=test,dc=test,dc=com"

foreach ($i in $list)
{
  $s=$i.Split('-')

  $ScriptBlock = {
    param ($s) 
    Import-Module ActiveDirectory

    get-adcomputer $s[0] | Move-ADObject -TargetPath $s[1]
  }

  invoke-command -computer dc.test.com -Argu $s -scriptblock $ScriptBlock -cred $Credentials 
}
}

when I run it on the DC it works fine. Can someone point me in the right direction?

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
user1221996
  • 127
  • 1
  • 3
  • 6

1 Answers1

0

The issue here is the fact that you pass array as argument for -ArgumentList parameter. This won't work the way you expect it to. Instead of passing array as a whole, you pass each element of this array to given parameter. There is only one, so only first element of passed array is used.

To understand what is going on try this:

$script = {
    param ($array?)
    $array?[0]
}

$array = 'a1-b2-c3'.Split('-')

Invoke-Command -ScriptBlock $script -ArgumentList $array
Invoke-Command -ScriptBlock $script -ArgumentList (,$array)

So you can either make sure that your array won't be destroyed (using unary comma) or just change code and assume you will get two parameters separately:

$ScriptBlock = {
    param ($comp, $target) 
    Import-Module ActiveDirectory
    get-adcomputer $comp | Move-ADObject -TargetPath $target
}

BTW: I suspect there may be issue with current TargetPath - it will be passed to cmdlet with quotes, so Move-ADObject may fail.

BartekB
  • 8,492
  • 32
  • 33