简体   繁体   中英

How to access results of powershell.exe command in the PowerShell session?

I am trying to start PowerShell from CMD by using this command.

powershell.exe -NoProfile -NoExit -command "& {$someVar = 'test'}"

How do I access the variable someVar in the PowerShell. MSDN says that "The results of the script are returned to the parent shell as deserialized XML objects, not live objects." .

& {$someVar = 'test'}" executes the scriptblock in a local scope which is deleted when it's done executing the scriptblock.

You need to create the variable in the $global -scope (session-wide)

CMD> powershell.exe -NoProfile -NoExit -command "& {$global:someVar = 'test'}"

PS> $someVar
test

or use dot-sourcing . <script/scriptblock> . <script/scriptblock> to excecute the scriptblock, which runs everything in the current scope (session in this case)

CMD> powershell.exe -NoProfile -NoExit -command ". {$someVar = 'test'}"

PS> $someVar
test

Read more about variables scopes here

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