Windows服务器Jenkins管道删除SUBST虚拟驱动器报错‘Drive already SUBSTed’
Jenkins SUBST卸载虚拟驱动器报错解决
问题场景
为规避Windows路径260字符限制,在Jenkins管道中使用SUBST命令创建虚拟驱动器可成功执行,但删除该驱动器时却报错Drive already SUBSTed,导致流水线执行失败。
最小复现脚本
node() { stage('Create drive') { echo "Already existing virtual drives" sh """ subst """ Character c = 'U' echo "Create drive ${c}:" sh """ subst ${c}: . """ echo "Remove drive ${c}:" sh """ subst ${c}: /d """ } }
运行日志
[Pipeline] Start of Pipeline [Pipeline] node Running on **** in E:/Jenkins/workspace/temp_testing_path_lenghty [Pipeline] { [Pipeline] stage [Pipeline] { (Create disk) [Pipeline] echo Already existing disks [Pipeline] sh + subst J:\: => E:\Jenkins\workspace\temp_testing_path_lenghty Y:\: => E:\Jenkins\workspace\temp_testing_path_lenghty [Pipeline] echo Create disks U: [Pipeline] sh + subst U: . [Pipeline] echo Remove disks U: [Pipeline] sh + subst U: /d Drive already SUBSTed [Pipeline] } [Pipeline] // stage [Pipeline] } [Pipeline] // node [Pipeline] End of Pipeline ERROR: script returned exit code 1 Finished: FAILURE
问题原因
Jenkins的sh步骤在Windows环境下执行多行命令(用"""包裹)时,会在变量替换后自动添加多余空格,导致subst ${c}: /d被解析为subst U: /d(盘符冒号后多了一个空格)。系统无法识别带空格的参数格式,误以为你要再次将U盘映射到名为/d的路径,而U盘已经处于映射状态,因此抛出Drive already SUBSTed错误。
解决方法
方法1:使用单行命令格式
将卸载命令改为单行,避免多行解析带来的空格问题:
echo "Remove drive ${c}:" sh "subst ${c}: /d"
方法2:清理变量空格
如果必须使用多行命令格式,对盘符变量做trim处理,消除隐形空格:
echo "Remove drive ${c}:" sh """ subst ${c.trim()}:/d """
方法3:先检查盘符再卸载
添加存在性检查,避免重复卸载操作触发报错:
echo "Remove drive ${c}:" sh """ if exist ${c}:\\ (subst ${c}: /d) """
内容的提问来源于stack exchange,提问作者ManquatLo
相关产品推荐
相关产品推荐

