0

I currently have the following code under C:\Users\MyName\Desktop\test.py

import subprocess
command='Set-Location new_folder'
subprocess.Popen('powershell -command '+"'"+command+"'", shell=True)

What I want this to do is for the

1. "Set-Location new_folder" to be written
2. And the 'Set-Location new_folder' command is executed and the currently directory is set to new_folder, such as "C:\Users\MyName\Desktop\new_folder"

However, this is not so and just the words are inputted and doesn't react, like the picture below: enter image description here

It can be seen that the one above is not colored in yellow, and the one below is colored in yellow. The yellow one is the one I hand-coded "Set-Location new_folder", which actually works and changes the directory to the new_folder. The above one which is not colored in yellow is when I executed from the python script, and the powershell doesn't recognize it as a command...

How to fix this?

bad_coder
  • 11,289
  • 20
  • 44
  • 72
Sihwan Lee
  • 179
  • 2
  • 10

1 Answers1

1

Read the docs, especially this part:

In cmd.exe, there is no such thing as a script block (or ScriptBlock type), so the value passed to Command will always be a string. You can write a script block inside the string, but instead of being executed it will behave exactly as though you typed it at a typical PowerShell prompt, printing the contents of the script block back out to you.

A string passed to Command is still executed as PowerShell code, so the script block curly braces are often not required in the first place when running from cmd.exe. To execute an inline script block defined inside a string, the call operator & can be used:

powershell.exe -Command "& {Get-WinEvent -LogName security}"

If the value of Command is a string, Command must be the last parameter for pwsh, because all arguments following it are interpreted as part of the command to execute.

As you are calling PowerShell from Python, you have to use the above mentioned syntax. Furthermore:

So, change your PowerShell call to the following line:

subprocess.Popen(['powershell', '-Command', '& {'+command+'}'])
stackprotector
  • 10,498
  • 4
  • 35
  • 64