Dictionary items not working when passed through powershell command

牧云@^-^@ 提交于 2019-12-11 10:48:30

问题


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"]

回答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




回答2:


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


来源:https://stackoverflow.com/questions/36038731/dictionary-items-not-working-when-passed-through-powershell-command

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!