【问题标题】:Execute command against all files in folder对文件夹中的所有文件执行命令
【发布时间】:2017-04-04 09:35:15
【问题描述】:

我有一个 .pem 文件列表,我想使用 winscp.com 转换为 .ppk。

命令是:

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

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

我想我需要用这个开始

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

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

【问题讨论】:

    标签: powershell putty


    【解决方案1】:

    & 是 PowerShell call operator$_ 是一个 automatic variable,在管道中保存当前对象,在本例中为 System.IO.FileInfo 对象。对于这种对象,表达式& $_ 调用文件的默认处理程序(关联程序),就像您在资源管理器中双击文件一样。

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

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

    【讨论】:

    • 就像一个魅力 - 谢谢!刚刚向 winscp.com 位置添加了一个变量,它会转换 $scpfile
    【解决方案2】:

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

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

    如果你运行它,你就会明白。因此,您可以像这样获取名称,然后使用 $name 变量在 foreach 循环中运行任何其他命令。

    【讨论】:

      【解决方案3】:

      试试这样的

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-18
        • 1970-01-01
        相关资源
        最近更新 更多