Powershell 从 Jenkins groovy 变量中去除双引号

时间:2021-07-12 21:11:11

标签: powershell jenkins groovy escaping double-quotes

我正在尝试将数据从 Jenkins 机器中的 Json 机密文件复制到另一台服务器。 我的 Json 文件数据将如下所示。

{
  "Server:name": "abc",
  "application.version": "12"
}

詹金斯代码是


import groovy.json.JsonOutput
import groovy.json.JsonSlurper



node
{
    stage("Print")
    {
     
     
      
      def path = "C:\\xyz\\jsonData.json"      //remote file path where data has to be saved
     
    
       withCredentials([file(credentialsId: 'xyz', variable: 'abcFile')])
       {
        
                
                writeFile file: 'tempFile', text: readFile(abcFile)
                def readContent = readFile 'C:\\***\\tempFile'    // get file Jenkins from workspace

                def temp = readContent.replace("\"","\"\"")

                // tried all these
                def temp = readContent.replace("\"","\"\"\"")
                def temp = readContent.replace("\"","\\\"")    //causes error in powershell
                def temp = readContent.replace("\"","\\\\\"")
                def temp = readContent.replace("\"","\\\`\"")   // causes error in jenkins
                def temp = readContent.replace("\"","\'\"")

               
                def dataInjson = JsonOutput.toJson(readContent) // this one causes error in powersehll

                //println temp
               
                 def psSh = "powershell.exe "
                 psSh += "-NonInteractive -ExecutionPolicy Bypass "
                 psSh += "-Command \"\$ErrorActionPreference='Stop'; "
                 psSh += "invoke-command -computername ${xyz} -authentication NegotiateWithImplicitCredential -scriptblock { "
                 psSh += "import-module webadministration;"
                
                 
                 psSh += "if (!(Test-Path ${path})) {"
                 psSh += "\$folder = New-Item -ItemType Directory -Force -Path \"${path}\" };"

                 //copying file didn't work because of not having right credentials (tried creating sessions)
                 //psSh += "Copy-Item $abcFile -Destination ${path}; "

                 //tried all these but not working

                 //psSh += "Set-Content -Path \"${path}\" -Value \"${readContent}\" "
                // psSh += "\"${dataInjson}\" | ConvertTo-Json | Set-Content \"${path}\" "
                 psSh +=  " \$s = \\\"${temp}\\\" ; "
                 psSh += " \$s | Set-Content -Path \"${path}\" "

                 psSh += "};"
                 psSh += "EXIT \$global:LastExitCode\" "
                 bat psSh
           
        }
    }

}

但我能得到的唯一体面的输出是没有双引号。 Powershell 正在去除双引号。

{
  Server:name: abc,
  application.version: 12
}

如果没有双引号,我的代码将无法运行。任何人都可以帮助我吗?

0 个答案:

没有答案