Using a variable to add a paramenter in a command

Welcome Forums General PowerShell Q&A Using a variable to add a paramenter in a command

This topic contains 6 replies, has 4 voices, and was last updated by

 
Participant
3 years ago.

  • Author
    Posts
  • #32955

    Participant
    Points: 42
    Rank: Member

    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

    Participant
    Points: 42
    Rank: Member

    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

    Member
    Points: 0
    Rank: Member

    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

    Participant
    Points: 42
    Rank: Member

    Dave Wyatt,

    Thanks!

  • #32981

    Participant
    Points: 0
    Rank: Member

    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

    Participant
    Points: 0
    Rank: Member

    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

    Participant
    Points: 0
    Rank: Member

    Good point Max

The topic ‘Using a variable to add a paramenter in a command’ is closed to new replies.