Adding content to loop in function

Brass Contributor

Hello I am trying to add a list of computers to loop through a function. I have added this line....

$computername = get-content c:\temp\servers.txt

 to the beginning of the script below but it does not work. The script below works fine but I have to manually specify the computer name each time I run it.

 

function Get-LoggedOnUser
 {
     [CmdletBinding()]
     param
     (
         [Parameter()]
         [ValidateScript({ Test-Connection -ComputerName $_ -Quiet -Count 1 })]
         [ValidateNotNullOrEmpty()]
         [string[]]$ComputerName = $env:COMPUTERNAME
     )
     foreach ($comp in $ComputerName)
     {
         $output = @{ 'ComputerName' = $comp }
         $output.UserName = (Get-WmiObject -Class win32_computersystem -ComputerName $comp).UserName
         [PSCustomObject]$output
     }
 }

Is there a way to add a list of computers to loop in the function above? Hope this makes sense and any help is greatly appreciated!

3 Replies
how are you calling the function? I guess..
get-loggedOnUser -ComputerName $computername

what value(s) does $output contain when the function returns

Hello @Animesh Joshi thanks for the reply. The message that comes back after running with adding the get-content line is....

 

Get-LoggedOnUser : Cannot validate argument on parameter 'ComputerName'. The " Test-Connection -ComputerName $_ -Quiet -Count 1 " validation script for
argument with value "pc1.mydomain.local" did not return a result of True. Determine why the validation script failed, and then try the command again.
At line:1 char:32
+ Get-LoggedOnUser -ComputerName $computername
+ ~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Get-LoggedOnUser], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Get-LoggedOnUser

@charlie4872 

I ran your script, without errors: 

 

function Get-LoggedOnUser
{
[CmdletBinding()]
param
(
[Parameter()]
[ValidateScript({ Test-Connection -ComputerName $_ -Quiet -Count 1 })]
[ValidateNotNullOrEmpty()]
[string[]]$ComputerName = $env:COMPUTERNAME
)
foreach ($comp in $ComputerName)
{
$output = @{ 'ComputerName' = $comp }
$output.UserName = (Get-WmiObject -Class win32_computersystem -ComputerName $comp).UserName
[PSCustomObject]$output
}
}
$ep = get-content -path C:\support\eps.txt
get-loggedonuser -ComputerName $ep

 

however, I can reproduce the error you get when I put an incorrect/non-existent computer name in eps.txt. You have a validation in function header to see if a computer is online, if the validation fails the function will fail, there are no try{} catch{} blocks to handle runtime and/or terminating errors.

In your case pc1.mydomain.local is failing the validation.