0

I am writing a powershell script to automate some of the boilerplate setup when initiating a .NET Core Blazor application, and for some reason it is not properly updating the .csproj file. What I would like to do is add a new node to the root of the file like so:

<Project Sdk="...">
  ...
  ... 
  ... 
  <Target Name="Tailwind" BeforeTargets="Build">
    <Exec Command="npm run input:build" />
  </Target>
</Project>

The script I am using works when I'm in a test environment using a mocked .csproj file:

# edit csproj as xml to include npm build scripts
$dir = Split-Path -Path (Get-Location) -Leaf
Write-Host "Adding build directives to "$dir".csproj . . .";
$xml = [XML] (Get-Content $dir".csproj");
$target = $xml.CreateElement("Target");
$target.SetAttribute("Name", "Tailwind");
$target.SetAttribute("BeforeTargets", "Build");
$cmd = $xml.CreateElement("Exec");
$cmd.SetAttribute("Command", "npm run input:build");
$xml.DocumentElement.AppendChild($target);
$target.AppendChild($cmd);
$xml.Save($dir+".csproj");
Write-Host ". . . done.";

The rest of the script is running perfectly, and everything seems to be PATH'd correctly. And like I said, the script runs fine in test. Is there a reason that a powershell automation script wouldn't be able to append a node to an existing .csproj file in a .NET project?

You'll have to excuse if my powershell looks heinous, as I am very new to it.

3
  • 1
    Perhaps it's being saved to a different path than you're expecting... Try $xml.Save("${PWD}\${dir}.csproj") Commented Jun 7, 2022 at 16:29
  • @MathiasR.Jessen Aha, that's it! Interesting that using relative paths worked fine in a test directory. I guess I should be more explicit about paths in the future. Thank you so much for your response, everything is working perfectly now. I'd give you some feel-good internet points if I could. Commented Jun 7, 2022 at 16:45
  • Great to hear! I've linked to a duplicate post that explains why you might see this behavior when passing relative paths to .NET base class libraries (TL;DR: powershell.exe doesn't update it's process environment with the new location when you use cd/Set-Location) Commented Jun 7, 2022 at 16:56

1 Answer 1

1

Mathias nailed it, the script required a full path to update and save the .csproj file in the root of the project directory.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.