Sunday, April 19, 2020

PowerShell: Join-Path Joining Multiple Children

PowerShell's Join-Path cmdlet allows file paths, registry paths, etc. to be combined. Using Join-Path does not take a PhD in quantum physics to understand but prior to PowerShell 6.0 joining multiple paths was tedious. PowerShell 6.x, 7.x and later versions support joining paths as follows (excerpt from Microsoft's documentation for Join-Path):


To understand the elegance of the documentations "Example 7" consider a registry key that needs to be created programmatically:
HKLM:\SOFTWARE\Policies\Google\Update

The following code works for PowerShell 6.0 or later and can generate the aforementioned path programmatically in the style of Example 7:

[string] $hive = 'HKLM:'
[string] $softwareKey = 'SOFTWARE'
[string] $policiesKey = 'Policies'
[string] $googleKey = 'Google'
[string] $updateKey = 'Update'


[string] $path = Join-Path `
                    $hive `
                    $softwareKey `
                    $policiesKey `
                    $googleKey `
                    $updateKey

$path

The output from the above script is as follows:


PowerShell 5.x and Earlier

The previous code will fail if run under PowerShell 5.x or earlier. These versions of PowerShell do not support the command-line option allowing the combination of an indefinite number of paths. A more verbose usage of Join-Path is required to create the equivalent path (see below):

[string] $hive = 'HKLM:'
[string] $softwareKey = 'SOFTWARE'
[string] $policiesKey = 'Policies'
[string] $googleKey = 'Google'
[string] $updateKey = 'Update'
[string] $path =
        Join-Path -Path $hive -ChildPath $softwareKey |
        Join-Path -ChildPath $policiesKey |
        Join-Path -ChildPath $googleKey |
        Join-Path -ChildPath $updateKey

$path

The previous PowerShell code make use of the -Path and -ChildPath command-line options to create the desired registry path.


No comments :

Post a Comment