2

I'm looking to pass variables from a Python script into variables of a Powershell script without using arguments.

var_pass_test.py

import subprocess, sys

setup_script = 'C:\\Users\\user\\Desktop\\Code\\Creation\\var_pass_test.ps1'

test1 = "Hello"

p = subprocess.run(["powershell.exe", 
          setup_script], test1,
          stdout=sys.stdout)

var_pass_test.ps1

Write-Host $test1

How would one go about doing this such that the Powershell script receives the value of test1 from the Python script? Is this doable with the subprocess library?

2
  • 2
    Possible duplicate of this but I'm unsure what you mean by "without using arguments". How would you pass the argument to Powershell if you were running this in Powershell instead of python? Commented May 25, 2021 at 21:53
  • 2
    I agree with @Kraigolas, you are trying to shoot without using bullets. That being said, putting the test1 into a temp file and reading that from Powershell would work, but it's fugly and just passing parameters to Powershell directly is the way to do it. Commented May 25, 2021 at 22:06

2 Answers 2

4
  • To pass arguments verbatim to the PowerShell CLI, use the -File option: pass the script-file path first, followed by the arguments to pass to the script.

  • In Python, pass all arguments that make up the PowerShell command line as part of the first, array-valued argument:

import subprocess, sys

setup_script = 'C:\\Users\\user\\Desktop\\Code\\Creation\\var_pass_test.ps1'

test1 = "Hello"

p = subprocess.run([
            "powershell.exe", 
            "-File", 
            setup_script,
            test1
          ],
          stdout=sys.stdout)
Sign up to request clarification or add additional context in comments.

Comments

0

You can also send variables to instances of PowerShell using f string formatted variables.

import subprocess
from time import sleep

var1 = 'Var1'
var2 = 'var2'

# List of values 
list_tab = ['389', '394', '399', '404', '409', '415', '444', '449', '495']

# Open PS instance for each value
for times in list_tab:
    # Use f string to send variables to PS
    subprocess.call(f'start C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe -noexit -File path_to_file.ps1 {var1} {var2}', shell=True)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.