MisterM
MisterM

Reputation: 41

Execute command against all files in folder

I have a list of .pem files I want to convert to .ppk using winscp.com.

The command is:

WinSCP.com /keygen filename.pem /output=filename.ppk

How do write a script that will automatically read all *.pem files in the folder and convert them to ppk?

I presume I need to use this for a start

Get-ChildItem -Recurse -Include "*.pem" | % { & $_ }

But how do I capture filenames and make it so it will replace the lines in the command and process all dozens of pem files in a folder?

Upvotes: 1

Views: 3690

Answers (3)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200383

& is the PowerShell call operator. $_ is an automatic variable holding the current object in a pipeline, in this case System.IO.FileInfo objects. For this kind of object the expression & $_ calls the default handler (the associated program) on the file, same as if you'd double-clicked the file in Explorer.

To get the code to do what you want you need to replace $_ with your winscp.com statement and replace the filename literals with appropriate variables. Use $_.FullName for the full name of the file. Change the extension for the output file and put that path in a different variable.

Get-ChildItem -Recurse -Include "*.pem" | % {
  $outfile = Join-Path $_.DirectoryName ($_.BaseName + '.ppk')
  & winscp.com /keygen $_.FullName "/output=$outfile"
}

Upvotes: 2

Esperento57
Esperento57

Reputation: 17472

try Something like this

$msbuild = "C:\pathofexefile\WinSCP.com"
$formatstring="/keygen {0} /output={1}.ppk"

Set-Location "c:\temp"

gci -file -Filter "*.txt"  | %{$arguments=($formatstring -f $_.FullName, $_.BaseName);start-process $msbuild $arguments  }

Upvotes: 0

Junaid
Junaid

Reputation: 603

This will give you the file name and full name. The difference is full name includes the complete path and name is just the file name.

 Get-ChildItem c:\users\somefolder -Recurse -filter "*.pem" | foreach{
   $name = $_.Name
   $fullName = $_.FullName
   Write-Output $name
   Write-Output $fullName
 }

If you run this you will understand. So you can get the name like this and then run any other command inside the foreach loop with the $name variable.

Upvotes: 1

Related Questions