Using a variable to add a paramenter in a command


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 }

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

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.

Dave Wyatt,


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)]

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

Good point Max