如何从 powershell 脚本中执行“dotnet build”

Gaa*_*aax 4 powershell .net-core

当我直接在 powershell 终端中运行以下行时,它工作得很好:

dotnet build ./MySolution.sln --configuration Release
Run Code Online (Sandbox Code Playgroud)

但是,当我将该行放入 powershell 脚本中并从同一目录中运行它时,我收到此错误:

MSBUILD : error MSB1009: Project file does not exist.
Run Code Online (Sandbox Code Playgroud)

我尝试以不同方式传递参数,如如何使用 & 运算符从 PowerShell 调用 MSBuild? 的答案之一中提到的那样。所以我现在很茫然。我需要做什么才能在 powershell 脚本中完成这项工作?

Ash*_*Ash 8

您的方法不起作用,因为它似乎找不到项目/解决方案文件。从你的评论中我认为在你的命令之前有些东西已经失败了。您应该检查正在运行的任何其他实用程序是否有错误。

一般来说,对于命令行工具,我倾向于通过将参数数组传递给可执行文件来完成类似的事情。当控制台中的行变得更长且更复杂时,参数数组似乎可以更好地工作。

$DotnetArgs = @()
$DotnetArgs = $DotnetArgs + "build"
$DotnetArgs = $DotnetArgs + ".\MySolution.sln"
$DotnetArgs = $DotnetArgs + "--configuration" + "Release"
& dotnet $DotnetArgs
Run Code Online (Sandbox Code Playgroud)

您可以创建一个像这样的可用函数并将其保存在您的个人资料中,至少我是这样做的。

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."
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样运行它:

Invoke-Dotnet -Command build -Arguments ".\MySolution.sln --configuration Release"
Run Code Online (Sandbox Code Playgroud)

  • 谢谢!您是否有机会解释为什么提问者使用的方法不起作用?那里有什么错误/问题 (3认同)