Friday, May 6, 2011

$$ Recursion?

After reading Lee Holmes $$ blog post, I realized the $$ command has some recursive properties.
You can assign a function to the $$ variable and then init that function as follows:



Function Repeat-History
{
$$='function gh {get-history}'
Invoke-History $$
gh
}



This allows us to do some interesting work. The function below will run through  a class C subnet pinging port 443 with a TCP based ping.   It does this by loading the "$$" variable with an nping cmd, echoing the command , and then using invoke-expression ('iex') to load the results into a file.  The advantage of  'executing your label' ...


function global:nmap_subnet
{
   [CmdletBinding()]
   Param(
        [string] $subnet,
        [string] $ErrorActionPreference="silentlycontinue"
         )

0..255 |% {$$="C:\tools\nmap-5.51-win32\nmap-5.51\nping -c 1 --tcp -p 443 $subnet.$_"
$$
iex $$ | findstr RCVD | out-file -append $subnet
}
}

No comments: