Thoughts on always specifying scope when defining variables in scripts

Welcome Forums General PowerShell Q&A Thoughts on always specifying scope when defining variables in scripts

Viewing 3 reply threads
  • Author
    Posts
    • #260337
      Participant
      Topics: 4
      Replies: 9
      Points: 93
      Rank: Member

      I’m hoping to get feedback or advice from others on this mainly cosmetically-driven question.  I’ve gotten into the habit of creating my variables like this:

      $Script:adUserParams

      The lowercase ‘ad’ is something I’ve been doing, and am settled on the fact that I like it.  The part I’m wondering about is ‘$Script:’.  I’ve read about_Scopes and totally get it.  The way this habit started was that it’s my way of muting Visual Studio Code, when it tells me my variable is assigned but never used.  Most times, it’s a false positive and running the script will never complain or fail, but nonetheless, I want to be told about my mistakes so I can avoid them, and thus I started assigning all my variables in scripts this way.

      Does anyone have a better or just another solution to share with me?  And the simple question too, is – is it bad for any reason that I’m doing this (with the notion that I don’t plan on sharing these variables outside of these scripts)?

      Thanks and look forward to any feedback.

    • #260364
      Senior Moderator
      Topics: 9
      Replies: 1373
      Points: 5,061
      Helping Hand
      Rank: Community MVP

      IMO, its always good to mention variable scopes as its makes it super clear. The warning from VSCode is from PSScriptAnalyzer and AFAIK, it shows such false positive for pester test scripts.

    • #260616
      Participant
      Topics: 4
      Replies: 9
      Points: 93
      Rank: Member

      Thanks for the feedback @kvprasoon.  I think so too re: the PSScriptAnalyzer/pester thing.  I’ll go one further and ask you this – when using the variables (after they’re already assigned using $Script:myVar), do you call them the same way ( $Script:myVar) or just as $myVar?

    • #260874
      Senior Moderator
      Topics: 9
      Replies: 1373
      Points: 5,061
      Helping Hand
      Rank: Community MVP

      I prefer $Script:var even when consuming the variable otherwise its gonna be difficult in bigger solutions.

Viewing 3 reply threads
  • You must be logged in to reply to this topic.