PowerShell - 双循环可能吗?

标签 powershell loops foreach compress-archive

我想将目录压缩到特定位置。 源路径为:\\$Computers\Users\$Names

我想要每台计算机的源路径中的每个用户目录的副本

我尝试使用 foreach 循环,例如:

$Computers = Get-ADComputer -Filter "Name -like 'PC*'" | Select-Object -ExpandProperty Name
$Names = Get-aduser -filter * | Select-Object -ExpandProperty givenname 

Foreach($Computer in $Computers)
{
    Compress-Archive -Path \\$Computer\Users\* -DestinationPath C:\Saves\\$Computer\Test.zip -Force
}

这确实有效,但我不知道如何在循环内添加第二个循环。

如果有人可以向我解释该功能或只是一些建议,请尝试这样做。

感谢您的宝贵时间。

最佳答案

您正在用错误的逻辑解决问题,您确实需要一个内部循环,但是,您可以查询远程计算机的,而不是尝试压缩您不确定是否存在的用户配置文件>Users 文件夹以查看其中有哪些并仅压缩那些:

$Computers = (Get-ADComputer -Filter "Name -like 'PC*'").Name
# Add the profiles you want to exclude here:
$toExclude = 'Administrator', 'Public'
$params = @{
    Force = $true
    CompressionLevel = 'Optimal'
}

foreach($Computer in $Computers)
{
    $source = "\\$Computer\Users"
    Get-ChildItem $source -Exclude $toExclude -Directory | ForEach-Object {
        $params.LiteralPath = $_.FullName
        # Name of the zipped file would be "ComputerExample - UserExample.zip"
        $params.DestinationPath = "C:\Saves\$computer - {0}.zip" -f $_.Name
        Compress-Archive @params
    }
}

关于PowerShell - 双循环可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71011035/

相关文章:

c# - 为什么我不能声明已声明的同名变量,但新变量不在其他变量的范围内

php - 从数据库中检索数据

powershell:错误的符号链接(symbolic link)解析

powershell - 如何从Powershell脚本中的列表中查询

sql-server - 存储过程调用另一个存储过程挂起很长时间

java - 有没有更好的方法来编写这个循环?

javascript - 想要打印 json 对象的循环但无法从 json 对象访问值

php - 跳过foreach mysql中的重复条目

powershell - Remove-AdObject with Import-CSV 错误

powershell - 如何将 Windows 服务设置为在 PowerShell 中自动启动?