Вы также можете поиграть с Regex:
$substring = if ($dirSourceFolder -match '\\?(BBG)\\?') { $matches[1] }
Или (с учетом регистра)
$substring = [regex]::Match($dirSourceFolder, '\\?(BBG)\\?').Groups[1].Value
Или так же, как указано выше, но теперь без учета регистра
$caseInsensitive = [System.Text.RegularExpressions.RegexOptions]::IgnoreCase
$substring = [regex]::Match($dirSourceFolder, '\\?(bbg)\\?', $caseInsensitive).Groups[1].Value
Все будут выводить
BBG
PS с использованием IndexOf
также будет работать, но требует больше усилий:
$index = $dirSourceFolder.IndexOf('\BBG\') #'# include the backslashes
if ($index -ge 0) {
$substring = $dirSourceFolder.Substring($index + 1, 'BBG'.Length)
}