5

It is my first time to post a question. I am both new to csharp and powershell. Please bear with me if my english is not good at all. I've been trying to convert my csharp code into powershell, but i'm not successful. I tried to research documents about powershell and try each one of them, unfortunately, nothing work for me. My csharp code is working in Visual Studio 2010 but I could not able to embed and work it in Powershell. The code below simply catch PID of a taskmanager and write it to notepad with time and date stamp. Any help will be greatly appreciated.

My csharp code is:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace GET_TASK
{
    class Program
    {
        static void Main(string[] args)
        {

            var processList = Process.GetProcessesByName("taskmgr");                

            foreach (var process in processList)
            {

                string myPath = "C:/powershell/GET_TASK"; //change data path as needed

                FileStream logfile;
                //log program process
                logfile = new FileStream(myPath + "/logfile.txt", FileMode.Append, FileAccess.Write); 

                TextWriter oldLog = Console.Out;  

                StreamWriter writelog;
                writelog = new StreamWriter(logfile);               

                DateTime time = DateTime.Now;
                string format = "MMM ddd d HH:mm yyyy";

                Console.SetOut(writelog);

                // print out the process id
                Console.WriteLine("Process Id=" + process.Id + " - " + time.ToString(format));

                Console.SetOut(oldLog);                        

                writelog.Close();

                System.Environment.Exit(0);                               
            }
        }
    }
}

In my Powershell code, I just put

$source = @"

at the begging of this code and

Add-Type -TypeDefinition $source
[GET_TASK.Program]::Main()

at the end of the code but it don't work. I'm using Powershell version 1. Please help convert my C# code.

Richard
  • 106,783
  • 21
  • 203
  • 265
  • Are you getting any errors? What happens when you run it powershell? We can't help you if you don't tell us anything more than "it don't work". Also, the activity carried out here (getting process ids and writing to a file) is most certainly easier to do directly in powershell with the builtin cmdlets. – Mike Zboray Nov 13 '12 at 04:39
  • 1
    `Add-Type` was added in PowerShell V2, it does not exist (so will fail in PSH V1). As PSH V1 is now rather old (and V2 enhanced PSH massively) have you considered committing to V2? – Richard Nov 13 '12 at 09:51

1 Answers1

3

Try this:

get-process | % { "Process ID = $($_.id) - $(get-date -Format "MMM ddd d HH:mm yyyy")" } |
out-file -path "C:/powershell/GET_TASK" -append

It's the powershell equivalent code.

Your code for using in add-type (only powershell V2 or V3, for V1 you have to create a DLL and use [Reflection.Assembly]::LoadFile("c:\myddl.dll") )

$t = @"
using System;
using System.Diagnostics;
using System.IO;

 public  class Program
    {
        public static void Main()
        {    
            var processList = Process.GetProcessesByName("taskmgr");    
            foreach (var process in processList)
            {    
                string myPath = "C:/"; //change data path as needed    
                FileStream logfile;
                //log program process
                logfile = new FileStream(myPath + "/logfile.txt", FileMode.Append, FileAccess.Write);    
                TextWriter oldLog = Console.Out;    
                StreamWriter writelog;
                writelog = new StreamWriter(logfile);
                    DateTime time = DateTime.Now;
                string format = "MMM ddd d HH:mm yyyy";    
                Console.SetOut(writelog);
                    // print out the process id
                Console.WriteLine("Process Id=" + process.Id + " - " + time.ToString(format));    
                Console.SetOut(oldLog);    
                writelog.Close();    
                //System.Environment.Exit(0); removed, otherwise closes the console  
          }
        }
    }
"@

Add-Type -TypeDefinition $t
[program]::main()
CB.
  • 58,865
  • 9
  • 159
  • 159
  • Thank you for that response. That actually work in powershell, but at this point, I'm trying to figure out how to embed a working C# code in powershell and make it work the same. I can embed a simple C# calculation, but I don't know how to embed a C# in powershell that use IO and FORMS like this one I have. cheers! – Allan Tolentino Nov 13 '12 at 12:45
  • @AllanTolentino I've added code for embed the C# code (a little revisioned) – CB. Nov 13 '12 at 13:02
  • now, i'm getting this error >> The type or namespace name 'var' could not be found (Are you missing a using directive or an assembly reference?). – Allan Tolentino Nov 13 '12 at 13:17
  • It seems to me that it is not wanting this declaration >> var processList = Process.GetProcessesByName("taskmgr"); any other way i can declare this without using var? I don't know why it won't accept that, or maybe i just need to put some reference somewhere? – Allan Tolentino Nov 13 '12 at 13:19
  • @AllanTolentino Read this answer http://stackoverflow.com/questions/2094694/how-can-i-run-powershell-with-the-net-4-runtime to make powershell v2 load Framework.net 4.0. Then you can add the type. I've tested it and it works. – CB. Nov 13 '12 at 13:23
  • christian - It partially worked when I did that. I noticed that powershell is not recognizing VAR variables. I have to remove the line below in order to work. >> var processList = Process.GetProcessesByName("taskmgr"); foreach (var process in processList) – Allan Tolentino Nov 13 '12 at 15:56
  • Are there any substitute for that VAR declaration? Thank you for the previous responses. Cheers! – Allan Tolentino Nov 13 '12 at 15:57
  • @AllanTolentino You can try use `Process[] processList = Process.GetProcessesByName("taskmgr");` because this method return an array of type process `Process[]` – CB. Nov 14 '12 at 13:10