包含日志功能后,Powershell脚本无法正常工作

时间:2018-05-10 15:50:28

标签: powershell

请在下面找到我的powershell脚本,该脚本用于将文件从一个文件夹移动到另一个文件夹:

    $folder = 'C:\test'
    $filter = '*.*'     
    $directory_source = $directory_source = 'C:\test1\*'                        # <-- set this according to your requirements
    $directory_target_cop = 'C:\Folder1'
    $directory_target_prop = 'C:\Folder2'
    $directory_target_dom = 'C:\Folder3'
    $LogTime = Get-Date -Format "MM-dd-yyyy"
    $dtNow =  Get-Date -Format "MM-dd-yyyy_hh-mm-ss"
    $script:loggingpathpreference = 'C:\PSLogs\'+$LogTime+".log"

    Set-PSBreakpoint -Variable Now -Mode Read -Action {Set-Variable Now (get-date -uformat '%Y\%m\%d %H:%M:%S') -Option ReadOnly, AllScope -Scope Global -Force -ErrorAction SilentlyContinue} -ErrorAction SilentlyContinue

    $fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property @{
     IncludeSubdirectories = $true              # <-- set this according to your requirements
     NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'
    }
Function Write-Log {
        [cmdletbinding()]
        Param(
            [Parameter(Position = 0, ValueFromPipeline = $true)]
            [ValidateNotNull()]
            $Message,

            [switch]$Warning
        )
        Process{
            if($Message -isnot [string]){
                $Message = $Message | Out-String
            }
            Write-Verbose $message
            Add-Content -Path $script:LoggingPathPreference -Value "`n$($dtNow) : $($Message)"
            if($Warning){
                Write-Warning $Message
            }
        }
    }

    $onCreated = Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action {
     $path = $Event.SourceEventArgs.FullPath
     $name = $Event.SourceEventArgs.Name
     $changeType = $Event.SourceEventArgs.ChangeType
     $timeStamp = $Event.TimeGenerated
     Write-Log "The file '$name' was $changeType at $timeStamp"

     try{
        $files = $(ls $directory_source)
        foreach ($file in $files) {
            if ( $(gc $file | Select-String "PROP" -Quiet) ) {
                mv -Path $file.Fullname -Destination $directory_target_prop
            } elseif ( $(gc $file | Select-String "COP" -Quiet) ) {
                mv -Path $file.Fullname -Destination $directory_target_cop 
            } elseif ( $(gc $file | Select-String "DOM" -Quiet) ) {
                mv -Path $file.Fullname -Destination $directory_target_dom 
            }
        }
     }catch{
        $ErrorMessage = $_.Exception.Message
        Write-Log $ErrorMessage 
        }
    }

现在,如果我删除了Write-Log功能,那么上面的脚本会将文件从测试文件夹移动到相应的三个文件夹,但是当我包含Write-Log功能时,上面的代码无法移动文件。 / p>

上面的代码正在进行日志记录,但没有移动文件。

我在这里做错了什么?

期待您的解决方案,并提前感谢。

0 个答案:

没有答案