为什么 invoke-command 和 new-pssession 不起作用?

Why is invoke-command and new-pssession not working?

我不知道为什么这不起作用。有任何想法吗?老实说,我不知道还能尝试什么。

我打算将它添加到提示用户输入计算机名/域凭据的脚本中,但对于初学者,我无法让它在 shell window 中工作。

这是一行:

Invoke-Command -Session New-PSSession -ComputerName server001 -ScriptBlock {shutdown.exe /r -t 0} 

这是错误:

Invoke-Command : Cannot bind parameter 'Session'. Cannot convert the "New-PSSession" value of type "System.String" to
type "System.Management.Automation.Runspaces.PSSession".
At line:1 char:25
+ Invoke-Command -Session New-PSSession -ComputerName server001 -Scrip ...
+                         ~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Invoke-Command], ParameterBindingException
    + FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.InvokeCommandCommand  

很抱歉没有任何进一步补充,但我仍在努力学习 PowerShell 并需要指导。

如错误所示,-Session 参数接受类型为 PSSession 的参数 - 要创建这样的对象,我们需要 调用 New-PSSession(不只是传递它的 name 作为参数):

$session = New-PSSession -ComputerName computer01
Invoke-Command -Session $session { ... }

如果您以后不打算重用该会话,您只需将计算机名称直接传递给 Invoke-Command,它会隐式地为您处理会话管理:

Invoke-Command -ComputerName computer01 { ... }