简体   繁体   English

从C#或Dynamics NAV2013执行Powershell脚本

[英]Executing Powershell Scripts from C# or Dynamics NAV2013

I have now tried about a hundred ways of automating the execution of powershell scripts from C# and Dynamics NAV 2013. 我现在尝试了约一百种方法来自动执行C#和Dynamics NAV 2013中的powershell脚本。

Running the script works 100% from either Powershell ISE or executing it with the following command in commandline: 从Powershell ISE或从命令行使用以下命令运行脚本都可以100%运行该脚本:

powershell.exe -version 3.0 -command ". 'C:\temp\script.ps1'"

So the last option I tried now was to put this all in a .bat file and execute the .bat file using System.Diagnostics.Process (also, executing the .bat file manually works 100%) 因此,我现在尝试的最后一个选项是将其全部放入.bat文件中,并使用System.Diagnostics.Process执行.bat文件(同样,手动执行.bat文件的工作方式为100%)

Setup.GET;
ProcessInfo := ProcessInfo.ProcessStartInfo(FileName); //The .bat File
ProcessInfo.UseShellExecute := FALSE;
ProcessInfo.RedirectStandardError := TRUE;

//<< Credentials
ProcessInfo.Domain := Setup.Domain;
ProcessInfo.UserName := Setup.Username;

SecurePwd := SecurePwd.SecureString();

FOR i := 1 TO STRLEN(Setup.Password) DO
  SecurePwd.AppendChar(Setup.Password[i]);

ProcessInfo.Password := SecurePwd;
//>> Credentials

Process := Process.Start(ProcessInfo);
StreamReader := Process.StandardError();

MESSAGE(StreamReader.ReadToEnd());

Without setting the credentials I get as output from the message: 没有设置凭据,我将从消息中获取输出:

The handle is invalid.
The handle is invalid.
The handle is invalid.
The handle is invalid.
The handle is invalid.
Set-ExecutionPolicy : Access to the registry key 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell' is denied.

And it just about complains about something on every line in the script. 它只是在脚本的每一行上抱怨某些东西。

Import-Module : The specified module 'D:\psmodules\Multitenancy\NAVMultitenancySamples.psm1' was not loaded because no valid module file was found in any module directory.

etc. etc. 等等等

With the credentials filled in, message is blank but it didn't do anything that it was supposed to. 填写凭据后,消息为空白,但未执行应做的任何操作。

Now, from the message I can see that it is trying to access the registry entries for Powershell version 1 instead of 3... could that be part of the problem? 现在,从消息中我可以看到它正在尝试访问Powershell版本1而不是版本3的注册表项...这可能是问题的一部分吗? Version 3 is installed: 已安装版本3:

PS C:\> $Host.Version

Major  Minor  Build  Revision
-----  -----  -----  --------
3      0      -1     -1      

Have you checked the UAC side of things? 您是否检查过UAC方面的内容? It may require UAC privileges, as opposed to just Admin credentials; 它可能需要UAC特权,而不仅仅是管理员凭据。

This other StackOverflow question details how to elevate a System.Diagnostics.Process command; 这个StackOverflow的另一个问题详细说明了如何提升System.Diagnostics.Process命令;参见参考资料

startInfo.Verb = "runas";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM