当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] 创建新的 PowerShell 项目

作者:精品下载站 日期:2024-12-14 07:48:56 浏览:14 分类:玩电脑

创建新的 PowerShell 项目


我从 DOS 批处理文件出现的早期就开始编写脚本了。像你们中的许多人一样,我只是将它们全部放在一个文件夹中,然后继续进行下一个项目。我的大部分工作只是为了我自己或编写项目,所以这种方法对我来说效果很好。但我需要生活在你们的世界里,2016 年这意味着新的工具和流程。对于许多开发 PowerShell 工具、模块和 DSC 资源的人来说,这意味着某种版本控制系统和测试。如果您正在进入 DevOps 的世界,这一点尤其正确。

所以我一直在我的新项目中学习和使用 Git 和 Pester。当我发现自己重新审视旧项目时,我也用 Git 存储库和一些 Pester 测试来改造它们。对我来说的一个主要好处是,每次这样做,我都会更多地了解这些工具。我已经掌握了一些知识并创建了一个项目配置脚本,我称之为 New-Project。我知道你们中有些人也有类似的情况。

该脚本采用顶级文件夹名称,我使用默认值 C:\Scripts 和项目名称。通常这将是模块的名称。该脚本使用项目名称创建一个文件夹,然后运行一组初始化步骤:

  • 创建并提交一个空的 Git 存储库(主)
  • 创建并提交 Dev 分支
  • 检查 Dev 分支
  • 创建 README.md 文件大纲
  • 创建项目 .ps1 文件的轮廓
  • 创建一个 Tests 子文件夹
  • 创建 Pester 测试文件的大纲。

所以我可能会这样使用它:

[玩转系统] 创建新的 PowerShell 项目

您需要安装 Git 命令行工具和 Pester 模块。我仍在讨论一些附加功能,例如将项目与我的 GitHub 存储库集成并包含许可证文件。甚至可能是生成模块清单的选项。也许您会尝试一下并建议一些其他新功能。该文件作为 Gist 存储在 GitHub 上。

New-Project.ps1:

#requires -version 4.0
#requires -module Pester

Function New-Project {

 New-Project -name PiedPiperBox -path C:\Scripts
PS C:\scripts\PiedPiperBox> dir -Recurse


    Directory: C:\scripts\PiedPiperBox


Mode                LastWriteTime         Length Name 
----                -------------         ------ ----
d-----        7/15/2016   5:33 PM                Docs
d-----        7/15/2016   5:33 PM                en-US
d-----        7/15/2016   5:33 PM                Tests
-a----        7/15/2016   5:33 PM             29 Changelog.txt
-a----        7/15/2016   5:33 PM           1154 LICENSE.txt
-a----        7/15/2016   5:33 PM            103 PiedPiperBox.psm1
-a----        7/15/2016   5:33 PM            392 README.md
-a----        7/15/2016   5:33 PM             32 scratch.ps1

    Directory: C:\scripts\PiedPiperBox\en-US


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----        7/15/2016   5:33 PM            132 About_PiedPiperBox.help.txt


    Directory: C:\scripts\PiedPiperBox\Tests


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----        7/15/2016   5:33 PM            260 PiedPiperBox.tests.ps1

PS C:\Scripts\PiedPiperBox> git status
On branch dev
nothing to commit, working directory clean


The first command will create a project folder C:\Scripts\PiedPiperBox and initialize as a Git repository. 
The remaining commands show what was added.

.NOTES
NAME        :  New-Project
VERSION     :  2.1
LAST UPDATED:  July 15, 2016
AUTHOR      :  Jeff Hicks (@jeffHicks)

Learn more about PowerShell:
http://jdhitsolutions.com/blog/essential-powershell-resources/

  ****************************************************************
  * DO NOT USE IN A PRODUCTION ENVIRONMENT UNTIL YOU HAVE TESTED *
  * THOROUGHLY IN A LAB ENVIRONMENT. USE AT YOUR OWN RISK.  IF   *
  * YOU DO NOT UNDERSTAND WHAT THIS SCRIPT DOES OR HOW IT WORKS, *
  * DO NOT USE IT OUTSIDE OF A SECURE, TEST SETTING.             *
  ****************************************************************
.LINK
git
.LINK
New-Item
.INPUTS
[string]
.OUTPUTS
None
#>

[cmdletbinding(SupportsShouldProcess)]
Param(
[Parameter(
 Position=0,
 Mandatory,
 HelpMessage="The name of the project")]
[ValidateNotNullorEmpty()]
[string]$Name,

[Parameter(HelpMessage="The top level path for the new project")]
[ValidateNotNullorEmpty()]
[ValidateScript({
if (Test-Path $_) {
   $True
}
else {
   Throw "Cannot validate path $_"
}
})]
[string]$Path = "C:\Scripts",
[switch]$Passthru
)

Write-Verbose "[BEGIN  ] Starting: $($MyInvocation.Mycommand)"

Write-Verbose "[PROCESS] Creating project $name under $path"

$newPath = Join-Path -Path $Path -ChildPath $Name

If (-Not (Test-path -Path $newPath) ) {
    $parent = New-Item -Path $path -Name $Name -ItemType Directory
    #create Test Folder
    $tests = New-Item -Path $newPath -Name Tests -ItemType Directory

    #create localized folder
    Write-Verbose "[PROCESS] Creating folder $psculture under $path"

    New-Item -path $newPath -Name $PSCulture -ItemType Directory | Out-Null

    #create About help topic
$about = @"
TOPIC
    About_$Name

SHORT DESCRIPTION
    under development

LONG DESCRIPTION
    under development

SEE ALSO

"@
    Write-Verbose "[PROCESS] Creating About help topic outline"
    Set-Content -Value $about -path "$newPath$PSCulture\About_$Name.help.txt"

    #create docs folder
    Write-Verbose "[PROCESS] Creating folder Docs under $path"
    New-Item -path $newPath -Name Docs -ItemType Directory | Out-Null

    #create Changelog.txt
    Write-Verbose "[PROCESS] Creating Changelog.txt"
    Set-Content -Path $newPath\Changelog.txt -Value "#Changelog for $Name"
        
    #create README.md
    Write-Verbose "[PROCESS] Creating README.md"
    $readme = @"
# $Name #


****************************************************************
DO NOT USE IN A PRODUCTION ENVIRONMENT UNTIL YOU HAVE TESTED 
THOROUGHLY IN A LAB ENVIRONMENT. USE AT YOUR OWN RISK. IF YOU DO 
NOT UNDERSTAND WHAT THIS SCRIPT DOES OR HOW IT WORKS, DO NOT USE
OUTSIDE OF A SECURE, TEST SETTING.      
****************************************************************
"@

    Set-Content -Value $readme -Path "$newPath\README.md"

    #create script file
    Write-Verbose "[PROCESS] Creating $name.psm1"
    $myScript = @"
#requires -version $($PSVersionTable.psversion.Major).$($PSVersionTable.psversion.Minor)

#region Main


#endregion

#define aliases

#export module members

"@

    Set-Content -Value $myScript -Path "$newPath$name.psm1"
    
    #create License file
$lic = @"
Copyright (c) 2016 JDH Information Technology Solutions, Inc.
       
       
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
       
       
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
       
       
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"@
    Write-Verbose "[PROCESS] Creating LICENSE.txt"
    Set-Content -Value $lic -Path "$newPath\LICENSE.txt"
   
    #create a scratch file which my git config is set to ignore
    Write-Verbose "[PROCESS] Creating scratch.ps1"
    Set-Content -Value "#scratch file for $Name" -Path "$newPath\scratch.ps1"

    #Pester Init
    Write-Verbose "[PROCESS] Running Pester setup"
    #body of Test script
    $TestInit = @"
`$here = Split-Path -Parent `$MyInvocation.MyCommand.Path
`$sut = (Split-Path -Leaf `$MyInvocation.MyCommand.Path) -replace '\.Tests\.', '.'
. `$here\..\`$sut

Describe $Name {
    It "does something useful" {
        `$true | Should Be `$true
    }
}
"@
    
    if ($PSCmdlet.ShouldProcess("newPath","Pester setup")) {
        $PesterTest = Join-Path -Path $Tests.FullName -ChildPath "$name.tests.ps1"
        Write-Verbose "[PROCESS] Creating $pestertest"
        Set-Content -Value $TestInit -Path $PesterTest
        Write-Verbose "[PROCESS] Git commit $pestertest"
        
    }
    
    #Git Init
    Write-Verbose "[PROCESS] Running Git setup"
    if ($PSCmdlet.ShouldProcess($newPath,"Git Init")) {    
        Write-Verbose "[PROCESS] Git: Init"
        git init -q $newpath
        cd $newPath
        #create Master and add all files
        Write-Verbose "[PROCESS] Git: Add base Files"
        git add .
        Write-Verbose "[PROCESS] Git: Initial Commit"
        git commit -a -q -m "Initial commit"
        #create Dev branch
        Write-Verbose "[PROCESS] Git: Create Dev branch"
        git branch -q dev
        #checkout dev
        Write-Verbose "[PROCESS] Git: Checkout Dev branch"
        git checkout -q dev
    }
    else {
        #simulate WhatIf processing for Git commands
        Write-Host "What if: performing the operation git init -q $newPath"
        Write-Host "What if: performing the operation git commit -a -q -m 'Initial commit'"
        Write-Host "What if: performing the operation git branch -q dev"
        Write-Host "What if: performing the operation git checkout -q dev"
    }    
}
else {
    Write-Warning "$NewPath appears to already exist."
}

if (Test-Path -path $newPath) {
    cd $newPath
}

if ($Passthru) {
    Get-ChildItem -Recurse
}
Write-Verbose "[END    ] Ending: $($MyInvocation.Mycommand)"

} #close function

我希望你能尝试一下并告诉我你的想法。

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯