What's the command of call operator &?

后端 未结 2 1638
轻奢々
轻奢々 2021-01-12 05:42

I used ls alias: and tried to find &. However, & is not in the output. What\'s &? Is it the combination of In

相关标签:
2条回答
  • 2021-01-12 05:54

    Some other uses for the call operator, not well documented:

    # Get and set a variable in a module scope with the call operator 
    # get module object
    $m = get-module counter
    
    & $m Get-Variable count
    & $m Set-Variable count 33
    
    # see module function definition
    & $m Get-Item function:Get-Count
    
    # run a cmdlet with a commandinfo object and the call operator
    $d = get-command get-date
    & $d
    

    You can think of & { } as an anonymous function.

    1..5 | & { process{$_ * 2} }
    

    Another really useful operator is the subexpression operator. $( ) It's not just for inside strings. You can combine two statements and make them act as one.

    $(echo hi; echo there) | measure
    

    If and Foreach statements can go inside them too. You couldn't normally pipe from foreach (). So anywhere you could put an expression or pipeline, with $() you can put any statement or group of statements.

    $(foreach ($i in 1..10) { $i;sleep 1 } ) | Out-Gridview
    

    Although, I like streaming from foreach with the call operator (or function), so I don't have to wait.

     & {foreach ($i in 1..10) { $i;sleep 1 } } | Out-GridView
    
    0 讨论(0)
  • 2021-01-12 06:15

    The call operator & allows you to execute a command, script or function.

    Many times you can execute a command by just typing its name, but this will only run if the command is in the environment path. Also if the command (or the path) contains a space then this will fail. Surrounding a command with quotes will make PowerShell treat it as a string, so in addition to quotes, use the & call operator to force PowerShell to treat the string as a command to be executed.

    PowerShell Call Operator

    I am not sure of all the operators that are in PowerShell, but another really useful one is --%, used to stop parsing.

    The stop-parsing symbol --%, introduced in PowerShell 3.0, directs PowerShell to refrain from interpreting any further input on the line as PowerShell commands or expressions.

    PowerShell Stop Parsing Operator

    Building on the comments that have been made:

    Get-Help About_Operators
    

    It will show you the best overview of all operator types and abstract ones like the Call and Stop Parsing Operators.

    0 讨论(0)
提交回复
热议问题