我有这个脚本应该能够在远程和本地主机上运行。它接受-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/