Search code examples
powershellremote-servershared-directorycopy-item

How to copy files from one server to other server with powershell when the shared path contains '$' symbol


I have 3 remote servers in my hand. Let us say Server X, Server Y and Server Z. I am running my powershell script from my local machine to login to Remote Server X. This Server X is my base server which has access to other 2 servers. I want to use this Server X as base server and want to copy files from Server Y to Server Z which is impossible through my local machine because of access permissions. So I logged in to Server X using admin credentials which has access to all 3 servers. After logging in, I am just mentioning copy-item command to copy files from shared path of Server Y to Shared Path of Server Z.

This is a similar question to many in this website here goes a twist. When I am debugging, it is showing completed but I am not getting any results. So I tried running this powershell script directly in Server X which contains only copy-item command and source and destination paths of shared folders. When I am debugging I am getting error that, user doesn't have permissions or path is not found. When I am trying to copy and paste files from shared path manually using the same credentials, it is working. But through powershell script, it's now working. I know the reason. It's because of symbol '$' in the shared paths. So I need the solution for this. It is not allowing '$' symbol in my source and destination paths. Is there any alternative for this? If I try to remove that symbol and copy the files, I get the 'Access Denied' Error as it is a shared path, E drive should prefixed with $ symbol.

Here goes my code:

 #Calling my Server Name, Credentials from App.Config File 

$currentDirectory = [IO.Path]::GetDirectoryName($MyInvocation.MyCommand.Path)
 $appConfigFile = [IO.Path]::Combine($currentDirectory, 'App.config')
 $appConfig = New-Object XML
 $appConfig.Load($appConfigFile)

 $ServerName = $appConfig.configuration.appSettings.add[0].value
 $Username = $appConfig.configuration.appSettings.add[1].value
 $Password = ConvertTo-SecureString -String $appConfig.configuration.appSettings.add[2].value -AsPlainText -Force 

 $cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $Username,$Password

Logging to Server X using credentials and copying files from Server Y to Server Z

 Invoke-command -ComputerName $ServerName -Credential $cred -ScriptBlock { 

 Copy-Item "\\ServerY\E$\SourceTestFolder\Test.docx" "\\ServerZ\E$\DestTestFolder" }

Solution

  • First idea: Replace the " with '. So powershell stops to fall over the $-symbols. The way you have written it now says: "Hey powershell, go ahead and look for a variable named $E and put it in there".