在PowerShell中使用WinSCP从SFTP服务器上下载阵列上的文件



我有这个PowerShell代码。

我有一个小问题:

  • 我下载两个远程文件Device.logSaveinfo.dat;不是所有的机器都有device.logsaveinfo.dat。有些机器只有device.log,当我在只有device.log的机器上尝试时,脚本失败了。我能做什么?

  • 如果机器有两个文件存档在一起,如果机器只有device.log存档文件(device.log)。

谢谢你
Add-Type -Path "C:Program Files (x86)WinSCPWinSCPnet.dll"

$db = import-csv -Path "C:Program Files (x86)WinSCPdb.csv"

$inputID = Read-Host -Prompt "ID"

$entry = $db -match $inputID
Write-Host "IP:" $entry.IP
$User = "user"
$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:loguriLogArhive*"
$remotePath = "/C:/Program Files/Common Files/logs/Device.log", "/C:/Program Files/Pc/SaveBVInfo.dat"

try {
# Connect
$session.Open($sessionOptions)
# Check files exists

if ($session.FileExists($remotePath))
{
Write-Host "File $remotePath exists"
# Transfer files
$session.GetFiles($remotePath, $localPath).Check()

exit 0
}
else
{
Write-Host "File $remotePath does not exist"
exit 1
}
}
finally {
$session.Dispose()
}
foreach ($file in "E:loguriLogArhiveDevice.log", "E:loguriLogArhiveSaveBVInfo.dat") {
Compress-Archive $file -DestinationPath "E:Arhive$inputID.zip" -Update
Remove-Item $file -Force
}

不能将PowerShell数组传递给不接受数组的。net方法。

你必须循环处理你的文件:

$remotePaths = "/C:/Program Files/Common Files/logs/Device.log", "/C:/Program Files/Pc/SaveBVInfo.dat"
foreach ($remotePath in $remotePaths)
{
if ($session.FileExists($remotePath))
{
Write-Host "File $remotePath exists"
# Transfer files
$session.GetFiles($remotePath, $localPath).Check()
}
else
{
Write-Host "File $remotePath does not exist"
}
}

脚本在哪里失败?我能看到两个你认为文件存在的地方。在调用$session.GetFiles()之前,应该首先调用$session.FileExists()来验证它是否存在。见https://winscp.net/eng/docs/script_checking_file_existence

其次,如果存在任何一个文件,则Test-Path将为真,但是无论是否只有一个文件,都将这两个文件添加到存档中。检查每个文件,然后添加。

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

最新更新