Error uploading file to FTP Server - powershell

I'm trying to use FTP to upload a file to an FTP server. I found the following script online, but I can't get it to work.
$UserName = 'username'
$Password = 'password'
$LocalFilePath = 'c:\FolderName\x.txt'
$RemoteFileName = 'x.txt'
$ServerName = 'my.ftpserver.co.uk'
$webclient = New-Object System.Net.WebClient
$webclient.Credentials = New-Object System.Net.NetworkCredential($UserName, $Password)
#Connect to FTP
$uri = New-Object System.Uri(“ftp://$ServerName/$RemoteFileName”)
write-host $uri
#upload as file
$webclient.UploadFile($uri, $LocalFilePath)
But when I run this I get the following error:
Exception calling "UploadFile" with "2" argument(s): "An exception occurred during a WebClient request."
At line:21 char:22
+ $webclient.UploadFile <<<< ($uri, $LocalFilePath)
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
Can anyone point me in the right direction?
I can connect using Filezilla etc from my PC, so it's not blocked by the firewall or anything,

Tested your script and it runs fine, only way I'm able to reproduce your error is if I point $LocalFilePath to a file that doesn't exist. Could you try:
Test-Path($LocalFilePath)
And see if it returns True?

From your comment and the code I see in the question the issue could just be the fact that you have smart quotes in there. It would be a product of your coding editor or the source of copying and paste that code into your environment. You need to watch out for these things. Assuming the paths are correctly formed perhaps that is just your issue.
Smart Quotes
$uri = New-Object System.Uri(“ftp://$ServerName/$RemoteFileName”)
Proper double quotes
$uri = New-Object System.Uri("ftp://$ServerName/$RemoteFileName")
The quotes in the second example are the ones you should use.

Related

FTP File upload powershell

WebClient.UploadFile: $client = New-Object System.Net.WebClient $client.Credentials = New-Object System.Net.NetworkCredential("user", "password") $client.UploadFile("ftp://ftp:50000/test.zip", "C:\HML-V-DC.zip")
When using this script on one computer I am able to upload a file directly to my FTP serve without any issues
But when running this on another machine in another location I get an error "You cannot call a null-valued expression"
Powershell version on computer that is not working: PSVersion 5.1.14393.3866
Powershell version on computer that is working: PSVersion 5.1.19041.610
You cannot call a method on a null-valued expression.
At line:1 char:1
WebClient.UploadFile: $client = New-Object System.Net.WebClient $clie ...
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Was hoping someone with some quick insight may be able to help me understand what I am missing here.
Thank you
Remove "WebClient.UploadFile: " from the line
$client = New-Object System.Net.WebClient

powershell Command Works When run alone, but note when scripted

I am working on a deployment script for some software, and my script is working on probably 90% of the machines it runs on, but on the other 10%, I get a failure in the download portion. Here is what I have:
$tls = "Tls";
$Token = "#ZorusKey#";
[System.Net.ServicePointManager]::SecurityProtocol = $tls;
$source = <Source>
$destination = "C:\installers\ZorusInstaller.exe";
$WebClient = New-Object System.Net.WebClient
$WebClient.DownloadFile($source, $destination)
I have created the C:\installers folder on all target machines, so I don't think that's the problem. When run as a script, I get the following exception:
Exception calling "DownloadFile" with "2" argument(s): "An exception occurred during a WebClient request."
At C:\Windows\system32\config\systemprofile\AppData\Local\f1e96243cb9c4ef0b0336a152ed8827f.ps1:8 char:1
+ $WebClient.DownloadFile($source, $destination)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : WebException
Which then causes the following steps to fail, as the downloaded file doesn't exist.
I have also taken the step on several of the failing machines of running each line of the script above one at a time (copied / pasted from the same Powershell ISE window) and the download works without issue. looking for a possible reason / resolution.
Thanks in advance.

PowerShell - read SharePoint file properties (datemodified, etc)

I need to compare a file in SharePoint against a local file and to make sure they are the same version (it's an accdb that's developed offline and shared in multiple client SharePoint locations). I need to get the modified date from the file in SharePoint, and I've been unable to do so.
NB: I don't have Get-SPWeb available, as this needs to be run by various users who won't have SharePoint 2013 Management Shell available to them (reference).
I've tried using Get-PnPFile with -AsListItem, and it doesn't return an error but I can't access any properties.
I've tried .FieldValuesAsText and .ListItemAllFields and not getting anywhere.
This bit, connecting to the SharePoint resource via SharePointPnPPowerShellOnline, is working:
$SiteURL = "https://myorg.sharepoint.com/sites/mysite"
$FileRelativeURL = "Shared Documents/mydb.accdb"
$UserName = "user#myorg.org"
$PlainPassword = "myP#ssw0rd#"
$SecurePassword = $PlainPassword | ConvertTo-SecureString -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PSCredential -ArgumentList $UserName, $SecurePassword
Connect-PnPOnline -Url $SiteURL -Credentials $Cred
I tried this, and it downloads the file; I don't need to do that:
$file1 = Get-PnPFile -Url $FileRelativeURL -AsFile
According to this, "-AsListItem" returns the file as a listitem showing all its properties. So I tried it. It didn't download the file, and it didn't return an error, so maybe I have an object I can query now?
$file1 = Get-PnPFile -Url $FileRelativeURL -AsListItem
write-host $file1
The second line returns Microsoft.SharePoint.Client.ListItem.
The following return empty strings:
write-host $file1.Name
write-host $file1.TimeLastModified
write-host $file1.LastModified
write-host $file1[-1]
write-host $file1[0,1,2,3,4,5,6,7,8,9]
Found FieldValuesAsText mentioned somewhere, so I tried it:
$props = $file1.FieldValuesAsText
write-host $props
write-host $props[0]
The first one returns Microsoft.SharePoint.Client.FieldStringValues; the second one returns an empty string.
Tried ListItemAllFields:
$props = $file1.ListItemAllFields
write-host $props
write-host $props[0]
The first line didn't generate an error; the second line returned an empty string; the third line returned:
Cannot index into a null array.
At line:1 char:1
+ write-host $props[0]
+ ~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : NullArray
Very new to PowerShell, and I'm probably missing something obvious. (SharePointPnPPowerShellOnline is installed and working.)
The code above doesn't include getting information from my local file; I haven't gotten that far yet. I imagine the instructions here will work. My issue is getting the metadata from the file in SharePoint.
Grateful for any assistance or pointing me to the right resource; I've done a couple hours of research and am coming up empty.
Your best bet would be to map the SharePoint drive as a PSDrive on your system. Then you can treat it like a regular file system and the property LastWriteTime will be available.
More info on New-PSDrive can be found in the documentation online or by typing Get-Help New-PSDrive in a PowerShell console/ISE.

powershell Accepting self-signed certificates using ServerCertificateValidationCallback

I cannot seem to get this to work using Powershell 5.1. The device is a Cisco MX800 CE9.3.
$url = "https://10.1.135.20/getxml?location=/Status"
[Net.ServicePointManager]::ServerCertificateValidationCallback={$true}
$webclient = New-Object System.Net.Webclient
$credCache = New-Object System.Net.CredentialCache
$creds = New-Object System.Net.NetworkCredential($user,$pwd)
$credCache.Add($url, "Basic", $creds)
$webclient.Credentials = $credCache
$webpage = $webclient.DownloadString($url)
Running this script using http returns XML as expected, but using https returns the error below
Exception calling "DownloadString" with "1" argument(s): "The underlying connection was closed: An unexpected error occurred on a send."
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : WebException
In the case above, after searching for answers, I dug in and did packet captures.
One packet capture with powershell talking to the server and one packet capture with a web browser talking to the server.
The PS Client Hello was using TLS1.0
The Web browsers Client Hello was using TLS1.2
So, in PS I added this to the code and I was able to use https against the server.
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

powershell could not create ssl/tsl secure

I'm using a powershell script to download and execute a file, but since some time I go I get a could not create ssl/tsl secure channel.
$down = New-Object System.Net.WebClient;
$url = 'url';
$file = 'file';
$down.DownloadFile($url,$file);
$exec = New-Object -com shell.application;
$exec.shellexecute($file);
exit;
TLS 1.2 should be enabled to get it working. In PowerShell you can find out which protocols your system supports by running this code:
[Enum]::GetNames([Net.SecurityProtocolType]) -contains 'Tls12'
If the result is True then your system supports TLS 1.2. You can find out which protocols are being used by running:
[System.Net.ServicePointManager]::SecurityProtocol.HasFlag([Net.SecurityProtocolType]::Tls12)
If the result is True then TLS 1.2 is being used . However, you can add TLS 1.2 explicitly by using:
[Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12
This should solve these problems.
It may be that the site you are connection to requires TLS 1.2, whereas powershell uses TLS 1.0 by default (if I remember correctly)
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$down = New-Object System.Net.WebClient
$url = 'https://github.com/mpdairy/posh.git'
$file = 'C:\ExistingDirectory\test.git'
$down.DownloadFile($url,$file)
$exec = New-Object -com shell.application
$exec.shellexecute($file)
exit
Without using Tls 1.2, I get this error:
Exception calling "DownloadFile" with "2" argument(s): "The request was aborted: Could not create SSL/TLS
secure channel."
At line:1 char:1
+ $down.DownloadFile($url,$file)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : WebException
I ran into the same error trying to install Wiki.js in Windows server. The issue was the ps1 script included TLS 1.1 as a fallback. The steps below can be changed for any other powershell install
To fix this;
I downloaded the install.ps1 file from installation instructions on Wiki.js installation
iex ((New-Object System.Net.WebClient).DownloadString('https://wiki.js.org/install.ps1'))
Removed "tls11, tls" from the first line
From:
[Net.ServicePointManager]::SecurityProtocol = "tls12, tls11, tls"
To:
[Net.ServicePointManager]::SecurityProtocol = "tls12"
Saved the file in a local directory and changed directory (CD) into
the local directory Ran the command
"iex .\install.ps1"
It's all good now.
Refer this sample code. I written this couple of years when Terraform moved to TLS.
$source=<folder where file suppose to be present>
Write-Verbose -Verbose "Downloading Terraform Required"
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::TLS12
$wc = New-Object System.Net.WebClient
if ((test-path "${source}\terraform.zip") -eq $false) {
$wc.downloadfile("https://releases.hashicorp.com/terraform/0.11.2/terraform_0.11.2_windows_amd64.zip","${source}\terraform.zip")
}
Add-Type -assembly "system.io.compression.filesystem"
[io.compression.zipFile]::ExtractToDirectory("$source\terraform.zip", $destination)
I had the same problem just before and how I fixed it is by changing the link. Make sure the page you're trying to download is a RAW file, for example -
https://raw.githubusercontent.com/TTT2866/Batch-username-generator/master/username_generator.bat
and not
https://github.com/TTT2866/Batch-username-generator/blob/master/username_generator.bat
Note the "raw" in the first link