Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

copy-item With Alternate Credentials

I'm using the CTP of powershell v2. I have a script written that needs to go out to various network shares in our dmz and copy some files. However, the issue I have is that evidently powershell's cmdlets such as copy-item, test-path, etc do not support alternate credentials...

Anyone have a suggestion on how best to accomplish my task..?

like image 888
xspydr Avatar asked Mar 04 '09 19:03

xspydr


People also ask

Does copy item overwrite?

By default, when you will copy item in PowerShell using the Copy-Item, it will overwrite the files in the destination folder. The above PowerShell script will overwrite the files but it will show an error for folders: Copy-Item : An item with the specified name D:\Bijay\Destination\Folder1 already exists.

How do I pass credentials in PowerShell without prompt?

$cred = Get-Credential without asking for prompts in powershell - Microsoft Tech Community.

Does xcopy work in PowerShell?

xcopy is the windows command. It works with both PowerShell and cmd as well because it is a system32 utility command.


2 Answers

I have encountered this recently, and in the most recent versions of Powershell there is a new BitsTransfer Module, which allows file transfers using BITS, and supports the use of the -Credential parameter.

The following sample shows how to use the BitsTransfer module to copy a file from a network share to a local machine, using a specified PSCredential object.

Import-Module bitstransfer $cred = Get-Credential $sourcePath = \\server\example\file.txt $destPath = C:\Local\Destination\ Start-BitsTransfer -Source $sourcePath -Destination $destPath -Credential $cred 

Another way to handle this is using the standard "net use" command. This command, however, does not support a "securestring" password, so after obtaining the credential object, you have to get a decrypted version of the password to pass to the "net use" command.

$cred = Get-Credential $networkCred = $cred.GetNetworkCredential() net use \\server\example\ $networkCred.Password /USER:$networkCred.UserName Copy-Item \\server\example\file.txt C:\Local\Destination\ 
like image 66
chills42 Avatar answered Oct 14 '22 12:10

chills42


Since PowerShell doesn't support "-Credential" usage via many of the cmdlets (very annoying), and mapping a network drive via WMI proved to be very unreliable in PS, I found pre-caching the user credentials via a net use command to work quite well:

# cache credentials for our network path net use \\server\C$ $password /USER:$username 

Any operation that uses \\server\C$ in the path seems to work using the *-item cmdlets.

You can also delete the share when you're done:

net use \\server\C$ /delete 
like image 26
wes Avatar answered Oct 14 '22 10:10

wes