使用start-process调用其他PowerShell文件时出现问题

14

编辑::::请参见最底部的问题当前状态。

在当前的设置中,一个批处理文件通过以下方式调用PowerShell脚本:

powershell D:\path\powershellScript.v32.ps1 arg1 arg2 arg3 arg4

我想将这个内容转换成调用另一个PowerShell的PowerShell脚本。但是,我在使用"Start-Process"时遇到了问题。以下是我目前拥有的内容,但在执行时我得到了以下错误:

No application is associated with the specified file for this operation

这是正在执行的PowerShell

$powershellDeployment = "D:\path\powershellScript.v32.ps1"
$powershellArguments = "arg1 arg2 arg3 arg4"
Start-Process $powershellDeployment -ArgumentList $powershellArguements -verb runas -Wait

由于下面的帮助,我现在有了以下内容

$username = "DOMAIN\username"
$passwordPlainText = "password"     
$password = ConvertTo-SecureString "$passwordPlainText" -asplaintext -force
$cred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $username,$password

$powershellArguments = "D:\path\deploy.code.ps1", "arg1", "arg2", "arg3", "arg4"
Start-Process "powershell.exe" -credential $cred  -ArgumentList $powershellArguments
然而,当我从远程机器上执行此脚本时,尽管使用的用户名具有对该计算机的完全管理员访问权限,但仍会出现“访问被拒绝”的错误。
2个回答

25
你应该使用Start-Process powershell.exe,并将脚本的路径作为参数列表中的-File参数传递。如果你的机器没有设置默认应用程序来处理.ps1文件,则会出现No application...提示。如果你在任何.ps1文件上执行整个操作右键单击 -> 使用其他程序打开 -> 选择应用程序 -> 选中“将此程序用作默认程序...”,那么这个消息就会消失。我的默认程序是notepad,所以当我在一个.ps1上使用Start-Process时,它会在notepad中弹出。

编辑:

把所有东西放在一起...

Start-Process powershell.exe -ArgumentList "-file C:\MyScript.ps1", "Arg1", "Arg2"

或者,如果你像Keith所说的那样定义了$powershellArguments(即$powershellArguments = "-file C:\MyScript.ps1", "arg1", "arg2", "arg3", "arg4"),则可以这样:

Start-Process powershell.exe -ArgumentList $powershellArguments

我通过删除$powershellDeployment内容周围的引号来消除了“没有应用程序...”的问题。目前脚本按预期执行,但它要求参数,这意味着我尝试传递的参数没有被正确传递。 - mhopkins321
@mhopkins321 我已经更新了我的答案,向您展示完整命令的样子。我使用一个简单的脚本测试了一下,它可以正常地回显输入参数。 - SpellingD
你能否查看我对上面帖子的编辑,并看看是否能够帮助解决新问题? - mhopkins321
StackOverflow的格式真的试图限制每个问题只有一个问题,因此,我建议您打开一个新问题,并提供更详细的版本(例如确切的错误消息)。然而,我强烈建议您在网站上搜索一些其他可能是您问题重复的问题,以查看是否已经回答了您的问题。谢谢! - SpellingD
这对我也起作用了。我发现如果你犯了一个错误,反馈会非常糟糕,所以如果可以的话,你要一次尝试一个参数。在我的情况下,我正在编写我调用的脚本,所以一开始不需要任何参数,然后逐个添加。 - Kirk Liemohn

7

请将此更改为:

$powershellArguments = "arg1 arg2 arg3 arg4"

to

$powershellArguments = "arg1", "arg2", "arg3", "arg4"
-ArgumentList参数需要一个包含多个参数的数组,而不是一个包含所有参数的单个字符串。

我已经进行了更改,但仍然出现相同的错误:“没有与此操作的指定文件相关联的应用程序”。 - mhopkins321
我通过删除$powershellDeployment周围的引号使其正常工作,但是那个特定的脚本正在手动请求参数,这意味着参数更改没有起作用。 - mhopkins321

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接