PS: Removing Backticks

1 minute read

Description:

So lately I have been going over my code and trying to remove backticks. That is because, although they work, they can cause a script to fail with a simple space character is placed after them. The way to do this has often been to place objects in hash tables instead. So now I follow this setup for hash tables and arrays:

To Resolve:

  1. Hashtables go in four steps => initialize, populate, call the function, and then clear the variable. You will see this often with my SetReg function for example:

    1
    2
    3
    4
    5
    6
    7
    8
    
    $Params = @{}
    $Params.Path= "HKCU:\Some\Path"
    $Params.Name = "Category"
    $Params.Value = "1"
    $Params.Type = "DWORD"
    }
    SetReg @Params
    Clear-Variable -Name Params
    
    • To test a value
    1
    2
    3
    4
    5
    6
    
    if( $Params.Value -eq 1 ){...}
    #For Example from the hash table above:
    If ($Params.Path -eq "HKCU:\Some\Path")
    {
    Write-Output "Path is correct
    }
    
    • To remove a key:
    1
    2
    3
    4
    5
    
    $Params.remove("Value")
    # For example:
    $Params.Remove("Path")
    # After this, $Params will still have the "Name", "Value", and "Type" properties - just not Path.
    # For more reading, see my references below
    
  2. Arrays:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    
    # For short arrays (less than 100 items)
    $Array = @()
    ForEach ($Item in $Collection)
    {
    $Array += $Item
    }
    
    # For more than 100 items:
    $Array = [System.Collections.ArrayList]@()
    ForEach ($Item in $Collection)
    {
    [void]$Array.Add("something")
    }
    $Array.clear()
    

References:

“Bye Bye Backtick: Natural Line Continuations in PowerShell “

“Hashtable as a collection of properties”

-----------------------------------------------------------
Spotted a mistake in this article? Why not suggest an edit!
Did you like the article? Donations are always welcome!
-----------------------------------------------------------

Comments