Narktor
Narktor

Reputation: 1037

What does "-" do in Powershell

I'm new to powershell and I'm still trying to understand the syntax. In a command like this

Get-ChildItem *.txt | Rename-Item -NewName { $_.name -Replace '\.txt$','.log' }

What does - actually do? Sometimes it is there, sometimes not, and I just don't understand what purpose it has xD

Upvotes: 2

Views: 177

Answers (3)

Srini V
Srini V

Reputation: 11355

-LiteralPath is what the meaning of using -. It's for paramters.

From your example, -NewName is treated as a parameter and -Replace is the operator

EDIT: As Peter rightly pointed out; amended the answer

Upvotes: 1

Ranadip Dutta
Ranadip Dutta

Reputation: 9133

In Powershell, All the parameters of a specific cmdlet has been defined to start with "-". It indicates the parameters are for the corresponding cmdlet.

All the cmdlets are functions that are written in Csharp or Powershell functions where they have defined the way to pass the argument of the parameters like:

Get-ChildItem *.txt | Rename-Item -NewName { $_.name -Replace '\.txt$','.log' }

Get-Childitem is the cmdlet which has a -include paramater and whose value is **.txt*. So even though you have not given the parameter name , powershell has the capability to identify certain parameters value by native. So that is the reason it is having no issue.

Similarly when you are piping the output of the first cmdlet to the second one (which is Rename-item) , it has a parameter -NewName whose value has been passed as an output of the entire {$_.name -Replace '.txt$','.log' }

Hope it helps you.

Upvotes: 1

Matt
Matt

Reputation: 46710

The hyphen character in PowerShell has a variety of uses that are context specific. It is primarily used in cmdlet names, parameters, operators and of course as a character literal.

CMDLet names

It is commonly used as a verb-noun separator e.g. Get-ChildItem. This is an encouraged practice when making custom functions and cmdlets as well.

Parameters

Used to tell the parser that a word denotes a parameter e.g. Rename-Item -NewName. In the example it is -NewName

Operators

This is a broad section but you will see the hyphen denote operators like -replace in your code sample. It does not always have a keyword associated either which is the case with arithmetic operators (-) and assignment operators (-=). You will also see the hyphen with comparison, containment, pattern-matching/text and logical/bitwise operators.

Upvotes: 3

Related Questions