【问题标题】:Looping in powershell script在powershell脚本中循环
【发布时间】:2020-01-14 00:11:22
【问题描述】:

我编写了一个脚本,其目的是从从 .txt 文件导入的计算机列表中列出目录中的所有文件,并将文件压缩到网络路径。不知道我写的对不对,希望大家看看有没有更好的办法告诉我。

脚本如下所示:

$destination = \\networkpath

$machines = (Get-Content "\\networkpath\machines.txt")

foreach ($machine in $machines) { $sourcefiles = gci "\\$machine\C$\localpath" }

foreach ($sourcefile in $sourcefiles) { 
    Compress-Archive -Path "\\$machine\C$\localpath" -Destinationpath "$Destination\$Sourcefile.zip" -CompresionLevel Optimal -Verbose }

该脚本适用于一台机器(文本文件中的最后一台),所以看起来它只是没有循环,可能是因为我正在使用这个双 foreach 循环。我尝试将 $sourcefiles 的输出通过管道传输到压缩存档,但这不会单独压缩文件。

我在这里出错的任何想法将不胜感激!

【问题讨论】:

    标签: windows powershell scripting


    【解决方案1】:

    当你在这里循环时,

    foreach ($machine in $machines) { $sourcefiles = gci "\\$machine\C$\localpath" }
    

    $sourcefiles 将始终是最后一台机器的源文件。您将需要跟踪每台机器的源文件,并在每台机器上运行这些文件。遍历机器一次,然后在一个循环中运行两个命令。

    【讨论】:

    • 知道了,你能想出一种方法,我可以在脚本中不为每台机器添加一行的情况下做到这一点吗?
    【解决方案2】:

    你需要做一个内部循环而不是一个单独的循环。 这样,您可以在迭代文件时访问$machine 的当前值。

    $destination = "\\networkpath"
    
    $machines = (Get-Content "\\networkpath\machines.txt")
    
    foreach ($machine in $machines) {
            $SourceFiles = Get-ChildItem -Path  "\\$machine\C$\localpath"
            Foreach ($SourceFile in $SourceFiles ) {
                    Compress-Archive -Path "\\$machine\C$\localpath" -Destinationpath "$Destination\$Sourcefile.zip" -CompresionLevel Optimal -Verbose 
            }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-11-22
      • 2017-04-17
      • 1970-01-01
      • 1970-01-01
      • 2022-10-17
      • 1970-01-01
      • 2014-11-10
      • 2022-07-14
      • 1970-01-01
      相关资源
      最近更新 更多