473,327 Members | 1,930 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,327 software developers and data experts.

WMI and Rebooting

I am trying to use WMI to reboot my system. I have admin privileges. I've
tried two different solutions but both fail for separate reasons.

private void button1_Click(object sender, System.EventArgs e)
{
ManagementBaseObject outParams = null;
ManagementClass os = new ManagementClass("Win32_OperatingSystem");

os.Scope.Options.EnablePrivileges = true; // enables required security
privilege.
os.Get();
ManagementBaseObject inParams = os.GetMethodParameters("Win32Shutdown");
inParams["Flags"] = "2"; // System forced reboot
inParams["Reserved"] = "0";
foreach (ManagementObject mo in os.GetInstances())
outParams = mo.InvokeMethod("Win32Shutdown", inParams, null);
}

This method gives me a run-time errors with System.Management telling me
"Privilege not held."

This next attempt, called from the click method, fails with a run-time error
saying "Invalid Method Parameter(s)".

ManagementClass os = new ManagementClass("Win32_OperatingSystem");
os.Scope.Options.EnablePrivileges = true; // enables required security
privilege.
os.Get();
ManagementBaseObject inParams = os.GetMethodParameters("Reboot");
ManagementBaseObject outParams = os.InvokeMethod("Reboot", inParams, null);

What am I doing wrong? I have .NET 1.1 on my system.

--
Steve
Nov 17 '05 #1
8 11544
I'd suggest going with Mentalis.org's solution. I've used it in a production
environment, and it works like a charm.
You can find it here:

http://www.mentalis.org/soft/class.qpx?id=7

Hope this helps,

Dan Cox

"Steve Teeples" <St**********@discussions.microsoft.com> wrote in message
news:0E**********************************@microsof t.com...
I am trying to use WMI to reboot my system. I have admin privileges. I've
tried two different solutions but both fail for separate reasons.

private void button1_Click(object sender, System.EventArgs e)
{
ManagementBaseObject outParams = null;
ManagementClass os = new ManagementClass("Win32_OperatingSystem");

os.Scope.Options.EnablePrivileges = true; // enables required security
privilege.
os.Get();
ManagementBaseObject inParams = os.GetMethodParameters("Win32Shutdown");
inParams["Flags"] = "2"; // System forced reboot
inParams["Reserved"] = "0";
foreach (ManagementObject mo in os.GetInstances())
outParams = mo.InvokeMethod("Win32Shutdown", inParams, null);
}

This method gives me a run-time errors with System.Management telling me
"Privilege not held."

This next attempt, called from the click method, fails with a run-time
error
saying "Invalid Method Parameter(s)".

ManagementClass os = new ManagementClass("Win32_OperatingSystem");
os.Scope.Options.EnablePrivileges = true; // enables required security
privilege.
os.Get();
ManagementBaseObject inParams = os.GetMethodParameters("Reboot");
ManagementBaseObject outParams = os.InvokeMethod("Reboot", inParams,
null);

What am I doing wrong? I have .NET 1.1 on my system.

--
Steve



Nov 17 '05 #2

"Steve Teeples" <St**********@discussions.microsoft.com> wrote in message
news:0E**********************************@microsof t.com...
I am trying to use WMI to reboot my system. I have admin privileges. I've
tried two different solutions but both fail for separate reasons.

private void button1_Click(object sender, System.EventArgs e)
{
ManagementBaseObject outParams = null;
ManagementClass os = new ManagementClass("Win32_OperatingSystem");

os.Scope.Options.EnablePrivileges = true; // enables required security
privilege.
os.Get();
ManagementBaseObject inParams = os.GetMethodParameters("Win32Shutdown");
inParams["Flags"] = "2"; // System forced reboot
inParams["Reserved"] = "0";
foreach (ManagementObject mo in os.GetInstances())
outParams = mo.InvokeMethod("Win32Shutdown", inParams, null);
}

This method gives me a run-time errors with System.Management telling me
"Privilege not held."

This next attempt, called from the click method, fails with a run-time
error
saying "Invalid Method Parameter(s)".

ManagementClass os = new ManagementClass("Win32_OperatingSystem");
os.Scope.Options.EnablePrivileges = true; // enables required security
privilege.
os.Get();
ManagementBaseObject inParams = os.GetMethodParameters("Reboot");
ManagementBaseObject outParams = os.InvokeMethod("Reboot", inParams,
null);

What am I doing wrong? I have .NET 1.1 on my system.

--
Steve


This is confirmed to be a known problem with v1.1 SP1 (and v1.0 SP3), check
[1] for a reply from MSFT on microsoft.public.dotnet.framework. for the same
issue.

Subject: PrivilegeNotHeld, .Net 1.1 sp1 bug, hotfix
Date: April 24, 2005

Willy.


Nov 17 '05 #3
Willy,

Is there any type of work-around? I am writing test code and would like to
call WMI methods as part of my test functionality.
--
Steve
"Willy Denoyette [MVP]" wrote:

"Steve Teeples" <St**********@discussions.microsoft.com> wrote in message
news:0E**********************************@microsof t.com...
I am trying to use WMI to reboot my system. I have admin privileges. I've
tried two different solutions but both fail for separate reasons.

private void button1_Click(object sender, System.EventArgs e)
{
ManagementBaseObject outParams = null;
ManagementClass os = new ManagementClass("Win32_OperatingSystem");

os.Scope.Options.EnablePrivileges = true; // enables required security
privilege.
os.Get();
ManagementBaseObject inParams = os.GetMethodParameters("Win32Shutdown");
inParams["Flags"] = "2"; // System forced reboot
inParams["Reserved"] = "0";
foreach (ManagementObject mo in os.GetInstances())
outParams = mo.InvokeMethod("Win32Shutdown", inParams, null);
}

This method gives me a run-time errors with System.Management telling me
"Privilege not held."

This next attempt, called from the click method, fails with a run-time
error
saying "Invalid Method Parameter(s)".

ManagementClass os = new ManagementClass("Win32_OperatingSystem");
os.Scope.Options.EnablePrivileges = true; // enables required security
privilege.
os.Get();
ManagementBaseObject inParams = os.GetMethodParameters("Reboot");
ManagementBaseObject outParams = os.InvokeMethod("Reboot", inParams,
null);

What am I doing wrong? I have .NET 1.1 on my system.

--
Steve


This is confirmed to be a known problem with v1.1 SP1 (and v1.0 SP3), check
[1] for a reply from MSFT on microsoft.public.dotnet.framework. for the same
issue.

Subject: PrivilegeNotHeld, .Net 1.1 sp1 bug, hotfix
Date: April 24, 2005

Willy.



Nov 17 '05 #4
CSharper,

Thanks for the lead. Given the issue with 1.1 and WMI I implemented your
suggested. It does work wonderfully. However, unfortunately, this only
addresses the issue of powering the system. I still need to be able to
implement calls to WMI methods generically for my test tools to function as
expected. Any suggestions?
--
Steve
"CSharper" wrote:
I'd suggest going with Mentalis.org's solution. I've used it in a production
environment, and it works like a charm.
You can find it here:

http://www.mentalis.org/soft/class.qpx?id=7

Hope this helps,

Dan Cox

"Steve Teeples" <St**********@discussions.microsoft.com> wrote in message
news:0E**********************************@microsof t.com...
I am trying to use WMI to reboot my system. I have admin privileges. I've
tried two different solutions but both fail for separate reasons.

private void button1_Click(object sender, System.EventArgs e)
{
ManagementBaseObject outParams = null;
ManagementClass os = new ManagementClass("Win32_OperatingSystem");

os.Scope.Options.EnablePrivileges = true; // enables required security
privilege.
os.Get();
ManagementBaseObject inParams = os.GetMethodParameters("Win32Shutdown");
inParams["Flags"] = "2"; // System forced reboot
inParams["Reserved"] = "0";
foreach (ManagementObject mo in os.GetInstances())
outParams = mo.InvokeMethod("Win32Shutdown", inParams, null);
}

This method gives me a run-time errors with System.Management telling me
"Privilege not held."

This next attempt, called from the click method, fails with a run-time
error
saying "Invalid Method Parameter(s)".

ManagementClass os = new ManagementClass("Win32_OperatingSystem");
os.Scope.Options.EnablePrivileges = true; // enables required security
privilege.
os.Get();
ManagementBaseObject inParams = os.GetMethodParameters("Reboot");
ManagementBaseObject outParams = os.InvokeMethod("Reboot", inParams,
null);

What am I doing wrong? I have .NET 1.1 on my system.

--
Steve



Nov 17 '05 #5
Willy, I read the article you pointed me to. It seems that the hotfix is
language specific. Is that true? If so, I deal with over 26 languages and
would need a hot fix for each. Any suggestions of how I should proceed?
--
Steve
"Willy Denoyette [MVP]" wrote:

"Steve Teeples" <St**********@discussions.microsoft.com> wrote in message
news:0E**********************************@microsof t.com...
I am trying to use WMI to reboot my system. I have admin privileges. I've
tried two different solutions but both fail for separate reasons.

private void button1_Click(object sender, System.EventArgs e)
{
ManagementBaseObject outParams = null;
ManagementClass os = new ManagementClass("Win32_OperatingSystem");

os.Scope.Options.EnablePrivileges = true; // enables required security
privilege.
os.Get();
ManagementBaseObject inParams = os.GetMethodParameters("Win32Shutdown");
inParams["Flags"] = "2"; // System forced reboot
inParams["Reserved"] = "0";
foreach (ManagementObject mo in os.GetInstances())
outParams = mo.InvokeMethod("Win32Shutdown", inParams, null);
}

This method gives me a run-time errors with System.Management telling me
"Privilege not held."

This next attempt, called from the click method, fails with a run-time
error
saying "Invalid Method Parameter(s)".

ManagementClass os = new ManagementClass("Win32_OperatingSystem");
os.Scope.Options.EnablePrivileges = true; // enables required security
privilege.
os.Get();
ManagementBaseObject inParams = os.GetMethodParameters("Reboot");
ManagementBaseObject outParams = os.InvokeMethod("Reboot", inParams,
null);

What am I doing wrong? I have .NET 1.1 on my system.

--
Steve


This is confirmed to be a known problem with v1.1 SP1 (and v1.0 SP3), check
[1] for a reply from MSFT on microsoft.public.dotnet.framework. for the same
issue.

Subject: PrivilegeNotHeld, .Net 1.1 sp1 bug, hotfix
Date: April 24, 2005

Willy.



Nov 17 '05 #6

"Steve Teeples" <St**********@discussions.microsoft.com> wrote in message
news:14**********************************@microsof t.com...
Willy, I read the article you pointed me to. It seems that the hotfix is
language specific. Is that true? If so, I deal with over 26 languages
and
would need a hot fix for each. Any suggestions of how I should proceed?
--
Steve
"Willy Denoyette [MVP]" wrote:


The article is suggest that hotfixes can be language specific, that is why
MSFT doesn't make hotfixes publicly available, but in this particular case
there isn't a language issue.

However, if you don't like to contact PSS, here are some work-around:

1. Enable the privilege required yourself in code using PInvoke. Following
class should give you a head start....

public sealed class TokenAdjuster
{
// PInvoke stuff required to set/enable security privileges
[DllImport("advapi32", SetLastError=true),
SuppressUnmanagedCodeSecurityAttribute]
static extern int OpenProcessToken(
System.IntPtr ProcessHandle, // handle to process
int DesiredAccess, // desired access to process
ref IntPtr TokenHandle // handle to open access token
);

[DllImport("kernel32", SetLastError=true),
SuppressUnmanagedCodeSecurityAttribute]
static extern bool CloseHandle(IntPtr handle);

[DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)]
static extern int AdjustTokenPrivileges(
IntPtr TokenHandle,
int DisableAllPrivileges,
IntPtr NewState,
int BufferLength,
IntPtr PreviousState,
ref int ReturnLength);

[DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)]
static extern bool LookupPrivilegeValue(
string lpSystemName,
string lpName,
ref LUID lpLuid);

[StructLayout(LayoutKind.Sequential)]
internal struct LUID {
internal int LowPart;
internal int HighPart;
}

[StructLayout(LayoutKind.Sequential)]
struct LUID_AND_ATTRIBUTES {
LUID Luid;
int Attributes;
}

[StructLayout(LayoutKind.Sequential)]
struct _PRIVILEGE_SET {
int PrivilegeCount;
int Control;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=1)] // ANYSIZE_ARRAY = 1
LUID_AND_ATTRIBUTES [] Privileges;
}

[StructLayout(LayoutKind.Sequential)]
internal struct TOKEN_PRIVILEGES
{
internal int PrivilegeCount;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=3)]
internal int[] Privileges;
}
const int SE_PRIVILEGE_ENABLED = 0x00000002;
const int TOKEN_ADJUST_PRIVILEGES = 0X00000020;
const int TOKEN_QUERY = 0X00000008;
const int TOKEN_ALL_ACCESS = 0X001f01ff;
const int PROCESS_QUERY_INFORMATION = 0X00000400;

public static bool EnablePrivilege (string lpszPrivilege, bool
bEnablePrivilege )
{
bool retval = false;
int ltkpOld = 0;
IntPtr hToken = IntPtr.Zero;
TOKEN_PRIVILEGES tkp = new TOKEN_PRIVILEGES();
tkp.Privileges = new int[3];
TOKEN_PRIVILEGES tkpOld = new TOKEN_PRIVILEGES();
tkpOld.Privileges = new int[3];
LUID tLUID = new LUID();
tkp.PrivilegeCount = 1;
if (bEnablePrivilege)
tkp.Privileges[2] = SE_PRIVILEGE_ENABLED;
else
tkp.Privileges[2] = 0;
if(LookupPrivilegeValue(null , lpszPrivilege , ref tLUID))
{
Process proc = Process.GetCurrentProcess();
if(proc.Handle != IntPtr.Zero) {
if (OpenProcessToken(proc.Handle, TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY,
ref hToken) != 0) {
tkp.PrivilegeCount = 1;
tkp.Privileges[2] = SE_PRIVILEGE_ENABLED;
tkp.Privileges[1] = tLUID.HighPart;
tkp.Privileges[0] = tLUID.LowPart;
const int bufLength = 256;
IntPtr tu = Marshal.AllocHGlobal( bufLength );
Marshal.StructureToPtr(tkp, tu, true);
if(AdjustTokenPrivileges(hToken, 0, tu, bufLength, IntPtr.Zero, ref
ltkpOld) != 0)
{
// successful AdjustTokenPrivileges doesn't mean privilege could be
changed
if (Marshal.GetLastWin32Error() == 0)
{
retval = true; // Token changed
}
}
TOKEN_PRIVILEGES tokp = (TOKEN_PRIVILEGES) Marshal.PtrToStructure(tu,
typeof(TOKEN_PRIVILEGES) );
Marshal.FreeHGlobal( tu );
}
}
}
if (hToken != IntPtr.Zero)
{
CloseHandle(hToken);
}
return retval;
}

Usage:

ManagementObject mo = new ManagementObject(path);
// Enable shutdown privilege
if(!TokenAdjuster.EnablePrivilege("SeShutdownPrivi lege", true))
// Could not enable privilege
..
else
// Go on and invoke your method.
2. take Wminet_utils.dll from a pre SP1 framework.

Willy.

Nov 17 '05 #7
Option 2 definately looks the simplest! Thanks. Do you know an approximate
timeframe when .NET Frameworks 2.0 is to be released?
--
Steve
"Willy Denoyette [MVP]" wrote:

"Steve Teeples" <St**********@discussions.microsoft.com> wrote in message
news:14**********************************@microsof t.com...
Willy, I read the article you pointed me to. It seems that the hotfix is
language specific. Is that true? If so, I deal with over 26 languages
and
would need a hot fix for each. Any suggestions of how I should proceed?
--
Steve
"Willy Denoyette [MVP]" wrote:


The article is suggest that hotfixes can be language specific, that is why
MSFT doesn't make hotfixes publicly available, but in this particular case
there isn't a language issue.

However, if you don't like to contact PSS, here are some work-around:

1. Enable the privilege required yourself in code using PInvoke. Following
class should give you a head start....

public sealed class TokenAdjuster
{
// PInvoke stuff required to set/enable security privileges
[DllImport("advapi32", SetLastError=true),
SuppressUnmanagedCodeSecurityAttribute]
static extern int OpenProcessToken(
System.IntPtr ProcessHandle, // handle to process
int DesiredAccess, // desired access to process
ref IntPtr TokenHandle // handle to open access token
);

[DllImport("kernel32", SetLastError=true),
SuppressUnmanagedCodeSecurityAttribute]
static extern bool CloseHandle(IntPtr handle);

[DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)]
static extern int AdjustTokenPrivileges(
IntPtr TokenHandle,
int DisableAllPrivileges,
IntPtr NewState,
int BufferLength,
IntPtr PreviousState,
ref int ReturnLength);

[DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)]
static extern bool LookupPrivilegeValue(
string lpSystemName,
string lpName,
ref LUID lpLuid);

[StructLayout(LayoutKind.Sequential)]
internal struct LUID {
internal int LowPart;
internal int HighPart;
}

[StructLayout(LayoutKind.Sequential)]
struct LUID_AND_ATTRIBUTES {
LUID Luid;
int Attributes;
}

[StructLayout(LayoutKind.Sequential)]
struct _PRIVILEGE_SET {
int PrivilegeCount;
int Control;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=1)] // ANYSIZE_ARRAY = 1
LUID_AND_ATTRIBUTES [] Privileges;
}

[StructLayout(LayoutKind.Sequential)]
internal struct TOKEN_PRIVILEGES
{
internal int PrivilegeCount;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=3)]
internal int[] Privileges;
}
const int SE_PRIVILEGE_ENABLED = 0x00000002;
const int TOKEN_ADJUST_PRIVILEGES = 0X00000020;
const int TOKEN_QUERY = 0X00000008;
const int TOKEN_ALL_ACCESS = 0X001f01ff;
const int PROCESS_QUERY_INFORMATION = 0X00000400;

public static bool EnablePrivilege (string lpszPrivilege, bool
bEnablePrivilege )
{
bool retval = false;
int ltkpOld = 0;
IntPtr hToken = IntPtr.Zero;
TOKEN_PRIVILEGES tkp = new TOKEN_PRIVILEGES();
tkp.Privileges = new int[3];
TOKEN_PRIVILEGES tkpOld = new TOKEN_PRIVILEGES();
tkpOld.Privileges = new int[3];
LUID tLUID = new LUID();
tkp.PrivilegeCount = 1;
if (bEnablePrivilege)
tkp.Privileges[2] = SE_PRIVILEGE_ENABLED;
else
tkp.Privileges[2] = 0;
if(LookupPrivilegeValue(null , lpszPrivilege , ref tLUID))
{
Process proc = Process.GetCurrentProcess();
if(proc.Handle != IntPtr.Zero) {
if (OpenProcessToken(proc.Handle, TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY,
ref hToken) != 0) {
tkp.PrivilegeCount = 1;
tkp.Privileges[2] = SE_PRIVILEGE_ENABLED;
tkp.Privileges[1] = tLUID.HighPart;
tkp.Privileges[0] = tLUID.LowPart;
const int bufLength = 256;
IntPtr tu = Marshal.AllocHGlobal( bufLength );
Marshal.StructureToPtr(tkp, tu, true);
if(AdjustTokenPrivileges(hToken, 0, tu, bufLength, IntPtr.Zero, ref
ltkpOld) != 0)
{
// successful AdjustTokenPrivileges doesn't mean privilege could be
changed
if (Marshal.GetLastWin32Error() == 0)
{
retval = true; // Token changed
}
}
TOKEN_PRIVILEGES tokp = (TOKEN_PRIVILEGES) Marshal.PtrToStructure(tu,
typeof(TOKEN_PRIVILEGES) );
Marshal.FreeHGlobal( tu );
}
}
}
if (hToken != IntPtr.Zero)
{
CloseHandle(hToken);
}
return retval;
}

Usage:

ManagementObject mo = new ManagementObject(path);
// Enable shutdown privilege
if(!TokenAdjuster.EnablePrivilege("SeShutdownPrivi lege", true))
// Could not enable privilege
..
else
// Go on and invoke your method.
2. take Wminet_utils.dll from a pre SP1 framework.

Willy.


Nov 17 '05 #8

"Steve Teeples" <St**********@discussions.microsoft.com> wrote in message
news:78**********************************@microsof t.com...
Option 2 definately looks the simplest! Thanks. Do you know an
approximate
timeframe when .NET Frameworks 2.0 is to be released?
--
Steve


Not really, my best guess is a RC by mid September (PDC 2005) and RTM a few
months later.

Willy.
Nov 17 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Al-ahmadi | last post by:
Hi EveryBody: Is there any way to add the rebooting code to the user interface of the setup project in VB.net ? if the answer is yes,how can I do it ? but if the answer is no, Is there any way...
0
by: Todd Bright | last post by:
I have a Windows service that I wrote in C#. It uses a form in another thread to keep it running because we needed some user interface activity. When the service is running the machine will NOT...
2
by: mr_amitkulkarni | last post by:
Hello Friends, Objective : I'm working on a trivial solution for an issue like if my server/pc hangs at any moment it should reboot automatically. proposed Solution : I'll be using an external...
4
by: A | last post by:
Anyone have any code to reboot from a C# app?
2
by: Brady Kelly | last post by:
When I use the ExitWindowsEx function in my C# console application it doesn't reboot. Any ideas why?
1
by: Al-ahmadi | last post by:
Hi EveryBody: Is there any way to add the rebooting code to the user interface of the setup project in VB.net ? if the answer is yes,how can I do it ? but if the answer is no, Is there any way...
7
by: Raju5725 | last post by:
Hi All, How can I Change Local Machine IP Address without rebooting the machine using VB.Net. As I want to shift from one IP address to another IP address with application the effect should...
3
by: spoonone | last post by:
Hi my daughters PC keeps rebooting, when it first loads, tried to Boot into safe mode, which I can not access, tried Windows Repair can't get in to give her password, tried making it a slave on my...
1
by: James Wright | last post by:
Hi, I am using oracle9i on Windows XP for my work. I have seen that sometimes oracle services(either listner or instance, sometimes both) are not getting started automatically on rebooting the...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.