user3424878
user3424878

Reputation: 1

Using Backtick in Powershell: Unexpected token

In the code below, I am searching through an .ini file and trying to replace certain lines with updated configurations. I've seen it done for single lines, but I am trying to do it for multiple & different lines. When trying to use a backtick, I get Unexpected token '^' in expression or statement..

$layout_choice = "TEST"
$store_pics_by_date_choice = "TEST"
$orientation_choice = "TEST"
$copy_strips_choice = $backup_path
$copy_pics_choice = "no"
$copy_gifs_choice = $backup_path
$copy_videos_choice = "no"
$viewer_monitor_choice = "TEST"

get-content $file | ForEach-Object{$_ -replace "^layout =.+$", "layout = $layout_choice"` 
-replace "^store_pics_by_date =.+$", "store_pics_by_date = $store_pics_by_date_choice"
-replace "^orientation =.+$", "orientation = $orientation_choice"
-replace "^copy_strips =.+$", "copy_strips = $copy_strips_choice"
-replace "^copy_gifs =.+$", "copy_gifs = $copy_gifs_choice"
-replace "^copy_pics =.+$", "copy_pics = $copy_pics_choice"
-replace "^copy_videos =.+$", "copy_videos = $copy_videos_choice"
-replace "viewer_monitor =.+", "viewer_monitor = $viewer_monitor_choice"
-replace "viewer_monitor =.+", "viewer_monitor = $viewer_monitor_choice"} | Set-Content ($newfile)

Upvotes: 0

Views: 760

Answers (1)

Cookie Monster
Cookie Monster

Reputation: 1791

The backtick is simply an escape character. It works for line continuation by escaping the carriage return.

I would recommend looking for an alternative approach: A single line with all the code, breaking the code into multiple lines, or using another solution.

An example of an alternate solution. Slightly more code, but less delicate than using backticks:

#gather up your replace pairs in an array, loop through them
$line = "abcdefg"
$replaceHash = @{
    "^store_pics_by_date =.+$" = "store_pics_by_date = blah"
    "b" = "blah"
    "c" = "cat"
}
foreach($key in $replaceHash.keys)
{
    $line = $line -replace $key, $replaceHash[$key]
}

Using a backtick to continue on the next line is rarely if ever the correct answer - it creates delicate code. Even the answer from Frode F. failed, as there was a character after the first backtick.

Good luck!

Upvotes: 4

Related Questions