Search code examples
c#.netvisual-studiomsbuildpre-build-event

Visual Studio prebuild powershell script exiting with code 9009 and failing to build


In my project I have set pre-build event that updates content of *.cs and *.xaml files (which are included in project being built).

I use Set-Content Powershell command for it.

When I test it in Powershell console everything is working perfectly.

But when I paste as in pre-build event it generates error with code 9009 and prevents VS from successfully building my project.

I have set build output verbosity to Diagnostic, but there's no more information on it.

What could be the problem?

My current guess is that VS locks files for building, thus Powershell commands can't modify them.


Solution

  • I use Set-Content Powershell command for it. What could be the problem?

    The cause of the issue:

    1.VS will call something like cmd.exe to execute the command you type in Build Events.

    That means you're trying to run Set-content command in cmd.exe.

    2.Like boxdog said, code9009 in VS do indicate the command is not recognized.

    More specifically, the Set-content is PowerShell command, not command recognized by cmd.exe.(See #1, VS calls cmd.exe to run the command).

    So the issue occurs: Type a PowerShell command in build events => VS calls cmd.exe to execute it => cmd.exe can't recognize a PS command. and throw error=> VS output log displays error code9009.

    Suggestions:

    You can't directly type Set-content in build events to run(equipment to run Set-content directly in CMD and it will cause error).

    Instead we can call powershell to run PS script or PS command in cmd.exe, you can find many related topics about how to run PS script from CMD online. See run PS command in cmd, run PS from CMD, How to run PS in CMD. But it's more like another issue, so I don't talk too much here:)

    In summary: You can choose to create a new PS script and move your Set-content command into it, and type command like powershell -file path\xx.ps1 or simple powershell - command in build events. Then the Error9009 would go away. (I believe the Error9009 would go away, but I've seen too many issues about other Error Codes, most of them are related to path issues, so take care about the Path defined in your script.)