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

问题描述:

我想从powershell脚本调用sc create。这是代码。我如何从powershell脚本调用sc创建

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 

它提供了以下错误:

Set-Content : A positional parameter cannot be found that accepts argument 'binpath='. 
At line:1 char:1 

问题是什么?什么是位置论据?

+0

命令中的=号之后不应该有空格 – AutomatedOrder

+6

正如错误所示,sc是Set-Content的别名。使用完整的文件名'sc.exe' –

+1

从PS4开始,您可以使用'New-Service' cmdlet https://technet.microsoft.com/en-us/library/hh849830(v=wps.630).aspx – sodawillow

这里的问题不在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 

你可能想要在构建命令行参数时使用-f运算符,以避免那些令人讨厌的引用转义回头的问题:

$CmdLine = 'sc.exe create "{0}" binpath= "{1}" displayname= "{2}" ' -f $ServiceName,$TargetPath,$DisplayName 
Execute-Command -Command $CmdLine