sav
sav

Reputation: 2150

Understanding powershell sessions

I've written a powershell script to notify a program of mine when a file is created. (Note: I provide the code for reference, but I'm not sure there is anything wrong with the code)

$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} 

It works fine when I run it in powershell.

Powershell

However I need to be able to programmatically invoke this script, rather than copy-paste it into the shell each time I want it to run.

I've tried invoking the script from a command line

ie:

Powershell.exe -executionpolicy remotesigned -File NotifyFileCreate.ps1

I've tried writing a C# program to invoke the script.

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();

        }
    }
}

It just seems like the powershell session won't persist once the script is run unless I manually paste it into powershell.

Upvotes: 0

Views: 109

Answers (1)

mjolinor
mjolinor

Reputation: 68273

Add the -NoExit option to your command line call:

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

Upvotes: 1

Related Questions