Certainly! Below is a PowerShell script that accomplishes what you're asking for. This script defines a function MoveSubstringToBeginning which takes a string as input, finds the substring between the first occurrence of "(" and the first occurrence of ")", moves that substring to the beginning of the string, and then returns the modified string.
function MoveSubstringToBeginning {
param (
[string]$inputString
)
# Find the indices of the first "(" and ")"
$openParenIndex = $inputString.IndexOf('(')
$closeParenIndex = $inputString.IndexOf(')')
if ($openParenIndex -ge 0 -and $closeParenIndex -ge 0 -and $openParenIndex -lt $closeParenIndex) {
# Extract the substring between "(" and ")"
$substring = $inputString.Substring($openParenIndex + 1, $closeParenIndex - $openParenIndex - 1)
# Remove the original substring from the input string
$remainingString = $inputString.Remove($openParenIndex, $closeParenIndex - $openParenIndex + 1)
# Construct the new string with the substring moved to the beginning
$newString = "$($substring)$(if ($remainingString) { $remainingString })"
return $newString
} else {
# If there are no "(" and ")" or they are not properly placed, return the original string
return $inputString
}
}
# Example usage:
$testString = "Hello (world) PowerShell"
$result = MoveSubstringToBeginning $testString
Write-Output $result
Explanation:
- Function Definition: The function
MoveSubstringToBeginning is defined to take a single parameter, $inputString.
- Index Finding: It finds the indices of the first occurrence of "(" and ")" using the
IndexOf method.
- Validation: It checks if both "(" and ")" are present and if "(" comes before ")".
- Substring Extraction: It extracts the substring between "(" and ")" using the
Substring method.
- String Manipulation: It removes the original substring from the input string using the
Remove method.
- String Construction: It constructs the new string by placing the extracted substring at the beginning and appending the remaining part of the original string.
- Return: It returns the new string. If the conditions are not met (e.g., no "(" or ")", or "(" comes after ")"), it returns the original string unchanged.
Example:
For the input string "Hello (world) PowerShell", the output will be "worldHello PowerShell".