我如何从powershell脚本调用sc创建

gyo*_*dor 15 powershell alias sc.exe

我想sc create从powershell脚本调用.这是代码.

function Execute-Command
{
    param([string]$Command, [switch]$ShowOutput=$True)
    echo $Command
    if ($ShowOutput) {
        Invoke-Expression $Command
    } else {
        $out = Invoke-Expression $Command
    }
}

$cmd="sc create `"$ServiceName`" binpath=`"$TargetPath`" displayname=`"$DisplayName`" "
Execute-Command -Command:$cmd
Run Code Online (Sandbox Code Playgroud)

这给出了以下错误:

Set-Content : A positional parameter cannot be found that accepts argument 'binpath=...'.
At line:1 char:1
Run Code Online (Sandbox Code Playgroud)

问题是什么?什么是位置参数?

Mat*_*sen 39

这里的问题不在于sc可执行文件.正如错误所述,sc解析为Set-Content.如果你发行Get-Alias -Name sc,你会看到:

gal sc

要绕过别名,请使用可执行文件的全名(包括文件扩展名):

PS C:\> sc.exe query wuauserv

SERVICE_NAME: wuauserv
        TYPE               : 20  WIN32_SHARE_PROCESS
        STATE              : 4  RUNNING
                                (STOPPABLE, NOT_PAUSABLE, ACCEPTS_PRESHUTDOWN)
        WIN32_EXIT_CODE    : 0  (0x0)
        SERVICE_EXIT_CODE  : 0  (0x0)
        CHECKPOINT         : 0x0
        WAIT_HINT          : 0x0
Run Code Online (Sandbox Code Playgroud)

您可能希望-f在构造命令行参数时使用运算符,以避免那些令人讨厌的引用 - 在整个地方转发回传:

$CmdLine = 'sc.exe create "{0}" binpath= "{1}" displayname= "{2}" ' -f $ServiceName,$TargetPath,$DisplayName
Execute-Command -Command $CmdLine
Run Code Online (Sandbox Code Playgroud)

  • 为什么是微软?为什么? (2认同)