>我有powershell函数,它返回解决方案中项目的路径数组。
function GetPathToSfProj($rootPath, $solutionName){
$retPath = Get-Content "$($rootPath)$($solutionName)" |
Select-String 'Project((.*.sfproj)' |
ForEach-Object {
$projectParts = $_ -Split '[,=]' | ForEach-Object { $_.Trim('[ "{}]') };
New-Object PSObject -Property @{
File = $projectParts[2];
}
}
return $retPath.File;
}
我尝试从批处理文件执行它并使用 msBuild 构建包。
FOR /F "delims=" %%i IN ('"powershell . ".GetSfProjPath.ps1 GetPathToSfProj -rootPath "%ProjectLocationPath%" -solutionName "%SolutionName%""; "') DO (
SET VAL=%%i
call %MSBuildPath%MSBuild.exe %VAL% /t:package /p:Configuration=Debug
)
但是在循环变量总是空
如果我单独测试电源外壳函数,它会返回正确的结果。所以批量问题。
我强烈建议不要在不需要的情况下混合脚本语言。只需参数化 PowerShell 脚本,并将函数的输出通过管道传输到调用MSBuild.exe
的ForEach-Object
循环:
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true]
[string]$ProjectLocationPath,
[Parameter(Mandatory=$true]
[string]$SolutionName
)
function GetPathToSfProj($rootPath, $solutionName) {
Get-Content "${rootPath}${solutionName}" |
Select-String 'Project((.*.sfproj)' |
ForEach-Object { ($_ -split '[,=]')[2].Trim('[ "{}]') }
}
GetPathToSfProj -rootPath $ProjectLocationPath -solutionName $SolutionName | ForEach-Object {
& "${env:MSBuildPath}MSBuild.exe" $_ '/t:package' '/p:Configuration=Debug'
}
据我所知。 这是许多人遇到的一个简单的问题。
<小时 />延迟扩展
确保脚本在循环之前的某处包含setlocal enableDelayedExpansion
。
@echo off
setlocal enableDelayedexpansion
rem script.
然后,要确保批量正确更改%val%
,请将%val%
更改为!val!
%MSBuildPath%MSBuild.exe !VAL! /t:package /p:Configuration=Debug
或者这个不需要延迟扩展的解决方案
%MSBuildPath%MSBuild.exe %%i /t:package /p:Configuration=Debug
或者最好的一个:
"%MSBuildPath%MSBuild.exe" "%%~i" /t:package /p:Configuration=Debug
~
的意思是去报价。
启动应用程序
CALL
仅在调用子例程或其他批处理脚本时使用,只需将其删除即可。
最终脚本
FOR /F "delims=" %%i IN ('"powershell . ".GetSfProjPath.ps1 GetPathToSfProj -rootPath "%ProjectLocationPath%" -solutionName "%SolutionName%""; "') DO (
"%MSBuildPath%MSBuild.exe" "%%~i" /t:package /p:Configuration=Debug
)