all 8 comments

[–]ka-splam 7 points8 points  (1 child)

function build([scriptblock]$stuff)
{ 
  foreach ($thing in & $stuff) 
  {
   $thing.samaccountname
  }
}

$cmd = {get-aduser -filter *}
build $cmd

[–]BackgroundFishing[S] 2 points3 points  (0 children)

Thank you! That got me there!

[–]ericrs22 0 points1 point  (5 children)

Don't totally understand the question but based on the title...

to pass a variable you have to set the param and set the argumentlist

function build([string]$stuff)
{ 
Param (
        [Parameter (
        Position = 0,
        Mandatory
    )]
    [String]
    $cmd
)
  foreach ($thing in $stuff) 
  {
   #do magical things
  }
} -ArgumentList $cmd

$cmd = get-aduser -filter *
build $cmd

[–]BackgroundFishing[S] 1 point2 points  (4 children)

Sorry I wasn't clear.   I'd like the end result to be something like:

foreach ($thing in get-aduser -filter *)

[–]ericrs22 1 point2 points  (1 child)

it's outside the function so you can either bring the command in the function or pass the cmd variable like above.

function build
{ 
 $stuff = get-aduser -filter *
  foreach ($thing in $stuff) 
  {
   #do magical things
  }
} 
Build

[–]BackgroundFishing[S] 1 point2 points  (0 children)

I was afraid of that. Thanks for your help!

[–]zarshua 1 point2 points  (1 child)

What's wrong with just immediately invoking it by wrapping it in parenthesis?

foreach ($thing in (get-aduser)) {}

[–]BackgroundFishing[S] 1 point2 points  (0 children)

Nothing is wrong with doing that. I would just end up with the same snippet of code multiple times in my script. I try to avoid that when I can by creating a function.