powershell - 如果ComputerName是localhost或 '.',则将powershell脚本作为本地脚本运行

标签 powershell powershell-remoting

我有这个脚本应该能够在远程和本地主机上运行。它接受-ComputerName作为带有'。'的参数。 (localhost)作为默认值。

目前,我正在测试如何验证新的远程 session ,并为此编写了一个小cmdlet。问题是,如果我使用“。”运行此脚本,或localhost作为ComputerName,脚本尝试连接到我的计算机上的新远程 session 。由于我未启用PSRemoting,因此无法使用。

这是我的测试脚本:

Function Test-PsRemoting {
[CmdletBinding()]
param(
    $ComputerName = ".",
    $Credentials    
)

$ErrorActionPreference = "Stop"

Test-Connection -ComputerName $ComputerName -Count 1 | 
    Format-List -Property PSComputerName,Address,IPV4Address,IPV6Address

Test-WSMan $ComputerName

$session = New-PSSession -ComputerName $ComputerName -Credential $Credentials
Invoke-Command -ComputerName $computername { 1 }
}

所有命令Test-WSMan,New-PSSession和Invoke-Command都会失败,因为它们假设我要建立远程连接

如果$ ComputerName为',是否可以让Powershell在本地 session 中运行命令。还是localhost还是必须自己在if / else子句中处理呢?

该脚本旨在在本地和远程计算机上运行,​​并且我不希望启用PSRemoting成为在本地运行脚本的要求

最佳答案

AFAIK没有$localsession -variable。您可以使用if-tests:

Function Test-PsRemoting {
    [CmdletBinding()]
    param(
        $ComputerName = ".",
        $Credentials    
    )

    $ErrorActionPreference = "Stop"

    $remote = $ComputerName -notmatch '\.|localhost'
    $sc = { 1 }

    #If remote computer, test connection create sessions
    if($remote) {
        Test-Connection -ComputerName $ComputerName -Count 1 | 
            Format-List -Property PSComputerName,Address,IPV4Address,IPV6Address

        Test-WSMan $ComputerName

        $session = New-PSSession -ComputerName $ComputerName -Credential $Credentials
    }

    if($remote) {
        #If remote computer
        Invoke-Command -ComputerName $computername -ScriptBlock $sc
    } else { 
        #Localhost
        Invoke-Command -ScriptBlock $sc
    }

}

关于powershell - 如果ComputerName是localhost或 '.',则将powershell脚本作为本地脚本运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25554449/

相关文章:

powershell - 在远程 session 中启动后台任务,当 session 被删除时不会被终止

powershell - 从数组列表中删除一个 hastable

powershell - 使用 C# API 连接到 Powershell Remoting

powershell - 在远程计算机上运行本地函数?

powershell - 无需外部工具即可设置新的 Azure 虚拟机

Powershell Test-NetConnection 在循环脚本中返回 False

json - VMWare对象上的ConvertTo-Json不起作用

regex - 带有命名组的替换字符串中的 Powershell 变量

Powershell 4.0 Transcript 未捕获 Write-Host 语句的输出