Pass variable to a parameter

I want to pass a single computer to the machines parameter or all computers from an OU. If I create a variable before the parameter the param doesn’t work.

The param will not work with the $All variable if I remove that line it works with a single computer.

$All = Get-ADComputer -filter * -SearchBase "OU=Servers,DC=ad,DC=test,DC=ad" | select -ExpandProperty name

param(
$machines
)
$report = @()
$object = @()
foreach($machine in $machines)
{
$object = gwmi win32_operatingsystem -ComputerName $machine | select csname, @{LABEL='LastBootUpTime';EXPRESSION={$_.ConverttoDateTime($_.lastbootuptime)}}
$report += $object
}
$report | sort lastbootuptime

The param () needs to go to the top of your script. Define the variable in the console then call the script with the -Machines parameter.

Also, try to be consistent with Microsoft’s parameter names. Instead of using -Machine use -ComputerName

pwshliquori

If you’re trying to give the parameter a default value for when you call the script without specifying, you need to assign to the parameter inside the parameter block instead. Below is one way you can write it.

[CmdletBinding()]
param(
    [Parameter()]
    [string[]]
    $ComputerName = (Get-ADComputer -Filter * -SearchBase "OU=Servers,DC=ad,DC=test,DC=ad" | Select-Object -ExpandProperty Name)
)

$Report = foreach($Machine in $ComputerName) {
    Get-WmiObject -ClassName Win32_OperatingSystem -ComputerName $Machine |
        Select-Object -Property CSName, @{ Name = 'LastBootUpTime'; Expression = {$_.ConverttoDateTime($_.LastBootUpTime)} }
}

$Report | Sort-Object -Property LastBootUpTime

Joel, that is perfect. Thanks