How do you get a script to start again from the top?

This topic contains 2 replies, has 2 voices, and was last updated by  Barry Thomson 3 years, 11 months ago.

  • Author
    Posts
  • #9991

    Barry Thomson
    Participant

    Hi,

    Sorry, total nooby question here. I've just started trying to learn powershell, and have a simple script that I use to find Mac addresses.

    $Name = Read-Host "Enter Machine Name"
    Get-WmiObject win32_networkadapter -ComputerName $Name |
    where {$_.physicaladapter -eq $true} |
    Select-Object macaddress,netconnectionid
    PAUSE

    I'd like for this script, once finshed, to prompt the user to continue, and then go back to the start. Could someone point me in the right direction?

    Many thanks

  • #9992

    Richard Siddaway
    Moderator

    First question has to be what are you trying to achieve?

    if this meant to be an interactive tool or are you trying to get the MAC address of a number of machines

    I'm going to assume the latter in which case you want something like this:

    param ([string]$name)
    Get-WmiObject -Class Win32_NetworkAdapter -Filter "PhysicalAdapter = $true" -ComputerName $Name |
    Select-Object macaddress,netconnectionid

    The param block accepts the name of the computer. I moved the filter into the Get-WmiObject -Filter because then the filter happens on the remote machine not your local machine
    Save the script as get-macaddress
    You can use it like this
    .\get-macaddress.ps1 -name server02
    .\get-macaddress.ps1 -name server03
    .\get-macaddress.ps1 -name exch10

    Better still make the script a function that accepts pipeline input

    function get-macaddress {
    [CmdletBinding()]
    param (
    [parameter(ValueFromPipeline=$true)]
    [string]$Computername
    )
    PROCESS {
    Get-WmiObject -Class Win32_NetworkAdapter -Filter "PhysicalAdapter = $true" -ComputerName $Computername |
    Select-Object PSComputerName, macaddress,netconnectionid
    }
    }

    Load the function like this:
    . .\get-macaddress.ps1

    You can then use it like this:
    get-macaddress -Computername server02
    get-macaddress -Computername server03
    get-macaddress -Computername exch10
    "server02", "server03", "exch10" | get-macaddress

    I would strongly urge you to buy and read Powershell in a Month of Lunches (www.manning.com/jones3) which is the best introduction to PowerShell

  • #9993

    Barry Thomson
    Participant

    This is fantastic, thank you.

    I'm reading Windows Powershell 3.0 First Steps, at the moment, and will probably read your suggestion too.

You must be logged in to reply to this topic.