How do you not to repeat code in a powershell module? For example, getting a list of hostnames from a file, or storing user credentials -


i writing powershell module list of utilties use on daily basis. however, question is: how can not repeat code?

for example if have function gets list of hostnames file, have create parameter in every single function. how can create once, , have each function prompt it, or grab it?

function copyfiles {  param ( [parameter(mandatory = $true, helpmessage = "enter path machine list file     (unc path or local). ")] [validatescript({$_ -ne ""})] [string] $machinelistfilename,  ...sometime later in script...  $machinelist = get-content $machinelistfilename  }  function dosomeothertask {      param ( [parameter(mandatory = $true, helpmessage = "enter path machine list file     (unc path or local). ")] [validatescript({$_ -ne ""})] [string] $machinelistfilename,  ...sometime later in script...  $machinelist = get-content $machinelistfilename  } 

it seems in-efficient cut , paste same code on , on again. like, domain-name, username, password, etc.

ultimately, i'm trying point write wrapper scripts these functions once import module. can pass parameters via command line. however, current way i'm doing it, module going littered lot of repetitive code, parameters username , password, etc.

is there better way?

make cmdlets/functions independent , flexible can. wrapper function way go, other times consolidating things 1 function , calling differently more workable.

in example you've given here, give caller 2 options - can pass in filename list of machines, or pass in list of machines. way, can read file once in calling script, , pass array of machine names each function. much more efficient you're reading disk 1 time.

i recommend reading on advanced functions , parametersets simplify things (you'll need suggestion above).

as "repetitive code" - find copying/pasting code, stop. find way make code generic , move own function, call function wherever it's needed. isn't powershell notion - standard programming, dry principle.

even then, you'll still find modicum of copypasta. it's going happen because of nature of powershell environment. @ microsoft's own cmdlets - you'll see evidence of there too. key minimize it.

having 3 cmdlets take username & password (why not take credential object instead/as option, btw?) will result in copying & pasting parameters in function definition. you're not going avoid that, , it's not bad thing. can create code snippets in editors (powershell ise included) automatically "generate" if makes easier/faster.


Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -