Newbie to Powershell and Programming

This topic contains 0 replies, has 1 voice, and was last updated by Profile photo of Forums Archives Forums Archives 5 years, 3 months ago.

  • Author
    Posts
  • #5219

    by spoony123 at 2012-10-22 08:11:05

    Hi I am just trying a few things in Powershell at the moment and am just practising with a very basic script that

    1.Checks for services with a particular name
    2.Selects that object
    3.Exports the Service Name and PC name to a CSV file.

    The problem i have is that in the excel spreadsheet the following is returned

    @{Name=Browser},PC1

    The hostname picks ups but Why does the Service name get put in brackets and prefixed with "Name=" in the Excel Spreadshee
    My code is below

    $a = get-service | where-object {$_.name -eq "browser"} | select-object name
    $system = hostname

    ("$a,$system") | Out-file -append c:\temp\database.csv

    This is probably something very simple to do with formatting or more likely bad code! Any pointers greatly recieved/

    by DonJ at 2012-10-22 08:22:21

    That's because $a is a service object, not just the service's name. A service consists of more than it's name.

    "$($a.name),$system"

    Would do what you want.

    A somewhat different approach:


    $system = 'hostname','otherhost','thirdhost'
    foreach {
    Get-Service -computername $_-name "browser" | select Name,@{n='system'=e={$_}}
    } | Export-CSV database.csv

    by spoony123 at 2012-10-22 08:42:07

    Hi Don,

    Thanks for the reply you additions worked just right – i would never have got that i don't think. So thankyou. However the additional script provided had the below errors, can you advise.

    Missing opening '(' after keyword 'foreach'.
    At line:2 char:9

    Invalid assignment expression. The left hand side of an assignment operator needs to be something that can be assigned to like a variable or a property.
    At line:3 char:73

    Missing closing '}' in statement block.
    At line:4 char:33

    by DonJ at 2012-10-22 08:56:24

    Check your typing. My example doesn't have any parentheses; they're { curly brackets. There was a typo, though – it should be a ; in front of the e:

    $system = 'hostname','otherhost','thirdhost'
    foreach {
    Get-Service -computername $_ -name "browser" | select Name,@{n='system';e={$_}}
    } | Export-CSV database.csv

    by spoony123 at 2012-10-23 09:12:07

    Thanks guys – this one can now be marked as solved.

You must be logged in to reply to this topic.