如何针对 OU 中的每台计算机运行脚本

问题描述 投票:0回答:1

我需要解决这个问题;它只是提取本地服务器文件夹与远程计算机文件夹 - 我知道我在一些地方缺少 $PC,但我不确定这是否会按预期工作。

期望:删除计算机上每个用户的签名文件夹中的数据

$OUpath = 'ou=GPO Testing Ground,ou=Workstations,ou=Domain Computers,dc=test,dc=com'
$PCList = (Get-ADComputer -Filter * -SearchBase $OUpath | Select-object -expandproperty Name)

ForEach ($PC in $PCList) 
{
    Write-host $PC
    If (Test-Connection $PC -Count 1 -Quiet)
    {
        $TopFolder = 'c$\users'
        $SigFolder = 'AppData\Roaming\Microsoft\Signatures'
        $FolderList = Get-ChildItem $TopFolder -Directory -Exclude default, Public
        write-host $folderlist
        foreach ($Item in $FolderList)
            {
                write-host (Join-Path -Path \\$PC\$Item -ChildPath $SigFolder)
                if (Test-Path (Join-Path -Path $Item -ChildPath $SigFolder))
                {
                    $compPath = "$Item" + "\" + "$SigFolder" + "\*"
                    #Remove-Item $compPath -Recurse -WhatIf
                    Write-host $compPath
                }
            }
    }
}

powershell
1个回答
0
投票

看起来像您丢失的 $PC,因此它搜索本地 C: 而不是远程计算机。 修改此以满足您的需要。

$OUpath = 'ou=GPO Testing Ground,ou=Workstations,ou=Domain Computers,dc=test,dc=com'
$PCList = Get-ADComputer -Filter * -SearchBase $OUpath

ForEach ($PC in $PCList.dnshostname) 
{
    Write-host $PC
    If (Test-Connection $PC -Count 1 -Quiet)
    {
        #$TopFolder = 'c$\users' # This is the error - no $PC, its looking for the local C:\ not the remote system
        $TopFolder = '\\$PC\c$\users'
        $SigFolder = 'AppData\Roaming\Microsoft\Signatures'
        $FolderList = Get-ChildItem $TopFolder -Directory -Exclude default, Public
        write-host $folderlist
        # Use "Fullname" for the complete filepath
        foreach ($Item in $FolderList.Fullname) 
            {
                #write-host (Join-Path -Path "\\$PC\$Item" -ChildPath $SigFolder)
                $Folderpath = Join-Path -Path "$Item" -ChildPath $SigFolder
                write-host "Testing path to $Folderpath"
                if (Test-Path $Folderpath)
                {
                    #$compPath = "$Item" + "\" + "$SigFolder" + "\*"
                    #Remove-Item $compPath -Recurse -WhatIf
                    #Write-host $compPath
                    $SigFolderpath = "$Folderpath\$Sigfolder"
                    Write-host -for Yellow "Attempting to remove $SigFolderpath"
                    Remove-Item $SigFolderpath -Recurse -WhatIf                 
                }
                else
                {
                    Write-Warning "Test-Path failed for $PC"
                    Write-Host -for Red $Error[0].Exception.Message
                }
            }
    }
    else
    {
        Write-Warning "Test-Testconnection failed for $PC"
        Write-Host -for Red $Error[0].Exception.Message
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.