1

我创建了一个 powershell 脚本,它将任何创建的文件(使用 WinSCP)传输到远程服务器,然后将文件移动到另一个本地文件夹。该脚本完美运行;但是,它需要在服务器启动时启动。创建服务是最好的选择。我可以使用 NSSM 将 PS1 文件转换为服务;但是,当我尝试启动它时,状态变为 PAUSE 并返回以下错误: Start-Service : Failed to 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
4

0 回答 0