Home > Back-end >  Function to copy file on a remote service
Function to copy file on a remote service

Time:03-22

I have written the below function to copy file on a remote server

Function deploy-file{
PARAM(
    [Parameter(Mandatory=$true,Position=0)][STRING]$cred,
    [Parameter(Mandatory=$true,Position=1)][STRING]$server,
    [Parameter(Mandatory=$true,Position=2)][STRING]$destdir,
    [Parameter(Mandatory=$true,Position=3)][STRING]$file
)

    $parameters = @{
        Name = $server
        PSProvider = "FileSystem"
        Root = $destdir
        Credential = $cred
    }
    new-psdrive @parameters
    $d=$server   ":\"           
    copy-item $file $d -force
    
    remove-psdrive $server -ErrorAction SilentlyContinue
}

Now, I am calling the above function from the main file as below:

$sn=abc.com
$server=($sn -split "\.")[0]
$destdir = 'e:\folder'
$file = 'file.zip'
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $usr, $pa
deploy-file $cred $server $destdir $file    

There is no issue with credentials.

My script keeps running and not even throwing any error. What is wrong with the script?

CodePudding user response:

Copying a file to a remote host using a PSSession would be as follows:

function Deploy-File {
    [cmdletbinding()]
    param(
        [Parameter(Mandatory, Position=0)]
        [securestring] $cred,
        [Parameter(Mandatory, Position=1)]
        [string] $server,
        [Parameter(Mandatory, Position=2)]
        [string] $destdir,
        [Parameter(Mandatory, Position=3)]
        [string] $file
    )
    
    try {
        [IO.FileInfo] $file = Get-Item $file
        $session = New-PSSession -ComputerName $server -Credential $cred
        Copy-Item -Path $file -Destination $destdir -ToSession $session
    }
    catch {
        $PSCmdlet.ThrowTerminatingError($_)
    }
    finally {
        if($session) {
            Remove-PSSession $session
        }
    }
}

By looking at your code is hard to tell what could be failing aside from what we know for sure is incorrect, the parameter $cred is being constrained to [string] when it actually should be [securestring]. By doing so you're rendering your PS Credential object unusable.

  • Related