Windows可执行文件无法看到PowerShell命令的输出

时间:2018-03-21 14:27:15

标签: powershell

这有效:

PS> $serviceName = Get-WmiObject Win32_service -filter "displayname = 'Security Center'" |select -expandproperty name
PS> sc.exe start $serviceName

这并不是 - 好像管道变量$_没有传递给sc.exe

PS> Get-WmiObject Win32_service -filter "displayname = 'Security Center'" |select -expandproperty name |sc.exe start "$_"
DESCRIPTION:
        Starts a service running.
USAGE:
        sc <server> start [service name] <arg1> <arg2> ...

我缺少什么让这项工作成为一名oneliner?我已经尝试了几乎所有我能想到的东西(scriptblocks et cetera),但似乎没有任何成功。

1 个答案:

答案 0 :(得分:2)

$_不会在调用范围内神奇地工作。将sc.exe语句换行到ForEach-Object scriptblock:

Get-WmiObject Win32_service -filter "displayname = 'Security Center'" |select -expandproperty name |ForEach-Object {
  sc.exe start "$_"
}