简体   繁体   中英

How to use line breaks in PowerShell Method-Chaining

I am trying to use a Retry Service that is written in the fluent-api pattern. The methods return the service and allow a chaining of methods. However even though i am using --> ` <-- i see a lot of errors as shown below. 在此处输入图像描述

Is there any workaround or other possibility to not write everything into one line? (I already checked the methods names and return types)

(Entry point of RetryService) 在此处输入图像描述

Unfortunately about_Methods doesn't seem to have a clarification on method chaining and its parsing rules. If you want to chain multiple methods on new lines, the dot . has to be at the end of each statement then a newline is allowed. The backticks are not needed .

In example:

[powershell]::Create().
    AddScript({ "hello $args" }).
    AddArgument('world').
    Invoke()

Another way to chain method calls is to use the ForEach-Object command (alias % ). This relies on the parameter set with the -MemberName parameter (implicitly by passing a string as the 1st argument).

PowerShell 7+ even lets you write the pipe symbol | on a new line:

[powershell]::Create()
    |% AddScript { "hello $args" }
    |% AddArgument 'world'
    |% Invoke

If there are multiple method arguments, you have to separate them by , (parentheses are unnecessary).

For PS 5 and below you have to use a slightly different syntax because the pipe symbol has to be on the same line as the previous command:

[powershell]::Create() |
    % AddScript { "hello $args" } |
    % AddArgument 'world' |
    % Invoke

Is this a better way than using member access operator . ? I don't think so, it's just a different way. IMO it does look more consistent compared to regular PowerShell commands. Performance might be even worse than . but for high level code it propably doesn't matter (I haven't measured).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM