Skip to content

Instantly share code, notes, and snippets.

@ashmind
Last active October 13, 2021 16:24
Show Gist options
  • Save ashmind/dd2da864e0a94e0bdae14642de1adee5 to your computer and use it in GitHub Desktop.
Save ashmind/dd2da864e0a94e0bdae14642de1adee5 to your computer and use it in GitHub Desktop.
Arbitrary scripts with dotnet run
<Project>
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<OutputType>Exe</OutputType>
<OutDir>build/bin</OutDir>
<BaseIntermediateOutputPath>build/obj</BaseIntermediateOutputPath>
</PropertyGroup>
<Target Name="PrepareProgram" BeforeTargets="BeforeBuild">
<PropertyGroup>
<ProgramPath>$(BaseIntermediateOutputPath)/Program.cs</ProgramPath>
<ProgramCode><![CDATA[$([MSBuild]::Escape('
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text.Json;
class Program {
static int Main(string[] args) {
var commands = JsonSerializer.Deserialize<Dictionary<string, string>>(File.ReadAllText("run.json"));
var command = commands[args[0]];
var process = Process.Start(new ProcessStartInfo("cmd", "/c " + command));
process.WaitForExit();
return process.ExitCode;
}
}
'))]]></ProgramCode>
</PropertyGroup>
<WriteLinesToFile File="$(ProgramPath)" Lines="$(ProgramCode)" Condition="!Exists('$(ProgramPath)')" />
<ItemGroup>
<Compile Include="$(ProgramPath)" />
</ItemGroup>
</Target>
<Import Project="Sdk.props" Sdk="Microsoft.NET.Sdk" />
<ItemGroup>
<Compile Remove="**/*.*" />
<None Remove="**/*.*" />
<Content Remove="**/*.*" />
<EmbeddedResource Remove="**/*.*" />
</ItemGroup>
<Import Project="Sdk.targets" Sdk="Microsoft.NET.Sdk" />
</Project>
{
"custom-command": "echo My custom command"
}
>dotnet run custom-command
My custom command
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment