Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
510 views
in Technique[技术] by (71.8m points)

alias - How do i invoke sc create from a powershell script

I want to invoke sc create from a powershell script. Here is the code.

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

which gives the following error:

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

What is the problem? What are positional arguments?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The issue here is not with the sc executable. As the error states, sc resolves to Set-Content. If you issue Get-Alias -Name sc, you'll see:

gal sc

To bypass the alias, use the full name of the executable (including the file extension):

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

You might want to use the -f operator when constructing your command line arguments, to avoid those annoying quote-escaping back ticks all over the place:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...