1

I am writing some PowerShell cmdlets in C# to access our production servers and report on the IIS/Service state.

The ServiceController class has a MachineName property, but neither Site nor ApplicationPool classes have this.

How would I go about returning the computer name alongside these objects (i.e. Get-Service | select MachineName,Status,DisplayName)? I considered extending the classes, but they are sealed and I don't wish to spend time implementing this solution.

Does anyone with more skill in writing cmdlets have an idea how I can easily accomplish this?

Community
  • 1
  • 1
hsimah
  • 1,265
  • 2
  • 20
  • 37

2 Answers2

1

You can use a custom expression with the Select cmdlet to add an custom property to the object that is returned by it.

$mn = $env:COMPUTERNAME
Get-Service | Select @{Expression={$mn};Label="MachineName"},Status,DisplayName

For more information on custom expression see this link.

Richard
  • 6,812
  • 5
  • 45
  • 60
  • Thanks, that is a useful tip for PowerShell. Any idea how to accomplish it in C#? I might attempt to use a dynamic object. – hsimah Sep 12 '16 at 22:19
0

I simply wrote a small wrapper for the classes I wanted. It's not perfect but it's also not important enough to spend time on.

public class MyApplicationPool
{
    public MyApplicationPool(ApplicationPool appPool, string machineName)
    {
        Name = appPool.Name;
        MachineName = machineName;
        State = appPool.State;
        Cpu = appPool.Cpu;
        QueueLength = appPool.QueueLength;

        ApplicationPool = appPool;
    }

    public string MachineName { get; }
    public string Name { get; }
    public ObjectState State { get; }
    public long QueueLength { get; }
    public ApplicationPoolCpu Cpu { get; }

    public ObjectState Start()
    {
        return ApplicationPool.Start();
    }

    public ObjectState Stop()
    {
        return ApplicationPool.Stop();
    }

    public ObjectState Recycle()
    {
        return ApplicationPool.Recycle();
    }

    private ApplicationPool ApplicationPool { get; }
}
hsimah
  • 1,265
  • 2
  • 20
  • 37