我有这个PowerShell代码。好工作。但是当我向db.csv
添加更多行时,它不起作用并返回错误代码:
Exception calling "Open" with "1" argument(s): "Connection has been unexpectedly closed. Server sent command exit status 0.
Authentication log (see session log for details):
Using username "username".
Authentication failed."
At C:UsersmeDesktoptesteScriptCollectLog.ps1:41 char:5
+ $session.Open($sessionOptions)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : SessionRemoteException
例如,当我在db.csv
中只有两行时,脚本工作得很好
HostName,IP
name1,10.10.1.1
name2,10.10.1.2
我尝试在CSV文档中使用19个主机名和Ip地址行并工作,但是当我只添加1个停止工作时。
19作品20+不行
任何想法?(谢谢你,对不起我的英语)
Add-Type -Path "WinSCPnet.dll"
$Name = @()
$ip = @()
Import-Csv db.csv |`
ForEach-Object {
$Name += $_.HostName
$ip += $_.IP
}
$inputID = Read-Host -Prompt "Type ID"
if ($Name -contains $inputID)
{
$Where = [array]::IndexOf($Name, $inputID)
Write-Host "IP: " $ip[$Where]
}
# Set up session options
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
Protocol = [WinSCP.Protocol]::Sftp
HostName = "$ip"
UserName = "username"
Password = "password"
GiveUpSecurityAndAcceptAnySshHostKey = "true"
}
$session = New-Object WinSCP.Session
try
{
# Connect
$session.Open($sessionOptions)
# Transfer files
$session.GetFiles("/C:/Program Files/Common Files/logs/Device.log", "E:loguriLogArhive*").Check()
}
finally
{
$session.Dispose()
}
Compress-Archive -Path "E:loguriLogArhiveDevice.log" -DestinationPath "E:loguriLogArhive$inputID.zip" -Update
Remove-Item -Path "E:loguriLogArhiveDevice.log" -Force
正如Theo所说,您不需要像您那样将CSV拆分为两个数组。像这样导入
$db = import-csv 'db.csv'
您可以访问每一行作为$db[0]
,$db[1]
和每一列从您的CSV将是一个属性,例如$db[0].Hostname
和$db[0].IP
读入输入后,只需要从数组$db
中选择条目。也许像这样。但是,无论是您的代码还是我的代码都没有涵盖不匹配的情况!
$entry = $db -match $inputID
那么你的会话将被这样定义
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
Protocol = [WinSCP.Protocol]::Scp
HostName = $entry.ip
UserName = "username"
Password = "password"
GiveUpSecurityAndAcceptAnySshHostKey = "true"
}
说了这么多,给出的错误信息显示用户名/密码和ip的组合是无效的。
Add-Type -Path "WinSCPnet.dll"
$db = import-csv 'db.csv'
$inputID = Read-Host -Prompt "Type ID"
$entry = $db -match $inputID
# Set up session options
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
Protocol = [WinSCP.Protocol]::Sftp
HostName = $entry.IP
UserName = "username"
Password = "password"
GiveUpSecurityAndAcceptAnySshHostKey = "true"
}
$session = New-Object WinSCP.Session
try {
# Connect
$session.Open($sessionOptions)
# Transfer files
$session.GetFiles("/C:/Program Files/Common Files/logs/Device.log", "E:loguriLogArhive*").Check()
}
finally {
$session.Dispose()
}
if (Test-Path "E:loguriLogArhiveDevice.log") {
Compress-Archive -Path "E:loguriLogArhiveDevice.log" -DestinationPath "E:loguriLogArhive$inputID.zip" -Update
Remove-Item -Path "E:loguriLogArhiveDevice.log" -Force
}