了解 PowerShell 会话

Understanding powershell sessions

我写了一个 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} 

当我运行它掌权shell时它工作正常。

但是我需要能够以编程方式调用此脚本,而不是每次我想要它时都将其复制粘贴到 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.

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

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