2017-08-07 63 views
0

我對大多數腳本都有通用的功能和格式。每個腳本都會爲我提供一個粘貼工作站的窗口,並在繼續之前執行基本任務,如檢查連接。通常,我複製並粘貼此代碼並修改主體。我想要做的是包含一個頁眉和頁腳,但是我在「聲明塊」中收到「錯過關閉」}。「錯誤。例如:使用PowerShell在頁眉/頁腳中包含常用代碼

<# Begin Header #> 
if($canceled) { 
    write-host "Operation canceled." 
} 
else { 
    if($computers.length -gt 0) { 
     [array]$computers = $computers.split("`n").trim() 

     # Loop through computers entered 
     foreach($pc in $computers) { 
      # Skip zero length lines for computers 
      if(($pc.length -eq $null) -OR ($pc.length -lt 1)) { 
       continue 
      } 
      else { 
       # Try to connect to the computer, otherwise error and continue 
       write-host "Connecting to: $pc$hr" 
       if(test-connection -computername $pc -count 1 -ea 0) { 
        <# End Header #> 

        Body of script 

        <# Begin Footer #> 
       } 
       else { 
        utC# Unable to contact 
       } 
      } 
      write-host "`n" 
     } 
    } 
} 
<# End Footer #> 

而不是複製/每次粘貼,我寧願做這個...

「C:\腳本\ header.ps1」。

- 代碼 - 。

「C:\腳本\ footer.ps1」

是,即使有可能當標題與開括號結束?我在PHP中這樣做,但我無法弄清PowerShell中的變通方法。

回答

2

可以將您的方法更改爲將函數存儲在一個文件中,並將您的自定義腳本運行用於另一個文件中的每個服務器。您可以在PowerShell中將腳本塊存儲到變量中,並將其作爲參數傳遞給函數。您可以使用Invoke-Command -scriptblock $Variable來執行該代碼。

寫你的函數是這樣的:

function runAgainstServerList { 
    param ([ScriptBlock]$ScriptBlock) 
    if($canceled) { 
     write-host "Operation canceled." 
    } 
    else { 
     if($computers.length -gt 0) { 
      [array]$computers = $computers.split("`n").trim() 

      # Loop through computers entered 
      foreach($pc in $computers) { 
       # Skip zero length lines for computers 
       if(($pc.length -eq $null) -OR ($pc.length -lt 1)) { 
        continue 
       } 
       else { 
        # Try to connect to the computer, otherwise error and continue 
        write-host "Connecting to: $pc$hr" 
        if(test-connection -computername $pc -count 1 -ea 0) { 

         Invoke-Command -ScriptBlock $ScriptBlock 

        } 
        else { 
         utC# Unable to contact 
        } 
       } 
       write-host "`n" 
      } 
     } 
    } 
} 

現在關閉保存到你包括像文件「myFunctions.ps1」

然後創建要這樣每臺服務器運行您的自定義腳本:

. myFunctions.ps1 

[ScriptBlock]$ScriptBlockToPass = { 
    ## Insert custom code here 
} 

runAgainstServerList $ScriptBlockToPass 

爲了讓你更接近了一步什麼可能是你的最終目標,你可能希望將-ComputerName "ComputerNameHere"參數追加到invoke-command聲明插件請參閱您的包含功能。這會導致腳本在遠程系統上執行,而不是在本地執行。

+0

Ty,工作完美。謝謝! – Adam