regex - Powershell 使用正则表达式替换文件

标签 regex file powershell replace gpo

下午好,我正在寻找修改首选项文件以使用稍后将由 gpo 部署的 powershell 脚本重置 chrome 中的默认缩放。

该策略是删除负责默认缩放的部分设置。手工完成时效果非常好。但是,使用此脚本时,我收到一条消息,指出首选项文件有误。

代码:

#Déclarations
$preferencePath = Join-Path $env:USERPROFILE                      'AppData\Local\Google\Chrome\User Data\Default\Preferences'
$newPreferencePath = Join-Path $env:USERPROFILE   'AppData\Local\Google\Chrome\User Data\Default\newpref.txt'
$regex = '("default_zoom_level":)[^\s]\d*.\d*(":)\d*.\d*(},)'

#Créer la version corrigé du fichier de préférence
Get-Content -path $preferencePath | % { $_ -Replace $regex , '' }  |  Out-    File $newPreferencePath

#Renomme les fichiers pour que le bon soit pris en compte
Rename-Item $preferencePath "PreferencesBAK"
Rename-Item $newPreferencePath "Preferences"

有人可以解释一下这段代码有什么问题吗?

谢谢!

最佳答案

请注意,Out-File 默认为 UTF-16LE 作为文件编码。您很可能需要将其写成 UTF-8(事先检查文件的编码):

... | Out-File -Encoding UTF8 $newPreferencePath

关于regex - Powershell 使用正则表达式替换文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42866995/

相关文章:

破折号的正则表达式问题

ruby - 正则表达式 : Evaluating part of the expression

file - 如何使用扫描仪从特定行号开始读取文件?

command-line - 自定义 powershell 提示正在清除 $lastexitcode

python - 如何正确使用正则表达式匹配来查找以下字符串中相关的前 3 个字母

javascript正则表达式: only english letters allowed

c - 读取十六进制 (Intel) C 中的扩展线性地址记录

php 函数在每个空行处分割数组?

iis - 如何使用 Powershell Web Admin Commandlet 更改 IIS 站点的应用程序池

powershell - 无法处理参数转换