【发布时间】:2018-03-02 06:57:31
【问题描述】:
我希望在 .ps1 文件中包含一些代码,以创建可在其他 .ps1 脚本中使用的 PSSession(以避免代码重复)。
起初我以为我需要一个创建 PSSession 并返回它的函数,但我对函数输出的工作方式感到困惑。
这是我的功能:
function newRemoteSession
{
param([string]$ipAddress)
$accountName = 'admin'
$accountPassword = 'admin'
$accountPasswordSecure = ConvertTo-SecureString $accountPassword -AsPlainText -Force
$accountCredential = New-Object System.Management.Automation.PSCredential ($accountName, $accountPasswordSecure)
Try
{
$remoteSession = New-PSSession -ComputerName $ipAddress -UseSSL -Credential $accountCredential -SessionOption (New-PSSessionOption -SkipCACheck -SkipCNCheck) -ErrorAction Stop
}
Catch [System.Management.Automation.RuntimeException] #PSRemotingTransportException
{
Write-Host 'Could not connect with default credentials. Please enter credentials...'
$remoteSession = New-PSSession -ComputerName $ipAddress -UseSSL -Credential (Get-Credential) -SessionOption (New-PSSessionOption -SkipCACheck -SkipCNCheck) -ErrorAction Stop
Break
}
return $remoteSession
}
但是当我打电话给$s = newRemoteSession(192.168.1.10) 时,$s 是空的。
当我运行脚本时
Write-Host '00'
$s = newRemoteSession('192.168.1.10')
$s
Write-Host '02'
function newRemoteSession
{
........
Write-Host '01'
$remoteSession
}
我在控制台中只得到“00”,但我知道该函数运行,因为我得到了凭据提示。
编辑:
好的,现在可以了:
- 捕捞中断正在阻止一切。
- 函数调用必须不带括号。
- 第二个代码错误,因为函数必须在调用之前定义。
【问题讨论】:
-
如果你把函数放在你试图调用它的同一个文件中,它会起作用吗?
-
运行
$s = newRemoteSession '192.168.1.10'不带括号。 -
$s = newRemoteSession '192.168.1.10'和$s = newRemoteSession -ipAddress '192.168.1.10'得到相同的结果 -
尝试从你的 catch 块中去掉限定符
-
第二个块是完整的脚本吗?该函数需要在调用之前定义。正如@JosefZ 所说,您还需要从函数调用中删除括号。如果可能,尝试在 PowerShell_ISE 中编写脚本,然后逐步调试。您也不需要在
catch块中休息。
标签: powershell syntax control-flow