Can I get “&&” or “-and” to work in PowerShell?

后端 未结 12 865
南笙
南笙 2020-11-29 17:33

&& is notoriously hard to search for on Google Search, but the best I\'ve found is this article which says to use -and.

Unfortunatel

相关标签:
12条回答
  • 2020-11-29 18:21

    It depends on the context, but here's an example of "-and" in action:

    get-childitem | where-object { $_.Name.StartsWith("f") -and $_.Length -gt 10kb }
    

    So that's getting all the files bigger than 10kb in a directory whose filename starts with "f".

    0 讨论(0)
  • 2020-11-29 18:23

    I tried this sequence of commands in PowerShell:

    First Test

    PS C:\> $MyVar = "C:\MyTxt.txt"
    PS C:\> ($MyVar -ne $null) -and (Get-Content $MyVar)
    True
    

    ($MyVar -ne $null) returned true and (Get-Content $MyVar) also returned true.

    Second Test

    PS C:\> $MyVar = $null
    PS C:\> ($MyVar -ne $null) -and (Get-Content $MyVar)
    False
    

    ($MyVar -ne $null) returned false and so far I must assume the (Get-Content $MyVar) also returned false.

    The third test proved the second condition was not even analyzed.

    PS C:\> ($MyVar -ne $null) -and (Get-Content "C:\MyTxt.txt")
    False
    

    ($MyVar -ne $null) returned false and proved the second condition (Get-Content "C:\MyTxt.txt") never ran, by returning false on the whole command.

    0 讨论(0)
  • 2020-11-29 18:25

    Very old question, but for the newcomers: maybe the PowerShell version (similar but not equivalent) that the question is looking for, is to use -and as follows:

    (build_command) -and (run_tests_command)

    0 讨论(0)
  • 2020-11-29 18:31

    Try this:

    $errorActionPreference='Stop'; csc /t:exe /out:a.exe SomeFile.cs; a.exe
    
    0 讨论(0)
  • 2020-11-29 18:32

    Use:

    if (start-process filename1.exe) {} else {start-process filename2.exe}
    

    It's a little longer than "&&", but it accomplishes the same thing without scripting and is not too hard to remember.

    0 讨论(0)
  • 2020-11-29 18:34

    We can try this command instead of using && method:

    try {hostname; if ($lastexitcode -eq 0) {ipconfig /all | findstr /i bios}} catch {echo err} finally {}
    
    0 讨论(0)
提交回复
热议问题