Как управлять конфигурацией переменных в проекте power shell

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

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.

Как управлять конфигурацией переменных в проекте power shell

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.

You can create an appsettings.json file within the $Env:ProgramDataPowerShellUniversal folder. You can use a subset of the settings from within the appsettings.json file. For example, if you wanted to override the JWT settings, you could have an appsettings.json file like this.

You can also set environment variables for your settings. Environment variables should have an underscore between each subset of the appsettings.json file. For example, if you want to change the JWT signing key via environment variable, you would set the variable $Env:Jwt__SigningKey. If you wanted to set the external API URL, you would set $Env:Api__Url.

Using an environment variable for the OpenID Connect secret.

$Env:Authentication__OIDC__ClientSecret = “mySecret”

Using an environment variable for JWT signing key.

$Env:Jwt__SigningKey = “mySigningKey”

You can specify the location of the appsettings.json file by using the –appsettings command line argument for Universal.Server.exe .

Kestrel / Endpoints

The Kestrel endpoints section allows you to configure the web server. This settings are not used when hosting in IIS. In this section you can configure options like HTTPS and the port that PowerShell Universal will listen on.

:/>  Как установить dns из командной строки в Windows 10 или 11?

When true, the web server will redirect HTTP requests to HTTPS

Required when configuring PowerShell Universal as a nested site within IIS. This should contain the nested IIS route. Such as /psu

When set to SameSiteNone, the SameSite=None value will be set on cookies in PSU. This is useful for when hosting PSU in iframes.

Sets the instrumentation key for Application Insights.

The logging options define the level of logging exposed by Universal. The core Universal logging setting Logging / LogLevel / Default can be adjusted to increase the level of logging by the Universal components.

The number of log files to retain. A new log file will be created each day.

The log levels for various portions for the Universal server. You can set values such as Debug, Information, Warning and Error.

The hosts that are allowed to connect to the webserver. Defaults to any host.

Configures the hosts that are allowed to make cross-origin resource sharing requests (CORS) to the server. To allow multiple hosts, separate each host by a semicolon.

Path to the storage location of the configuration files used by Universal.

Path to the database used by Universal.

Git remote used to sync to Universal.

Git branch to checkout when syncing to Universal.

Location of a custom configuration script to load. You can return objects like scripts, dashboards and endpoints from this script.

Sets the git mode. It can be either manual or automatic. Defaults to manual.

Sets the external URL used internally by Universal. This is necessary when running Universal from within a reverse proxy like IIS. When using cmdlets like Get-UAScript from within a running job, the Universal server needs to determine where the web server. When running within a proxy, it cannot determine this itself. You will want to configure this to point to the name and port of the IIS website in this configuration.

OpenID Connect authentication settings.

Whether OIDC is enabled.

The path that the OIDC provider will call back to.

The configured OIDC client ID.

The configured OIDC client secret.

Resources granted with this OIDC token.

The authority to invoke when authenticating. This is the URL of your OIDC provider.

The type of response returned by the provider. This most common value here is code

Whether to save the token so it is available to endpoints like dashboards.

Correlation cookie same settings.

If set to true, the cookie life time will be set to the token life time. This overrides the session time out value.

WS-Federation authentication settings.

Whether WS-Fed is enabled.

The metadata address to retrieve information about the WS-Fed instance.

Session timeout threshold (minutes)

Number of minutes before a logged in session times out (defaults to 25)

JSON Web Token configuration settings

The signing key for the JWT tokens.

The issuer that will be included in the token.

The audience that will be included in the token.

Options for configuring the default secret vaults.

SecretStore PasswordThe password for the PSUSecretStore vault. This uses the Microsoft SecretStore module.

Database EncryptionKeyThe AES 128 encryption key used to encrypt secrets stored in the database.

Generating an Encryption Key

Encryption keys are 128-bit and require the proper length. They are encoded as a base64 string and converted to bytes on startup.

Settings for automation specific features.

Custom queues that this PSU instance is a part of.

The number of seconds to wait before failing a job after starting the PowerShell process to execute it if the process does not communicate back to the server.

Whether to generate files in the temporary directory when starting job. This is useful for debugging if jobs are timing out before starting.

Whether to continue running a job after the service has stopped. Job progress will fail to be reported but the script will continue to run.

The number of Hangfire worker threads to start on the server. This setting is node specific. It defaults to 100. This is the total number of jobs that can run on the particular node at a single time.

The node name option is used to change the name of the PowerShell Universal instance. By default, this is the local computer’s name. When using PowerShell Universal in a container, this can become probematic because the name can change whenever the container is restarted.

To set a static node name, change this parameter.

:/>  Запуск powershell из bat файла и выполнение команды

Enables profiling of scripts within PowerShell Universal. This is disabled by default as there is a memory impact when enabling profiling.

One of the challenges of writing PowerShell scripts is how to handle variables configuration, such as settings, paths, credentials, and other values that may vary depending on the environment or context. In this article, we will explore some best practices for managing variables configuration in a PowerShell project.

Use a Configuration File

One of the simplest and most common ways to manage variables configuration is to use a configuration file. A configuration file is a PowerShell script that defines global variables that can be used by other scripts in the project. For example, you can create a file named Config.ps1 and put all your configuration variables in it, such as:

Enter fullscreen mode

Exit fullscreen mode

# Dot-source the configuration file# Use the configuration variables

Using a configuration file has some advantages:

However, using a configuration file also has some drawbacks:

Use Environment Variables

Another way to manage variables configuration is to use environment variables. Environment variables are variables that are defined by the operating system or by other applications and are available to all processes running on the system. PowerShell can access environment variables using the env: drive, which is a special provider that exposes environment variables as a hierarchical namespace. For example, you can access the PATH environment variable using $env:PATH.

To use environment variables for your configuration values, you need to define them before running your PowerShell script. You can do this using various methods, such as:

Using environment variables has some advantages:

However, using environment variables also has some drawbacks:

Use Parameters

A third way to manage variables configuration is to use parameters. Parameters are arguments that are passed to a PowerShell script or function when it is invoked. Parameters allow you to specify input values for your script or function without hard-coding them in the code. You can define parameters for your script or function using the param keyword at the beginning of the script or function body. For example:

# Use the parameters

Then, you can pass values to the parameters when you call the script or function. You can do this using various methods, such as:

# Define a hash table with parameter names and values

Using parameters has some advantages:

However, using parameters also has some drawbacks:

My favorite approach

For my project I would like to use a typical config file with a key-value-pair for each line.
Something like this:

tenantID=this is my tenant
clientID=client id
clientSecret=my secrets
tenantName=Contoso.com

There isn’t an official way to do that in PowerShell directly.
So, you have to create a small portion of code to load the config file content and set the variable names and values.

I created a function for a better approach and maintenance of the code.
In this foreach, the code set a variable with the same name of the config key and the value with everything in the row after the = character.
In order to use the variables in all the scripts in your project and modules, the script sets the scope as global.

Using the variables is very easy, you just need to add the dollar symbol on a variable with the same name of the config key.
From the previous example you can have:
$tenantID, $clientID and so on.

You can call the function Load-Config at the beginning of your script. In this case you can be sure that all the script and functions have access to the variables.

Conclusion

Как управлять конфигурацией переменных в проекте power shell

If you run the same commands every time you launch the PowerShell console, then it’s probably time to customize your PowerShell profile for a smoother scripting experience.

When you develop a profile in PowerShell, you define your settings as a PowerShell script to make the process easier. In this article, learn about the PowerShell profile, how to edit your profile for any PowerShell console — the newer cross-platform PowerShell 7, Windows PowerShell 5.1, Visual Studio (VS) Code and PowerShell Integrated Script Environment (ISE) — and several handy additions for your profile.

What is the PowerShell profile?

The PowerShell profile is a PowerShell script that runs every time you launch PowerShell, except when you use the flag. The PowerShell profile location varies depending on several conditions:

  • Linux: /usr/local/Microsoft/powershell/7/
  • macOS: /usr/local/Microsoft/powershell/7/

The directories can have several valid profile files. The difference between the profiles is based on the host application that launches PowerShell. We use ISE and VS Code as examples for hosts:

If any of those files don’t exist, PowerShell skips that profile.

:/>  Ping update api 1c ru new 1000

The easiest way to retrieve the PowerShell profile is through PowerShell itself. You don’t need to remember the profile paths because they are stored in the variable.

The $Profile variable shows the PowerShell profile location.

Как управлять конфигурацией переменных в проекте power shell

Find the other PowerShell profile locations on the system.

Как управлять конфигурацией переменных в проекте power shell

How to customize the PowerShell profile

Due to the PowerShell profile’s flexibility, you have a range of customization options to suit how you want PowerShell to work.

Customize your PowerShell prompt

We could dedicate a whole article to this topic and still not cover all the possibilities to modify the PowerShell prompt. If you aren’t familiar with customizing your PowerShell prompt, you can find many examples of cool prompts to see what’s possible. This article covers a basic example.

To make this function run every time PowerShell loads, put it in your profile.

How to load a PowerShell module and set defaults

A mistake that I regularly make is using a module that requires authentication before I’ve authenticated. Some of the modules have checks that remind you to authenticate, while others throw a cryptic error. If this problem occurs for a module you use frequently, then consider adding the authentication steps to your profile.

How to add aliases and argument completers

However, one of my favorite aliases is for kubectl, the Kubernetes command-line tool for working with clusters. I use the letter as my alias:

New-Alias -Name k -Value kubectl

How to add custom functions to your PowerShell profile

As you develop your PowerShell abilities, you might write more one-off functions to help with your work. But you might not feel the code is worth adding to a module. After you put your code in a source control platform, such as GitHub, then you can use dot sourcing to load the code when running PowerShell:

This is just the start of what is possible. Start thinking about the commands you run frequently, and consider the other ways you can customize your PowerShell profile to make your life easier.

Anthony Howell is an IT expert who is well versed in multiple infrastructure and automation technologies, including PowerShell, DevOps, cloud computing, and the Windows and Linux OSes.

Installing the PowerShell extension

The PowerShell extension can be installed from the Visual Studio Code Marketplace by clicking the
Install Button. You can also install the PowerShell extension from within VS Code by opening
the Extensions view with keyboard shortcut (Windows, Linux ), typing PowerShell,
and selecting the PowerShell extension:

Как управлять конфигурацией переменных в проекте power shell

Major features

Or run the PowerShell: Show Session Menu command from the Command Palette
( (Windows, Linux )).

CodeLens support

CodeLenses are a VS Code feature to provide actionable, contextual information that’s displayed
within the source code.

CodeLens features include:

PSScriptAnalyzer integration

The PowerShell extension includes PSScriptAnalyzer by default, and automatically performs
analysis on PowerShell script files you edit in VS Code.

PSScriptAnalyzer comes with a collection of built-in rules that check various aspects of
PowerShell source code such as presence of uninitialized variables, usage of PSCredential type,
usage of Invoke-Expression, and others. The module also allows you to include or exclude specific
rules.

To disable PSScriptAnalyzer, open your settings ( (Windows, Linux )), browse
Extensions, select the PowerShell extension, and deselect the checkbox for Script
Analysis: Enable (powershell.scriptAnalysis.enable).

PSScriptAnalyzer also provides code formatting. You can invoke automatic document formatting
with the Format Document command or the ( (Windows , Linux )) keyboard shortcut.

Pester integration

Plaster is a template-based file and project generator written in PowerShell. Its purpose is
to streamline the creation of PowerShell module projects, Pester tests, DSC Configurations and more.

The PowerShell extension allows the creation of new Plaster projects using the PowerShell: Create
New Project from Plaster Template command from the Command Palette
( (Windows, Linux )).

PowerShell extension settings

You can also select the gear icon located in the lower left corner of the Activity Bar.

Types.ps1xml and Format.ps1xml files

You can also open the examples from the Command Palette ( (Windows, Linux )) with
the PowerShell: Open Examples Folder command.

Additional resources

There are more detailed articles in the PowerShell documentation. Start with Using VS Code.

Check out the troubleshooting guide for answers to common questions.

Testing new features and providing feedback

Как управлять конфигурацией переменных в проекте power shell

If you find a bug, open an issue and revert to the stable version while we fix it.

Оставьте комментарий