I created a powershell script that transfers any created file (using WinSCP) to a remote server, then moves the file to another local folder. The script works perfectly; however, it needs to start on server startup. Creating a service is the best option. I can convert the PS1 file to a service using NSSM; however, when I try to start it, the status changes to PAUSE and the following error is returned: Start-Service : Failed to start service 'Doc Manager (Doc Manager)'. It must be an issue with the script as I have used this method for many scripts in the past.
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