Windows Powershell脚本独立运行,但提供';方法调用失败';作为可执行文件运行时出错

Windows Powershell脚本独立运行,但提供';方法调用失败';作为可执行文件运行时出错,windows,powershell,go,Windows,Powershell,Go,以下是获取所有已安装应用程序的powershell脚本片段: $tPatchObject = @() #initialize array #invoking the native powershell(32 bit/64 bit) $tPatchObject = &"$env:systemroot\sysnative\windowspowershell\v1.0\powershell.exe" -NonInteractive -NoProfile -Command {Get-Chil

以下是获取所有已安装应用程序的powershell脚本片段:

$tPatchObject = @() #initialize array

#invoking the native powershell(32 bit/64 bit)
$tPatchObject =  &"$env:systemroot\sysnative\windowspowershell\v1.0\powershell.exe" -NonInteractive -NoProfile -Command {Get-Childitem "HKLM://SOFTWARE//Microsoft//Windows//CurrentVersion//Uninstall//*" | Get-ItemProperty | Sort-Object DisplayName -Unique;};

#appending applications from a different path to same array
$tPatchObject += &"$env:systemroot\sysnative\windowspowershell\v1.0\powershell.exe" -NonInteractive -NoProfile -Command {Get-Childitem "HKLM://SOFTWARE//Wow6432Node//Microsoft//Windows//CurrentVersion//Uninstall//*" | Get-ItemProperty | Sort-Object DisplayName -Unique}
在Windows server 2008 R2系统上进行测试时,如果直接从powershell执行,它将提供正确的输出。但当作为Golang中编译的可执行文件的一部分执行相同的脚本时,会出现错误

方法调用失败,因为[System.Management.Automation.PSObject]不包含名为“op_Addition”的方法


仅在Windows server 2008系统上面临此问题。我的假设是,由于调用了
&“powershell.exe”

我不明白为什么要在powershell内运行的脚本中调用新的powershell会话。PowerShell的路径也错误,它应该是
$env:SystemRoot\System32\WindowsPowerShell\v1.0\PowerShell.exe
。创建数组后,应使用
+=
在每次后续注册表调用中对其进行更新,而不是像第二行中那样仅使用
=
重新分配变量

GetApps.ps1

$tPatchObject=@()
$tPatchObject+=Get-Childitem“HKLM://SOFTWARE//Microsoft//Windows//CurrentVersion////*”| Get-ItemProperty |排序对象显示名称-唯一
$tPatchObject+=Get-Childitem“HKLM://SOFTWARE//Wow6432Node//Microsoft//Windows//CurrentVersion//Uninstall//*”| Get-ItemProperty |排序对象显示名称-唯一
$tPatchObject
我不太了解Golang,但我可能会创建一个工作的PowerShell脚本,如上所述,然后从Go with执行它

stdout,stderr:=exec.Command(“powershell”、“-file”、“C:\\temp\\GetApps.ps1”).Output()
//对stdout中的输出执行一些操作。
我已经在您的问题中添加了
Go
标记。一些对围棋有更多经验的人可能会提供更好的答案

注意:若您只需要应用程序的显示名数组,则应使用
-ExpandProperty
开关,而不是尝试此操作

cmd:=`Get Childitem“HKLM://SOFTWARE//Microsoft//`
ps,u:=exec.LookPath(“powershell.exe”)
args:=append([]字符串{“-NoProfile”,“-NonInteractive”,cmd})
out,U3;:=exec.Command(ps,args…).Output()

一些澄清:1)调用新powershell是因为此执行需要使用64位shell,可执行文件默认调用32位shell。2)
$env:SystemRoot\sysnative\
用于调用相应的(32/64位)这台机器的powershell。
$env:SystemRoot\System32\
调用32位shell。3)go代码的使用方式与您描述的运行脚本的方式完全相同。4)
+=
两者都使用过,但它作为可执行文件仍然失败。我显然遗漏了一些东西,因为我不太明白为什么它对shell很重要您可以使用。正如您所知,32位和64位的注册表项都可以通过不同的注册表路径进行访问,因为您正在对它们中的每一个执行调用。我的代码仍然可以同时获得这两组应用程序。我无法进一步帮助,因为如果代码是在Powershell中自行运行的,那么Go应该能够像其他任何应用程序一样执行它r script.FYI,另一个答案没有
-File
开关。在执行PowerShell脚本时,我发现它是必须的)64位shell是必需的,因为32位shell不能提供该机器上的所有应用程序。我已经验证了这一点,它似乎是Windows问题。这可以工作,但我仍然不理解为什么从Go源代码调用它可以工作,但不能从powershell调用。