If a build fails or otherwise misbehaves in TeamCity but you believe it should not, follow these this procedure:
Find a way to do run the task from a command prompt. Make sure it works on the TeamCity agent machine, under the same user as the TeamCity agent runs under, with the same environment the agent receives. If necessary, run the TeamCity agent under a different user or tweak it's its environment. When the command runs OK, configure the same command in a TeamCity build using a the command-line runner with the custom script setting. If that works, try other runner if that feels applicable.
If the TeamCity build agent is run as a service (e.g. it is installed as a Windows service), try running the TeamCity agent under a regular user with administrative permissions from the command line. See also Windows Service limitations.
If this fixes the issue, you can try to figure out why running under the service is a problem for the build. Most often this is service-specific and is not related to TeamCity directly. Also, you can setup the TeamCity agent to be run from the console all the time (e.g. configure an automatic user logon and run the agent on the user logon).
Add the following setting described in the Microsoft documentation to the
machine.configfile on all agents:
<configuration> <runtime> <generatePublisherEvidence enabled="false"/> </runtime> </configuration>
You can modify the machine.config file as described in this external blog post and pass this config file to all agents, e.g. using a custom script.
Alternatively, upgrade .Net Framework on the TeamCity agents to version 4.0 and above. Details are available in the Microsoft documentation.