В среде Windows каждому доменному и локальному пользователю, группе и другим объектам безопасности, присваивается уникальный идентификатор — Security Identifier или SID. Именно SID, а не имя пользователя используется для контроля доступа к различным ресурсам: сетевым каталогам, ключам реестра, объектам файловой системы и т.д. В этой статье мы покажем несколько простых способов узнать SID пользователя и обратной процедуры – определения имени пользователя Windows по его SID.
Гораздо проще воспользоваться утилитой командной строки или скриптом Powershell
Получить SID локального пользователя
В этом примере SID пользователя — S-1-5-21-1175651296-1316126944-203051354-1005
Если нужно узнать SID текущего пользователя, выполните такую команду:
На PowerShell скрипт, выдающий тот же результат можно реализовать с помощью двух классов SecurityIdentifier и NTAccount.
Получить SID доменного пользователя
Узнать SID текущей доменной учетной записи можно командой:
Если модуль AD для PowerShell отсутствует, через Powershell можно запросить данные из домена так:
Эта же команда в одну строку:
Определить имя пользователя по SID
Чтобы узнать имени учетной записи пользователя по SID (обратная процедура), можно воспользоваться одной из следующих команд:
На PowerShell при помощи модуля AD для Powershell:
Why Logging Matters in PowerShell
Logging is the process of recording events and data to a file or other output streams. In PowerShell, logging is vital for debugging purposes, monitoring script execution, and ensuring that you have a record of what actions were taken and when.
There are various ways you can create a log file in PowerShell.
Method 1: Start-Transcript and Stop-Transcript
PowerShell offers a built-in cmdlet called Start-Transcript to log a PowerShell session. This cmdlet starts recording all interactions with the console and saves them to a specified file. To stop recording, use the Stop-Transcript cmdlet.
Here is an example.
Start-Transcript -Path "C:\Logs\PowerShell_Log.txt"
# Your script commands here
Stop-TranscriptOnce you execute the above PowerShell script, it will create a log file and write the particular text in the above specified path.
Method 2: Out-File Cmdlet
The Out-File cmdlet in PowerShell is another way to write output directly to a log file. You can use it to append or overwrite data in a log file.
Here is a complete example:
"Information: Logging started." | Out-File -FilePath "C:\Logs\ScriptLog.txt" -Append
# Your script commands here
"Information: Logging completed." | Out-File -FilePath "C:\Logs\ScriptLog.txt" -AppendThis method allows you to selectively log information to your file, providing more control over what gets logged.
Method 3: Add-Content Cmdlet
Add-Content is a cmdlet in PowerShell that lets you append content to a log file without overwriting the existing content. This is useful for adding log entries as your script runs.
Here is a complete example.
Add-Content -Path "C:\Logs\ScriptLog.txt" -Value "Script has started at $(Get-Date)"
# Your script commands here
Add-Content -Path "C:\Logs\ScriptLog.txt" -Value "Script has finished at $(Get-Date)"This cmdlet is similar to Out-File -Append, but it’s specifically designed for adding text to files, making it ideal for logging purposes.
Method 4: Custom Logging Function
You can create a custom function to handle logging in PowerShell. This function can include parameters for the log message, log file path, and other options like timestamping.
Here’s a simple function that writes log entries to a specified file:
function Write-Log { Param ( [string]$LogString, [string]$LogFile ) Add-Content -Path $LogFile -Value $LogString
}
# Usage
$LogFile = "C:\MyFolder\script.log"
Write-Log "This is a log entry" -LogFile $LogFileThis function uses the Add-Content cmdlet to append the log string to the specified log file.
You can see the output in the screenshot below after I executed the PowerShell script using VS code.

function Write-Log { param ( [string]$LogPath, [string]$Message ) $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss" $logEntry = "$timestamp - $Message" Add-Content -Path $LogPath -Value $logEntry
}
$LogPath = "C:\MyFolder\CustomLog.txt"
Write-Log -LogPath $LogPath -Message "Script started"
# Your script commands here
Write-Log -LogPath $LogPath -Message "Script ended"This will prepend the current date and time to each log entry, formatted as YYYY-MM-DD HH:MM:SS.
Method 5: PSFramework
Here is a complete example.
Import-Module PSFramework
Set-PSFLoggingProvider -Name logfile -Enabled $true -LogPath "C:\Logs\PSFrameworkLog.txt"
Write-PSFMessage "Script started" -Level Important
# Your script commands here
Write-PSFMessage "Script ended" -Level ImportantThis method requires the installation of the PSFramework module but offers a professional logging setup that can be essential for enterprise-level scripts.
Best Practices for PowerShell Logging
- Consistency: Use a consistent log file naming convention to make it easier to locate and analyze logs.
- Timestamps: Include timestamps in your logs to provide context for when events occurred.
- Log Levels: Implement log levels (e.g., DEBUG, INFO, WARN, ERROR) to categorize the importance of log messages.
- Error Handling: Include logging within try/catch blocks to capture exceptions and errors.
- Log Rotation: Implement log rotation to prevent log files from becoming too large and unmanageable.
- Sensitive Data: Be cautious about logging sensitive information. Always sanitize logs if they may contain passwords, PII, or other sensitive data.
Conclusion
I hope that now, from this tutorial, you can create and write a log file in PowerShell using the above-mentioned methods.
You may also like:
Login Page
Documentation on how to customize the login page.
Login page customization requires a license.
Customizing the login page
Next, we can create a loginPage.ps1 file in the repository folder. Add the various colors, text and image URL to customize the login page. As soon as you save this file, you can refresh the login page to see the result.
'DBATools Web Portal'This login page looks like this.
This feature will be available in PowerShell Universal 2.3.
Customizing the login page with an App
You can override the login page with an app by setting an app’s base URL to /login. You need to ensure that the app does not require authentication.
You will then need to implement the login features manually.
Implementing an app-based login page
'Content-type': 'application/json; charset=UTF-8' .then((response) => response.json()). window.location.href = 'http://localhost:5000/app2'# Send Email Here with a link like: http://localhost:5000/app?email=email&passcode=$Password# For Testing Set-UDClipboard -Data "http://localhost:5000/app/Home?email=$($EventData.email)&passcode=$Password" -ToastOnSuccess"Please check your email!""Send Login Email"The resulting app will look like this when loaded.
A URL will be generated and, in this example, copied to the clipboard.
# Check the cache to see if this email + passcode combination is valid# Do standard form login hereClear-Host
Get-EventLog -LogName Security | Where-Object {$_.EventID -eq 4624} | ForEach-Object { $message = $_.Message $userName = ($message -split "Kontoname: ")[1] -split "`r`n"[1] [PSCustomObject]@{ TimeGenerated = $_.TimeGenerated UserName = $userName }
} | Format-Table TimeGenerated, UserNamewhere is my mistake, or maybe I have the wrong PowerShell command?
Who can help me or has a script example for me?
Clear-Host
Get-EventLog -LogName Security | Where-Object {$_.EventID -eq 4624} | ForEach-Object { $message = $_.Message $userName = ($message -split "Kontoname: ")[1] -split "`r`n"[1] [PSCustomObject]@{ TimeGenerated = $_.TimeGenerated UserName = $userName }
} | Format-Table TimeGenerated, UserNameasked Sep 23, 2023 at 19:53
The issue seem to be the missing of parentheses, also most likely you want the index 0 of the second split:
# This:
$userName = ($message -split "Kontoname: ")[1] -split "`r`n"[1]
# Should be:
$userName = (($message -split 'Kontoname: ')[1] -split "`r`n")[0]However, there is a much easier way to get the Target Account Name from the 4624 events, that is by getting the value at index 5 of the .Properties property. Also note the use of Get-WinEvent (newer cmdlet) instead of Get-EventLog.
Get-WinEvent -FilterHashtable @{ LogName = 'Security'; ID = 4624 } | ForEach-Object { [PSCustomObject]@{ TimeGenerated = $_.TimeCreated UserName = $_.Properties[5].Value }
}answered Sep 23, 2023 at 20:09

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


Если скрипт вернул False, возможные причины:
- Неверное имя пользователя (проверьте, что пользователь существует) или пароль
- Учетная запись пользователя в AD отключена или временно заблокирована
- Домен недоступен
Этот PowerShell скрипт не использует PowerShell модуль для Active Directory из набора RSAT и его можно использовать для тестирования учетных данных пользователя с любого Windows компьютера.
Если нужно подключиться к контроллеру домена с компьютера в рабочей группе или другого домена, нужно указать LDAP строку для подключения к DC. Замените 4 строку на:
Или можно подключиться к контроллеру домена по IP адресу:




