使用&& [英] Multiple statements using &&
问题描述
CMD的等效语句是什么:
What would be the equivalent statement of CMD's:
dir && cd ..
在Powershell中?
in Powershell?
我尝试过:
dir -and cd ..
但会引发错误:
Get-ChildItem:找不到与之匹配的参数参数名称
'和'。
Get-ChildItem : A parameter cannot be found that matches parameter name 'and'.
在第1行:1个字符:5
At line:1 char:5
+
dir -and(cd ..)
+
dir -and (cd ..)
+
CategoryInfo: InvalidArgument:(:) [Get-ChildItem],ParameterBindingException
+
CategoryInfo : InvalidArgument: (:) [Get-ChildItem], ParameterBindingException
+
FullyQualifiedErrorId:NamedParameterNotFound,Microsoft.PowerShell
.Commands.GetChildItemCommand
+
FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell
.Commands.GetChildItemCommand
推荐答案
PowerShell中没有直接等效的cmd。 exe && ,这意味着仅在左侧成功的情况下才在右侧执行。但是,您可以编写一个简短的函数来执行等效操作:
There is not a direct equivalent in PowerShell of cmd.exe && which means "only execute right-hand side if the left-hand side succeeds." However you could write a short function to do the equivalent:
function IfTrue([ScriptBlock] $testExpression, [ScriptBlock] $runExpression) {
if ( & $testExpression ) { & $runExpression }
}
例如:
IfTrue { get-childitem "fileThatExists.txt" -ea SilentlyContinue } { "File exists..." }
如果要让$ testExpression产生输出,则可以将IfTrue函数编写如下:
If you want for the $testExpression to produce output, the IfTrue function can be written as follows:
function IfTrue([ScriptBlock] $testExpression, [ScriptBlock] $runExpression) {
& $testExpression
if ( $? ) { & $runExpression }
}
Bill
这篇关于使用&&的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!