1

I have multiple functions. By the end of the function they all need to go through exactly the same couple of lines of code, doing some logistic work. How can I define these couple of lines of code into a script block outside these functions and be able to use for all functions, either global reference or passed in as an argument(less preferred)? These lines of code will involve both global and local variables. The ideal is whenever I need to update the logistic work content, I can update it in one place, like script block definition, instead of using a function, which seems overkill for a few lines of codes. Thanks.

function A {
    ...
    $var1 = $global:x + 1
    Write-Host var1 value is $var1
}

function B {
    ...
    $var1 = $global:x + 1
    Write-Host var1 value is $var1
}

$global:x = 0

A

B
3
  • 1
    Small functions that do one very small well defined thing is actually a design pattern that is often aspired to. If I understand what you want then I would actually prefer to have a two line function that I called. Commented Aug 23, 2019 at 4:59
  • Keep in mind that modifying Global variables in a function isn't best practice. It makes it very hard for someone reading your script to see what is actually happening in or outside the scope. Commented Aug 23, 2019 at 7:14
  • Pass the variables as parameters to your functions. Or just write a function. I know which one I'd prefer. Commented Aug 23, 2019 at 9:37

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.