简体   繁体   English

如何从上下文菜单对文件运行 PowerShell 脚本?

[英]How do I run a PowerShell script on a file from the context menu?

I have written a PS script, which replaces a specific string at the beginning of the file, adds another piece of string to the end of the file, and finally it puts out an XML.我写了一个PS脚本,它在文件开头替换了一个特定的字符串,在文件末尾添加了另一段字符串,最后它输出了一个XML。

My code might be ugly (I am not a programmer/engineer or anything, just trying to make life easier for some family members who are running a small business), but it works:我的代码可能很难看(我不是程序员/工程师或其他任何人,只是想让一些经营小型企业的家庭成员的生活更轻松),但它确实有效:

$content = Get-Content -Path 'C:\Users\blabla\Desktop\4440341930.txt'
$newContent = $content -replace 'text to be replaced','this is going to replace stuff'
$newContent | Set-Content -Path 'C:\Users\blabla\Desktop\4440341930.txt'
Add-Content C:\Users\blabla\Desktop\4440341930.txt '</Items>'
$x = [xml](Get-Content "C:\Users\blabla\Desktop\4440341930.txt")
$x.Save("C:\Users\blabla\Desktop\4440341930.xml")

I would like them to be able to run this script from the context menu, by right clicking on a txt file.我希望他们能够通过右键单击 txt 文件从上下文菜单中运行此脚本。 I did a little research and I kind of get what I have to add to Registry, however, I'm not sure how to make it work.我做了一些研究,我得到了我必须添加到注册表的内容,但是,我不确定如何使它工作。 Since the path of each file that they are going to right click on is going to be different, the path that I'm specifying in $content is not going to work.由于他们要右键单击的每个文件的路径会有所不同,因此我在 $content 中指定的路径将不起作用。

What do I have to modify in my code to be able to add it to the Registry?我必须在我的代码中修改什么才能将其添加到注册表中?

To accomplish this you need to:为此,您需要:

  1. Create a Shortcut in the SendTo Folder: "$DestinationPath\AppData\Roaming\Microsoft\Windows\SendTo"在 SendTo 文件夹中创建快捷方式:“$DestinationPath\AppData\Roaming\Microsoft\Windows\SendTo”
  2. The target: "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"目标:“C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe”
  3. The Arguments: -File "d:\path\your PS1 file" Arguments:-File "d:\path\your PS1 file"
  4. In your program read the file name passed by Explorer as:在您的程序中,将 Explorer 传递的文件名读取为:
Param
(
   [Parameter(Mandatory=$false)]
     [String] $FilePath
)

I've written a Setup Function that accomplishes steps 1-3 that I include in all my programs that I want on the context menu and then just run the program with the -Setup switch.我编写了一个安装程序 Function,它完成了步骤 1-3,我将这些步骤包含在上下文菜单中我想要的所有程序中,然后使用 -Setup 开关运行程序。 We're not supposed to post developed code here, but if you can't figure it out let me know and I'll post it and hope I don't get killed for it.我们不应该在这里发布开发的代码,但是如果您无法弄清楚,请告诉我,我会发布它并希望我不会因此而被杀。 LOL!哈哈!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM