windows Powershell警告和错误处理

a7qyws3x  于 2023-01-18  发布在  Windows
关注(0)|答案(1)|浏览(288)

下面的代码我正在写,以取代我下面的批处理脚本.

$Script:srcpath = ((Get-Location).Path)
$Script:configure = "$Script:srcpath\qtbase\configure.bat"

if (Get-Item "$Script:srcpath\qtbase\configure.bat" -WarningAction (Write-Warning "$Script:configure not found. Did you forget to run 'init-repository'?")) {
    continue
}

我正在尝试重写qt配置批处理脚本:

set "srcpath=%~dp0"
set "configure=%srcpath%qtbase\configure.bat"
if not exist "%configure%" (
    echo %configure% not found. Did you forget to run "init-repository"? >&2
    exit /b 1
)

if not exist qtbase mkdir qtbase || exit /b 1

echo + cd qtbase
cd qtbase || exit /b 1

echo + %configure% -top-level %*
call %configure% -top-level %*
set err=%errorlevel%

cd ..

exit /b %err%

我在PowerShell中遇到的错误如下:

Get-Item : Cannot bind parameter 'WarningAction' to the target. Exception setting
"WarningAction": "Object reference not set to an instance of an object."
At line:4 char:67
+ ... rningAction (Write-Warning "$Script:configure not found. Did you forg ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : WriteError: (:) [Get-Item], ParameterBindingException
    + FullyQualifiedErrorId : ParameterBindingFailed,Microsoft.PowerShell.Commands.GetItemCommand

问题是抛出的错误是错误的,因为我调用的警告应该取代它来告诉人们该项目不存在。所以运行“init-repository”。
PowerShell中没有一个好的“如果不存在”。
好吧,有,但看起来像这样:

catch [System.Management.Automation.ItemNotFoundException]

我现在上班都有问题。
为什么我这样做之前,有人问是因为我觉得微软将逐步淘汰CMD的一段时间,这是很好的有更新的脚本。

k97glaaz

k97glaaz1#

为什么不管用

WarningAction不是这样工作的。
about_CommonParameters documentation
确定cmdlet如何响应命令发出的警告。默认值为“Continue”。仅当命令生成警告消息时,此参数才起作用。例如,当命令包含Write-Warning cmdlet时,此参数起作用。
因此,WarningAction的值默认为Continue,可以设置为InquireSilentlyContinueStop。设置该值是为了确定 * 如果 * Get-item命令引发警告,将采取什么操作,而不是在Get-item引发警告时写入什么警告。
您可以更改首选项变量$WarningPreference,以便在当前作用域内设置WarningAction,或者在其前面加上一个作用域修饰符。

如何让它运转
一米十纳一x

我赞同Richard的意见,使用Test-Path,这将返回TrueFalse,这取决于它是否找到该文件。

if (-not (Test-Path -Path "$Script:srcpath\qtbase\configure.bat")){
    Write-Warning 'Does not exist!'
    # do other stuff
    continue
}else{
    Get-Item $configure
}

1米14英寸/1米15英寸

您可以尝试直接在try/catch中捕获Get-Item引发的异常。与WarningAction类似,ErrorAction确定在引发错误时如何处理。终止错误是必需的,因此ErrorAction设置为Stop

try{
    Get-Item $configure -ErrorAction Stop
}catch [System.Management.Automation.ItemNotFoundException]{
    Write-Output "Item not found"
    # do other stuff
}catch{
    Write-Output "Some other error"
    $Error[0] # prints last error
}

相关问题