Powershell:为SSL和NOSSL连接构建动态invoke-command

时间:2017-10-13 14:16:19

标签: powershell

我们的服务器设置类型为WinRM连接安全且正常。

我需要建立一个带或不带-usessl开关的远程PowerShell连接。

我想避免使用两个相同的脚本块,唯一的区别是是否有-usessl开关。

我尝试使用参数splatting但是无法处理 -usessl开关,也尝试使用invoke-expression但是它破坏了检索数据的能力;来自远程作业的哈希值。

有什么建议吗?

if (test-wsman -ErrorAction SilentlyContinue -cn "$($Cmpname.name).sample.com" –UseSSL ) {
Write-host $Cmpname.name,WSMan Connected SSL 
$strWSMAN = "SSL"
$strRemoteHash = invoke-command -cn "$($Cmpname.name).sample.com" -usessl  -scriptblock {
        Write-host "calculating Hash values"
        $strLocalhash = Get-ChildItem -Path "c:\Windows\ccmcache" -Filter "Windows10.0-KB4041691-x64.cab" -Recurse -ErrorAction SilentlyContinue -Force | Get-FileHash -Algorithm sha1

    New-Object pscustomobject -Property @{
    RemotePath = $strLocalhash.path 
    RemoteHash = $strLocalhash.hash 
    }
    }

}  else {   
    $strWSMAN = "NoSSL"
    $strRemoteHash = invoke-command -cn "$($Cmpname.name).sample.com" -scriptblock {
    Write-host "calculating Hash values"
    $strLocalhash = Get-ChildItem -Path "c:\Windows\ccmcache" -Filter "Windows10.0-KB4041691-x64.cab" -Recurse -ErrorAction SilentlyContinue -Force | Get-FileHash -Algorithm sha1

    New-Object pscustomobject -Property @{
    RemotePath = $strLocalhash.path 
    RemoteHash = $strLocalhash.hash 
    }
    }
    }

1 个答案:

答案 0 :(得分:0)

作为mjolinor said,你需要在splatting时为switch参数提供一个布尔值:

$ParameterValues = @{
    ComputerName = "$($Cmpname.name).sample.com"
    UseSSL = [bool](Test-WSMan -ErrorAction SilentlyContinue -ComputerName "$($Cmpname.name).sample.com" –UseSSL)
    ScriptBlock = {
        Write-host "calculating Hash values"
        $strLocalhash = Get-ChildItem -Path "c:\Windows\ccmcache" -Filter "Windows10.0-KB4041691-x64.cab" -Recurse -ErrorAction SilentlyContinue -Force | Get-FileHash -Algorithm sha1

        New-Object pscustomobject -Property @{
            RemotePath = $strLocalhash.path 
            RemoteHash = $strLocalhash.hash 
        }
    }
}
Invoke-Command @ParameterValues