PowerShell FTP无法访问Catch块

时间:2014-03-19 14:29:35

标签: powershell error-handling ftp try-catch

我有这个脚本,我用它来FTP到大型机下载一些数据用于报告。

我从用户输入中获取用户名和密码。

我将所有内容都包含在try/catch块中。出于某种原因,我似乎没有发现错误。如果我键入了不良信用,我希望它出错并点击我的catch块并写入相应的错误消息,并停止继续我的其余脚本。

我环顾四周试图找到答案,但似乎没有任何效果。 当我输入错误的登录信息时(这显然是预期的),这是在我的控制台中抛出的错误。

ftp.exe : Login failed.
At C:\Users\SomeUser\Desktop\PS\script.ps1:348 char:5
+     ftp <<<<  -s:ftp.txt | Out-Null -ErrorAction Stop
    + CategoryInfo          : NotSpecified: (Login failed.:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

它跳过我的catch块并继续运行我的脚本。

这是我正在运行的功能,略有修改。

function FTPMainFrame{

try{

#re-assigning variables
$user = $username
$pass = $password

$pw = $pass | ConvertTo-SecureString -AsPlainText -Force
ConvertFrom-SecureString $pw | Out-File ftppass.txt -Encoding ASCII 

$pw = ConvertTo-SecureString -String (Get-Content ftppass.txt)
$cred = New-Object System.Management.Automation.PsCredential(".",$pw)
$cred.GetNetworkCredential()|fl | Out-Null

# Template for FTP script
$Script = @" 
open XXX.XXX.XXX.XXX
<username>
<password>
get 'SOME.FILES.1' C:\Users\$userName\Desktop\SomeFolder\data\data1.txt
get 'SOME.FILES.2' C:\Users\$userName\Desktop\SomeFolder\data\data2.txt
get 'SOME.FILES.3' C:\Users\$userName\Desktop\SomeFolder\data\data3.txt
get 'SOME.FILES.4' C:\Users\$userName\Desktop\SomeFolder\data\data4.txt
quit
"@

# Reconstitute stored password
$pw = ConvertTo-SecureString -String (Get-Content ftppass.txt)
$cred = New-Object System.Management.Automation.PsCredential(".",$pw)
$passtext = $cred.GetNetworkCredential().Password
$Script = $Script -replace '<username>', $user
$Script = $Script -replace '<password>', $passtext
$Script | Out-File ftp.txt -Encoding ASCII

Write-Host "Running Batch..."

ftp -s:ftp.txt | Out-Null #error's here

#ftp -s:ftp.txt | Out-Null -ErrorAction Stop 
#I've tried this and quite a few other things to force it to be a terminating error...
}
Catch{
    Write-Host "FTP Login Failed, please check your user name and password."

    $ErrorActionPreference = Stop  #should stop the rest of the script..
}
Remove-Item -Path .\ftp.txt
}

我可以在这里做什么来让它击中我的catch块,然后停止运行脚本?

如果我的问题不清楚,或者您需要更多信息,请随时提出。

任何帮助都会很棒,谢谢!

1 个答案:

答案 0 :(得分:2)

您可以使用自动变量$?来检查上一个命令是否成功执行。

我会移除try..catch并将ftp.exe来电替换为:

# Redirect error output
ftp -s:ftp.txt 2> $null

if(-not $?) {
    # Display your message, and stop the script.
    throw "FTP Login Failed, please check your user name and password."
}