Are global parameters a thing?

Welcome Forums General PowerShell Q&A Are global parameters a thing?

This topic contains 3 replies, has 3 voices, and was last updated by

 
Keymaster
9 months ago.

  • Author
    Posts
  • #93676

    Participant
    Points: 21
    Rank: Member

    Hi,

    I'm new to the forum so please excuse me if this is a commonly asked question. I carried out some searches but could not find the answers I need.

    Is it possible to set certain parameters as global within a module?

    Example:

    param(
    	[String]$SearchBase = "OU=Domain Users,DC=myOrg,DC=com",
    	[Switch]$CreateReport
    )
    
    function createReport {
    	if($CreateReport) {
    		Write-Host "Creating a report"
    	}
    }
    
    function Get-InactiveAccounts{
    	param(
    		[int32]$Days = 30
    	)
    	adminCheck
    	Search-ADAccount `
    	-SearchBase $SearchBase `
    	-AccountInactive -UsersOnly -TimeSpan "$days" | 
    		Where-Object {$_.Enabled -eq $True } |
    		Sort-Object Name | 
    		Select-Object Name,`
    			@{Name='Username';Expression={$_.SamAccountName}},`
    			LastLogonDate
    	createReport
    }
    

    What I'm trying to achieve is have a parameter option for all functions in the module called CreateReport, however I am only getting the parameter Days which I've created local to the function.

    Is this something that is possible within the module? Or should I be looking at another way of doing it?

    Any help will be greatly appreciated!

  • #93696

    Participant
    Points: 13
    Rank: Member

    Ahh the joys and pains of variable scopes 🙂 Have a look at the links below they should set you on the correct path.

    https://4sysops.com/archives/the-powershell-variable-scope/

    http://mikefrobbins.com/2017/06/08/what-is-this-module-scope-in-powershell-that-you-speak-of/

    • #93700

      Participant
      Points: 21
      Rank: Member

      Thanks for those links. Unfortunately I'm still not much the wiser on my issue.

      What I'm looking for is a way to define a 'Global' parameter at the top of the module so that each function will have a switch of -CreateReport without me needing to include a separate parameter in each function.

      I've confirmed that the functions can access the 'module defined' parameters, but as I mentioned above, they do not show up as being usable parameters for the functions themselves.

  • #93720

    Keymaster
    Points: 1,624
    Helping HandTeam Member
    Rank: Community Hero

    No, there's not. Parameters are always per function.

The topic ‘Are global parameters a thing?’ is closed to new replies.