PoshCode / PowerShellPracticeAndStyle

The Unofficial PowerShell Best Practices and Style Guide
https://poshcode.gitbooks.io/powershell-practice-and-style
Other
2.24k stars 289 forks source link

Question: Best Practice fot #139

Closed brumhard closed 5 years ago

brumhard commented 5 years ago

So I'm currently working on a module in PowerShell which uses a standard REST API in the background. For that I wrote a Connect-Server cmdlet that retrieves an auth key for later calls. My question is, is there any best practice to share the data with other cmdlets in cases like that? I know i could easily just return it from the Connect function and set it as a parameter value for the following cmdlet, but that's not what I'm looking for.

Until know I've been using global variables for that exchange of data. But as i've read in the best practice guidelines you should try not to pollute the global scope. Other solutions I've seen use Get and Set cmdlets but I don't think that's the best PowerShell way of doing it.

So are there any other ways of solving that?

lipkau commented 5 years ago

I am currently fond of storing it in a $script: variable and have that be the default value for the parameters in other functions (validating that is not null or empty)

https://github.com/lipkau/ConfluencePS/blob/feature/useAtlassianPSConfiguration/ConfluencePS/Public/Connect-Server.ps1

ChrisLGardner commented 5 years ago

Seconding the use of $Script: scope variables for things like this. It'll be accessible only inside your module and won't pollute the global scope and is more difficult to change for the average user.

brumhard commented 5 years ago

Oh true, completely forgot about that. Thanks guys.