当前位置: 首页 > 编程语言 > C#

从C#应用程序运行PowerShell脚本Share

时间:2023-04-11 10:55:47 C#

从C#应用程序运行PowerShell脚本我正在尝试从C#应用程序执行PowerShell脚本。该脚本必须在特殊的用户上下文下执行。我尝试了不同的方案,有些方案很困难:1.从PowerShell直接调用我直接从ps-console调用脚本,它在正确的用户凭据下运行。C:ScriptsGroupNewGroup.ps11结果:脚本运行成功。2.从ac#consoleapplication我调用了ac#consoleapplication中的脚本,该脚本是在正确的用户凭据下启动的。代码:stringcmdArg="C:\Scripts\GroupNewGroup.ps11"Runspacerunspace=RunspaceFactory.CreateRunspace();runspace.ApartmentState=System.Threading.ApartmentState.STA;runspace.ThreadOptions=PSThreadOptions.UseCurrentThread;运行空间.Open();流水线pipeline=runspace.CreatePipeline();pipeline.Commands.AddScript(cmdArg);pipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error,PipelineResultTypes.Output);收集结果=pipeline.Invoke();varerror=管道.Error.ReadToEnd();运行空间.Close();if(error.Count>=1){字符串错误="";foreach(varErrorinerror){错误=错误+""+Error.ToString();}}结果:没有成功。还有许多“空数组”异常。3.从ac#console应用程序-代码端模拟(http://platinumdogs.me/2008/10/30/net-c-impersonation-with-network-credentials)我从ac#consoleapplication调用脚本正确的用户凭据和代码包含模拟。代码:使用(newImpersonator("Administrator2","domain","testPW")){使用(RunspaceInvokeinvoker=newRunspaceInvoke()){invoker.Invoke("Set-ExecutionPolicyUnrestricted");}stringcmdArg="C:\Scripts\GroupNewGroup.ps11";运行空间runspace=RunspaceFactory.CreateRunspace();runspace.ApartmentState=System.Threading.ApartmentState.STA;runspace.ThreadOptions=PSThreadOptions.UseCurrentThread;运行空间.Open();流水线流水线=运行空间。创建管道();pipeline.Commands.AddScript(cmdArg);pipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error,PipelineResultTypes.Output);收集结果=pipeline.Invoke();varerror=pipeline.Error.ReadToEnd();运行空间.Close();if(error.Count>=1){字符串错误="";foreach(varErrorinerror){错误=错误+""+Error.ToString();}}}结果:到目前为止没有有效的答案有谁知道为什么会有差异以及如何解决它?您是否尝试过Set-ExecutionPolicyUnrestrictedusing(newImpersonator("myUsername","myDomainname","myPassword")){using(RunspaceInvokeinvoker=newRunspaceInvoke()){invoker.Invoke("Set-ExecutionPolicyUnrestricted");}}编辑:发现这个小宝石……http://www.codeproject.com/Articles/10090/A-small-C-Class-for-impersonating-a-User命名空间工具{#region使用指令。//-----------------------------------------------------------------使用系统;使用System.Security.Principal;使用System.Runtime.InteropServices;使用System.ComponentModel;//----------------------------------------------------------------#endregion////////////////////////////////////////////////////////////////////////////模拟用户。允许在另一个///用户上下文中执行代码。///请注意实例化Impersonator类的帐户///需要具有“作为操作系统的一部分”权限集。/////////此类基于Microsoft知识库中的信息base///articlehttp://support.microsoft.com/default.aspx?scid=kb;en-us;Q306158//////将实例封装到using指令中,例如://////...///using(newImpersonator("myUsername","myDomainname","myPassword"))///{///...///[在新上下文中执行的代码]///...///}///...//////有关此类的问题,请联系作者UweKeim(mailto:uwe.keim@zeta-software.de)///。///publicclassImpersonator:IDisposable{#region公共方法。//----------------------------------------------------------------//////构造函数。使用给定的凭据开始模拟。///请注意,实例化Impersonator类的帐户///需要具有“作为操作系统的一部分”权限集。//////要充当的用户的名称。///要充当的用户的域名。///作为用户的密码。公共模仿者(字符串用户名,STringdomainName,stringpassword){ImpersonateValidUser(userName,domainName,password);}//----------------------------------------------------------------#endregion#regionIDisposable成员。//----------------------------------------------------------------publicvoidDispose(){UndoImpersonation();}//----------------------------------------------------------------#endregion#regionP/调用。//----------------------------------------------------------------[DllImport("advapi32.dll",SetLastError=true)]privatestaticexternintLogonUser(stringlpszUserName,stringlpszDomain,stringlpszPassword,intdwLogonType,intdwLogonProvider,refIntPtrphToken);[DllImport("advapi32.dll",CharSet=CharSet.Auto,SetLastError=true)]privatestaticexternintDuplicateToken(IntPtrhToken,intimpersonationLevel,refIntPtrhNewToken);[DllImport("advapi32.dll",CharSet=CharSet.Auto,SetLastError=true)]privatestaticexternboolRevertToSelf();[DllImport("kernel32.dll",CharSet=CharSet.Auto)]privatestaticexternboolCloseHandle(IntPtrhandle);私有constintLOGON32_LOGON_INTERACTIVE=2;私人常量intLOGON32_PROVIDER_DEFAULT=0;//----------------------------------------------------------------#endregion#region私有成员。//----------------------------------------------------------------//////进行实际模拟。//////要充当的用户的名称。///要充当的用户的域名。///作为用户的密码。privatevoidImpersonateValidUser(stringuserName,stringdomain,stringpassword){WindowsIdentitytempWindowsIdentity=null;IntPtrtoken=IntPtr.Zero;IntPtrtokenDuplicate=IntPtr.Zero;try{if(RevertToSelf()){if(LogonUser(userName,domain,password,LOGON32_LOGON_INTERACTIVE,LOGON32_PROVIDER_DEFAULT,reftoken)!=0){if(DuplicateToken(token,2,reftokenDuplicate)!=0){tempWindowsIdentity=newWindowsIdentity(tokenDuplicate);impersonationContext=tempWindowsIdentity.Impersonate();}else{thrownewWin32Exception(Marshal.GetLastWin32Error());}}else{thrownewWin32Exception(Marshal.GetLastWin)32Error};else{thrownewWin32Exception(Marshal.GetLastWin32Error());}}finally{if(token!=IntPtr.Zero){CloseHandle(token);}if(tokenDuplicate!=IntPtr.Zero){CloseHandle(tokenDuplicate);}//////还原模拟。///privatevoidUndoImpersonation(){if(impersonationContext!=null){impersonationContext.Undo();}}privateWindowsImpersonationContextimpersonationContext=null;//--------------------------------------------------------------------#endregion}///////////////////////////////////////////////////////////////////////////我刚花了一天时间自己解决这个问题我终于通过将-ScopeProcess添加到Set-ExecutionPolicyinvoker.Invoke("Set-ExecutionPolicyUnrestricted-ScopeProcess");多个PowerShellcmddlet使用PSCredential对象使用特定用户帐户运行。查看这篇文章-http://letitknow.wordpress.com/2011/06/20/run-powershell-script-using-another-account/以下是创建包含要使用的用户名和密码的Credential对象的方法:$username='domainuser'$password='something'$cred=New-ObjectSystem.Management.Automation.PSCredential-ArgumentList@($username,(ConvertTo-SecureString-String$password-AsPlainText-Force))readyincredentials一旦密码在对象中使用,您可以做很多事情,例如调用Start-Process启动PowerShell.exe,在-Credential参数中指定凭据,或调用Invoke-Command在本地调用“远程”命令,指定-Credential参数中的凭据,或者您可以将Start-Job作为后台作业调用,将您想要的凭据传递到-Credential参数中。更多信息参见这里、这里和msdn以上就是《C#学习教程:从C#应用程序运行PowerShell脚本》的全部内容,如果对大家有用,需要进一步了解《C#学习教程》,希望大家付费注意——本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: