Extremely Serious

Category: Powershell (Page 1 of 2)

Understanding the $_ Variable in PowerShell

PowerShell, a versatile scripting language for Windows environments, introduces the $_ (underscore) variable, a fundamental component in the pipeline operation. This variable is used to reference the current object being processed, particularly within cmdlets that operate on objects in a pipeline. See the following sample usages:

ForEach-Object: Iterating through Objects

The ForEach-Object cmdlet allows the iteration through a collection of objects. The $_ variable is employed to reference the current object within the script block.

$numbers = 1, 2, 3, 4, 5

$numbers | ForEach-Object {
    "Current value is: $_"
}

In this example, $_ represents each number in the array during the iteration.

Where-Object: Filtering Objects

With Where-Object, you can filter objects based on specified criteria. The $_ variable is used to reference the current object within the script block defining the filtering condition.

$numbers = 1, 2, 3, 4, 5
$numbers | Where-Object { $_ -gt 2 }

Here, $_ is employed to compare each number in the array and filter those greater than 2.

Select-Object: Customizing Object Output

Select-Object is utilized for customizing the output of selected properties. The $_ variable is used to reference the current object's properties.

Get-Process | Select-Object Name, @{Name='Memory (MB)'; Expression={$_.WorkingSet / 1MB}}

In this example, $_ enables the selection and manipulation of properties for each process in the pipeline.

Sort-Object: Sorting Objects

Sorting objects with Sort-Object involves specifying a script block. The $_ variable is used to reference the current object for sorting.

Get-Service | Sort-Object {$_.Status}

Here, $_ is utilized to determine the sorting order based on the Status property of each service.

Group-Object: Grouping Objects

Group-Object groups objects based on a specified property. The $_ variable is essential for referencing the current object during the grouping process.

Get-Process | Group-Object {$_.PriorityClass}

In this instance, $_ plays a key role in grouping processes based on their PriorityClass property.

Understanding and effectively utilizing the $_ variable empowers PowerShell users to manipulate objects within the pipeline, providing flexibility and control over script operations.

Understanding PowerShell Script Blocks

PowerShell, with its versatility and scripting capabilities, provides a powerful feature called script blocks. Script blocks are enclosed sections of code that can be executed as a single unit. They are denoted by curly braces {} and can be assigned to variables, passed as parameters, or used with various PowerShell cmdlets and operators.

Basic Syntax

The basic syntax of a script block is as follows:

& {
    # Your code here
}

The ampersand & is the call operator, which is used to invoke the script block. The script block itself is enclosed within curly braces.

When to Use Script Blocks

1. Grouping Commands

Script blocks are handy for grouping multiple commands as a single unit. This is especially useful when you want to execute several commands together. For example:

& {
    $variable1 = "Hello"
    $variable2 = "World"
    Write-Host "$variable1 $variable2"
}

In this case, the script block groups the assignment of variables and the Write-Host command.

2. ForEach-Object Cmdlet

Script blocks are often used with the ForEach-Object cmdlet to perform actions on each item in a collection. Here's an example doubling each number in an array:

$numbers = 1, 2, 3, 4, 5

& {
    $numbers | ForEach-Object {
        $_ * 2
    }
}

3. Passing Parameters

Script blocks can receive parameters, making them versatile for dynamic code execution. Example:

$greet = {
    param($name)
    Write-Host "Hello, $name!"
}

& $greet -name "John"

Using Script Blocks in Batch Scripts

You can integrate PowerShell script blocks into batch scripts using the powershell.exe command. Here's a simple example:

@echo off
setlocal enabledelayedexpansion

set "PowerShellCommand=$numbers = 1, 2, 3, 4, 5; $numbers | ForEach-Object { $_ * 2 }"

for /f "delims=" %%i in ('powershell -Command "!PowerShellCommand!"') do (
    echo Doubled number: %%i
)

endlocal

This batch script utilizes a PowerShell script block to double each number in an array.

Conclusion

Understanding PowerShell script blocks opens up a range of possibilities for code organization, iteration, and dynamic execution. Whether you're grouping commands, iterating through a collection, or passing parameters dynamically, script blocks are a valuable tool in PowerShell scripting. Experimenting with different use cases will enhance your PowerShell scripting skills and help you streamline your automation tasks.

Managing PowerShell Module Repositories

PowerShell module repositories play a crucial role in the distribution and management of PowerShell modules. These repositories serve as centralized locations where modules can be stored and easily accessed by PowerShell users. In this article, we'll explore how to register, list, and unregister module repositories using PowerShell cmdlets.

Registering a Module Repository

To register a new module repository, you can use the Register-PSRepository cmdlet. The basic syntax for registering a repository is as follows:

Register-PSRepository -Name RepositoryName -SourceLocation RepositorySource -InstallationPolicy Policy

Here, "RepositoryName" is the desired name for your repository, "RepositorySource" is the location where the modules are stored, and "Policy" is the installation policy for the repository. For example:

Register-PSRepository -Name MyRepository -SourceLocation 'https://someNuGetUrl.com/api/v2' -InstallationPolicy Trusted

This command registers a repository named "MyRepository" with the source location set to https://someNuGetUrl.com/api/v2 and an installation policy set to "Trusted." The installation policy can be set to Trusted, Untrusted, or Undefined.

Listing Module Repositories

To view a list of all registered module repositories, you can use the Get-PSRepository cmdlet:

Get-PSRepository

Executing this command will display information about each registered repository, including its name, source location, installation policy, and other relevant details.

Unregistering (Deleting) a Module Repository

If you need to remove a repository, you can use the Unregister-PSRepository cmdlet. The syntax is straightforward:

Unregister-PSRepository -Name RepositoryName

For example, to unregister "MyRepository," you would run:

Unregister-PSRepository -Name MyRepository

Conclusion

Effectively managing PowerShell module repositories is essential for maintaining an organized and efficient development and deployment environment. Whether you are registering a new repository, listing existing ones, or removing unnecessary ones, these PowerShell cmdlets provide the necessary tools to streamline your module management workflow.

By incorporating these commands into your PowerShell scripts and workflows, you can enhance your ability to work with modules and ensure a smooth and efficient development process. Don't forget to consider the installation policy when registering repositories to control script execution on your system.

Remember to run PowerShell with appropriate permissions, especially when performing actions that involve registering or unregistering repositories.

PowerShell Module Management: Installation, Listing, Updating, and Importing

PowerShell modules are an integral part of extending the functionality of PowerShell. They are collections of cmdlets, functions, workflows, providers, and scripts that can be easily shared and reused. In this article, we'll explore the basics of PowerShell module management, covering installation, listing, updating, importing, and filtering the module list.

1. Listing Installed Modules:

Before managing modules, it's useful to know which modules are already installed on your system. The Get-Module cmdlet with the -ListAvailable parameter allows you to view a list of modules available on your system.

# Display all available modules
Get-Module -ListAvailable

This command displays information about all available modules. You can filter the list using -Name parameter for more specific results.

# Display only modules with "Name" in their name
Get-Module -ListAvailable -Name '*Name*'

Replace *Name* with the keyword you want to filter.

2. Listing All Available Repositories:

To view information about all registered repositories, use the Get-PSRepository cmdlet.

Get-PSRepository

This command displays a list of registered repositories along with their names, sources, and other relevant information.

Managing repositories is not part of this article.

Use this if you need to know where the modules are coming from.

3. Installing a Module from PowerShell Gallery:

To install a module from the registered repositories, use the Install-Module cmdlet.

Install-Module -Name ModuleName

Replace ModuleName with the actual name of the module you want to install.

5. Updating a Module:

Keeping modules up-to-date is essential for utilizing the latest features and improvements. The Update-Module cmdlet simplifies this process.

Update-Module -Name ModuleName

This command fetches and installs the latest version of the specified module.

6. Uninstalling a Module:

If a module is no longer needed, you can uninstall it using the Uninstall-Module cmdlet.

Uninstall-Module -Name ModuleName

This removes the specified module from your system.

7. Importing a Module (Without -Force):

When importing a module without the -Force parameter, PowerShell checks for conflicts with existing modules before importing.

Import-Module -Name ModuleName

This is the default behavior, and PowerShell only imports the module if there are no conflicts.

8. Importing a Module with -Force Parameter:

When importing a module with the -Force parameter, PowerShell forcefully imports the module, even if there are conflicts with existing modules.

Import-Module -Name ModuleName -Force

This is useful when you want to ensure that the module is imported, regardless of any conflicts.

Note: Starting with PowerShell 3.0, module auto-loading is the preferred method. PowerShell automatically loads a module when you use a cmdlet or function from that module. However, if you need to explicitly import a module, Import-Module is available.

Conclusion:

PowerShell module management is a straightforward process that involves listing, installing, updating, and uninstalling modules. Additionally, importing modules allows you to make their functionality available in your PowerShell session. To explore available repositories, use the Get-PSRepository cmdlet. When importing a module, consider using the -Force parameter if you encounter conflicts, or import without it to perform conflict checks.

Happy scripting!

Creating and Using PowerShell Modules: A Step-by-Step Guide

owerShell modules provide a way to organize and package your PowerShell code for better reusability and maintainability. In this guide, we'll walk through the process of creating a simple PowerShell module, exporting cmdlets, and accessing module information.

Step 1: Module Structure

Let's start by creating a basic structure for our module. We'll have a module manifest file (PSD1) and a script module file (PSM1).

MyModule.psd1

# MyModule.psd1

@{
    ModuleVersion = '1.0.0.0'
    Author = 'YourName'
    Description = 'A simple PowerShell module example'
    RootModule = 'MyModule.psm1'
}

MyModule.psm1

# MyModule.psm1

function Get-Greeting {
    Write-Output 'Hello, this is a greeting from MyModule!'
}

Without the usage of Export-ModuleMember all the members are exported. Thus in this initial version of the module the Get-Greeting cmdlet is exported.

Step 2: Cmdlet in a Separate File

You may want to organize your cmdlets in a separate PS1 file within the module. Let's create a file named Cmdlets.ps1 to hold our Get-Double cmdlet.

Cmdlets.ps1

# Cmdlets.ps1

function Get-Double {
    param (
        [int]$Number
    )

    $result = $Number * 2
    Write-Output "Double of $Number is $result"
}

Update the main module file to dot-source this file:

MyModule.psm1

# MyModule.psm1

# Dot-source the separate PS1 file containing cmdlets
. $PSScriptRoot\Cmdlets.ps1

function Get-Greeting {
    Write-Output 'Hello, this is a greeting from MyModule!'
}

# Export the cmdlet
Export-ModuleMember -Function Get-Double

In this update with the usage of Export-ModuleMember cmdlet this makes Get-Greeting cmdlet private.

Step 3: Using the Module

Now, let's use our module in a PowerShell session.

  1. Navigate to the directory containing the "MyModule" folder.

  2. Import the module:

    Import-Module .\MyModule
  3. Use the exported cmdlet:

    Get-Double -Number 5
  4. Use other functions within the module:

    Get-Greeting

Step 4: Accessing Module Information

To access information about the loaded module, use the Get-Module cmdlet:

# Import the module (if not already imported)
Import-Module .\MyModule

# Get information about the module
$moduleInfo = Get-Module -Name MyModule

# Display module information
$moduleInfo

You can also access specific properties:

# Access specific properties
$moduleName = $moduleInfo.Name
$moduleVersion = $moduleInfo.Version
$moduleAuthor = $moduleInfo.Author

# Display specific properties
Write-Output "Module Name: $moduleName"
Write-Output "Module Version: $moduleVersion"
Write-Output "Module Author: $moduleAuthor"

With these steps, you've created a simple PowerShell module, exported a cmdlet, and learned how to access module information. This modular approach can greatly enhance the organization and reusability of your PowerShell scripts and functions. Happy scripting!

Understanding Dot Sourcing in PowerShell

PowerShell, a powerful scripting language and command-line shell developed by Microsoft, offers various features for efficient script development. One such feature is dot sourcing, a technique that allows you to run a script in the current scope rather than a new one.

What is Dot Sourcing?

Dot sourcing involves loading and executing the contents of a script within the current scope. This is achieved by prefixing the script's path with a dot and a space. For example:

. .\YourScript.ps1

The dot and space indicate that the script should be run in the current scope, enabling you to access functions, variables, and other elements directly.

Why Dot Source?

1. Scope Retention

When a script is executed without dot sourcing, it runs in its own scope. This means any variables, functions, or changes made within the script do not affect the calling scope. Dot sourcing, on the other hand, allows the script to retain and modify the variables and functions of the calling scope.

2. Code Modularization

Dot sourcing promotes code modularization. You can break down your scripts into smaller, manageable parts and then use dot sourcing to incorporate them into larger scripts or your PowerShell session. This enhances code reusability and maintainability.

3. Function and Variable Access

By dot sourcing a script, you gain direct access to its functions and variables. This can be particularly useful when you have utility functions or configurations stored in separate script files that you want to leverage in different contexts.

How to Dot Source

To dot source a script, follow these simple steps:

  1. Navigate to the Directory: Open a PowerShell session and navigate to the directory containing your script.

  2. Dot Source Command: Use the dot source command followed by the path to your script:

    . .\YourScript.ps1

This command executes YourScript.ps1 in the current scope, making its elements accessible directly.

Example Scenario

Let's consider a practical example to illustrate dot sourcing. Suppose you have a utility script named Utilities.ps1 with a function that adds two numbers:

Utilities.ps1

# Utilities.ps1

function Add-Numbers {
    param (
        [int]$a,
        [int]$b
    )

    $sum = $a + $b
    Write-Output "The sum of $a and $b is: $sum"
}

Now, you can use dot sourcing in another script, say MainScript.ps1, to leverage the Add-Numbers function:

MainScript.ps1

# MainScript.ps1

# Dot source the Utilities.ps1 script
. .\Utilities.ps1

# Use the Add-Numbers function from the dot sourced script
Add-Numbers -a 5 -b 7

When you run MainScript.ps1, it will output:

The sum of 5 and 7 is: 12

This example demonstrates how dot sourcing allows you to use functions defined in another script directly in the current script, promoting code modularity and reusability.

Conclusion

Dot sourcing is a valuable technique in PowerShell, providing a way to bring the functionality of external scripts into the current scope. Whether for code modularization, retaining scope changes, or easy access to functions and variables, dot sourcing contributes to a more organized and efficient scripting experience in PowerShell.

Remember to use dot sourcing judiciously, keeping in mind its impact on scope and code structure. With this technique, you can harness the full power of PowerShell for streamlined script development.

Java UTF-16LE Base64 CODEC

The UTF-16LE base64 encoding is compatible to be used with powershell's encoded command.

Encoding

//The text to encode.
var command = "Write-Output \"Hello World\"";
var encodedString = Base64.getEncoder().encodeToString(command.getBytes(StandardCharsets.UTF_16LE));
System.out.printf("Base64: %s%n", encodedString);

Output

Base64: VwByAGkAdABlAC0ATwB1AHQAcAB1AHQAIAAiAEgAZQBsAGwAbwAgAFcAbwByAGwAZAAiAA==

The preceding output can be used with powershell like the following:

powershell -encodedcommand VwByAGkAdABlAC0ATwB1AHQAcAB1AHQAIAAiAEgAZQBsAGwAbwAgAFcAbwByAGwAZAAiAA==

Decoding

//The base64 text to decode.
var base64="VwByAGkAdABlAC0ATwB1AHQAcAB1AHQAIAAiAEgAZQBsAGwAbwAgAFcAbwByAGwAZAAiAA==";
byte[] decodedBytes = Base64.getDecoder().decode(base64);
String decodedString = new String(decodedBytes, StandardCharsets.UTF_16LE);
System.out.printf("Decoded: %s%n", decodedString);

Output

Decoded: Write-Output "Hello World"

Removing the Timestamp from the downloaded SNAPSHOT

Use case

The downloaded snapshot has timestamp associated with it like the following:

artifact-1.0.0-20211012.041152-1.jar

But the tooling is expecting an absolute name like the the following:

artifact-1.0.0-SNAPSHOT.jar

Powershell Script

#The target artifact
$ArtifactId = "artifact"

#The target SNAPSHOT version
$Version = "1.0.0-SNAPSHOT"

if ($Version -match "^(.*)-SNAPSHOT$") 
{
    $Prefix = "{0}-{1}" -f $ArtifactId,$Matches.1
    $Pattern = "^(${Prefix}).*(\.jar)$"

    Get-ChildItem ('.') | ForEach-Object {
        If ($_.Name -match $Pattern) {
            $NewName = "{0}-SNAPSHOT{1}" -f $Matches.1, $Matches.2
            Rename-Item $_ -NewName $NewName
            $Message = "Renaming from {0} to {1}" -f $_.Name, $NewName
            echo $Message
        }
    }
}
« Older posts