首页 文章

使用&& [duplicate]的多个语句

提问于
浏览
0

这个问题在这里已有答案:

什么是CMD的等效声明:

dir && cd ..

在Powershell?

我试过了:

dir -and cd ..

但它会引发错误:

Get-ChildItem:找不到与参数名称'和'匹配的参数 . 在行:1 char:5 dir - 和(cd ..)CategoryInfo:InvalidArgument:(:) [Get-ChildItem],ParameterBindingException FullyQualifiedErrorId:NamedParameterNotFound,Microsoft.PowerShell .Commands.GetChildItemCommand

2 回答

  • 2

    在PowerShell中没有直接等效的cmd.exe && 这意味着"only execute right-hand side if the left-hand side succeeds."但是你可以写一个简短的函数来做同等的事情:

    function IfTrue([ScriptBlock] $testExpression, [ScriptBlock] $runExpression) {
      if ( & $testExpression ) { & $runExpression }
    }
    

    例如:

    IfTrue { get-childitem "fileThatExists.txt" -ea SilentlyContinue } { "File exists..." }
    

    如果你想让$ testExpression产生输出,那么IfTrue函数可以写成如下:

    function IfTrue([ScriptBlock] $testExpression, [ScriptBlock] $runExpression) {
      & $testExpression
      if ( $? ) { & $runExpression }
    }
    

    法案

  • 4

    这个怎么样?

    dir; if ($?) {cd ..}
    

    正在运行 get-help about_automatic_variables | more 解释:

    $?包含上次操作的执行状态 . 如果上一次操作成功,则包含TRUE;如果失败,则包含FALSE .

    在PS中, dir 只是 get-ChildItem 的别名; cd 同样适用于 Set-Location .

    edit: 同样的问题here,包括an answer直接从马的嘴里 .

相关问题