首页 > 解决方案 > 从 powershell 脚本上的函数获取失败消息

问题描述

我不太清楚如何解释我的问题,但我有一个安装 Office 的功能,想象一下运行此脚本的人没有互联网连接或她的硬盘驱动器上没有足够的空间。我将 XML 文件设置为隐藏安装界面,因此用户看不到安装过程。只是为了清楚我的所有代码都可以正常工作,只是想添加此功能,以便在用户运行脚本时出现问题,我知道错误在哪里。

这是我的功能:

Function Install-Office365OfficeProducts{
    Write-Host ""
    Start-Sleep -Seconds 5
    Write-Host "Installing Office 365 ProPlus..."
    # Installing Office 365 ProPlus
    Install-Office365Product -path "$PSScriptRoot\setup.exe" -xmlPath "$PSScriptRoot\InstallO365.xml"

这是我尝试过的:

if (Install-Office365OfficeProducts -eq 0) {
Write-Host "FAILED"}

我很困惑,我认为一个没有错误运行的函数返回 1,当它运行有错误时返回 0。

也尝试过这样写代码:

try {
    Install-Office365Product -path "$PSScriptRoot\setup.exe" -xmlPath "$PSScriptRoot\InstallO365.xml"
} catch {
    Write-Host "Failed!"
}

编辑:

基本上,如果 Office 设置未完成,我想显示一个错误...

@托马斯

Function Install-Office365Product{
    Param (
        [string]$path,
        [string]$xmlPath
    )

    $arguments = "/configure `"$xmlPath`""
    try{
        Start-Process -FilePath "$path" -ArgumentList "$arguments" -Wait -NoNewWindow -ErrorAction Stop
    }catch{
        Write-Host "It was not possible to install the product!"
    }
}

标签: powershelloffice365

解决方案


你的try/ catch-block 里面Install-Office365OfficeProducts是没用的,因为Install-Office365Product不会抛出任何东西,除非你传递错误的参数。里面的try/ catch-blockInstall-Office365Product很可能也不会捕获任何东西。但是你当然可以评估你的安装程序的返回码Start-Process

function Install-Office365Product {
    Param (
        [string]$path,
        [string]$xmlPath
    )

    $arguments = "/configure `"$xmlPath`""
    $process = Start-Process -FilePath "$path" -ArgumentList "$arguments" -Wait -PassThru -NoNewWindow
    if ($process.ExitCode -eq 0) {
        Write-Host "Installation successful"
    } else {
        Write-Host "Installation failed"
    }
}

除了写入stdout之外,您当然也可以抛出异常并稍后在更高级别的函数中处理它。


推荐阅读