首页 > 解决方案 > 选择多主机 PowerShell

问题描述

我有这个ps代码。有人可以帮助我一个想法:如何键入多个主机并在多个主机上执行此脚本?

例如,我运行脚本并询问我 ID,我输入 ID 脚本试图在 db.csv 中查找 IP 以连接 ssh/sftp,但如果可以的话,我想输入更多 ID。“输入 ID:”A、B、C、D、...、X 并执行。

Add-Type -Path "C:\Program Files (x86)\WinSCP\WinSCPnet.dll"
 
$db = import-csv -Path "C:\Program Files (x86)\WinSCP\db.csv"
 
$inputID = Read-Host -Prompt "Type the ID"
 
$entry = $db -match $inputID

Write-Host "IP:" $entry.IP

    $User = "username"
    $Password = "Password"
    $Command = "C:\SaveBVInfo.exe"

    $secpasswd = ConvertTo-SecureString $Password -AsPlainText -Force
    $Credentials = New-Object System.Management.Automation.PSCredential($User, $secpasswd)

Get-SSHTrustedHost | Remove-SSHTrustedHost

$SessionID = New-SSHSession -ComputerName $entry.IP -Credential $Credentials -AcceptKey:$true

Invoke-SSHCommand -Index $sessionid.sessionid -Command $Command


# Set up session options
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
    Protocol = [WinSCP.Protocol]::Sftp
    HostName = $entry.IP
    UserName = "$User"
    Password = "$Password"
    GiveUpSecurityAndAcceptAnySshHostKey = "true"
}
 
$session = New-Object WinSCP.Session

$file = "Device.log", "SaveBVInfo.dat"
$localPath = "E:\loguri\Log\Arhive\*" 
$remotePath = "/C:/Program Files/Common Files/logs/Device.log", "/C:/Program Files/SaveBVInfo.dat"

try {
    # Connect
    $session.Open($sessionOptions)

    # Check exists files
    foreach ($remotePath in $remotePath)
{
    if ($session.FileExists($remotePath))
    {
        Write-Host "Fisierul $remotePath exista"
        
        # Transfer files

        $session.GetFiles($remotePath, $localPath).Check()
    }
    else
    {
        Write-Host "Fisierul $remotePath NU exista"
        }
    }
}
finally {
    $session.Dispose()
}

foreach ($file in "E:\loguri\Log\Arhive\Device.log", "E:\loguri\Log\Arhive\SaveBVInfo.dat") {
    if (Test-Path $file) {
    Compress-Archive $file -DestinationPath "E:\loguri\Log\Arhive\$inputID.zip" -Update
    Remove-Item $file
    }
}

谢谢 :D

标签: powershell

解决方案


您必须用逗号、空格等分隔输入。

$inputID = Read-Host -Prompt "Type the ID"
$inputID -split " "

...但是,一旦使用foreach.

$inputID = Read-Host -Prompt "Type the ID"
$grouped = $inputID -split " "
Foreach($id in $grouped){
    "This is ID: $ID"
    }

输出:

Type the ID: 1 2 3 4 5 6
This is ID: 1
This is ID: 2
This is ID: 3
This is ID: 4
This is ID: 5
This is ID: 6

推荐阅读