Вставить оператор ForEach в другой ForEach на удаленном компьютере - PullRequest
0 голосов
/ 30 января 2020

Как всегда, новичок в powershell и попытка самообучения. Заранее всем спасибо:

У нас есть сценарий входа, который автоматически устанавливает реестр на НАШУ домашнюю страницу. Когда мы собираем компьютеры, мы помещаем скрипт входа в папку C: \ Users \ Default \% Appdata% \ roaming .... \ startup \. Таким образом, любой новый пользователь, который входит в систему, получает bat-файл в свою папку% AppData%, а его домашняя страница автоматически настраивается.

Мы недавно создали новый сервер, и из-за некоторых проблем нам нужно изменить наш URL домашней страницы, поэтому необходимо изменить файл logon.bat на всех компьютерах для всех профилей пользователей.


Этот скрипт, который я нашел здесь, работает отлично, но только на локальном компьютере, на котором он работает:

$source = '\\ITE00463866\Applications\_Layer1_Installs\TS Sector\firstlogon.txt'
$profilesfolder = 'c:\users\'
$excluded_profiles = @( 'All Users', 'Default User', 'Default.migrated', 'Public', 'DefaultAppPool', 'cdwuser', '.NET v4.5 Classic', '.NET v4.5')
$profiles = get-childitem $profilesfolder -Directory -force | Where-Object { $_.BaseName -notin $excluded_profiles }
$targetfolder = "\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup"

foreach ($profile in $profiles) {
    $destination = $profilesfolder + $profile + $targetfolder
    If ( $(Try { Test-Path $destination.trim() } Catch { $false }) ) {

        copy-item -path $source -destination $destination -Force -Verbose
        }
    Else {

       New-Item -Path $destination -ItemType Directory
       copy-item -path $source -destination $destination -Force -Verbose
        }
    } 

Я пытался добавить вышеупомянутое утверждение ForEach ВНУТРИ Get-Content | FOREACH ($ P C in $ Computers) {....}, но вы получите все эти проблемы с ODD, и это повлияет только на локальную машину, на которой выполняется скрипт. Например, беря каждую папку в моей папке System32 и создавая пользователя с именем независимо от имени папки System32, затем помещая logon.bat во все эти папки% AppData% ...

 $source = '\\ITE00463866\Applications\_Layer1_Installs\TS Sector\firstlogon.txt'
$list = "\\ITE00463866\Applications\_Layer1_Installs\TS Sector\test.txt"
$computers = gc $list

foreach($pc in $computers){

$targetfolder = "\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup"
$excluded_profiles = @( 'Administrator', 'All Users', 'Default User', 'Default.migrated', 'Public', 'DefaultAppPool', 'cdwuser', '.NET v4.5 Classic', '.NET v4.5')
$profiles = get-childitem $profilesfolder -Directory -force | Where-Object { $_.BaseName -notin $excluded_profiles }
$profilesfolder = 'c:\users\'

foreach ($profile in $profiles) {

    $destination = $profilesfolder + $profile + $targetfolder
       if ( $(Try { Test-Path $destination.trim() } Catch { $false }) ) {

       #If folder Startup folder is found for profile, add file to destionation, force overwrite
        copy-item -path $source -destination $destination -Force -Verbose
        }
    Else {

       #If folder is NOT found, create folder and move file to destination
        New-Item -Path $destination -ItemType Directory
        copy-item -path $source -destination $destination -Force -Verbose
        }
    }
    } 

Как мне объединить два сценария: Для каждого компьютера в моем списке просмотрите все профили пользователей и для каждого профиля (исключая упомянутые) добавьте новый logon.bat

Ответы [ 2 ]

0 голосов
/ 31 января 2020

Спросил одного из наших главных программистов, и он исправил мой оригинальный скрипт, не добавляя в него блок scipt. Спасибо за 1-е предложение!

Вот последний сработавший скрипт!

$source = '\\ITE00463866\Applications\_Layer1_Installs\TS Sector\firstlogon.bat'
$list = "\\ITE00463866\Applications\_Layer1_Installs\TS Sector\computers.txt"
$computers = gc $list

foreach($pc in $computers){

$targetfolder = "\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup"
$excluded_profiles = @( 'Administrator', 'All Users', 'Default User', 'Default.migrated', 'Public', 'DefaultAppPool', 'cdwuser', '.NET v4.5 Classic', '.NET v4.5')
$profilesfolder = '\\' + $pc + '\c$\users\'
$profiles = get-childitem $profilesfolder -Directory -force | Where-Object { $_.BaseName -notin $excluded_profiles }


foreach ($profile in $profiles) {

    $destination = $profilesfolder + $profile + $targetfolder
       if ( $(Try { Test-Path $destination.trim() } Catch { $false }) ) {

       #If folder Startup folder is found for profile, add file to destionation, force overwrite
        copy-item -path $source -destination $destination -Force -Verbose
        }
    Else {

       #If folder is NOT found, create folder and move file to destination
        New-Item -Path $destination -ItemType Directory
        copy-item -path $source -destination $destination -Force -Verbose
        }
    }
    } 
0 голосов
/ 30 января 2020

Если скрипт, который вы разместили наверху, работает для вас, и пока winrm настроен в вашей среде, вы можете заключить его в блок скриптов, как показано ниже:

$scriptblock = {
    $source = '\\ITE00463866\Applications\_Layer1_Installs\TS Sector\firstlogon.txt'
    $profilesfolder = 'c:\users\'
    $excluded_profiles = @( 'All Users', 'Default User', 'Default.migrated', 'Public', 'DefaultAppPool', 'cdwuser', '.NET v4.5 Classic', '.NET v4.5')
    $profiles = get-childitem $profilesfolder -Directory -force | Where-Object { $_.BaseName -notin $excluded_profiles }
    $targetfolder = "\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup"

    foreach ($profile in $profiles) {
    $destination = $profilesfolder + $profile + $targetfolder
    If ( $(Try { Test-Path $destination.trim() } Catch { $false }) ) {

        copy-item -path $source -destination $destination -Force -Verbose
        }
    Else {

        New-Item -Path $destination -ItemType Directory
        copy-item -path $source -destination $destination -Force -Verbose
        }
    }
}

И затем использовать ur foreach l oop вроде так:

$list = "\\ITE00463866\Applications\_Layer1_Installs\TS Sector\test.txt"
$computers = gc $list

foreach($pc in $computers){
    Invoke-Command -ComputerName $pc -ScriptBlock $scriptblock
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...