I will like upload a file to SFTP Filezilla but I have an error message and I can not solve my problem
$ftp = "Address"
$Username = "username"
$Password = "password"
$Localdir = "address\test.docx"
$webclient = New-Object System.Net.WebClient
$webclient.Credentials = New-Object System.Net.NetworkCredential($UserName, $Password)
foreach ($item in (dir $Localdir "*.docx")) {
"Uploading $item..."
$uri = New-Object System.Uri($ftp+$item.Name)
Write-Output $uri,$item.FullName
$webclient.UploadFile($uri, $item.FullName)
}
When I execute my script, I have an error message :
Exception when calling "UploadFile" with "2" argument (s): "An exception occurred during a WebClient request. To the character C: \ Users \ PCA \ Downloads \ powershell \ test4 - to see.ps1: 15: 5 + $ webclient.UploadFile ($ ftp, $ item)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : WebException
How resolve this problem ? (I execute this script with on windows 10 and the version powershell is 5.1)
Related
I am trying to connect one FTP server using PowerShell like below.
$line = 'MilanRamani.json'
$file = "C:\brivo\json\" + $line
$ftpuri = "ftp://theflowregister\selfregisterflow:Buter239##waws-prod-am2-555.ftp.azurewebsites.windows.net/site/wwwroot/json/" + $line
$webclient = New-Object System.Net.WebClient
$uri = New-Object System.Uri($ftpuri)
$webclient.DownloadFile($uri,$file)
$webclient.Dispose()
Where theflowregister\selfregisterflow is a username, Buter239# is password, waws-prod-am2-555.ftp.azurewebsites.windows.net/site/wwwroot is host and json/ is subfolder.
I am trying to copy one file named MilanRamani.json from FTP and download it at a particular location in the system. but I am getting this error when I execute the above code.
New-Object : Exception calling ".ctor" with "1" argument(s): "Invalid URI: The hostname could not be parsed."
At line:5 char:8
+ $uri = New-Object System.Uri($ftpuri)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [New-Object], MethodInvocationException
+ FullyQualifiedErrorId :
ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand
Exception calling "DownloadFile" with "2" argument(s): "The requested URI is invalid for this
FTP command."
At line:6 char:1
+ $webclient.DownloadFile($uri,$file)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : WebException
The # (hash/number sign) has special meaning in URL. If you want to use it explicitly, you have to URL-encode it to %23. You might also have to URL-encode the \ (backslash) as %5C. In general, you can use Uri.EscapeDataString to encode the credentials (and also the filename):
$ftpuri =
"ftp://" +
[Uri]::EscapeDataString("theflowregister\selfregisterflow") + ":" +
[Uri]::EscapeDataString("Buter239#") +
"#waws-prod-am2-555.ftp.azurewebsites.windows.net/site/wwwroot/json/" +
[Uri]::EscapeDataString($line)
An alternative and safer approach is to set the credentials via WebClient.Credentials property, instead of the URL:
$ftpuri =
"ftp://waws-prod-am2-555.ftp.azurewebsites.windows.net/site/wwwroot/json/" +
[Uri]::EscapeDataString($line)
$uri = New-Object System.Uri($ftpuri)
$webclient = New-Object System.Net.WebClient
$webclient.Credentials =
New-Object System.Net.NetworkCredential(
"theflowregister\selfregisterflow", "Buter239#")
I am hoping to get some assistance on PowerShell usage for HTTPS file upload. My current task to automate the copying of a directory of PDF file from a local network path to a HTTPS:// website. Whilst I have a local account on the web server, I have an issue with file upload and recursing the list all PDF's.
I tried Invoke-RestMethod -URI
$sourceFilePath = Get-ChildItem "\\DFS-Netwrok\PDF" -Recurse -Include *.pdf
$siteAddress = "https://contoso.com/PDF";
$urlDest = "{0}/{1}" -f ($siteAddress, "*.pdf");
$UserName = "UserName"
$Password = "Password"
function uploadFile() {
Param ([string] $sourceFilePath,
[string] $siteAddress ,
[string] $urlDest,
[string] $UserName,
[string] $Password)
$webClient = New-Object System.Net.WebClient;
$webClient.Credentials = New-Object System.Net.NetworkCredential($UserName,$Password);
("*** Uploading {0} file to {1} ***" -f ($sourceFilePath, $siteAddress) ) | write-host -ForegroundColor Green
$webClient.UploadFile($urlDest, "PUT", $sourceFilePath);
$httpresponse = $httprequest.GetResponse()
}
Upload-File -File $SourceFilePath -URI $SiteAddress -Dest $URLDest -Username $MyUsername -Password $MyPassword
Currently I get error on Upload-File.
I am happy to convert to any code which can provide the above task, list PDF from internal path connect to website with User/Pass and upload all PDF from local Directory. I can confirm the account can connect and has correct permissions on the destination website URL.
I am also looking at this example with error "Forbidden":
$Dir="\\Netwrok\Path"
$Url = "https://Website/PDF"
$user = "User"
$pass = "Password"
$webclient = New-Object System.Net.WebClient
$webclient.Credentials = New-Object System.Net.NetworkCredential($user,$pass)
foreach($item in (dir $Dir "*.pdf"))
{
"Uploading $item..."
$uri = New-Object System.Uri($Url+$item.Name)
$webclient.UploadFile($uri, $item.FullName)
}
Returns error:
Exception calling "UploadFile" with "2" argument(s): "The remote server
returned an error: (403) Forbidden."
At line:16 char:22
+ $webclient.UploadFile($uri, $item.FullName)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : WebException
I need a script to help me for uploading a single file, to a cloud.
I found some answers with the protocol SFTP (SSH), but I cannot find a script working with FTPS (SSL).
I have tried this script, but it doesn't work:
Add-Type -Path "C:\Program Files (x86)\WinSCP\WinSCPnet.dll"
$sessionOptions = New-Object WinSCP.SessionOptions
$sessionOptions.ParseUrl("**ftps**://**login**:**password**#**ipoftheremoteserver**:990/")
$session = New-Object WinSCP.Session
$session.Open($sessionOptions)
$session.PutFiles("D:\QAPPLI\Quadra\DATABASE\PAIE\000001\qpaie.mdb", "/FOLDER1/08h00").Check()
$session.Dispose()
I have this error:
PS C:\Windows\system32> D:\Script\08h00_000001_Client1_to_ftps.ps1 Exception lors de l'appel de « Check » avec « 0 » argument(s) :
« Erreur lors du transfert du fichier 'D:\QAPPLI\Quadra\DATABASE\PAIE\000001\qpaie.mdb'.
Server sent passive reply with unroutable address 172.16.59.131, using host address instead.
Copie de fichiers vers le coté distant échouée.
Filename invalid
Au niveau de D:\08h00_000001_Client1_to_ftps.ps1 : 8
Caractère : 85
+ $session.PutFiles("D:\QAPPLI\Quadra\DATABASE\PAIE\000001\qpaie.mdb", "/FOLDER1/08h00").Check <<<< ()
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
Translated to English:
D:Script08h00_000001_Client1_to_ftps.ps1 Exception when calling "Check" with "0" argument (s): «"Error transferring file ' D:QAPPLIQuadraDATABASEPAIE000001qpaie.mdb '. Server sent passive reply with unroutable address 172.16.59.131, using host address instead.
Copying files to the failed remote side.
Filename Invalid
at D:08h00_000001_Client1_to_ftps.ps1:8 character: 85 + $session. PutFiles ( "D:QAPPLIQuadraDATABASEPAIE000001qpaie.mdb", "/FOLDER1/08h00"). Check < < < () + CategoryInfo: NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId: DotNetMethodException
Many thanks for your help.
The remotePath (second) argument of Session.PutFiles is:
Full path to upload the file to.
While you seem to pass in a path to a folder only, not full path to a file.
This should be correct:
$session.PutFiles(
"D:\QAPPLI\Quadra\DATABASE\PAIE\000001\qpaie.mdb", "/FOLDER1/08h00/qpaie.mdb").Check()
Using the .Net Framework's FTPWebRequest class from PowerShell, with the EnableSsl property to enable FTPS
[Net.ServicePointManager]::ServerCertificateValidationCallback={$true}
$Dir = "D:\FolderWithBackupFilesToMove"
foreach($item in (dir $dir))
{
write-output "-------------"
$fileName = $item.FullName
write-output $fileName
$ftp = [System.Net.FtpWebRequest]::Create("ftp://some.ftp.server.com/someRootFolder/"+$item.Name)
$ftp = [System.Net.FtpWebRequest]$ftp
$ftp.UsePassive = $true
$ftp.UseBinary = $true
$ftp.EnableSsl = $true
$ftp.Credentials = new-object System.Net.NetworkCredential("UserName","Password")
$ftp.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile
$rs = $ftp.GetRequestStream()
$reader = New-Object System.IO.FileStream ($fileName, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::Read)
[byte[]]$buffer = new-object byte[] 4096
[int]$count = 0
do
{
$count = $reader.Read($buffer, 0, $buffer.Length)
$rs.Write($buffer,0,$count)
} while ($count -gt 0)
$reader.Close()
$rs.Close()
write-output "+transfer completed"
$item.Delete()
write-output "+file deleted"
}
We migrated one Windows Server 2008 to Server 2016.
Now I'm getting an error at this script:
cls
$key = (2,3,56,34,254,222,1,1,2,23,42,54,33,233,1,34,2,7,6,5,35,43,6,6,6,6,6,6,31,33,60,23)
$pass = Read-Host -AsSecureString
$securepass = $pass | ConvertFrom-SecureString -Key $key
$bytes = [byte[]][char[]]$securepass
$csp = New-Object System.Security.Cryptography.CspParameters
$csp.KeyContainerName = "SuperSecretProcessOnMachine"
$csp.Flags = $csp.Flags -bor [System.Security.Cryptography.CspProviderFlags]::UseMachineKeyStore
$rsa = New-Object System.Security.Cryptography.RSACryptoServiceProvider -ArgumentList 5120,$csp
$rsa.PersistKeyInCsp = $true
$encrypted = $rsa.Encrypt($bytes,$true)
$encrypted | Export-Clixml 'C:\Temp\encrypted_ysastaginpro_PRE.txt' -Force
Error Code:
New-Object : Exception calling ".ctor" with "2" argument(s): "Object already
exists."
At C:\Program Files\Staging\MESDI\Create_PSW_File_Poly.ps1:13 char:10
+ ... $rsa = New-Object System.Security.Cryptography.RSACryptoServiceP ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [New-Object], MethodInvocationException
+ FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand
Exception calling "Encrypt" with "2" argument(s): "Bad Length."
At C:\Program Files\Staging\MESDI\Create_PSW_File_Poly.ps1:18 char:3
+ $encrypted = $rsa.Encrypt($bytes,$true)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : CryptographicException
I found the the solution.
Run the PS Script as adminstrator.
I have been using this code from another post from this site:
$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.FileName = "notepad.exe"
$pinfo.RedirectStandardError = $true
$pinfo.RedirectStandardOutput = $true
$pinfo.UseShellExecute = $false
$pinfo.Arguments = ""
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $pinfo
**$p.Start() | Out-Null**
#Do Other Stuff Here....
**$p.WaitForExit()**
$p.ExitCode
It has worked fine under PowerShell 2.0. The server was upgraded to PowerShell 3.0, and now the two bold like fail with:
Exception calling "Start" with "0" argument(s): "The system cannot find the
file specified"
At \\asdnsom3978\optim_windows\script_master\exportall.ps1:126 char:1
+ $p.Start() | Out-Null
+ ~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : Win32Exception
Exception calling "WaitForExit" with "0" argument(s): "No process is
associated with this object."
At \\asdnsom3978\optim_windows\script_master\exportall.ps1:128 char:1
+ $p.WaitForExit()
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : InvalidOperationException
Why did it broke and how do I correct it so it works for both version 2.0 and 3.0?
Hmm, I can't repro the error on my V3 system. But why are you going to all this trouble when you can just use the Start-Process command to do this e.g.:
$p = Start-Process Notepad -Wait -PassThru
$p.ExitCode
You might want to try providing a fully-qualified path to notepad.exe, like "C:\Windows\notepad.exe".