powershell - 选择多主机 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
解决方案
您必须用逗号、空格等分隔输入。
$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
推荐阅读
- python - playhouse.pool.MaxConnectionsExceeded:超过了多线程的最大连接数
- c# - iTextSharp 创建一个 pdf 但只写英文单词/字母
- python - 如何使用普通文本加入列
- jinja2 - 如何隐式地拥有全局自定义宏使用上下文?
- javascript - 对机器人发布的消息做出反应
- go - LeetCode 问题 Path Sum II: Recursive solution bug
- node.js - Node + Express Backend:调用第三方API
- c++ - 为 HP-35 C++ 程序实现科学函数
- python-3.x - 顶层窗口小部件在父窗口上创建
- javascript - 为什么 highcharts 不接受第二个 y 轴的数组?