2015-02-11 68 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