Изменить атрибуты компьютера в active directory

Изменить атрибуты компьютера в active directory
The first version of PowerShell
Изменить атрибуты компьютера в active directory
PowerShell for Linux 7.3.1 on Ubuntu 22.10

Изменить атрибуты компьютера в active directory

Wikiversity has learning resources about PowerShell

  • PowerShell on GitHub
  • Windows PowerShell Survival Guide on TechNet Wiki
ExtensionDescription
.ps1Script file[111]
.psd1Module’s manifest file; usually comes with a script module or binary module[112]
.psm1Script module file[113]
.dllDLL-compliant[a] binary module file[114]
.ps1xmlFormat and type definitions file[49][115]
.xmlXML-compliant[b] serialized data file[116]
.psc1Console file[117]
.psscSession configuration file[118]
.psrcRole Capability file[119]

  • cmdlets (.NET Framework programs designed to interact with PowerShell)
  • PowerShell scripts (files suffixed by .ps1)
  • PowerShell functions
  • Standalone executable programs

Extended Type System

The number of cmdlets included in the base PowerShell install has generally increased with each version:

VersionCmdletsRef
Windows PowerShell 1.0[38]
Windows PowerShell 2.0[39]
Windows PowerShell 3.0[40]
Windows PowerShell 4.0?
Windows PowerShell 5.0[41]
Windows PowerShell 5.1[]
PowerShell Core 6.0?
PowerShell Core 6.1?
PowerShell Core 6.2?
PowerShell 7.0[]
PowerShell 7.1?
PowerShell 7.2?
PowerShell 7.4

 
 # Definition of static parameters # Definition of dynamic parameters # Set of instruction to run at the start of the pipeline # Main instruction sets, ran for each item in the pipeline # Set of instruction to run at the end of the pipeline 
 

PowerShell
Изменить атрибуты компьютера в active directory
Изменить атрибуты компьютера в active directory

Screenshot of a PowerShell 7 session in Windows Terminal

ParadigmImperative, pipeline, object-oriented, functional and reflective
Designed byJeffrey Snover, Bruce Payette, James Truher (et al.)
DeveloperMicrosoft
First appearedNovember 14, 2006; 17 years ago
Stable release
Typing disciplineStrong, safe, implicit and dynamic
Implementation languageC#
PlatformPowerShell: .NET
Windows PowerShell: .NET Framework
OS
LicenseMIT License[2] (but the Windows component remains proprietary)
Filename extensions
  • .ps1 (Script)
  • .ps1xml (XML Document)
  • .psc1 (Console File)
  • .psd1 (Data File)
  • .psm1 (Script Module)
  • .pssc (Session Configuration File)
  • .psrc (Role Capability File)
  • .cdxml (Cmdlet Definition XML Document)
Website
Influenced by
Python, Ksh, Perl, C#, CL, DCL, SQL, Tcl, Tk,[3] Chef, Puppet

PowerShell includes its own extensive, console-based help (similar to man pages in Unix shells) accessible via the Get-Help cmdlet. Updated local help contents can be retrieved from the Internet via the Update-Help cmdlet. Alternatively, help from the web can be acquired on a case-by-case basis via the -online switch to Get-Help.

Introduction

Welcome to the PowerShell comments tutorial! If you’ve ever worked with PowerShell scripts, you know they can get pretty complex. Comments are the unsung heroes in these scripts. They’re like those sticky notes you put in your textbook – not part of the main text, but super helpful for understanding what’s going on. In this guide, we’ll explore how comments can make your PowerShell scripting life easier and why you should care about using them effectively.

Importance in Scripting

Let’s face it, nobody writes perfect code on the first try. And when you come back to your script six months later, you’ll thank your past self for leaving comments. They’re not just for others; they’re like breadcrumbs you leave for yourself to make sense of the logic behind your code. In PowerShell, where scripts can range from straightforward to ‘what was I thinking?’, comments are your best pals in making sense of it all.

Before we get started, if you want to take your PowerShell scripting skills to the next level then consider taking our PowerShell course which includes video lessons and IT labs at the link below:

Course: Administration and Automation with Windows PowerShell

ApplicationVersionCmdletsProviderManagement GUI
Exchange Server2007402YesYes
Windows Server2008YesYesNo
Microsoft SQL Server2008YesYesNo
Microsoft SharePoint2010YesYesNo
System Center Configuration Manager2012 R2400+YesNo
System Center Operations Manager200774YesNo
System Center Virtual Machine Manager2007YesYesYes
System Center Data Protection Manager2007YesNoNo
Windows Compute Cluster Server2007YesYesNo
Microsoft Transporter Suite for Lotus Domino[120]08.02.001247NoNo
Microsoft PowerTools for Open XML[121]1.033NoNo
IBM WebSphere MQ[122]6.0.2.244NoNo
IoT Core Add-ons[123]74Un­knownUn­known
Quest Management Shell for Active Directory[124]1.795NoNo
Special Operations Software Specops Command[125]1.0YesNoYes
VMware vSphere PowerCLI[126]6.5 R1500+YesYes
Internet Information Services[127]7.054YesNo
Windows 7 Troubleshooting Center[128]6.1YesNoYes
Microsoft Deployment Toolkit[129]2010YesYesYes
NetApp PowerShell Toolkit[130][131]4.22000+YesYes
JAMS Scheduler – Job Access & Management System[132]5.052YesYes
UIAutomation[133]0.8432NoNo
Dell Equallogic[134]3.555NoNo
LOGINventory[135]5.8YesYesYes
SePSX[136]0.4.139NoNo
:/>  Как установить дату и время на компьютере

Initially using the code name “Monad”, PowerShell was first shown publicly at the Professional Developers Conference in October 2003 in Los Angeles. All major releases are still supported, and each major release has featured backwards compatibility with preceding versions.

Windows PowerShell 1.0

Изменить атрибуты компьютера в active directory
Windows PowerShell 1.0 session using the Windows Console

Windows PowerShell 2.0

Изменить атрибуты компьютера в active directory
Windows PowerShell ISE v2.0 on Windows 7, an integrated development environment for PowerShell scripts

Windows PowerShell 3.0

  • Scheduled jobs: Jobs can be scheduled to run on a preset time and date using the Windows Task Scheduler infrastructure.
  • Session connectivity: Sessions can be disconnected and reconnected. Remote sessions have become more tolerant of temporary network failures.
  • Improved code writing: Code completion (IntelliSense) and snippets are added. PowerShell ISE allows users to use dialog boxes to fill in parameters for PowerShell cmdlets.
  • Delegation support: Administrative tasks can be delegated to users who do not have permissions for that type of task, without granting them perpetual additional permissions.
  • Help update: Help documentations can be updated via Update-Help command.
  • Automatic module detection: Modules are loaded implicitly whenever a command from that module is invoked. Code completion works for unloaded modules as well.
  • New commands: Dozens of new modules were added, including functionality to manage disks get-WmiObject win32_logicaldisk, volumes, firewalls, network connections, and printers, which had previously been performed via WMI.[further explanation needed]

Windows PowerShell 4.0

New features in PowerShell 4.0 include:

  • Desired State Configuration:[83][84][85] Declarative language extensions and tools that enable the deployment and management of configuration data for systems using the DMTF management standards and WS-Management Protocol
  • New default execution policy: On Windows Servers, the default execution policy is now RemoteSigned.
  • Save-Help: Help can now be saved for modules that are installed on remote computers.
  • Enhanced debugging: The debugger now supports debugging workflows, remote script execution and preserving debugging sessions across PowerShell session reconnections.
  • -PipelineVariable switch: A new ubiquitous parameter to expose the current pipeline object as a variable for programming purposes
  • Network diagnostics to manage physical and Hyper-V‘s virtualized network switches
  • Where and ForEach method syntax provides an alternate method of filtering and iterating over objects.

Windows PowerShell 5.0

Изменить атрибуты компьютера в active directory
PowerShell 5.0 icon

Key features included:

  • The new class keyword that creates classes for object-oriented programming
  • The new enum keyword that creates enums
  • OneGet cmdlets to support the Chocolatey package manager[87]
  • Extending support for switch management to layer 2 network switches.[88]
  • Debugging for PowerShell background jobs and instances of PowerShell hosted in other processes (each of which is called a “runspace”)
  • Desired State Configuration (DSC) Local Configuration Manager (LCM) version 2.0
  • DSC partial configurations
  • DSC Local Configuration Manager meta-configurations
  • Authoring of DSC resources using PowerShell classes

Windows PowerShell 5.1

PowerShell Core 6

  • The -Parallel switch for the ForEach-Object cmdlet to help handle parallel processing
  • Near parity with Windows PowerShell in terms of compatibility with built-in Windows modules
  • A new error view
  • The Get-Error cmdlet
  • Pipeline chaining operators (&& and ||) that allow conditional execution of the next cmdlet in the pipeline
  • The ?: operator for ternary operation
  • The ?? operator for null coalescing
  • The ??= operator for null coalescing assignment
  • Cross-platform Invoke-DscResource (experimental)
  • Return of the Out-GridView cmdlet
  • Return of the -ShowWindow switch for the Get-Help

Изменить свойства компьютера с помощью консоли Active Directory (ADUC)

Администратор может изменить атрибуты компьютер в Active Directory с помощью графической консоли ADUC.

:/>  Сенсорные панели оператора. Сенсорная панель

Изменить свойства компьютера в Active Directory

Вы можете отредактировать значения остальных атрибутов компьютера на вкладке Attribute Editor. Будьте внимательными при редактировании обязательных атрибутов компьютера. Редактор атрибутов объекта в AD не проверяет корректность введенных данных (проверяется только тип данных и длина значения), поэтому при некорректных значения атрибутов компьютера, он может потерять доверительные отношения с доменом.

Редактор атрибутов компьютера в AD

Comment-Based Help and Syntax

Structure and Syntax

<#
.SYNOPSIS
This script does some really cool stuff.
.DESCRIPTION
Here's a more detailed explanation of what this script can do.
.EXAMPLE
PS C:\> .\CoolScript.ps1
Runs the script and does the cool stuff.
#>

Examples and Best Practices

Writing Effective Comments

# Check if the file exists before attempting to delete
if (Test-Path "C:\temp\file.txt") { Remove-Item "C:\temp\file.txt"
}

Balancing Detail with Brevity

A good rule of thumb is to comment on why you’re doing something if it’s not immediately obvious. If your code is straightforward, like Get-Content "log.txt", you probably don’t need a comment. But if you’re doing something unusual or tricky, that’s a good place for a comment.

Self-Documenting Code

Principles and Advantages

Self-documenting code means writing your script so that it’s as clear as possible on its own. Good naming conventions for variables and functions, consistent formatting, and a logical structure all help make your script self-explanatory, reducing the need for extensive comments.

Implementing in PowerShell

Comparison of cmdlets with similar commands

  1. ls and man aliases are absent in the Linux version of PowerShell Core.
  2. Clear-Host is implemented as a predefined PowerShell function.
  3. Available in Windows NT 4, Windows 98 Resource Kit, Windows 2000 Support Tools
  4. Introduced in Windows XP Professional Edition
  5. Also used in UNIX to send a process any signal, the “Terminate” signal is merely the default
  6. curl and wget aliases are absent from PowerShell Core, so as to not interfere with invoking similarly named native commands.

Desired State Configuration

Upon running a configuration, DSC will ensure that the system gets the state described in the configuration. DSC configurations are idempotent. The Local Configuration Manager (LCM) periodically polls the system using the control flow described by resources (imperative pieces of DSC) to make sure that the state of a configuration is maintained.

Embedding Basic Comments

Single Line Comments

Starting with the basics, single line comments in PowerShell are like whispering a secret to the code. You start with a hash symbol (#), and PowerShell promises to ignore everything after it on that line. It’s great for quick notes or temporarily turning off a line of code.

# This line is just for us, PowerShell won’t mind. Get-Process -Name svchost

Multi-line Comments

When you have more to say, multi-line comments come to the rescue. Wrapped between <# and #>, they’re perfect for longer explanations or giving a time-out to big chunks of code.

<#
Here's where we explain things in detail.
Like a mini diary entry in the middle of your script.
Or for making multiple lines take a break.
#>
Get-Service

Изменить значение атрибута компьютера в AD с помощью PowerShell

Командлет Set-ADComputer (из модуля Active Directory для PowerShell) позволяет изменить атрибуты учетной записи компьютера в Active Directory.

Например, вы хотите добавить в свойства компьютера в AD его, название компании и департамента, которому он принадлежит.

Чтобы изменить значение основных атрибутов компьютера, можно использовать встроенные параметры, таки как
-Description
,
-DisplayName
,
-DNSHostName
,
-HomePage
,
-Location
и т.д., Например указать местоположение компьютера:

Set-ADComputer –Identity SRV-MAN01 –Location "Spb/Russia"

Также можно изменить значение любого атрибута с помощью параметров
Add
,
Replace
,
Clear
и
Remove
.

Задать новое описание учетной записи компьютера:

:/>  На сколько увеличить файл подкачки на windows 7

Если нужно задать несколько параметров компьютера, воспользуйтесь такой конструкцией PowerShell:

$Server = Get-ADComputer -Identity SRV-MAN01
$Server.company = "contoso"
$Server.department = "IT"
Set-ADComputer -Instance $Server

С помощью Get-ADComputer можно получить текущие значения атрибутов:

Set-ADComputer командлет PowerShell

С помощью Set-ADComputer вы также можете отключить или включить учетную запись компьютера в AD:

Set-ADComputer srv-man01 -Enabled $false

Avoiding Overuse of Comments

Identifying Necessary vs. Unnecessary Comments

It’s easy to go overboard with comments. If you find yourself writing a comment for every line of code, you’re probably doing too much. Comments should enhance your code, not drown it. If your code is readable and self-explanatory, let it speak for itself.

Striking the Right Balance

The goal is to find that sweet spot where your comments add value without being overwhelming. A well-commented script should feel like a guided tour, not a lecture.

Comments in Functions and Scripts

Documenting Functions

When you write a function in PowerShell, think of it as creating a mini-application. Comments play a crucial role here, explaining what the function does, its parameters, and what it returns. A well-documented function is a joy to use and much easier to maintain.

function Get-LatestLogFile { <# .SYNOPSIS Retrieves the most recent log file from a specified directory. .PARAMETER Path The directory to search for log files. .EXAMPLE Get-LatestLogFile -Path "C:\Logs" #> # Function logic goes here
}

Script-Level Comments

<#
.SYNOPSIS
This script automates the backup process for server data.
.DESCRIPTION
Executes a series of backup operations, including logging and error checks.
.NOTES
Requires administrative privileges to run.
#>
# Script logic follows...

Keeping Comments Relevant and Updated

One of the key challenges with comments is keeping them up to date. As your script evolves, make sure your comments reflect those changes. Outdated comments can be more misleading than no comments at all. It’s a good practice to review and update comments as part of your script maintenance routine.

# Updated 2023-12-26: Added error handling
$files = Get-ChildItem -Path "C:\Data"

Tools and Techniques

Utilize version control systems like Git to track changes in your scripts and their comments. This not only helps in maintaining the history of changes but also in collaborating with others, ensuring everyone understands the evolution of the script.

Как добавить имя пользователя и IP адрес в свойства компьютера в AD?

IP адрес компьютера мы будем хранить в атрибуте description, а имя пользователя, который работает за компьютером – в атрибуте ManagedBy.

делегирование прав Write Description + Write Managed By в AD на компьютеры

Данный PowerShell скрипт будет запускаться при входе пользователя, определять имя и IP адрес компьютера, CN пользователя и сохранит их в свойства компьютера в AD. Для работы скрипта на компьютерах должен быть установлен модуль AD PowerShell.

В консоли ADUC теперь отображаются IP адреса компьютеров, а в свойствах компьютера на вкладке Managed By теперь есть активная ссылка на учетную запись пользователя, который последним входил на компьютер.

имя пользователя в свойствах компьютера ad

Теперь вы можете быстро найти компьютеры в домене по IP адресу:

поиск компьютеров в ad по имени пользователя

Аналогичным образом вы можете записать в свойства аккаунтов компьютеров в AD любую информацию о рабочей станции или пользователе, и использовать ее для поиска (выборки) компьютеров в AD. В статье по ссылке описано как записать в описание компьютера в AD информацию о модели, серийном номере оборудования.

Conclusion

And that wraps up our tour of PowerShell comments! Remember, good commenting can turn a decent script into a great one. It’s about clarity, maintenance, and being kind to future readers of your code. So next time you’re scripting in PowerShell, take a moment to leave some thoughtful comments – your future self will thank you.