Search code examples
windowsmavenbatch-fileexec-maven-plugin

Run batch script as admin during Maven build


I'm trying to set up a build process during which, a Windows service has to be started and stopped. I tried doing that by using the exec-maven-plugin:

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <version>1.6.0</version>
    <executions>
        <execution>
            <id>startServer</id>
            <goals>
                <goal>exec</goal>
            </goals>
            <configuration>
                <executable>${project.basedir}/bin/startService.cmd</executable>
                <workingDirectory>${project.basedir}/bin</workingDirectory>
            </configuration>
        </execution>
    </executions>
</plugin>

The problem that I'm running into is, that to be able to control services, you need to have adminsitrative rights. My user is local admin so the script works if I run it in an elevated prompt (right click->'Run as Adminsitrator').

I've tried using runas /user:administrator but it's prompting for a password. I could run the Maven build itself as admin but I'd like to run it from environments where this might not be possible (Eclipse, Jenkins).

Does anyone have an idea on how to implement the described scenario?


Solution

  • This is the other half of my solution to elevation mkdir in batch file as admin. The first half was console specific. This is the more general non console solution. WshShell.Run didn't work well as a console program, hence the use of VB/VBA shell command. The WshShell.Run has a window style (0 is hidden) and a flag to wait on the app or not.

    Put files on the desktop. They must be ANSI.

    RunAsAdmin.vb

    imports System.Runtime.InteropServices 
    Public Module MyApplication  
    
    Public Sub Main ()
            Dim wshshell as object
            WshShell = CreateObject("WScript.Shell")
                '8 is non active window, true means wait for exit
            WshShell.Run("""C:\Windows\Notepad.exe""",8, true)
        End Sub 
    End Module 
    

    RunAsAdmin.manifest

    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
    <assemblyIdentity
        version="1.0.0.0"
        processorArchitecture="*"
        name="Color Management"
        type="win32"
    />
    <description>Serenity's Editor</description>
    <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2"> 
    <security> 
        <requestedPrivileges> 
            <requestedExecutionLevel level="requireAdministrator" uiAccess="false"/> 
        </requestedPrivileges> 
    </security> 
    </trustInfo> 
    
    </assembly>
    

    And the command to compile.

    C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc "%userprofile%\Desktop\RunAsAdmin.vb" /win32manifest:"%userprofile%\Desktop\RunAsAdmin.manifest" /out:"%userprofile%\Desktop\RunAsAdmin.exe" /target:winexe