从Windows批处理文件返回字符串 [英] Return a String from a Windows Batch file

查看:195
本文介绍了从Windows批处理文件返回字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在Jenkins管道中的GitHub上提交拉取请求时,我想找到目标分支.为此,我正在执行以下操作:

I want to find the target branch when a pull request is submitted on GitHub, in my Jenkins pipeline. To achieve this I am doing the following:

我正在从我的Jenkinsfile调用Windows批处理文件,该文件又调用了nodejs脚本.此脚本在内部调用GitHub API以获取目标分支,该分支将在Jenkinsfile中的某些变量上设置(下面给出的代码段): Jenkinsfile

I am invoking a windows batch file from my Jenkinsfile, which in turn invokes a nodejs script. This script internally invokes GitHub APIs to get the target branch which is to be set on some variable in Jenkinsfile(code snippet given below): Jenkinsfile

env.TARGET_BRANCH = bat "GetTargetBranchFromGit.bat ${env.BRANCH_NAME}"

批处理文件:

node getTargetBranchForPR.js %1

但是不幸的是,即使nodejs脚本获得了正确的值,变量env.TARGET_BRANCH也没有设置为目标分支.我实际上无法从批处理文件返回值.有人可以帮我吗?

But unfortunately, the variable env.TARGET_BRANCH is not getting set to the target branch even though the nodejs script gets the right value. I am in fact not able to return the value from the batch file. Could someone please help me here?

推荐答案

@npocmaka提及是正确的方法:

@npocmaka mention is the right way: How to do I get the output of a shell command executed using into a variable from Jenkinsfile (groovy)?

根据 Jenkins文档.

returnStdout(可选),如果选中,则任务的标准输出为 作为字符串作为步长值返回,而不是打印到 构建日志. (如果有标准错误,则仍会打印到 log.)您通常会希望在结果上调用.trim()来剥离一个 尾随换行符.

returnStdout (optional) If checked, standard output from the task is returned as the step value as a String, rather than being printed to the build log. (Standard error, if any, will still be printed to the log.) You will often want to call .trim() on the result to strip off a trailing newline.

所以您的代码应该看起来像

So your code should look like

env.TARGET_BRANCH = bat( script: "GetTargetBranchFromGit.bat ${env.BRANCH_NAME}",
                         returnStdout: true
).trim()

如果返回的结果超出预期,则可能需要对其进行解析.

If you get back more than expected you probably need to parse it.

这篇关于从Windows批处理文件返回字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆