Powershell pipe in string

I tried to rename some files using powershell script below

 powershell.exe "& { Get-ChildItem *.txt | Rename-Item -NewName { $_.name -Replace '.txt','.csv' } }"

      

But it $_.name

appears to be parsed when executed "& command"

, so it complains that it doesn't know .name

(with already removed $_

). Doing this without the outer line solves the problem, but for other reasons it is not possible in my case.

How to avoid $_.name

?

+3


source to share


3 answers


This works great:



powershell.exe "& { Get-ChildItem *.txt | Rename-Item -NewName { `$_.name -Replace '.txt','.csv' } }"

      

+2


source


I don't see anything wrong with your original command, but personally I would use Path.ChangeExtension

instead-replace

powershell.exe -command "& {Get-ChildItem *.txt | Rename-Item -NewName { [io.path]::ChangeExtension($_.name, 'csv') }}"

      



Or as you seem to be calling PowerShell from the command line, you can just use the "rename" command (and not use PowerShell at all):

ren *.txt *.csv

      

0


source


powershell.exe "& {
    Get-ChildItem -Filter *.txt | ForEach-Object {`$_.Name}
}"

      

Backticks triggers special characters in PowerShell strings

`

      

-1


source







All Articles