PowerShell Access Network Share In Script As Different User - powershell

I am trying to access a domain network share in my PowerShell script that is currently running as NETWORK SERVICE. I have a domain user credential configured below.
$secStringPassword = ConvertTo-SecureString "password" -AsPlainText -Force
$shareCredential = New-Object System.Management.Automation.PSCredential ("DOMAIN\Username", $secStringPassword)
I would like to be able to run the following commands in the PowerShell script as the user specified above.
New-Item -Path "\\SERVER\Share\Folder" -ItemType Directory
Get-ChildItem "\\SERVER\Share\Folder"
Running the below is showing as not supported:
New-Item -Path "\\SERVER\Share\Folder" -ItemType Directory -Credential $shareCredential

"The New-Item cmdlet creates a new item and sets its value" If you're trying to connect to a share as a different user I suggest using new-psdrive first to create a mount as that user. This mounts that share as a drive so that it behaves more like a local location than a UNC path
New-PSDrive -Name "ShareNAME" -PSProvider "FileSystem" -Root "\\Server\Share" -Credential $shareCredential
New-Item -Path ShareNAME:\Folder -ItemType Directory -Credential $shareCredential
Get-ChildItem ShareNAME:\Folder -Credential $shareCredential

Related

Move-Item Failure, move doesnt appear in destination directory no error

I have written the below script for a WebDav share on a public website. The intention is to list all PDF from a internal network share and move files to the WebDAV share on the website. I can confirm both New-PSDrive mapping are successful. I then move files and the file are removed from source but do not appear in destination.
I am trying to find fault when no error presented. As WebDAV share and not used this before is there something I am missing in logic here ?.
In move Item I have also tried adding the $Path1 then -Destination and $Path but fails. I modify script for local session path like C:\Temp and works fine. Suspect something different for WebDAV Shares.
$user = "webdav"
$pass = convertto-securestring -String 'WebDAV Password' -AsPlainText -Force
$cred = New-Object -typename System.Management.Automation.PSCredential($user,$pass)
$user1 = "Domain Account"
$pass1 = convertto-securestring -String 'DOMAIN PASSWORD HERE' -AsPlainText -Force
$cred1 = New-Object -typename System.Management.Automation.PSCredential($user1,$pass1)
[String]$path = '\\constoso.com#SSL/Dav/PDF'
[String]$path1 = '\\Domain\corpdata\PDF'
New-PSDrive -Name WebSite -PSProvider FileSystem -Root $path -Credential $cred
New-PSDrive -Name FilePath -PSProvider FileSystem -Root $path1 -Credential $cred1
Get-ChildItem -Path FilePath: -Include *.pdf -Recurse | Move-Item -Destination $path
No error reported files are not in destination when using WebDAV share can confirm in Get-PSDrive they are successfully mapped and accessible. Move appears to remove from source but not present in destination.
As you are working with PSDrive cmdlets you'll have to specify the 'Provider' info. In your case the UNC paths belong to the 'Filesystem' provider. So, try changing your 'path' variables like the below,
[String]$path = 'Filesystem::\\constoso.com#SSL\Dav\PDF'
[String]$path1 = 'Filesystem::\\Domain\corpdata\PDF'
Cheers!
~K

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 Remote file copy is not working

I am trying to copy files remotely on several IIS servers from one source server.
sourcepath is a UNC path like \\server\c$\path\ and destinationpath is a local folder c:\data\destination\
The strange thing is when I run this on the local server this will work perfectly.
$cmd = $sqlConnection.CreateCommand()
$cmd.CommandText ="SELECT * from infrastructure"
$Serverinfo = $cmd.ExecuteReader()
try
{
while ($Serverinfo.Read())
{
$servername = $Serverinfo.GetValue(1)
$location = $Serverinfo.GetValue(2)
#Invoke-Command -ComputerName $servername { new-item -Path $Using:destinationpath -name $Using:versionnumber -Itemtype directory }
Invoke-Command -ComputerName $servername { Copy-Item -Path $Using:sourcepath -destination $Using:destinationpath }
#Invoke-Command -ComputerName $servername {Import-Module WebAdministration ; New-WebApplication -force -Site "Default Web Site" -Name $Using:versionnumber -PhysicalPath $Using:destinationpath$Using:versionnumber }
}
}
What you have posted is incomplete without a catch block and source and destination path defined as others said.
But what I can see here as a possible cause even if you mention all above three constrains.
You will face issues with credential delegation . You are remoting to one server using PSRP and copying one file to that machine and you are taking your source file from a UNC path which requires some authentication.
I could give you two better alternatives, of course 1st once could be the proper solution.
If you are in PS 5.o or later, you can use -ToSession parameter of Copy-Item cmdlet.
$Session = New-PSSession -ComputerName $ServerName
Copy-Item -SourcePath \\\Server\c$\path -Destination c:\data\Destination-ToSession $Session
For more info Get-Help Copy-Item
Edit:
The second one:
Copy-Item -Path <Sourcepath> -DestinationPath \\destinataionserver\c$\folder
from source to the destination by accessing the shared folder of the destination system.

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"

how to copy a file from local pc to remote using remote credentials powershell

i am trying to copy a file from my local pc and paste it to the remote computer but i am getting logon error. if i use the invoke command with -credential parameter than it works, but first i would like to copy the files from local to the remote server. here is my code
$pwd = convertto-securestring "password1234" -asplaintext -force
$cred=new-object -typename System.Management.Automation.PSCredential -argumentlist
".\Administrator",$pwd
$localpath = "C:\_Projects\test.ps1"
$destination = "\\my ip\c$\_Projects\Deployments\"
copy-item -path $localpath -destination $destination -recurse -Force -Credential $cred