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..?
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.
$cred = Get-Credential without asking for prompts in powershell - Microsoft Tech Community.
xcopy is the windows command. It works with both PowerShell and cmd as well because it is a system32 utility command.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With