user12765410
user12765410

Reputation: 41

Passing Python Variables to Powershell Script

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?

Upvotes: 2

Views: 6545

Answers (2)

Pominaus
Pominaus

Reputation: 11

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)

Upvotes: 0

mklement0
mklement0

Reputation: 437708

  • 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)

Upvotes: 4

Related Questions