更改注册表值的C#WMI方法适用于调试但不适用

时间:2015-04-17 14:35:19

标签: c# wmi release-mode remote-registry

我已经做了一些谷歌搜索,看看我是否能找到解决方案,但到目前为止我还没有找到任何有用的东西。我的问题正如标题所述。我尝试通过更改注册表值将远程计算机作为指定用户登录,并且它在调试模式下正常工作,但不能发布(注册表值保持不变)。我以管理员身份登录Windows,并且还使用我的管理员凭据进行WMI。返回值为" 0"对于这两种情况,这意味着没有错误。另外需要注意的是,我使用WMI的所有其他函数在调试和发布版本(即WMI查询,WMI关闭/重新启动/注销)中都能正常工作,所以我不确定为什么这个特定的函数会赢得'在释放模式下工作。这是我的代码:

    public static bool LogOnAsViaWMI(string computerName, string username, string password, string logonUsername, string logonPW)
    {
        try
        {
            // Set connection options
            ConnectionOptions options = new ConnectionOptions();
            options.EnablePrivileges = true;
            options.Username = username;
            options.Password = password;

            // Connect to machine
            ManagementScope scope = new ManagementScope("\\\\" + computerName + "\\root\\CIMV2", options);
            scope.Connect();

            // Set management class
            ManagementPath managementPath = new ManagementPath("StdRegProv");
            ManagementClass mc = new ManagementClass(scope, managementPath, null);

            // Set registry values
            if (!SetRegKeyValue(mc, "AutoAdminLogon", "1") ||
                !SetRegKeyValue(mc, "ForceAutoLogon", "1") ||
                !SetRegKeyValue(mc, "DefaultUserName", logonUsername) ||
                !SetRegKeyValue(mc, "DefaultPassword", logonPW) ||
                !SetRegKeyValue(mc, "DefaultDomainName", "MyDomainName"))
            {
                MessageBox.Show("Failed to set Windows logon registry values");
                return false;
            }

            // Log off to log in as new default
            LogOff(computerName, username, password);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

        return true;
    }

    private static bool SetRegKeyValue(ManagementClass mc, string valueName, string value)
    {
        // Set values
        ManagementBaseObject inParams = mc.GetMethodParameters("SetStringValue");
        inParams["hDefKey"] = HKEY_LOCAL_MACHINE;
        inParams["sSubKeyName"] = @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon";
        inParams["sValueName"] = valueName;
        inParams["sValue"] = value;

        // Invoke inParams
        ManagementBaseObject outParams = mc.InvokeMethod("SetStringValue", inParams, null);
        if (outParams["returnValue"].ToString() != "0")
            return false;

        return true;
    }

0 个答案:

没有答案