【问题标题】:powershell loop trough files and execute command against itpowershell 循环遍历文件并对其执行命令
【发布时间】:2021-12-05 12:37:44
【问题描述】:

我正在研究如何遍历一组文件并针对这些文件执行一个程序,该程序在扫描 hyper-v 虚拟硬盘时输出一个日志和 tar 文件。

我已经想到的是以下内容: 将所有 VHDX 收集到一个卷上。将它们放入变量中。

但是,我一直在处理 foreach,以及灵活输出 tar 文件和日志名称。

例子:

Get-ChildItem -Path $VDHXPath -Filter $Extension -Recurse -ErrorAction SilentlyContinue -Force | % { $_.FullName }

其中 $VHDXPath 表示代表驱动器号的可自定义变量。 这样我就得到了一个填充有一个或多个 VHDX 的变量。

比我需要针对查询/库存的 VHDX 执行程序。平面单文件/直行命令行如下:

win.exe guid -o "tarfile.tar" -l "logfile.log" -p default --history "pathtovhdxfile.vhdx"

所以我已经尝试了许多如何执行 foreach 并调用命令来与 VHDX 对话的变体。示例:

Foreach ($file in $files){
Start-Process -NoNewWindow -FilePath ".\win.exe" -ArgumentList "guid -o tarfile.tar -l logfile.tar -p default --history vhdxfile.vhdx"
}

其中 tar 文件和日志文件的输出必须与正在处理的 VHDX 的名称匹配。

我也试过了:

Foreach ($file in $files){
& ".\win.exe" "guid -o tarfile.tar -l logfile.tar -p default --history vhdxfile.vhdx"
}

很遗憾没有结果。我要么提到该程序不是有效的 powershell cmd-let 或可执行程序。或者程序本身的反应是 tarfile、logfile 和 vhdxfiles 无效,因为命令行一次获取所有 VHDX'。

目标是获取一个 tar 和日志文件,其中包含它处理的每个 VHDX 的名称。

任何指导将不胜感激

编辑:

我说得更远了:

$VDHXPath = "C:\Users\%USERNAME%"
$Extension = "*.VHDX"
Foreach ($file in Get-ChildItem -Path $VDHXPath -Filter $Extension -Recurse -ErrorAction SilentlyContinue -Force | % { $_.FullName }) {
   
   & .\win.exe guid -o '.\$file.name'.tar -l '.\$file.name'.log -p default --history $file
}

所以现在程序会遍历文件,但我只是在为每个 VHDX 日志文件名和 tar 文件名而苦苦挣扎。

【问题讨论】:

  • “tar 文件和日志文件的输出,必须与正在处理的 VHDX 的名称相匹配”——“必须匹配”是什么意思?您是否需要引用与Get-ChildItem 发现的vhdx 文件在同一目录中 的tar 文件?
  • @MathiasR.Jessen 我的意思是说,我正在扫描位于 D:\Hyper-V\Computer1\Computer1.vhdx 中的名为 Computer1 的 VDHX,单独的日志和 tar 文件名必须是:computername1.tar 和 computername1.log,所以对于我扫描的每个 vhdx,我都会得到一个单独的日志和 tar 文件。

标签: powershell foreach command exe get-childitem


【解决方案1】:

使用$file.BaseName 获取不带扩展名的文件名。要在可扩展字符串中扩展成员表达式(如 $file.FullName),请使用 $() 子表达式运算符:

Foreach ($file in Get-ChildItem -Path $VDHXPath -Filter $Extension -Recurse -ErrorAction SilentlyContinue -Force) {
   $basename = $file.BaseName
   & .\win.exe guid -o ".\${basename}.tar" -l ".\${basename}.log" -p default --history "$($file.FullName)"
}

【讨论】:

  • 奇怪的是,我仍然看到 .log 和 tar.tar 文件,没有生成文件名。我错过了什么?
  • @loewie1984 我的错,我忘了从你现有的脚本中删除 | % { $_.FullName },再试一次
  • 你我的英雄! :) 来自 NL 的亲切问候。见你也在那里。这行得通!
猜你喜欢
  • 2013-10-24
  • 2018-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-18
  • 2020-06-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多