# Help tweaking my parameter input

**URL:** <https://forums.powershell.org/t/help-tweaking-my-parameter-input/23186>\
**Category:** PowerShell Help\
**Created:** [November 19, 2023, 12:47am UTC](https://forums.powershell.org/t/help-tweaking-my-parameter-input/23186 "2023-11-19T00:47:57Z")\
**Posts on this page:** 10\
**Page:** 1

<div class="post-metadata">

**Author:** ![matt1974](https://avatars.discourse-cdn.com/v4/letter/m/dbc845/32.png) [@matt1974](https://forums.powershell.org/u/matt1974)\
**Post date:** [November 19, 2023, 12:47am UTC](https://forums.powershell.org/t/help-tweaking-my-parameter-input/23186/1 "2023-11-19T00:47:57Z")

</div>

Hello folks,  
I have this script that Im pretty happy with, but would like to make 2 changes, neither of which work when i try them.

I would like to be able to run the script passing in multiple computers on the command line, like so:  
Get-MKProcesses -computer computer1, computer2, etc

As it is I can run it with various other params like these:  
Get-MKProcesses (for local computer) -number 10  
Get-MKProcesses -computer remotecomputer -number 2  
Get-MKProcesses -number 6 -computer c:\temp\inputfiles\servers.txt

and they all work great. When I try and tweak for the comma separated list, I end up breaking one of those other input methods.

The other thing was , my starttime column shows multiple entries for some, anyway to only have 1 start time per process?

Any help would be great, thanks!

Here is the script:

```auto
<#
Get-MKProcesses
function to get X number of top processes by cpu%
usage:
Get-MKProcesses (for local computer) -number 10
Get-MKProcesses -computer remotecomputer -number 2
Get-MKProcesses -number 6 -computer c:\temp\inputfiles\servers.txt
#>
function Get-MKProcesses {
    param (
        $computer = $env:COMPUTERNAME,
        $number = 5
    )

    # Check if $computer is a file path
    if (Test-Path $computer -ErrorAction SilentlyContinue) {
        $computerNames = Get-Content $computer
    }
    else {
        $computerNames = @($computer)
    }

    foreach ($computerName in $computerNames) {
        $scriptblock = {
            param($localNumber)
            $i = 0
            
            # Get the top processes by CPU usage
            $topProcesses = Get-Process -IncludeUserName | Sort-Object CPU -Descending | Select-Object -First $localNumber
            # Get the total CPU usage
            $totalCPU = (Get-Counter '\Processor(_Total)\% Processor Time').CounterSamples.CookedValue
            # Get the hostname
            $hostname = $env:COMPUTERNAME

            # Output information for each process as PSCustomObject
            $processInfo = foreach ($process in $topProcesses) {
                $i++
                $processuser = $process.username
                $processName = $process.ProcessName
                $processid = $process.Id
                $processcputime = $process.cpu
                $cpuCounter = (Get-Counter "\Process($($processName))\% Processor Time").CounterSamples.CookedValue
                $cpuUsage = "{0:N2}%" -f $cpuCounter
                $path = if ($process.Path) { $process.Path } else { "N/A" }
                $memoryUsage = "{0:N2} MB" -f ($process.WorkingSet / 1MB)
                $processInfoInstance = Get-CimInstance -ClassName Win32_Process -Filter "Name='$processName.exe'"
                $startTime = $processInfoInstance.CreationDate
             

                [PSCustomObject]@{
                    Number = $i
                    ProcessName = $processName
                    Path = $path
                    PID = $processid
                    CPUUsage = $cpuUsage
                    MemoryUsage = $memoryUsage
                    ProcessCPUTime = $processcputime
                    ProcessUser = $processuser
                    Hostname = $hostname
                    StartTime = $startTime
                } 
            }         
            # Output the process information
            $processInfo | Format-Table -AutoSize
            Write-Host "Total CPU usage $totalCPU`r`n" -NoNewLine -ForegroundColor Yellow
            Write-Host "ProcessCPUTime shows CPU time consumed by the process in seconds" -ForegroundColor Red
        }

        if ($computerName -eq $env:COMPUTERNAME) {
            # Run the script block locally
            . $scriptblock -localNumber $number
        }
        else {
            # Run the script block on a remote computer
            Invoke-Command -ComputerName $computerName -ScriptBlock $scriptblock -ArgumentList $number
        }
    }
}

```

And the output:

```auto
 get-mkProcesses

Number ProcessName Path PID CPUUsage MemoryUsage ProcessCPUTime ProcessUser Hostname StartTime
------ ----------- ---- --- -------- ----------- -------------- ----------- -------- ---------
     1 System N/A 4 10.82% 5.10 MB 9242.73 MK-1ST
     2 msedge C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe 44940 3.08% 193.02 MB 8265.14 MK-1ST\Matt MK-1ST {11/16/2023 6:59:59 AM, 11/16/2023 6:59:59…
     3 CefSharp.BrowserSubprocess C:\Program Files (x86)\Razer\Razer Services\Razer Central\CefSharp.BrowserSubprocess.exe 22472 0.00% 102.21 MB 6989.70 MK-1ST\Matt MK-1ST {11/15/2023 7:24:20 AM, 11/15/2023 7:24:20…
     4 dwm C:\WINDOWS\system32\dwm.exe 1516 0.00% 95.37 MB 6587.55 Window Manager\DWM-1 MK-1ST 11/15/2023 7:06:22 AM
     5 EADesktop C:\Program Files\Electronic Arts\EA Desktop\EA Desktop\EADesktop.exe 20568 3.10% 185.13 MB 6392.92 MK-1ST\Matt MK-1ST 11/15/2023 7:24:21 AM

```

---

<div class="post-metadata">

**Author:** ![Olaf](https://sea1.discourse-cdn.com/flex019/user_avatar/forums.powershell.org/olaf/32/992_2.png) [@Olaf](https://forums.powershell.org/u/Olaf)\
**Post date:** [November 19, 2023, 1:06am UTC](https://forums.powershell.org/t/help-tweaking-my-parameter-input/23186/2 "2023-11-19T01:06:31Z")

</div>

> [@matt1974](#):
>
> but would like to make 2 changes, neither of which work when i try them.
> 
> I would like to be able to run the script passing in multiple computers on the command line, like so:  
> Get-MKProcesses -computer computer1, computer2, etc

I am curious. What have you tried to make it work like you want it to? 🤔

Have you tried calling your script in a loop feeding it your list of computernames? Like so …

```auto
'Computer1','Computer2','Computer3' |
    Foreach-Object {
        Get-MKProcesses -number 6 -computer $_
    }

```

Let’s start with reading the help …

> **[about Functions Advanced Parameters - PowerShell](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_functions_advanced_parameters?view=powershell-7.3#static-parameters)**
>
> Explains how to add parameters to advanced functions.

The paragraph about static parameters already shows how to make a parameter accepting arrays of string values. 😉

> [@matt1974](#):
>
> ```auto
> # Check if $computer is a file path
> if (Test-Path $computer -ErrorAction SilentlyContinue) {
> $computerNames = Get-Content $computer
> }
> else {
> $computerNames = @($computer)
> }
> 
> ```

In my opinion that’s a very bad approach since it would be unexpected for a parameter named `-Computer` to accept a file path. And I would use the parameter name `ComputerName` instead as this is very common. You could use `-Computer` as an alias if you like or need for backwards compatibility.

> [@matt1974](#):
>
> The other thing was , my starttime column shows multiple entries for some, anyway to only have 1 start time per process?

If you have multiple processes you also have multiple start times … that’s logical, isn’t it? 🤔  
You will have to come up with an idea how you like to handle multiple processes with the same name. Especially for browsers that’s a very common thing to launch multiple processes even when you just started them and didn’t even open more than one tab. 🤷🏼‍♂️

---

<div class="post-metadata">

**Author:** ![matt1974](https://avatars.discourse-cdn.com/v4/letter/m/dbc845/32.png) [@matt1974](https://forums.powershell.org/u/matt1974)\
**Post date:** [November 19, 2023, 1:44am UTC](https://forums.powershell.org/t/help-tweaking-my-parameter-input/23186/3 "2023-11-19T01:44:09Z")

</div>

Thanks Olaf. I didnt really think about the -computer taking a path not making sense lol, and turns out changing that bit solves my problem with the string input.

```auto
<#
Get-MKProcesses
function to get X number of top processes by cpu%
usage:
Get-MKProcesses (for local computer) -number 10
Get-MKProcesses -computer remotecomputer1,remotecomputer2 -number 2
Get-MKProcesses -number 6 -computer c:\temp\inputfiles\servers.txt
#>
function Get-MKProcesses {
    param (
        [string[]]$computer = $env:COMPUTERNAME,
        $number = 5,
		$path
    )

    # Check if $computer is a file path
    if (Test-Path $path -ErrorAction SilentlyContinue) {
        $computernames = Get-Content $path
    }
    else {
        $computernames = @($computer)
    }

    foreach ($computername in $computernames) {
        $scriptblock = {
            param($localNumber)
            $i = 0
            
            # Get the top processes by CPU usage
            $topProcesses = Get-Process -IncludeUserName | Sort-Object CPU -Descending | Select-Object -First $localNumber
            # Get the total CPU usage
            $totalCPU = (Get-Counter '\Processor(_Total)\% Processor Time').CounterSamples.CookedValue
            # Get the hostname
            $hostname = $env:COMPUTERNAME

            # Output information for each process as PSCustomObject
            $processInfo = foreach ($process in $topProcesses) {
				$processInfoInstance = Get-CimInstance -ClassName Win32_Process -Filter "Name='$processName.exe'"
                $startTime = $processInfoInstance.CreationDate
                $i++
				$processuser = $process.username
                $processName = $process.ProcessName
                $numProcesses = (Get-Process -Name $processName).Count
				$processid = $process.Id
                $processcputime = $process.cpu
                $cpuCounter = (Get-Counter "\Process($($processName))\% Processor Time").CounterSamples.CookedValue
                $cpuUsage = "{0:N2}%" -f $cpuCounter
                $path = if ($process.Path) { $process.Path } else { "N/A" }
                $memoryUsage = "{0:N2} MB" -f ($process.WorkingSet / 1MB)
                								
                [PSCustomObject]@{
                    Number = $i
                    ProcessName = $processName
                    Path = $path
                    PID = $processid
                    CPUUsage = $cpuUsage
                    MemoryUsage = $memoryUsage
                    ProcessCPUTime = $processcputime
                    ProcessUser = $processuser
                    Processes = $numProcesses
                    StartTime = $startTime
                } 
            }         
            # Output the process information
            $processInfo | Format-Table -AutoSize
            Write-Host "Total CPU usage $totalCPU`r`n" -NoNewLine -ForegroundColor Yellow
            Write-Host "ProcessCPUTime shows CPU time consumed by the process in seconds" -ForegroundColor Red
        }

        if ($computername -eq $env:COMPUTERNAME) {
            # Run the script block locally
            . $scriptblock -localNumber $number
        }
        else {
            # Run the script block on a remote computer
            Invoke-Command -ComputerName $computername -ScriptBlock $scriptblock -ArgumentList $number
        }
    }
}

```

---

<div class="post-metadata">

**Author:** ![matt1974](https://avatars.discourse-cdn.com/v4/letter/m/dbc845/32.png) [@matt1974](https://forums.powershell.org/u/matt1974)\
**Post date:** [November 19, 2023, 2:29am UTC](https://forums.powershell.org/t/help-tweaking-my-parameter-input/23186/4 "2023-11-19T02:29:26Z")

</div>

I also took your advice and changed $computer to $computername. here is the final version:

```auto
<#
Get-MKProcesses
function to get X number of top processes by cpu%
usage:
Get-MKProcesses (for local computer) -number 10
Get-MKProcesses -computer remotecomputer1,remotecomputer2 -number 2
Get-MKProcesses -number 6 -filepath c:\temp\inputfiles\servers.txt
#>
function Get-MKProcesses {
    param (
        [string[]]$computername = $env:COMPUTERNAME,
        $number = 5,
        $filepath
    )

    # Check if $computer is a file path
    if (Test-Path $filepath -ErrorAction SilentlyContinue) {
        $computernames = Get-Content $filepath
    }
    else {
        $computernames = @($computername)
    }

    foreach ($computer in $computernames) {
        $scriptblock = {
            param($localNumber)
            $i = 0
            
            # Get the top processes by CPU usage
            $topProcesses = Get-Process -IncludeUserName | Sort-Object CPU -Descending | Select-Object -First $localNumber
            # Get the total CPU usage
            $totalCPU = (Get-Counter '\Processor(_Total)\% Processor Time').CounterSamples.CookedValue
            # Get the hostname
            $hostname = $env:COMPUTERNAME

            # Output information for each process as PSCustomObject
            $processInfo = foreach ($process in $topProcesses) {
                $processInfoInstance = Get-CimInstance -ClassName Win32_Process -Filter "Name='$processName.exe'"
                $startTime = $processInfoInstance.CreationDate
                $i++
                $processuser = $process.username
                $processName = $process.ProcessName
                $numProcesses = (Get-Process -Name $processName).Count
                $processid = $process.Id
                $processcputime = $process.cpu
                $cpuCounter = (Get-Counter "\Process($($processName))\% Processor Time").CounterSamples.CookedValue
                $cpuUsage = "{0:N2}%" -f $cpuCounter
                $path = if ($process.Path) { $process.Path } else { "N/A" }
                $memoryUsage = "{0:N2} MB" -f ($process.WorkingSet / 1MB)
                								
                [PSCustomObject]@{
                    Number = $i
                    ProcessName = $processName
                    Path = $path
                    PID = $processid
                    CPUUsage = $cpuUsage
                    MemoryUsage = $memoryUsage
                    ProcessCPUTime = $processcputime
                    ProcessUser = $processuser
                    Processes = $numProcesses
                    StartTime = $startTime
                } 
            }         
            # Output the process information
            $processInfo | Format-Table -AutoSize
            Write-Host "Total CPU usage $totalCPU`r`n" -NoNewLine -ForegroundColor Yellow
            Write-Host "ProcessCPUTime shows CPU time consumed by the process in seconds" -ForegroundColor Red
        }

        if ($computer -eq $env:COMPUTERNAME) {
            # Run the script block locally
            . $scriptblock -localNumber $number
        }
        else {
            # Run the script block on a remote computer
            Invoke-Command -ComputerName $computer -ScriptBlock $scriptblock -ArgumentList $number
        }
    }
}

```

---

<div class="post-metadata">

**Author:** ![Olaf](https://sea1.discourse-cdn.com/flex019/user_avatar/forums.powershell.org/olaf/32/992_2.png) [@Olaf](https://forums.powershell.org/u/Olaf)\
**Post date:** [November 19, 2023, 2:37am UTC](https://forums.powershell.org/t/help-tweaking-my-parameter-input/23186/5 "2023-11-19T02:37:04Z")

</div>

> [@matt1974](#):
>
> ```auto
> if (Test-Path $filepath -ErrorAction SilentlyContinue) {
> $computernames = Get-Content $filepath
> }
> else {
> $computernames = @($computername)
> }
> 
> ```

What if a user of your script/function provides both - a computername or a list of computer names AND a file path to an input file with computernames? 🤔 😏 😜 ☝🏼

---

<div class="post-metadata">

**Author:** ![matt1974](https://avatars.discourse-cdn.com/v4/letter/m/dbc845/32.png) [@matt1974](https://forums.powershell.org/u/matt1974)\
**Post date:** [November 19, 2023, 4:53pm UTC](https://forums.powershell.org/t/help-tweaking-my-parameter-input/23186/6 "2023-11-19T16:53:48Z")

</div>

> [@Olaf](#):
>
> What if a user of your script/function provides both - a computername or a list of computer names AND a file path to an input file with computernames?

hmm good question! as it is it fails by only returning the -filepath params it seems?

I was thinking of something like this:

```auto
param(
    [Parameter(ParameterSetName="Computer")]
    [string[]]$computername = $env:COMPUTERNAME,

    [Parameter(ParameterSetName="FilePath")]
    $filepath,

    [Parameter(ParameterSetName="Computer")]
    [Parameter(ParameterSetName="FilePath")]
    [switch]$number = 5
)

```

but its not exactly working.

Any thoughts on how to handle that?

Thank You.

---

<div class="post-metadata">

**Author:** ![matt1974](https://avatars.discourse-cdn.com/v4/letter/m/dbc845/32.png) [@matt1974](https://forums.powershell.org/u/matt1974)\
**Post date:** [November 19, 2023, 5:38pm UTC](https://forums.powershell.org/t/help-tweaking-my-parameter-input/23186/7 "2023-11-19T17:38:53Z")

</div>

maybe something like this:

```auto
# Check if both $computername and $filepath are provided
    if ($computername -and $filepath) {
        Write-Error "Please choose either a remote computer or a file as input, not both."
        return
    }

```

---

<div class="post-metadata">

**Author:** ![krzydoug](https://sea1.discourse-cdn.com/flex019/user_avatar/forums.powershell.org/krzydoug/32/1008_2.png) [@krzydoug](https://forums.powershell.org/u/krzydoug)\
**Post date:** [November 19, 2023, 5:46pm UTC](https://forums.powershell.org/t/help-tweaking-my-parameter-input/23186/8 "2023-11-19T17:46:51Z")

</div>

I would use parameter sets to keep exclusive parameters from conflicting

---

<div class="post-metadata">

**Author:** ![Olaf](https://sea1.discourse-cdn.com/flex019/user_avatar/forums.powershell.org/olaf/32/992_2.png) [@Olaf](https://forums.powershell.org/u/Olaf)\
**Post date:** [November 19, 2023, 10:10pm UTC](https://forums.powershell.org/t/help-tweaking-my-parameter-input/23186/9 "2023-11-19T22:10:47Z")

</div>

> [@matt1974](#):
>
> I was thinking of something like this:

… a good start …

> [@matt1974](#):
>
> but its not exactly working.

What exactly do you mean by this? 🤔

> [@matt1974](#):
>
> Any thoughts on how to handle that?

To be honest - since you already have a way to prvide a list of computers to the function I would drop the filepath parameter completely. Instead I would make the parameter `-ComputerName` “_pipeline aware_” using `ValueFromPipeline` or even `ValueFromPipelineByPropertyName`. This way you could easily do something like this:

```auto
Get-Content -Path '<Path\To\Your\Input\File.txt>' | 
    Get-MKProcesses 

```

---

<div class="post-metadata">

**Author:** ![dotnVo](https://avatars.discourse-cdn.com/v4/letter/d/4af34b/32.png) [@dotnVo](https://forums.powershell.org/u/dotnVo)\
**Post date:** [May 16, 2024, 8:14pm UTC](https://forums.powershell.org/t/help-tweaking-my-parameter-input/23186/10 "2024-05-16T20:14:34Z")

</div>

Closed on May 16, 2024, 8:14pm UTC


