send file to remote folder powershell - powershell

this is what i would use for copying without asking for password, because i want to schedule this script
$Source = "d:\test\myZipFile.zip"
$Dest = "\\REMOTE_ip\D$\test"
$Username = "Administrator"
$Password = ConvertTo-SecureString "PasswordOFRemotePC" -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 "d:\test\myZipFile1.zip"
But it gives me error
New-PSDrive : The network resource type is not correct At D:\test\copy.ps1:7 char:1
New-PSDrive -Name J -PSProvider FileSystem -Root $Dest -Credential $m ...
+ CategoryInfo : InvalidOperation: (J:PSDriveInfo) [New-PSDrive], Win32Exception
+ FullyQualifiedErrorId : CouldNotMapNetworkDrive,Microsoft.PowerShell.Commands.NewPSDriveCommand

Going by the title of your question, I think you are overdoing this.
In your scheduled task, decide which user account should be running the script. That user should have Read access to the machine's local D:\Test folder and must have Write/Modify permissions to the remote path \\REMOTE_ip\D$\test.
You can set the task so that particular user does not even have to be logged in.
The executable to run is PowerShell.exe and the arguments are -File <PathToTheScript.ps1>
(for that, the task-running user must have Read & Execute permissions on the location of the script file)
The script itself can then be as simple as:
$Source = "d:\test\myZipFile.zip"
$Dest = "\\REMOTE_ip\D$\test"
Copy-Item -Path $Source -Destination $Dest -Force

Related

Why is Get-ChildItem inside a Function Access denied after correct New-PSDrive? (It works outside of the function scope.)

This doesnt work
function ImportProcess{
param(
[Parameter()]
[string]$XMLPath
)
$sourcePath = $XMLPath
$DestPath = split-path "$sourcePath" -Parent #this gives format without slash at and and makes powerShell *very happy*
write-host "connecting to Dir"
New-PSDrive -Name "Drive" -PSProvider FileSystem -Credential $global:cred -Root "$DestPath" | Out-Null
write-host "done"
write-host "getting all xml files"
$temp1 = Get-ChildItem -Path $sourcePath
}
I want to put this inside a function and access the files in the path and this below works. I got this methode from using credentials to get-childitem on other server
$sourcePath = "path"
$DestPath = split-path "$sourcePath" -Parent #this gives format without slash at and and makes powerShell *very happy*
write-host "connecting to Dir"
New-PSDrive -Name "Drive" -PSProvider FileSystem -Credential $global:cred -Root "$DestPath" | Out-Null
write-host "done"
write-host "getting all xml files"
$temp1 = Get-ChildItem -Path $sourcePath
I tried different scopes in New-PSDrive and set-location before get-childitem, aswell as setting the Path to the Drive name + needed subdir
i removed the part where i get the credentials, because all works but as soon as i put the process in a function i get "Get-ChildItem : Access is denied"

How to use credentials in powershell script to copy file to a destination server?

I am trying to copy file from my local machine to a server destination
My Script: Copy-Item –Path D:\Test.txt –Destination '\\10.10.X.X\c$'
Error:
Copy-Item : The network path was not found
At D:\PS_Test_script.ps1:1 char:2
+ Copy-Item –Path D:\Test.txt –Destination '\\10.10.X.28X\c$'
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Copy-Item], IOException
+ FullyQualifiedErrorId : System.IO.IOException,Microsoft.PowerShell.Commands.CopyItemCommand
The server has credentials, I am guessing that, I have to invoke something to use the credentials.
To keep it somewhat simple, to copy to a folder share which requires different credentials to access you can use New-PSDrive to map a drive using those credentials
$desiredMappedDrive = 'J'
$desiredMappedDrivePath = '\\10.10.X.X\c$' # Map to administrative C: drive share requires administrator credentials)
$source = 'D:\Test.txt'
$destination = "${desiredMappedDrive}:\temp"
# Get-Credential cmdlet will request that you enter a username and password that has access to the share
New-PSDrive -Name $desiredMappedDrive -PSProvider FileSystem -Root $desiredMappedDrivePath -Credential (Get-Credential)
# after drive is mapped copy file over
Copy-Item -Path $source -Destination $destination -Verbose
Here is a whole different approach using PSSession no need to map any drives:
$targetComputerName = "127.0.0.1"
$Session = New-PSSession $targetComputerName -Credential 'username'
$DestinationPath = "C:\temp"
$source = 'D:\Test.txt'
Copy-Item -Path $source -ToSession $Session -Destination $DestinationPath
$Session | Remove-PSSession
If you want to execute it as a script you would have to create a [SecureString] and build a credential object.

Moving files on FTP with PowerShell using Rename-FTPItem fails with "(550) File unavailable"

I need to move files on a remote FTP server from Test to Tested. The files are always .csv, but the name changes as it's timestamped. Using the PSFTP module, I have written the following
$FtpServer = "ftp://myftpserver.com/"
$User = "myusername"
$PWD = "mypassword"
$Password = ConvertTo-SecureString $Pwd -AsPlainText -Force
$FtpCredentials = New-Object System.Management.Automation.PSCredential ($User, $Password)
Set-FTPConnection -Credentials $FtpCredentials -Server $FtpServer -Session MyFtpSession -UsePassive
$FtpSession = Get-FTPConnection -Session MyFtpSession
$ServerPath = "ftp://myftpserver.com/Test"
$fileList = Get-FTPChildItem -Session $FtpSession -Path $ServerPath -Filter *.csv
$archivefolder = "ftp://myftpserver.com/Tested"
foreach ($element in $fileList )
{
$filename = $ServerPath + $element.name
$newfilename = $archivefolder + $element.name
Rename-FTPItem -Path $filename -NewName $newfilename -Session $FtpSession
}
The files do exist in the Test folder, but not yet in the archive (Tested) folder. I thought by using a variable to generate what the new file location should be, that would work.
When I try this, I get
Rename-FTPItem : Exception calling "GetResponse" with "0" argument(s): "The remote server returned an error: (550) File unavailable (e.g., file not found, no access)."
Is there a way to move files while using a wildcard, or a better way to achieve what I'm trying to do?
Thanks in advance
The -NewName should be a path only, not a URL:
$archivefolder = "/Tested"
(In the -Path, the URL is acceptable, but it's redundant, you specify the session already using the $FtpSession)
You are missing a slash between the folder paths and the file names.
$filename = $ServerPath + "/" + $element.name
$newfilename = $archivefolder + "/" + $element.name
So you should call the Rename-FTPItem like this:
Rename-FTPItem -Path "ftp://myftpserver.com/Test/file.txt" -NewName "/Tested/file.txt" -Session $FtpSession
or like this:
Rename-FTPItem -Path "/Test/file.txt" -NewName "/Tested/file.txt" -Session $FtpSession

Remove a file using powershell through admin account

Brief summary of what I'm trying to do.
I have a script in powershell that takes 2 files and reads in the embedded credentials and stores them in a variable to which then I can run administrative commands from.
This works great, however, after the files are read and the key is stored, I'm trying to delete the 2 files and I keep getting the following error:
Start-Process : Parameter set cannot be resolved using the specified
named parameters. At \mars\Client-Installs\NetSmart
Test3\Setup.ps1:137 char:15
+ Start-Process <<<< -FilePath "powershell.exe" -Credential $adminCreds -WindowStyle Hidden -ArgumentList "Remove-Item -Path
$file1 -Force" -WorkingDirectory $path -NoNewWindow -PassThru
+ CategoryInfo : InvalidArgument: (:) [Start-Process], ParameterBindingException
+ FullyQualifiedErrorId : AmbiguousParameterSet,Microsoft.PowerShell.Commands.StartProcessCommand
Start-Process : Parameter set cannot be resolved using the specified
named parameters. At \mars\Client-Installs\NetSmart
Test3\Setup.ps1:138 char:15
+ Start-Process <<<< -FilePath "powershell.exe" -Credential $adminCreds -WindowStyle Hidden -ArgumentList "Remove-Item -Path
$file2 -Force" -WorkingDirectory $path -NoNewWindow -PassThru
+ CategoryInfo : InvalidArgument: (:) [Start-Process], ParameterBindingException
+ FullyQualifiedErrorId : AmbiguousParameterSet,Microsoft.PowerShell.Commands.StartProcessCommand
The account I'm running with is part of domain admin and when I look in task manager I can see it running in Administrative mode.
I also know that the folder path where the files reside also have full share and security access to.
Here is a snippit of my code (The bottom 2 lines are the ones that don't seem to work)
function Authentication
{
#---------------------------------------------------
#Authenticate Admin Account using encrypted password
#---------------------------------------------------
$TempFolder = $env:temp
#The 2 lines underneath is if you are running the auth files from the same directory
#$global:AESKeyFilePath = $path + "\aeskey.txt"
#$global:SecurePwdFilePath = $path + "\credpassword.txt"
#Move the files to the temp folder
$global:file1 = $path + "\aeskey.txt"
$global:file2 = $path + "\credpassword.txt"
Copy-Item -Path $file1 -Destination $TempFolder -force
Copy-Item -Path $file2 -Destination $TempFolder -force
#If you choose to run it from the temp directory comment the lines above and uncomment the 2 below.
$global:AESKeyFilePath = $TempFolder + "\aeskey.txt"
$global:SecurePwdFilePath = $TempFolder + "\credpassword.txt"
$global:userUPN = "domain\user"
#use key and password to create local secure passwordtemp
$global:AESKey = Get-Content -Path $AESKeyFilePath
$global:pwdTxt = Get-Content -Path $SecurePwdFilePath
$global:securePass = $pwdTxt | ConvertTo-SecureString -Key $AESKey
#create a new psCredential object with required username and password
$global:adminCreds = New-Object System.Management.Automation.PSCredential($userUPN, $securePass)
#Remove the files below
Start-Process -FilePath "powershell.exe" -Credential $adminCreds -WindowStyle Hidden -ArgumentList "Remove-Item -Path $file1 -Force" -WorkingDirectory $path -NoNewWindow -PassThru
Start-Process -FilePath "powershell.exe" -Credential $adminCreds -WindowStyle Hidden -ArgumentList "Remove-Item -Path $file2 -Force" -WorkingDirectory $path -NoNewWindow -PassThru
}
You cannot specify -NoNewWindow and -WindowStyle together, its contradicting.
See Get-Command Start-Process -Syntax for the parameter sets.
I hope below way is what you need. Just use -WindowStyle Hidden.
Start-Process -FilePath "powershell.exe" -Credential $adminCreds -WindowStyle Hidden -ArgumentList "Remove-Item -Path $file2 -Force" -WorkingDirectory $path -PassThru

Copy-Item works for IP address, not Computer Name

The following code will copy files to remote_computer if I use its IP address 10.10.10.10
$j = "remote_computer"
New-PSDrive -Name Z -PSProvider FileSystem -Root \\$j\share -Credential $credentials -ErrorAction Stop
Copy-Item -Path D:\ps_*able.ps1 -Destination \\10.10.10.10\share
Remove-PSDrive -name Z
This script will NOT copy over files if I use Z, the psdrive
$j = "remote_computer"
New-PSDrive -Name Z -PSProvider FileSystem -Root \\$j\share -Credential $credentials -ErrorAction Stop
Copy-Item -Path D:\ps_*able.ps1 -Destination Z
Remove-PSDrive -name Z
How to fix?
"Z" is not a valid path
Copy-Item -Path D:\ps_*able.ps1 -Destination Z:\