PowerShell module - pass a parameter while importi

2019-02-18 04:34发布

In the below sample module file, is there a way to pass the myvar value while importing the module.

For example,

import-module -name .\test.psm1 -?? pass a parameter? e.g value of myvar

#test.psm1
$script:myvar = "hi"
function Show-MyVar {Write-Host $script:myvar}
function Set-MyVar ($Value) {$script:myvar = $Value}
#end test.psm1

(This snippet was copied from another question.)

1条回答
乱世女痞
2楼-- · 2019-02-18 05:07

This worked for me:

You can use the –ArgumentList parameter of the import-module cmdlet to pass arguments when loading a module.

You should use a param block in your module to define your parameters:

param(
    [parameter(Position=0,Mandatory=$false)][boolean]$BeQuiet=$true,
    [parameter(Position=1,Mandatory=$false)][string]$URL  
)

Then call the import-module cmdlet like this:

import-module .\myModule.psm1 -ArgumentList $True,'http://www.microsoft.com'

As may have already noticed, you can only supply values (no names) to –ArgumentList. So you should define you parameters carefully with the position argument.

Reference

查看更多
登录 后发表回答