在Powershell中使用Backtick:意外的令牌

时间:2014-03-16 05:06:03

标签: powershell backticks

在下面的代码中,我正在搜索.ini文件并尝试用更新的配置替换某些行。我已经看到它为单行做了,但我正在努力做到多个&不同的线条。在尝试使用backtick时,我会获得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)

1 个答案:

答案 0 :(得分:4)

反引号只是an escape character。它适用于escaping the carriage return的行继续。

我建议寻找替代方法:包含所有代码的单行,将代码分成多行或使用其他解决方案。

备用解决方案的示例。稍微多一些代码,但不如使用反引号那么精致:

#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]
}

使用反引号继续下一行很少是正确答案 - 它会创建精巧的代码。甚至Frode F.的回答都失败了,因为在第一次反击后有一个角色。

祝你好运!