Search code examples
sql-servercmdwmic

How to check ReturnValue from WMIC


I am setting up a simple batch file to configure a few things on an MS SQL Express server. One of the configuration items is to enable the TCP/IP protocol. I have gotten it to work with the following command:

WMIC /NAMESPACE:\\root\Microsoft\SqlServer\ComputerManagement15 PATH ServerNetworkProtocol Where ProtocolName='Tcp' CALL SetEnable

Now I want to check that it worked. If it works I get the output:

Executing (\\PCNAME\root\Microsoft\SqlServer\ComputerManagement15:ServerNetworkProtocol.InstanceName="SQLEXPRESS",ProtocolName="Tcp")->SetEnable()
Method execution successful.
Out Parameters:
instance of __PARAMETERS
{
        ReturnValue = 0;
};

For this to work, I have to run the batch file as an administrator. If I don't, I get the output:

Executing (\\PCNAME\root\Microsoft\SqlServer\ComputerManagement15:ServerNetworkProtocol.InstanceName="SQLEXPRESS",ProtocolName="Tcp")->SetEnable()
Method execution successful.
Out Parameters:
instance of __PARAMETERS
{
        ReturnValue = 2147942405;
};

The only difference is the ReturnValue. How can I check the return value and e.g. echo "Success" or "Fail" based on whether I get a ReturnValue of 0 or something else?

I'm also open to solving the problem by using another wmic command to check whether TCP/IP is enabled, but I haven't been able to find a way of doing this.


Solution

  • You could try:

    for /F "tokens=2 delims==; " %R in ('wmic /NameSpace:\\root\Microsoft\SqlServer\ComputerManagement15 path ServerNetworkProtocol where ProtocolName='Tcp' call SetEnable ^| findstr /RC:"\<ReturnValue ="') do @echo/%R
    

    to extract the value of ReturnValue, or, if you just want to check it against zero:

    wmic /NameSpace:\\root\Microsoft\SqlServer\ComputerManagement15 path ServerNetworkProtocol where ProtocolName='Tcp' call SetEnable | findstr /RC:"\<ReturnValue = 0;\>" && (echo zero) || (echo non-zero)