Home > database >  How to use line breaks in PowerShell Method-Chaining
How to use line breaks in PowerShell Method-Chaining

Time:01-06

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. enter image description here

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) enter image description here

CodePudding user response:

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()

CodePudding user response:

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).

  • Related