微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用NSSM将PS1调用FileSystemWatcher类转换为服务

如何解决使用NSSM将PS1调用FileSystemWatcher类转换为服务

我创建了一个powershell脚本,该脚本将任何创建的文件(使用WinSCP)传输到远程服务器,然后将文件移动到另一个本地文件夹。该脚本运行完美;但是,它需要在服务器启动时启动。创建服务是最好的选择。我可以使用NSSM将PS1文件转换为服务;但是,当我尝试启动它时,状态变为PAUSE,并返回以下错误:Start-Service:无法启动服务'Doc Manager(Doc Manager)'。脚本一定是有问题的,因为我过去在许多脚本中都使用过这种方法

using namespace System.IO

# Create watcher
$fsw = [FileSystemWatcher]::new("C:\PowerShell\DocSource")
$fsw.NotifyFilter =
[NotifyFilters]::LastAccess,[NotifyFilters]::LastWrite,[NotifyFilters]::FileName,[NotifyFilters]::DirectoryName

# Define handler methods
$handler_OnChanged =
{
    param([object] $source,[FileSystemEventArgs] $e)
        
        # Load WinSCP .NET assembly
        Add-Type -Path "C:\Program Files (x86)\WinSCP\WinSCPnet.dll"

        # Set up session options
        $sessionoptions = New-Object WinSCP.Sessionoptions -Property @{
            Protocol = [WinSCP.Protocol]::Sftp
            HostName = "SOMEIPADDRESS"
            UserName = "sftpuser"
            Password = "SOMEPASSWORD"
            SshHostKeyFingerprint = "ssh-rsa 2048 SOMEKEY"
            Timeout = new-timespan -minutes 1
        }

        $session = New-Object WinSCP.Session

        try
        {
            # Connect
            $session.DebugLogPath = "C:\PowerShell\Scripts\docs.log"
            $session.Open($sessionoptions)

            $source = "C:\PowerShell\DocSource\*"
            $destination = "C:\PowerShell\DocDestination\"   
            
            # Set Options
            $transferOptions = New-Object WinSCP.TransferOptions
            $transferOptions.TransferMode = [WinSCP.TransferMode]::Binary  

            # Transfer cp files
            $session.PutFiles($source,"/files/*",$False,$transferOptions).Check()

            # Move files from source to destination
            Get-ChildItem -Path $source -Recurse | ForEach-Object {   
                $nextName = Join-Path -Path $destination -Childpath $_.name
                Move-Item -Path $_.FullName -Destination $nextName -Force
            } 
            
        }
        finally
        {
            $session.dispose()
        }

}

# Wire of event handlers
Register-ObjectEvent -InputObject $fsw -EventName Created -Action $handler_OnChanged

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。