了解powershell会话

时间:2015-02-11 02:39:11

标签: c# session 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

但是我需要能够以编程方式调用此脚本,而不是每次我希望它运行时将其复制粘贴到shell中。

我尝试从命令行调用脚本

即:

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 个答案:

答案 0 :(得分:1)

将-NoExit选项添加到命令行调用:

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