【问题标题】:Script stops on specific command without go into catch block脚本在特定命令上停止而不进入 catch 块
【发布时间】:2013-05-03 08:44:34
【问题描述】:

我有一个带有 PowerCLI 命令的 powershell 脚本来安装和配置虚拟机。

这些是环境中的设置

  • Windows Server 2008 R2
  • ESX 4.1
  • PowerShell v2
  • PowerCLI 5.1

脚本将由网站上的用户触发。以下代码启动脚本。 PathToScript 是 UNC 路径

const string Path32BitPowerShell = @"C:\Windows\SysWOW64\Windowspowershell\v1.0\powershell.exe";

public static void Run32BitPowerShell(String PathToScript, Boolean WaitForExit, String Arguments = "")
{
    Process PowerShellProcess = new Process();
    PowerShellProcess.StartInfo.CreateNoWindow = true;
    PowerShellProcess.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
    PowerShellProcess.StartInfo.FileName = Path32BitPowerShell;
    PowerShellProcess.StartInfo.WorkingDirectory = @"C:\";
    PowerShellProcess.StartInfo.Arguments = PathToScript + " " + Arguments;

    PowerShellProcess.Start();

    if (WaitForExit)
    {
        PowerShellProcess.WaitForExit();
    }
}

脚本有这两个全局设置:

$ErrorActionPreference = "Stop"
$ConfirmPreference = "None"

整个代码在一个带有 catch/finally 的 try 块中 但是代码永远不会进入 catch 块。我知道是因为我在 catch 块 Stop-Computer -Force -Confirm:$false 的第一行写了一次,并且在脚本完成 5 分钟后网络服务器仍在运行。

代码停在命令Invoke-VMScript:

Invoke-VMScript -VM $VM -ScriptType Bat -ScriptText "powershell.exe  -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile -Command Set-ExecutionPolicy Unrestricted -Scope CurrentUser" -GuestUser "***" -GuestPassword "****"  

C# 进程的退出代码是1

重要:

脚本运行完美,我以交互方式启动它(从 ISE)! 该问题仅在网络服务器启动时出现(非交互式)。

有人知道问题出在哪里?

/更新

它也可以直接从 powershell 命令行工作,但也可以交互

【问题讨论】:

  • 对我来说听起来像是授权/权利问题。 iis 用户是否有足够的权限来启动它?
  • 是的,应用程序池标识设置为通用域用户。他在 ESX 环境中具有特殊权限。当我使用他的凭据登录并使用 ISE 运行脚本时,它按预期工作。
  • 要运行 Invoke-VMScript,用户必须具有对包含虚拟机的文件夹的读取权限和 Virtual Machine.Interaction.Console 交互权限。 是否选中?
  • 是的,用户有这个权利,当从网站触发时(权利遗传),连接到 ESX 服务器使用来自运行脚本的用户的凭据。这是通用帐户(应用程序池标识)

标签: c# exception powershell powershell-2.0 powercli


【解决方案1】:

不妨试试

$Global:ErrorActionPreference = '停止'

$Global:ConfirmPreference = '无'

当我遇到非常相似的问题时为我工作。

【讨论】:

    猜你喜欢
    • 2013-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-07
    相关资源
    最近更新 更多