Posts

Showing posts with the label Array

Counting the objects returned by a PowerShell command

Image
Today I going to write about a little trick I'm using when I want to check the number of objects a PowerShell command returned. If you execute a PowerShell command that returns some kind of objects, you either get a single object or an array of objects. The array object has a property called "Count" that will return the number of items in the array but what if the command returns a single object? Depending on the implementation of the command that returns the objects,  There is no count property on a single object -and if there is, it's probably irrelevant and will result in a bug. Using the logic below you can check if the variable "copies" is an array and if not, create an array with the object in the variable. if ( $copies -isnot [System.Array] ){ $copies = @ ( $copies )} You can also create an array when assigning the result to the variable like: $copies = @ ( Get-ChildItem ) The newer versions of PowerShell will allow you to use the ...

Invoke-Command Array in ArgumentList

When dealing with multiple servers, you may often have to run a powershell command or script on many or all of them. This is where "Invoke-Command" comes into play. The Invoke-Command will execute a powershell command on a remote system and return the results to our powershell console. Let's take a look at a simple example. We are going to test whether or not a folder exists on multiple servers: $servers = @ ( "dc1" , "dc3" ) $servers | %{ Invoke-Command -ComputerName $_ ` -ScriptBlock { Write-Output "C:\Temp" } } The Write-Output cmdlet is executed on the dc1 and dc3 servers. But what if we have to pass parameters to the scriptblock? We will use the -ArgumentList parameter of the Invoke-Command as follows: $servers = @ ( "dc1" , "dc3" ) $path = "C:\Temp" $servers | %{ Invoke-...