Learning PowerShell: Using PSComputerName
Let's run through a quick scenario. This won't take long, I promise.
An Invoke-Command block returns a variable from the remote host where the block executed. I want to store that variable. That's easy enough to do.
$Results = Invoke-Command -ComputerName 'DummyPC' {Get-Variable}
Awesome! But I want to run this against multiple computers at once. Okay, I can do that too.
$Results = Invoke-Command -ComputerName 'ListOfDummies' {Get-Variable}
Fantastic! Now, I want a printout of which values were returned from which computers. To do this, I'll first create a new table called $PrintOut. Then I'll loop through $Results, using the PSComputerName property of each value to build out the new table as I go.
$PrintOut = @{}
$Results = Invoke-Command -ComputerName 'ListOfDummies' {Get-Variable}
foreach ($Variable in $Results)
{
$Computer = $Variable.PSComputerName
$PrintOut.$Computer += $Variable
}
If I return the $PrintOut table as it is now, I'll get what I wanted but not in the exact format I'm looking for. I want the table sorted by hostname. I can solve this problem by amending the script in two ways:
- Setting $PrintOut as a dictionary by using the [ordered] attribute
- Sorting $Results by PSComptuterName before looping through it
$PrintOut = [ordered]@{}
$Results = Invoke-Command -ComputerName 'ListOfDummies' {Get-Variable}
$Results = $Results | Sort-Object -PropertyName PSComputerName
foreach ($Variable in $Results)
{
$Computer = $Variable.PSComputerName
$PrintOut.$Computer += $Variable
}
We're almost done, but first, COMMENTS!
# Define ordered dictionary for reporting
$PrintOut = [ordered]@{}
# Get some variables from dummies then sort values by PSComputerName
$Results = Invoke-Command -ComputerName 'ListOfDummies' {Get-Variable}
$Results = $Results | Sort-Object -PropertyName PSComputerName
# Build $PrintOut table
foreach ($Variable in $Results)
{
$Computer = $Variable.PSComputerName
$PrintOut.$Computer += $Variable
}
And DONE!
Thanks for reading!
No comments to display
No comments to display