我正在毁掉我的大脑" Test-Path"条件。帮助将非常感激。这就是我想要做的事情:
这些都是步骤,如果没有" .csv" FTP中的文件,它必须记录文件已被复制到共享。
我删除了记录的评论,因为它是法语。如果需要,我可以重新发布完整的代码。评论只是回声"一些blabla" >> $日志
总之... 无论我做什么,代码都会通过" IF"条件,它总是正确的!即使没有" .csv" FTP上/ OUT /文件夹中的文件 该剧本永远不会通过" ELSE"一部分。
我真的很感激一些帮助,因为我对此感到生气,因为我不明白出了什么问题
我很确定这是我看不到的非常明显的事情。
以下是代码:
$date = Get-Date
$datef = Get-Date -format yyyy_MM_dd@HH-mm-ss
$distant = "/OUT/"
$checkdistant = Test-Path -Path $distant | Where-Object { (-not $_.IsDirectory) -and ($_.Name -ne "*.csv")}
$localfile = "\\myshare\*.csv"
$log = New-Item -Path c:\Logs\ -ItemType file -Name Log_Out$($datef).txt
Add-Type -Path "C:\scripts\WinSCP\WinSCPnet.dll"
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
Protocol = [WinSCP.Protocol]::Sftp
HostName = ""
UserName = ""
Password = ""
SshHostKeyFingerprint = ""
}
$session = New-Object WinSCP.Session
$session.SessionLogPath = "c:\Logs\$(((get-date).ToLocalTime()).ToString("yyyy_MM_dd@HH-mm-ss"))_FTP_Session.log"
$sessionftp = $session.SessionLogPath
try
{
$session.Open($sessionOptions)
$dir = $session.ListDirectory($distant)
foreach ($fileInfo in $dir.Files)
{
$remotedir = ($fileInfo.FullName + " " + " " + $fileInfo.LastWriteTime)
$remotedir >> $log
}
if ($checkdistant = $true)
{
$session.GetFiles("/OUT/*", "\\myshare\").Check
$ls = ls $localfile
$ls >> $log
echo "$date "files copied OK to \\myshere" >> $log
$session.RemoveFiles( 'OUT/*.csv' )
}
else
{
echo "`r$date my blabla to my log" >> $log
}
}
finally
{
$session.Dispose()
exit 0
}
答案 0 :(得分:2)
有几个问题。
=
代替-eq
这是一个经典/常见的PowerShell错误。
If ($checkdistant = $true) { }
是将$checkdistant
设置为true,然后评估它是否为真(总是如此)。你需要这样做:
If ($checkdistant -eq $true) { }
您也可以这样做:
If ($checkdistant) { }
因为有任何价值,所以这是真的。
这不像你想象的那样有效:
$checkdistant = Test-Path -Path $distant | Where-Object { (-not $_.IsDirectory) -and ($_.Name -ne "*.csv")}
因为Test-Path
返回true / false结果,然后您将传递给Where-Object以过滤它是否不是目录而不是扩展名为.csv的文件。
你可能想要这样做:
$distant = (Get-ChildItem -Path "/OUT/" | Where-Object { (-not $_.IsDirectory) -and ($_.Name -ne "*.csv")}).FullName
$checkdistant = Test-Path -Path $distant
这使用Get-ChildItem
获取与您的过滤条件匹配的文件的.FullName
属性,然后将该列表与Test-Path
一起使用。
我认为您实际上可以通过以下方式进一步简化:
$distant = (Get-ChildItem -Path "/OUT/" -Directory -Exclude *.csv).FullName