-1

I am writing a script, that creates a new VM, connects to it via New-PSSession and runs serveral Commands to alter a few settings and copy folders from a UNC path to the local C: and C:\Program files (x86).

Everything works fine expect the copy part - I get an error saying

permission denied.

I run the script itself as domain admin and the credentials I pass also has domain admin rights.

For example:

$source = '\\server\share'
$cred = Get-Credential
$pss = New-PSSession -ComputerName "$computername" -Credential $cred
Invoke-Command -Session $pss -ScriptBlock {
    Copy-Item "$source\FOLDER" -Destination 'C:\FOLDER' -Recurse -Force -
Credential 
$cred

Even if I pass the cedentials it fails. A quick search results in "use robocopy", but in my opinion it must be possible to copy files from a UNC path to a local directory with PowerShell even if that directory is basically protected by Microsoft.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Kuroda
  • 1
  • 1
  • 2

3 Answers3

0

I think you need to pass the variable to the remote session:

invoke-Command -Session $pss -Args $source -ScriptBlock{Copy-Item "$args[0]\FOLDER" ...}

otherwise $source is considered a variable in the remote session and since it doesn't exist there ps will try to copy from \Folder

whatever
  • 871
  • 4
  • 11
  • ah, yep, my fault. Actually I did that in my current Script and the variable is known and resolvable inside the remote session. – Kuroda Aug 24 '17 at 12:22
  • I got the same error with an interactive session using enter-pssession and solved it with new-psdrive -name Y -PSProvider FileSystem -Root $source -Credential $cred set-location Y: doing this I am able to copy files. I put this into my new-pssession and let my script run. It'll now take a time and I'll write as soon as i got an result I – Kuroda Aug 24 '17 at 12:25
0

You can try to use -ToSession parametr without entering to PSSession.

$ses = New-PSSession -ComputerName WorkStation


Copy-Item -ToSession $ses -Destination C:\users\TempUser\Documents\ -Path '\\10.0.0.1\share\' -Recurse
0

My solution for Copy-Item is:

-Destination $($(dir "env:programfiles(x86)").value + "\Avest\AvPCM_nces\")
HatLess
  • 10,622
  • 5
  • 14
  • 32