【问题标题】:Printing the error in try catch block in powershell在powershell的try catch块中打印错误
【发布时间】:2026-01-16 08:55:02
【问题描述】:

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

 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 块不存在一样。

【问题讨论】:

    标签: exception try-catch powershell-3.0


    【解决方案1】:

    你需要使用特殊变量$_

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

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

    $_ 是一个对象,所以你可以这样做

    $_|gm
    

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

    【讨论】:

      最近更新 更多