Переменные среды power shell set

Scope of Environmental Variables in Windows

There are 3 different scopes for environment variables

  • User Scope Environment Variables – These are linked to the user who is currently executing the process.
  • System Scope Environment Variables – These are linked to the system and apply to all users who log in to this computer.
  • Process Scope Environment Variables – These are created dynamically by Windows and linked to user or system environment variables.

View current environment variables using PowerShell

Environment variables in PowerShell are stored as PS drive (Env: ). To retrieve all the environment variables stored in the operating system we can use the below command

#View current environment variables
Get-ChildItem -Path Env:
#To get specific environment variable, type variable name after env:
Get-ChildItem -Path Env:\SystemDrive
#

We can create new environment variables, and view, edit or copy environment variables via PowerShell using item cmdlets or using System. Environment methods

Using Item cmdlets

We can create a new environment variable using New-Item, set the value of an environment variable with Set-Item, list environment variables with Get-Item, copy the environment variable with Copy-Item and delete the environment variable with Remove-Item.

#Create a new environment variable using New-Item
New-Item -Path Env:\MyOrg -value 'mshub.com'
#Set value of an environment variable with Set-Item
Set-Item -Path Env:\MyOrg -value 'mshub'
#List specific environment variables with Get-Item
Get-Item -Path Env:\MyOrg
#Copy the environment variable with Copy-Item
Copy-Item -Path Env:\MyOrg -Destination Env:\MyOrg2 -PassThru
#Delete the environment variable with Remove-Item
Remove-Item -Path Env:\MyOrg* -Verbose
#

Using System.Environment methods

Set an Environment Variable scoped for the Local Session

The below PowerShell command will set the environment variable scoped for the local PowerShell Console

#Set an Environment Variable scoped for Local PowerShell session
[Environment]::SetEnvironmentVariable('MyOrg','mshub.com')
#

Set an Environment Variable scoped for User

#Set an Environment Variable scoped for User
[Environment]::SetEnvironmentVariable('MyOrg','mshub.com', ‘User’)
#

Set an Environment Variable scoped for the Machine

Below PowerShell command will set persistent environment variable scoped for the machine

#Set an Environment Variable scoped for Machine
[Environment]::SetEnvironmentVariable('MyOrg','mshub.com', ‘Machine’)
#

Get an Environment Variable using GetEnvironmentVariable class

The below PowerShell command will get the environment variable using the GetEnvironmentVariable class

#Get environment variable using GetEnvironmentVariable class
[Environment]::GetEnvironmentVariable('MyOrg')
#

Remove an environment variable using GetEnvironmentVariable class

We can remove an environment variable with the SetEnvironmentVariable method by specifying an empty string for the variable’s value.

#Remove an environment variable scoped for user
[Environment]::SetEnvironmentVariable('MyOrg','', ‘User’)
#Remove an environment variable scoped for machine
[Environment]::SetEnvironmentVariable('MyOrg','', ‘Machine’)
#

View and set environment variables using GUI

  • Open the System Control Panel
  • Select System
  • Select Advanced System Settings
  • Go to the Advanced tab
  • Select Environment Variables
  • Make your changes

For many IT professionals and developers working with Azure, the ability to efficiently switch between different subscriptions is crucial for managing resources and controlling costs. Whether you’re a seasoned Azure veteran or new to the platform, this post is designed to guide you through the process of changing Azure subscriptions using two powerful tools: PowerShell and the Azure Command Line Interface (CLI). We’ll explore step-by-step instructions, best practices, and useful tips to make your subscription management seamless and effective.

To change your Azure subscription using PowerShell, you can use the Set-AzContext cmdlet. This cmdlet changes the active subscription for your current Azure session. Before changing your subscription, you can list all your Azure subscriptions with the Get-AzSubscription cmdlet.

To list all the subscriptions available to you:

# Lists all subscriptions
Get-AzSubscription

To change the active subscription in your session:

# Change the active subscription by name
Set-AzContext -Subscription "My Azure Subscription"
# Change the active subscription by subscription ID
Set-AzContext -Subscription "11111111-1111-1111-1111-111111111111"

Remember to replace "My Azure Subscription" with the actual name of your subscription or "11111111-1111-1111-1111-111111111111" with the actual subscription ID. After executing the Set-AzContext cmdlet with the correct parameters, your Azure PowerShell session will target the specified subscription.

Changing Subscription in CLI

In Azure CLI, you can change the active subscription using the az account set command, specifying either the subscription name or ID. Here are examples of how to do this:

To change the active subscription using the subscription name:

az account set --subscription "My Demos"

To change the active subscription using the subscription ID:

az account set --subscription "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"

If you have the subscription name stored in a variable, you can also set the subscription like this:

subscriptionId="$(az account list --query "[?name=='my case sensitive subscription full name'].id" --output tsv)"
az account set --subscription $subscriptionId

Replace "My Demos" with your actual subscription name and "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" with your actual subscription ID

Frequently Asked Questions: 

Q: How can I add or change the administrators for my Azure subscription?

Q: What steps are involved in transferring billing ownership of an Azure subscription?

Q: Can I switch my Azure subscription to a different Microsoft Entra Directory?

Yes, you can switch your Azure subscription to a different Microsoft Entra Directory. This process involves changing the tenant ID associated with your subscription. You can use the Azure portal or Azure CLI to select the subscription you wish to change and then associate it with the new tenant. This is particularly useful when you need to manage resources across different directories or for organizational restructuring.

Q: How do I manage access and role assignments using Azure Role-Based Access Control (RBAC)?

Q: What are the necessary steps to transfer an Azure subscription to another account?

Q: How do I use Azure CLI to manage my Azure subscription?

To use Azure CLI for managing your Azure subscription, first install the CLI tool on your system. Then, you can execute various commands to manage different aspects of your subscription. For instance, you can use ‘az account show’ to view your current subscription details or ‘az role assignment list’ to check role assignments. Azure CLI is a powerful tool for scripting and automating Azure resource management tasks.

Q: What is Microsoft Cost Management, and how can it help in managing Azure resources?

Microsoft Cost Management is a service provided by Azure that helps you monitor, allocate, and optimize your Azure costs. By using this service, you can gain insights into your spending patterns, set budgets, and analyze your costs over time. It’s an essential tool for effectively managing the financial aspect of your Azure resources and ensuring you stay within your budget while making the most of Azure services.

Q: How can I create a new resource group or subscription in Azure?

Q: What are the next steps after getting a Visual Studio Enterprise Subscription in Azure?

After obtaining a Visual Studio Enterprise Subscription in Azure, the next steps include setting up your Azure environment. This involves creating resource groups, setting up Azure services like Azure SQL or Azure Plan, and assigning Azure roles using role-based access control. You should also familiarize yourself with Azure support and available resources to maximize the benefits of your subscription, including technical support and security updates.

:/>  Как добавить принтер с помощью IP-адреса в Windows 10

Q: How can I see and manage my Azure subscription and its resources?

To see and manage your Azure subscription and its resources, you can use the Azure portal or Azure CLI. With the Azure portal, you can view all your subscriptions, select the subscription you want to manage, and access various resources within it. You can also use Azure CLI commands like ‘az account show’ to view details of your current subscription and perform various management tasks. This helps you keep track of your resources and their usage.

Q: What is the process to transfer a Microsoft Azure subscription to a different pay-as-you-go plan?

To transfer a Microsoft Azure subscription to a different pay-as-go plan, you need to check the subscription’s eligibility for transfer under Azure’s policies. This can be done through the Azure portal, where you can see the current plan and options for changing it. Once you confirm the eligibility, you can initiate the transfer to the new pay-as-you-go plan, ensuring that the subscription is billed according to the new plan going forward.

Q: How do I assign roles and manage role-based access in Azure?

Q: What should I do if I need to change my Azure subscription to another offer?

Q: How can I view and manage my Azure subscription’s role assignments and access control?

Q: What steps should I take to prepare for a new Azure subscription?

When preparing for a new Azure subscription, start by understanding the different types of subscriptions available, like classic subscription or pay-as-you-go. You should also determine your resource needs, such as whether you need a new resource group or if you’re planning to use specific Azure services like Azure SQL. Then, use the Azure portal or Azure CLI to set up your subscription and configure it according to your needs.

Q: How do I transfer a subscription within Microsoft Azure?

To transfer a subscription within Microsoft Azure, first, you need to determine the type of transfer you need, such as transferring billing ownership or transferring a subscription to a different Microsoft customer agreement. Then, initiate the transfer request through the Azure portal. The recipient of the transfer request will need to accept it to have access to manage the resources under the new agreement or billing account.

Q: What should I know about managing Azure subscriptions as part of a Microsoft Customer Agreement?

When managing Azure subscriptions as part of a Microsoft Customer Agreement, it’s important to understand the terms and conditions of the agreement. You should also familiarize yourself with how your subscription is billed under this agreement. Use the Azure portal for managing your subscriptions, accessing billing information, and checking frequently asked questions related to your agreement and subscription. This knowledge is essential for ensuring compliance and effective management of your Azure resources.

Q: How can a tenant add an Azure subscription to their Microsoft Entra Tenant?

To add an Azure subscription to your Microsoft Entra tenant, you can associate the subscription with your account. This involves using Azure Resource Manager to manage and change the azure subscription or account. You can see the details of your current subscription and add or change it to another subscription as needed.

Q: What is the process to determine account billing administrator in Azure?

Q: Where can one find additional resources for managing Azure subscriptions?

For additional resources on managing Azure subscriptions, Microsoft Learn offers comprehensive guides and answers to frequently asked questions. This includes information on various resource types, subscription management, and using Azure RBAC for assigning roles in Azure.

Q: What are the steps to transfer an Azure subscription to a new administrator?

What is Windows Registry?

Let’s get our basics straight before diving in. The Windows Registry is the nerve center of your Windows operating system and the apps that call it home. It’s a database storing vital configuration info.

Important
Meddling in the Registry without care is like juggling chainsaws — thrilling but risky!

The Registry is a maze of keys within keys, storing values with specific data types. It’s a flexible repository for system and application settings, organized into ‘hives’ — logical groupings that Windows loads during startup.

Remember the days when editing the Registry was a daredevil’s game, done through regedit.exe?

Windows NT changed the game with the reg.exe command, ushering in safer programmatic management. And let’s not forget WMI (Windows Management Instrumentation), another powerful tool for Registry wrangling.

reg.exe command

How to Set a Registry Key with PowerShell

For IT professionals working with PowerShell, life got easier with the introduction of the Registry provider. This nifty tool simplifies Registry tasks, transforming complex chores into a walk in the park.

PowerShell could have gone the route of creating a zillion cmdlets for every data store — Registry, files, certificates, you name it.

But instead, it introduced providers, an intermediary layer that turns these data stores into something akin to a file store. You can use familiar commands across different data types, thanks to these providers.

Curious about available providers? Run the `Get-PSProvider` cmdlet. It’ll introduce you to:

  • Registry: This provider deals with the Windows Registry, offering access to keys like HKLM (local machine) and HKCU (current user).
  • Alias, Environment, and Function: These providers handle aliases, environment variables, and functions.
  • FileSystem: This one’s for managing files and folders.
  • Certificate: For working with certificates.
Get-PSProvider in Windows PowerShell

Registry Value Entries: The Building Blocks

Let’s explore Registry Value Entries and how they play a role in PowerShell scripting.

Think of Registry Value Entries as attributes of registry keys. PowerShell’s *-ItemProperty cmdlets are your tools for managing these.

Here’s how you can use them in real-world scenarios:

Scenario 1

Imagine creating a “Version” registry value under the key “HKCU:\Software\Test\MyKey” with a value of “12“.

:/>  Windows 10 не видит жесткий диск. Работа с разделами.

You might be tempted to use the `New-ItemProperty` cmdlet like this:

$RegistryPath = 'HKCU:\Software\Test\MyKey’
$Name	= 'Version'
$Value	= ‘12’
New-ItemProperty -Path $RegistryPath -Name $Name -Value $Value -PropertyType DWORD -Force

But if “HKCU:\Software\Test\MyKey” doesn’t exist, you’ll hit an error.

To avoid this, use Test-Path to check for the key’s existence, and New-Item to create it if needed:

New-ItemProperty : Cannot find path 'HKCU:\Software\Test\MyKey' because it does not exist.
New-Item property error

To address this issue more gracefully, you can take a safer approach:

# Set variables to indicate value and key to set
$RegistryPath = 'HKCU:\Software\Test\MyKey’
$Name	= 'Version'
$Value	= '12'
# Create the key if it does not exist
If (-NOT (Test-Path $RegistryPath)) { New-Item -Path $RegistryPath -Force | Out-Null
}
# Now set the value
New-ItemProperty -Path $RegistryPath -Name $Name -Value $Value -PropertyType DWORD -Force

This modified script first checks whether the registry key exists using `Test-Path`. If it doesn’t exist, it creates the key using `New-Item`. This way, you ensure that the required registry structure is in place before setting the value entry.

New-Item to create the registry key

If we know that the registry key value already exists and we want to modify the value, we can use the `Set-ItemProperty` cmdlet. Think of each Registry Value Entry as an attribute of a particular registry key.

Scenario 2

Imagine you have a scenario where you want to update an existing registry value entry called “Version” under the key “HKCU:\Software\CommunityBlog\Scripts” with a new value, let’s say “13.”

You can achieve this using the `Set-ItemProperty` cmdlet. Here’s an example of how you can do it:

# Define the registry path and property name
$RegistryPath = 'HKCU:\Software\Test\MyKey’
$PropertyName = 'Version'
# Specify the new value
$NewValue = '13'
# Use Set-ItemProperty to update the registry value
Set-ItemProperty -Path $RegistryPath -Name $PropertyName -Value $NewValue
Set-ItemProperty to update the registry value

By running this script, you can effectively change the “Version” value in the specified registry key to “13.”

This demonstrates how `Set-ItemProperty` can be a valuable tool for managing and updating registry values within your PowerShell scripts.

Important
Tinkering with the registry, whether through the Registry Editor or PowerShell commands, can have serious consequences if done improperly.
Always exercise caution, back up critical data, and be certain of the changes you’re making. The power of the registry comes with the responsibility to use it wisely!

Set a registry key with PowerShell App Deployment Toolkit

Now, for the IT pros responsible for getting software up and running on a bunch of Windows computers. Sometimes, you need to tweak things behind the scenes to make sure the software behaves just right. That’s where the `Set-RegistryKey` function steps in.

This custom cmdlet makes it much easier to work with registry keys as opposed to the example we just had a look above. With this you don’t need to worry about additional checks in the registry by using Test-Path cmdlet.

This handy tool lets you tinker with the Windows Registry, a database that holds all sorts of settings for your operating system and applications. With `Set-RegistryKey`, you can make changes, create new settings, or fine-tune existing ones to match your needs.

Picture this: you’re deploying a new app, and it’s got a particular setting that needs to be just so. You can use `Set-RegistryKey` to make sure that setting is dialed in perfectly on all the computers you’re working with. No need to manually mess around in the Registry – it’s all automated.

Here’s a quick example of how you might use it:

Let’s say you’re deploying a new application, and it needs a specific registry setting to work correctly. You can use `Set-RegistryKey` to create that setting and make sure it’s set to the right value. No fuss, no manual Registry editing – it’s all taken care of.

# Set a registry value to configure application behavior
Set-RegistryKey -Key 'HKLM\Software\YourApplication' -Name 'SettingName' -Value 'DesiredValue'
# Create a new registry key if it doesn't exist
Set-RegistryKey -Key 'HKLM\Software\YourApplication\NewKey'
# Modify an existing registry value
Set-RegistryKey -Key 'HKCU\Software\YourApplication' -Name 'ExistingSetting' -Value 'UpdatedValue'

Conclusion

In essence, the Set-RegistryKey cmdlet in the PowerShell Application Deployment Toolkit is your secret weapon for smooth software deployments. It’s like having a magic wand for the Windows Registry, ensuring your software runs seamlessly on every computer.

See author's page

Alex Marin

Application Packaging and SCCM Deployments specialist, solutions finder, Technical Writer at Advanced Installer.

Managing all the license options within an organization can turn into a daunting challenge if you don’t know how to do it.

What is the Set-MsolUserLicense Cmdlet?

Let’s quickly explore the meaning of the parameters on the syntax:

  • ObjectId: Unique identifier for the user targeted for license modification.
  • LicenseOptions: Additional settings for license assignment (optional).
  • AddLicenses: Specifies the array of licenses to be added to the user.
  • RemoveLicenses Parameter: Licenses to be removed from the user.
  • TenantId: Identifier for the Microsoft 365 tenant (useful in multi-tenant environments).

What Can You Use Set-MsolUserLicense For?

  • Onboarding a New Employee: When a new employee joins the company, use Set-MsolUserLicense to grant them access to Microsoft 365 services by assigning a specific license, such as one that includes email, collaboration tools, and other applications.
  • Offboarding a Departing Employee: When an employee leaves the organization, use the cmdlet to remove their Microsoft 365 license, ensuring that they no longer have access to company resources and services.
  • Adjusting License Plans for Role Changes: If an employee’s role changes within the organization, use Set-MsolUserLicense to modify their license plan. For example, upgrade a user to a plan that offers more advanced features or downgrade to a plan with fewer features based on their new responsibilities.

How to Use Set-MsolUserLicense in PowerShell

Step 1: Connect to Office 365

Then, we’ll use this command to access the Microsoft Office 365 module:

Step 2: Run Set-MsolUserLicense

Step 3: Verify the Changes Using the Get-MsolUser Cmdlet

Using the Set-MsolUserLicense Command

Either way, keep in mind that due to the recent changes in the Azure Active Directory module, Microsoft is planning to deprecate certain PowerShell commands in March, 2024.

Переменные среды power shell set

The ProblemJump To Solution

When I attempt to run a PowerShell script (for example, MyScript.ps1), I get the error:

Click to Copy

MyScript.ps1 cannot be loaded because the execution of scripts is disabled on this system.

How do I enable script execution?

The Solution

To run PowerShell scripts, it may be necessary to change the PowerShell execution policy. The execution policy on most modern Windows systems is set to Restricted by default, preventing the execution of any PowerShell scripts. This is a security measure as PowerShell scripts can have powerful and dangerous functionality.

:/>  Режим «В самолете» в Windows 10: что это за режим и как его отключить

Click to Copy

To temporarily bypass the execution policy and run scripts in a single PowerShell session, we can specify the flag -ExecutionPolicy Bypass when starting PowerShell from Windows CMD or the Run dialog.

For example, the command below will run MyScript.ps1 without modifying the execution policy:

Click to Copy

powershell -noexit -ExecutionPolicy Bypass -File MyScript.ps1

To enable script execution permanently, we can use PowerShell’s Set-ExecutionPolicy cmdlet.

Click to Copy

This will allow execution of any locally written PowerShell scripts, but will also require that PowerShell scripts downloaded from the internet are digitally signed by a trusted publisher. This is the default setting for Windows Servers.

If this policy is still too restrictive, we can remove all restrictions with this command:

Click to Copy

This will allow any script to be executed. You will still be prompted for permission when executing a script from the internet.

A full list of execution policy options is available here.

To set the environmental variable using PowerShell you need to use the assignment operator (). If the
variable already exists then you can use the operator to append the value, otherwise, a new environment variable will be created.

For example, there is no AZURE_RESOURCE_GROUP environment variable that exists in the system. We can create it as below.

Now when you check the environment variables in the system, you will get the above variable name.

\ProgramData
APPDATA CCOMPUTERNAME TEST1

If you have another resource group and if you need to add to the same environment variable then as
mentioned earlier use operator and separate value with a semicolon (;).

PS C:\Windows\system32> $env:AZURE_RESOURCE_GROUP
MyTestResourceGroup;MyTestResourceGroup2

If the value(s) already exists for an environment variable then you can also change the value by simply assigning the value to the variable. For example,

The above method we have seen is to set the environment variable temporarily, once you close the
PowerShell console the value gets destroyed. To add or set the environment variable persistently you
need to use the .NET method.

Setting Environment Variable Persistently

PS C:\> $env:ResourceGroup
AZ_Resource_Group
Kickstart Your

Get certified by completing the course

Переменные среды power shell set

Ah, Monday morning dramas — the boss has that “we’ve got a problem” look plastered on their face. Surprise, surprise! You’re moving offices, and guess who’s got to wave their IT magic wand to make your network play nice with the existing setup? Oh yes, it’s you! But hold on — before you start thinking of visiting each computer individually like it’s 1999, let’s introduce you to PowerShell. I present a PowerShell method for configuring static and DHCP IP addresses that utilizes the newer PowerShell cmdlets.

Newer versions of PowerShell mean more cmdlets

Microsoft implemented more PowerShell cmdlets, including some cmdlets that are specific to configuring network adapters and TCP/IP settings.

 Using these commands, we can set various network configurations and settings more easily from a PowerShell script.

If you have multiple network adapters, you need to identify which network adapter you wish to view or modify by name, interface index, status, etc. For systems with one adapter, you can typically get this by using only Get-NetAdapter with no extra parameters. Please adjust this to suit your environment.

This cmdlet gets you the network configuration (interfaces, IP addresses, and DNS servers). 

The Get-NetIPInterface cmdlet gets you the IP interfaces, which can include both IPv4 and IPv6 addresses and their associated configurations. We will use just IPv4 today, so my example reflects that.

The Set-NetIPInterface allows you to modify settings.

This cmdlet lets you set the DNS servers associated with a particular network interface.

This cmdlet lets you modify IP routes in the routing table, including wiping out all routes.

This cmdlet allows you to create and configure an IP address. This can include both IPv4 and IPv6 addresses.

How to set static/DHCP IP addresses

Enough of the boring explanations. Let’s move on to the fun!

We’re going to give a couple of examples for setting static and DHCP IP addresses by using the commands mentioned above.

Set a static IP address

Set an address with DHCP

How to disable static/DHCP IP addresses

In PowerShell, you can manage network adapter settings to disable or enable static (manually assigned) and DHCP (automatically assigned) IP addresses using the Set-NetIPInterface cmdlet. The specific command depends on whether you want to disable static or DHCP addresses. Here are the PowerShell commands for each scenario:

Disable a static IP address

To disable a static IP address on a network adapter, you can set the interface to obtain an IP address automatically (DHCP). Here’s the PowerShell command:

Replace “YourNetworkAdapterName” with the actual name or alias of your network adapter. This command configures the interface to obtain an IP address automatically from a DHCP server.

Disable DHCP (obtain IP automatically) and enable a static IP address

Replace “YourNetworkAdapterName” with the actual name or alias of your network adapter, “YourStaticIPAddress” with the desired static IP address you want to assign, “YourSubnetPrefixLength” with the subnet prefix length (e.g., 24 for a typical subnet mask of 255.255.255.0), and “YourDefaultGatewayIP” with the IP address of your default gateway.

Final thoughts

This is still just scratching the surface of what’s available. Remember to check out what properties and methods are available for Win32_NetworkAdapterConfiguration, and you’ll be able to customize all the settings for your particular environment. For a more complete list of cmdlets you can use to set network and TCP/IP settings, check out our PowerShell Commands Library.

Jordan Hammond fun headshot

Jordan had spent his life wondering why tasks he didn’t like to do had no options to complete themselves. Eventually he had to make that happen on his own. It turned out that he enjoyed making tasks complete themselves, and PDQ thought that is something he should talk about on the internet.