下面的代码我正在写,以取代我下面的批处理脚本.
$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的一段时间,这是很好的有更新的脚本。
1条答案
按热度按时间k97glaaz1#
为什么不管用
WarningAction
不是这样工作的。从about_CommonParameters documentation:
确定cmdlet如何响应命令发出的警告。默认值为“Continue”。仅当命令生成警告消息时,此参数才起作用。例如,当命令包含Write-Warning cmdlet时,此参数起作用。
因此,
WarningAction
的值默认为Continue
,可以设置为Inquire
、SilentlyContinue
或Stop
。设置该值是为了确定 * 如果 *Get-item
命令引发警告,将采取什么操作,而不是在Get-item
引发警告时写入什么警告。您可以更改首选项变量
$WarningPreference
,以便在当前作用域内设置WarningAction
,或者在其前面加上一个作用域修饰符。如何让它运转
一米十纳一x
我赞同Richard的意见,使用
Test-Path
,这将返回True
或False
,这取决于它是否找到该文件。1米14英寸/1米15英寸
您可以尝试直接在try/catch中捕获
Get-Item
引发的异常。与WarningAction
类似,ErrorAction
确定在引发错误时如何处理。终止错误是必需的,因此ErrorAction
设置为Stop
。