2010-01-15 230 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)