1

I have a dictionary created from a .txt file that contains desktop links. I need these links to be plugged in to a powershell command. However when I use '%s' % my_data[key] I get extra backslashes and therefore powershell will not process the command because it has no idea what to look for, how do I remove extra backslashes?

['powershell.exe', "$sh = New-Object -COM WScript.Shell\n$sh.CreateShortcut('C:\\Users\\johns\\desktop\\python\\Survey+Update\\testing this shared.lnk\n').TargetPath"]
Deusdeorum
  • 1,426
  • 2
  • 14
  • 23

2 Answers2

1

I found that the double backslash was not the problem. for my code subprocess.Popen([r"powershell.exe", r"$sh = New-Object -COM WScript.Shell" + "\n" + "$sh.CreateShortcut(%s).TargetPath" % my_data[key]], stdout=subprocess.PIPE).communicate()[0].

The dictionary had \n at the end of each line. I used my_dict[key].replace("\n","") to get rid of it. also the path needed "path" \"%s\" fixed that. I don't know how powershell was able to handle the double backslash???? but it did

Billal Begueradj
  • 20,717
  • 43
  • 112
  • 130
0

Try using os.path.normpath as such:

dir_file = os.path.normpath("C:/Users/johns/desktop/python/Survey+Update/testing this shared.lnk")
['powershell.exe', "$sh = New-Object -COM WScript.Shell\n$sh.CreateShortcut({0}).TargetPath".format(dir_file)]
Bernardo Meurer
  • 2,295
  • 5
  • 31
  • 52
  • Okay let me try this. – John Shiveley Mar 16 '16 at 16:49
  • Dang it, let me keep trying – Bernardo Meurer Mar 16 '16 at 16:52
  • Oh and incase I did not say it enough. Thank you for taking the time. I looked for 2 days before posting. – John Shiveley Mar 16 '16 at 16:53
  • @JohnShiveley I changed my answer, see how it goes now. And you're welcome, hope I can fix this one. – Bernardo Meurer Mar 16 '16 at 16:59
  • upon second look I see that this is a different method all together. I am using a dictionary because I pulled these paths from a text file. I need each item in my dictionary to run through this powershell script. ' for key, value in my_data.iteritems(): subprocess.Popen([r"powershell.exe", "$sh = New-Object -COM WScript.Shell" + "\n" + "$sh.CreateShortcut(%s).TargetPath" % my_data[key]], stdout=subprocess.PIPE).communicate()[0] ' – John Shiveley Mar 16 '16 at 17:38
  • @JohnShiveley That's alright. I'll be honest, if that one doesn't work I have no clue what else to try. – Bernardo Meurer Mar 16 '16 at 17:59
  • That's okay thanks for your help. `I can do this now XD` – John Shiveley Mar 16 '16 at 18:14
  • If you have a chance please take a look at this http://stackoverflow.com/questions/36062041/python-capture-reply-from-powershell?noredirect=1#comment59771264_36062041 – John Shiveley Mar 18 '16 at 01:21