使用powershell替换变量中的内容

使用powershell替换变量中的内容,powershell,macros,Powershell,Macros,所以我有一些代码保存在变量中,例如$powershell脚本中的宏。 我需要替换从Dim stm到Set al的整行,并将输出保存回变量$Macro中 entry_class = "enumerate.now" Dim stm As Object, fmt As Object, al As Object Set stm = CreateObject("System.IO.MemoryStream") Set fmt = CreateObject("System.Runtime.Serializ

所以我有一些代码保存在变量中,例如$powershell脚本中的宏。 我需要替换从Dim stmSet al的整行,并将输出保存回变量$Macro中

entry_class = "enumerate.now"

Dim stm As Object, fmt As Object, al As Object
Set stm = CreateObject("System.IO.MemoryStream")
Set fmt = CreateObject("System.Runtime.Serialization.Formatters.Binary.BinaryFormatter")
Set al = CreateObject("System.Collections.ArrayList")

Dim dec
dec = decodeHex(serialized_obj)
有人能告诉我怎么做吗? 我试着使用下面的,但它不工作

$macro = $macro -replace 'Dim stm As Object, fmt As Object, al As Object',' replaced code'
$macro = $macro -replace 'Set stm = CreateObject("System.IO.MemoryStream")',' replaced code'

Powershell默认情况下不理解换行符,括号和逗号应使用反勾号进行转义,替换时不需要正则表达式,因此必须执行以下操作:

$macro = 'entry_class = "enumerate.now" Dim stm As Object`, fmt As Object`, al As Object`nSet stm = CreateObject`("System.IO.MemoryStream"`)`nSet fmt = CreateObject`("System.Runtime.Serialization.Formatters.Binary.BinaryFormatter"`)`nSet al = CreateObject("System.Collections.ArrayList")`nDim dec`ndec = decodeHex`(serialized_obj`)'
$macro = $macro.replace("Dim stm As Object`, fmt As Object`, al As Object'", '"replaced code")
$macro = $macro.replace('Set stm = CreateObject`("System.IO.MemoryStream"`)',' replaced code')

嘿,谢谢你。。这很有帮助,我用注释(')替换了每行的开头,我的下一步是将以下数据[片段]添加到同一变量的特定行中。这里有什么指示吗?manifest=“But”不是powershell中的注释方法。它是VBScript中的注释方法。改为使用powershell中的#。如果有效,请单击答案中的灰色勾号接受答案。@AirSnow是新手,因此您可能不知道这一点,但习惯于单击✓ 在左边。在回答了新的要求后,不要扩展问题,而是发布一个新的问题。