Access to elements of $_

Viewed 56

In order to create symlinks in PowerShell, you need to use the following command :

New-Item -Path C:\temp\myLink -Target C:\Users\{me}\Documents\target.txt -ItemType SymbolicLink

I would like to implement a more straightforward syntax as shown below :

"C:\temp\myLink", "C:\Users\{me}\Documents\target.txt" | Ln

Ln is a filter defined as such :

filter Ln {
     New-Item -Path $_[0] -Target  $_[1] -ItemType SymbolicLink
}

However, it doesn't work, and I would like to know how to access single elements of $_, for instance in our case shouldn't we have $_[0] == "C:\temp\myLink" ?

Thanks in advance for your help !

2 Answers

If you want to use the syntax proposed in your question an easy workaround would be to change your filter for a non-advanced function and utilize the automatic variable $input to collect both paths being passed through the pipeline:

function Ln {
    $params = @($input)
    if($params.Count -ne 2) {
        throw 'Unsoported!'
    }
    New-Item -Path $params[0] -Target $params[1] -ItemType SymbolicLink
}

"C:\temp\myLink", "C:\Users\{me}\Documents\target.txt" | Ln
Related