Вы нашли ключ к решению своей проблемы, осознав, что ваша попытка извлечь x
из строки, такой как x = 123
, была ошибочной, поскольку вместо нее было извлечено x
(с завершающим пробелом).
Самое простое решение - просто урезать пробел из результата вашего оператора извлечения подстроки (обратите внимание на вызов .Trim()
):
# Extract everything before "=", then trim whitespace.
$vars += $line.substring(0,$line.IndexOf("=")).Trim()
Однако рассмотрите возможность оптимизации кода следующим образом:
$varsRegex = $sep = ''
# Use Get-Content to read the file as an *array of lines*.
Get-Content .\file.js | ForEach-Object {
# See if the line contains a variable assignment.
# Construct the regex so that the variable name is captured via
# a capture group, (\w+), excluding the surrounding whitespace (\s).
if ($_ -match '^\s*(\w+)\s*=') {
# Extract the variable name from the automatic $Matches variable.
# [1] represents the 1st (and here only) capture group.
$varName = $Matches[1]
# Build a list of variable names as a regex with alternation (|) and
# enclose each name in \b...\b to minimize false positives while replacing.
$varsRegex += $sep + '\b' + $varName + '\b'
$sep = '|'
}
# Replace the variable names with themselves prefixed with '$'
# Note how '$' must be escaped as '$$', because it has special meaning in
# the replacement operand; for instance, '$&' refers to what the regex
# matched in the input string (in this case: a variable name).
$line = $_ -replace $varsRegex, '$$$&'
# Output the modified line.
# Note: Use Write-Host only for printing directly to the screen.
$line
}