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

问题描述

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

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

这是一行:

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 { ... }