2010-01-15 251 views

回答

20

使用Windows任务调度和运行脚本是这样的:

powershell -File myScript.ps1 -WindowStyle Hidden 

,它运行在一个特定的用户帐户和不仅当用户登录另外创建脚本。否则,你会看到一个控制台窗口。

+0

我现在,但我如何在后台运行powershell? – magol 2010-01-15 12:48:04

+0

@magol - 你需要获得多少“背景”? Windows任务调度程序是您如何运行“后台”任务,在这种情况下,该任务将启动PowerShell并运行指定的脚本。 – 2010-01-15 15:52:36

+1

好吧,公平地说,如果当前用户是管理员并且不更改任务的默认设置,那么最初的答案不会导致后台进程。但是,无论登录用户如何修复,都明确让任务运行。嗯。到目前为止,我的测试脚本运行了181次。我应该再次关闭该任务:-) – Joey 2010-01-15 15:57:45

15

也许这种情况下。我们不会每分钟都启动PowerShell可执行文件(这很贵,顺便说一下)。相反,我们通过调用一次每分钟调用一次工作脚本的额外脚本来启动它(或者在工作者脚本退出或失败后实际等待一分钟)。

创建开始调用-MyScript.ps1:

for(;;) { 
try { 
    # invoke the worker script 
    C:\ROM\_110106_022745\MyScript.ps1 
} 
catch { 
    # do something with $_, log it, more likely 
} 

# wait for a minute 
Start-Sleep 60 
} 

(从启动.bat文件如)从Cmd的运行如下命令:

start /min powershell -WindowStyle Hidden -Command C:\ROM\_110106_022745\Invoke-MyScript.ps1 

出现PowerShell窗口片刻,但它由于start /min而被最小化,并在一瞬间永久隐藏起来。所以实际上只有任务栏图标显示一会儿,而不是窗口本身。这不是太糟糕。

1

这些答案是很奇怪的! 如果你想运行PowerShell脚本作为后台作业尝试 启动工作。\文件夹中的脚本 从CLI你在内部脚本。

9

安排你的任务是运行的系统。下面的命令将安排一个脚本在后台运行,而不显示PowerShell控制台窗口:

schtasks /create /tn myTask /tr "powershell -NoLogo -WindowStyle hidden -file myScript.ps1" /sc minute /mo 1 /ru System

/ru开关可以让你改变在计划任务将被执行的用户上下文。

+0

谢谢Xemlock!在我的情况下,你的建议是唯一生成完全没有PowerShell窗口的解决方案。 – WebFixItMan 2017-03-10 19:46:27

2

在任务的任务计划程序属性的[常规]选项卡上,选择“运行用户是否已登录”单选按钮可防止窗口出现在我的Windows 7计算机上。

1

如果您想在时间间隔内自动运行脚本。 (对于Windows操作系统)

1) Open Schedule tasks from control panel. 
2) Select Task Scheduler Library from left side window. 
3) select Create Task from right side window. 
4) Enter Name in General tab (any name). 
5) Open Triggers tab -> New 
6) Select interval as needed.Use Advanced settings for repeat task. 
7) Open Actions tab ->New 
8) Copy/Paste following line in Program/script * 

* Here D:\B.ps1 in code is path to my B.ps1 file 

C:\ WINDOWS \ SYSTEM32 \ WindowsPowerShell \ V1.0 \ powershell.exe d:\ B.ps1

9) ok and apply changes 
10) Done! 
-1
# Filecheck.ps1 

# Version 1.0 

# Use this to simply test for the existance of an input file... Servers.txt. 

# I want to then call another script if the input file exists where the 

# servers.txt is neded to the other script. 

# 


    $workpath=".\Server1\Restart_Test" 

# Created a functon that I could call as part of a loop. 


    function Filecheck 

    { 
    if (test-path $workpath\servers.txt) 

     { 

     rename-item $workpath\servers.txt servers1.txt 

     "Servers.txt exist... invoking an instance of your script agains the list of servers" 


     Invoke-Expression .\your_Script.ps1 

     } 

    Else 
     { 

      "sleeping" 

      Start-Sleep -Seconds 60 
     } 

    } 

    Do 
     { 
     Filecheck 

     $fred=0 
     # Needed to set a variabe that I could check in the while loop. 

     # Probably a better way but this was my way. 

     } 

     While($fred -lt 1)