如何在PowerShell脚本中执行“dotnet build”

3
当我在powershell终端中直接运行以下代码时,它完美地工作:
dotnet build ./MySolution.sln --configuration Release

然而,当我将这行代码放入PowerShell脚本中,并从相同目录中运行时,我遇到了以下错误:
MSBUILD : error MSB1009: Project file does not exist.

我尝试按照如何使用&运算符从PowerShell调用MSBuild?中的一个答案中提到的不同方式传递参数。现在我不知所措了。我需要在PowerShell脚本中怎么做才能使它工作?


1
调用语法没有问题。错误信息表明,尽管您在问题中所说的是正确的,但您正在从另一个目录运行脚本,该目录中不存在 *.sln 文件。 - mklement0
1个回答

7
您的方法无法正常工作,因为似乎找不到项目/解决方案文件。根据您的评论,我假设在执行您的命令之前发生了错误。您应该检查您运行的任何其他实用程序是否有错误。
通常,我使用命令行工具时会通过将参数数组传递给可执行文件来完成此类操作。当控制台中的命令变得越来越长和复杂时,使用参数数组似乎更有效。
$DotnetArgs = @()
$DotnetArgs = $DotnetArgs + "build"
$DotnetArgs = $DotnetArgs + ".\MySolution.sln"
$DotnetArgs = $DotnetArgs + "--configuration" + "Release"
& dotnet $DotnetArgs

您可以像这样创建一个可用的函数并将其保存在您的个人资料中,至少这就是我所做的。
function Invoke-Dotnet {
    [CmdletBinding()]
    Param (
        [Parameter(Mandatory = $true)]
        [System.String]
        $Command,

        [Parameter(Mandatory = $true)]
        [System.String]
        $Arguments
    )

    $DotnetArgs = @()
    $DotnetArgs = $DotnetArgs + $Command
    $DotnetArgs = $DotnetArgs + ($Arguments -split "\s+")

    [void]($Output = & dotnet $DotnetArgs)

    # Should throw if the last command failed.
    if ($LASTEXITCODE -ne 0) {
        Write-Warning -Message ($Output -join "; ")
        throw "There was an issue running the specified dotnet command."
    }
}

然后你可以这样运行它:

Invoke-Dotnet -Command build -Arguments ".\MySolution.sln --configuration Release"

3
谢谢!您能否解释一下为什么提问者使用的方法不起作用?其中有什么错误或问题? - omajid
我尝试了你的第一种方法(将参数聚合到一个数组中),但是我收到了相同的错误... 我不想尝试创建整个函数,因为这个脚本最终将在 Azure 流水线中运行。 - Gaax
1
刚才说错了,在我脚本中之前的一个命令出现问题,导致做出这些调整后出现了错误。你的方法非常好!谢谢 =) - Gaax

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接