【问题标题】:Powershell replace in file using regexPowershell使用正则表达式替换文件
【发布时间】:2017-08-09 13:41:22
【问题描述】:

下午好,我正在寻找修改首选项文件以使用稍后将由 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"

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

谢谢!

【问题讨论】:

    标签: regex file powershell replace gpo


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      原来问题出在替换功能上。此外,编码是ASCII。以下是感兴趣的人的工作代码:

      #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'
      $oldPrefFile = Join-Path $env:USERPROFILE 'AppData\Local\Google\Chrome\User Data\Default\PreferencesBAK'
      $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 -Encoding ASCII $newPreferencePath
      
      #Renomme les fichiers pour que le bon soit pris en compte
      if (Test-Path $oldPrefFile) {
         Remove-Item $oldPrefFile
      }
      Rename-Item $preferencePath "PreferencesBAK"
      Rename-Item $newPreferencePath "Preferences"
      

      【讨论】:

      • 我看到你还没有这样做,只是想让你知道你可以点击灰色的复选标记来接受你自己的答案,这样它在社区中会更好地脱颖而出。跨度>
      猜你喜欢
      • 2012-06-20
      • 2016-02-13
      • 2012-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-12
      • 2021-10-13
      • 1970-01-01
      相关资源
      最近更新 更多