Up until now we havent really been scripting. Its basically been single or linked commands, and the most advanced things we covered is WMI, parameters, and functions. Today, according to Don, is when we start getting to "Scripting" and its slightly more programming oriented constructs.
First up, IF! The IF construct is similar to that of DOS or the CMD shell IF. It allows you to right a command that would return a true or false ($True or $False in PowerShell) and have another command performed. Microsoft expounds on the IF statement with ElseIF and Else. The ElseIF is what would run in the case that your IF statement is not true. Else would be what would run if the statement is neither true or false, say if your command returned a value instead of true or false. The syntax is pretty straight forward
If (property-eq '1000') {
#command you want to perform#}ElseIF { Property-eq '999') {
#command you want to perform#
}Else {
#final command you want to perform#
}
Here is an example that I created to look at every service name starting with the letter B. It labels the ones I am looking for and annotate the ones that I don’t. I even color coded the Write-Host output. I Went a little Obi Wan here but it gets the point across.
$services = Get-Service -Name 'B*'
foreach($Service in$services) {
If($service.servicename -eq 'BITS') {
Write-Host'Background Intelligent Transfer Service' -fore Red
} ElseIf($service.servicename -eq 'BDESVC'){
Write-Host'Bitlocker Encryption Service' -fore Red
} Else{
Write-Host'These are not the services you are looking for'`
-fore black-back White
}
}
Up next is the For construct. This will allow you to put a script block into a loop for a specified number of times. Once again the syntax is the same for this as it is with the previous two.
Now we get to ForEach. This is the most useful of these constructs and the one I have spent the most time on. Notice that I use this one in previous script example. ForEach allows you to enumerate each object in a collection and perform a command against it. In my previous example I created a variable that stored each service that started with the letter 'B'. I then put that variable into aForEach loop that looks at each service object and enumerates the service name property. If it matched the value I was looking for I had it Write-Host the name of the service. If it did not then I had it Write-Host that it wasn’t what I was looking for.
All in all this was a very enjoyable lesson and I learned quite a lot about the way that constructs work and how to format them. I actually wrote a script by myself and didn’t even use the internet. Im so proud of myself. : )
No comments:
Post a Comment