当前位置: 首页 > 知识库问答 >
问题:

在powershell中打印try catch块中的错误

蓟俊杰
2023-03-14

这是我的脚本,它返回一个布尔值

 param($fileName, $path, $contextMenuItem, $automationDLLPath)

 function CloseWindowsExplorer()
{
(New-Object -comObject Shell.Application).Windows() | foreach-object {$_.quit()}
}

Try
{ 

Import-Module $automationDLLPath

# Open the explorer window in a maximized form
Start-Process explorer $path -WindowStyle Maximized
Start-Sleep 1
Get-UIAActiveWindow

# Get the "Items View" in Explorer to go through all the lements
$list = Get-UIAList -Name 'Items View' -TimeOut 30000;

# Get the file specified in the feature file from the Items View 
# Added a sleep because the VM takes time to perform the functions
Start-Sleep 1
$file = $list | Get-UIAListItem -Name $fileName;

# Perform a single click on the file to invoke a right click on it
Invoke-UIAListItemSelectItem -InputObject $file -ItemName $fileName;

# Added a sleep because the VM takes time to perform the functions
Start-Sleep 1

# Invoke the right click on the selected file
$menu = Invoke-UIAControlContextMenu -InputObject $file;

Start-Sleep 1

# select our context menu item
$menuItem = Get-UIAMenuItem -InputObject $menu $contextMenuItem -TimeOut 30000;

# Display error if the required item in the context menu is not found
if( $null -eq $menuItem){
%{ Write-Host 'cannot find menuItem' }
}
# Invoke the item if found in the context menu
else{

Invoke-UIAMenuItemClick -InputObject $menuItem 
}

# close the windows explorer and return true   
CloseWindowsExplorer
Write-Output "true"
}

Catch
{ 
# close the explorer window as a part of teardown and return false to reflect test        failure 

Write-Output "false"

CloseWindowsExplorer
}

我希望脚本打印捕获的异常,并返回布尔值,但在本例中,脚本失败时只返回false。感谢您的帮助,我需要打印异常,就像try-catch块不存在一样。

共有1个答案

邴宏大
2023-03-14

您需要使用特殊变量$_

这个小例子展示了它是如何工作的:

try {
  testmenow
} catch {
  Write-Host $_
}

$\是一个对象,因此您可以

$_|gm

在catch块中查看可以调用的方法。

 类似资料:
  • 打印工作流程有时很复杂。首先了解所需的设置,然后再浏览到感兴趣的主题。 更多此类内容 设置打印文档 打印分色 印刷标记和出血 PostScript 打印 用色彩管理打印 打印渐变、网格和颜色混合 打印和存储透明图稿 叠印 陷印 打印预设

  • 问题内容: 我正在尝试在PyQt中打印小部件,但收到“ QPaintDevice:无法销毁正在绘制的绘制设备”的错误。我认为问题是我的方法结束了,因此在绘画者完成绘制像素图之前,qPaintDevice被破坏了。但是,我不知道如何降低画家的速度。 我的方法的代码在这里: 对于它的价值,我尝试使用.begin()和.end()方法,但无济于事。 问题答案: 我发现了我的问题-我忘记了删除画家,这在事

  • 我在标签打印机上打印时遇到了问题。下面的代码在一个上打印4个“标签”(附标签图片)。 下面的代码打印到兄弟QL-500标签打印机上。它打印到3.5"乘1.1"标签上。 如果有人能帮我更好地理解代码,那也太好了。 下面是它打印的内容:

  • 在foreach-object并行块下面捕获错误的最佳方法是什么,因为将有三个单独的线程/运行空间运行并执行块中编写的代码,并且多个错误/异常可能同时发生?是否可以捕获列表/变量中的所有错误,并在脚本执行结束时显示?

  • 我想写一些代码来处理从web下载时的错误。 这两条语句运行成功。下面,我创建了一个不存在的网址: 不存在。如何编写循环(函数)以便: 当URL错误时,输出为:“web URL错误,无法获取” 当URL错误时,代码不会停止,而是继续下载,直到URL列表结束