Table of Contents:
{ | |
( | |
[()][] | |
[()][] | |
) | |
{} | |
() { | |
( ) | |
} | |
() { | |
( ) | |
} | |
SearchBase Filter { rightsGuid } Properties rightsGuid | |
System.Collections.ArrayList | |
( ) { | |
[] | |
SearchBase Filter { attributeSecurityGUID } Properties | |
( ) { | |
([]{ | |
([] ).ToString() | |
}) | |
} | |
} | |
} |
Okay so I’m trying to figure out how to use PowerShell to write to AD in both the phone number and the other attributes:
Typically I am just using a code that will take a name and a number and apply it to the Mobile, telephone, pager etc.
Function AddNumberToAD
{
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[Alias('UserInfo')]
[string]$UserNameToAdd,
[Parameter(Mandatory=$true)]
[Alias('PhoneNumber')]
[string]$UsersPhoneNumberToAdd
)
$user = EmailToName $UserNameToAdd
oneEmptyLine
$usersRealName = Get-ADUser -Identity $user -Properties Name
$title = 'Assign Number'
Write-Host "Users Name: ", $usersRealName.Name
write-Host "Username: ", $user
Write-Host "Email: ",$UserNameToAdd
Write-Host "Phone Number to be Added: ",$UsersPhoneNumberToAdd
$question = 'Assign Phone Number as?'
$choices = @(
[System.Management.Automation.Host.ChoiceDescription]::new("&Mobile Number", "Verizon Wireless Number")
[System.Management.Automation.Host.ChoiceDescription]::new("&Telephone Number", "Teams Phone Number")
[System.Management.Automation.Host.ChoiceDescription]::new("&Cancel", "Exit Function")
)
$decision = $Host.UI.PromptForChoice($title, $question, $choices, 2)
if ($decision -eq 0)
{
}
elseif($decision -eq 1)
{
Write-Host "Setting user Telephone Number to Active Directory..." -ForegroundColor Green
Set-ADUser $user -Add @{telephonenumber=$UsersPhoneNumberToAdd}
}
Elseif($decision -eq 2)
{
Return
}
Else
{
Write-Host "Invalid input recieved..." -ForegroundColor Red
Works just fine, however we uttilize the other function and typically match the mobile number to the number:
(ignore the 3, this is just an example)
I would like to write the script so it would insert the mobile number into the mobile other attribute but i can not figure out how to. Any assistance would be appreciated.
I have tried -OtherAttribute but I cant seem to make it work.
Tried just about everything that I can think of. Just trying to get it to replicate into the other column,
I try to access all attributes of the given method from any classes into the WMI.
For example, I can list the methods inside “Win32_SystemDriver ” class
Get-WmiObject -Class Win32_SystemDriver -List | Select -ExpandProperty Methods
Name InParameters OutParameters Origin Qualifiers
---- ------------ ------------- ------ ----------
StartService System.Management.ManagementBaseObject CIM_Service {MappingStrings, Override, ValueMap}
StopService System.Management.ManagementBaseObject CIM_Service {MappingStrings, Override, ValueMap}
PauseService System.Management.ManagementBaseObject Win32_BaseService {MappingStrings, ValueMap}
ResumeService System.Management.ManagementBaseObject Win32_BaseService {MappingStrings, ValueMap}
InterrogateService System.Management.ManagementBaseObject Win32_BaseService {MappingStrings, ValueMap}
UserControlService System.Management.ManagementBaseObject System.Management.ManagementBaseObject Win32_BaseService {MappingStrings, ValueMap}
Create System.Management.ManagementBaseObject System.Management.ManagementBaseObject Win32_BaseService {MappingStrings, Static, ValueMap}
Change System.Management.ManagementBaseObject System.Management.ManagementBaseObject Win32_BaseService {MappingStrings, ValueMap}
ChangeStartMode System.Management.ManagementBaseObject System.Management.ManagementBaseObject Win32_BaseService {MappingStrings, ValueMap}
Delete System.Management.ManagementBaseObject Win32_BaseService {MappingStrings, ValueMap}
In MSDN document, Create method of the Win32_SystemDriver class has many attributes like;
uint32 Create(
[in] string Name,
[in] string DisplayName,
[in] string PathName,
[in] uint8 ServiceType,
[in] uint8 ErrorControl,
[in] string StartMode,
[in] boolean DesktopInteract,
[in] string StartName,
[in] string StartPassword,
[in] string LoadOrderGroup,
[in] string LoadOrderGroupDependencies[],
[in] string ServiceDependencies[]
);
Can I see these properties with CIM/WMI cmdlets? Also, if it is possible I want to see with their descriptions.
Do you want to get meta data of a file using PowerShell? In this tutorial, I will explain how to get details of a file in PowerShell. We will cover various methods to retrieve file metadata, attributes, and content, etc.
To get details of a file in PowerShell, you can use the Get-ItemProperty cmdlet to retrieve properties such as file size, creation time, and last modified time. For example, Get-ItemProperty -Path “C:\MyFolder\File.txt” will list these properties for the specified file. To read the contents of a file, use Get-Content -Path “C:\MyFolder\File.txt”, and for bulk operations on multiple files, Get-ChildItem combined with Get-ItemProperty can provide detailed information for each file in a directory.
Get Details of a File using Get-ItemProperty
To get file details using PowerShell, you can use the Get-ItemProperty. This PowerShell cmdlet retrieves the properties of the item at a specified path, which can include a file or a folder. Let’s look at a basic example:
Get-ItemProperty -Path "C:\MyFolder\MyFile.txt"
This command will output properties such as the file’s LastWriteTime
, Length
(file size), and CreationTime
, among others.
You can see the output in the screenshot below after I executed the above PowerShell script.
For a more detailed view, you can specify particular properties that you want to retrieve, like Name, Length, Lastwritetime, etc.:
Get-ItemProperty -Path "C:\MyFolder\MyFile.txt" -Name Length, LastWriteTime
This script will display only the size and last modified time of the specified file.
Get File Content using the Get-Content PowerShell cmdlet
If you want to read the contents of a file using PowerShell, you can use the Get-Content
cmdlet. Here is the PowerShell command.
Get-Content -Path "C:\MyFolder\MyFile.txt"
This command will display the contents of “MyFile.txt” in the console. If you wish to read a certain number of lines from the file, you can use the -TotalCount
parameter:
Get-Content -Path "C:\MyFolder\MyFile.txt" -TotalCount 5
This script will output the first five lines of the file.
Get File Attributes with Get-Item
To get more in-depth with file attributes, you can use the Get-Item
PowerShell cmdlet. This cmdlet allows you to retrieve the file object and its attributes, such as ReadOnly
, Hidden
, and Archive
. Here’s how you can use it:
$file = Get-Item -Path "C:\MyFolder\MyFile.txt"
$file.Attributes
The output will list all the attributes set on the file. You can also filter to check if a specific attribute is set:
$file = Get-Item -Path "C:\MyFolder\MyFile.txt"
$file.Attributes -match "ReadOnly"
If the file is read-only, this script will return True
.
Use Get-ChildItem for Multiple Files
If you need to retrieve details for multiple files at once, then you can use the Get-ChildItem
PowerShell cmdlet. This cmdlet can be used to list all files in a directory and then pipe the output to Get-ItemProperty
for detailed information:
Get-ChildItem -Path "C:\MyFolder" -File | Get-ItemProperty | Select-Object Name, Length, LastWriteTime
This command will list the names, sizes, and last modified times for all files in the specified directory.
You can see the screenshot below; after I executed the above script, it displayed details of all the files.
Get File Details in CSV Format
Here is a complete script that retrieves specific details for all files in a directory and exports the information to a CSV file:
$files = Get-ChildItem -Path "C:\MyFolder" -File
$fileDetails = foreach ($file in $files) {
$properties = Get-ItemProperty -Path $file.FullName
[PSCustomObject]@{
FileName = $properties.Name
Size = $properties.Length
LastModified = $properties.LastWriteTime
IsReadOnly = ($properties.Attributes -match "ReadOnly")
}
}
$fileDetails | Export-Csv -Path "C:\MyFolder\FileDetails.csv" -NoTypeInformation
This script first gathers all files in the specified directory, then iterates over each file, collecting its name, size, last modified time, and read-only status. The collected data is then exported to a CSV file.
Conclusion
In this PowerShell tutorial, I have explained how to get details of a file using Get-ItemProperty in PowerShell. Also, I have explained how to use Get-ChildItem PowerShell cmdlet to get file details of multiple files.
You may also like:
Изменить свойства компьютера с помощью консоли Active Directory (ADUC)
Администратор может изменить атрибуты компьютер в Active Directory с помощью графической консоли ADUC.
Вы можете отредактировать значения остальных атрибутов компьютера на вкладке Attribute Editor. Будьте внимательными при редактировании обязательных атрибутов компьютера. Редактор атрибутов объекта в AD не проверяет корректность введенных данных (проверяется только тип данных и длина значения), поэтому при некорректных значения атрибутов компьютера, он может потерять доверительные отношения с доменом.
Get All User Attributes with PowerShell
Here is an example command.
get-aduser -Identity robert.allen -properties *
To count the number of attributes use the below command.
$user= get-aduser robert.allen -properties *;
$user | Get-Member -MemberType Property,AliasProperty | Measure-Object
I hope you found this guide useful. If you have questions or comments post them below.
Как добавить имя пользователя и IP адрес в свойства компьютера в AD?
IP адрес компьютера мы будем хранить в атрибуте description, а имя пользователя, который работает за компьютером – в атрибуте ManagedBy.
Данный PowerShell скрипт будет запускаться при входе пользователя, определять имя и IP адрес компьютера, CN пользователя и сохранит их в свойства компьютера в AD. Для работы скрипта на компьютерах должен быть установлен модуль AD PowerShell.
В консоли ADUC теперь отображаются IP адреса компьютеров, а в свойствах компьютера на вкладке Managed By теперь есть активная ссылка на учетную запись пользователя, который последним входил на компьютер.
Теперь вы можете быстро найти компьютеры в домене по IP адресу:
Аналогичным образом вы можете записать в свойства аккаунтов компьютеров в AD любую информацию о рабочей станции или пользователе, и использовать ее для поиска (выборки) компьютеров в AD. В статье по ссылке описано как записать в описание компьютера в AD информацию о модели, серийном номере оборудования.
How to View User Attributes using Active Directory Users and Computers (ADUC)
Step 1. Open ADUC
Step 2. Click on View and enable Advanced Features
When you enable advanced features this option will stay enabled, meaning you do not need to enable it each time you open ADUC.
Step 3. Open the Attribute Editor
There will be many attributes that are blank, this is normal. If you want to see only the attributes that have values click on filter and select Show only attributes that have values.
Step 1. Run All Users Report
Step 2. Add or Remove User Attributes
The AD Pro Toolkit includes over 200 pre-built reports.
- User Reports
- Computer Reports
- Group Policy Reports
- Group Reports
- OUs
- Security Reports
Try the Toolkit for FREE in your domain, Download Free Trial.
Изменить значение атрибута компьютера в 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
.
Задать новое описание учетной записи компьютера:
Если нужно задать несколько параметров компьютера, воспользуйтесь такой конструкцией PowerShell:
$Server = Get-ADComputer -Identity SRV-MAN01
$Server.company = "contoso"
$Server.department = "IT"
Set-ADComputer -Instance $Server
С помощью Get-ADComputer можно получить текущие значения атрибутов:
С помощью Set-ADComputer вы также можете отключить или включить учетную запись компьютера в AD:
Set-ADComputer srv-man01 -Enabled $false