From the course: Complete Guide to PowerShell 7

Creating and using variables - PowerShell Tutorial

From the course: Complete Guide to PowerShell 7

Creating and using variables

- [Instructor] In PowerShell, variables are created by assigning a value proceeded by the dollar prefix. This straightforward approach makes it easier for users to define and utilize variables within scripts and commands, unlike many programming languages that require explicit declarations of variable types or specific syntax to define variables. PowerShell eliminates that complexity. As a result, you can focus more on the logic of the scripts without being bogged down by cumbersome declarations. When a variable is assigned a value, PowerShell automatically determines its data type based on the value that it holds. This dynamic type feature allows for greater flexibility and easier management of variables, especially as users can change the value of the variable throughout the script without needing to redefine it. This is particularly useful for both beginners who are just learning scripting and experienced users who want to streamline the coding process. Variables in programming serve as placeholders that can store information for later use. They can be assigned direct values, such as numbers, strings, or Boolean values, or they can hold the results of calculated expressions. Additionally, variables can derive their values from other existing variables or the outcomes of various operations. This versatility is particularly beneficial for creating dynamic data-driven scripts. For example, you can use a variable to perform a calculation based on user input, process data from external sources, or adjust functionality based on changing conditions within the program. By allowing for both static and dynamic data assignments, variables enable you to write more flexible and efficient code that can adapt to the different scenarios. Values of variables can be modified and updated as a result of new inputs, calculations, or user interactions. This dynamic capability is essential in programming as it allows the script to respond flexibly to various conditions and situations. By enabling real-time changes, this feature facilitates more complex behavior in scripts, allowing them to handle a wider range of tasks effectively. For instance, as users interact with an application or provide new data, the program can adapt its functionality, such as recalculating results or updating displays, ensuring it's a more engaging and responsive user experience. Overall, the ability to alter variable values enhances the richness and versatility of script behavior, making it a fundamental aspect of the programming. Global variables are accessible from anywhere within the program. This means that they can be used and modified throughout different functions and sections of the code, providing a convenient way to share data. Local variables, on the other hand, are restricted to the current scope or blocking which they are defined. This accessibility is limited, helping to avoid conflicts with order variables that may have the same name in different areas of the code. Script variables apply to the entire script file. This type of scope allows variables to be used throughout the whole script, while still maintaining a level of organization and control over variable accessibility. Private variables are restricted to the current scope as well. This means they can only be accessed and manipulated within the specific context for which they were created, offering an additional layer of protection against unintended interference from other parts of the programming. Displaying variable values is a crucial aspect of script execution as it allows you to verify the contents of variables at various points during the execution. In PowerShell, there are two primary commands for displaying output, the first one, Write-Output, and the second, Write-Host. The Write-Output command is used primarily for standard output, which means the output can be easily redirected to files or other commands. This is particularly useful when you want to capture the output for logging or further manipulation. On the other hand, Write-Host is designed for console output. It displays messages directly in the console window, but does not allow for interaction or redirection. This is important to note, as output from Write-Host cannot be easily captured or processed, limiting its use in scripts where output needs to be logged or passed to other commands. Using these different output commands provides flexibility in how information is presented to the user and logged for future reference. By choosing between Write-Output and Write-Host, you as the script author can enhance the user experience and maintain clear visibility into the script's operations. Combining variables within strings is a powerful technique that enhances the ability to construct messages and outputs easily. When using strings, the choice between double-quoted and single-quoted formats plays a crucial role in how variables are treated. Double-quoted strings allows for variable expansion, meaning any variables included within the string are evaluated and replaced with their corresponding values. On the other hand, single-quoted strings provide a different functionality by preserving the literal values of the included text. This means that any variables placed within the single quotes will not be evaluated. Instead, they'll be treated as fixed text. This distinction is important when the intention is to display variable names or other expressions without invoking their values. Variables play a crucial role in programming as they can be used within expressions for various purposes. One of the primary functions is to perform arithmetic calculations. By assigning values to variables, you can manipulate these values and utilize them in mathematical operations, simplifying complex calculations. In addition to arithmetic operations, variables are essential for creating conditional statements. Conditional statements allow the program to make decisions based on certain criteria. By incorporating variables into these statements, you can create dynamic behaviors in your scripts, tailoring the flow of the execution according to the value of the variables at runtime. Variables are also instrumental in controlling loops within a program. Loop control structures rely on variables to determine how many times a block of code should execute. By adjusting the value of variables that govern loop conditions, you can create responsive scripts that adapt to user input or other changing data, which enhances the functionality and the user experience. Arrays and collections are foundational data structures in programming that allow you to group multiple values into a single value. They are defined using the @ parentheses syntax, which indicates that you are creating an array. This specific syntax is straightforward and helps in organizing and managing data efficiently. By using arrays and collections, you can handle a list of items without needing to create separate variables for each value, leading to cleaner and more manageable code. One of the key features of arrays is its ability to access the elements by their index. In most programming languages, arrays are zero-based, meaning that the index of the first element is zero, the second is one, and so on. This allows you to retrieve or manipulate specific elements by simply referencing their index. For example, if you have an array of numbers, you can easily access the first number by using the index 0, which significantly simplifies operations like searching, sorting, or modifying data. In addition to accessing elements, arrays provide flexibility when it comes to adding new elements. You can dynamically increase the size of an array by appending new values, which makes it easier to expand your dataset as needed. This capability is particularly useful in scenarios where the amount of data is not known in advance. By allowing for easy addition and modification of elements, arrays streamline data management, making scripts more efficient and responsive to changing requirements. Now, when we create variables, obviously we can create variables at different scopes as well. And so if we first look at a global variable, then we can create one by utilizing the $global, which means this is accessible anywhere in the session. So if I run this selection here, it says $global:globalvar. I can then obviously say $globalvar and get access to the contents of that variable. Now, what does that really mean? Well, let's go over to Visual Studio Code here and just say PowerShell, and I've launched a new one that's here. So what I can now do is just say $globalvar, and notice there's no entry there, and that's because it's related to the current session itself. So let's go back to here. I can then populate that into a function, and then I can say, Show-GlobalVar, and sure enough, I get access to that variable. So that means it's available everywhere within the session, so at any point all the way down. Now, of course, we can also create local variables, which means that they are part of the function itself. Now notice here, I'm going to say lovalVar. "I'm accessible from the function." So if I happen to call this variable right now, it's just going to give me that message, "I'm accessible only in this function." So let's put this into the function and say Show-LocalVar, and then let's execute Show-LocalVar, which I'll now run, and it says, "I am a local variable." If I now say localVar, it then says, "I'm accessible only in this function." So you can see that we can override the values, but for the purposes of this specific function. So even though we declare something as $localVar, which means it's only available in the function, actually, if it's outside the function, it's still available with the existing value, even though we changed the name of the property or the value or whatever it would be inside the function itself. Now, of course, we do have the ability to create script variables, too, which means that I can go ahead and say $script, so $script definition, run that option that's there. And then, of course, if I want to see what's in that variable, I'm going to say $scriptVar, and it says, "I'm only accessible in this script here." Now what that means is I have a variable outside. If I create a function here called show ScriptVar, and then I run that ScriptVar, it's going to say, "I'm accessible only in this script," because it's a variable that we've put inside that script itself. So of course, it becomes quite complicated when you're kind of defining the variables, because some variable values are available outside, some variables are available inside the function, some variables are available outside with one value, but in the function can be called with a different one. Now, we also have this idea of creating private functions and private variables, so we're going to talk about private variables. So I have a new function called Show-PrivateVar, and in there, I've defined a variable called $private:privateVar, and it says, "I am private to this function." So let's just execute that, and before we execute the actual function, what I'm going to do here is get the value of that one, and notice it's nothing. There's no value. It doesn't exist, but if I do Show-PrivateVar here, then of course it says, "I am private to this function." So it's all about defining the variables in the right locations. If you want them available for the entire script itself, then you define them at the top and make them global variables or script variables, but if you want them to be unique to a function, you put them inside the function and then perhaps not overwrite them as you go through. Now, of course, what we can do here is we can tie all of these together. So let's create a global called varGlobal and one called varScript. I'm going to run that selection, and then I'm going to create a local variable and a private one, and I'm going to say, let's test the scope. So I'm going to run selection here, and then when I say Test-Scope, I end up with a message that says, Inside function: Global, Script, Local, Private. So in actual fact, what happens, depending where we define these variables, in all fairness, in PowerShell, variables become accessible all over the place. So it's important thing to understand and note, that depending where you execute them and where you run them will determine how they get ran. Also, what makes it more unique here is that we're running this interactively. So as we are going through each block of code, we're executing it, whereas when you get to call the specific PS1 file, then the definition of global and script become more important, because then, because you're not running the code interactively, you're running it as a PS1 file, the definitions of the variables will then come into play. But that's how we define the variables. Fairly straightforward to be able to define something as private, script, or global, and to be able to utilize those in the PS1 script itself. In our next video, we'll discuss variable scopes.

Contents