powershell - 从 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!"
}
}
解决方案
你的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
之外,您当然也可以抛出异常并稍后在更高级别的函数中处理它。
推荐阅读
- javascript - 如何成功地将两组普通对象与吸气剂“合并”?
- clips - 在 CLIPS 中生成真值表
- node.js - 使用 Penthouse + Cloud Run 启动浏览器进程失败
- google-analytics - 在 Google Analytics 中跟踪 HTML5 视频播放事件需要什么代码?
- mongodb - Mongodb 打不开
- python - 在 Python 中使用 URL 从 txt 中提取数据
- flutter - 在flutter中调用api后更新ModalBottomSheet
- bash - 使用 xargs 并行的多个 rsync - 最有效的目录结构通过
- python - 如何将更长的列表附加到数据框
- css - vue-simple-calendar“类”项目属性不起作用