PowerShell Rookie and getting Powershell to accept input.

This topic contains 1 reply, has 2 voices, and was last updated by Profile photo of Dave Wyatt Dave Wyatt 3 years, 5 months ago.

  • Author
    Posts
  • #12617
    Profile photo of William Davis
    William Davis
    Participant

    So far, and with much help from a "MonthOfLunches" I am starting to make some progress. I have leaned that I can input questions for PS to answer in couple of different ways. Either by using a variable and read-host to query one machine, or by using a variable and the get-content cmdlet, them pass PS a UNC path. So here is my question that I am stuck on. I want to be able to prompt the admin/user to enter input, using a simple phrase like "Enter the machine name, or UNC path name to the text file" The admin would then either do one or the other. I can get this done right now but I have to use two different scripts, I would love to be able to use only one and have powershell fire up and deliver the info. This might be a little to advance for me right now, but I am at that point where I am getting a little creative, please help push me in the right direction if you can, SALUTE!

  • #12619
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    What you're describing is technically possible, but then you're faced with the challenge of parsing the user's input to tell whether it looks like a valid computer name or a valid UNC path. A more common way of accomplishing this in PowerShell is to define parameter sets, and the user can specify either -ComputerName or -Path when calling your script or function. For example, here's the skeleton of a script or function that would use that approach:

    [CmdletBinding(DefaultParameterSetName = 'ComputerName')]
    param (
        [Parameter(Mandatory, ParameterSetName = 'ComputerName', ValueFromPipeline)]
        [string[]]
        $ComputerName,
    
        [Parameter(Mandatory, ParameterSetName = 'InputFile')]
        [string[]]
        $Path
    )
    
    process
    {
        if ($PSCmdlet.ParameterSetName -eq 'ComputerName')
        {
            foreach ($computer in $ComputerName)
            {
                # Do something with $computer
            }
        }
        else
        {
            foreach ($file in $Path)
            {
                Get-Content -Path $file |
                ForEach-Object {
                    $computer = $_
    
                    # Do something with $computer
                }
            }
        }
    }
    

    If you want to actually prompt the user to enter input (which means the script has to be run interactively; it can't be run as a scheduled task, for instalce), use the Read-Host cmdlet:

    $userInput = Read-Host -Prompt 'Enter the machine name, or UNC path name to the text file'
    

You must be logged in to reply to this topic.