首页 > 解决方案 > 从 VBA 运行 PowerShell FTP 上传脚本并发出带有结果的消息框

问题描述

我有一个基本的 FTP 上传 PowerShell 代码,我通过 Excel 中的 VBA 运行(隐藏):

VBA:

Call Shell("powershell -executionpolicy bypass & """ & ThisWorkbook.Path & "\FTP\FTPUpload.ps1""", vbHide)

FTP上传.ps1:

$File = "H:\Workbook\file.txt"
$ftp ="ftp://user:pass@ftp.site.org/incoming/file.txt"

"ftp url: $ftp"

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

"Uploading $File..."

$webclient.UploadFile($uri, $File)

我希望能够向用户显示通过/失败消息。做这个的最好方式是什么?

标签: vbapowershellftp

解决方案


使 PowerShell 脚本通过退出代码发出其结果信号:

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

    "Uploading $File..."

    $webclient.UploadFile($uri, $File)

    exit 0
}
catch
{
    exit 1
}

并修改您的 VBA 代码以等待退出代码并采取相应措施。
请参阅VBA Shell 并等待退出代码


推荐阅读