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.

2
  • 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. Commented Nov 13, 2012 at 4: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? Commented Nov 13, 2012 at 9:51

1 Answer 1

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()
Sign up to request clarification or add additional context in comments.

8 Comments

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!
@AllanTolentino I've added code for embed the C# code (a little revisioned)
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?).
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?
@AllanTolentino Read this answer stackoverflow.com/questions/2094694/… to make powershell v2 load Framework.net 4.0. Then you can add the type. I've tested it and it works.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.