I am trying to decode and get information on a certificate using PowerShell. I want to be able to have a variable $Cert and then pull information about the certificate i.e.
$Cert.Subject
$Cert.Issuer
$Cert.ValidFrom
$Cert.ValidToI have the certificate as a variable.
$Cert = -----BEGIN CERTIFICATE-----
Content Here
-----END CERTIFICATE-----10 октября 2023
В 2018 г. появилось программное обеспечение PowerShell Core 6.0 как кроссплатформенный инструмент автоматизации для операционных систем Windows, Linux и MacOS. PowerShell Core имеет открытый исходный код и работает на платформе .NET Core 2.x, в отличии от предыдущих версий, работающих на .NET Framework.
В статье представлен обзор, как изменилось использование PowerShell с версии 6 до последнего обновления 7.x.
Вступление
Переход на PowerShell Core требовался для обеспечения кроссплатформенности продукта, но при этом привел к снижению функциональности, стабильности и надежности. Кроме того, пользователи столкнулись с проблемами совместимости с существующими модулями Windows PowerShell.
- Не поддерживаются уже привычные решения:
- Возможность параллельного выполнения команд с помощью workflows.
- Нет поддержки WMI v1 и соответственно не работают командлеты Get-WmiObject, Invoke-WmiMethod, Register-WmiEvent и т.д.
- Исчезли командлеты связанные с графическим отображением такие, как Out-GridView, Show-Command и параметр -ShowWindow
- Не работают модули ActiveDirectory и DnsClient.
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, LastWriteTimeThis 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 5This 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.AttributesThe 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, LastWriteTimeThis 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" -NoTypeInformationThis 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:
Welcome to Practical PowerShell
A Series to Help You Improve Your PowerShell Scripts
While GitHub Copilot might be helpful when making changes to scripts, it still requires a human to validate Copilot-generated code. For that, humans need to possess certain skills. This is the first installment in a monthly PowerShell Scripting series that’s designed to help part-time PowerShell developers. We expect readers to have some PowerShell knowledge and be comfortable with loading and using the Microsoft 365 PowerShell modules. We start with some essential talking points, such as functions and flow control. Eventually, we will talk about how to incorporate snippets in a self-contained script.
Lastly, when publishing code, it’s always better to expand aliases, including the shorthand for ForEach-Object (%) and Where-Object (?). Spelling cmdlets out improves readability. This is less of an issue when using the command line or drafting some code, but it’s critical if you expect people to read and understand your code.

One-liners Versus Scripts
Get-Mailbox | ForEach-Object { $_.EmailAddresses | ForEach-Object { Write-host $_ } }$Mailboxes= Get-ExoMailbox
ForEach( $Mailbox in $Mailboxes) {
ForEach( $Email in $Mailbox.EmailAddresses) {
Write-host $Email
}
}Before the comments start rolling in: Yes, the last example can be written in many ways, and yes, Select-Object -ExpandProperty could have been used, and yes, this is less efficient and performant, but that is not the point here. The point is that both commands perform the same task, but only the first is a one-liner according to the definition. Using the pipeline may, in theory, bring performance benefits because it can process objects sent through the pipeline in parallel. I say in theory because, for example, the Sort-Object needs to collect all input before it can perform its magic.
The second example is better in terms of readability, but it also uses variables to store objects. Putting data into variables enables other options, such as the ability to perform other operations on the objects, such as setting values. But then the code is already starting to look more script-ish and less of a one-liner.
In my mind, everything depends on the intended use of the code. Also, since you can separate cmdlets in PowerShell using semi-colons, you can have your own PowerShell obfuscated code contest, like the International Obfuscated C Code Contest. While this technique might be great to show off, is that code readable and maintainable? Not so much.
Friends Don’t Let Friends Use Backticks
Earlier I mentioned a one-liner can consist of more than one line, which is where the backtick might come into play. PowerShell one-liners can become very long. For readability, you might want to break statements from the same one-liner or cmdlet and put them on multiple lines. Also, backticks can be used to add manual line-breaks for improved readability, instead of having automatic line-breaks inserted right after a parameter dash, such as in this example:
Set-Mailbox -Identity olrik@contoso.com – MessageCopyForSentAsEnabled $True
The backtick (`) is a line continuation character, allowing you to write a command using multiple lines. However, the consensus in the community is that backticks are terrible for readability. Depending on the situation, techniques such as splatting using hash tables might be more appropriate, as shown in the example below:
Set-CalendarProcessing -Identity Ohio.Conference ` -AllRequestInPolicy $True -AllBookinPolicy $False ` -BookInPolicy 'Conference Organizers'
$CPSettings= @{
Identity= 'Ohio.Conference'
AllRequestInPolicy= $True
AllBookinPolicy= $False
BookInPolicy= 'Conference Organizers'
}
Set-CalendarProcessing @CPSettingA quick glance at the second example shows why it is easier on the eye and more maintainable than the single-line version. This becomes even more apparent as you add more parameters to the command.
Get-Mailbox -RecipientTypeDetails UserMailbox –IncludeInactiveMailbox
The presence or absence of IncludeInactiveMailbox determines what Get-Mailbox should fetch; there is no need to pass a value the usual way. Therefore, this will not work:
Get-Mailbox -RecipientTypeDetails UserMailbox -IncludeInactiveMailbox $True
A trick is available for parameters: assign values using a colon. This also works for switches. You might already use this when turning off confirmation prompts for cmdlets by specifying -Confirm:$False:
Get-Mailbox -RecipientTypeDetails UserMailbox -IncludeInactiveMailbox:$True
In splatting, you do not have to worry about switches:
$filter= @{
RecipientTypeDetails='UserMailbox'
IncludeInactiveMailbox=$True
}
Get-Mailbox @filterSummarizing Our Start
3
В начале 2023 г. появилась версия PowerShell 7.3, основанная на .NET 7.0.
Некоторые критические изменения в новой версии:
- PowerShell 7.3 не работает в Windows 7.
- PowerShell Direct для Hyper-V поддерживается только в Windows 10, версия 1809 и более поздних версиях.
- Test-Connection не работает из-за намеренного критического изменения в .NET 7
- Перемещение определения данных типа System.Security.AccessControl.ObjectSecurity в модуль Microsoft.PowerShell.Security.
- Дополнительные улучшения заполнения нажатием клавиши TAB.
- Улучшена обработка ошибок.
- Улучшены сеансы и удаленное взаимодействие.
- Обновлены ряд командлетов.
- Добавлены новые экспериментальные функции.
УЦ АйТи Клауд по направлению системное администрирование, сетевые технологии, безопасность сетей
Create an X.509 certificate object from the byte array
$certificate = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2`
`$certificate.Import($certificateBytes)Error – MethodInvocationException: Exception calling “Import” with “1” argument(s): “X509Certificate is immutable on this platform. Use the equivalent constructor instead.”
$certificate= New-Object -TypeName system.Security.Cryptography.X509Certificates.X509Certificate2($CertificateBytes)Error – New-Object: Cannot find an overload for “X509Certificate2” and the argument count: “1608”.
$certificateBytes.Count1
Осенью 2020 г. вышла общедоступная версия PowerShell 7.1, основанная на .NET 5.0.
В этой версии появился ряд новых функций и обновлений:
- PSReadLine 2.1.0 с прогнозной технологией IntelliSense
- Версия PowerShell 7.1 опубликована в Microsoft Store.
- Пакеты установщика обновлены для новых версий ОС с поддержкой ARM64.
- 2 экспериментальные функции PSNullConditionalOperators и PSUnixFileStat стали основными.
- Добавлены 4 экспериментальные функции Microsoft.PowerShell.Utility.PSManageBreakpointsInRunspace, PSNativePSPathResolution, PSCultureInvariantReplaceOperator и PSSubsystemPluginModel.
Хотите преподавать в АйТи Клауд?
Если вы имеете компетенции и хотите работать тренером курсов в АйТи Клауд – оставьте ваши данные, мы свяжемся с вами!
Курсы к статье
Будьте в курсе всех событий
Затрудняетесь
с выбором курса?
Оставьте заявку на консультацию
2
PowerShell 7.2 — это следующий выпуск Long Term Servicing (LTS) на основе .NET 6.0.
Новые возможности, обновления и критические изменения:
- Добавлены новые универсальные пакеты установщика для большинства поддерживаемых дистрибутивов Linux.
- Включена поддержка Центра обновления Майкрософт в Windows.
- Добавлены две новые экспериментальные возможности.
– Улучшена поддержка передачи аргументов собственных команд.
– Включена поддержка цвета в ANSI для FileInfo.
- Улучшены варианты заполнения нажатием клавиши TAB.
- Семь экспериментальных функций стали основными, одна удалена.
- Платформа DSC отделена от PowerShell 7, чтобы обеспечить возможность внесения будущих улучшений.
- Несколько критических изменений для повышения удобства использования.
Decode the Base64 content into a byte array
$CertificateBytes = [System.Convert]::FromBase64String($Cert) and it completes.
$CertificateBytesjust contains a list of numbers.
Decode the Base64 content into a byte array
$CertificateBytes = [System.Convert]::FromBase64String($Cert)**Error – MethodInvocationException: Exception calling “FromBase64String” with “1” argument(s): “The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.”
**
I’ve tried to see if there are hidden characters etc.
I did make some progress when I removed the —–BEGIN CERTIFICATE—– & —–END CERTIFICATE—– from the $Cert variable
I run the command again
0
В начале 2020 г. компания Microsoft выпустила PowerShell 7.0. В этом программном обеспечении удалось решить большую часть проблем 6-ой версии. 7-ая версия основана на .NET Core 3.x, где поддерживается множество API .NET Framework, обеспечивая обратную совместимость с более 90% существующих модулей Windows PowerShell. Теперь поддерживаются модули ActiveDirectory, DnsClient, DnsServer, BitLocker, BranchCache, Defender, Hyper-V и многие другие, полный список которых приводится на сайте Microsoft.
Вернулись командлеты требующие графическую функциональность, такие как Out-GridView и Show-Command. Повысилась стабильность и производительность.
В PowerShell 7.0 появились новые функции, в том числе:
- параллелизация конвейера с помощью ForEach-Object -Parallel;
- новые операторы:
- упрощенное динамическое представление ошибок и командлет Get-Error для более легкого анализа ошибок;
- автоматические уведомления о новых версиях;
- возможность вызывать ресурсы DSC непосредственно из PowerShell 7.
Жизненый цикл PowerShell 7.0 теперь соответствует политике жизненного цикла поддержки .NET Core и включает выпуски Long Term Service и non-Long Term Service.




