powershell - 如何将 get-childitem 的结果传递到命令中?

标签 powershell

我的目录结构中有几个目录、子目录等,其中一些会有各种匹配文件。例如如果X.config.default存在于目录中,它也会有一个相应的X.config.build

c:\Stuff\dir1
web.config.default
web.config.build

c:\Stuff\dir2
app.config.default
app.config.build

c:\Stuff\dir2\sub2
foo.config.default
foo.config.build
bar.config.default
bar.config.build
这将显示所有匹配 *.config.default 的文件名及其相应的目录
get-childitem -Recurse *.* -Filter *.config.default | Select Name, Directory

但是我不想显示文件及其路径,而是想为每个“匹配”做一些事情。在本例中,我想调用一个名为 ctt 的程序并向其发送三个参数。 ctt 的调用方式如下:

ctt s:<source file> t:<transform file> d:<destination file>

假设第一个匹配项在目录 c:\Stuff\dir1 中名为 fubar,则执行的 ctt 命令应如下所示:

ctt s:c:\Stuff\dir1\fubar.config.default t:c:\Stuff\dir1\fubar.config.build d:c:\Stuff\dir1\fubar.config pw

我猜有几种方法可以做到这一点。将 get-childitem 结果通过管道传输到命令中,或者将它们发送到某种集合,我可以在其中执行 foreach 循环。

谢谢

最佳答案

有几种不同的方法可以解决这个问题。如果您使用的是旧版本的 PowerShell,您很可能只使用 ForEach-Object cmdlet。

Get-ChildItem -Path c:\Stuff\* -Recurse -Filter *.config.default | 
  ForEach-Object -Process {
    $BuildName = $PSItem.Name.Split('.')[0] ### Get just the "fubar" part.
    ctt s:"$($PSItem.FullName)" t:"$($PSItem.Directory.FullName)\$BuildName.config.build" d:"$($PSItem.Directory.FullName).config" pw
  }

在较新版本的 PowerShell 上,从 4.0 开始,您可以使用 ForEach() 方法语法。

http://social.technet.microsoft.com/wiki/contents/articles/26489.powershell-4-0-where-and-foreach-method-syntax.aspx

(Get-ChildItem -Path c:\Stuff\* -Recurse -Filter *.config.default).ForEach({ 
  $BuildName = $PSItem.Name.Split('.')[0] ### Get just the "fubar" part.
  ctt s:"$($PSItem.FullName)" t:"$($PSItem.Directory.FullName)\$BuildName.config.build" d:"$($PSItem.Directory.FullName).config" pw
}

关于powershell - 如何将 get-childitem 的结果传递到命令中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40393333/

相关文章:

ssl - 在 PowerShell 上使用 netsh 失败并出现错误 : The parameter is incorrect

windows - 从 PowerShell 调用 Windows 运行时类 - window 8 Lockscreen Switcher

powershell - 如何使用 PowerShell 导入 CSV 文件?

powershell - 在 Powershell 中创建带前导零的文件夹

powershell - 如何在 PowerShell 中读取多行多字符串注册表项?

powershell - 将get-process用于未运行的进程时,如何防止错误消息?

Powershell:从 runas/netonly 启动时发现默认网络凭据

powershell - 与对象的属性进行比较时,Get-ADUser -Filter 失败

powershell - Sitecore Powershell get-user命令