错误处理- PowerShell FTP失败,没有击中Catch块



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

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

我把所有东西都包装在一个try/catch块中。出于某种原因,我似乎没有捕捉到错误。如果我输入了错误的凭据,我希望它出错并击中我的catch块并写入适当的错误消息,并阻止脚本的其余部分继续。

我已经环顾四周,试图找到一个答案,但似乎没有工作。这是当我输入错误的登录信息(这显然是预期的)时抛出到我的控制台的错误。

ftp.exe : Login failed.
At C:UsersSomeUserDesktopPSscript.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$userNameDesktopSomeFolderdatadata1.txt
get 'SOME.FILES.2' C:Users$userNameDesktopSomeFolderdatadata2.txt
get 'SOME.FILES.3' C:Users$userNameDesktopSomeFolderdatadata3.txt
get 'SOME.FILES.4' C:Users$userNameDesktopSomeFolderdatadata4.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块,并停止运行脚本?

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

任何帮助将是伟大的,谢谢!

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

我将删除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."
}

最新更新