Can Powershell read code from stdin?

I am trying to start a Powershell subprocess from Python. I need to send Powershell code from Python to a child process. I'm so far away:

import subprocess
import time

args = ["powershell", "-NoProfile", "-InputFormat None", "-NonInteractive"]

startTime = time.time()
process = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

process.stdin.write("Write-Host 'FINISHED';".encode("utf-8"))

result = ''
while 'FINISHED' not in result:
    result += process.stdout.read(32).decode('utf-8')
    if time.time() > startTime + 5:
        raise TimeoutError(result)
print(result)

This time because nothing is written to stdout. I think the cmdlet Write-Hostwill never be executed. Even simple bash / Cygwin code echo "Write-Host 'FINISHED';" | powershelldoes not seem to do the job.

For comparison, sending a block of code using the flag -Commandis correct.

How can I convince Powershell to run the code I submit to stdin?

+4
source share
2 answers

Here are a few things you can consider:

  • PowerShell , script, . script . -File <FilePath> PowerShell (. docs)

  • stdin, . , , PowerShell, EOF . PowerShell, , "" stdin. , , -Command -: The value of Command can be "-", a string. or a script block. If the value of Command is "-", the command text is read from standard input. : fooobar.com/questions/1452281/...

  • , , out, err = subprocess.communicate(in)

+2

, .

:

import subprocess

args = ["powershell.exe", "-Command", r"-"]
process = subprocess.Popen(args, stdin = subprocess.PIPE, stdout =   subprocess.PIPE)

process.stdin.write(b"$data = Get-ChildItem C:\\temp\r\n")
process.stdin.write(b"Write-Host 'Finished 1st command'\r\n")
process.stdin.write(b"$data | Export-Clixml -Path c:\\temp\state.xml\r\n")
process.stdin.write(b"Write-Host 'Finished 2nd command'\r\n")

output = process.communicate()[0]

print(output.decode("utf-8"))
print("done")

. powershell -Command, "-", Jan-Philipp.

- , , . \r\n .

Powershell - . , ,

output = process.communicate()[0]

Powershell .

+2

Source: https://habr.com/ru/post/1527339/


All Articles