如何将构建后事件限制为仅为一种类型的构建运行?

我正在使用事件将DLL文件复制到本地IIS虚拟目录,但我不希望在发布模式下的构建服务器上发生这种情况。


当前回答

我发现我可以在项目文件中添加多个条件,就像这样:

  <Target Name="PostBuild" AfterTargets="PostBuildEvent" Condition=" '$(Configuration)' != 'Debug' AND '$(Configuration)' != 'Release' ">
      <Exec Command="powershell.exe -ExecutionPolicy Unrestricted -NoProfile -NonInteractive -File $(ProjectDir)postBuild.ps1 -ProjectPath $(ProjectPath) -Build $(Configuration)" />
  </Target>

其他回答

截至2022年,我已经找到了两个解决方案。在我的特定情况下,我想打包到不同的目录,这取决于Configuration。

选项1

<Target Name="PostBuild" AfterTargets="PostBuildEvent">
    <Exec Command="if $(Configuration) == Debug (dotnet pack --no-build -o ~/../../../../../nuget-repo/debug -p:PackageVersion=$(VersionInfo)) else (dotnet pack --no-build -o ~/../../../../../nuget-repo -p:PackageVersion=$(VersionInfo))" />
</Target>

选项2

<Target Name="PostBuild" AfterTargets="PostBuildEvent">
    <Exec Condition="'$(Configuration)' == 'Debug'" Command="dotnet pack --no-build -o ~/../../../../../nuget-repo/debug -p:PackageVersion=$(VersionInfo)" />
    <Exec Condition="'$(Configuration)' == 'Release'" Command="dotnet pack --no-build -o ~/../../../../../nuget-repo -p:PackageVersion=$(VersionInfo)" />
</Target>

我更喜欢第二种选择。

供你参考,你不需要使用goto。shell IF命令可以用圆括号括起来:

if $(ConfigurationName) == Debug (
  copy "$(TargetDir)myapp.dll" "c:\delivery\bin" /y
  copy "$(TargetDir)myapp.dll.config" "c:\delivery\bin" /y
) ELSE (
  echo "why, Microsoft, why".
)

生成前和生成后事件作为批处理脚本运行。您可以在$(ConfigurationName)上执行条件语句。

例如

if $(ConfigurationName) == Debug xcopy something somewhere

我发现我可以在项目文件中添加多个条件,就像这样:

  <Target Name="PostBuild" AfterTargets="PostBuildEvent" Condition=" '$(Configuration)' != 'Debug' AND '$(Configuration)' != 'Release' ">
      <Exec Command="powershell.exe -ExecutionPolicy Unrestricted -NoProfile -NonInteractive -File $(ProjectDir)postBuild.ps1 -ProjectPath $(ProjectPath) -Build $(Configuration)" />
  </Target>

从Visual Studio 2019开始,现代的.csproj格式支持直接在目标元素上添加条件:

<Target Name="PostBuild" AfterTargets="PostBuildEvent" Condition="'$(Configuration)' == 'Debug'">
    <Exec Command="nswag run nswag.json" />
</Target>

UI没有提供设置这个的方法,但是如果您通过UI进行更改,它似乎可以安全地将Configuration属性保留在适当的位置。