2017-08-07 8 views
0

ほとんどのスクリプトに共通の機能とフォーマットがあります。各スクリプトはワークステーションを貼り付けるためのウィンドウを表示し、処理前に接続をチェックするなどの基本的なタスクを実行します。一般的に、私はこのコードをコピー&ペーストして本文を修正します。私がしたいのはヘッダーとフッターですが、ステートメントブロックで "Missing closing '}'が出ます。"エラー。 。例: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 

歩近づくあなたの最終目標であるかもしれないものにあなたを得るために、あなたはあなたのinvoke-commandステートメントインへ-ComputerName "ComputerNameHere"引数を追加することもできますあなたのインクルード関数です。これにより、スクリプトはローカルではなくリモートシステム上で実行されます。

+0

Ty、これは完全に機能しました。ありがとう! – Adam

関連する問題