Описание файла psd 1

Microsoft.PowerApps.PowerShell.psd1

# Script module or binary module file associated with this manifest.

# Version number of this module.

# ID used to uniquely identify this module

# Author of this module
‘Microsoft Common Data Service Team’

# Company or vendor of this module

# Description of the functionality provided by this module
‘PowerShell interface for Microsoft PowerApps and Flow features’

# Minimum version of the Windows PowerShell engine required by this module

# Name of the Windows PowerShell host required by this module
# PowerShellHostName = ”

# Minimum version of the Windows PowerShell host required by this module

# Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only.

# Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# CLRVersion = ”

# Processor architecture (None, X86, Amd64) required by this module
# ProcessorArchitecture = ”

# Variables to export from this module
# VariablesToExport = ‘*’

# A URL to the license for this module.

# A URL to an icon representing this module.

# ReleaseNotes of this module

 
1.0.9:

    Added usgov and usgovhigh support.’

# End of PSData hashtable

# End of PrivateData hashtable

# HelpInfo URI of this module
# HelpInfoURI = ”

# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix.
# DefaultCommandPrefix = ‘PowerApp’

Описание файла PSD1

Microsoft Partner

Резюме файла PSD1

Расширение файла PSD1 имеет один тип (-ов) файла (-ов) и связано с один различными программными обеспечениями, но главным образом с Microsoft Windows PowerShell, разработанным Microsoft Corporation. Часто они представлены в формате Windows PowerShell Data File.
Большинство файлов PSD1 относится к Developer Files.

Файлы с расширением PSD1 были идентифицированы на настольных компьютерах (и некоторых мобильных устройствах). Они полностью или частично поддерживаются Windows.

Рейтинг популярности расширения файла PSD1 составляет «Низкий», что означает, что эти файлы, как правило, не встречаются в большинстве файловых хранилищ пользователя.

Важность
Пересмотренный

Скачать FileViewPro и открыть PSD1

Описание файла psd 1

Типы файлов PSD1

Основной тип PSD1

Описание файла psd 1

Форматирование:.psd1
Категория:Windows PowerShell Data File

Расширение файла, связанного с Windows PowerShell, в командной строке оболочки Windows. В PSD1 файл хранит различные данные конфигурации для модуля PowerShell или сценария.

Описание файла psd 1

Поиск типов файлов

Описание файла psd 1

Запросы PSD1

Усложнения в PSD1-файле

Описание файла psd 1

Проблемы при открытии PSD1-файлов

Microsoft Windows PowerShell удален

При попытке открыть файл PSD1 вы получаете сообщение об ошибке «Не удается открыть тип файла PSD1». Когда это происходит, это обычно связано с отсутствием Microsoft Windows PowerShell в %%os%%. Поскольку ваша операционная система не знает, что делать с этим файлом, вы не сможете открыть его двойным щелчком мыши.

Описание файла psd 1

Совет: Если вам извстна другая программа, которая может открыть файл PSD1, вы можете попробовать открыть данный файл, выбрав это приложение из списка возможных программ.

Неверная версия Microsoft Windows PowerShell

В некоторых случаях может быть более новая (или более старая) версия файла Windows PowerShell Data File, которая не поддерживается установленной версией приложения. Загрузите последнюю версию Microsoft Windows PowerShell с веб-сайта Microsoft Corporation, чтобы убедиться, что у вас установлена правильная версия. Основной причиной этой проблемы является то, что файл Windows PowerShell Data File был создан другой (более новой) версией Microsoft Windows PowerShell, чем установленная.

Описание файла psd 1

Совет . Иногда вы можете получить подсказки о правильной версии программы, щелкнув правой кнопкой мыши PSD1-файл, выбрав «Свойства» и посмотрев информацию о версии.

Резюме: В любом случае, большинство проблем, возникающих во время открытия файлов PSD1, связаны с отсутствием на вашем компьютере установленного правильного прикладного программного средства.

Описание файла psd 1

Связанные трудности при загрузке PSD1-файлов

Даже при установке правильной версии Microsoft Windows PowerShell вы все равно можете испытывать трудности с открытием PSD1-файлов. Если у вас по-прежнему возникают ошибки при загрузке PSD1-файлов, могут быть виноваты другие внешние проблемы. Эти другие проблемы включают (перечислены в порядке от наиболее до наименее распространенных):

  • Неверные ссылки на файлы PSD1 в реестре Windows («телефонная книга» операционной системы Windows)
  • Ошибочное удаление описания реестра Windows PSD1
  • Недопустимая установка программы, связанной с PSD1 (например, Microsoft Windows PowerShell)
  • Повреждение файла, влияющее на PSD1-файл
  • Не удается открыть файл PSD1, запятнанный вредоносными программой
  • Оборудование, связанное с PSD1, имеет устаревшие драйверы
  • Недостаточно системных ресурсов для успешного открытия файлов Windows PowerShell Data File

Опрос: Ваш любимый формат аудио?

Описание файла psd 1

Описание файла psd 1

Несмотря на то, что в интернете вы можете найти очень много различных инструкций по поводу того, как создать свой собственный Powershell-модуль, даже официальная документация не дает полного понимания, как все-таки создать модуль правильно.

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

Придумайте название

Это важно :-). Потом с этим названием вы будете долго жить, поэтому придумайте то, что вам потом будет приятно видеть каждый день =).

В моем случае я решил придерживаться следующего подхода: <код_заказчика\название заказчика>.<код_проекта>.Powershell.

Для целей этого гайда давайте делать модуль My.OwnModule.Powershell.

Придумайте префикс для названия командлетов\функций

Если вы разрабатываете несколько разных модулей (например, для разных компаний или команд), иногда в модулях может быть одна и та же функция. И если вы начнете сами использовать эти модули одновременно, при их импорте начнутся конфликты имен. Поэтому имеет смысл использовать для каждого модуля свой уникальный префикс.

:/>  Выделение текста клавишами на клавиатуре

В нашем примере я буду использовать MyOwn. Например стандартное имя New-Item превратится в New-MyOwnItem.

Установите необходимые утилиты

Кроме самого Powershell, Вам понадобится утилита командной строки nuget. Она будет нужна, чтобы паковать модуль в nuget-пакет и распространять модуль между другими компьютерами\пользователями.

Создайте дерево каталогов

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

D:.
└───My.OwnModule.Powershell
    ├───images
    ├───private
    ├───public
    │   └───common
    └───_bin

  • images. Тут будет лежать иконка для пакета, которая в теории будет видна в каком-нибудь репозитории типа Artifactory.
  • private. Тут будут лежать скрипты, которые должны быть доступны только для служебных нужд. Например, чтобы прочитать файл с диска с обработкой ошибок.
  • public. Тут будут лежать скрипты, в которых будут доступны непосредственно пользователям модуля.
    • public -> common. Эта папка нужна исключительно для структурирования и группировки файлов. Все внутри Public будет читаться рекурсивно.
  • _bin. Тут будут лежать пакеты с модулем, когда утилита nuget скомпилирует пакет.

Создайте необходимые файлы

Также нужно создать файлы, которые собственно и превращают набор Powershell-сриптов в модуль.

D:.
│   LICENSE
│   PSScriptAnalyzerSettings.psd1
│   README.md

└───My.OwnModule.Powershell
    │   local-build.ps1
    │   local-install.ps1
    │   My.OwnModule.Powershell.nuspec
    │   My.OwnModule.Powershell.psd1
    │   My.OwnModule.Powershell.psm1
    │
    ├───images
    │       icon.png
    │
    ├───private
    │       _stub.ps1
    │
    ├───public
    │   └───common
    │           Read-MyOwnJsonFile.ps1
    │
    └───_bin

Нас интересуют файлы, которые лежат в корневой папке модуля, в private и public. Остальные – это служебные файлы git-репозитория. Ниже привожу содержимое каждого файла с комментариями.

Заполняем служебные файлы для Powershell-модуля

My.OwnModule.Powershell.nuspec

Этот файл нужен, чтобы nuget генерировал пакет.

<?xml version="1.0" encoding="utf-8"?>
<package >
  <metadata>
    <id>My.OwnModule.Powershell</id>
    <version>0.0.2</version>
    <authors>Адрес электронной почты защищен от спам-ботов. Для просмотра адреса в браузере должен быть включен Javascript.</authors>
    <requireLicenseAcceptance>false</requireLicenseAcceptance>
    <icon>images\icon.png</icon>
    <description>
      There is no any description available at this time. Sorry for that.
    </description>
    <releaseNotes>Initial release.</releaseNotes>
    <tags>PSEdition_Core PSEdition_Desktop Linux Mac PSModule PSIncludes_Cmdlet</tags>
  </metadata>
</package>

My.OwnModule.Powershell.psd1

Этот файл – манифест, описание модуля с точки зрения самого Powershell. Тут хранятся различные сведения об авторе, о функциях, которые модуль будет предосталять и т.п.

Обратите внимание на строку 11 и параметр FunctionsToExport. Это функции, которые будут доступны пользователям вашего модуля. Поэтому, при добавлении новых функций в модуль, необходимо помнить и добавлять их сюда.

@{
    RootModule           = "My.OwnModule.Powershell.psm1"
    ModuleVersion        = "0.0.2"
    CompatiblePSEditions = "Desktop", "Core"
    GUID                 = "8f37ba7b-be77-4b6e-8ceb-d30c0c328674"
    Author               = "Адрес электронной почты защищен от спам-ботов. Для просмотра адреса в браузере должен быть включен Javascript."
    PowerShellVersion    = "7.0"

    ScriptsToProcess     = @();
       
    FunctionsToExport    = @(
        "Read-MyOwnJsonFile"
    );
    CmdletsToExport      = "*"
    VariablesToExport    = "*"
    AliasesToExport      = "*"
}

My.OwnModule.Powershell.psm1

Этот файл – скрипт, который выполняется, когда вы запускаете (или сама система запускает) Import-Module. Это самый главный файл в модуле, вообще говоря, это и есть сам модуль.

#Requires -Version 7.0


$public  = @( Get-ChildItem -Path $PSScriptRoot\public\*.ps1 -Recurse; );
$private = @( Get-ChildItem -Path $PSScriptRoot\private\*.ps1 -Recurse; );


# Dot source the files
foreach ($import in @($public + $private))
{
    try
    {
        Write-Verbose "Importing '$($import.FullName)'.";
        . $import.FullName;
    }
    catch
    {
        Write-Error -Message "Failed to import function $($import.fullname): $_";
    }
}


Export-ModuleMember -Function $public.Basename;

_stub.ps1

Я положил этот файл-заглушку, чтобы скрипт из psm1-файла смог нормально прочитать папку без возможных проблем. А вообще он полностью пустой.

Read-MyOwnJsonFile.ps1

Это файл командлета, который мы будем предоставлять нашим модулем. Обратите внимание, как он называется – Read-MyOwnJsonFile, всмысле что используется префикс для имен командлетов модуля.

local-build.ps1

Этот файл не является непосредственной частью Powershell-модуля. Это скрипт, который я использую для упаковки модуля в nuget-пакет, чтобы потом его можно было положить куда-нибудь в архив. Также этот скрипт в каждый запуск изменяет версию модуля на +1.

# Config
$moduleName = "My.OwnModule.Powershell";


# Clear old packages
# Get-ChildItem .\$moduleName\_bin | Remove-Item -Force -Verbose;


#region Get current package version and increment Patch
$version = Select-String -Path .\$moduleName\$moduleName.nuspec -Pattern "<version>(\d)\.(\d)\.(\d{1,})</version>";
[int]$majorVersion = $version | Select-Object @{name="version"; expression={$_.Matches.Groups[1].Value}} | select-object -ExpandProperty version;
[int]$minorVersion = $version | Select-Object @{name="version"; expression={$_.Matches.Groups[2].Value}} | select-object -ExpandProperty version;
[int]$patchVersion = $version | Select-Object @{name="version"; expression={$_.Matches.Groups[3].Value}} | select-object -ExpandProperty version;
$patchVersion++;
$nuspecVersionString = "<version>$majorVersion.$minorVersion.$patchVersion</version>";
$psd1VersionString = "ModuleVersion        = `"$majorVersion.$minorVersion.$patchVersion`"";
#endregion /Get current package version and increment Patch


#region Update package version
$a = Get-Content -Path ".\$moduleName\$moduleName.nuspec" | %{$_ -replace "<version>(\d)\.(\d)\.(\d{1,})<\/version>", $nuspecVersionString };
$a | Out-File ".\$moduleName\$moduleName.nuspec" -Verbose;

$a = Get-Content -Path ".\$moduleName\$moduleName.psd1" | %{$_ -replace "ModuleVersion        = `"\d\.\d.\d{1,}`"", $psd1VersionString };
$a | Out-File ".\$moduleName\$moduleName.psd1" -Verbose;
#endregion /Update package version


nuget pack ".\$moduleName\$moduleName.nuspec" -OutputDirectory .\$moduleName\_bin -Properties NoWarn=NU5111,NU5110,NU5100
$package = Get-ChildItem .\$moduleName\_bin\*.nupkg | Sort-Object -Property CreationTime | Select-Object -Last 1;

$package

local-install.ps1

Соответственно, этот кастомный скрипт – для установки модуля.

$moduleName = "My.OwnModule.Powershell";
$repoName = "My.OwnModule.Powershell.Repository";
$repoPath = "D:\Private\My.OwnModule.Powershell\My.OwnModule.Powershell\_bin\";

Register-PSRepository -Name $repoName -SourceLocation $repoPath -InstallationPolicy Trusted -ScriptSourceLocation $repoPath;

Install-Module -Name $moduleName -Repository $repoName -Verbose;

Get-Module $moduleName -ListAvailable;

Упаковка модуля

Попробуем запустить local-build.ps1 и посмотреть, что получится.

Разработка и распространение модуля на Powershell

Отлично! Nuget-пакет готов и лежит в папке My.OwnModule.Powershell\_bin\My.OwnModule.Powershell.0.0.3.nupkg. Попробуем его установить и воспользоваться.

:/>  Ноутбук прошедший множество боев... Ремонт hp dv6-6b54er после нескольких сервисов. | Пикабу

Установка Powershell-модуля из nuget-пакета.

Разработка и распространение модуля на Powershell

Прекрасно, модуль готов к работе!

Там Verbose говорит, что версия 0.0.5 уже установлена и так далее. Это потому что я попытался понизить версию, вместо того, чтобы повысить. Не обращайте внимание.

GitHub репозиторий

Вы можете найти все эти файлы в моем репозитории: https://github.com/vicioussn/My.OwnModule.Powershell.

This about file contains information about using hashtables and psd1 files to configure Merge-Script. These psd1 files (e.g. “package.psd1”) are also used by PowerShell Tools for Visual Studio Code.

Config File Schema

# Whether to package as an executable. 
# Whether to obfuscate the resulting executable. 
# Whether to hide the console window.  Only valid for console applications.
            # The target .NET Framework version. You will need the .NET Developer Pack for this version installed on your machine.
# If target PowerShell 7, you can also use netcoreapp31 here 

# The output file version
# The output file description
# The output file product name
# The output file product version.
            RequireElevation = $false # Whether to require elevation when running the executable. Only valid for console applications. 
# The path to the application icon to use for the executable. 
# The type of executable to generate. Valid values are Service or Console. 
# The name of the service if the package type is Service. 
# The display name of the service if the package type is Service. 
# Whether to enable high DPI support for WinForm applications
            PowerShellArguments = '' # Sets the arguments for the PowerShell process that is hosted within the executable. You can use arguments like -NoExit, -ExecutionPolicy and -NoProfile.
# Sets the architecture of the executable. Can be either 'x86' or 'x64'
            PowerShellVersion = 'Windows PowerShell' # You can specify Windows PowerShell or PowerShell 7 or later versions version (e.g. 7.0.0)
            RuntimeIdentifier = 'win-x64' # You can specify other runtimes like linux-x64 (See .NET Core runtime identifiers)
# Disables the quick edit mode on windows console apps
# The PowerShell Host to use. 
# Removes WPF and WinForm support in PowerShell 7 executables.
            Enabled = $true # Whether to bundle multiple PS1s into a single PS1. Always enabled when Package is enabled. 
# Whether to bundle modules into the package

Using a config file

A config file can be used either from within a PowerShell script as a hashtable or imported from a psd1 file containing the hashtable. The standard name for this file is package.psd1.

The root script to package.

The path of the output directory for the resulting executable.

Options for the packager. See the config file schema for the proper layout.

Whether the packager is enabled. Valid values are either $true or $false.

Whether to obfuscate the assembly. Only valid for Windows PowerShell. Valid values are $true or $false. Note: this is a legacy technique (for educational purposes) which is easily reversed by free modern security tools.

Whether to hide the console window. Useful for when packaging form applications. Valid values are $true or $false.

The .NET version to target for the executable. You can find the valid values below.

PowerShell VersionValid .NET Versions

net4.6.2, net4.7.0, net4.7.1, net4.7.2, net4.8.0

The file version to display in the assembly properties.

The file description to display in the assembly properties.

The product name to display in the assembly properties.

The product version to display in the assembly properties.

Whether the executable requires elevation to run. This setting is only supported on Windows. Either $true or $false.

The path to the icon to display for this application.

The type of package to product. Valid values are Console or Service.

The name of the service when packaging a service (e.g. “MyService”).

The display name of the service when packaging a service (e.g. “My Utility Service”).

Enable high DPI support for Windows Forms applications. Either $true or $false.

Additional arguments to provide to the PowerShell process. This can include arguments like -ExecutionPolicy or -NoProfile. Do not include -Command.

The target architecture for the executable. This should be either x86 or x64.

The PowerShell version to target. Ensure that you specify a supported .NET version when selecting your PowerShell version. Supported versions are (replace x with specific version number):

The .NET runtime identifier to target. This defaults to win-x64. If you wish to target Linux, you could specify linux-x64. You can find a list of valid .NET runtime identifiers here.

Disables the quick edit mode on Windows console applications. This defaults to $false. Either $true or $false.

An array of resources to include with the executable. This should be an array of strings. These resources will be stored as embedded resources.

This is an advanced option. The target .NET SDK to use when packaging the executable. If not specified, the highest version will be used.

The name of the output assembly. When this is not specified, this will be the root script name.

:/>  Прикрепите изображение к буквенно-цифровому устройству ввода и ознакомьтесь с 10 эффективными сочетаниями клавиш, которые необходимы любому человеку, использующему персональный компьютер

Removes WinForms and WPF support from .NET 7\PowerShell 7 executables. This reduces the overall footprint of the executable by about 45%.

Whether bundling is enabled. Bundling will include referenced scripts and modules in the resulting executable.

Whether to bundle modules with the script executable. Modules will only be bundled when imported with Import-Module.

Whether to include nested modules of packaged modules. Requires Modules to be set to $true.

A list of modules to ignore during packaging. This should be an array of strings.

It is not required to include all aspects of the config when using Merge-Script. The only required components are Root and OutputPath. Aside from that, anything that is not include will be considered false. This means that in the below example, packaging is disabled but bundling is not. The below operation will not bundle nested modules or required assemblies of any modules it is bundling.





Create console application

Creates a PowerShell console based application that has an application icon and hides the console window.




Ironman Software Host

Use the Ironman Software host to build your executable without having to install the .NET SDK.




Create a service

Creates a PowerShell service based on the service.ps1 file and outputs to the out directory on the desktop. It will use the .NET 4.6.2 Developer Pack. The service name will be PSService and the display name will be PowerShell Service.










After building a service, you can install the service with the --install parameter of your service’s executable. To uninstall a service, use the --uninstall parameter.

Package PowerShell 7.0

Creates an executable that contains the PowerShell 7.0 engine. This executable does not require the target machine to have PowerShell or .NET Core installed. The size of the executable will be considerably larger than a typical Merge-Script executable.

Note: PowerShell 7.0 is no longer supported by Microsoft or IronmanSoftware and is considered legacy. You must use a currently supported version of PowerShell with PowerShell Pro Tools to receive support from Ironman Software.

See Microsoft Support LifeCycle for PowerShell for a list of supported versions.






Package PowerShell 7.1

You can package PowerShell 7.1 scripts by targeting .NET 5.0. You will need the .NET 5.0 SDK or later.

Note: PowerShell 7.1 is no longer supported by Microsoft or IronmanSoftware and is considered legacy. You must use a currently supported version of PowerShell with PowerShell Pro Tools to receive support from Ironman Software.

See Microsoft Support LifeCycle for PowerShell for a list of supported versions.






Package PowerShell 7.2

PowerShell Pro Tools 2021.12.0 or later required.

You can package PowerShell 7.2 scripts by targeting .NET 6.0. You will need the .NET 6.0 SDK or later.






Package PowerShell 7.3

PowerShell Pro Tools 2023.7.0 or later required.

You can package PowerShell 7.3 scripts by targeting .NET 7.0. You will need the .NET 7.0 SDK or later.






Package PowerShell 7.4

PowerShell Pro Tools 2023.7.0 or later required.

You can package PowerShell 7.4 scripts by targeting .NET 8.0. You will need the .NET 8.0 SDK or later.

        Enabled = $true
        DotNetVersion = 'net8.0'
        PowerShellVersion = "7.4.1"
        Enabled = $true
        Modules = $true

Bundle resources in a WPF application

Embeds the image.png file within the application so you can reference it in your XAML. This file resides in the same folder as window.ps1.




In the XAML, you can reference the image like this.



Access Resources in Your Script


In your script, just use this function to load the file.

You will package the resource file, just like you do with WPF applications.




Adding an Icon to a WPF Window

You cannot directly add icons to WPF windows with PowerShell and will need to do so using code. First, you’ll need to ensure that your icon is in the same directory of the script. You will also need to add your icon as a resource.




If you are using Visual Studio rather than package.psd1, you can set the add the icon to your project and set it as a resource.

Next, in your PS1 file for your WPF window, you will need to load your icon from either the file system or the packaged resources. The Get-Resource function below attempts to load from the packaged resource and, if not found, will instead load it from disk.




Next, you’ll need to create a new bitmap and set the window’s icon property to the bitmap.



An entire working example of the PS1 file can be found below.










The result is a WPF window with a custom icon that is shown both when packaged and when running the script outside of the package.

Оставьте комментарий