Build/PowershellBuilder.cs

using System.Reflection;
using MoreLinq;
 
namespace Build;
 
public class PowershellBuilder
{
    public async Task Invoke()
    {
 
 
        // system management automation encounters error with snapin loading
 
        var dirPath = GetProjectRoot() + "/PowerShellStandardModule1/bin/Release/net8.0/win-x64/publish/PowerShellUtils";
        var filePath = dirPath + "/PowerShellUtils.psd1";
 
        Console.WriteLine($"Reading file: {filePath}");
 
        var content = await File.ReadAllLinesAsync(filePath);
        var line = content.Index().First(x => x.Value.StartsWith("ModuleVersion"));
 
        var versionStr = line.Value.Split("'")[1];
 
        var version = Version.Parse(versionStr);
 
        Console.WriteLine($"Current version: {version}");
        version.IncrementPatch();
        Console.WriteLine($"Updated to new version: {version}");
 
        var contentToWrite = content.Select((x, i) => i == line.Key ? $"ModuleVersion = '{version}'" : x);
 
        await File.WriteAllLinesAsync(filePath, contentToWrite);
    }
 
    public DirectoryInfo GetProjectRoot()
    {
        var currentDirectory = new DirectoryInfo(Assembly.GetExecutingAssembly().Location);
        while (currentDirectory.Name is not "PowerShellStandardModule1")
        {
            currentDirectory = currentDirectory.Parent!;
        }
 
        return currentDirectory;
    }
}
 
public record Version
{
    public int Major { get; set; }
    public int Minor { get; set; }
    public int Patch { get; set; }
 
    public static Version Parse(string version)
    {
        var parts = version.Split(".");
        var intParts = parts.Select(int.Parse).ToList();
        return new Version
        {
            Major = intParts[0],
            Minor = intParts[1],
            Patch = intParts[2]
        };
    }
 
    public Version IncrementMajor()
    {
        Major++;
        Minor = 0;
        Patch = 0;
        return this;
    }
 
    public Version IncrementMinor()
    {
        Minor++;
        Patch = 0;
        return this;
    }
 
    public Version IncrementPatch()
    {
        Patch++;
        return this;
    }
 
    public override string ToString()
    {
        return $"{Major}.{Minor}.{Patch}";
    }
}