Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net mvc 如何在没有错误消息或异常的情况下调试PowerShell进程_Asp.net Mvc_Powershell - Fatal编程技术网

Asp.net mvc 如何在没有错误消息或异常的情况下调试PowerShell进程

Asp.net mvc 如何在没有错误消息或异常的情况下调试PowerShell进程,asp.net-mvc,powershell,Asp.net Mvc,Powershell,我正在尝试从.NET应用程序中运行以下PowerShell脚本: try { Start-Process "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" -ArgumentList "--headless --disable-gpu --print-to-pdf=c:\myDir\file.pdf https://www.bing.com" $x = "Complete" $x | Out-File C:\my

我正在尝试从.NET应用程序中运行以下PowerShell脚本:

try {
    Start-Process "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" -ArgumentList "--headless --disable-gpu --print-to-pdf=c:\myDir\file.pdf https://www.bing.com"
$x = "Complete" 
$x | Out-File C:\myDir\error.txt
}
Catch {
    $_ | Out-File C:\myDir\error.txt
}
简单地说,以上内容将创建一个基于bing.com网站的pdf

在我的开发环境中,它作为PowerShell脚本运行良好。它在生产服务器上也可以正常运行(同样,作为PowerShell脚本)

当我从生产服务器上的web应用程序调用此PowerShell脚本时,会出现此问题。我的C#代码是

这在我的开发机器上运行良好。它在生产服务器上出现故障。
error.txt
文件被写入光盘,这表明这不是权限问题。但是,
error.txt
文件的内容始终显示“完成”。它从不出错

因此,PowerShell脚本中的捕获似乎从未被命中。因此,没有错误消息。C代码中没有抛出异常。不管怎样,它不起作用

我如何调试这个

或者,如果更简单的话,我很乐意直接运行代码,而不是调用PowerShell脚本文件,但下面的代码也“什么都不做”

 var command = $"\"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe\" -ArgumentList \"--no-sandbox --headless --disable-gpu --print-to-pdf={imagePath} {fullUrl}";

我能重现你的问题。这是因为生产服务器上的web应用程序正在当前未登录的用户下运行。它正在分配的应用程序池的标识下运行。如果Chrome是在与当前登录用户不同的用户下启动的,则可能无法正常工作。如果您查看该链接,您将看到该问题已于2012年12月注册,但仍未解决。如果在不同的用户下启动Chrome(“当按下Shift键调用时,在快捷上下文菜单中以不同用户的身份运行”),则很容易重现该问题。在这种情况下,Chrome不会打开任何页面,只会显示灰色屏幕

启动Chrome时使用
——无沙盒开关。谷歌实际上并没有重新编译这个。不过,如果您以自动方式运行Chrome来访问受信任的源代码,我相信这是可以的

因此,要解决此问题,请按以下方式修改脚本中的
启动流程

start-process "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" -ArgumentList "--no-sandbox --headless --disable-gpu --print-to-pdf=c:\myDir\file.pdf https://www.bing.com"
更新

起初我低估了这个问题。现在,经过额外的研究和许多尝试的方法,我可以提出有效的解决方案

我没有设法修复您当前从Web应用程序直接启动powershell和chrome的方法。Chrome无法启动,事件日志中出现以下错误:

Faulting application name: chrome.exe, version: 64.0.3282.186, time stamp: 0x5a8e38d5
Faulting module name: chrome_elf.dll, version: 64.0.3282.186, time stamp: 0x5a8e1e3d
Exception code: 0x80000003
Fault offset: 0x00000000000309b9
Faulting process id: 0x11524
Faulting application start time: 0x01d3bab1a89e3b4f
Faulting application path: C:\Program Files (x86)\Google\Chrome\Application\chrome.exe
Faulting module path: C:\Program Files (x86)\Google\Chrome\Application\64.0.3282.186\chrome_elf.dll
Report Id: e70a5a36-26a4-11e8-ac26-b8ca3a94ba80
即使您将应用程序池配置为使用可能启动chrome的某些现有(普通)用户的身份,也会发生此错误。 也许可以配置IIS或应用程序池来防止这些错误,但我还没有找到方法

我的建议是从启动powershell进程从控制器操作切换到使用Windows任务调度器调度任务

以下是完成此任务应采取的步骤:

  • 在生产服务器上创建一个用户,在该用户下启动Chrome。我将创建的用户称为“testuser”
  • testuser
    下登录,启动chrome,打开一些站点。如果没有这个步骤,流程就不会成功,可能是因为缺少chrome用户帐户
  • 授予
    testuser
    的“作为批处理作业登录”权限。成功执行
    testuser
    下的计划任务需要此步骤。中介绍了该过程
  • 如我在初始答案中所述,向脚本添加
    --无沙盒
    参数
  • Process.Start()
    的代码替换为任务作业的计划 从.Net计划任务是通过。将其安装到应用程序并添加以下代码:

    string powerShellScript = @"c:\myDir\ps.ps1";
    string userName = @"YOURCOMP\testuser";
    string userPassword = "TestPwd123";
    
    using (TaskService ts = new TaskService())
    {
        TaskDefinition td = ts.NewTask();
        td.Triggers.Add(new RegistrationTrigger
        {
            StartBoundary = DateTime.Now,
            EndBoundary = DateTime.Now.AddMinutes(1),
        });
        td.Settings.DeleteExpiredTaskAfter = TimeSpan.FromSeconds(5);
        td.Actions.Add(new ExecAction("powershell.exe", powerShellScript));
        ts.RootFolder.RegisterTaskDefinition($@"Print Pdf - {Guid.NewGuid()}", td, createType: TaskCreation.Create, userId: userName, password: userPassword, logonType: TaskLogonType.Password);
    }
    
    在上面的代码片段中,更改
    testuser
    的名称和密码

    使用这种方法,您的脚本将成功执行,pdf将成功打印

    由OP更新


    如果上述操作继续失败,请再次检查事件查看器日志。在本例中,我遇到了一个类似于
    的消息问题,机器默认权限设置不为具有CLSID{20FD4E26-8E0F-4F73-A0E0-F27B8C57BE6F}和APPID不可用的COM服务器应用程序授予本地激活权限,但已通过授予解决了该问题。此外,尝试在任务调度器中单独运行任务,例如创建一个新任务以简单地启动记事本或类似工具,以确保该任务与您要测试的帐户一起工作。在我的情况下,我必须使用管理员帐户

    您必须重定向stdin和stdout,以便它将其从powershell.exe发送回父进程(您的web应用程序)。我修改了您的代码示例以执行此操作:

    var command = "c:\myDir\ps.ps1";
    ProcessStartInfo psi = new ProcessStartInfo();
    psi.FileName = "powershell.exe";
    psi.Arguments = command;
    
    psi.RedirectStandardOutput = true;
    psi.RedirectStandardError = true;
    
    Process process = new Process();
    process.StartInfo = psi;
    process.Start();
    
    process.WaitForExit();
    
    Console.WriteLine(process.StandardOutput);
    Console.WriteLine(process.StandardError);
    

    我认为除了CodeFuller所说的没有沙盒选项之外,您还应该禁用所有扩展、同步和书签

    最好是使用
    --bwsi
    选项设置来宾会话别名“不登录浏览”

    有趣的是,在测试过程中,我发现在执行
    --bwsi
    之前,使用
    --disable extensions
    显式禁用扩展更好,得到了更好的pdf打印输出

    我已经测试过了,对我来说它很有效。我期待你的反馈

    Edit1和Edit3-删除try…catch并添加用户和密码,以及添加psuser详细信息

    您可能在域上,因此我已调整脚本以作为域上的不同用户运行(该用户必须具有正确的权限!)

    首先使用以下命令创建凭据文件:

    登录到用户,例如,psuser

    创建密码文件:

    # Encrypt user password and save it to file
    Read-Host -AsSecureString | ConvertFrom-SecureString | Out-File 'C:\<your_path>\your_secret_password.txt'
    
    b) 脚本中缺少域信息:

    Exception calling "Start" with "0" argument(s): "The stub received bad data"                            
    At C:\prg\PowerShell\test\chrome_print.ps1:39 char:12                                                   
    +            [Void]$process.Start()                                                                     
    +            ~~~~~~~~~~~~~~~~~~~~~~                                                                     
        + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException                           
        + FullyQualifiedErrorId : Win32Exception                                                            
    
    Exception calling "WaitForExit" with "0" argument(s): "No process is associated with this object."      
    At C:\prg\PowerShell\test\chrome_print.ps1:41 char:12                                                   
    +            $process.WaitForExit()                                                                     
    +            ~~~~~~~~~~~~~~~~~~~~~~                                                                     
        + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException                           
        + FullyQualifiedErrorId : InvalidOperationException                                                 
    
    You cannot call a method on a null-valued expression.                                                   
    At C:\prg\PowerShell\test\chrome_print.ps1:44 char:12                                                   
    +            $output = $process.StandardOutput.ReadToEnd()                                              
    +            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~                                              
        + CategoryInfo          : InvalidOperation: (:) [], RuntimeException                                
        + FullyQualifiedErrorId : InvokeMethodOnNull                                                        
    
    You cannot call a method on a null-valued expression.                                                   
    At C:\prg\PowerShell\test\chrome_print.ps1:45 char:12                                                   
    +            $output += $process.StandardError.ReadToEnd()                                              
    +            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~                                              
        + CategoryInfo          : InvalidOperation: (:) [], RuntimeException                                
        + FullyQualifiedErrorId : InvokeMethodOnNull     
    
    打印pdf

    以及stderr消息:

    [0313/112937.660:ERROR:gpu_process_transport_factory.cc(1009)] Lost UI shared context.
    [0313/112937.662:ERROR:instance.cc(49)] Unable to locate service manifest for metrics
    [0313/112937.662:ERROR:service_manager.cc(890)] Failed to resolve service name: metrics
    [0313/112938.152:ERROR:instance.cc(49)] Unable to locate service manifest for metrics
    [0313/112938.153:ERROR:service_manager.cc(890)] Failed to resolve service name: metrics
    [0313/112942.876:INFO:headless_shell.cc(566)] Written to file C:\prg\PowerShell\test\chrom e_file.pdf.
    
    Edit2使用ASP.NET添加windows帐户模拟

    使用ASP.NET模拟windows帐户: ASP.NET用户未被传递到新服务器
    Exception calling "Start" with "0" argument(s): "There are currently no logon servers available to service the logon request"
    At C:\prg\PowerShell\test\chrome_print.ps1:56 char:12
    +            [Void]$process.Start()
    +            ~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
        + FullyQualifiedErrorId : Win32Exception
    
    Exception calling "WaitForExit" with "0" argument(s): "No process is associated with this object."
    At C:\prg\PowerShell\test\chrome_print.ps1:58 char:12
    +            $process.WaitForExit()
    +            ~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
        + FullyQualifiedErrorId : InvalidOperationException
    
    You cannot call a method on a null-valued expression.
    At C:\prg\PowerShell\test\chrome_print.ps1:61 char:12
    +            $output = $process.StandardOutput.ReadToEnd()
    +            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
        + FullyQualifiedErrorId : InvokeMethodOnNull
    
    You cannot call a method on a null-valued expression.
    At C:\prg\PowerShell\test\chrome_print.ps1:62 char:12
    +            $output += $process.StandardError.ReadToEnd()
    +            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
        + FullyQualifiedErrorId : InvokeMethodOnNull
    
    Exception calling "Start" with "0" argument(s): "The stub received bad data"                            
    At C:\prg\PowerShell\test\chrome_print.ps1:39 char:12                                                   
    +            [Void]$process.Start()                                                                     
    +            ~~~~~~~~~~~~~~~~~~~~~~                                                                     
        + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException                           
        + FullyQualifiedErrorId : Win32Exception                                                            
    
    Exception calling "WaitForExit" with "0" argument(s): "No process is associated with this object."      
    At C:\prg\PowerShell\test\chrome_print.ps1:41 char:12                                                   
    +            $process.WaitForExit()                                                                     
    +            ~~~~~~~~~~~~~~~~~~~~~~                                                                     
        + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException                           
        + FullyQualifiedErrorId : InvalidOperationException                                                 
    
    You cannot call a method on a null-valued expression.                                                   
    At C:\prg\PowerShell\test\chrome_print.ps1:44 char:12                                                   
    +            $output = $process.StandardOutput.ReadToEnd()                                              
    +            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~                                              
        + CategoryInfo          : InvalidOperation: (:) [], RuntimeException                                
        + FullyQualifiedErrorId : InvokeMethodOnNull                                                        
    
    You cannot call a method on a null-valued expression.                                                   
    At C:\prg\PowerShell\test\chrome_print.ps1:45 char:12                                                   
    +            $output += $process.StandardError.ReadToEnd()                                              
    +            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~                                              
        + CategoryInfo          : InvalidOperation: (:) [], RuntimeException                                
        + FullyQualifiedErrorId : InvokeMethodOnNull     
    
    [0313/112937.660:ERROR:gpu_process_transport_factory.cc(1009)] Lost UI shared context.
    [0313/112937.662:ERROR:instance.cc(49)] Unable to locate service manifest for metrics
    [0313/112937.662:ERROR:service_manager.cc(890)] Failed to resolve service name: metrics
    [0313/112938.152:ERROR:instance.cc(49)] Unable to locate service manifest for metrics
    [0313/112938.153:ERROR:service_manager.cc(890)] Failed to resolve service name: metrics
    [0313/112942.876:INFO:headless_shell.cc(566)] Written to file C:\prg\PowerShell\test\chrom e_file.pdf.
    
    <authentication mode="Windows" />
    <identity impersonate="True" />
    
    // You need to create a Runspace. Each other pipeline you create will run in the same Runspace
    // Do it only once, all others will be pipelined
    RunspaceConfiguration powershellConfiguration = RunspaceConfiguration.Create();
    var powershellRunspace = RunspaceFactory.CreateRunspace(powershellConfiguration);
    powershellRunspace.Open();
    
    // create a pipeline the cmdlet invocation
    using ( Pipeline psPipeline = powershellRunspace.CreatePipeline() ){
        // Define the command to be executed in this pipeline
        Command script = new Command("PowerShell_script");
    
        // Add any parameter(s) to the command
        script.Parameters.Add("Param1", "Param1Value");
    
        // Add it to the pipeline
        psPipeline.Commands.Add(script);
    
        try {
            // Invoke() the script
            var results = psPipeline.Invoke();
            // work with the results
        } catch (CmdletInvocationException exception) {
        // Any exceptions here - for the invoked process
        }
    }
    
    <configuration>
    <runtime>
    ...
    <legacyImpersonationPolicy enabled="true" />
    <alwaysFlowImpersonationPolicy enabled="false" />
    </runtime>
    </configuration>