Search code examples
powershellcopy-item

Copy-Item from New-PSDrive within PSSession


I have the following Powershell code:

Enter-PSSession -ComputerName test01 
New-PSDrive -Name Source -PSProvider FileSystem -Root \\test02\SMBTest -Credential test\Administrator 
Copy-Item Source:\Test.txt -Destination C:\Temp
Remove-PSDrive Source 
Exit-PSSession

When I execute each line on it's own it works, but when I save it and run it as a ps1 file it doesn't do anything.

Can anyone help explain why (I'm using Powershell --version 5.1)


Solution

  • Thanks @theincorrigible1 - I've modified it to the below and it is now working.

    $s = New-PSSession -ComputerName test01
    Invoke-Command -Session $s -ScriptBlock {
    New-PSDrive -Name Source -PSProvider FileSystem -Root \\test02\SMBTest -
    Credential test\Administrator
    Copy-Item Source:\Test.txt -Destination C:\Temp
    Remove-PSDrive Source
    }