I would like to import a csv file containing a list of servers where I want tjek if a specific service is running and if it is not then start this service. Show the result in powershell
So… if $ServerList is a CSV file, I’m not sure why Get-ChildItem is in use. Get-ChildItem doesn’t read the contents of a file… I’m not sure what your intent was, there. Maybe I don’t understand the question. But you’re using $_ in some places that make no sense to me, I’m unsure why Format-Table is involved, and I don’t see where you’re passing a computer name to Invoke-Command.
Let’s maybe start over.
If ServerList.csv looks like:
ComputerName
SERVER1
SERVER2
This assumes I have a column header named “ComputerName,” which lets me reference the column. Then…
Would be the short way. You’d get errors for ones where the service was already started, since I didn’t actually check first on that second example, but hopefully that’s an illustration.
My issue is that foreach-object and get-childitem confuses me a lot. And also when to use { } or when to use ( ).
The format-table, was something I used in another script with PSremoting, where I had listed of a few servers comma-seperated, so in order to make it look nice I added the Format-table.
Btw, I don’t mind taking the long way as long as I learn something during that process. Thats the most important thing for me right now regarding powershell.
I’m very happy that you didn’t replaced Foreach with a % sign.
ForEach-Object: Takes one or more object, and runs a hunk of code for each object you give it. It is NOT the same as the ForEach language construct, although they have the same purpose.
Get-ChildItem: Gets a directory listing. It’s the real command behind “dir.”
{} encloses executable code. () encloses an expression. More on that in a minute.
Be really careful with formatting - see “The Big Book of PowerShell Gotchas.” Formatting can break more than it fixes when it’s in a script.
And I am not a huge fan of % as an alias, at least not when I’m trying to explain stuff ;).
{} and () confuses everybody. () is for expressions you want evaluated first - just like in math. For example:
if (5 -gt 10) { Do-This }
The () gets evaluated first, so this simplifies to (this isn’t real code, but it’s what goes in in PowerShell’s head):
if $false { Do-This }
OK, it’s False, so I won’t Do-This. The {} is a hunk of code - it’s what would have executed had the expression been True. It’s contained in {} so PowerShell can tell where the code begins and ends.