Search code examples
visual-studiopowershellbatch-filetarget

Cannot execute reg query from visual studio post build target via batch script


So this is strange and I am not sure how to go about solving the issue. I have written a little Batch (.bat) routine to code sign an assembly when I am done building my Visual Studio Solution. Here's the BAT code:

@echo off
echo.
echo Signing Dlls...
setlocal ENABLEEXTENSIONS

set DLL_PATH=%1
set PFX_PATH="C:\Users\ksobon\source\repos\HOK-Revit-Addins\_cert\archilabCertificate.pfx"
set KEY_NAME="HKEY_LOCAL_MACHINE\SOFTWARE\HOK"
set VALUE_NAME="certificatePassword"

for /f "tokens=3" %%a in ('reg query %KEY_NAME% /V %VALUE_NAME% ^|findstr /ri "REG_SZ"') do set PFX_PASS=%%a

echo PFX File Path: %PFX_PATH%
echo PFX Password: %PFX_PASS%
echo DLL File Path: %DLL_PATH%

"C:\Program Files (x86)\Windows Kits\10\bin\10.0.15063.0\x86\signtool.exe" sign /f %PFX_PATH% /p %PFX_PASS% /t http://timestamp.comodoca.com/authenticode %DLL_PATH%

endlocal

When I call it from a PowerShell like so:

.\codeSigning.bat "C:\Users\ksobon\Desktop\Newtonsoft.Json.dll"

I get the proper result and the dll gets signed. No issues there. However, when I add it to my Visual Studio build target like so:

  <Target Name="CopyFiles" AfterTargets="AfterBuild">
    <Exec Command="&quot;$(SolutionDir)..\_postBuild\codeSigning.bat&quot; &quot;$(TargetPath)&quot;"/>
  </Target>

It craps out on me with the following error:

enter image description here

Ideas?


Solution

  • For anyone else stumbling into this. The issue was explained here: Powershell script from Visual Studio Post-build-event failing

    Basically it has to do with the fact that Visual Studio calls PowerShell that is different version (x64) than the one that i would get when I just launch it from Start Menu (x86). The way to fix this was to specify which power shell to use directly in my call like so:

      <Target Name="CopyFiles" AfterTargets="AfterBuild">
        <Exec Command="&quot;%WINDIR%\SysNative\WindowsPowerShell\v1.0\powershell.exe&quot; &quot;$(SolutionDir)..\_postBuild\codeSigning.bat&quot; &quot;$(TargetPath)&quot;"/>
      </Target>