如何解决仅当文件存在时,才在 PowerShell 中使用 WinSCP 从 SFTP 服务器从阵列下载文件
-
我下载了两个远程文件
Device.log
和Saveinfo.dat
;并非所有机器都有device.log
和saveinfo.dat
。有些机器只有device.log
,当我尝试使用只有device.log
的机器时,脚本失败。我能做什么?
谢谢
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 "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:\loguri\Log\Arhive\*"
$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:\loguri\Log\Arhive\Device.log","E:\loguri\Log\Arhive\SaveBVInfo.dat") {
Compress-Archive $file -DestinationPath "E:\Arhive\$inputID.zip" -Update
Remove-Item $file -Force
}
解决方法
脚本在哪里失败?我可以看到您假设文件存在的两个地方。在您调用 $session.GetFiles()
之前,您一定要先调用 $session.FileExists()
以验证它是否存在。见https://winscp.net/eng/docs/script_checking_file_existence
其次,如果存在任一文件,则您的 Test-Path
将为真,但无论是否只有一个文件,您都将两者都添加到存档中。检查每个文件,然后添加。
foreach ($file in "E:\Arhive\Device.log","E:\Arhive\Saveinfo.dat") {
if (Test-Path $file) {
Compress-Archive $file -DestinationPath "E:\Arhive\$inputID.zip" -Update
Remove-Item $file
}
}
,
您不能将 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"
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。