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?

user12765410
  • 41
  • 1
  • 5
  • 2
    Possible duplicate of [this](https://stackoverflow.com/q/4795190/11659881) 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? – Kraigolas May 25 '21 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. – Edo Akse May 25 '21 at 22:06

2 Answers2

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)
mklement0
  • 382,024
  • 64
  • 607
  • 775
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)
Pominaus
  • 1
  • 3