使用 PowerShell Test-Connection 测试与 FTP 服务器的连接

使用 PowerShell Test-Connection 测试与 FTP 服务器的连接

我尝试了这个脚本,但它对我不起作用

$file = "test.txt"

$filePath = "C:\" + $file

$server = "ftp://server"

IF (Test-Connection -ComputerName $server -Quiet -Count 1 -ErrorAction SilentlyContinue)
{
$ftp = $server+$file

$webclient = New-Object System.Net.WebClient

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

"Uploading $File..."

$webclient.UploadFile($uri, $filePath)
}
ELSE
{write-host "error"}

当我运行脚本时,主机中出现消息“错误”,这意味着没有与服务器联系,但当我 ping 时服务器有响应

答案1

正如 @flolilolilo 已经评论的那样,Test-Connection接受主机名,而不是 URL,因此您必须server仅使用 来调用它,而不是ftp://server

修复该问题后,您将面临另一个问题,即您的 URI 错误,因为您在server和之间缺少一个斜线test.txt。URI 应该是ftp://server/test.txt


无论如何,我不明白打电话有什么意义Test-Connection。只需立即尝试上传文件即可。

答案2

我使用命令get-content获取 IP 地址列表并对其进行 ping 操作,如果 IP 为 Live 打开 FTP 会话并将文件发送到打印机

$printers = get-content "C:\......\servers.txt"
$info="C:\CommunityName.zpl" 
$ftp = "ftp://$ip/dir/CommunityName.zpl" 
$user = "" 
$pass = ""

$webclient = New-Object System.Net.WebClient 
$webclient.Credentials = New-Object System.Net.NetworkCredential($user,$pass)


 foreach ($ip in $printers){
 IF (Test-Connection -ComputerName $ip -Quiet -Count 1 -ErrorAction SilentlyContinue){

    try { $uri = New-Object System.Uri($ftp)
          $webclient.UploadFile($uri, $info)
          Write-Host "UploadFile it's done $ip"  -backGround Green
        } 

    catch { Write-Host "An Error occured while uploading file to: $Uri" Throw

        }
}
 ELSE{ Write-Host "no conacting $ip"  -backGround Red}
}

相关内容