Posts

Showing posts with the label Parameter

PowerShell Dynamic Validate Set

When writing advanced PowerShell functions you may have to add a parameter with a validate set that is created dynamically. Let me use an example to make thing clearer. I was writing a function that has the ability to query different Active Directory forests. That function is actually a wrapper for the  Find-LDAPObject  cmdlet and provides a better interface by saving the configuration of each directory in a csv file. Each row of the csv file contains the name of the directory, the server and port to connect, the root DN of the directory and the credentials to use. What I wanted to achieve was to create a validate set that would contain all the names of directories in the csv file, so that the user would be able to choose amongst them. Martin Schvartzman has posted a great article on dynamic validate sets that proved to be very helpful! The way to create a dynamic validate set is to create the entire parameter in the function code. We'll start with the standar...

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-...

Powershell: How to pass a parameter to a scriptblock

Scriptblock. Very common in the powershell world and used by many cmdlets and functions like Invoke-Command. But how can we pass a parameter to the scriptblock? Lets say that we are developing a function that will execute a command on remote computers. As a real world example, I want to check the status of a service on remote computers. I need however my function to be agile and accept the name of the service to check. Since I am going to be using the Invoke-Command cmdlet, I need to pass the name of the service to the scriptblock parameter. Fortunatelly, this is fairly easy and cam be accomplished using the param statement in the scriptblock just like: Invoke-Command -ComputerName $Computer ` -ScriptBlock { param ( $ServiceName ) Get-Service -Name $ServiceName } ` -ArgumentList $ServiceName Of course, the Get-Service has a ComputerName parameter for this purpose but this is just an example.