Powershell 使用NSSM将PS1(调用FileSystemWatcher类)转换为服务
我创建了一个powershell脚本,该脚本将任何创建的文件(使用WinSCP)传输到远程服务器,然后将该文件移动到另一个本地文件夹。剧本写得很好;但是,它需要在服务器启动时启动。创建服务是最好的选择。我可以使用NSSM将PS1文件转换为服务;但是,当我尝试启动它时,状态更改为“暂停”,并返回以下错误:启动服务:无法启动服务“文档管理器(文档管理器)”。这一定是脚本的问题,因为我在过去的许多脚本中都使用了这种方法Powershell 使用NSSM将PS1(调用FileSystemWatcher类)转换为服务,powershell,filesystemwatcher,winscp,nssm,Powershell,Filesystemwatcher,Winscp,Nssm,我创建了一个powershell脚本,该脚本将任何创建的文件(使用WinSCP)传输到远程服务器,然后将该文件移动到另一个本地文件夹。剧本写得很好;但是,它需要在服务器启动时启动。创建服务是最好的选择。我可以使用NSSM将PS1文件转换为服务;但是,当我尝试启动它时,状态更改为“暂停”,并返回以下错误:启动服务:无法启动服务“文档管理器(文档管理器)”。这一定是脚本的问题,因为我在过去的许多脚本中都使用了这种方法 using namespace System.IO # Create watch
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
您是否考虑将脚本调度到系统启动,而不是使用任务调度器?您不能通过调度器运行PS脚本。我们尝试了一种类似的方法,使用批处理文件调用ps脚本;但是,bat无法运行脚本。我们不知道为什么,“你不能通过调度程序运行ps脚本”——当然可以。如果在scheduler甚至nvvm中启动脚本时都有问题,为什么要询问nvvm而不是scheduler?调度器是为这个设计的。您是否考虑将脚本调度到系统启动,而不是使用任务调度器?您不能通过调度器运行PS脚本。我们尝试了一种类似的方法,使用批处理文件调用ps脚本;但是,bat无法运行脚本。我们不知道为什么,“你不能通过调度程序运行ps脚本”——当然可以。如果在scheduler甚至nvvm中启动脚本时都有问题,为什么要询问nvvm而不是scheduler?调度器就是为此而设计的。