Reputation: 384
My Powershell script works fine this way (it uses FTP to send IHM_OTP_CRT_20190812_0701.txt
to the server and save it as newfile.txt
)
$File = "Z:\Export\IHM_OTP_CRT_20190812_0701.txt"
$ftp = "ftp://ftpuse:[email protected]/inbound/newfile.txt"
"ftp url: $ftp"
$webclient = New-Object System.Net.WebClient
$uri = New-Object System.Uri($ftp)
"Uploading $File..."
$webclient.UploadFile($uri, $File)
But it does not work if I change the second line
$ftp = "ftp://ftpuse:[email protected]/inbound/newfile.txt"
to the following
$File = Get-ChildItem -Recurse | Where-Object { $_.Name -match 'IHM_OTP_CRT_.' } | sort LastWriteTime | select -last 1
$NewFileName = $File.Name
$ftp = "ftp://ftpuse:[email protected]/inbound/" + $NewFileName
and this is driving me crazy.
I've tried various concatenation methods...I used the $var1``$var2
concept saved into $NewFileName
to avoid the + sign, I've used parenthesis around the argument like:
$ftp = ("ftp://ftpuse:[email protected]/inbound/" + $NewFileName)
And the more frustrating part is that when I use @echo
, the concatenated string looks perfect. Also, this works fine:
$ftp = "ftp://ftpuse:[email protected]/inbound/" + "IHM_OTP_CRT_20190812_0701.txt"
So, it's only concatenating with a separate object (even if it's a string) that doesn't work. I can concatenate to "blah" but not to a variable that equates to "blah". I've spent hours on this and I don't imagine it should be this difficult.
The error I am receiving is:
"Exception calling "UploadFile" with 2 argument(s): "The requested URI is invalid for this FTP command...at :17 char: 22..."
The error makes sense to me - it think's that my "concatenated" object contains a separate argument into the Upload File method, but I can't understand how to make it understand that I'm intending to pass a single string.
Upvotes: 0
Views: 147
Reputation: 13453
The issue is that the Get-ChildItem
object .ToString()
will only return the file name, not the full path. Therefore in the Webclient Upload you have to specify the .FullName
property:
$webclient.UploadFile($uri, $File.FullName)
Full code:
$File = Get-ChildItem -Recurse | Where-Object { $_.Name -match 'IHM_OTP_CRT_.' } | sort LastWriteTime | select -last 1
$NewFileName = $File.Name
$ftp = "ftp://ftpuse:[email protected]/inbound/" + $NewFileName
"ftp url: $ftp"
$webclient = New-Object System.Net.WebClient
$uri = New-Object System.Uri($ftp)
"Uploading $File..."
$webclient.UploadFile($uri, $File.FullName)
Upvotes: 2