Copy-Item from New-PSDrive within PSSession - powershell

I have the following Powershell code:
Enter-PSSession -ComputerName test01
New-PSDrive -Name Source -PSProvider FileSystem -Root \\test02\SMBTest -Credential test\Administrator
Copy-Item Source:\Test.txt -Destination C:\Temp
Remove-PSDrive Source
Exit-PSSession
When I execute each line on it's own it works, but when I save it and run it as a ps1 file it doesn't do anything.
Can anyone help explain why (I'm using Powershell --version 5.1)

Thanks #theincorrigible1 - I've modified it to the below and it is now working.
$s = New-PSSession -ComputerName test01
Invoke-Command -Session $s -ScriptBlock {
New-PSDrive -Name Source -PSProvider FileSystem -Root \\test02\SMBTest -
Credential test\Administrator
Copy-Item Source:\Test.txt -Destination C:\Temp
Remove-PSDrive Source
}

Related

PowerShell script to copy same file from multiple folders of a server and paste in another server

I have a file with name "file.config" in multiple folders (D:\Auth0\file.config, D:\Auth1\file.config, D:\Auth2\file.config.....) of a server "S01". I want to copy this file from all the Auth folders and paste in another server using PowerShell.
All I came up with is below:
$Session = New-PSSession -ComputerName "S01" -Credential "domain\user"
Copy-Item "D:\Auth0\file.config" -Destination "\C:\Backups" -FromSession $Session
This script only copies the file from Auth0 folder and pastes in the C drive of the same server. To copy from other folders, I have to change the folder name and run the script again.
I want to run the script which copy this file from all the Auth folders and pastes in another server.
Please help.
Thanks
Can't you just run the Copy-Item command several times in your script?
$Session = New-PSSession -ComputerName "S01" -Credential "domain\user"
Copy-Item "D:\Auth0\file.config" -Destination "\C:\Backups" -FromSession $Session
Copy-Item "D:\Auth1\file.config" -Destination "\C:\Backups" -FromSession $Session
Copy-Item "D:\Auth2\file.config" -Destination "\C:\Backups" -FromSession $Session
Alright, if I understand you correctly this should work:
$DestinationSession = New-PSSession -ComputerName "S01" -Credential "domain\user"
# Is S01 you destination server? And from where are you running this script?
# See the difference between -ToSession and -FromSession
foreach($n in 1..1000)
{
Copy-Item "D:\Auth$($n)\file.config" -Destination "C:\Backups" -ToSession $DestinationSession
}

Powershell Remote Copy fails, locally it works

We have logfile on a server A in a different location (no UNC Path access) and we wish to copy the file to server B. This successfully works with Copy-Item -FromSession (run on Server B) as long as the file is closed. So we can successfully copy the previous day's logs but not today's.
$cred = Get-OurUserCredentials
$sess = New-PSSession -ComputerName $ServerA -Credential $cred -Authentication Negotiate
$LogFile = "D:\log\tomcat\access.20180227.log"
Copy-Item -FromSession $sess $LogFile "D:\logs\tomcat\" -Force
However, we can locally copy the active log of today if we run Copy-Item locally on server A. It's only Copy-Item -FromSession on server B which fails with:
Copy-Item : The process cannot access the file 'D:\log\tomcat\access.20180227.log' because it is being used by another process.
At line:11 char:2
As a workaround we could create a local task on server A to create a local copy but why is this necessary?
Why does Copy-Item behave differently when run remotely and can we "fix" it's behaviour so it copies the log remotely as it would locally.
A version of the answer proposed in the OP but avoiding the need for a scheduled task.
$cred = Get-OurUserCredentials
$sess = New-PSSession -ComputerName $ServerA -Credential $cred -Authentication Negotiate
#ScriptBlock to copy file locally
$SB =
{
#Create variables on the remote machine avoid havin gto pass to scriptblock
$LogFile = "D:\log\tomcat\access.20180227.log"
$TempDes = "temporarylocationhere"
Copy-Item -Path $LogFile -Destination $Des
}
#optional scriptblock to clean up
$SB2 =
{
Remove-Item -Path $TempDes -force
}
#Run the copy file scriptblock
Invoke-Command -Session $sess -ScriptBlock $SB
#Copy file
Copy-Item -FromSession $sess $TempDes "D:\logs\tomcat\" -Force #"
#Run clean up scriptblock
Invoke-Command -Session $sess -ScriptBlock $SB2
Have you considered using a PSDrive to map the remote location and then copy the file to or from that drive?
The New-PSDrive cmdlet creates temporary and persistent drives that
are mapped to or associated with a location in a data store, such as a
network drive, a directory on the local computer, or a registry key,
and persistent Windows mapped network drives that are associated with
a file system location on a remote computer.
Example using your code:
# Change the ServerNameToCopyTo below
New-PSDrive -Name "Remote" -PSProvider "FileSystem" -Root "\\ServerNameToCopyTo\log\tomcat\"
$LogFile = "D:\log\tomcat\access.20180227.log"
Copy-Item $LogFile "Remote:\" -Force

PowerShell map persistent sharepoint path

I'm trying to map the path to a SharePoint document library in a persistent way. It's strange that this works fine:
$Sharepoint = '\\domain.net\stuff\Documents\Folders - Permission matrix'
New-PSDrive -Name P -Root $Sharepoint -PSProvider FileSystem -Credential $Credentials
But this doesn't work:
New-PSDrive -Persist -Name P -Root $Sharepoint -PSProvider FileSystem -Credential $Credentials
New-PSDrive : The network resource type is not correct
At line:1 char:1
+ New-PSDrive -Persist -Name P -Root $Sharepoint -PSProvider FileSystem -Credentia ...
The commands are both using the same PSProvider but one is persistent and the other one not. How can I have this persistent without reverting to net use?
I ran into this problem a few weeks back in a script which mysteriously stopped worked whilst I was developing it, seems to be a Windows error 66 rather than Powershell as explained here
Here is an alternative to net use which uses credentials
# map drive using credentials
(New-Object -ComObject WScript.Network).MapNetworkDrive("$LocalDrive","\\$computer\$drive",$false,$($credentials.username),$($credentials.GetNetworkCredential().password))
I tend to use PSDrive like this
# discover and delete
if (Get-PSDrive -Name Results -ErrorAction SilentlyContinue) { Remove-PSDrive -Name Results -Scope Global | Out-Null }
# create using credentials
if ((New-PSDrive -Name Results -PSProvider FileSystem -Root "\\server\share" -Credential $Credentials -Scope Global -ErrorAction SilentlyContinue) -eq $null) { $WSHShell.popup(“You do not have access to the results repository“,0,””,0) | Out-Null }
# call from a separate function
(Get-PSDrive -Name Results).root
It might just be that a reboot will solve the problem because I cannot recreate the issue today.
I had a similar issue, turns out Windows 2016 and 2019 needs WEBDav Redirection installed.
I was getting error 53, when trying to map a SharePoint library.

PowerShell Command to Copy File on Remote Machine

I have a requirement to copy file from local machine to remote machine using PowerShell. I can copy the file to remote computer using following command:
copy-item -Path d:\Shared\test.txt -Destination \\server1\Shared
the above command uses network share path to copy the file. I don't want to use network share option as the folder will not be shared on the remote machine. I tried following commands but not working.
copy-item -Path d:\Shared\test.txt -Destination \\server1\c$\Shared
Invoke-Command -ComputerName \\server -ScriptBlock {
copy-item -Path D:\Shared\test.txt -Destination C:\Shared
}
Please let me know how to make it working without using UNC path. I have full permissions on that folder on the remote machine.
Quickest way I found to this, since the account being used is Administrator, is to do the following:
New-PSDrive -Name X -PSProvider FileSystem -Root \\MyRemoteServer\c$\My\Folder\Somewhere\
cd X:\
cp ~\Desktop\MyFile.txt .\
## Important, need to exit out of X:\ for unmouting share
cd c:\
Remove-PSDrive X
Works every time.
You must have a shared folder to be able to copy files from one host to another, either on the remote host if you want to push the file:
Copy-Item -Path D:\folder\test.txt -Destination \\server1\remoteshare\
or on the local host if you want to pull the file:
Invoke-Command -ComputerName server1 -ScriptBlock {
Copy-Item -Path \\localcomputer\localshare\test.txt -Destination C:\Shared\
}
Administrative shares (\\server1\c$) can only be used if your account has admin privileges on that particular computer.
If there is not an accessible share, you'll have to make the file content itself an argument to the script:
Invoke-Command -ComputerName \\server -ScriptBlock {
$args[0] | Set-Content C:\Shared\test.txt
} -ArgumentList (Get-Content D:\Shared\test.txt -Raw)
Powershell 5 (Windows Server 2016)
Also downloadable for earlier versions of Windows. -ToSession can also be used.
$b = New-PSSession B
Copy-Item -FromSession $b C:\Programs\temp\test.txt -Destination C:\Programs\temp\test.txt
Earlier versions of PowerShell
Does not require anything special, these hidden shares exist on all machines.
Copy-Item -Path \\serverb\c$\programs\temp\test.txt -Destination \\servera\c$\programs\temp\test.txt
Invoke-Command -ComputerName compname -Credential $cred -ScriptBlock { Get-Content C:\myfolder\result.txt } >>res.txt
Note the C:\myfolder\result.txt is on the remote computer
Here's a script that worked for me for small files. Run as admin.
#pre 5.0 powershell copy-item to remote computer
Write-Host "Remote copy a file"
$servers = #("server01.dot.com", "server02.dot.com")
foreach($server in $servers) {
$username = 'USERNAME'
$password = 'PASSWORD'
$pw = ConvertTo-SecureString $password -AsPlainText -Force
$cred = New-Object Management.Automation.PSCredential ($username, $pw)
$myfile = [System.IO.File]::ReadAllBytes("C:\Temp\srctest.txt")
$s = New-PSSession -computerName $server -credential $cred
Enter-PSSession $s
Invoke-Command -Session $s -ArgumentList $myfile -Scriptblock {[System.IO.File]::WriteAllBytes("C:\Temp\desttest.txt", $args)}
Write-Host "Completed"
Remove-PSSession $s
}

How to use PowerShell and robocopy to backup files to a server?

I am just starting with PowerShell, so please be kind.
All I want to do is backup my directories and files from my laptop to the desktop computer, i.e. "server", using PowerShell and robocopy. I am the administrator to both machines (Windows 7).
This fails with access denied on the "server", i.e., desktop, despite the permissions being set for "Everybody" to do everything.
Any help (or better way) is really appreciated! Thanks.
$cred=get-credential
$sourcepath = ("\\localhost\C$\nova5");
$TargetPath = ("\\library\E$\nova5");
New-PSDrive -Name source -PSProvider FileSystem -Root $SourcePath
New-PSDrive -Name target -PSProvider FileSystem -Root $TargetPath -Credential $cred
robocopy source target /e;
return;
Psdrive is a feature for powershell cmdlet not for extrrnal command , change this line:
robocopy "\\localhost\C$\nova5" "$TargetPath" /e
You could try this:
$cred=get-credential
$sourcepath = C:\nova5 ;
$TargetPath = "\\library\E$\nova5"
New-PSDrive -Name target -PSProvider FileSystem -Root $TargetPath -Credential $cred
.\robocopy.exe $source $target "/e"