How to use operator '-replace' in PowerShell to replace strings of texts with special characters and replace successfully

后端 未结 3 2205
既然无缘
既然无缘 2020-12-18 17:59

I have a script where I am basically doing a find and replace on several strings of text. The first couple of strings work, but when I do the account keys, they do not. How

相关标签:
3条回答
  • 2020-12-18 18:38

    In your example, you prepended your source string with AccountKey= but not your target string.

    $c = $c -replace 'AccountKey=eKkij32jGEIYIEqAR5RjkKgf4OTiMO6SAyF68HsR/Zd/KXoKvSdjlUiiWyVV2+OUFOrVsd7jrzhldJPmfBBpQA==','AccountKey=DdOegAhDmLdsou6Ms6nPtP37bdw6EcXucuT47lf9kfClA6PjGTe3CfN+WVBJNWzqcQpWtZf10tgFhKrnN48lXA=='
    

    By not including that in the target string, the resulting string will remove AccountKey= instead of replacing it. You correctly do this with the AccountName= example, which seems to support this conclusion since it is not giving you any problems. If you really mean to have that prepended, then this may resolve your issue.

    0 讨论(0)
  • 2020-12-18 18:58

    '-replace' does a regex search and you have special characters in that last one (like +) So you might use the non-regex replace version like this:

    $c = $c.replace('AccountKey=eKkij32jGEIYIEqAR5RjkKgf4OTiMO6SAyF68HsR/Zd/KXoKvSdjlUiiWyVV2+OUFOrVsd7jrzhldJPmfBBpQA==','DdOegAhDmLdsou6Ms6nPtP37bdw6EcXucuT47lf9kfClA6PjGTe3CfN+WVBJNWzqcQpWtZf10tgFhKrnN48lXA==')
    
    0 讨论(0)
  • 2020-12-18 18:59

    If you've got V3, you can take advantage of auto-enumeration, the -Raw switch in Get-Content, and some of the new line contiunation syntax to simply it to this, using the string .replace() method instead of the -replace operator:

    (Get-ChildItem "[FILEPATH]" -recurse).FullName |
      Foreach-Object {
       (Get-Content $_ -Raw).
         Replace('abt7d9epp4','w2svuzf54f').
         Replace('AccountName=adtestnego','AccountName=zadtestnego').
         Replace('AccountKey=eKkij32jGEIYIEqAR5RjkKgf4OTiMO6SAyF68HsR/Zd/KXoKvSdjlUiiWyVV2+OUFOrVsd7jrzhldJPmfBBpQA==','AccountKey=DdOegAhDmLdsou6Ms6nPtP37bdw6EcXucuT47lf9kfClA6PjGTe3CfN+WVBJNWzqcQpWtZf10tgFhKrnN48lXA==') |
       Set-Content $_
      }
    

    Using the .replace() method uses literal strings for the replaced text argument (not regex), so you don't need to worry about escaping regex metacharacters in the text-to-replace argument.

    0 讨论(0)
提交回复
热议问题