我正在使用WMI代码创建者来创建代码来添加一个网络打印机。
http://img13.imageshack.us/img13/9847/wmicodecreatorwin32prin.png
生成的代码工作得很好(无论如何,在我的域帐户下):
using System;
using System.Management;
using System.Windows.Forms;
namespace WMISample
{
public class CallWMIMethod
{
public static void Main()
{
try
{
ManagementClass classInstance =
new ManagementClass("root\\CIMV2",
"Win32_Printer", null);
// Obtain in-parameters for the method
ManagementBaseObject inParams =
classInstance.GetMethodParameters("AddPrinterConnection");
// Add the input parameters.
inParams["Name"] = "\\\\PrintServer\\PrinterName";
// Execute the method and obtain the return values.
ManagementBaseObject outParams =
classInstance.InvokeMethod("AddPrinterConnection", inParams, null);
// List outParams
Console.WriteLine("Out parameters:");
Console.WriteLine("ReturnValue: " + outParams["ReturnValue"]);
}
catch(ManagementException err)
{
MessageBox.Show("An error occurred while trying to execute the WMI method: " + err.Message);
}
}
}
}但是,我需要将联网打印机添加到本地PC帐户,即没有访问\PrintServer的非域帐户。
在哪里可以将域用户(服务帐户)的用户名和密码输入到上述代码中?
我已经在谷歌上搜索了几个小时,但我只能找到一个愚蠢的帖子,上面写着如何在远程机器上添加打印机,这不是我想要做的。
(我需要将远程打印机添加到当前PC,而不是远程PC。)(请注意,登录用户是本地PC帐户。)
有人知道如何才能做到这一点吗?
发布于 2011-08-06 04:22:28
您可以在打印服务器上创建相同的本地帐户,通过这样做启用对等身份验证.
也就是说,pc1在本地有用户bob1。使bob1成为打印服务器上的用户。
以bob1的形式在pc1上运行您的地图程序,您应该能够到达打印机。
这有用吗?
否则,网络打印机是每个user...running您的程序,因为拥有访问权限(即runas)的域用户将无法工作,因为它只会将打印机映射到用户会话,而不是您实际需要的会话。
关于这个的...what?http://www.codescript.co.uk/wmi_connect_as_another_user.htm
...or scriptomatic?http://www.microsoft.com/download/en/details.aspx?DisplayLang=en&id=12028 (即使不是c#,它仍然可以提供wmi synatx )
发布于 2017-09-21 17:57:27
所以既然其他答案被删除了。我刚刚测试了这个,结果成功了。下面是我使用的https://www.codeproject.com/Articles/10090/A-small-C-Class-for-impersonating-a-User类的链接,下面是为我工作的代码。如果您看一看,有一些更好的类实现可以模拟用户。
static void Main(string[] args)
{
using (new Impersonator("username", "domainName", "myPassword"))
{
// The following code is executed under the impersonated user.
AddPrinterUnc(@"\\PrintServer\printershare");
}
}
public static void AddPrinterUnc(string printUncPath)
{
using (ManagementClass oPrinterClass = new ManagementClass(new ManagementPath("Win32_printer"), null))
{
using (ManagementBaseObject oInputParameters = oPrinterClass.GetMethodParameters("AddPrinterConnection"))
{
oInputParameters.SetPropertyValue("Name", printUncPath);
oPrinterClass.InvokeMethod("AddPrinterConnection", oInputParameters, null);
}
}
}https://stackoverflow.com/questions/6963152
复制相似问题