Reputation: 1063
I'm trying to pass the results of an LDAP query (computers) into my Powershell function. However, the function only processes one value. Here's some example code:
Function Get-ComputerName {
Param(
[Alias('Computer','ComputerName','HostName')]
[Parameter(
Mandatory=$true,
Position=0,
ValueFromPipeline=$true
)]
[Object[]]$computers
)
if(-not($computers)) { Throw “You must supply at least one computer” }
foreach($computer in $computers) {
write-host $computer.Name
}
}
When I run:
Get-ADComputer -SearchBase 'OU="Devices",dc=FVWM1,dc=Local' -Filter '*' | Get-ComputerName
The result is only one computer name printed but there should definitely be more than one. Help! Thanks.
Upvotes: 0
Views: 30
Reputation: 7499
When using the pipeline to pass multiple objects into a function, make sure to use the Begin, Process, and End blocks. After building a $computers object of my own, I can replicate the issue.
$computers = @()
$computers += New-Object -TypeName PSObject -Property @{
Name = "Test"
Note = "TestTest"
}
$computers += New-Object -TypeName PSObject -Property @{
Name = "Test2"
Note = "TestTest"
}
$computers += New-Object -TypeName PSObject -Property @{
Name = "Test3"
Note = "TestTest"
}
$computers | Get-InstalledSoftware
This yields test3
The solution is to simply wrap the internals of the function with Process {}
like so:
Function Get-InstalledSoftware {
Param(
[Alias('Computer','ComputerName','HostName')]
[Parameter(
Mandatory=$true,
Position=0,
ValueFromPipeline=$true
)]
[Object[]]$computers
)
Process {
if(-not($computers)) { Throw “You must supply at least one computer” }
foreach($computer in $computers) {
write-host $computer.Name
}
}
}
Upvotes: 2