简体   繁体   中英

Executing a simple powershell command on the command line

I try to run a simple powershell command by setting a variable and printing it.

This is what I want to do:

powershell -command "& {$name=\"hi\"; echo $name}"

But it fails with:

The string is missing the terminator: ".
   + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
   + FullyQualifiedErrorId : TerminatorExpectedAtEndOfString

The invoke operator ( & ) works fine with commands such as:

 powershell -command "& {&echo hi}"

I read about the invoking operator and how to execute commands with -command option and executing scripts with -File option etc. They are working as expected. But my attempts to do the same for setting a variable and printing it as above doesn't work. I suspect -command works with only commands . Any idea how to achieve what I do above?

from a DOS shell this works:

powershell -command "& {$name='hi'; echo $name}"

but also your code works.

From a Powershell console use this:

powershell -command {$name='hi'; echo $name}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM