2013-04-03 63 views
1

我想知道是否有人知道如何讓PowerShell腳本在運行之前檢查自身的更新。Powershell - 在運行前檢查腳本的更新

我有一個腳本,我將分派到多臺計算機,並且不希望每次在腳本中進行更改時都必須將其重新部署到每臺計算機。我想讓它檢查某個位置,看看是否有更新的版本(如果需要,可以自行更新)。

我似乎無法想出辦法。請讓我知道是否有人可以幫忙。謝謝。

回答

3

那麼,一種方法可能是創建一個運行實際腳本的簡單批處理文件,該批處理文件中的第一行可能是檢查更新文件夾中是否存在ps1。如果有,它可以先複製它,然後啓動你的PowerShell腳本

例如。每當有更新時,你把你的「Mypowershellscript.ps1」腳本c:\temp\update\ folder

,讓我們假設你的腳本將

c:\temp\myscriptfolder\ 

運行,那麼你可以創建一個這樣

if NOT exist C:\temp\update\mypowershelscript.ps1 goto :end 

copy /Y c:\temp\update\MyPowerShellScript.ps1 c:\temp\MyScriptFolder\ 

:END 

%systemroot%\System32\WindowsPowerShell\v1.0\powershell.exe -nologo -noprofile -file "c:\temp\myscriptfolder\mypowershellscript.ps1" 
批處理文件
+0

很好的建議,我感謝幫助。 – CodingRiot 2013-04-03 20:56:06

+0

有沒有一種方法可以讓你知道在線檢查(在一個特定的URL中 - 例如「www.testserver.com/updates/powershellprogram.ps1」),如果更新文件存在,然後將它下載到目錄中?或者只能通過本地網絡資源使用 – CodingRiot 2013-04-03 21:06:45

+0

如果是這樣的話,我可能會使用Powershell而不是批處理,這對於本地和網絡文件檢查來說是很好的,但不適合通過互聯網檢查文件的存在「除非「你會使用像'wget'這樣的幫助工具來做窗口。 你可能想看看這裏[鏈接](http://stackoverflow.com/questions/4619088/windows-batch-file-file-download-from-a-url) – 2013-04-03 21:25:19

0

這是我放在一起的一個功能。將它傳遞給可能包含更新版本的文件的路徑。這將自行更新,然後重新運行任何交給原始腳本的參數。在此過程中儘早做到這一點,其他功能結果將會丟失。我通常檢查網絡上了,我看到了股份制較新的文件,然後運行這個:

function Update-Myself 
 
{ 
 
    [CmdletBinding()] 
 
    param 
 
    (
 
     [Parameter(Mandatory = $true, 
 
        Position = 0)] 
 
     [string]$SourcePath 
 
    ) 
 
    #Check that the file we're comparing against exists 
 
    if (Test-Path $SourcePath) 
 
    { 
 
    #The path of THIS script 
 
    $CurrentScript = $MyInvocation.ScriptName 
 
     if (!($SourcePath -eq $CurrentScript)) 
 
     { 
 
      if ($(Get-Item $SourcePath).LastWriteTimeUtc -gt $(Get-Item $CurrentScript).LastWriteTimeUtc) 
 
      { 
 
       write-host "Updating..." 
 
       Copy-Item $SourcePath $CurrentScript 
 
       #If the script was updated, run it with orginal parameters 
 
       &$CurrentScript $script:args 
 
       exit 
 
      } 
 
     } 
 
    } 
 
    write-host "No update required" 
 
} 
 

 
Update-Myself "\\path\to\newest\release\of\file.ps1"