How To Transfer File Between 2 PSDrives - powershell

I created two PSDrives on my client computer PowerShell session to two different Remote Servers.
New-PSDrive -Name DllFrom -PSProvider FileSystem -Root "\\WPDHSFMSLxx\adap\Database\Install\KareAssistTest\HIDn"
New-PSDrive -Name DllTo -PSProvider FileSystem -Root "\\WTDHSAPPLxx\d\ServerDLLDev"
I can dir either one and contents are displayed.
I can't copy a text file between these 2 drives using Copy-Item:
PS C:\WINDOWS\system32> Copy-Item DllFrom/HelloWorld.txt DllTo/HelloWorld.txt
Copy-Item : Cannot find path 'C:\WINDOWS\system32\DllFrom\HelloWorld.txt' because it does
At line:1 char:1
+ Copy-Item DllFrom/HelloWorld.txt DllTo/HelloWorld.txt
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (C:\WINDOWS\syst...\HelloWorld.txt:String) [
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.CopyItemCommand
I changed the location to the DLLFrom drive and tried it.
Set-Location DllFrom:
PS DllFrom:\>Copy-Item HelloWorld.txt DllTo
and
PS DllFrom:\> Copy-Item \\WPDHSFMSL03\adap\Database\Install\KareAssistTest\HIDn\HelloWorld.txt DllTo
Nothing happened, command line refreshed, but no file showed up.

DllFrom and DllTo are drives, and need a colon in their name when you refer to them. You create them with a -Name without the colon, but later use it when using the drive, just like a single letter drive C: or other providers like HKCU:
Try: Copy-Item DllFrom:/HelloWorld.txt DllTo:/HelloWorld.txt
There is more overview on PSDrives at 4sysops. From the linked page:
Remember that the PSDrive name does not include the colon (:) but you need to include it when using the drive to set location.
When you did Copy-Item HelloWorld.txt DllTo, you'll find a copy of HellowWorld.txt in your current directory named "DllTo"

Related

Get an error when retrieving files from a mapped network drive

I am creating a mapped network drive in PowerShell, but have some weird behavior when retrieving files from the drive. When I create the drive (without -Persist -Scope Global):
$somePath = "\\testtest.lan\Res\Application\TestApp\SomeFiles"
$PsDrive = New-PSDrive -Name "M" -PSProvider "FileSystem" -Root $somePath
Get-ChildItem "M:\" -Recurse | Select-Object -Property *, #{n='Path';e={$_.FullName -replace [regex]::Escape("M:\")}}
On my first attempt to do Get-Child as mentioned above I get an error saying:
"Get-ChildItem: Length cannot be less than zero"
Immediately on my second attempt it works just fine and I can see all the files listed. Next time I try it is stops working(in the same session) with a different error:
Get-ChildItem : An unexpected network error occurred.
At line:1 char:1
+ Get-ChildItem "M:\" -Recurse
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ReadError: (\testtest.l..er\Res\Application\TestApp\SomeFiles:String) [Get-ChildItem], IOException
+ FullyQualifiedErrorId : DirIOError,Microsoft.PowerShell.Commands.GetChildItemCommand
When I try to create the mapped network drive like this:
New-PSDrive -Name "M" -PSProvider "FileSystem" -Root $somePath -Persist -Scope Global
It works immediately couple of times, but it just stops working after some time with the same error as above:
Get-ChildItem : An unexpected network error occurred.
At line:1 char:1
+ Get-ChildItem "M:\" -Recurse
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ReadError: (\testtest.l..er\Res\Application\TestApp\SomeFiles:String) [Get-ChildItem], IOException
+ FullyQualifiedErrorId : DirIOError,Microsoft.PowerShell.Commands.GetChildItemCommand
When I do Get-PsDrive I can see the mapped drive there.
Am I doing something wrong in the code or some problem with the network location I am trying to access. It shouldn't be related to permissions since there are times when it's working correctly or maybe it could be. I am able to access the network location when I try from File Explorer.
Let me know your thinking about this.
Thanks,
Andrej

Powershell copy from linux samba to local windows server folder

I need to copy a file from a Linux samba server to various Windows Server 2008.
The shared folder has a specific login and is read-only.
I can access and copy the shared file using Windows Explorer without a problem.
But, when using PowerShell to copy the file, it always give an error as shown below.
I have tried using Copy-item, robocopy and bitstransfer but they all give an error.
$arq = "file.zip"
$downloadSource = "\\domain.or.ip\sharedfolder\$arq"
echo $downloadSource
Copy-Item -Path "$downloadSource" -Destination ".\$arqAgenteZabbix"
this method gives me the following error
Copy-Item : Access denied
CategoryInfo : PermissionDenied: (\domain.or.ip\sharedfolder\file.zip:String) [Copy-Item], UnauthorizedAc
cessException
FullyQualifiedErrorId : ItemExistsUnauthorizedAccessError,Microsoft.PowerShell.Commands.CopyItemCommand
...
Copy-Item: path not found...
So, I tried adding a credential parameter
$credencial = New-PSSession -ComputerName "serverhostname" -Credential "serverhostname\sharedfolder"
Copy-Item -Path "$downloadSource" -Destination ".\$arqAgenteZabbix" -ToSession $credencial
But received this error after typing my password:
"New-PSSession : [pxl0mon00013] Fail to connect to remote server >serverhostname ...
WinRM cannot process the request... error 0x80090311 ...
CategoryInfo : OpenError (System.Manageme....RemoteRunspace:RemoteRunspace) [New-PSSession], PSRemotin
gTransportException
FullyQualifiedErrorId : AuthenticationFailed,PSSessionOpenFailed
Then, I decided to give BitsTransfer a shot.
Import-Module bitstransfer
$arq = "file.zip"
$downloadSource = "\\domain.or.ip\sharedfolder\$arq"
Start-BitsTransfer -DisplayName DownloadName `
-TransferType Download `
-Source $downloadSource `
-Destination .\$arq
And it also gave me an error:
Start-BitsTransfer : path not found
'\domain.or.ip\sharedfolder\file.zip' does not exist.
CategoryInfo : ObjectNotFound: (\domain.or.ip\sharedfolder\file.zip:String) [Start-BitsTransfer], ParentC
ontainsErrorRecordException
FullyQualifiedErrorId : PathNotFound,Microsoft.BackgroundIntelligentTransfer.Management.NewBitsTransferCommand
How can I make this file copy, please?
EDIT - 20190403
I tried the following:
get-childitem \\domain.or.ip\sharedfolder\
which resulted in:
Get-ChildItem : Cannot find path '\\domain.or.ip\sharedfolder\' because it does not exist.
At line:1 char:3
+ ls <<<< \\domain.or.ip\sharedfolder\
+ CategoryInfo : ObjectNotFound: (\domain.or.ip\sharedfolder\:String) [Get-ChildItem], ItemNotFo
undException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
So, I opened Explorer and pasted \domain.or.ip\sharedfolder\ at the address bar. It asked me for username and password, then, the file was available.
After that, I returned to PowerShell and tried once again the same Get-ChildItem cmdlet. Then, I was able to list the shared folder contents as expected.
Directory: \\domain.or.ip\sharedfolder
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 01/04/2019 10:06 3896455 file.zip
Finally, I tried:
Copy-Item -Path \\domain.or.ip\sharedfolder\file.zip -Destination ".\file.zip"
And it was copied successfully.
Well, only after I entered my login information in Explorer that PowerShell was able to find the shared folder.
But I need it to copy without having to open explorer.
You can provide alternate credentials with Invoke-Command:
Invoke-Command -ScriptBlock {
$arq = "file.zip"
$downloadSource = "\\domain.or.ip\sharedfolder\$arq"
echo $downloadSource
Copy-Item -Path "$downloadSource" -Destination ".\$arqAgenteZabbix"
} -Credential $Cred
I finally managed to successfully copy the shared file in a relative simple way. I used "NET USE" command to open a session and copy the file, like shown below.
$arq = "file.zip"
$downloadSource = "\\domain.or.ip\sharedfolder"
net use $downloadSource /persistent:no /user:[user] [pass]
Copy-Item -Path "$downloadSource\$arq" -Destination ".\$arq"
net use $downloadSource /delete
Now, a new challenge... encrypt the clear-text password.

Error with PowerShell command for copying file to remote server with credential

PS C:\Windows\system32> Copy-Item -ToSession $s C:\Programs\temp\test.txt -Destination C:\Programs\temp\test.txt
Copy-Item : A parameter cannot be found that matches parameter name
'ToSession'. At line:1 char:11
Copy-Item -ToSession $s C:\Programs\temp\test.txt -Destination C:\Programs\temp\ ...
~~~~~~~~~~
CategoryInfo : InvalidArgument: (:) [Copy-Item], ParameterBindingException
FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.CopyItemCommand
As it is noted in the change list of PoSh V5 here and you tagged your question with V4 the simple answer is probably your version's Copy-Item cmdlet does not provide that parameter
Copy-Item now lets you copy files or folders from one Windows
PowerShell session to another, meaning that you can copy files to
sessions that are connected to remote computers, (including computers
that are running Nano Server, and thus have no other interface). To
copy files, specify PSSession IDs as the value of the new -FromSession
and -ToSession parameters, and add –Path and –Destination to specify
origin path and destination, respectively. For example, Copy-Item
-Path c:\myFile.txt -ToSession $s -Destination d:\destinationFolder.

Test-Path returns True but ExtractToDirectory Could not find path

I have a simple powershell script which is supposed to ease some deployment tasks.
In an earlier portion of the script, I create a virtual drive mapped to Z: which is on a remote server. The part that is tripping up is when it tries to unzip the files on the remote server mapped to Z:
function UnzipBuild($destinationFolder)
{
Add-Type -assembly "System.IO.Compression.Filesystem"
$zipFiles = Get-ChildItem -Path $destinationFolder -Filter *.zip
foreach($zip in $zipFiles)
{
$folderName = $zip.ToString().TrimEnd(".zip")
$extractPath = Join-Path $destinationFolder $folderName
New-Item -ItemType Directory $extractPath
Write-Host "Extracting $zip to $extractPath `r`n"
[io.compression.zipfile]::ExtractToDirectory([string]$zip.FullName, "$extractPath")
}
}
When it reaches the ::ExtractToDirectory line it throws an exception
Hit Line breakpoint on 'D:\MyDeploymentScript.ps1:85'
[DBG]: PS C:\WINDOWS\system32>>
Exception calling "ExtractToDirectory" with "2" argument(s): "Could not find a part of the path
'Z:\Build_11_17_13_28\Web'."
At D:\MyDeploymentScript.ps1:85 char:9
+ [io.compression.zipfile]::ExtractToDirectory([string]$zip.FullName, "$ex ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DirectoryNotFoundException
But the crazy thing is if I breakpoint that same spot and check the path with Test-Path it returns True. I am at a loss for what can be wrong right now.
[DBG]: PS C:\WINDOWS\system32>> Test-Path Z:\Build_11_17_13_28\Web
True
It seems like you might be mapping your drive in the earlier portion of the script with New-PSDrive. The drive created with that cmdlet is only visible within PowerShell, unless you use the -Persist switch. That switch creates it as an actual mapped drive (as though you had used net use or group policy or mapped it through explorer).
The .ExtractToDirectory method you're calling can't see any of the powershell provider namespaces, so it needs a real mapped drive or UNC path that's visible to the whole operating system.
Remember that if you're using -Persist you may also want to unmap the drive manually now.

Can I use New-Symlink on UNC paths?

I am trying to create a symlink to a file on Windows using PowerShell. I am using the New-Symlink cmdlet from the PowerShell Community Extensions.
After struggling to figure out the syntax of New-Symlink I was able to get it to work correctly on my local drive. However, I am trying to get it to work on a file share and when I run the command there, I get this output
[PC-KHARPER] <~>$ New-Symlink '\\nyprodfs01\profiles$\kharper\testDir\testFile2' '\\nyprodfs01\profiles$\kharper\testFile'
New-Symlink : Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
At line:1 char:1
+ New-Symlink '\\nyprodfs01\profiles$\kharper\testDir\testFile2' '\\nyprodfs01\pro ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (Microsoft.Power...stDir\testFile2:UnresolvedPscxPathImpl) [New-Symlink], Unauthoriz
edAccessException
+ FullyQualifiedErrorId : CreateSymbolicLinkError,Pscx.Commands.IO.Ntfs.NewSymlinkCommand
Is this expected output for UNC paths? Or should it be working and I'm just doing something wrong?
If you use the symlink support that comes with PS5 (which came out well after this question was posted) then you can mount a symlink to a UNC share.
[host]: PS> New-Item -ItemType SymbolicLink -Path <localpath> -Value \\<uncpath>
There is a problem if you need to pass credentials as New-Item doesn't take creds. The workaround I use is to mount a PSDrive to the folder and then symlink the PSDrive.
[host]: PS> New-PSDrive Z FileSystem \\<uncpath> -Credential <cred>
[host]: PS> New-Item -ItemType SymbolicLink -Path <path> -Value Z:\