Search code examples
msbuildwindows-consolemsbuild-targetpowershell-7.4

How can I launch PowerShell as a post-build step in MSBuild?


Currently, you cannot easily debug a binary PowerShell module in Visual Studio 2022 (not Code!).

Instead of being required to manually open a PowerShell session, change the location to my project, attach the debugger to it, import my module and run one of my functions, I'd like to have a new PowerShell automatically opened and do all these things up to importing my module by using an MSBuild PostBuild step.

The following .NET project file entry doesn't work:

<Target Name="PostBuild" AfterTargets="PostBuildEvent">
  <Exec Command="Start-Process -FilePath pwsh -ArgumentList &quot;-NoExit -Command Set-Location '$(OutputPath)'&quot;" />
</Target>

MSBuild returns the following error then:

1>The command "Start-Process" is either misspelled or could not be found.
1>My.csproj(23,5): error MSB3073: The command "Start-Process -FilePath pwsh -ArgumentList "-NoExit -Command Set-Location 'bin\Debug\net8.0-windows\'"" exited with code 9009.

From the error I can see that it's not PowerShell that's executing the command but the Console.

How can I successfully open a new PowerShell window from a post-build step using MSBuild?

EDIT

If I just run <Exec Command="pwsh" /> (which should work without flaw), I get the following build error:

1>PowerShell 7.4.2
1>[31;1m´╗┐: [31;1mThe term '´╗┐' is not recognized as a name of a cmdlet, function, script file, or executable program.[0m
1>[31;1m[31;1mCheck the spelling of the name, or if a path was included, verify that the path is correct and try again.[0m
1>PS C:\MyPSModule> ´╗┐PS C:\MyPSModule>
1>C:\MyPSModule\MyPSModule.csproj(36,5): error MSB3073: The "pwsh" command exited with code 1.

Solution

  • If you want to start a new, interactive PowerShell window from an MSBuild Exec task, you need to use the start command to instruct CMD to create a new process instead of switching to the PowerShell conhost within the same window:

    <Target Name="PostBuild" AfterTargets="PostBuildEvent">
      <Exec Command="start pwsh" />
    </Target>