簡體   English   中英

從C#或Dynamics NAV2013執行Powershell腳本

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

我現在嘗試了約一百種方法來自動執行C#和Dynamics NAV 2013中的powershell腳本。

從Powershell ISE或從命令行使用以下命令運行腳本都可以100%運行該腳本:

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

因此,我現在嘗試的最后一個選項是將其全部放入.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());

沒有設置憑據,我將從消息中獲取輸出:

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.

它只是在腳本的每一行上抱怨某些東西。

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

等等等

填寫憑據后,消息為空白,但未執行應做的任何操作。

現在,從消息中我可以看到它正在嘗試訪問Powershell版本1而不是版本3的注冊表項...這可能是問題的一部分嗎? 已安裝版本3:

PS C:\> $Host.Version

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

您是否檢查過UAC方面的內容? 它可能需要UAC特權,而不僅僅是管理員憑據。

這個StackOverflow的另一個問題詳細說明了如何提升System.Diagnostics.Process命令;參見參考資料

startInfo.Verb = "runas";

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM