Перейти к содержимому

powershell

Как заставить Cisco IP Communicator подхватывать настройки пользователя в vdi horizon Instant Clone not run as administrator.

Суть проблемы в том что Cisco IP Communicator не сохраняет настройки Device Name у пользователя при работе в vdi horizon Instant Clone.

В horizon Instant Clone каждый раз машина пересоздается и у нею каждый раз генериться mac .

C технологией horizon Instant Clone настроено еще fslogix перемещаемый профиль.

Суть в том что настройки Device Name Cisco IP Communicator меняются в ветки реестра Компьютер\HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Cisco Systems, Inc.

Но при этом у пользователя в ветке реестра HKCU:\Software\Cisco Systems, Inc.\Communicator остается информация о Device Name.

Дабы исправить данную проблему сделал скрипт на powershell :

$value = Get-ItemProperty  -Path "HKCU:\Software\Cisco Systems, Inc.\Communicator" -name HostName
 
Set-ItemProperty 
Читать далее

Как сделать что бы настройки cisco ip communicator мог править сам пользователь. Без run as administrator

Задача состоит в том что бы пользователь сам мог настраивать cisco ip communicator без прав администратора.

Как сделать что бы настройки cisco ip communicator мог править сам пользователь. Без run as administrator

Что бы Cisco IP Communicator не просил админские права для редактирования Device Name надо дать права на ветку реестра Компьютер\HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Cisco Systems, Inc.

Как сделать что бы настройки cisco ip communicator мог править сам пользователь. Без run as administrator

Рег файл для настроек

Windows Registry Editor Version 5.00
 
[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Cisco Systems, Inc.\Communicator]
"HostName"="SEP00987654321"
"UseSetVolume"=dword:00000001
"EnableHttpDownload"=dword:00000001
"UseDefaultDevices"=dword:00000000
"AlternateTftp"=dword:00000001
"TftpServer1"=dword:0b2e10ac
"TftpServer2"=dword:0c2e10ac
 
 
[HKEY_CURRENT_USER\Software\Cisco Systems, Inc.\Communicator]
"TftpServer1"=dword:0b2e10ac
"TftpServer2"=dword:0c2e10ac
"HostName"="SEP00987654321"

Создал powershrll скрипт для редактирование Device Name и tftp сервера

Add-Type -AssemblyName Microsoft.VisualBasic
$hostname = [Microsoft.VisualBasic.Interaction]::InputBox('Username:', 'User', "Enter cisco device name here")
 
 
#$hostname = Read-Host 'cisco device name?' -AsSecureString
 
 
Set-ItemProperty -Path 'HKLM:\SOFTWARE\WOW6432Node\Cisco Systems, Inc.\Communicator' -Name HostName -Value 
Читать далее

Как удалить файлы с длинным путем The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters.

function Remove-PathToLongDirectory
{
    Param(
        [string]$directory
    )
 
    # create a temporary (empty) directory
    $parent = [System.IO.Path]::GetTempPath()
    [string] $name = [System.Guid]::NewGuid()
    $tempDirectory = New-Item -ItemType Directory -Path (Join-Path $parent $name)
 
    robocopy /MIR $tempDirectory.FullName $directory | out-null
    Remove-Item $directory -Force | out-null
    Remove-Item $tempDirectory -Force | out-null
}

Remove-PathToLongDirectory "T:\Закрытые проекты"

 

Как cменить пароль локального администратора в домене на серверах через Powershell.

Получаем список серверов или пк

Get-ADComputer -filter * -SearchBase 'DC=adminbd,DC=adminbd,DC=ru' | select -ExpandProperty name | sc c:\comps.txt
Get-ADComputer -filter * -SearchBase 'DC=adminbd,DC=adminbd,DC=ru' | select -ExpandProperty name | sc c:\comps.txt
 
 
$computer = "c:\comps.txt"
foreach ($computerName in (Get-Content $computer))
{
If (Test-Connection -ComputerName $computerName -Count 2 -Quiet)
{
Write-Host "Пытаюсь проверить компьютер на пакеты ping";
Invoke-Command -ComputerName $computerName -ScriptBlock {
#$credential = Get-Credential -UserName "Администратор" -Message "Введите новый пароль";
$UserName="Admin"
$Password=convertto-securestring "пароль" -asplaintext -force
If ($UserName -eq $null)
{
Write-Warning "The username and/or the password is empty! I quit.";
Exit;
}
Set-LocalUser -Name $UserName -Password $Password;
}
} Else
{
Write-Warning "Компьютер 
Читать далее

Как поменять логин и пароль на hp ilo и настроить ldap.

Задача сменить локального пользователя на всех hp ilo и настроить ldap авторизацию с группами администраторов и юзеров . Удалить лишних пользователей.

Устанавливаем HPiLOCmdlet

Оставлю локально вдруг что та смениться.  HPiLOCmdlets-x64

После установки

Import-Module HPiLOCmdlets

или

Install-Module -Name HPEiLOCmdlets

Если не хватает прав на запуск

Set-ExecutionPolicy RemoteSigned

Если ошибки

Install-PackageProvider Nuget –Force

Install-Module –Name PowerShellGet –Force

Update-Module -Name PowerShellGet

для начало надо просканировать сеть на наличие ilo hp.

Find-HPiLO 172.16.35.0-255 | ft -AutoSize

Как поменять логин и пароль на hp ilo и настроить ldap.

После этого поместим все найденные ip в файл

Find-HPiLO 172.16.35.0-255 |  Select-Object ip |  Export-Csv C:\1\2.csv

После этого смотрим какие есть уз на ilo

$Username="iloadmin"
$Password="пароль"

$path = 
Читать далее

Как сделать плановую перезагрузку серверов RD host windows 2016, со снятием нагрузки и возвращением её после ребута.

Задача: есть 7 серверов rd host sesion . Необходимо раз в неделю перезагружать сервер.

Скрипт по снятию подключений с rd host. Запускается в 18-00

Скрипт для запуска через cmd stop rdsh to day.bat

powershell -NoLogo -ExecutionPolicy Bypass -File "%~dp0\stop rdsh to day.ps1"
$dp0         = ($MyInvocation.MyCommand.Path | Split-Path -Parent)
#$dp0 = "C:\Scripts\Restart-RDSH"
$RDSCollection = "Farm"
$activbrocer= Get-RDConnectionBrokerHighAvailability 


# Get the current day
$date = Get-Date;

# determine the day, month, and year
$curDay = $date.DayOfWeek;
$curMonth = $date.Month;
$curYear = $date.Year;

# get total days in month
$totalDaysInMonth = [DateTime]::DaysInMonth($curYear, $curMonth);

switch($curDay){
    "Monday" {
        # this is where we want to 
Читать далее

Как подключиться к почте Exchange через Powershell на другом сервере и создать почтовый ящик пользователю.

Выполняем команды в powershell для подключения к серверу Exchange.

$UserCredential = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://mxs01.admindb.ru/PowerShell/ -Authentication Kerberos -Credential $UserCredential
Import-PSSession $Session -DisableNameChecking

После когда поработали нужно отключиться.

Remove-PSSession $Session

Создать почтовый ящик командой

get-user -Identity d.pupkin | Enable-Mailbox -Database MSK06 -RetentionPolicy "Move to archive after 6 month"
get-user -Identity d.pupkin | Enable-Mailbox -ACrchive -ArchiveDatabase ARC02

 

Как отправлять через powershell пользователям письмо с просьбой о смене пароля т.к. срок пароля истекает.

Задача отправлять письмо о том что срок пароля подходит к концу. Сделали через powershell.

Import-Module ActiveDirectory

$OrgUnit 	= "OU=Locations,DC=adminbd,DC=RU"
$Sender = "helpdesk@adminbd.ru"
$smtpserver ="mail.adminbd.ru"

$warnDays = (get-date).adddays(10)
$2Day = get-date
$Users = Get-ADUser -SearchBase $OrgUnit -filter {Enabled -eq $True -and PasswordNeverExpires -eq $False} -Properties msDS-UserPasswordExpiryTimeComputed, EmailAddress, Name | select Name, @{Name ="ExpirationDate";Expression= {[datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed")}}, EmailAddress
#$Users = Get-ADUser -Identity aleksey.potapushkin -Properties msDS-UserPasswordExpiryTimeComputed, EmailAddress, Name | select Name, @{Name ="ExpirationDate";Expression= {[datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed")}}, EmailAddress
foreach ($user in $users) {
if (($user.ExpirationDate -lt $warnDays) -and ($2Day -lt $user.ExpirationDate) ) {
$lastdays = ( $user.ExpirationDate -$2Day).days
$Subject = 'Срок действия пароля Вашей учетной записи '+$user.EmailAddress+ ' 
Читать далее

Как открыть профиль пользователя без монтирования (vhdx) user profile disk.

Задача добавлять тестовые базы в 1с. Для этого нужно у пользователя поправить C:\Users\%USERNAME%\AppData\Roaming\1C\1CEStart\v8i . Так как у нас ферма rdsh ,то проблема править файл через монтирование vhds. Через проводник будет легче всего.

Запуск проводника с правами администратора.

param([switch]$Elevated)
 
function Test-Admin {
  $currentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())
  $currentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
}
 
if ((Test-Admin) -eq $false)  {
    if ($elevated)
    {
        # tried to elevate, did not work, aborting
    }
    else {
        Start-Process powershell.exe -Verb RunAs -ArgumentList ('-noprofile -noexit -file "{0}" -elevated' -f ($myinvocation.MyCommand.Definition))
}
 
exit
}
 
'running with full privileges'
taskkill /f /FI "USERNAME eq $env:UserName"/im explorer.exe
pause
c:\windows\explorer.exe /nouaccheck
c:\windows\explorer.exe /nouaccheck

после запуска  … Читать далее

Как удалить site и pools из windows iis с помощью powershell.Deleting sites and application pools from Microsoft IIS using PowerShell

Удалить po0ls

#Deleting Sites and app pools in IIS 7 with PowerShell
$appCmd = "C:\windows\system32\inetsrv\appcmd.exe"

#lists all the sites
#& $appcmd list site 
#deletes a specific site
#& $appcmd delete site "Name of site"
#lists all the sites
#& $appcmd list apppool 
#deletes a specific application pool
#& $appcmd delete apppool "Name of app pool"
#delete any app pools that use a certain username (in the identity column of the GUI)
#$account = "TheDomain\TheAccount"
$AppPools = & $appcmd list apppool 
foreach ($pool in $AppPools){
    $pool = $pool.split(" ")[1] #get the name only
    & $appcmd delete apppool $pool
}
#delete all 
Читать далее