【问题标题】:Run powershell script for each folder with subfolders为每个带有子文件夹的文件夹运行 powershell 脚本
【发布时间】:2019-01-19 05:10:05
【问题描述】:

我有一些脚本需要针对十几个文件夹运行,它们都具有相对路径。我正在尝试使用一个主脚本来解决这个问题,该脚本为该路径中的每个文件夹运行,一次一个文件夹。这些文件夹都是以下路径中“here”文件夹的所有子文件夹。我似乎无法正确使用语法,但我想我已经接近了:)

有没有更有效的方法来针对目录中每个文件夹的内容运行脚本,一次一个文件夹?

$pdfFolder = 'C:\path\to\folders\here'
$Completed = Get-ChildItem $pdfFolder -Recurse

ForEach-Object ($Completed){
Invoke-Expression -Command "C:\path\where\scriptis\script.ps1"
}`

【问题讨论】:

    标签: powershell


    【解决方案1】:
    $pdfFolder = 'C:\path\to\folders\here'
    
    # Get all subfolders - note the -Directory switch (PSv3+)
    $Completed = Get-ChildItem $pdfFolder -Recurse -Directory
    
    # Pipe the subfolders to ForEach-Object, invoke the
    # script with & (avoid Invoke-Expression), and pass the subfolder
    # at hand as an argument.
    $Completed | ForEach-Object {
      & "C:\path\where\scriptis\script.ps1" $_
    }
    

    至于你尝试了什么

    Get-ChildItem $pdfFolder -Recurse

    此命令不仅返回文件夹(目录),还返回文件。要将输出限制为文件夹,请传递开关 -Directory (PSv3+)。


    ForEach-Object ($Completed) { ... }

    您将foreach loop 的语法与基于管道的ForEach-Object cmdlet 的语法混淆了。
    该 cmdlet 需要来自 管道 的输入,因此您必须改用
    $Completed | ForEach-Object { ... }

    另请注意,除非您确实需要首先将所有子文件夹收集到一个数组中,否则您可以简单地将您的 Get-ChildItem 调用直接传递给 ForEach-Object


    Invoke-Expression -Command "C:\path\where\scriptis\script.ps1"

    Invoke-Expression should be avoided,因为它很少是正确的工具,并且可能存在安全风险。

    您只需使用&, the call operator,通过其引用 和/或存储在-a-变量 文件路径中调用脚本即可,如上所示。

    【讨论】:

      猜你喜欢
      • 2020-07-04
      • 2014-06-11
      • 1970-01-01
      • 2020-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-27
      • 2023-01-19
      相关资源
      最近更新 更多