替代在Powershell中运行外部程序

时间:2011-03-17 15:06:34

标签: .net powershell

在尝试在Powershell中运行外部程序时,我能够运行此特定行的唯一方法是使用[Diagnostics.Process]::Start()。但是,这似乎不适用于旧版操作系统,如Windows XP。还有另一种选择吗?我曾尝试过一种&符号(&)类型的跑步,但它会让我的争论更加突出。这就是我所拥有的:

$vmrc = "C:\Program Files\Common Files\VMware\VMware Remote Console Plug-in\vmware-vmrc.exe"
$vmrcArgs = "-h $($server) -p $($unencoded) -M $($moref)"

[void] [Diagnostics.Process]::Start($vmrc, $vmrcArgs)

3 个答案:

答案 0 :(得分:5)

Start-Process也应该有效。

$vmrc = "C:\Program Files\Common Files\VMware\VMware Remote Console Plug-in\vmware-vmrc.exe"  
Start-Process -FilePath $vmrc -ArgumentList "-h $($server) -p $($unencoded) -M $($moref)"

答案 1 :(得分:1)

我很幸运使用invoke-expression运行Robocopy,例如,使用大量命令行参数。

$cmd = "$vmrc$vmrcArgs"
$out = invoke-expression $cmd

答案 2 :(得分:1)

我发现这个小C程序可用于确定PowerShell对传递给外部程序的参数的作用。 (为UNICODE编译它。)

#include "windows.h"
#include "stdio.h"

int wmain(int argc, wchar_t* argv[])
{
    wprintf(L"%s\n", GetCommandLineW());

    for (int i=0; i<argc; ++i)
    {
        wprintf(L"arg[%d]: %s\n", i, argv[i]);
    }

    return 0;
}

这是你原来的例子,如果你把命令调用为:

,它可能会有用
& $vmrc -h $($server) -p $unencoded -M $moref

我说“可能”因为我不知道$ unencoded和$ moref是什么。

尝试将其作为:

调用
& $vrmr $vmrcArgs

会导致$ vmrcArgs的值被包含在外部应用程序的命令行中的引号中,因此应用程序可能会将其解释为单个参数。使用C程序,你会看到PowerShell在为外部应用程序生成命令行时如何尝试做引用决定的智能决策。

(如果你打算运行一个独立的过程,那么这个答案是不合适的。如果是这样的话,很抱歉。)