Краткое руководство по установке переменных в power shell

In other words: the dynamic module returned by .GetNewClosure() does not know about your Say-Hello function, because it was created in a child scope of the global scope, which is where scripts and functions run by default.


Here’s a simplified, stand-alone example:

& { # Execute the following code in a *child* scope. $name = 'before' # The value to lock in. function Say-Hello { "Hello $name" } # Your function. # Create a script block from a *string* inside of which you can redefine # function Say-Hello in the context of the dynamic module. $scriptBlockWithClosure = [scriptblock]::Create(" `${function:Say-Hello} = { ${function:Say-Hello} } Say-Hello `$name ").GetNewClosure() $name = 'after' # Call the script block, which still has 'before' as the value of $name & $scriptBlockWithClosure # -> 'Hello before'
}

This lesson introduces PowerShell variables, constants, and data types.

After completing this lesson, you will be able to:

  • Explain basic concepts regarding variables.
  • Describe the difference between variables and constants.
  • Understand data types and type conversions.
  • Use variables to capture user input and use that input later in script output.
# This script demonstrates the difference between numeric and string data types. # Displays 2 # Displays Int32 # Displays 11 # Displays String

Variables may be cast from one type to another by explicit conversion.

# This script demonstrates data types and data type conversion. # Displays 1.9 # Displays 2 # Displays 1.9 # Displays 1.9 # Displays True 
# This script demonstrates the difference between single quotes and double quotes. '$(1 + 2)' # Displays $(1 + 2) # Displays 3
 'Is it morning, afternoon, or evening? ' 
  1. Review Microsoft TechNet: Get-Variable and Microsoft TechNet: about_Automatic_Variables. Start a new PowerShell session and use Get-Variable to display a list of all automatic variables and values that are defined by default when a new session is started.
  2. Review Microsoft TechNet: Using the Read-Host Cmdlet. Write a script that asks the user to enter their name, and then display a greeting back to the user that includes their name, such as ‘Hello Wikiversity!’. Add a comment at the top of the script that describes the purpose of the script.
  3. Review Microsoft TechNet: about_Quoting_Rules. Experiment with the Hello script above using both using single quotes and double quotes to display the strings to ensure that you understand the difference between the two.
  4. Review Windows IT Pro: Working with PowerShell’s Data Types. Experiment with entering different types of data (integers, floating point values, dates, strings) and use GetType() to display the data type entered.
  5. Review PowerShell.cz: Explicit Type Casting Versus Strongly Typed Variables. Experiment with data type conversion (type casting) and strongly typed variables when entering different types of data.
  • A variable or scalar is a storage location and an associated symbolic name (an identifier) which contains some known or unknown quantity or information, a value.[5]
  • A constant is an identifier whose associated value cannot typically be altered by the program during its execution.[6]
  • Many programming languages employ a reserved value (often named null or nil) to indicate an invalid or uninitialized variable.[7]
  • In almost all languages, variable names cannot start with a digit (0–9) and cannot contain whitespace characters.[8]
  • A data type or simply type is a classification identifying one of various types of data, such as real, integer or Boolean, that determines the possible values for that type, the operations that can be done on values of that type; the meaning of the data; and the way values of that type can be stored.[9]
  • Type conversion, typecasting, and coercion are different ways of, implicitly or explicitly, changing an entity of one data type into another.[10]
  • The scope of a variable describes where in a program’s text the variable may be used, while the extent (or lifetime) describes when in a program’s execution a variable has a (meaningful) value.[11]
  • Scope can vary from as little as a single expression to as much as the entire program, with many possible gradations — such as code block, function, or module — in between. [12]
  • In PowerShell, a variable name always begins with a dollar sign ($).[13]
  • PowerShell variable names are not case sensitive.[14]
  • The assignment operator (=) sets a variable to a specified value. You can assign almost anything to a variable, even complete command results.[15]
  • PowerShell data types include integers, floating point values, strings, Booleans, and datetime values.
  • Variables may be converted from one type to another by explicit conversion, such as [int32]$value.
  • In Windows PowerShell, single quotes display literal strings as is, without interpretation. Double quotes evaluate strings before displaying them.[16]
  • The Read-Host cmdlet reads a line of input from the console.[17]
ASCII (American Standard Code for Information Interchange)
A character-encoding scheme originally based on the English alphabet that encodes 128 specified characters – the numbers 0-9, the letters a-z and A-Z, some basic punctuation symbols, some control codes that originated with Teletype machines, and a blank space – into 7-bit binary integers.[18]
bit
A binary digit, having only two possible values most commonly represented as 0 and 1.[19]
Boolean
A data type with only two possible values: true or false.[20]
byte
A unit of digital information in computing and telecommunications that most commonly consists of eight bits, representing the values 0 through 255.[21]
character
A unit of information that roughly corresponds to a symbol , such as in an alphabet in the written form of a natural language.[22]
floating-point
A method of representing an approximation of a real number in a way that can support a wide range of values based on a fixed number of significant digits which are scaled using an exponent.[23]
garbage collection
A form of automatic memory management in which the garbage collector attempts to reclaim memory occupied by objects that are no longer in use by the program.[24]
immutable
An object whose state or value cannot be modified after it is created.[25]
integer
A data type which represents some finite subset of whole numbers, such as -32,768 to 32,767.[26][27]
memory leak
Incorrect management of memory allocation by a program, resulting in a reduction of available memory for running applications.[28]
string
A data type which represents a sequence of characters, either as a literal constant or as some kind of variable.[29]
Unicode
A computing industry standard for the consistent encoding, representation and handling of text expressed in most of the world’s writing systems, in which a single character may be represented by one, two, or four bytes, depending on the character set and encoding used.[30]
:/>  Пропала языковая панель, что делать?

Enable JavaScript to hide answers.

Click on a question to see the answer.

1.
A variable or scalar is _____.

A variable or scalar is a storage location and an associated symbolic name (an identifier) which contains some known or unknown quantity or information, a value.

2.
A constant is _____.

A constant is an identifier whose associated value cannot typically be altered by the program during its execution.

3.
Many programming languages employ a reserved value (often named _____) to indicate an invalid or uninitialized variable.

Many programming languages employ a reserved value (often named null or nil) to indicate an invalid or uninitialized variable.

4.
In almost all languages, variable names cannot start with _____ and cannot contain _____.

In almost all languages, variable names cannot start with a digit (0–9) and cannot contain whitespace characters.

5.
A data type or simply type is _____ that determines _____, _____, _____, and _____.

A data type or simply type is a classification identifying one of various types of data, such as real, integer or Boolean, that determines the possible values for that type, the operations that can be done on values of that type; the meaning of the data; and the way values of that type can be stored.

6.
Type conversion, typecasting, and coercion are _____.

Type conversion, typecasting, and coercion are different ways of, implicitly or explicitly, changing an entity of one data type into another.

7.
The scope of a variable describes _____, while the extent (or lifetime) describes _____.

The scope of a variable describes where in a program’s text the variable may be used, while the extent (or lifetime) describes when in a program’s execution a variable has a (meaningful) value.

8.
Scope can vary from as little as _____ to as much as _____, with many possible gradations — such as _____ in between.

9.
In PowerShell, a variable name always begins with _____.

In PowerShell, a variable name always begins with a dollar sign ($).

10.
PowerShell variable names _____ case sensitive.

PowerShell variable names are not case sensitive.

11.
The assignment operator _____. You can assign almost anything to a variable, even _____.

The assignment operator (=) sets a variable to a specified value. You can assign almost anything to a variable, even complete command results.

12.
PowerShell data types include _____.

PowerShell data types include integers, floating point values, strings, Booleans, and datetime values.

13.
Variables may be converted from one type to another by _____.

14.
In Windows PowerShell, single quotes display literal strings _____. Double quotes _____.

In Windows PowerShell, single quotes display literal strings as is, without interpretation. Double quotes evaluate strings before displaying them.

15.
The Read-Host cmdlet _____.

The Read-Host cmdlet reads a line of input from the console.

I will discuss everything about the PowerShell naming conventions in this PowerShell tutorial.

When you work with PowerShell, adhering to established naming conventions improves the readability and maintainability of your scripts and modules.

Scripts and Modules: When naming scripts and modules, choose names that succinctly describe their functionality. Avoid abbreviations and instead, opt for full words to eliminate ambiguity.

EntityConvention Example
CmdletGet-Item
FunctionConvertTo-Json
Variable$totalCount
ScriptBackup-Server.ps1
ModuleUserManagement.psm1

Remember, consistency across your cmdlets, variables, scripts, and modules benefits you and others who may use or maintain your code in the future. By sticking to these foundational conventions, you’ll enhance the clarity and professionalism of your PowerShell scripts.

PowerShell Cmdlet Naming

In PowerShell, cmdlet naming is a systematic way of providing clear, self-descriptive commands. This convention ensures consistency across the PowerShell ecosystem, making it easier for you to recognize and utilize cmdlets effectively.

Verb-Noun Pair Usage

Standard Verb Definitions and Usage

PowerShell defines a set of approved verbs to ensure uniformity in the actions that cmdlets perform. Using Get-Verb can provide you with the list of these verbs. For common actions like creating, you should use New, for reading, opt for Get, and for updates, apply Set. Here’s a brief list of some standard verbs with their intended actions:

  • Get: Retrieve data
  • Set: Modify existing data
  • Add: Append data
  • Remove: Delete data
  • New: Create new instances
  • Make certain to use these approved verbs to make your cmdlets intuitive and aligned with the cmdlets created by others.

Noun Naming Best Practices

When naming the noun part of a cmdlet, you should be specific and avoid ambiguity. The noun should reflect the entity that the cmdlet is acting upon and should not contain a verb. Avoid using plural nouns to keep in line with PowerShell’s naming convention. Here are examples of good noun usage:

  • For a cmdlet that lists processes: Get-Process (not Get-Processes)
  • To copy a file: Copy-Item (not Copy-Items or Copy-File)

PowerShell Script and Function Structure

In PowerShell, the structure of your scripts and functions greatly contributes to their clarity and ease of use. Correct naming and design ensure that your code is accessible and maintainable.

Script Module Design

Your script module acts as a container for a group of functions. It is essential to:

  • Use a descriptive name in PascalCase, such as UserManagement or NetworkDiagnostics.
  • Include a .psm1 file that contains your functions, and a .psd1 manifest file which describes the module and its dependencies.

PowerShell Function Definition Conventions

  • Names follow the <Verb>-<Noun> format, with PascalCase for the noun, e.g., Get-Process.
  • The verb should be from the approved list, retrievable by executing Get-Verb.
  • For advanced functions, use the CmdletBinding attribute to enable cmdlet-like features.
:/>  Анализ и баллистическое проектирование системы с присоединенной камерой подгона – тема научной статьи по физике читайте бесплатно текст научно-исследовательской работы в электронной библиотеке КиберЛенинка

Parameter Naming Best Practices

Parameters are crucial for script flexibility. Ensure your parameter names are:

  • Clear and descriptive: e.g., -FilePath instead of -Path.
  • PascalCase with no underscores or hyphens, e.g., -UserName.

For parameters accepting specific values:

  • Use the ValidateSet attribute to restrict inputs, which improves usability and reduces errors.
  • To accept input from the pipeline, use the ValueFromPipeline attribute, allowing users to pipe values directly to the parameter.

PowerShell Variables and Arrays Naming Conventions

In PowerShell, successful scripting hinges on your ability to handle variables and arrays effectively. Proper naming and usage of these entities increase readability and maintainability.

Variable Naming Guidelines

When you name variables:

  • Avoid Reserved Words: Do not use keywords reserved by PowerShell, such as $true, $false, $null, or loop and conditional keywords like $for and $while.
  • Be Descriptive: Your variable names should clearly indicate their purpose or content, promoting code readability. For example, use $userName instead of $un.
  • Consider Scope Prefixes: Incorporate scope prefixes to clarify variable reach. Use $local:VarName for local scope, $script:VarName for script scope, and consider $global:VarName for global variables when necessary.

Array Usage and Naming Conventions

Arrays are fundamental for handling collections of items.

  • Declare with Intent: Define an array with a specific purpose, ensuring the name reflects the content, such as $processList for an array of processes.
  • Initialization Syntax: You can declare an array with $myArray = @() and populate it with elements, $myArray = 'element1', 'element2'.
  • Accepting Arrays as Parameters: When writing cmdlets or functions, allow an array parameter to enable bulk operations, like in Get-Process -Name $processNames.

PowerShell arrays and variables named and used judiciously empower your scripts with efficiency and fluidity.

PowerShell Best Practices for Error Handling and Debugging

Effective error handling and debugging are vital for creating robust scripts in PowerShell. You’ll need to manage script errors strategically and have the skills to debug scripts when issues arise.

Using ErrorAction Parameter

The -ErrorAction parameter is crucial for controlling how PowerShell responds to non-terminating errors. You can specify behaviors like Stop, Continue, SilentlyContinue, or Inquire. Here’s a brief rundown:

  • Stop: Halts the execution of the script when an error is encountered.
  • Continue: Default behavior that prints the error message and continues execution.
  • SilentlyContinue: Suppresses the error message and continues execution.
  • Inquire: Prompts you for action when an error occurs.

Remember to use -ErrorAction with cmdlets to define error handling behavior inline.

Get-Item "Path\To\Nonexistent\File" -ErrorAction Stop

Debugging PowerShell Scripts

When debugging, leverage PowerShell’s built-in debugger. Use breakpoints to pause script execution and analyze the current state. There are several types of breakpoints:

  • Line Breakpoints: Pause execution at a specific line.
  • Variable Breakpoints: Trigger when a variable is accessed or modified.
  • Command Breakpoints: Halt when a specific command is about to run.

Setting a Line Breakpoint:

Set-PSBreakpoint -Script "script.ps1" -Line 15

Additionally, use the Debug parameter with cmdlets to trigger the debugger when an error occurs in the cmdlet.

Invoke-Command -ScriptBlock { param($path) Get-Content $path } -ArgumentList "Path\To\File" -Debug

Understanding and using these tools will significantly enhance your PowerShell scripting experience by allowing you to handle errors and debug more efficiently.

PowerShell Naming Conventions

Best Practices for PowerShell Code Readability

When writing PowerShell scripts, adhering to clear naming conventions greatly enhances your code’s readability. You should name your cmdlets, functions, and variables with precision to reflect their purpose and functionality.

Cmdlet Naming: Always use Pascal case for cmdlets names (e.g., Get-Item). It’s an adopted standard in PowerShell that aligns with .NET framework conventions, making your cmdlets easily recognizable.

Function Names: Similar to cmdlets, use Pascal case and specific nouns for function names (e.g., ConvertTo-Json). This not only aids in discoverability but also in understanding the action the function performs.

Braces: Place the opening brace at the end of the function, if, or loop statement, not on a new line. This is a common practice that keeps your code tidy and structured.

  • Examples: function Get-LogContent { Param([string] $Path) # Your code here } if ($errorCondition) { Write-Host "An error occurred." }

Maintaining these best practices in your PowerShell scripts will ensure they are not only readable but maintainable for both you and others who may use or modify your code in the future.

PowerShell Security and Execution Policies

When working with PowerShell, your security is paramount. PowerShell includes an execution policy feature, which is a crucial aspect of your scripting environment’s security. Execution policies determine the conditions under which PowerShell loads configuration files and runs scripts, helping to prevent the execution of unauthorized or malicious scripts.

Here’s how you can manage execution policies:

  • View Current Policy: Use Get-ExecutionPolicy to check the current execution policy setting.
  • Set Policy: Change the policy using Set-ExecutionPolicy, with available policies ranging from Restricted (no scripts run) to Unrestricted (all scripts run).

PowerShell’s engine does not enforce the execution policy, but rather serves as a guideline to prevent inadvertent script execution. Keep in mind that execution policies are not defenses against malicious actors, but they do offer a layer of protection for your system.

Execution Policy Scopes:

  • MachinePolicy: Affects all users on the computer.
  • UserPolicy: Applies to the current user profile.
  • Process: Influences only the current PowerShell session.
  • CurrentUser: Targets only the current user.
  • LocalMachine: Applies to all users on the computer.

Remember to always operate within the principles of least privilege, setting execution policies that are as restrictive as necessary for your task but allow your scripts to run efficiently. Use the -Scope parameter to specify which scope you wish to alter when using Set-ExecutionPolicy. If working on Windows, be aware that Group Policy might override your execution policy settings.

# Check the current execution policy
Get-ExecutionPolicy
# Set an execution policy for the current user
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

By remaining vigilant and understanding PowerShell’s execution policies, you can ensure an additional layer of security for your scripts and configuration files.

:/>  Настройка даты и времени через cmd

PowerShell Naming Convention Function

Use PascalCase: Capitalize the first letter of each word in the function name, ensuring there are no spaces between words. For example: Get-Process.

Approved Verbs: Select a verb from the list of PowerShell-approved verbs. Retrieve this list by executing Get-Verb.

Singular Nouns: Always use singular nouns to avoid confusion. If your function deals with multiple items, the name should still use the singular form to remain consistent with PowerShell cmdlets.

Prefixes: Consider prefixing nouns to prevent name clashes and provide additional context about the function.

Function NameVerbNounDescription
Convert-ToCsvConvertToCsvConverts objects to a comma-separated value
Get-InventoryItemGetInventoryItemRetrieves information on an inventory item
Set-UserPreferenceSetUserPreferenceModifies a user’s preferences

PowerShell Naming Convention Variables

In PowerShell, adhering to a naming convention for variables enhances script readability and maintainability. Your variable names should clearly indicate their purpose and scope.

PowerShell Local Variable Naming Convention

Local variables in PowerShell are typically named using camelCase. This means you start with a lowercase letter and capitalize the first letter of each subsequent concatenated word. For example:

$localAccountDetails = "Details of a local account"
$invoiceNumber = 12345

Remember, variable names should be descriptive enough to provide clarity on their usage within your code.

PowerShell Constant Variable Naming Convention

When you declare constant variables — values that do not change — use PascalCase. This convention starts with an uppercase letter and capitalizes the first letter of each new word. It is good practice to also include a prefix that indicates the variable is a constant. Here’s an example:

$ConstantTaxRate = 0.05
$MaxAllowedConnections = 100

Using clear and consistent naming conventions for your variables makes your PowerShell scripts more accessible and easier for you and others to understand.

PowerShell Module Naming Convention

  • Verb: Use an approved PowerShell verb that describes the action your module performs.
  • Noun: Choose a noun that clearly identifies the entity or concept acted upon.

Best Practices for Naming Your Module:

  • Ensure the name is concise and descriptive.
  • Avoid using abbreviations that might be unclear to others.
  • Stick with singular nouns, as recommended by PowerShell guidelines.

Example: For a module that manages system backups, a suitable name could be Save-SystemBackup.

Directory and File Naming:

  • Save the PowerShell script with a .psm1 extension and use the same name for the script and the directory where the script is saved. This consistency prevents confusion when importing the module using commands such as Import-Module.

PowerShell Constant Naming Convention

When you define constants in PowerShell, it’s crucial to adopt a clear and consistent naming convention. This aids in making your code more readable and maintainable.

The recommended approach for naming constants is to use a descriptive name that clearly indicates what the constant represents. Typically, constants are written in PascalCase (also known as UpperCamelCase), where the first letter of each word is capitalized, and there are no underscores between words.

Example:

If you’re setting a constant for a maximum size value, you could name it like this:

Set-Variable MaxSize -Option Constant -Value 1024

Best Practices:

  • Descriptive Names: Choose names that reflect the constant’s purpose, as in MaxSize for representing a size limit.
  • PascalCase: Write the constant names using PascalCase for better visibility.
  • Avoid Abbreviations: Use full words rather than abbreviations to make the meaning clear.

When implementing constants in your scripts, remember that a constant cannot be changed once it is set. Attempting to modify a constant will result in an error. PowerShell offers the Set-Variable cmdlet to define a constant, which you should use along with the -Option Constant flag.

Remember, PowerShell constants are immutable. If you need a variable that can be modified but not removed, consider using the -Option ReadOnly.

Here’s a table summarizing the key points:

PropertyRecommendationExample
CasePascalCaseMaxSize
DescriptivenessClear and specific namesDefaultFilePath
ImmutabilitySet with -Option Constant flagSet-Variable usage

By adhering to these conventions, you ensure that your PowerShell script remains structured and comprehensible.

PowerShell Cmdlet Naming Convention

When crafting cmdlets in PowerShell, you must adhere to a specific naming convention that utilizes a verb-noun pair. This ensures that your cmdlets are easily identifiable and the actions they perform are understood at a glance.

Verb Usage: Choose a verb from the approved list by PowerShell, as these verbs convey standardized actions within the naming convention.

  • Get: Retrieve data without changing the system state.
  • Set: Modify data or system state.
  • Start: Initiate a process or task.
  • Get-Process
  • Set-Date
  • Start-Service
  • Consistency: Stick with the established patterns to ensure reliability across different scripts and modules.
  • Clarity: Use clear and descriptive nouns that accurately reflect the entities your cmdlet operates on.

Frequently Asked Questions

What are the best practices for naming functions in PowerShell?

When naming functions, use a Verb-Noun format with each word capitalized, such as Get-Process. Choose verbs from the standard PowerShell verb list to maintain consistency.

How should I structure the naming of modules in PowerShell?

What should I consider when using verbs in PowerShell command names?

Use approved verbs from the PowerShell verb list for your command names. For instance, use Get for retrieval operations and Set for modifying operations. Stick to these standardized verbs to ensure compatibility and predictability.

How does camelCase notation fit within PowerShell scripting standards?

Can you explain the significance of the PS1 file naming convention in PowerShell?

.ps1 is the file extension for PowerShell scripts. When naming these files, use descriptive phrases that summarize their function, separated by dashes, like backup-database.ps1. This naming aids in quickly identifying the script’s purpose.

What guidelines exist for naming parameters in PowerShell scripts?

Conclusion

I have explained everything about the PowerShell naming conventions and best practices in this PowerShell tutorial. We covered:

  • PowerShell Naming Conventions for Functions
  • PowerShell Naming Convention for Variables
  • PowerShell Module Naming Conventions
  • PowerShell Constant Naming Conventions
  • PowerShell Cmdlet Naming Conventions

You may also like: