EDIT: I have discovered it's definitely the password that is causing issues. I have a forward slash in my password and cannot figure out how to get this to accept it. I've already tried replacing it with %5B. Changing the password is not a possibility.
cd v:
$username = "*********"
$password = "*********"
$usrpass = $username + ":" + $password
$webclient = New-Object -TypeName System.Net.WebClient
function ftp-test
{
if (Test-Path v:\*.204)
{
$files = Get-ChildItem v:\ -name -Include *.204 | where { ! $_.PSIsContainer } #gets list of only the .204 files
foreach ($file in $files)
{
$ftp = "ftp://$usrpass#ftp.example.com/IN/$file"
Write-Host $ftp
$uri = New-Object -TypeName System.Uri -ArgumentList $ftp
$webclient.UploadFile($uri, $file)
}
}
}
ftp-test
When I run the above code I get
Exception calling "UploadFile" with "2" argument(s): "An exception occurred during a WebClient request."
At line:13 char:34
+ $webclient.UploadFile <<<< ($uri, $file)
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
I'm not sure what the issue is. Searching has brought issue with proxies, but I have no proxy that I need to get through.
I can manually upload the file with ftp.exe, but I'd rather do all this in PowerShell if possible instead of generating a script to use ftp.exe with.
You have to URL-encode the special characters. Note that encoded slash (/) is %2F, not %5B (that's [).
Instead of hard-coding encoded characters, use Uri.EscapeDataString:
$usrpass = $username + ":" + [System.Uri]::EscapeDataString($password)
Or use the WebClient.Credentials property, and you do not need to escape anything:
$webclient.Credentials =
New-Object System.Net.NetworkCredential($username, $password)
...
$ftp = "ftp://ftp.example.com/IN/$file"
Similarly for (Ftp)WebRequest: Escape the # character in my PowerShell FTP script
Related
I am trying to run a powershell script inside a SQL Agent job. I keep getting the error: Import-Clixml : The system cannot find the file specified. At \Data\Powershell\Collibra\Dev\test.ps1:95 char:21 + ... redential = Import-Clixml -Path Filesystem::\Data\Powershell... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [Import-Clixml], Cryptographic Exception + FullyQualifiedErrorId : System.Security.Cryptography.CryptographicExcept ion,Microsoft.PowerShell.Commands.ImportClixmlCommand
$Credential = Import-Clixml -Path
Filesystem::\\energy\data\apps\BISharedServices\Powershell\Collibra\Dev\credentials.xml
$username = $Credential.GetNetworkCredential().UserName
$password = $Credential.GetNetworkCredential().Password
$credPair = "$($username):$($password)"
$encodedCredentials = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($credPair))
$H = #{ Authorization = "Basic $encodedCredentials" }
I have tried mapping a new drive and doing a set-location. Same results. This is driving me nuts!
Thanks for the help.
In basic Powershell without SSIS at least, it's only one slash at the beginning:
Import-Clixml -Path FileSystem::\path\to\file.txt
I have the following code to upload a file to an FTP Server via powershell but it's giving me this error:
Code:
$Directory=”C:\test”
#FTP server configuration
$ftpserver = “ftp://ftpserver/”
$username = “user”
$password = “pw”
$webclient = New-Object System.Net.WebClient
$webclient.Credentials = New-Object System.Net.NetworkCredential($username,$password)
#Copy each file which type is *.tx*
foreach($file in (dir $Directory “*.txt*”)){
“Uploading $file…”
$uri = New-Object System.Uri($ftpserver+$file.Name)
$webclient.UploadFile($uri, $file.FullName)
}
Error:
Exception calling "UploadFile" with "2" argument(s): "Excepção durante um pedido WebClient."
At C:\Users\home\Desktop\test6.ps1:16 char:1
+ $webclient.UploadFile($uri, $file.FullName)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : WebException
Try it like so:
$Directory = "C:\test"
#FTP server configuration
$ftpserver = "ftp://ftpserver/"
$username = "user"
$password = "pw"
$ftpserverURI = New-Object -TypeName System.Uri -ArgumentList $ftpserver, [System.UriKind]::Absolute
$webclient = New-Object System.Net.WebClient
$webclient.Credentials = New-Object -TypeName System.Net.NetworkCredential -ArgumentList $username, $password
#Copy each file which type is *.tx*
Get-ChildItem $Directory -Filter *.txt* | ForEach-Object {
Write-Host "Uploading $($_.FullName)..."
$uri = New-Object -TypeName System.Uri -ArgumentList $ftpserverURI, $_.Name
$webclient.UploadFile($uri, [System.Net.WebRequestMethods+Ftp]::UploadFile, $_.FullName)
}
The differences are that I'm making System.Uri combine the path instead of relying on string concatenation, and I'm telling WebClient.UploadFile() the method to use when uploading the file.
If this doesn't work, then I agree with the comments that you should examine the server logs. If you can't, then try it against a server that you can see the logs for. Alternately, you may want to try to use WinSCP, which is also scriptable with PowerShell or with a custom script file. WinSCP has the advantage of supporting FTP, FTPS, and SFTP, as well. The .Net WebClient only natively supports plain FTP, as far as I'm aware.
As far as smart quotes, they work just fine on Windows PowerShell (<= v5.x), but they don't work at all on PowerShell Core (v6+). I would avoid using them to make your code more portable and more future proof.
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 want to copy a file from remoter server(which is on another domain) to local
I am new to powershell and got this code from tech forum, however its not working
$Source = "\\xx.xxx.xxx.xx\Users\test\test_1.txt"
$Dest = "D:\Demo\"
$Username = "domainname\username"
$Password = "xxx"
$WebClient = New-Object System.Net.WebClient
$WebClient.Credentials = New-Object System.Net.NetworkCredential($Username, $Password)
$WebClient.DownloadFile($Source, $Dest)
getting below error
Exception calling "DownloadFile" with "2" argument(s): "An exception occurred during a WebClient request."
At line:9 char:1
+ $WebClient.DownloadFile($Source, $Dest)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : WebException
Pretty sure your problem is you need to specify the full file path. Not just a target folder. Looking at WebClient.DownloadFile we can see
fileName String
The name of the local file that is to receive the data.
So perhaps all you need to do is...
$Source = "\\xx.xxx.xxx.xx\Users\test\test_1.txt"
$Dest = [io.path]::Combine("D:\Demo\", Split-Path $source -Leaf)
It was probably denied access to write to a folder.
I am using the current code to download a file from a sharepoint...
$webClient = New-Object System.Net.WebClient
$webClient.UseDefaultCredentials = $true
$webClient.DownloadFile($sharepointPathFile, $localPathFile) | Out-Null
But what if I wanted to check if the file is already at the local location and the size matches or is different? How would I do this using powershell?
Update
This was the closest I could get...
$url = $sharepointPathFile
$clnt = [System.Net.WebRequest]::Create($url)
$resp = $clnt.GetResponse()
$fileSize = $resp.ContentLength
Write-Host $fileSize
But I am getting the following error:
Exception calling "GetResponse" with "0" argument(s): "The remote server returned an error: (401) Unauthorized."
At C:\Scripts\Tests\testCheckUpdatedSearchFiles.ps1:345 char:2
+ $resp = $clnt.GetResponse()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : WebException
I have full read and download rights, so is there something else not going right here?
I'm not sure if the "GetResponse" method will return exactly what you're looking for. And depending on the ContentLength, you may want to explicitly define your types. I would try something like this:
$webClient = New-Object System.Net.WebClient
$webClient.OpenRead("path/to/file")
[Int64]$fileSize = $webClient.ResponseHeaders["Content-Length"]
Write-Host $fileSize