Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an equivalent of "this" in powershell?

Tags:

powershell

Basically I have this code:

$file = $web.GetFile("Pages/default.aspx")
$file.CheckOut()

and I was wondering if there is anyway to use a pipe and the powershell equivalent of this to rewrite it as:

$web.GetFile("Pages/default.aspx") | $this.CheckOut()

When I try this I get the error:

Expressions are only allowed as the first element of a pipeline.

I also tried using $_ instead of $this but got the same error.

like image 826
Abe Miessler Avatar asked Dec 16 '11 16:12

Abe Miessler


People also ask

What is $_ in PowerShell?

The “$_” is said to be the pipeline variable in PowerShell. The “$_” variable is an alias to PowerShell's automatic variable named “$PSItem“. It has multiple use cases such as filtering an item or referring to any specific object.

What does $() mean in PowerShell?

Subexpression operator $( ) For a single result, returns a scalar. For multiple results, returns an array. Use this when you want to use an expression within another expression. For example, to embed the results of command in a string expression. PowerShell Copy.

What is $PSScriptRoot in PowerShell?

$PSScriptRoot variable in PowerShell PowerShell $PSscriptRoot contains the full filesystem path of the directory from which the current script or command is being executed or run.


2 Answers

Actually there is a $this in a few cases. You can create a ScriptProperty or ScriptMethod and attach it to an object, and $this will be the original object. You can then define these in types files (I'd recommend using the module EZOut, it makes life much easier) so that any time you see that type, you get that method.

For example:

$Web  | Add-Member ScriptMethod EditFile { $this.Checkout() }

Hope this helps

like image 170
Start-Automating Avatar answered Oct 16 '22 14:10

Start-Automating


What you're looking for is $_ and it represents the current object in the pipeline. However you can only access $_ in a scriptblock of a command that takes pipeline input e.g.:

$web.GetFile("Pages/default.aspx") | Foreach-Object -Process {$_.Checkout()}

However there are aliases for the Foreach-Object cmdlet {Foreach and %} and -Process is the default parameter so this can be simplified to:

$web.GetFile("Pages/default.aspx") | Foreach  {$_.Checkout()}

One other point, the GetFile call appears to return a single file so in this case, the following would be the easiest way to go:

$web.GetFile("Pages/default.aspx").Checkout()

Of course, at this point you no longer have a variable containing the file object.

like image 44
Keith Hill Avatar answered Oct 16 '22 13:10

Keith Hill