Using a variable to add a paramenter in a command

This topic contains 6 replies, has 4 voices, and was last updated by Profile photo of Curtis Smith Curtis Smith 1 year, 5 months ago.

  • Author
    Posts
  • #32955
    Profile photo of Vandrey Trindade
    Vandrey Trindade
    Participant

    Hi,

    I'm trying to do something that I don't know if I'm doing the right way.
    I'm doing a script to get event logs from a machine, and want to give options to the user.
    Example of the command:

    Get-EventLog -LogName System | select -First 20

    So I want to give the option to show the first X records or show all records.
    What I've tried was:


    $period = "select | -First 20"
    Get-EventLog -LogName System $period

    But that doesn't work... and I don't want to make a if statement like:


    if ($period -ne $Null){
    Get-EventLog -LogName | select -First $period
    }
    else{
    Get-EventLog -LogName
    }

  • #32956
    Profile photo of Vandrey Trindade
    Vandrey Trindade
    Participant

    I was able to do what I want using this:


    $records = Read-Host "Type the amount of records desired"
    $period = "| select -First $records"
    $cmd = "Get-EventLog -LogName System $period"
    Invoke-Expression $cmd

    Still don't know if this is the best way

  • #32963
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    That's very dangerous. Whatever the user types gets executed, and they can do some nasty things that way (intentionally or by accident).

    You're going to wind up with an If statement somewhere regardless of what you do, if you want the select-object part to be optional. I'd just go with what's in your first post, personally.

  • #32974
    Profile photo of Vandrey Trindade
    Vandrey Trindade
    Participant

    Dave Wyatt,

    Thanks!

  • #32981
    Profile photo of Curtis Smith
    Curtis Smith
    Participant

    Here is a way to do what you want using array partitioning, but I agree with Dave. The 'if" option is better because the select cmdlet will stop the retrieval of the rest of the log file once the requested number of entries has been retrieved. Using this method, the entire event log is retrieved, but only the requested number of entries are displayed.

    $eventcount = 5
    (Get-EventLog -LogName System)[0..($eventcount - 1)]
    
  • #33029
    Profile photo of Max Kozlov
    Max Kozlov
    Participant

    Excusively for EventLog: there is -Newest parameter
    Get-EventLog -LogName system | select -first 10
    is equivalent of
    Get-EventLog -LogName system -Newest 10

    and usage of this parameter can be solved with splatting

    $params = @{LogName='System'}
    if ($wantLimit) {
     $params.Newest = 10
    #$params.Newest = $wantLimit
    }
    Get-EventLog @params
    
  • #33044
    Profile photo of Curtis Smith
    Curtis Smith
    Participant

    Good point Max

You must be logged in to reply to this topic.