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..?
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\
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
PowerShell 3.0 now supports for credentials on the FileSystem provider. To use alternate credentials, simply use the Credential parameter on the New-PSDrive cmdlet
PS > New-PSDrive -Name J -PSProvider FileSystem -Root \\server001\sharename -Credential mydomain\travisj -Persist
After this command you can now access the newly created drive and do other operations including copy or move files like normal drive. here is the full solution:
$Source = "C:\Downloads\myfile.txt"
$Dest = "\\10.149.12.162\c$\skumar"
$Username = "administrator"
$Password = ConvertTo-SecureString "Complex_Passw0rd" -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential($Username, $Password)
New-PSDrive -Name J -PSProvider FileSystem -Root $Dest -Credential $mycreds -Persist
Copy-Item -Path $Source -Destination "J:\myfile.txt"