Re: Function Args
- From: "Kevin Loo [MSFT]" <kevinloo@xxxxxxxxxxxxxxxxxxxx>
- Date: Wed, 18 Jan 2006 15:04:47 -0800
The $args[0] in function foo {gps | where {$_.name -eq $args[0]}} is args to
the script block {$_.name -eq $args[0]}. In this case, $args[0] will be
$null. Since there isn't a process on the machine whose name is null, you
don't get any return.
You could try function foo {$firstArg = $args[0]; gps | where{$_.name -eq
$firstArg}}.
--
Kevin Loo [MSFT]
Microsoft Command Shell Development
Microsoft Corporation
This posting is provided "AS IS" with no warranties, and confers no rights.
"ebgreen" <ebgreen@xxxxxxxxxxxxxxxxxxxxxxxxx> ¼¶¼g©ó¶l¥ó·s»D:86B0E7F2-F261-48F0-9979-7E48250FCCA3@xxxxxxxxxxxxxxxx
>I was trying to make a quick and dirty process killer and I ran across
> something I don't understand. Here is a function that will do what I
> expect
> it to:
> function showit
> {
> $Args[0]
> }
> When you call the function with a parameter, the paramter is displayed:
> 14:55:09 C:\> showit foo
> foo
>
> This is a function that works
> function showNotepad
> {
> get-process | where{$_.ProcessName -eq "notepad"}
> }
> It will display the data on the notepad process if you have notepad open:
> 14:59:28 C:\> showNotepad
>
> Handles NPM(K) PM(K) WS(K) VS(M) CPU(s) Id ProcessName
> ------- ------ ----- ----- ----- ------ --
> -----------
> 47 2 1012 3404 30 0.09 5068
> notepad
>
> This function does not work:
> function doNotShow
> {
> get-process | where{$_.ProcessName -eq $Args[0]}
> }
> If you run it looking for notepad you get nothing back:
> 15:03:56 C:\> doNotShow notepad
> 15:04:01 C:\>
>
> And then lastly, this does work:
> function showProcess
> {
> param([string]$proc)
> get-process | where{$_.ProcessName -eq $proc}
> }
> You get the info on running processes named whatever you pass to it:
> 15:09:05 C:\> showProcess notepad
>
> Handles NPM(K) PM(K) WS(K) VS(M) CPU(s) Id ProcessName
> ------- ------ ----- ----- ----- ------ --
> -----------
> 47 2 1036 3428 30 0.19 4320
> notepad
> 47 2 1012 3408 30 0.09 5068
> notepad
>
>
> Now I suspect this behavior has to do with the explicit cast that the
> param
> does, but I was looking for some confirmation just to better help me
> understand.
.
- Follow-Ups:
- Re: Function Args
- From: Keith Hill [MVP]
- Re: Function Args
- Prev by Date: Re: Function Args
- Next by Date: Re: [MSH] Profiles and Variables
- Previous by thread: Re: Function Args
- Next by thread: Re: Function Args
- Index(es):
Relevant Pages
|