2015-02-11 73 views
0

我已經寫了一個PowerShell腳本來通知我的程序創建文件時。 (注:我公司提供的代碼以供參考,但我不知道有什麼不好的代碼)瞭解powershell會話

$folder = 'C:\Dev\Repositories\HD-CMC\trunk\XE5\IRBatch\JOAPSpectra' 
$filter = '*.sp' 

$fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property @{IncludeSubdirectories = $false;NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'} 

Function Send-StringOverTcp 
( 
    [Parameter(Mandatory=$True)][String]$DataToSend, 
    [Parameter(Mandatory=$True)][UInt16]$Port 
) 
{ 
    Try 
    { 
     $ErrorActionPreference = "Stop" 
     $TCPClient = New-Object Net.Sockets.TcpClient 
     $IPEndpoint = New-Object Net.IPEndPoint([System.Net.IPAddress]::parse("127.0.0.1"), $Port) 
     $TCPClient.Connect($IPEndpoint) 
     $NetStream = $TCPClient.GetStream() 
     [Byte[]]$Buffer = [Text.Encoding]::ASCII.GetBytes($DataToSend) 
     $NetStream.Write($Buffer, 0, $Buffer.Length) 
     $NetStream.Flush() 
    } 
    Finally 
    { 
     If ($NetStream) { $NetStream.Close() } 
     If ($TCPClient) { $TCPClient.Close() } 
     If ($IPEndpoint) { $IPEndpoint.Close() } 
    } 
} 

Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action{ 
$name = $Event.SourceEventArgs.Name 
$changeType = $Event.SourceEventArgs.ChangeType 
$timeStamp = $Event.TimeGenerated  
Send-StringOverTcp -DataToSend 'file created' -Port 22} 

它,當我在PowerShell中運行它工作正常。

Powershell

不過,我需要能夠以編程方式調用此腳本,而不是它,我希望它每次運行復制粘貼到外殼。

我試着從一個命令行

即調用腳本:

Powershell.exe -executionpolicy remotesigned -File NotifyFileCreate.ps1 

我試圖寫一個C#程序調用腳本。

using System; 
using System.Management.Automation; 
using System.Collections; 
using System.Collections.ObjectModel; 
using System.IO; 
using System.Management.Automation.Runspaces; 
using System.Text; 
using System.Diagnostics; 
using System.Collections.Generic; 

namespace PowershellInvoker 
{ 
    class MainClass 
    { 
     public static void Main (string[] args) 
     { 
      String[] lines = File.ReadAllLines ("C:\\Dev\\Repositories\\HD-CMC\\trunk\\XE5\\IRBatch\\PowerShell\\NotifyFileCreate.ps1"); 

      List<String> linesList = new List<String>(lines); 

      String script = String.Join("\n", linesList); 
      RunScript(script);  
     } 

     public static string RunScript(string scriptText) 
     {   
      Runspace runspace = RunspaceFactory.CreateRunspace(); 

      runspace.Open(); 

      Pipeline pipeline = runspace.CreatePipeline(); 
      pipeline.Commands.AddScript(scriptText); 


      //pipeline.Commands.Add("Out-String"); 

      Collection<PSObject> results = pipeline.Invoke(); 

      runspace.Close(); 

      StringBuilder stringBuilder = new StringBuilder(); 
      foreach (PSObject obj in results) 
      { 
       stringBuilder.AppendLine(obj.ToString()); 
      } 

      return stringBuilder.ToString(); 

     } 
    } 
} 

這似乎像powershell會話不會持續運行腳本,除非我手動將其粘貼到PowerShell中。

回答

1

的-noexit選項添加到您的命令行調用:

Powershell.exe -executionpolicy remotesigned -NoExit -File NotifyFileCreate.ps1