对文件夹中的所有文件执行命令

Execute command against all files in folder

我有一个 .pem 文件列表,我想使用 winscp.com.

将其转换为 .ppk

命令是:

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

如何编写一个脚本,自动读取文件夹中的所有 *.pem 文件并将它们转换为 ppk?

我想我需要先用这个

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

但是我如何捕获文件名并使其能够替换命令中的行并处理一个文件夹中的所有数十个 pem 文件?

这将为您提供文件名和全名。不同之处在于 full name 包括完整路径,而 name 只是文件名。

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

如果你运行这个你就明白了。因此,您可以获得这样的名称,然后使用 $name 变量 运行 foreach 循环内的任何其他命令。

试试这样的东西

$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  }

& 是 PowerShell call operator. $_ is an automatic variable holding the current object in a pipeline, in this case System.IO.FileInfo 对象。对于这种对象,表达式 & $_ 调用文件的默认处理程序(关联程序),就像您在资源管理器中双击文件一样。

要让代码执行您想要的操作,您需要将 $_ 替换为 winscp.com 语句,并将文件名文字替换为适当的变量。使用 $_.FullName 作为文件的全名。更改输出文件的扩展名并将该路径放在不同的变量中。

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