【问题标题】:Run a powershell script inside a windows service在 Windows 服务中运行 powershell 脚本
【发布时间】:2014-11-12 15:20:57
【问题描述】:

我有一个运行良好的 powershell 脚本, 我在 power shelle 命令行中调用这个脚本:

PS C:> .\myscript.ps1 -var1 variable1 -var2 variable2 

我需要使用愚蠢的 sc create 将其安装在服务中,但我找不到启动它的方法

有什么帮助吗?

非常感谢。

【问题讨论】:

标签: powershell windows-services


【解决方案1】:

使用Windows service wrapper。它是高度可配置的,并提供了许多有用的选项,如日志轮换、服务帐户、失败操作等。它甚至可以自动从 URL 下载资源并将其作为文件放置在本地,因此您可以将脚本托管在某个地方并自动更新。以下是启动和运行 PowerShell 服务的基本步骤:

  1. 下载\构建winsw。可以在here 找到版本 1.x 的二进制文件。要构建最新的winsw 2.x,请使用Visual Studio Community 2013(开源项目免费)。更详细的构建说明是here
  2. 为您的服务创建 XML 配置文件。示例:

    <service>
        <id>MyPsSvc</id>
        <name>My PowerShell Service</name>
        <description>Does funny stuff with your PC</description>
        <executable>PowerShell.exe</executable>
        <logmode>reset</logmode>
        <arguments>-ExecutionPolicy Bypass -NoLogo -NoProfile -NonInteractive -WindowStyle Hidden -File "myscript.ps1" -var1 variable1 -var2 variable2</arguments>
    </service>
    

    配置文件必须与winsw可执行文件具有相同的基本名称,即:

    • winsw.exe
    • winsw.xml
  3. 如果您打算在没有 Internet 连接的情况下在 PC 上使用您的服务,请disable digital signature verification for winsw。为此,请创建文件 winsw.exe.config。示例:

    <configuration>
      <runtime>
        <generatePublisherEvidence enabled="false"/> 
      </runtime>
    </configuration>
    
  4. 如果您运行的是 Windows Server 2012 或 Windows 8,并且不想安装 .Net 2.0 支持,请在上述配置文件中specify .NET 4.0 runtime support

    <configuration>
        <runtime>
            <generatePublisherEvidence enabled="false"/> 
        </runtime>
        <startup>
            <supportedRuntime version="v2.0.50727" />
            <supportedRuntime version="v4.0" />
        </startup>
    </configuration>
    
  5. 安装您的服务,从命令行运行winsw.exe install。安装服务后,您可以从 Windows 服务管理器启动它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-17
    • 1970-01-01
    • 1970-01-01
    • 2013-08-22
    • 1970-01-01
    • 2017-08-17
    • 2017-04-09
    • 2010-11-09
    相关资源
    最近更新 更多