PowerShell String – Java2Blog https://java2blog.com A blog on Java, Python and C++ programming languages Fri, 14 Jul 2023 07:23:19 +0000 en-US hourly 1 https://wordpress.org/?v=6.2.9 https://java2blog.com/wp-content/webpc-passthru.php?src=https://java2blog.com/wp-content/uploads/2022/09/cropped-ICON_LOGO_TRANSPARENT-32x32.png&nocache=1 PowerShell String – Java2Blog https://java2blog.com 32 32 PowerShell Remove Special Characters from String https://java2blog.com/powershell-remove-special-characters-from-string/?utm_source=rss&utm_medium=rss&utm_campaign=powershell-remove-special-characters-from-string https://java2blog.com/powershell-remove-special-characters-from-string/#respond Fri, 14 Jul 2023 07:23:19 +0000 https://java2blog.com/?p=24307 Using Regex.Replace() Method

Use the Regex.Replace() method to remove special characters from the specified string in PowerShell.

$str = "How #$%are ^&*you?@!"
$cleanedStr = [System.Text.RegularExpressions.Regex]::Replace($str, '[^\w\s]', '')

Write-Host @"
Original String: $str
Cleaned String: $cleanedStr
"@
Original String: How #$%are ^&*you?@!
Cleaned String: How are you

First, we declared a variable named $str and set its value to a string containing some special characters. Then, we used the Replace() method of the Regex class from the System.Text.RegularExpressions namespace to replace the special characters with an empty string.

The Replace() method took three arguments: the string ($str), the regular expression ('[^\w\s]'), and an empty string (''). The regular expression pattern matched any character that was not a word character (represented by \w) or whitespace character (denoted by \s). Here, ^ meant negation. Note that the replacement string was empty (''), removing matched special characters from the input string.

Next, we used the Write-Host cmdlet to display the original and cleaned string on the PowerShell console; the @"..."@ notation was used to write a multiline statement.

The word characters are [a-zA-Z0-9_].

Remember, if the System.Text.RegularExpressions namespace is not available in your system already, then use the Add-Type cmdlet as follows:

Add-Type -TypeDefinition @"
using System.Text.RegularExpressions;
"@

The Add-Type cmdlet dynamically adds an assembly or a .NET type to the PowerShell session. This cmdlet is needed if the required namespace is not available already.

Similarly, we use the Regex.Replace() method inside the ForEach loop to remove special characters from an array of strings in PowerShell.

$strArray = @("How #$%are ^&*you?@!", "Hello $&World")

$cleanedStr = foreach ($string in $strArray) {
        [System.Text.RegularExpressions.Regex]::Replace($string, '[^\w\s]', '')
}

Write-Host @"
Original Array of Strings: $strArray
Cleaned Array of Strings: $cleanedStr
"@
Original Array of Strings: How #$%are ^&*you?@! Hello $&World
Cleaned Array of Strings: How are you Hello World

In the above code fence, we created an array of strings using an array operator (@()) and assigned this array to the $strArray variable. Next, we used the ForEach loop to iterate over the $strArray. After that, we used the Regex.Replace() method in each iteration to remove special characters from the current string ($string). We have learned about the Regex.Replace() method with previous code examples; you can refer to that.

We assigned the cleaned strings to the $cleanedStr variable. Finally, we used the Write-Host cmdlet to print the original and updated array of strings on the console.

Using String.Replace() Method

Use the String.Replace() method to remove special characters from the specified string in PowerShell. This approach is useful when removing a particular special character(s).

$str = "How #$%are ^&*you?@!"
$specialChars = @('#','$','%','^','&','*','@','!')
echo "Original String: $str"

ForEach ($character in $specialChars) {
    $str = $str.Replace($character, '')
}

echo "Cleaned String: $str"
Original String: How #$%are ^&*you?@!
Cleaned String: How are you?

Again, we have $str containing special characters. Then, we used an array operator (@()) to create an array where each item was a special character we did not want in the output string. We stored this array in the $specialChars variable. Next, we used the echo command to display the $str on the PowerShell console.

After that, we used the ForEach loop (a.k.a. ForEach statement) to iterate over the $specialChars. We invoked the Replace() method of the String class in each iteration. It took two arguments, the current character and an empty string; here, we wanted to replace the matched current character with an empty string.

Notice that we updated the $str in every iteration. Finally, we used another echo to print the updated $str.

Similarly, we use the String.Replace() method inside the nested ForEach loop to remove special characters from an array of strings in PowerShell.

$strArray = @("How #$%are ^&*you?@!", "Hello $&World")
$specialChars = @('#','$','%','^','&','*','@','!')
echo "Original Array of Strings: $strArray"

ForEach ($index in 0..($strArray.Length - 1)) {
    ForEach ($character in $specialChars) {
        $strArray[$index] = $strArray[$index].Replace($character, '')
    }
}

echo "Cleaned Array of Strings: $strArray"
Original Array of Strings: How #$%are ^&*you?@! Hello $&World
Cleaned Array of Strings: How are you? Hello World

This example is comparable to the last one, which had an array of strings ($strArray), an array of special characters ($specialChars), and used the echo command to display the $strArray on PowerShell console.

Then, we used the nested ForEach loop. The outer loop was responsible for iterating over the $strArray; it used the $index variable to access each element in the $strArray. The inner loop was accountable for looping over the $specialChars array.

Inside the inner ForEach loop, we used the String.Replace() method to effectively replace the special character with an empty string to draw them out from the string. Lastly, we used another echo to display the updated array of strings.

Using -replace Operator

The -replace operator can be used with different variations of a regular expression to remove special characters from the given string or array of strings. Let’s learn them using the -replace operator.

Use the -replace operator with regex, specified via ranges, to remove special characters from the specified string in PowerShell.

$str = "How #$%are ^&*you?@!"
$cleanedStr = $str -replace '[^a-zA-Z0-9\s]', ''
Write-Host @"
Original String: $str
Cleaned String: $cleanedStr
"@
Original String: How #$%are ^&*you?@!
Cleaned String: How are you

Use the -replace operator with regex, written using ASCII characters, to remove special characters from the specified string in PowerShell.

$str = "How #$%are ^&*you?@!"
$cleanedStr = $str -replace '[^\x30-\x39\x41-\x5A\x61-\x7A\x20]+', ''
Write-Host @"
Original String: $str
Cleaned String: $cleanedStr
"@
Original String: How #$%are ^&*you?@!
Cleaned String: How are you

Use the -replace operator with regex, written using Unicode characters, to remove special characters from the specified string in PowerShell.

$str = "How #$%are ^&*you?@!"
$cleanedStr = $str -replace '[^\u0030-\u0039\u0041-\u005A\u0061-\u007A\u0020]+', ''
Write-Host @"
Original String: $str
Cleaned String: $cleanedStr
"@
Original String: How #$%are ^&*you?@!
Cleaned String: How are you

Use the -replace operator with regex specified using meta character (\W) to remove special characters from the specified string in PowerShell.

$str = "How #$%are ^&*you?@!"
$cleanedStr = $str -replace '[\W]', ''
Write-Host @"
Original String: $str
Cleaned String: $cleanedStr
"@
Original String: How #$%are ^&*you?@!
Cleaned String: Howareyou

Use the -replace operator with the regular expression written using Unicode categories to remove special characters from the specified string in PowerShell.

$str = "How #$%are ^&*you?@!"
$cleanedStr = $str -replace '[^\p{L}\p{Nd}]', ''
Write-Host @"
Original String: $str
Cleaned String: $cleanedStr
"@
Original String: How #$%are ^&*you?@!
Cleaned String: Howareyou

Alternatively, you can do as follows if you want to keep some special characters based on the project’s needs.

$str = "How #$%are ^&*you?@!"
$cleanedStr = $str -replace '[^\p{L}\p{Nd}/?/!/\s]', ''
Write-Host @"
Original String: $str
Cleaned String: $cleanedStr
"@
Original String: How #$%are ^&*you?@!
Cleaned String: How are you?!

The above examples in this section resembled one another and had a $str containing special characters. They all used the -replace operator with a regex to remove special characters by replacing them with an empty string. We assigned the cleaned string to the $cleanedStr variable.

Moreover, the above examples used the Write-Host cmdlet to print the primary and updated string on the PowerShell console. They only differed in specifying the regular expression. Let’s learn them below.

  1. [^a-zA-Z0-9\s] – This regex pattern matched all characters excluding the alphabets (a-z and A-Z), numbers (0-9), and a space character (\s).
  2. [^\x30-\x39\x41-\x5A\x61-\x7A\x20]+ – This regex pattern was written using ASCII characters; it matched all characters excluding the numbers ranging from 0 to 9 (\x30-\x39), upper case alphabets (\x41-\x5A), lower case alphabets (\x61-\x7A), and a space character (\x20). Here, + indicates the preceding group or character class should have at least one or multiple occurrences.
  3. [^\u0030-\u0039\u0041-\u005A\u0061-\u007A\u0020]+ – This regex was similar to the last one but specified using Unicode characters. It matched all characters excluding the numbers 0-9 (\u0030-\u0039), upper case and lower case letters (\u0041-\u005A and \u0061-\u007A), and a space character (\u0020).
  4. [\W] – Matched any non-word character. Remember the word characters are [a-zA-Z0-9_]. So, you must not use this regex if you don’t need underscore (_) in your output string.
  5. [^\p{L}\p{Nd}] – It matched all characters that were not the letters or digits. Here, \p{L} matched any Unicode letter characters, including the letters from different languages or scripts. While the \p{Nd} matched any Unicode decimal digit character.
  6. [^\p{L}\p{Nd}/?/!/\s] – This regex is similar to the above but used when we want to keep certain special characters. In this case, it kept the ?, !, and a space character (\s) in the output string.

In the above regular expressions, the ^ means the negation, while [] were used to define the character class or group.

The ASCII and Unicode characters in a regular expression are prefixed by \x and \u escape sequences. On the other hand, the \p escape sequence represents the Unicode character category.

Use the -replace operator to remove special characters from an array of strings in PowerShell.

$strArray = @("How #$%are ^&*you?@!", "Hello $&World")
$specialChars = '[^\w\s]+'

$cleanedStr = $strArray -replace $specialChars, ''

Write-Host @"
Original Array of Strings: $strArray
Cleaned Array of Strings: $cleanedStr
"@
Original Array of Strings: How #$%are ^&*you?@! Hello $&World
Cleaned Array of Strings: How are you Hello World

Using Char.IsLetterOrDigit Method

Use the Char.IsLetterOrDigit() method to remove special characters from the given string in PowerShell.

$str = "How #$%are ^&*you?@!"
$cleanedStr = ""

ForEach ($char in $str.ToCharArray()) {
    if ([Char]::IsLetterOrDigit($char)) {
        $cleanedStr += $char
    }
}

Write-Host @"
Original String: $str
Cleaned String: $cleanedStr
"@
Original String: How #$%are ^&*you?@!
Cleaned String: Howareyou

We created two string variables; one had a string value with special characters ($str), and the other was initialized with an empty string ($cleanedStr). Then, we used the ForEach loop to iterate over the character array, which we created using the ToCharArray() method as $str.ToCharArray().

Inside the loop, we used the if statement with the IsLetterOrDigit() method to check if the current character represented by $char was a letter or digit. If it was, we appended the $cleanedStr with $char using the += operator to omit the special characters effectively. Finally, we used the Write-Host cmdlet to print the original and updated string on the console.

To keep space characters in your output string, use the Char.IsWhiteSpace() method as demonstrated below.

$str = "How #$%are ^&*you?@!"
$cleanedStr = ""

ForEach ($char in $str.ToCharArray()) {
    if ([Char]::IsLetterOrDigit($char) -or [Char]::IsWhiteSpace($char)) {
        $cleanedStr += $char
    }
}

Write-Host @"
Original String: $str
Cleaned String: $cleanedStr
"@
Original String: How #$%are ^&*you?@!
Cleaned String: How are you

See the following code example to remove special characters from an array of strings using PowerShell.

$strArray = @("How #$%are ^&*you?@!", "Hello $&World")
$cleanedStrArray = @()

foreach ($string in $strArray) {
    $cleanedStr = ""

    foreach ($char in $string.ToCharArray()) {
        if ([Char]::IsLetterOrDigit($char) -or [Char]::IsWhiteSpace($char)) {
            $cleanedStr += $char
        }
    }

    $cleanedStrArray += $cleanedStr
}

Write-Host @"
Original Array of Strings: $strArray
Cleaned Array of Strings: $cleanedStrArray
"@
Original Array of Strings: How #$%are ^&*you?@! Hello $&World
Cleaned Array of Strings: How are you Hello World

This example is similar to the last ones for removing special characters from an array of strings. The outer loop iterated over the array of strings ($strArray), while the inner loop iterated over the character array for the current string, which was converted as $string.ToCharArray().

We used the if statement inside the inner loop with the IsLetterOrDigit() and IsWhiteSpace() methods. These methods took the current character ($char) and determined if it was the letter, digit, or whitespace. If it was, then concatenated with the $cleanedStr variable using the += operator.

Once the inner loop was finished, the $cleanedStr was append to the $cleanedStrArray using the += operator in the outer loop. Finally, we used Write-Host to display the original and updated array of strings on the PowerShell console.

Using String.Join() Method

Use the String.Join() method to remove special characters from the input string in PowerShell.

$str = "How #$%are ^&*you?@!"

$cleanedStr = [String]::Join('', 
                     ($str.ToCharArray() |
                      Where-Object { 
                         $_ -match '\w|\s' 
                      }))

Write-Host @"
Original String: $str
Cleaned String: $cleanedStr
"@
Original String: How #$%are ^&*you?@!
Cleaned String: How are you

We used the String.Join() method, which took two arguments. The first was the empty string. While for the second argument, we converted the string to the character array using the ToCharArray() and piped it to the Where-Object cmdlet.

This cmdlet iterated over the character array, matched the current character ($_) with the \w|\s pattern using the -match operator, and joined them using an empty string (the first argument). In the \w|\s pattern, the \w matched the word character, while \s matched a space character. Finally, we used the Write-Host cmdlet to display the results on the console.

Use the String.Join() method to remove special characters from an array of strings in PowerShell.

$strArray = @("How #$%are ^&*you?@!", "Hello $&World")
$cleanedStrArray = @()

ForEach ($string in $strArray) {
    $cleanedStrArray += [String]::Join('',
                   ($string.ToCharArray() |
                    Where-Object { 
                        $_ -match '\w|\s'
                    }))
}

Write-Host @"
Original String: $strArray
Cleaned String: $cleanedStrArray
"@
Original String: How #$%are ^&*you?@! Hello $&World
Cleaned String: How are you Hello World

This code snippet is similar to the last one, but we used ForEach to loop over the $strArray and stored the cleaned strings in the $cleanedStr array.

That’s all about PowerShell remove special characters from String.

]]>
https://java2blog.com/powershell-remove-special-characters-from-string/feed/ 0
PowerShell Trim String After Character https://java2blog.com/powershell-trim-string-after-character/?utm_source=rss&utm_medium=rss&utm_campaign=powershell-trim-string-after-character https://java2blog.com/powershell-trim-string-after-character/#respond Thu, 29 Jun 2023 18:14:26 +0000 https://java2blog.com/?p=23943 Using Split()Method

Use the Split() method to trim the string after the first occurrence of the specified character in PowerShell.

$string = "Hi! Welcome to Java2Blog! Let's learn."
$newString = ($string.Split("!"))[0]
Write-Output $newString
Hi

We declared and initialized the $string variable with "Hi! Welcome to Java2Blog! Let's learn." value. Next, we chained the Split() method with the $string variable to split the $string into an array based on the provided separator. In the above code, the Split() method took the "!" character as an argument and split the $string wherever it found the ! character.

The Split() method returned an array of substrings having three elements; Hi, Welcome to Java2Blog, and Let's learn.. As we were only interested in the first element, we used the index operator by giving 0 as an index ([0]) to grab the Hi element and store it in the $newString variable. Finally, we used the Write-Host cmdlet to print the $newString value on the PowerShell console.

Using IndexOf() and Substring() Methods

Use the IndexOf() and Substring() methods to trim the string after the first occurrence of the given character in PowerShell.

$string = "Hi! Welcome to Java2Blog! Let's learn."
$newString = $string.Substring(0, $string.IndexOf("!"))
Write-Output $newString
Hi

Again, we set the value of the $string variable with "Hi! Welcome to Java2Blog! Let's learn." value. We chained the Substring() method with the $string variable this time. The Substring() method took two arguments: the starting index from where we want to extract the string and the ending index. Remember, the character living at the ending index would not be included in the extracted string.

As we wanted to grab the string from the first character of the $string, we mentioned 0 as starting index. To specify the ending index, we used the IndexOf() method, passed "!" as an argument to it to get the index of its first occurrence in the $string variable.

The Substring() method returned Hi, which we stored in the $newString variable to use further with the Write-Host cmdlet to print its value on the PowerShell console.

Using LastIndexOf() and Substring() Methods

Use the LastIndexOf() and Substring() methods to trim the string after the last occurrence of the specified character in PowerShell.

$string = "Hi! Welcome to Java2Blog! Let's learn."
$newString = $string.Substring(0, $string.LastIndexOf("!"))
Write-Output $newString
Hi! Welcome to Java2Blog

This code block is similar to the previous one, but we trimmed the $string based on the last occurrence of the specified character (!) in $string. Note that the LastIndexOf() method took one argument, which was "!" and returned the index of the last occurrence of ! in $string.

Using Replace(), Substring(), & IndexOf() Methods

Use Replace(), Substring(), and IndexOf() methods together to trim string after the first occurrence of the given character in PowerShell.

$string = "Hi! Welcome to Java2Blog! Let's learn."
$substring = $string.Substring($string.IndexOf("!"))
$newString = $string.Replace($substring, "")
Write-Output $newString
Hi

In previous examples, we have already learned about the Substring() and IndexOf() methods. This time, we added another method known as Replace(); this method replaces the first argument with the second one in the string. The point is what to replace and how? Let’s understand it.

After setting the value of the $string variable, we used the Substring() with the IndexOf() method to get the ! Welcome to Java2Blog! Let's learn. substring from $string, which we stored in the $substring variable.

After that, we used the Replace() method, providing $substring as the first argument and an empty string ("") as the second argument. The Replace() method replaced the $substring with an empty string and returned Hi, which we stored in the $newString variable and printed on the console using the Write-Host cmdlet.

Using IndexOf() and Remove() Methods

Use IndexOf() and Remove() methods to trim string after the first occurrence of the given character in PowerShell.

$string = "Hi! Welcome to Java2Blog! Let's learn."
$index = $string.IndexOf("!")
$newString = $string.Remove($index)
Write-Output $newString
Hi

This time we used the IndexOf() method to get the index of the ! character’s first occurrence in the $stringand stored it in the $index variable. Next, we used the Remove() method to remove all characters from the specified $index onwards. As a result, we got Hithat we stored in the $newString variable to print it on the console using the Write-Host cmdlet.

Using Regular Expression with replace operator

Use regular expression with replace operator to trim string after the first occurrence of the given character in PowerShell.

$string = "Hi! Welcome to Java2Blog! Let's learn."
$newString = $string -replace "!.*", ""
Write-Output $newString
Hi

For this example, we used the -replace operator to replace the string that matches the given regular expression with an empty string. In the above example, the "!.*" regex means ! and any character after it, any number of times. We stored the returned string by the -replace operator in the $newString variable and printed it on the PowerShell console using the Write-Host cmdlet.

That’s all about PowerShell trim String after character.

]]>
https://java2blog.com/powershell-trim-string-after-character/feed/ 0
PowerShell Split String by Multiple Delimiters https://java2blog.com/powershell-split-string-by-multiple-delimiters/?utm_source=rss&utm_medium=rss&utm_campaign=powershell-split-string-by-multiple-delimiters https://java2blog.com/powershell-split-string-by-multiple-delimiters/#respond Wed, 07 Jun 2023 17:35:24 +0000 https://java2blog.com/?p=24160 Using -split Operator with Regular Expression

Use the -split operator with a regular expression to split string by multiple delimiters in PowerShell.

$string = "one,two;three four"
$delimiters = "[,; ]+"
$parts = $string -split $delimiters
$parts
one
two
three
four

First, a string variable named $string and an array variable called $delimiters is defined. Then, the $string is assigned with "one,two;three four", while $delimiters is set with "[,; ]+".

After that, the -split operator is used on the string variable named $string, with the $delimiters variable passed as an argument. The resulting output is an array containing the individual parts of the string split by the specified delimiters.

In case you want to remove entries, you can use where-object cmdlet.

$string = "one,two;three four"
$delimiters = "[,; ]+"
$parts = $string -split $delimiters | Where-Object { $_ -ne "" }
$parts
one
two
three
four

In the above example, we used the Where-Object cmdlet to select all substrings of the given array excluding empty elements (empty substrings). How to exclude empty elements? For that, we used a condition as {$_ -ne ""} to determine if the current element ($_) is not equal to (-ne) an empty string (""). Finally, the resulting array was stored in the $parts variable.

Using Regex.Split() Method

Use the Regex.Split() method to split string by multiple delimiters in PowerShell.

$string = "one,two;three four"
$delimiters = "[,; ]+"
$parts = [Regex]::Split($string, $delimiters)
$parts
one
two
three
four

First, the PowerShell variable $string is assigned a with string, i.e., "one,two;three four" and the delimiters "[,; ]+"/are assigned to the $delimiters variable.

After that, to split the string, the Regex.Split() method is used in this solution. Finally, the $string and the $delimiters variables are given as parameters to the Split() method. The resulting output also being an array containing the individual parts of the string.

Using String.Split() Method

Use the String.Split() method to split string by multiple delimiters in PowerShell.

$string = "one,two;three four"
$delimiters = @(",", ";", " ")
$parts = $string.Split($delimiters, [System.StringSplitOptions]::RemoveEmptyEntries)
$parts
one
two
three
four

The code defines a string variable named $string and an array variable called $delimiters. The string contains a sequence of words separated by commas, semicolons, and spaces, i.e., "one,two;three four". The array includes the delimiters that should be used to split the string, i.e.,@(",", ";", " "). Then the Split() method is called on the string variable $string, passing the $delimiters array as the delimiter parameter.

The RemoveEmptyEntries option removes any empty entries resulting from consecutive delimiters or delimiters at the beginning or end of the string. The resulting array is stored in the $parts variable and then displayed.

Using System.Text.RegularExpressions.Regex Class

Use the System.Text.RegularExpressions.Regex class to split strings by multiple delimiters in PowerShell.

$string = "one,two;three four"
$delimiters = "[,; ]+"/
$regex = [System.Text.RegularExpressions.Regex]::new($delimiters)
$parts = $regex.Split($string)
$parts
one
two
three
four

First, the PowerShell variable $string is assigned a with string, i.e., "one,two;three four". After that the delimiters "[,; ]+"/are assigned to the $delimiters variable. Then, an instance of the Regex class is created. The $delimiters variable is passed as an argument to the new() function of the System.Text.RegularExpressions.Regex class.

Then the Regex instance is used with the Split() method to split the string. The resulting output also being an array containing the individual parts of the string. Note that all the methods discussed above generated the same outcome. You may choose any of the methods as per your requirement and preference.

That’s all about powershell split string by multiple delimiters.

]]>
https://java2blog.com/powershell-split-string-by-multiple-delimiters/feed/ 0
Concatenate String and Variable in PowerShell https://java2blog.com/concatenate-string-and-variable-powershell/?utm_source=rss&utm_medium=rss&utm_campaign=concatenate-string-and-variable-powershell https://java2blog.com/concatenate-string-and-variable-powershell/#respond Sun, 28 May 2023 11:39:37 +0000 https://java2blog.com/?p=23953 Using Concatenation Operators

Use concatenation operator represented by + to concatenate String and variable in PowerShell.

$variable = "together"
$concatenatedStr = "Let's learn " + $variable
Write-Host $concatenatedStr
Let's learn together

The + is the most basic concatenation operator; we used it to concatenate the "Let's learn "string with the $variable and stored the new string in the $concatenatedStr variable, which we further used with Write-Host cmdlet to display on the PowerShell console.

Don’t forget to enclose the "Let's learn " + $variable expression within the parentheses (()) if you are not storing the concatenated string in a variable but joining them while using Write-Host cmdlet; see the following example.

$variable = "together"
Write-Host ("Let's learn " + $variable)
Let's learn together

Here is what will happen if you will not enclose it within ():

$variable = "together"
Write-Host "Let's learn " + $variable
Let's learn  + together

Use the concatenation operator represented by += to concatenate String and variable in PowerShell.

$string1 = "together."
$string2 = "Let's learn "
$string2 += $string1
Write-Host $string2
Let's learn together.

The += operator is used when we want to perform concatenation and assignment in one step. In the above example, $string1 was concatenated with $string2, and the new string was assigned to $string2.

Be careful when using + and += concatenation operators because order matters greatly. See the following example as a demonstration.

$string1 = "together."
$string2 = "Let's learn "
Write-Host ($string1 + "Are you going ")
$string1 += $string2
Write-Host $string2
together.Are you going
Let's learn

We concatenated the "Are you going " string with the $string1 variable, which resulted in together.Are you going as an output. The correct concatenation order was "Are you going " + $string1. Similarly, we concatenated the $string2 with $string1 using the += operator and stored a new string in $string1, but we printed the $string2 containing the Let's learn value.

Using String Interpolation with $()

Use string interpolation with $() to concatenate String and variable in PowerShell.

$variable = "together"
Write-Host "Let's learn $($variable)."
Let's learn together.

Concatenate string and a variable without using $() in PowerShell.

$variable = "together"
Write-Host "Let's learn $variable."
Let's learn together.

This approach is more reader-friendly and easy to comprehend than using concatenation operators.

Using Format Operator

Use the format operator (-f) to concatenate String and variable in PowerShell.

$course1 = "Java"
$course2 = "PowerShell"
$course3 = "Python"
Write-Host ("Let's learn {0}, {1}, and {2}." -f $course1, $course2, $course3)
Let's learn Java, PowerShell, and Python.

We used the -f operator in the above example to format the specified string. The format string is "Let's learn {0}, {1}, and {2}." and $course1, $course2, and $course are the three arguments that we passed in. The format specifiers are the numbers enclosed within the {}, follow the format of {index:format} and correspond to the arguments’ indices being passed in. These indices control the order in which the arguments should be displayed on the PowerShell console.

Let’s see another example below.

$course1 = "Java"
$course2 = "PowerShell"
$course3 = "Python"
Write-Host ("The average of {0}, {1}, and {2} courses is {3:n2}%." -f $course1, $course2, $course3, 83.5269)
The average of Java, PowerShell, and Python courses is 83.53%.

In {3:n2}, the 3 is the index, while n2 means the number of decimal places (the number of digits after the floating-point). You can find more valid format strings here.

Using -join Operator

Use the -join operator to concatenate the string with variable(s) in PowerShell.

$course1 = "Java"
$course2 = "PowerShell"
$course3 = "Python"
Write-Host ("Available Courses:",$course1, $course2, $course3, "R" -join " ")
Available Courses: Java PowerShell Python R

The -join operator joined all the given strings with variables separated by a single white space. Note that you can use any separator that you want.

Using join() Method

Use join() method to concatenate string with variable(s) in PowerShell.

$course1 = "Java"
$course2 = "PowerShell"
$course3 = "Python"
Write-Host ([string]::join(" ", "Available Courses:",$course1, $course2, $course3, "R"))
Available Courses: Java PowerShell Python R

Here, we used the join() method of the string class; it does the same as the -join operator, which joins all the strings and variables separated by the specified delimiter. In the join() method, the first argument is the delimiter; the remaining is the strings and variables that should be concatenated.

Using Concat() Method

Use Concat() method to concatenate string with variable(s) in PowerShell.

$course1 = "Java"
$course2 = "PowerShell"
$course3 = "Python"
Write-Host ([string]::Concat("Available Courses: ",$course1," ", $course2," ", $course3, " R"))
Available Courses: Java PowerShell Python R

The Concat() method also belongs to the string class and joins all the given strings and variables, but we must be careful about the separator.

Using StringBuilder Class

Use the StringBuilder class to concatenate the string with variable(s) in PowerShell.

$variable = "How are you?"
$stringBuilder = New-Object System.Text.StringBuilder
$stringBuilder.Append("Hello! ")
$stringBuilder.Append($variable)
Write-Host ($stringBuilder.ToString())
Hello! How are you?
Capacity MaxCapacity Length
-------- ----------- ------
      16  2147483647      7
      32  2147483647     19

Here, we used the New-Object cmdlet to instantiate the StringBuilder class to access its Append() method to concatenate the string with a variable. Finally, we used the ToString() method to convert it into a string and printed it on the PowerShell console using the Write-Host cmdlet. It also displayed other details about the concatenated string that you can see in the above output.

Using Join-String Cmdlet

Use the Join-String cmdlet to concatenate a collection of strings with variable(s) in PowerShell.

$names = "How", "are", "you?"
$concatenatedStr = $names + "What's going on?" | Join-String -Separator " "
Write-Host $concatenatedStr
How are you? What's going on?

The Join-String cmdlet is used to combine or concatenate a string collection into a single string separated by a delimiter specified using the -Separator parameter. We piped the collection of strings ($names) to the Join-String cmdlet. If you want to concatenate a string value with a collection of strings, then you can use the + operator as we did in the above example.

So, we have multiple ways to concatenate string(s) with variable(s), but choosing the one best suits the project requirements is most important.

That’s all about how to concatenate String and Variable in PowerShell.

]]>
https://java2blog.com/concatenate-string-and-variable-powershell/feed/ 0
PowerShell Add Quotes to String https://java2blog.com/powershell-add-quotes-to-string/?utm_source=rss&utm_medium=rss&utm_campaign=powershell-add-quotes-to-string https://java2blog.com/powershell-add-quotes-to-string/#respond Sat, 27 May 2023 11:00:59 +0000 https://java2blog.com/?p=24009 Using Backtick Characters

Use backtick characters to add double quotes to string in PowerShell.

$string = "Hello `"World`""
$string
Hello "World"

Backtick character is escape character in PowerShell. Here, it is used to escape double quotes in the String.

Use backtick characters to add single quotes to string in PowerShell.

$string = "Hello `'World`'"
$string
Hello 'World'

Using String Concatenation Operator

Use string concatenation operator (+) to add double quotes to string in PowerShell.

$string = "Hello " + """World"""
$string
Hello "World"

Use string concatenation operator (+) to add single quotes to string in PowerShell.

$string = "Hello " + "'World'"
$string
Hello 'World'

Using Format Operator

Use format operator to add double quotes to string in PowerShell.

$name = "John Williamson"
$string = "Hi! This is ""{0}""." -f $name
$string
Hi! This is "John Williamson".

Use format operator to add single quotes to string in PowerShell.

$name = "John Williamson"
$string = "Hi! This is '{0}'." -f $name
$string
Hi! This is 'John Williamson'.

We used the format operator (-f) to format strings by inserting values into the placeholders within the string. This operator works using the format string, which contains placeholders indicated by curly braces ({}). These placeholders can have format specifiers illustrating how the value must be formatted.

Now, the point is which value will be inserted into the placeholders? For that, the -f operator is used. The values to be inserted into the specified placeholders are mentioned as arguments to the -f operator. In the above example, {0} is the placeholder while $name is the argument to the -f operator. Don’t forget to enclose the {0} within quotes; refer to the above examples to find out how to have single or double quotes.

Using Replace() Method

Use the Replace() method to add double quotes to the string in PowerShell.

$string = "Hello World"
$string = $string.Replace("World", """World""")
$string
Hello "World"

Use the Replace() method to add single quotes to a string in PowerShell.

$string = "Hello World"
$string = $string.Replace("World", "'World'")
$string
Hello 'World'

The Replace() method took two arguments. The first is the string we want to replace, and the second is the replacement. Don’t forget that Replace() does a case-sensitive replacement.

Using -replace Operator

Use the -replace operator to add double quotes to the string in PowerShell.

$string = "Hello World"
$string = $string -replace "World", """World"""
$string
Hello "World"

Use the -replace operator to add single quotes to a string in PowerShell.

$string = "Hello World"
$string = $string -replace "World", "'World'"
$string
Hello 'World'

The -replace method is similar to the Replace() method, replacing the old string with a new string, but it does case-insensitive replacement, which is the same as the -ireplace operator does. Use the Replace() method or the -creplace operator for case-sensitive replacement.

Using New-Object Cmdlet

Use the New-Object cmdlet to create a string object having double quotes in PowerShell.

$string = New-Object String("Hello `"World`"")
$string
Hello "World"

Use the New-Object cmdlet to create a string object having single quotes in PowerShell.

$string = New-Object String("Hello`'World`'")
$string
Hello 'World'

We used the New-Object cmdlet to create an instance of the String class. Then, the String() constructor was used to initialize the $string with a value containing the quotes, whether double or single.

Using ForEach Cmdlet to add double quotes to each element of array

Use the ForEach cmdlet to add double quotes to each array element where each element is a string value.

$stationary = @("pencil", "notebook", "paper")
$quotedStationary = $stationary | ForEach-Object { """$_""" }
$quotedStationary
"pencil"
"notebook"
"paper"

Use the ForEach cmdlet to add single quotes to each array element where each element is a string value.

$stationary = @("pencil", "notebook", "paper")
$quotedStationary = $stationary | ForEach-Object { "'$_'"}
$quotedStationary
'pencil'
'notebook'
'paper'

In the above examples, we used the array operator (@()) to create an array having string values and stored it in the $stationary variable. Then, we piped $stationary to the ForEach-Object cmdlet to iterate over $stationary. In each iteration, we enclosed the current element, represented by $_, within quotes.

That’s all about PowerShell add quotes to String.

]]>
https://java2blog.com/powershell-add-quotes-to-string/feed/ 0
PowerShell Check if List Contains String https://java2blog.com/powershell-check-if-list-contains-string/?utm_source=rss&utm_medium=rss&utm_campaign=powershell-check-if-list-contains-string https://java2blog.com/powershell-check-if-list-contains-string/#respond Tue, 25 Apr 2023 15:54:21 +0000 https://java2blog.com/?p=23858 Using -Contains Operator

Use the -Contains operator to check if the list contains the specified string in PowerShell.

$list = @("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")
$searchString = "Wednesday"
$list -Contains $searchString
True

In the above example, we used an array operator represented with @() to create a list, which we stored in the $list variable. Next, we initialized the $searchString variable with a string value we wanted to search in the $list.

Finally, we used the -Contains operator to determine if the $list contains the $searchString. If it is, we will get True as an output; otherwise, False. Note that the -Contains operator is case-insensitive, meaning it would treat "Wednesday", "wednesday", and "WeDnesDay" same.

In PowerShell, the -Contains and -iContains operators produce the same results because both perform case-insensitive matches. Here i denotes the insensitivity. Let’s see them in the following example.

$list = @("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")
echo "Results using '-Contains':"
$list -Contains "Wednesday"
$list -Contains "wednesday"
$list -Contains "WeDnesDay"
echo "Results using '-iContains':"
$list -iContains "Wednesday"
$list -iContains "wednesday"
$list -iContains "WeDnesDay"
Results using '-Contains':
True
True
True
Results using '-iContains':
True
True
True

See, we got True for all the matches. Now, think of a use case where we must perform a case-sensitive match. In that case, we would use the -cContains operator; see the following example.

$list = @("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")
$list -cContains "Wednesday"
$list -cContains "wednesday"
$list -cContains "WeDnesDay"
True
False
False

We only got True for the first match because -cContains returned False for the "wednesday" and `"WeDnesDay" search strings.

In PowerShell, prefix the -Contains operator with i and c ( as -iContains and -cContains) to perform the case-insensitive and case-sensitive match. Remember, by default, the -Contains produces the same output as the -iContains operator.

Let’s make this code more reader-friendly by adding an if-else block to display meaningful messages. See the following example.

$list = @("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")
$searchString = "Wednesday"
$result = $list -cContains $searchString
if($result){
   Write-Host "'$searchString' is found."
}else{
   Write-Host "'$searchString' is not found."
}
'Wednesday' is found.

The above output seems more reader-friendly and easy to comprehend. To do this, we stored the Boolean value in the $result variable, which was returned by the $list -cContains $searchString expression.

After that, we used the if statement and passed the $result variable to it. If the value of $result was True, the if block would be executed; otherwise, the else block would be. Finally, we used the Write-Host cmdlet in the if and else blocks to display customized and meaningful messages on the PowerShell console.

Using Contains() Method

Use the Contains() method to assess if the list contains the specified string in PowerShell.

$list = @("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")
$searchString = "Wednesday"
$result = $list.Contains($searchString)
if($result){
   Write-Host "'$searchString' is found."
}else{
   Write-Host "'$searchString' is not found."
}
'Wednesday' is found.

This code example is similar to the last code snippet, but we used the Contains() method this time. The Contains() method took the $searchString as a parameter and returned a Boolean value which we stored in the $result variable. The Boolean value can be True or False where True represents match is found while False denotes match is not found.

To make it easier to understand, we passed the $result to the if statement, which would only be executed if the value of $result would be True; otherwise, the Write-Host cmdlet within the else block would be executed.

The Contains() method performs a case-sensitive match by default, and we do not have a direct method to do a case-insensitive match using the Contains() method. However, we can use iContains (learned in the previous section), -ilike, and -like operators. We will learn -like and -ilike later in this article.

Using -like Operator

Use the -like operator to check if the list contains a string in PowerShell.

$fruitList = @("orange", "melon", "cherry", "banana")
$searchPattern = "*an*"
$matchedStrings = $fruitList | Where-Object {$_ -like $searchPattern}
if ($matchedStrings.Count -gt 0) {
    Write-Host "List contains '$matchedStrings'."
} else {
    Write-Host "List does not contain '$matchedStrings'."
}
List contains 'orange banana'.

First, we created a list of fruits and stored it in the $fruitList variable. Next, we initialized the $searchPattern variable with the "*an*" pattern. This pattern means the matched string must contain an exactly while the * wildcard character shows any number of characters. We used * before and after the an, so the matched string will have an n number of characters before and after the an. Remember, the number of characters before and after the an may or may not be the same.

After that, we piped the $fruitList to the Where-Object cmdlet, which iterated over each item of the $fruitList and performed partial matching using the -like operator. The -like operator finds multiple occurrences of an item by performing partial matching, while wildcard patterns are used for flexible search. Here, $_ represents the current item in PowerShell.

We stored the matched strings in the $matchedStrings variable, which we passed to the if statement. In the if statement, we used the Count property of the $matchedStrings variable and checked if that is greater than 0 using the -gt operator (greater than the operator). If it is, we execute the Write-Host cmdlet from the if block to display a message saying the match is found; otherwise, the Write-Host from the else block will be executed, stating the match is not found.

Worth noting point is that the -like operator does a case-insensitive match by default, which is the same as the -ilike operator. Using -like and -ilike operators, we get the same output for the patterns "*an*", "*AN*" and "*aN*". On the other hand, -clike does a case-sensitive match. See the following example to understand the difference.

$fruitList = @("orange", "melon", "cherry", "banana")
echo "Match using -like Operator:"
$fruitList | Where-Object {$_ -like "*an*"}
$fruitList | Where-Object {$_ -like "*AN*"}
$fruitList | Where-Object {$_ -like "*aN*"}
echo "Match using -ilike Operator:"
$fruitList | Where-Object {$_ -ilike "*an*"}
$fruitList | Where-Object {$_ -ilike "*AN*"}
$fruitList | Where-Object {$_ -ilike "*aN*"}
echo "Match using -clike Operator:"
$fruitList | Where-Object {$_ -clike "*an*"}
$fruitList | Where-Object {$_ -clike "*AN*"}
$fruitList | Where-Object {$_ -clike "*aN*"}
Match using -like Operator:
orange
banana
orange
banana
orange
banana
Match using -ilike Operator:
orange
banana
orange
banana
orange
banana
Match using -clike Operator:
orange
banana

For the -like and -ilike operators, we got two matched values (orange and banana) thrice because the values were matched for "*an*", "*AN*" and "*aN*" patterns. On the other hand, the -clike returned two matched values (orange and banana) once because the match was found for the "*an*" pattern only.

Using -in Operator

Use the -in operator to check if the list contains the specified string in PowerShell.

$fruitList = @("orange", "melon", "cherry", "banana")
$searchString = "orange"
$match = $searchString -in $fruitList
if ($match) {
    Write-Host "List contains '$searchString'."
} else {
    Write-Host "List does not contain '$searchString'."
}
List contains 'orange'.

This time we used the -in operator to determine if the $searchString is in the $fruitList. If it is, we will get True; otherwise, False. We stored this returned Boolean value in $match to pass it to the if statement. Now, the if statement will be executed if the value of the $match variable is True.

Note that the -in operator performs case-insensitive match, meaning if we initialize the $searchString with "Orange", it would still execute the if block and return the expected output. See the following example.

$fruitList = @("orange", "melon", "cherry", "banana")
$searchString = "Orange"
$match = $searchString -in $fruitList
if ($match) {
    Write-Host "List contains '$searchString'."
} else {
    Write-Host "List does not contain '$searchString'."
}
List contains 'Orange'.

The -in operator will not work with the search patterns such as "*an*".

Using IndexOf()Method

Use the IndexOf() method to determine if the list contains a string in PowerShell.

$list = @("Mehvish", "Tania", "Divya")
$searchString = "Divya"
$index = $list.IndexOf($searchString)
if ($index -ge 0) {
    Write-Host "'$searchString' found in list at index $index."
} else {
    Write-Host "List does not contain '$searchString'."
}
'Divya' found in list at index 2.

For this example, we created a list having first names, and we stored this list in the $list variable. Next, we defined the $searchString variable and set its value to "Divya". After that, we chained the IndexOf() method with $list. This method took $searchString as a parameter and returned the index if the string match was found.

We stored the returned index in the $index variable. Then, the $index was passed to the if statement, where we used the -ge operator to determine if the value of the $index variable is greater than or equal to 0. If it is, we used Write-Host to print the matched string with the corresponding index; otherwise, the else block would be executed.

Note that the IndexOf() performs a case-sensitive match, which means we will get -1 if we specify "divya" instead of "Divya" as a search string. See the following example.

$list = @("Mehvish", "Tania", "Divya")
$searchString = "divya"
$index = $list.IndexOf($searchString)
if ($index -ge 0) {
    Write-Host "'$searchString' found in list at index $index."
} else {
    Write-Host "List does not contain '$searchString'."
}
List does not contain 'divya'.

See, the match was not found this time. So the else block was executed as we got a -1 index.

Using Where() Method with a Filter

Use the Where() method with a filter to check if the list contains a string in PowerShell.

$list = @("Mehvish", "Tania", "Divya")
$searchString = "Divya"
$list.Where({$_ -eq $searchString})

<pre title=-‘OUTPUT’>
Divya

For the above code snippet, we used the Where() method with a filter to determine if the current list element matched the value of $searchString. Suppose it matched; the $list.Where({$_ -eq $searchString}) returned it; otherwise, we would get nothing on the PowerShell Console.

What if we change the value of $searchString from "Divya" to "divya". See what happens below.

$list = @("Mehvish", "Tania", "Divya")
$searchString = "divya"
$list.Where({$_ -eq $searchString})
Divya

We still got the same output. Why? Because the -eq operator within the Where() method performs the case-insensitive comparison.

Using -match Operator

Use the -match operator to determine if the list contains a string in PowerShell.

$list = @("apple", "banana", "cherry")
$searchString = "apple"
if ([string]$list -match $searchString) {
    Write-Host "List contains '$searchString'."
} else {
    Write-Host "List does not contain '$searchString'."
}
List contains 'apple'.

This example is similar to the previous ones, but we used the -match operator this time. To use this operator, we had to convert the $list to string, or we can say we had to typecast the $list to string as [string]$list. If the converted string ([string]$list) matches the searchString, then the Write-Host from the if block will be executed. Otherwise, the Write-Host from the else block will display the specified message on the PowerShell console.

Using ForEach() Method

Use the ForEach() method to check if the list contains a string in PowerShell.

$list = @("apple", "banana", "cherry")
$searchString = "apple"
$matched = $false
$list.ForEach({
    if ($_ -eq $searchString) { 
        $matched=$true
    }
})
if ($matched) { 
    Write-Host "List contains '$searchString'."
} else {
    Write-Host "List does not contain '$searchString'."
}
List contains 'apple'.

After setting the values of the $list and $searchString variables, we initialized the $matched with the $false value; this value will be used to represent whether the match was found or not. Next, we used the ForEach() method to iterate over all the list items. Finally, we used the if statement with the -eq operator for each list item to check if the current list item (represented by $_) equals the $searchString. If it is, then set the value of the $matched variable to $true.

Finally, we passed the $matched to another if statement outside the ForEach() method. If the value of $matched was True, then the if block will be executed; otherwise, the else block will be.

This code will produce the same output for the "apple" and "AppLe" search strings because the -eq operator inside the ForEach() method performs the case-insensitive comparison.

Using All Approaches with List Created Using List()

Use all of the above approaches with list created using List() method in PowerShell.

#Create a list
$list = New-Object System.Collections.Generic.List[string]

#Add list items
$list.Add("apple")
$list.Add("orange")
$list.Add("grapes")

#returns True if string found
$list -Contains "grapes"

#returns True if string found
$list.Contains("grapes")

#returns matched string if found
$list | Where-Object {$_ -like "gra*"}

#returns True if string found
"grapes" -in $list

#returns index of the string,
#if it is greater than or equal to 0,
#then string is found
$list.IndexOf("grapes")

#returns matched string if found
$list.Where({$_ -eq "grapes"})

#prints "string found", if it is found
ForEach($item in $list){
    if ($item -eq "grapes") { 
        Write-Host "string found."
    }
}

#returns True if string found
[string]$list -match "grapes"
True
True
grapes
True
2
grapes
string found.
True

Using All Approaches with List Created Using ArrayList()

Use all of the above approaches with list created using ArrayList() method in PowerShell.

#Create a list
$list = New-Object System.Collections.ArrayList

#Add list items
$list.Add("apple") #returns 0 index
$list.Add("orange") #returns 1 index
$list.Add("grapes") #returns 2 index

#returns True if string found
$list -Contains "grapes"

#returns True if string found
$list.Contains("grapes")

#returns matched string if found
$list | Where-Object {$_ -like "gra*"}

#returns True if string found
"grapes" -in $list

#returns index of the string,
#if it is greater than or equal to 0,
#then string is found
$list.IndexOf("grapes")

#returns matched string if found
$list.Where({$_ -eq "grapes"})

#prints "string found", if it is found
ForEach($item in $list){
    if ($item -eq "grapes") { 
        Write-Host "string found."
    }
}

#returns True if string found
[string]$list -match "grapes"
0
1
2
True
True
grapes
True
2
grapes
string found.
True
]]>
https://java2blog.com/powershell-check-if-list-contains-string/feed/ 0
PowerShell Split and Get Last Value https://java2blog.com/powershell-split-and-get-last-value/?utm_source=rss&utm_medium=rss&utm_campaign=powershell-split-and-get-last-value https://java2blog.com/powershell-split-and-get-last-value/#respond Mon, 24 Apr 2023 16:53:41 +0000 https://java2blog.com/?p=23496 Using Split() Method

Use the Split() method with the indexing operator to split the specified string and get the last value in PowerShell.

$string = "This is a sample string"
$lastElement = ($string.Split(" "))[-1]
Write-Host "The last element of '$string' is '$lastElement'"
The last element of 'This is a sample string' is 'string'

First, we defined a $string variable and initialized it with a string value, as shown in the above code fence. Next, we used the Split() method, passed whitespace as a delimiter, and chained this method with $string to split it wherever it found a whitespace.

We enclosed the output returned by the Split() method in parentheses and used the indexing operator ([]) to get the last value. In PowerShell, we can use -1 to get the last index or element from an array. Finally, we used the Write-Host cmdlet to print the customized output showing the complete string and its last element wrapped with single quotes.

Use the Split() method with the Select-Object cmdlet to split the given string and get the last value in PowerShell.

$string = "This is a sample string"
$lastElement = ($string.Split(" ")) | Select-Object -Last 1
Write-Host "The last element of '$string' is '$lastElement'"
The last element of 'This is a sample string' is 'string'

This code is similar to the previous one, but we piped the output of the Split() method to the Select-Object cmdlet.

This cmdlet is used to choose specified properties of the object or a set of objects. We can also use this cmdlet to select the given number of objects, unique objects, or objects in a particular position in the specified array. Additionally, we can use -First, -Last, -Skip, -Unique, and -Index parameters to select objects from a collection such as an array.

We used the Select-Object cmdlet with the -Last parameter whose value was set to 1 to get the last element of the $string. Finally, we used the Write-Host cmdlet to display the customized results on the PowerShell console.

We can also specify the 2, 3, …, or n number of words preceded by the -Last parameter to get them as one string element.

Using -Split Operator

Use the -Split operator with the indexing operator to split the specified string and get the last value in PowerShell.

$string = "This is a sample string"
$lastElement = ($string -Split " ")[-1]
Write-Host "The last element of '$string' is '$lastElement'"
The last element of 'This is a sample string' is 'string'

Use the -Split operator with the Select-Object cmdlet to split the specified string and get the last value in PowerShell.

$string = "This is a sample string"
$lastElement = ($string -Split " ") | Select-Object -Last 1
Write-Host "The last element of '$string' is '$lastElement'"
The last element of 'This is a sample string' is 'string'

Above, both code snippets are the same as the examples in the previous section where we used the Split() method. The only difference is that we used the -Split operator this time, which did the same as the Split() method, but there are some differences and similarities that you can find [here](Please add ‘PowerShell Split Path into Array’ article’s link, it is from MS11).

Until now, we split a simple string and retrieved the last element from it; suppose we have a path as a string value and are told to retrieve the last value from it. Here, the last value can be a file or folder name. See the following section to explore it.

Using System.IO.Path Class

To split the specified path & directory and get the last value in PowerShell:

  • Store the path in a variable.
  • Use the GetDirectoryName() method to retrieve the directory from the path and store it in a variable.
  • Use the Split() method with the indexing operator twice to get the last element from the path and directory created in the first and second steps.
  • Use the Write-Host cmdlet to display customized results on the PowerShell console.
$path = "C:\Users\Mehvish\Desktop\Samples\House_Prediction_Using_Two_File_Dataset.pdf"
$directory = [System.IO.Path]::GetDirectoryName($path)
$pathLastElement = ($path.Split("\"))[-1]
$directoryLastElement = ($directory.Split("\"))[-1]
Write-Host "Path: $path"
Write-Host "Last element of the path:'$pathLastElement'"
Write-Host "Directory: $directory"
Write-Host "Last element of the directory:'$directoryLastElement'"
Path: C:\Users\Mehvish\Desktop\Samples\House_Prediction_Using_Two_File_Dataset.pdf
Last element of the path:'House_Prediction_Using_Two_File_Dataset.pdf'
Directory: C:\Users\Mehvish\Desktop\Samples
Last element of the directory:'Samples'

After storing the path in the $path variable, we used the GetDirectoryName() method of the Path class. First, we passed the $path as a parameter to get its directory, which we stored in the $directory variable. Next, we chained the Split() method with $path and $directory variables separately and passed \ as a delimiter to split them based on the \ character; however, the indexing operator with -1 value was used to get the last value for both of them. Finally, we used the Write-Host cmdlet to print the customized messages to make the output easier to understand.

Use the System.IO.Path class with the Select-Object cmdlet to split the specified path & directory and get the last value in PowerShell.

$path = "C:\Users\Mehvish\Desktop\Samples\House_Prediction_Using_Two_File_Dataset.pdf"
$directory = [System.IO.Path]::GetDirectoryName($path)
$pathLastElement = ($path.Split("\")) | Select-Object -Last 1
$directoryLastElement = ($directory.Split("\"))[-1] | Select-Object -Last 1
Write-Host "Path: $path"
Write-Host "Last element of the path:'$pathLastElement'"
Write-Host "Directory: $directory"
Write-Host "Last element of the directory:'$directoryLastElement'"
Path: C:\Users\Mehvish\Desktop\Samples\House_Prediction_Using_Two_File_Dataset.pdf
Last element of the path:'House_Prediction_Using_Two_File_Dataset.pdf'
Directory: C:\Users\Mehvish\Desktop\Samples
Last element of the directory:'Samples'

This example is similar to the previous one, but we used the Select-Object with the -Last parameter to get the last value. Note that we have already learned the [Select-Object while using Split() method](add link of the first section here).

Until now, we used different approaches to split the simple string, but what if we need to split a particular string which is the value of an object’s property? Don’t worry; let’s dive into the following section to learn it.

Using Split(), -Split for an Object’s Property

Use the Split() method and the -Split operator with the indexing operator to split the value of the object’s property and get its last element in PowerShell.

$studentObject = New-Object PSObject -Property @{
    studentFirstName = "Mehvish"
    studentLastName = "Ashiq"
    studentAge = 30
    Address = "123 Main St, sometown, UK"
}
$lastElementUsingSplitOperator = ($studentObject.Address -Split ' ')[-1]
$lastElementUsingSplitFunction = ($studentObject.Address.Split(' '))[-1]
Write-Host "Last element using -Split operator with indexing operator: '$lastElementUsingSplitOperator'"
Write-Host "Last element using Split() method with indexing operator: '$lastElementUsingSplitFunction'"
Last element using -Split operator with indexing operator: 'UK'
Last element using Split() method with indexing operator: 'UK'

For the above example, we used the New-Object cmdlet to create an object and store it in the $studentObject variable. The -Property parameter was used to set a new object’s property values and call methods. This object had key=value pairs; each pair was separated by a new line (line break) where key was the property name (such as $studentAge) and value was the property value (such as 30).

The key can also be methods, and the value can be method arguments.

We derived our new object from the PSOObject class because it helps to specify those properties that don’t exist on an object. So, the New-Object cmdlet specified properties to the object as NoteProperty.

After creating the object, we used dot notation (.) as $studentObject.Address to retrieve the value of the Address property. Then, we used the -Split operator with an indexing operator to get the last value that we stored in the $lastElementUsingSplitOperator variable. Similarly, we retrieved the last element using the Split() method and stored the value in the $lastElementUsingSplitFunction variable. Finally, we used the Write-Host cmdlet to display customized results on the console.

Use the Split() method and the -Split operator with the Select-Object cmdlet to split the value of the object’s property and get its last element in PowerShell.

$studentObject = New-Object PSObject -Property @{
    studentFirstName = "Mehvish"
    studentLastName = "Ashiq"
    studentAge = 30
    Address = "123 Main St, sometown, UK"
}
$lastElementUsingSplitOperator = ($studentObject.Address -Split ' ') | Select-Object -Last 1
$lastElementUsingSplitFunction = ($studentObject.Address.Split(' ')) | Select-Object -Last 1
Write-Host "Last element using -Split operator with Select-Object cmdlet: '$lastElementUsingSplitOperator'"
Write-Host "Last element using Split() method with Select-Object cmdlet: '$lastElementUsingSplitFunction'"
Last element using -Split operator with Select-Object cmdlet: 'UK'
Last element using Split() method with Select-Object cmdlet: 'UK'

This example is the same as the last one, but we used the Select-Object cmdlet with the -Last parameter to get the last element.

That’s all about PowerShell split and get last value.

]]>
https://java2blog.com/powershell-split-and-get-last-value/feed/ 0
Run String as Command in PowerShell https://java2blog.com/run-string-as-command-powershell/?utm_source=rss&utm_medium=rss&utm_campaign=run-string-as-command-powershell https://java2blog.com/run-string-as-command-powershell/#respond Sat, 22 Apr 2023 13:34:39 +0000 https://java2blog.com/?p=23861 Using Invoke-Expression Cmdlet

Use the Invoke-Expression cmdlet to run a string as a command in PowerShell. Invoke-Expression cmdlet evaluates string as command and return the result of string expression.
Here is simple exampple:

$command = "notepad.exe"
Invoke-Expression $command

This will open new notepad window.

Here is more complicated example.

$command = "Get-Process | Sort-Object -Property CPU -Descending | Select-Object -First 5"
Invoke-Expression -Command $command
Handles  NPM(K)    PM(K)      WS(K)     CPU(s)      Id   SI ProcessName
-------  ------    -----      -----     ------     --  --   -----------
   1456     205   329656     294348     670.89   6328   3   Grammarly.Desktop
   2564      67   326064     354484     503.28  12276   3   chrome
    524      24   776508     798760     444.05   1248   3   chrome
    644      17     7196      21308     400.55  12324   3   SynTPEnh
   1420      41   315816     308592     394.67   8188   3   chrome

The Invoke-Expression evaluates a string as a PowerShell expression, allowing you to execute any valid PowerShell command or script. For example, the above code is functioning in the following manner:

  • Get-Process: Retrieves a list of currently running processes on the system.
  • Sort-Object -Property CPU -Descending: Sorts the list of processes by the CPU property (which represents the CPU usage for each process) in descending order.
  • Select-Object -First 5: Select the first five items from the sorted list of processes.

After defining the command in the $command variable, we use the Invoke-Expression cmdlet to execute the command stored in the $command. The output of this code is a list of the top 5 processes with the highest CPU usage, sorted in descending order.

Using & Operator

Use the & operator to run a string as a command in PowerShell

$command = "notepad.exe"
& $command

The call operator & invokes a command as if it were a command name or function. This allows you to execute a command stored in a variable or run a command that is not in the current scope or path. For example, the above code is functioning in the following manner:

  • A string variable $command is initialized with an executable file, in this case, notepad.exe.
  • After that, the call operator (&) was used to execute the command stored in $command. This tells PowerShell to run the executable specified in the $command. In this case, it has launched the Notepad application.

Using Double Quotes ("")

Use the Double Quotes to run a string as a command in PowerShell.

$filename = "File1.txt"
$command = "Get-Process | Out-File -FilePath "E:\$filename""
Invoke-Expression -Command $command
Handles  NPM(K)    PM(K)      WS(K)     CPU(s)     Id  SI ProcessName                     
-------  ------    -----      -----     ------     --  -- -----------                     
    507      20     8804      16768             13328   0 AppHelperCap                   
    773      43    36872      48716       9.02   1212   3 ApplicationFrameHost           
    318      17     3700      14256              3388   0 armsvc                         
    315      16   105520      19700       0.34   3760   0 audiodg                         
    555      24   409364     392232     505.98   1248   3 chrome                         
    399      32    24192      47240     120.28   2476   3 chrome                         
    255      16    18168      35456       0.23   5224   3 chrome                         
    260      17    43572      65600      18.72   7476   3 chrome                         
   1335      33   244596     226076     508.02   8188   3 chrome                         
   ...       ...  ...        ...        ...      ...    ...
   ...       ...  ...        ...        ...      ...    ...
   ...       ...  ...        ...        ...      ...    ...

The above code is functioning in the following manner:

  • A string variable $filename is created, set to File1.txt.
  • The $command variable is then set to a string that contains a PowerShell command to get a list of running processes and write them to a file with the specified filename on the E: drive.
  • The Out-File cmdlet is used to write the output of the Get-Process cmdlet to a file with the specified filename. The backticks (`) escape the double quotes within the string.
  • The Invoke-Expression cmdlet is then used to execute the command stored in the $command variable.
  • The output of this code is a file named File1.txt located in the E: drive, which contains a list of running processes when the command was executed.

Using [scriptblock]::Create() Method

Use the [scriptblock]::Create() method to run a string as a command in PowerShell.

$commandString = "Get-ChildItem C:\TEST1"
$commandBlock = [scriptblock]::Create($commandString)
& $commandBlock
Mode                 LastWriteTime         Length   Name
----                 -------------         ------   ----
d-----         2/21/2023  11:26 PM                  FolderA
d-----         2/21/2023  11:27 PM                  FolderB
-a----         2/21/2023   9:32 PM              0   File1.txt
-a----         2/21/2023   9:32 PM              0   File2.txt

The above code is functioning in the following manner:

  • The first line of the code block creates a variable called $commandString and sets its value to "Get-ChildItem C:\TEST1".
  • After that, the second line creates a script block object called $commandBlock using the static Create() method of the ScriptBlock class. The Create method takes a string as input and returns a script block object that can be executed as a PowerShell command. In this case, the string passed to Create() is the value of the $commandString variable, which is "Get-ChildItem C:\TEST1". This creates a script block representing the Get-ChildItem command with the argument C:\TEST1.
  • Finally, in the last line of code, the call operator (&) was used to execute the script block stored in the $commandBlock variable. The call operator tells PowerShell to treat the script block as a command and run it. The script block, in turn, executes the Get-ChildItem command with the argument C:\TEST1, which retrieves information about the files and folders located in the C:\TEST1 directory.

Considering the above solutions, running string as a command in PowerShell is a powerful tool that can help you automate complex tasks and perform advanced system administration tasks. Furthermore, following best practices, you can use this feature securely and efficiently to manage your Windows systems.

That’s all about how to run string as command in PowerShell.

]]>
https://java2blog.com/run-string-as-command-powershell/feed/ 0
PowerShell Check if String Starts with https://java2blog.com/powershell-check-if-string-starts-with/?utm_source=rss&utm_medium=rss&utm_campaign=powershell-check-if-string-starts-with https://java2blog.com/powershell-check-if-string-starts-with/#respond Sat, 22 Apr 2023 11:27:46 +0000 https://java2blog.com/?p=23539 Using StartsWith() Method

Use the StartsWith() to check if string starts with another string in PowerShell.

$text = "Hello, world!"
$prefix = "Hello"
$startsWithPrefix = $text.StartsWith($prefix)
Write-Host "Text: $text"
Write-Host "Prefix: $prefix"
Write-Host "Does '$text' start with '$prefix'? $startsWithPrefix"
Text: Hello, world!
Prefix: Hello
Does 'Hello, world!' start with 'Hello'? True

In the above code, a string variable named $text is initialized with the value of Hello, world! and another string variable called $prefix is created with the value of Hello. After that, using the StartsWith() method, the function checks if $text starts with the $prefix, assigning the result (either true or false) to $startsWithPrefix. Finally, it displays the result using the Write-Host cmdlet.

If you want to ignore case, pass another parameter CurrentCultureIgnoreCase to StartsWith() method.

$text = "Hello, world!"
$prefix = "hello"
$startsWithPrefix = $text.StartsWith($prefix,'CurrentCultureIgnoreCase')
Write-Host "Text: $text"
Write-Host "Prefix: $prefix"
Write-Host "Does '$text' start with '$prefix'? $startsWithPrefix"

Text: Hello, world!
Prefix: hello
Does 'Hello, world!' start with 'hello'? True

Using -like Operator

Use the -like operator to determine if string starts with another string in PowerShell.

$string = "Hello World"
if ($string -like "H*") {
    Write-Host "String starts with H"
}
String starts with H

The -like operator compares a string with a pattern and returns a Boolean value of $true if the string matches the pattern; otherwise, $false.

The -like operator in the above code determines whether the $string starts with the letter H (remember that the * is a wildcard that matches zero or more random characters). The code utilizes the Write-Host cmdlet to output the message String starts with H if $string begins with H. The code does nothing if the $string does not start with the letter H.

Assume you have a situation where you are only required to check if the specified string starts with an alphabet, number or neither. In that case, you can use the -match operator as follows.

Using -match Operator

Use the -match operator to check if the specified string starts with an alphabet, digit or neither of them in PowerShell.

$string = "123Hello World"
if ($string -match "^\d"){
    Write-Host "String starts with a digit" 
}
elseif ($string -match "^[A-Za-z]"){
    Write-Host "String starts with an alphabet" 
}
else{
    Write-Host "String neither starts with a number nor an alphabet"
}
String starts with a digit

The above code snippet creates a string variable like the previous two code fences; it then uses the -match operator with regular expression patterns to assess if the given string begins with a digit or an alphabet. If both cases are not satisfied, then it executes the else block saying the specified string neither starts with a digit nor an alphabet.

However, the ^\d and ^[A-Za-z] expressions were used to check if the $string starts with a digit or an alphabet at the beginning of the string. In the ^\d expression, the character d is used to match any digit (the same as [0-9]), while the symbol ^ denotes the beginning of the string.

Similarly, in the ^[A-Za-z] expression, [A-Za-z] matches any upper/lower case alphabet, while ^ represents the start of the string. Finally, we used the Write-Host cmdlet to print a customized message based on whether $string start with a digit, an alphabet, or neither.

Using IndexOf() Method

Use the IndexOf() method to determine if string starts with another string in PowerShell.

$string = "Hello World"
if ($string.IndexOf("H") -eq 0){
    Write-Host "String starts with H"
}
String starts with H

This function gives us the position of the first instance of a specified character or string in a given string. For example, if the returned index is 0, it indicates that the string begins with the specified value.

The above code snippet uses the IndexOf() method to find the index of the first occurrence of the character H in the $string. So, for example, if the string’s first character stored in the variable $string is H (i.e., if its index is 0), the code will utilize the Write-Host cmdlet to display the message on the console.

Using Substring() Method

Use the Substring() method to check if string starts with another string in PowerShell.

$string = "Hello World"
if ($string.Substring(0,1) -eq "H") {
    Write-Host "String starts with H"
}
String starts with H

The above code uses the Substring() method to extract the first character of the $string, starting at index 0 and including the 1 character. If the extracted character is equal to the "H", the code uses the Write-Host cmdlet to print out the message String starts with H.

Considering the above solutions, checking if a string starts with a specific set of characters in PowerShell is a simple task that can be accomplished using the Startwith() method, -like operator, match operator, IndexOf(), and Substring() method. Furthermore, understanding these tools allows you to easily manipulate and extract substrings within larger strings to perform various tasks.

That’s all about PowerShell check if String starts with.

]]>
https://java2blog.com/powershell-check-if-string-starts-with/feed/ 0