Powershell脚本在远程执行期间失败但在本地运行

时间:2018-03-06 22:18:59

标签: powershell powershell-v2.0 powershell-remoting

我正在尝试执行以下代码。错误是不言自明的,但只有在远程运行时才会发生。在本地运行时,所有代码都可以工作,我可以通过从需要Tls12的Web服务器中提取内容并在未更改安全协议时收到错误来验证它们是否具有所需的效果。

$tls12 = [Enum]::ToObject([Net.SecurityProtocolType], 3072)
[Net.ServicePointManager]::SecurityProtocol = $tls12

在服务器上运行时,它们执行得很完美。通过Invoke-Command远程运行时,我收到此错误。

Exception setting "SecurityProtocol": "The requested security protocol
is  not supported."
+ CategoryInfo          : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyAssignmentException
+ PSComputerName        : servername

或者,这行代码基本相同。

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

这在直接在服务器上运行时也有效,但在远程运行时会导致此错误。

Exception setting "SecurityProtocol": "Cannot convert null to type
 "System.Net.SecurityProtocolType" due to invalid enumeration values. Specify one of the following enumeration values and 
try again. The possible enumeration values are "Ssl3, Tls"."
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyAssignmentException
+ PSComputerName : servername

远程服务器Windows Server 2008 R2并且正在运行powershell 2.0。安装的最新Framework版本是4.5版本378389.我正在执行的机器是运行PowerShell 5.0和Framework 4.6.2的Windows 10,以防万一。

这是我用来远程执行它的代码。

$webSession = New-PsSession -ComputerName servername

$cmd = {
    #$tls12 = [Enum]::ToObject([Net.SecurityProtocolType], 3072)
    #[Net.ServicePointManager]::SecurityProtocol = $tls12
    [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
}

Invoke-Command -ScriptBlock $cmd -Session $webSession
remove-pssession  $webSession

如果有人有想法或建议,我将非常感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

[ 注意:此答案的其余部分应为真,但ISN' T :即使Tls12值不是在交互式PSv2会话中定义,可以分配生效使用OP的解决方法,{{ 1}};相比之下,通过 PS remoting 尝试相同的事情,使用[Net.ServicePointManager]::SecurityProtocol = [Enum]::ToObject([Net.SecurityProtocolType], 3072) 失败了升级目标计算机上的PowerShell可能仍然是答案,但此答案提供了无解释的行为。]

正如Sambardo在对该问题的评论中所述,症状表明远程目标计算机不支持Invoke-Command -ComputerName值:

PSv2 总是使用.NET框架的Tls12版本,其中不支持TLS 1.2 - 无论是否存在 newer < / em>给定计算机上的.NET框架。

如果您使用PSv2 在计算机上运行2.0,您将看到只支持以下值:

[enum]::GetNames([Net.SecurityProtocolType])

所以答案是升级远程计算机上的PowerShell

顺便说一句:PowerShell在类型转换方面具有很大的灵活性,您只需使用# PSv2 > [enum]::GetNames([Net.SecurityProtocolType]) Ssl3 Tls 值的字符串表示;例如,以下两个陈述是等价的:

[enum]