【问题标题】:Powershell FTP Script String ConcatenationPowershell FTP 脚本字符串连接
【发布时间】:2019-08-14 17:54:34
【问题描述】:

我的 Powershell 脚本以这种方式工作正常(它使用 FTP 将IHM_OTP_CRT_20190812_0701.txt 发送到服务器并将其保存为newfile.txt

$File = "Z:\Export\IHM_OTP_CRT_20190812_0701.txt"

$ftp = "ftp://ftpuse:mypass@e2b.kpsci.com/inbound/newfile.txt"

"ftp url: $ftp"

$webclient = New-Object System.Net.WebClient
$uri = New-Object System.Uri($ftp)

"Uploading $File..."

$webclient.UploadFile($uri, $File)

但是如果我更改第二行它不起作用

$ftp = "ftp://ftpuse:mypass@e2b.kpsci.com/inbound/newfile.txt"

到下面

$File = Get-ChildItem -Recurse | Where-Object { $_.Name -match 'IHM_OTP_CRT_.' } | sort LastWriteTime | select -last 1
$NewFileName = $File.Name
$ftp = "ftp://ftpuse:mypass@e2b.kpsci.com/inbound/" + $NewFileName 

这让我发疯了。

我尝试了各种连接方法...我使用保存到 $NewFileName 中的 $var1``$var2 概念来避免 + 符号,我在参数周围使用了括号,例如:

$ftp = ("ftp://ftpuse:mypass@e2b.kpsci.com/inbound/" + $NewFileName)

更令人沮丧的是,当我使用@echo 时,连接起来的字符串看起来很完美。此外,这工作正常:

$ftp = "ftp://ftpuse:mypass@e2b.kpsci.com/inbound/" + "IHM_OTP_CRT_20190812_0701.txt"

所以,它只是与一个不起作用的单独对象(即使它是一个字符串)连接。我可以连接到“blah”,但不能连接到等同于“blah”的变量。我已经为此花费了数小时,我认为这应该不会这么困难。

我收到的错误是:

"Exception calling "UploadFile" with 2 argument(s): "The requested URI is invalid for this FTP command...at :17 char: 22..."

这个错误对我来说很有意义 - 它认为我的“连接”对象在 Upload File 方法中包含一个单独的参数,但我不明白如何让它明白我打算传递一个字符串。

【问题讨论】:

  • 在 ISE 或 VSCode 中逐步执行您的代码,当您到达问题行时,您可以看到变量和正在发生的事情,答案很可能是显而易见的。
  • 我试过了——我的“Echo”语句都运行良好,但最终的 FTP 没有运行。
  • ....但后来我改变了一些代码,此时我想检查我的正则表达式。我想找到以“IHM_OTP_CRT_”开头的文件的最新版本,尽管末尾会附加日期。因为我确信该文件现在甚至没有填充,即使我知道它更早...... :)
  • 愚蠢的问题,但工作示例与您的其他示例所做的不同。您是否尝试将 destination ftp 路径设置为 $ftp = "ftp....inbound/IHM_OTP_CRT_20190812_0701.txt"$ftp = "ftp....inbound/newfile.txt"
  • 目标路径应该是 $ftp = "ftp....inbound/IHM_OTP_CRT_20190812_0701.txt"

标签: powershell ftp


【解决方案1】:

问题在于Get-ChildItem 对象.ToString() 只会返回文件名,而不是完整路径。因此,在 Webclient Upload 中,您必须指定 .FullName 属性:

$webclient.UploadFile($uri, $File.FullName)

完整代码:

$File = Get-ChildItem -Recurse | Where-Object { $_.Name -match 'IHM_OTP_CRT_.' } | sort LastWriteTime | select -last 1
$NewFileName = $File.Name
$ftp = "ftp://ftpuse:mypass@e2b.kpsci.com/inbound/" + $NewFileName 

"ftp url: $ftp"

$webclient = New-Object System.Net.WebClient
$uri = New-Object System.Uri($ftp)

"Uploading $File..."

$webclient.UploadFile($uri, $File.FullName)

【讨论】:

  • 好的,谢谢!!我过于关注 $ftp 变量,但我需要将完整文件路径传递给“UploadFile”,因为我的文件存储在与脚本运行位置不同的位置......同时将短文件名附加到 /入站。这很有趣,因为我在睡了一夜之后又花了一天的时间才意识到你的回答正是我所需要的。