2

so I a have this huge set of scripts made of scriptblocks in files. The problem is that some functionality is repeated in different scriptblocks, so I am thinking that it would be more elegant if I could split the scriptblocks to even smaller parts and join them as necessary. When I tried to join them just with + operator it does not work though. Any ideas if that's possible?

$sb1={some commands}
$sb2={some more commands}
$sb3=$sb1+$sb2
invoke-command $sb3
McVitas
  • 272
  • 1
  • 17

1 Answers1

3

Hm, this ain't exactly pretty, but as a quick adhoc, instead of combining the actual scriptblock objects, you can load the scriptblocks as strings, concatenate them with a newline, and create a scriptblock out of that new string.

$sb1="gps"
$sb2="gsv"
$sb3= [scriptblock]::Create($sb1 + "`n" + $sb2)
invoke-command $sb3
PowerShellGuy
  • 733
  • 2
  • 8
  • 2
    that's a great idea! However not practical to write big code as string because all the syntax highlighting and code autocomplete would stop working! But I think I managed to improve your idea and make it maybe a bit more crazy, but it seems to work! You can actually write those scriptblocks, then concatenate them into a string like this $s=[string]($sb1)+"`n" + [string]$sb2 and then make new scriptblock from this $s like this: $sb=[scriptblock]::Create($s) If you like this edit your question with this variant. – McVitas Oct 09 '20 at 19:11
  • There are many ways to go about doing what I think you want, but I don't have much information to work with, and I'm not sure what the end goal is. Can you post examples of what one of these files looks like? – PowerShellGuy Oct 09 '20 at 19:20
  • I am using this wonderful library which allows very fast parallel operations which you can use to do various actions or scans of servers in a domain for example https://github.com/RamblingCookieMonster/Invoke-Parallel For that I have a script with nested menu and all the funcionality is in script blocks, because that's the way how you start it in parallel on a list of hostnames. So imagine there is one block doing large inventory scan also checking AV versions. Then there is another block doing smaller scan, but also including AV versions check. I don't want to repeat that code in each block. – McVitas Oct 09 '20 at 20:23