I am attempting to copy a file over a network from a Windows 2012r2 server running PowerShell 5.0 to a 2008 r2 server running PowerShell 2.0. I am attempting to do this using the Copy-Item command. The script that executes the command is:

$secPassword = ConvertTo-SecureString $password -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ($userName, $secPassword)
$sessionOptions = New-PSSessionOption -SkipCACheck -SkipCNCheck

$session = New-PSSession -Computername $computerName -SessionOption $sessionOptions -Credential $cred 

Copy-Item -Path $source -Destination $destination -ToSession $session

When executing the command, I receive the following error:

Copy-Item : Unable to index into an object of type System.IO.FileInfo. At C:\Users\pmartin.CLUBSOFTINC\Documents\Repos\Test\PowerShell\test.ps1:21 char:1 + Copy-Item -Path $source -Destination $destination -ToSession $session + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (0:Int32) [Copy-Item], RuntimeException + FullyQualifiedErrorId : CannotIndex

After doing some research, it appears this is caused by a compatibility issue in PSv2 where returning a value at index [0] from a non-array element does not return the element (as compared to PSv5 which would return the element).

Is there a workaround for this issue? If so, how can I implement it within my script?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.