我有一个 ASP .NET WEB Forms 项目,我想执行 power-shell 脚本来更新hosts
文件。
private void ExecutePowerShellScript(string scriptToExecute)
{
using (PowerShell powershelInstance = PowerShell.Create())
{
var authManger = powershelInstance.Runspace.RunspaceConfiguration.AuthorizationManager;
powershelInstance.AddScript(scriptToExecute);
Collection<PSObject> results = powershelInstance.Invoke();
if (powershelInstance.Streams.Error.Count > 0)
{
throw powershelInstance.Streams.Error[0].Exception;
}
foreach (var result in results)
{
}
}
}
有脚本:
$hostsPath = "$env:windir\System32\drivers\etc\hosts";
$hosts = get-content $hostsPath;
[System.Collections.ArrayList]$arr = $hosts;
$arr.Add(someValueHere);
$arr | Out-File $hostsPath -enc ascii;
# returns results;
$arr;
# end of the script";
我试过这个: Invoke( Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Unrestricted
);
然后将此粘贴Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Unrestricted
在脚本的开头。使用这个Set-ExecutionPolicy Unrestricted
- 相同和相同的错误。访问路径C:\Windows\System32\drivers\etc\hosts' 被拒绝。
如果我遇到控制台应用程序,该脚本可以完美运行。
更新:我以管理员身份运行 Visual Studio。
更新 2:好的,现在我正在使用ImpersonatedUser
,但发生另一个异常。“不允许请求的注册表访问。”
堆栈跟踪:
at System.ThrowHelper.ThrowSecurityException(ExceptionResource resource)
at Microsoft.Win32.RegistryKey.OpenSubKey(String name, Boolean writable)
at System.Environment.GetEnvironmentVariable(String variable, EnvironmentVariableTarget target)
at System.Management.Automation.ModuleIntrinsics.SetModulePath()
at System.Management.Automation.ExecutionContext.InitializeCommon(AutomationEngine engine, PSHost hostInterface)
at System.Management.Automation.AutomationEngine..ctor(PSHost hostInterface, RunspaceConfiguration runspaceConfiguration, InitialSessionState iss)
at System.Management.Automation.Runspaces.LocalRunspace.DoOpenHelper()
at System.Management.Automation.Runspaces.RunspaceBase.CoreOpen(Boolean syncCall)
at System.Management.Automation.PowerShell.Worker.CreateRunspaceIfNeededAndDoWork(Runspace rsToUse, Boolean isSync)
at System.Management.Automation.PowerShell.CoreInvokeHelper[TInput,TOutput](PSDataCollection`1 input, PSDataCollection`1 output, PSInvocationSettings settings)
在 System.Management.Automation.PowerShell.CoreInvoke[TInput,TOutput](PSDataCollection 1 input, PSDataCollection
1 输出,
using (ImpersonatedUser impersonatedUser = new ImpersonatedUser(username, domain, password))
{
using (PowerShell powershelInstance = PowerShell.Create())
{
powershelInstance.AddScript(scriptToExecute);
//When the .Invoke() method is called, an exception with message "Requested registry access is not allowed." was thrown.
Collection<PSObject> results = powershelInstance.Invoke();
if (powershelInstance.Streams.Error.Count > 0)
{
throw powershelInstance.Streams.Error[0].Exception;
}
}
}