Показаны сообщения с ярлыком PowerShell. Показать все сообщения
Показаны сообщения с ярлыком PowerShell. Показать все сообщения

20.9.19

Как вывести список всех установленных ролей и компонент Windows Server 2012/2016?

powershell>Get-WindowsFeature


Список всех установленных ролей и компонент

Get-WindowsFeature | Where-Object {$_. installstate -eq "installed"} | Format-List Name,Installstate | more




Список установленных ролей и компонент на удаленном хосте.

Get-WindowsFeature -ComputerName dc01 | Where-Object {$_. installstate -eq "installed"} | Format-List Name,Installstate | more



1.7.19

Как включить удаленный рабочий стол удаленно в Windows 10


1. Включаем удаленный рабочий стол с помощью групповых политик GPO.

Computer Configuration > Administrative Templates > Windows Components >Remote Desktop Services > Remote Desktop Session Host > Connections.





1.2 Разрешаем RDP в брандмауэре Windows на удаленном компьютере с Windows 10.


Однако, групповые политики распространяются не так уж быстро, и если вы хотите войти в компьютер "здесь и сейчас" то это способ вам не подходит.


2. Включаем удаленный рабочий стол с помощью Powershell

Однако есть одна загвоздка - на самом деле, две. Брандмауэр Windows может помешать вам, если на компьютере не включено удаленное взаимодействие  c PowerShell. Мне известны два способа удаленного включения удаленного рабочего стола через PowerShell. Какой метод вы используете в основном, зависит от конфигурации брандмауэра Windows.


Предположим, что удаленное взаимодействие PowerShell включено на удаленном компьютере. Если это так, вы можете просто включить удаленный рабочий стол, изменив раздел реестра на удаленном компьютере:

Скорее всего, брандмауэр Windows блокирует RDP на удаленной машине. Чтобы открыть порт удаленного рабочего стола, вы можете использовать эту команду PowerShell:

 3. Включаем удаленный рабочий стол с помощью WMI

Если удаленное взаимодействие PowerShell не включено на удаленном компьютере, вы все равно можете использовать PowerShell через WMI для этой задачи. Это может быть полезно, если вам нужно включить RDP на нескольких машинах или если эта задача является частью более крупной проблемы автоматизации, а рекомендации по безопасности вашей организации не допускают удаленного взаимодействия PowerShell. Вот сценарий PowerShell, использующий командлет Get-WmiObject, он позволяет удаленно управлять компьютерами без удаленного взаимодействия PowerShell.


Чтобы использовать сценарий, вам просто нужно сохранить его в файл (Enable-RDPAccess.ps1) и затем запустить эту команду:



Если вы хотите включить RDP на нескольких компьютерах с Windows 10, вы можете сохранить имена компьютеров в текстовом файле и затем использовать команделет Get-Content, чтобы передать имена компьютеров в файл Enable-RDPAccess.ps1:

Настройка брандмауэра через WMI, а именно с помощью команды wmic:

Конечно, вы также можете включить удаленный рабочий стол с помощью wmic:



Обратите внимание, что необходимо настроить брандмауэр Windows на удаленном компьютере, чтобы разрешить доступ к WMI для сценария PowerShell и для работы wmic.
Вы можете сделать это с помощью групповой политики:

Computer Configuration > Policies > Windows Settings > Security Settings > Windows Firewall with Advanced Security.

4. Включаем удаленный рабочий стол с помощью Psexec

Еще одним вариантом является бесплатный инструмент от Microsoft Psexec. Этот способ также не требует удаленного взаимодействия PowerShell. Единственным недостатком является то, что использовать его не так просто, как Invoke-Command в сценариях PowerShell. Psexec требует, чтобы брандмауэре Windows был открыт порты для общего доступа к файлам и принтерам, что, вероятно, более распространено, чем открытые порты WMI или включенное удаленное взаимодействие с PowerShell:

Computer Configuration > Policies > Administrative Templates > Network > Network Connections > Windows Firewall > Domain Profile > Windows Firewall: Allow inbound file and printer sharing exception

Чтобы изменить реестр для включения RDP с помощью psexec, необходимо выполнить следующую команду:
Чтобы разрешить RDP-подключения в брандмауэре Windows, вы также можете использовать psexec:


Enable Remote Desktop remotely on Windows 10

22.5.18

Как принудительно удалить приложения в Windows 10?

1. Запускаем powershell от имени администратора.
2.  Команда Get-AppxPackage | Select Name, PackageFullName выводит полный список установленных приложений.


3. Находим приложение которое необходимо удалить. (например lenovocorporation)

5. Удаляем командой:
 Remove-AppxPackage LenovoCorporation.LenovoID_2.0.37.0_x86__4642shxvsv8s2

Кроме этого вы можете удалить предустановленные приложения, командой:
Get-AppxProvisionedPackage -Online | Select DisplayName, PackageName
Remove-AppxProvisionedPackage Microsoft.ZuneMusic_2019.6.11821.0_neutral_~_8wekyb3d8bbwe

Наконец вы можете удалить все приложения командой (будте осторожны с выполнением этой команды)
Get-AppxPackage | Remove-AppxPackage

Get-AppxProvisionedPackage -online | Remove-AppxProvisionedPackage -online

https://superuser.com/questions/942418/how-do-you-forcefully-remove-apps-in-windows-10

16.4.18

Как установить принтер по умолчанию с помощью powershell

Try
{
    Write-Verbose "Get the specified printer info."
    $Printer = $Printers | Where{$_.Name -eq "$PrinterName"}
 
    If($Printer)
    {
        Write-Verbose "Setting the default printer."
        $Printer.SetDefaultPrinter() | Out-Null
 
        Write-Host "Successfully set the default printer."
    }
    Else
    {
        Write-Warning "Cannot find the specified printer."
    }
}
Catch
{
    $ErrorMsg = $_.Exception.Message
    Write-Host $ErrorMsg -BackgroundColor Red
}


https://gallery.technet.microsoft.com/scriptcenter/How-to-set-default-printer-cf89670b

14.3.18

Изменение атрибутов пользователя с помощью PowerShell

cls
#Импортируем модуль для работы с Active Directory
Import-Module ActiveDirectory -ErrorAction SilentlyContinue
#OU Откуда берем пользователей
$sourceOU="OU=CompanyName_Users,DC=office,DC=local"
# Указываем исходный файл
$impfile = "C:\Scripts\useratribute_utf8.csv"
# Импортируем файл, указывая в качестве разделителя символ точку с запятой
$users = Import-CSV $impFile -Delimiter ";"
#Запускаем цикл и парсим каждую строчку
foreach ($user in $users)
{

#Считыаем данные из каждой ячейки матрицы в свою переменную
$dplname = $user.displayname
$titlename = $user.title
$officename = $user.physicalDeliveryOfficeName
$depname = $user.department

#Имя компании
$companyname = 'ООО "Имя компании"'
#Ищем пользователя в AD и проверяем его актуальность
$userset=get-aduser -f {enabled -eq $false -and name -eq $dplname} -SearchBase $sourceOU
if ($userset -eq $Null)
{

# Если пользователь активен
write-host "Пользователь $dplname активен, $titlename"
#Получаем все данные о пользователе в переменную getname
$getname=get-aduser -f {name -eq $dplname} -SearchBase $sourceOU
$adname=$getname.SamAccountName

#Изменяем атрибуты пользователя
#Департамент
Set-ADUser $adname -Replace @{department = $depname}
#Имя компании
Set-ADUser $adname -Replace @{Company = $companyname}
# Город
Set-ADUser $adname -Replace @{l = $officename}
#Расположение офиса
Set-ADUser $adname -Replace @{physicalDeliveryOfficeName = $officename}
#Должность
Set-ADUser $adname -Replace @{title = $titlename}
# End If True
}
# Конец цикла For
}

http://blog.volobuev.su/izmenenie-atributov-polzovatelya-s-pomoshhyu-powershell/comment-page-1/

13.3.18

AD-Powershell for Active Directory Administrators

List all computer accounts in a domain

Get-ADComputer –Filter {Name –Like "*"}


View all computers that are logged in for 90 days to the Active Directory

Search-ADaccount -AccountInactive -Timespan 90 -ComputersOnly

OR

$lastLogon = (get-date).adddays(-90).ToFileTime()
Get-ADComputer -filter {lastLogonTimestamp -gt $lastLogon} 

Find and delete all disabled Computer accounts in Active Directory

Search-ADAccount -AccountDisabled -ComputersOnly | Sort-Object | Remove-ADComputer

Find and delete disabled computer accounts from a specific OU

Search-ADAccount -AccountDisabled -Searchbase "OU=IT,DC=Contoso,DC=Com" -ComputersOnly | Sort-Object | Remove-ADComputer

Find and delete all computer accounts that no longer have signed up since 11/20/2011 to the Active Directory

Search-ADAccount -AccountInactive -DateTime "20.11.2011" –ComputersOnly | Sort-Object | Remove-ADComputer
List only disabled Computer accounts in Domain
Search-ADAccount -AccountDisabled -ComputersOnly | Format-Table Name

Move Computer to other OU (example: Computer=CLIENT1 to OU=IT)


Get-ADComputer CLIENT1 | Move-ADObject -TargetPath "OU=IT,DC=Contoso,DC=Com"

See Computer account detail (example: Computer=CLIENT1)

Get-ADComputer -Filter {Name -Like "CLIENT1"}

Get a specific computer showing all the properties (example: Computer=CLIENT1)

Get-ADComputer "CLIENT1" -Properties *

List Computers (Name, Operating System, Service Pack, Operating System version)

Get-ADComputer -Filter * -Property * | Format-Table Name,OperatingSystem,OperatingSystemServicePack,OperatingSystemVersion -Wrap –Auto

Export Computers List (Name, Operating System, Service Pack, Operating Systemversion)to CSV File

Get-ADComputer -Filter * -Property * | Select-Object Name,OperatingSystem,OperatingSystemServicePack,OperatingSystemVersion | Export-CSV AllWindows.csv -NoTypeInformation -Encoding UTF8

Get Computer IPv4 Address and DnsHostName

Get-ADComputer -Filter {Name -Like "Computer-Name"} -Properties IPv4Address | Format-List Name,DnsHostName,IPv4Address

Get all Computers in a specific OU (example: OU=IT, Domain=Contoso.com)

Get-ADComputer -SearchBase "OU=IT,DC=Contoso,DC=Com" -filter *

Get all the Computers without a specific DNS suffix

Get-ADComputer -filter "DnsHostName -notlike '*.Contoso.Com'"

Get Computer Service Principal Names (SPNs)

Get-ADComputer "Computer-Name" –Properties ServicePrincipalNames | Select-Object –Expand ServicePrincipalNames

Get Computers Security Identifiers (SIDs)

Get-ADComputer -Filter {Name -like "*"} | Select Name,SID | Format-Table -Auto
 

All computer accounts that were created in the last 90 days in the Active Directory


Get-ADComputer -Filter * -Properties whenCreated | ? { ((Get-Date) - $_.whenCreated).Days -lt 90} | Format-Table Name,WhenCreated,Name,DistinguishedName -Autosize -Wrap

All computer accounts that were created as of December 1, 2011 (12/01/2011) in the Active Directory

Get-ADComputer -LDAPFilter "(&(objectCategory=person)(whenCreated>=20111201000000.0Z))" -Properties whenCreated | Format-Table Name,whenCreated,distinguishedName -Autosize -Wrap

All computer accounts that were created here in a given time, between the 10/01/2011 and 12/01/2011 in Active Directory

$Start = Get-Date -Day 01 -Month 10 -Year 2011 -Hour 00
$End = Get-Date -Day 01 -Month 12 -Year 2011 -Hour 23 -Minute 59
Get-ADComputer -Filter * -Properties whenCreated | ? { ($_.whenCreated -gt $Start) -and ($_.whenCreated -le $End) } | Format-Table Name,WhenCreated,DistinguishedName -Autosize -Wrap


All computer accounts, Last Password Set in a given time, between the 10/01/2011 and 12/01/2011 in Active Directory
$Start = Get-Date -Day 01 -Month 10 -Year 2011 -Hour 00
$End = Get-Date -Day 01 -Month 12 -Year 2011 -Hour 23 -Minute 59
Get-ADComputer -Filter * -Properties PasswordLastSet | ? { ($_.PasswordLastSet -gt $Start) -and ($_.PasswordLastSet -le $End) } | Format-Table Name,WhenCreated,DistinguishedName -Autosize -Wrap


All computer accounts, Last Password Set in the last 90 days in Active Directory
$Date = (Get-Date).AddDays(-90)
Get-ADComputer -Filter * -Properties PasswordLastSet | where { $_.PasswordLastSet -le $Date } | Format-Table Name,PasswordLastSet,DistinguishedName -Autosize -Wrap

Group object commands


List all members of a group (example: Group=Experts)

Get-ADGroupMember Experts | Format-Table Name

All properties of a group (example: Group=IT)

Get-ADGroup IT -Properties *

List only Universal Security groups

Get-ADGroup –LDAPFilter "(&(objectCategory=group)(groupType:1.2.840.113556.1.4.803:=-2147483640))"

List only Global Security groups

Get-ADGroup –LDAPFilter "(&(objectCategory=group)(groupType:1.2.840.113556.1.4.803:=-2147483646))"

List only Domain Local Security groups

Get-ADGroup –LDAPFilter "(&(objectCategory=group)(groupType:1.2.840.113556.1.4.803:=-2147483644))"

List all Group memberships for a user (example: User=EdPrice)

Get-ADAccountAuthorizationGroup EdPrice

Move a Group to another OU (example: Group=Experts, Old-OU=IT, New-OU=Service, Domain=Contoso.com)

Move-ADObject "CN=Experts,OU=IT,DC=Contoso,DC=com" -TargetPath "OU=Service,DC=Contoso,DC=com"

Add members to a group (example: Group=Experts, User=EdPrice)

Add-ADGroupmember Experts -Member EdPrice

Delete Group (example: Group=Experts)

Remove-ADGroup Experts

Delete a User from a Group (example: Group=Experts, User=EdPrice)
Remove-ADGroupMember Experts -Member EdPrice

Set Description for a Group (example: Group=JoinPC, Description=This group is allowed join PCs to Domain)
Set-ADGroup JoinPC -Description "This group is allowed join PCs to Domain"

Add Users from one Group to another Group (example: from Group1=DataUsers to Group2=SQLUsers)
Get-ADGroupMember DataUsers | Select sAMAccountName | ForEach { Add-ADGroupMember SQLUsers -Members $_.sAMAccountName }
Comparing two Groups to see the Group memberships (example: Group1=Administratorso, Group2=DNSAdmins)
Compare-Object ( Get-ADGroupMember Administrators) ( Get-ADGroupMember DNSAdmins) -IncludeEqual

Organizational Unit (OU) commands


All OUs in Domain

Get-ADOrganizationalUnit -Filter {Name -like „*“} | FT Name, DistinguishedName -A

Create OU (example: OU=IT, Domain=Contoso.com)

New-ADOrganizationalUnit -Name IT -Path "DC=Contoso,DC=Com"


Contents of a specific OU (example: OU=IT, Domain=Contoso.com)


Get-ADObject -Filter {Name -Like "*"} -Searchbase "OU=IT,DC=Contoso,DC=Com"

Rename OU (example: Old-Name=IT, New-Name=Admin, Domain=Contoso.com)

Rename-ADObject "OU=IT,DC=Contoso,DC=Com" -NewName Admin

Delete OU including contents (example: OU=IT, Domain=Contoso.com)

Remove-ADOrganizationalUnit IT -Recursive

Delete user from specific OU (example: User=EdPrice, OU=IT, Domain=Contoso.com)

Remove-ADObject "CN=EdPrice,OU=IT,DC=Contoso,DC=Com"

Move all objects from one OU to another OU (example: Old-OU=IT, New-OU=Manager, Domain=Contoso.com)

Get-ADObject -Filter {Name -Like "*"} -Searchbase "OU=IT,DC=Contoso,DC=Com" -SearchScope OneLevel | Move-ADObject -TargetPath "OU=Manager,DC=Contoso,DC=Com"



User object commands



List all User accounts in the Domain

Get-ADUser –Filter *

List all User accounts in a specific OU (example: OU=IT, Domain=Contoso.com)

Get-ADUser –Filter * -Searchbase "OU=IT,DC=Contoso,DC=Com" | FT

List all User accounts from specific City (example: City=NewYork)

Get ADUser -Filter {city - like "NewYork"} | FT

List only disabled User accounts in Domain
Search-ADAccount –AccountDisabled –Usersonly | FT Name

List all User accounts whose First Name is Ed


Get-ADUser –Filter {givenName –Like "Ed"} | FT

List all User accounts whose Last Name is Price

Get-ADUser –Filter {Surname –Like "Price"} | FT

List all User accounts from the specific Department (example: Department=Support) 

Get-ADUser –Filter {Department –Like "Support"} | FT

List a User's Group memberships (example: User=Richard)

Get-ADPrincipalGroupMembership -Identity Richard 

List all Users from specific Group and move Users to another OU (example: Group=People, Target OU=NewYork, Domain=Contoso.com)

Get-ADGroupMember People -Recursive | Move-ADObject  –TargetPath "OU=NewYork,DC=Contoso,DC=Com"

Remove all users in an OU from a specific Group (example: Group=People, OU=NewYork, Domain=Contoso.com)

$Users = Get-ADUser -Filter * -Searchbase "OU=NewYork,DC=Contoso,DC=Com"
Remove-ADGroupMember -Identity People -Member $Users -Confirm:0




https://social.technet.microsoft.com/wiki/contents/articles/5819.ad-powershell-for-active-directory-administrators.aspx