【问题标题】:PowerShell calling function for telnet shows strange behavior用于 telnet 的 PowerShell 调用函数显示奇怪的行为
【发布时间】:2014-06-21 17:35:31
【问题描述】:

我有一个 telnet 脚本作为函数,如果直接调用它,它的表现很好。

如果我尝试循环调用它,它就会开始出现异常。

这段代码对我来说很好用:

$HostList = Import-CSV ".\list.csv" -Header IP,Script,SNMP -Delimiter (";") 

ForEach ($item in $HostList)
{
    Write-Host "Connecting to: $item" -NoNewline
    $Script = Get-Content (".\Scripts\" + $item.Script + ".txt") 
    Get-Telnet -RemoteHost $item.IP -SNMPLoc $item.SNMP -Login $login -PassWord $password -Commands $Script
}

以下更改似乎破坏了脚本,因为我想让控制文件更加动态:

$login = Read-Host 'Please provide the login? '
$password = Read-Host -AsSecureString 'Please provide the password? '
Import-CSV ".\list.csv" -Delimiter (";") | Foreach-Object { 
    [String[]] $VarValues = ""
    foreach ($item in $_.PSObject.Properties)
    {
        if ($item.Name.Contains("IP"))
        {
            $HostName = $item.Value
        }

        if ($item.Name.Contains("Script"))
        {
            $Script = Get-Content (".\Scripts\" + $item.Value + ".txt") 
        }

        if (!$item.Name.Contains("IP") -and !$item.Name.Contains("Script")) 
        {
            $VarValues += $item.Name + "#" + $item.Value
        }
    }

    Get-Telnet -RemoteHost $HostName -Login $login -PassWord $password -Commands $Script -Vars $VarValues
} 

如果我调用 Get-Telnet 函数是自己的,它仍然可以工作。

我不知道,控制文件 (.\list.csv) 中可能有多少列,有没有其他方法可以从文件中创建 $VarValues 列表?

【问题讨论】:

  • 我推荐你使用ifelseifelse;或者switch 来处理您的情况。你的脚本有什么错误吗?还是只是默默地失败了?

标签: powershell csv foreach telnet


【解决方案1】:

我改成>

$data = Import-CSV $ControlFile -Delimiter (";")
$OutputPath = $OutputPath + "%{0}.txt"
Clear-Host
foreach ($obj in $data) 
{
    [String[]] $VarValues = ""
    foreach ($item in $obj.psobject.properties)
    {
        $Key = $item.name
        $Value = $item.value

        switch ($Key)
        {
            "IP" { $HostName = $Value }
            "Script" { $Script = Get-Content ($ScriptPath + $Value + ".txt") }
            default { $VarValues += $Key + "#" + $Value }
        }
    }
    Get-Telnet -RemoteHost $HostName -Login $login -PassWord $password -Commands $Script -Vars $VarValues
}

这似乎可以解决问题,使用 switch 的想法让事情变得更加容易。

W2K 本身可能有些问题 - 一旦管道消失 - 一切顺利。

【讨论】:

    猜你喜欢
    • 2015-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 2020-02-06
    相关资源
    最近更新 更多