我正在尝试将 .ps1 文件转换为作为 Windows 服务运行。这需要作为服务运行,因为它是业务连续性的要求(计划任务不是一个选项)。我一直使用 NSSM 来包装 .ps1,因为它将通过 NSSM 作为 exe 运行。
这适用于 Windows Server 2012 中的不同脚本,但此脚本略有不同,我需要让此服务在 Windows Server 2016 上运行。脚本本身连接到大量其他服务器(总共我会有 3 项服务 - Windows 服务/Windows 进程/Linux 进程),它们在 PowerShell 中运行时都可以正常工作。
下面是脚本开头的示例,因此您可以了解它是如何工作的(可能不相关);
while ($test = 1)
{
[string]$query
[string]$dbServer = "DBSERVER" # DB Server (either IP or hostname)
[string]$dbName = "DBNAME" # Name of the database
[string]$dbUser = "CONNECTIONUSER" # User we'll use to connect to the database/server
[string]$dbPass = "CONNECTIONPASSWORD" # Password for the $dbUser
$conn = New-Object System.Data.Odbc.OdbcConnection
$conn.ConnectionString = "Driver={PostgreSQL Unicode(x64)};Server=$dbServer;Port=5432;Database=$dbName;Uid=$dbUser;Pwd=$dbPass;"
$conn.open()
$cmd = New-object System.Data.Odbc.OdbcCommand("select * from DBNAME.TABLENAME where typeofcheck = 'Windows Service' and active = 'Yes'",$conn)
$ds = New-Object system.Data.DataSet
(New-Object system.Data.odbc.odbcDataAdapter($cmd)).fill($ds) | out-null
$conn.close()
$results = $ds.Tables[0]
$Output = @()
foreach ($result in $results)
{
$Hostone = $Result.hostone
$Hosttwo = $Result.hosttwo
$Hostthree = $Result.hostthree
$Hostfour = $Result.hostfour
Write-Output "checking DB ID $($result.id)"
#Host One Check
if (!$result.hostone)
{
$hostonestatus = 17
$result.hostone = ""
}
else
{
try
{
if(Test-Connection -ComputerName $result.hostone -quiet -count 1)
{
$hostoneres = GET-SERVICE -COMPUTERNAME $result.hostone -NAME $result.ServiceName -ErrorAction Stop
$hostonestatus = $hostoneres.status.value__
$Result.HostOneCheckTime = "Last checked from $env:COMPUTERNAME at $(Get-date)"
}
else
{
$hostonestatus = 0
$result.hostonestatus = "Failed"
$Result.HostOneCheckTime = "Last checked from $env:COMPUTERNAME at $(Get-date)"
}
}
catch
{
$hostonestatus = 0
$result.hostonestatus = "Failed"
$Result.HostOneCheckTime = "Last checked from $env:COMPUTERNAME at $(Get-date) Errors Found"
}
if ($hostonestatus -eq 4)
{
$result.hostonestatus = "Running"
}
if ($hostonestatus -eq 1)
{
$result.hostonestatus = "Stopped"
}
elseif ($hostonestatus -eq 0)
{
$result.hostonestatus = "Failed"
}
}
如前所述,独立运行的确切脚本可以无缝运行。
将其作为服务运行的最佳方式是什么,或者在 Windows Server 2016 中使用 NSSM 时是否存在任何已知问题?
我还发现下面可能指向正确的方向,因为我在日志中间歇性地得到了这些;