1675417825
As we do many experiments with UI based frameworks node_modules folders occupy a large portion of the disk space and after a few years, the disk space starts to diminish.
I have a 500GB SSD hard disk in my laptop and have recently run out of space and started to analyze what is that occupies so much space. I do not store personal images and documents on my laptop, at least not more than 1-2 GB.
When I analyzed the code base folder I realized that the experiments I did years ago are still on my machine and needed some cleanup. The easiest way was to remove unused data without any kind of loss is by deleting the huge node_modules folder in every project I did not use currently.
For this purpose, I wrote below PowerShell script to clean up all the node_modules folders in my code folder
Get-ChildItem -Path . -Filter node_modules -Recurse | Remove-Item -Force -Recurse
The "Get-Childitem" here gets all the folders with path "." (which is the current folder I am running the script in) with filter as folder name "node_module" and pipes in into "Remove-Item" command. This command recursively finds all the files and folders inside and deletes them without confirmation. ("Force" parameter is added to avoid asking yes/no before deleting each folder)
After executing this command I was able to recover more than 20Gb of disk space.
Original article source at: https://www.c-sharpcorner.com/
1671922500
If you are getting this error which says .ps1 file cannot be run because the file is not digitally signed. You cannot run this script on the current system
By default, the command prompts are set to run only the scripts that are digitally signed. Usually, in prod servers this could be the ideal case.
But in some cases, you may not need digitally signed scripts to execute the standard admin jobs, such as getting the system performance, or generating the M365 services report or running some standard migrations from on-prem to cloud. In this case, you can set the execution policy for current user to unrestricted.
Set-ExecutionPolicy Unrestricted -Scope CurrentUser
After running this command, you should be able to run the unsigned PowerShell scripts for this user.
Original article source at: https://www.c-sharpcorner.com/
1671311940
Problem: Unzip mulitple files in one go.
PowerShell
PowerShell is a task automation and configuration management program from Microsoft, consisting of a command-line shell and the associated scripting language
I started working on PowerShell years back when I started with dev ops to automate simple tasks, like packaging the application products, automated builds, etc.
When I hit a problem like unzipping a huge number of files, my very first thought was to select all the files and right-click and select unzip, but this did not work. That's when I landed on the below line to unzip bulk.
$files = Get-Childitem .
foreach($fs in $files){Expand-Archive $fs -DestinationPath .}
The file line reads all the files in the current directory (. implies current directory, you can also give full directory path)
The second line is using PowerShell "Expand-Archive" command to unzip all the zip files in the list.
Expand-Archive
[-Path] <String>
[[-DestinationPath] <String>]
[-Force]
[-PassThru]
[-WhatIf]
[-Confirm]
[<CommonParameters>]
Steps
If this fails, then set the execution policy to unrestricted for this session and try again.
Conclusion
If you are using a windows machine and need a quick way to unzip files, then go with expand-archive.
References
Original article source at: https://www.c-sharpcorner.com/
1671276780
Finding inactive users in an organization is very difficult where hundreds of users are working. Many organizations share information with external users or guest users who do not belong to their organization. For example, some companies connect with their customers on MS teams or shares information through SharePoint or One Drive where they provide access as guest users. Many times, companies do not have information about whether those guests’ users are still active or not. How many days they last logged in?
One simple solution is login to Azure Active Directory and navigate to a specific user and get the last login date. But it is very time-consuming to go to every single user and get the last login date.
Another solution is Azure Audit Log which captures users’ activity with datetime.
Get-AzureADAuditSignInLogs -Filter “userPrincipalName= ' UserPrincipalName '” -Top 1
The parameter -Top is for the maximum number of records to return. In case of above we will get last one record.
The above PowerShell command returns last sign in datetime of the specific user of any of the apps like MS Teams, SharePoint, One Drive, etc. Use Get-AzureADUser to get a list of users and loop through it to get each specific user’s last sign-in date. Here, there is one challenge in using Get-AzureADAuditSignInLogs command in loop. It returns a throttling issue when looping through a set of users.
To resolve the problem, just add Start-Sleep -Milliseconds 10 at the end of each request. We will be using this in try/catch.
Below is the complete PowerShell script which reads users from Azure AD, get last sign-in date of each user, and save it in CSV file.
Function FindLastSignInDate {
param ( [string]$upn )
$AllUsers = @()
$DateToday =(Get-Date).ToString("yyyy-MM-dd")
$Days = 0
$filter = "userPrincipalName = '" + $upn + "'"
Try {
$Result = Get-AzureADAuditSignInLogs -Filter $filter -Top 1 | Select-Object CreatedDateTime, UserPrincipalName
$LoginTime = $Result.CreatedDateTime
if($LoginTime -ne $null){
$LoginDate = $LoginTime.substring(0,10)
$ts = New-TimeSpan -Start $LoginDate -End $DateToday
$Days = $ts.Days
$AllUsers += [pscustomobject]@{
UPN= $UPN
LoginDate = $LoginDate
Days = $Days
}
}
Catch
{
sleep 10
GetLastSignInDate $upn
}
finally {
$AllUsers | Out-File "c:\LastLogin.csv" -Append
}
}
Import-Module AzureADPreview
$Result = ""
$output = ""
$filter = ""
#Connect to Azure AD
$user = "xxxxxxxxxx@xxxxxxxxx.com"
$password = "xxxxxxxxxxxx"
$secPass = ConvertTo-SecureString $password -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PSCredential ($user, $secPass)
Connect-AzureAD -Credential $Cred
$Users = Get-AzureADUser -all $true
Foreach($user in $Users ){
$upn = $user.UserPrincipalName.ToLower().Trim()
FindLastSignInDate $upn
}
The above script will create a CSV file.
Original article source at: https://www.c-sharpcorner.com/
1670069069
In this blog, we will learn to manually install PowerShell modules. Recently, I was working on VM desktop with restricted access to perform PowerShell tasks, no direct internet access, and PSRepository access for installing modules. If you do not have any restrictions, we can install PowerShell modules from the official PowerShell gallery repository using the command "Install-Module".
Note
There is no direct repository to download modules from the official PowerShell gallery. You can download only NuGet(a .nupkg file) package from the official site to install the module, but this will not be the complete module installation.
Prerequisites
Below are the steps to manually installing PowerShell modules,
Step 1
To ensure that the module exists, launch PowerShell and search for it in the PowerShell Gallery.
Find-Module -Name “module name”
Step 2
Download and save module to local folder path using Save-Module command.
Save-Module –Name “module name” –Path “local folder path”
Downloaded module to the specified location:
Step 3
Now copy the downloaded module to C:\Program Files\WindowsPowerShell\Modules path.
Step 4
Offline installation is complete, now you can validate if this module is available.
Get-Module -ListAvailable “module name”
Step 5
We can get list of available commands for installed modules.
Get-Command -Module “module name”
In this blog, we learned how to manually install PowerShell modules in offline mode when you have restricted access to a computer or are working on an isolated network with no direct access to the internet.
Original article source at: https://www.c-sharpcorner.com/
1661615340
Please note that due to low usage this module is no longer being actively maintained. It is recommended to use either the
Docker cli (docker.exe)
or try Docker.DotNet directly.
PowerShell for Docker
This repo contains a PowerShell module for the Docker Engine. It can be used as an alternative to the Docker command-line interface (docker
), or along side it. It can target a Docker daemon running on any operating system that supports Docker, including both Windows and Linux.
Note that this module is still in alpha status and is likely to change rapidly.
Note that there is no dependency on the Docker client.
Currently, the Docker endpoint must support API version 1.24, which is still in development. Practically speaking, this means you will need a development build of Docker. If your Docker endpoint is running on Windows Server Technical Preview 5, that should be new enough.
See our Releases page for current releases of Docker PowerShell, or you can try the development builds below. Feedback and contributions welcome!
The following information will allow you to install development builds -- do understand that these are early builds and will change (hopefully with your feedback).
The dev builds are updated for every commit to master and are released to https://ci.appveyor.com/nuget/docker-powershell-dev. To install the latest build, in PowerShell 5.0 run:
> Register-PSRepository -Name DockerPS-Dev -SourceLocation https://ci.appveyor.com/nuget/docker-powershell-dev
> Install-Module -Name Docker -Repository DockerPS-Dev -Scope CurrentUser
(Note: if you get an error like "WARNING: MSG:SourceLocationNotValid" try updating your Nu-Get version as explained in this issue comment.)
After this, you can update to new development builds with just:
> Update-Module -Name Docker
As of the v6.0.0-alpha.10 release of PowerShell, the instructions listed above for development builds work as expected on Linux.
From an internet connected machine:
> Save-Module -Name Docker -Path .
Copy the entire folder .\Docker
to the destination at: %ProgramFiles%\WindowsPowerShell\Modules
We welcome contributions to this project in the form of issues (bugs, suggestions, proposals, etc.) and pull requests.
For pull requests, we do require that you sign the Microsoft Contribution License Agreement. It is a simple process that you only need to complete once.
This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.
This project uses Docker.DotNet as a git submodule (git submodule --help
to view manual pages for submodule). When first starting a new clone of Docker.Powershell, this requires one-time initializtion of the submodule with git submodule update --init
to prepare the directories used by the submodule. When making changes to Docker.PowerShell that use corresponding changes made to Docker.DotNet master branch, use git submodule update --remote
to sync the submodule to the latest in master, and include the updated commit id for the submodule in the changes submitted to Docker.Powershell.
To compile this project, you need the following:
Once these are installed, you can run:
> dotnet restore
> dotnet publish .\src\Docker.PowerShell -o .\src\Docker.PowerShell\bin\Module\Docker -f net46
or for a module targetted at cross-platform PowerShell:
> dotnet restore
> dotnet publish .\src\Docker.PowerShell -o .\src\Docker.PowerShell\bin\Module\Docker -f netstandard1.6
This will produce the PowerShell module at .\src\Docker.PowerShell\bin\Module\Docker
in the project folder.
You will only need to run dotnet restore
once unless you pull changes that update the project dependencies in project.json.
This codebase includes markdown files corresponding to the help information for each of the cmdlets. This markdown is generated and consumed by the platyPS PowerShell module. You should use the platyPS cmdlets to update and refresh the markdown files to reflect any changes made to the structure or behavior of the cmdlets. Follow the instructions on the platyPS github readme to get the module installed, and then after imported the Docker module with your changes compiled in, run:
> New-MarkdownHelp -Module Docker -OutputFolder .\src\Docker.Powershell\Help -ErrorAction SilentlyContinue
> Update-MarkdownHelp -Path .\src\Docker.PowerShell\Help
This will create new entries for any added parameters in existing cmdlets, as well as new markdown files for any new cmdlets, leaving placeholder text for the descriptions and examples. Please keep the descriptions of any existing or new parameters or cmdlets up-to-date with any changes to the implementation.
If you use Visual Studio Code as your editor, you will find three tasks pre-defined in the top-level directory:
restore
will perform dotnet restore
across the whole project to reload any dependencies.build
will perform the dotnet publish
command with the arguments listed in the compilation section above.test
will launch a new powershell window with the module loaded for manual testing.update-help
will use powershell to run the New-MarkdownHelp and Update-MarkdownHelp cmdlets with the arguments necessary to generate any updates to the help markdown files. NOTE: This requires the platyPS module and uses the most recently built local Docker module.Author: Microsoft
Source code: https://github.com/Microsoft/Docker-PowerShell
License: MIT license
#docker #powershell
1661228100
A Docker orchestration of open-source solutions to facilitate secure, collaborative development.
The ShinyStudio project is an orchestration of various open-source solutions with the goal of providing:
There are two distributions of ShinyStudio, the image and the stack, explained below.
The ShinyStudio image, hosted on DockerHub, builds upon the Rocker project to include:
The image is great for a personal instance, a quick demo, or the building blocks for a very customized setup.
The ShinyStudio stack builds upon the image to incorporate:
Each component of the stack is run in a Docker container for reproducibility, scalability, and security. Only the NGINX port is exposed on the host system; all communication between ShinyProxy and other components happens inside an isolated Docker network.
The setup has been verified to work on each of Docker (for Linux) and Docker Desktop (for Mac and Windows).
Note: when upgrading ShinyStudio, please setup from scratch and migrate existing content/settings afterward.
Note: Setup must be run as a non-root user.
To download and run the ShinyStudio image from DockerHub, first, create a docker network named shinystudio-net
:
docker network create shinystudio-net
Then, execute docker run
in the terminal for your OS:
docker run -d --restart always --name shinyproxy \
--network shinystudio-net \
-v /var/run/docker.sock:/var/run/docker.sock \
-e USERID=$USERID \
-e USER=$USER \
-e PASSWORD=password \
-e CONTENT_PATH="${HOME}/ShinyStudio" \
-e SITE_NAME=shinystudio \
-p 8080:8080 \
dm3ll3n/shinystudio
docker run -d --restart always --name shinyproxy `
--network shinystudio-net `
-v /var/run/docker.sock:/var/run/docker.sock `
-e USERID=1000 `
-e USER=$env:USERNAME `
-e PASSWORD=password `
-e CONTENT_PATH="/host_mnt/c/Users/$env:USERNAME/ShinyStudio" `
-e SITE_NAME=shinystudio `
-p 8080:8080 `
dm3ll3n/shinystudio
Notice the unique form of the path for the
CONTENT_PATH
variable in the Windows setup.
Once complete, open a web browser and navigate to http://<hostname>:8080
. Log in with your username and the password password
.
The stack distribution of ShinyStudio is delivered through the GitHub repo and introduces two additional requirements:
HTTPS is configured by default, so SSL/TLS certs are required in order for the stack to operate. Use the provided script certify.sh
(certify.ps1
for Windows) to create a self-signed certificate, or to request one from LetsEncrypt (more on that).
# copy the setup files.
git clone https://github.com/dm3ll3n/ShinyStudio
# enter the directory.
cd ShinyStudio
# run certify to generate self-signed cert.
./certify.[sh/ps1]
Now, browse to http://<hostname>
(e.g., http://localhost
) to access ShinyStudio. On first launch, you will need to accept the warning about an untrusted certificate. See the customized setup to see how to request a trusted cert from LetsEncrypt.
The default logins are below. See the customized setup to see how to add/remove accounts.
username | password |
---|---|
user | user |
admin | admin |
superadmin | superadmin |
There are three files essential to a customized configuration:
.env
The docker-compose environment file. The project name, content path, and HTTP ports can be changed here.
Note that Docker volume names are renamed along with the project name, so be prepared to migrate or recreate data stored in Docker volumes when changing the project name.
application.yml
The ShinyProxy config file. Users can be added/removed here. Other configurations are available too, such as the site title and the ability to provide a non-standard landing page.
Using the provided template, you can assign users to the following groups with tiered access:
Review the ShinyProxy configuration documentation for all options.
nginx.conf
The NGINX config file. Defines the accepted site name and what ports to listen on.
If you change the ports here, you must also change the ports defined in the .env
file. Also, if you change the domain name, you must provide/generate a new certificate for it.
certify.[sh/ps1]
The script used to generate a self-signed cert, or to request a trusted cert from LetsEncrypt.
With no parameters, certify
generates a self-signed cert for example.com
(the default domain name defined in nginx.conf
).
To generate a self-signed cert with another domain name, first edit the domain name in nginx.conf
. Afterward, generate a new cert with:
./certify.sh <domain name>
# e.g., ./certify.sh www.shinystudio.com
If your server is accessible from the web, you can request a trusted certificate from LetsEncrypt. First, edit nginx.conf
with your domain name, then request a new cert from LetsEncrypt like so:
./certify.sh <domain name> <email>
# e.g., ./certify.sh www.shinystudio.com donald@email.com
CertBot, included in the stack, will automatically renew your LetsEncrypt certificate.
To manage the services in the stack, use the native docker-compose commands, e.g.:
# stop all services.
docker-compose down
# start all services.
docker-compose up -d
Open either RStudio or VS Code and notice two important directories:
Files must be saved in either of these two directories in order to persist between sessions.
These two folders are shared between instances RStudio, VS Code, and Shiny Server. So, creating new content is as simple as saving a file to the appropriate directory.
The ShinyStudio image comes with…
…and ODBC drivers for:
These are persistent because they are built into the image.
Persistent | |
---|---|
__ShinyStudio__ directory | Yes |
__Personal__ directory | Yes |
Other directories | No |
R Libraries | Yes |
Python Packages | Yes |
PowerShell Modules | Yes |
RStudio User Settings | Yes |
VS Code User Settings | Yes |
Installed Apps | No |
Installed Drivers | No |
Author: fresh2dev
Source Code: https://github.com/fresh2dev/ShinyStudio
License: MIT license
1652797028
Antes de comenzar, el código completo utilizado para este artículo está disponible aquí: https://github.com/santoshkaranam/PSUnitTestFramework
Si está familiarizado con PowerShell, Perster y PSSCriptAnalyzer, pase a la sección "Generación del informe".
Escribir scripts de PowerShell ha sido la forma más fácil para que los desarrolladores automaticen las cosas si tienen un fondo Azure .NET, ya que PowerShell funciona en todas las plataformas. Pero a menudo olvidamos que estos scripts también deben poder mantenerse. Para esto, necesitamos tener todas las pautas de codificación, casos de prueba y cobertura de prueba para mantener los scripts mantenibles. Aquí estoy discutiendo mi solución para lograr lo mismo usando Pester, PSSCriptAnalyzer ReportUnit.
PowerShell se ejecuta en Windows, Linux y macOS. PowerShell es una solución de automatización de tareas multiplataforma compuesta por un shell de línea de comandos, un lenguaje de secuencias de comandos y un marco de gestión de configuración.
El caparazón incluye las siguientes características:
Puede abrir el editor de powershell usando "powershell ise" en ejecución.
Nota: - Para desarrollar y ejecutar scripts de PowerShell en su máquina, debe cambiar la política de ejecución a sin restricciones.
Establecer política de ejecución sin restricciones
La naturaleza extensible de PowerShell ha permitido que un ecosistema de módulos de PowerShell implemente y administre casi cualquier tecnología con la que trabaje. Por ejemplo:
microsoft
Azure Windows Exchange SQL
Tercero
AWS VMware Google Cloud
Como resultado de estas características, PowerShell se usa ampliamente para automatizar, pero estos scripts no se prueban, ya que una vez que se completa la automatización, estos scripts nunca se modifican hasta que algo falla.
Para tener guiones que se puedan mantener, es necesario escribir casos de prueba para cubrir todos los escenarios y cubrir los guiones completos. En este artículo, voy a explicar una de las formas de escribir casos de prueba para scripts y automatizar completamente la generación de informes de cobertura.
Para esto estoy usando Perter y PSScriptAnalyzer que están disponibles como módulo en powershell. El resultado final generará un archivo HTML que se puede visualizar como se muestra a continuación
Con este HTML generado usando ReportUnit.exe, puede verificar los casos de prueba que han pasado y verificar si algunos casos de prueba han fallado. Para los casos de prueba fallidos, las líneas y los casos de prueba exactos están disponibles en el informe HTML. Este informe se puede publicar en un servidor estático para ser visualizado.
Pester es un marco de prueba y simulación para PowerShell.
Pester proporciona un marco para escribir y ejecutar pruebas. Pester se usa más comúnmente para escribir pruebas unitarias y de integración, pero no se limita solo a eso. También es una base para herramientas que validan entornos completos, implementaciones informáticas, configuraciones de bases de datos, etc.
Crear una prueba de Pester
BeforeAll {
function Get-Planet ([string]$Name = '*') {
$planets = @(
@{ Name = 'Mercury' }
@{ Name = 'Venus' }
@{ Name = 'Earth' }
@{ Name = 'Mars' }
@{ Name = 'Jupiter' }
@{ Name = 'Saturn' }
@{ Name = 'Uranus' }
@{ Name = 'Neptune' }
) | ForEach-Object { [PSCustomObject] $_ }
$planets | Where-Object { $_.Name -like $Name }
}
}
Describe 'Get-Planet' {
It 'Given no parameters, it lists all 8 planets' {
$allPlanets = Get-Planet
$allPlanets.Count | Should -Be 8
}
}
Intento
Puede leer más sobre cómo escribir casos de prueba de secuencias de comandos de powershell usando pester aquí: https://pester-docs.netlify.app/docs/quick-start
Perster también genera estadísticas de cobertura de código para Hit Commands (líneas hit), comentarios perdidos (no cubiertos en las pruebas), esta es una característica útil cuando desea analizar su código.
Una vez que tenemos los casos de prueba escritos, lo siguiente es verificar la cobertura del código y el análisis del script para detectar violaciones de las reglas.
PSScriptAnalyzer es un verificador de código estático para módulos y scripts de PowerShell. PSScriptAnalyzer comprueba la calidad del código de PowerShell ejecutando un conjunto de reglas. Las reglas se basan en las mejores prácticas de PowerShell identificadas por el equipo de PowerShell y la comunidad. Genera DiagnosticResults (errores y advertencias) para informar a los usuarios sobre posibles defectos en el código y sugiere posibles soluciones para mejorar.
PSScriptAnalyzer se envía con una colección de reglas integradas que verifica varios aspectos del código de PowerShell, como la presencia de variables no inicializadas, el uso de PSCredential Type, el uso de Invoke-Expression, etc. También se admiten funcionalidades adicionales como excluir/incluir reglas específicas.
Se puede leer más aquí: https://github.com/PowerShell/PSScriptAnalyzer
Ahora la Carne!!!!!!!!
Ahora que sabemos cómo escribir casos de prueba con perter, PSSCriptAnalyzer profundizaremos en .\TestExecutor.ps1
Import-Module Pester
# paths to include for code coverage report
$filesCovered = @("$PSScriptRoot\scripts\*.psm1","$PSScriptRoot\scripts\*.ps1")
#check and create artifacts folder
$artifactFolder = "$PSScriptRoot\artifacts"
if (!(test-path -path $artifactFolder)) {new-item -path $artifactFolder -itemtype directory}
# run pester test cases
$testOutputFile = "$PSScriptRoot\artifacts\TestResults.xml"
$results = Invoke-Pester -EnableExit -OutputFile $testOutputFile -OutputFormat NUnitXml -PassThru -CodeCoverage $filesCovered
#run reportunit.exe to generate test report using input '$testOutputFile' in same folder
.\reportgenerator\ReportUnit.exe "$testOutputFile"
#output coverage result to different files from '$results.CodeCoverage' variable
$results.CodeCoverage.HitCommands | ConvertTo-Html | Out-File -FilePath "$PSScriptRoot\artifacts\HitCommands.html"
if($results.CodeCoverage.MissedCommands -ne $null){
$results.CodeCoverage.MissedCommands | ConvertTo-Html | Out-File -FilePath "$PSScriptRoot\artifacts\MissedCommands.html"}
$results.CodeCoverage.AnalyzedFiles | Out-File -FilePath "$PSScriptRoot\artifacts\AnalyzedFiles.txt"
#calculate coverage percentage
$Percentage = ($results.CodeCoverage.NumberOfCommandsExecuted / $results.CodeCoverage.NumberOfCommandsAnalyzed)*100
$results.CodeCoverage | Add-Member Percentage ($Percentage | % { '{0:0.##}' -f $_ })
$results.CodeCoverage | ConvertTo-Html | Out-File -FilePath "$PSScriptRoot\artifacts\CoverageReport.html"
Intento
En la secuencia de comandos anterior, primero obtenemos todos los archivos que deben probarse y ejecutamos el módulo perster para probar las secuencias de comandos utilizando los casos de prueba escritos en secuencias de comandos separadas.
Luego, los resultados se almacenan en un archivo XML para que los use el generador de informes.
El generador de informes se alimenta con este archivo para producir un HTML estático para visualizar.
Ejemplo de informe de errores
Puede verificar que la página realmente muestre qué línea en el script tiene el error.
GitHub : https://github.com/santoshkaranam/PSUnitTestFramework
Si le gusta este marco, puede clonar este repositorio y usarlo con su equipo. Este código tiene licencia MIT License. Puede mejorar el marco contribuyendo al código.
Escribir scripts de PowerShell ha sido la forma más fácil para que los desarrolladores automaticen las cosas si tienen un fondo de Azure .NET, ya que PowerShell funciona en todas las plataformas. Pero a menudo olvidamos que estos scripts también deben poder mantenerse. Para esto, necesitamos tener todas las pautas de codificación, casos de prueba y cobertura de prueba para mantener los scripts mantenibles.
He mostrado aquí formas simples que seguí para mantener los scripts que he escrito usando Pester y PSSCriptAnalyzer y ReportGenerator con los cuales no solo podemos escribir casos de prueba sino también generar informes de cobertura y estado de ejecución de casos de prueba en un hermoso HTML proporcionado por ReportUnit.Exe que se pueden publicar en servidores de compilación para el acceso del equipo.
Descargue el código del repositorio de github y ejecútelo localmente y déjeme saber los comentarios.
Referencias
Fuente: https://www.c-sharpcorner.com/article/test-coverage-for-powershell-scripts-with-pester/
1652796780
始める前に、この記事で使用されている完全なコードは、https://github.com/santoshkaranam/PSUnitTestFrameworkから入手できます。
powershell、perster、およびPSSCriptAnalyzerに精通している場合は、「レポートの生成」のセクションに進んでください。
PowerShellスクリプトは、すべてのプラットフォームで機能するため、紺碧の.netバックグラウンドからのものである場合、DevOpsが自動化する最も簡単な方法です。しかし、これらのスクリプトも保守可能である必要があることを忘れがちです。このためには、スクリプトを保守可能に保つために、すべてのコーディングガイドライン、テストケース、およびテストカバレッジを実行する必要があります。ここでは、Pester、PSSCriptAnalyzerReportUnitを使用して同じことを実現するためのソリューションについて説明しています。
PowerShellは、Windows、Linux、およびmacOSで実行されます。PowerShellは、コマンドラインシェル、スクリプト言語、および構成管理フレームワークで構成されるクロスプラットフォームのタスク自動化ソリューションです。
シェルには次の機能が含まれています。
実行中に「powershellise」を使用してPowerShellエディターを開くことができます。
注:-マシンでPowerShellスクリプトを開発して実行するには、実行ポリシーを無制限に変更する必要があります。
Set-ExecutionPolicy Unrestricted
PowerShellの拡張可能な性質により、PowerShellモジュールのエコシステムは、使用するほぼすべてのテクノロジを展開および管理できます。例えば:
マイクロソフト
Azure Windows Exchange SQL
第三者
AWS VMWare Google Cloud
これらの機能の結果として、PowerShellは自動化に広く使用されていますが、自動化が完了すると、何かが失敗するまでこれらのスクリプトが変更されることはないため、これらのスクリプトはテストされません。
保守可能なスクリプトを作成するには、すべてのシナリオをカバーし、スクリプト全体をカバーするテストケースを作成する必要があります。この記事では、スクリプトのテストケースを作成し、カバレッジレポートの生成を完全に自動化する方法の1つについて説明します。
このために、PowerShellのモジュールとして利用できるPerterとPSScriptAnalyzerを使用しています。最終結果は、以下のように視覚化できるHTMLファイルを生成します
ReportUnit.exeを使用して生成されたこのHTMLを使用すると、合格したテストケースを確認し、一部のテストケースが失敗したかどうかを確認できます。失敗したテストケースについては、正確なテストケースと行がHTMLレポートに表示されます。このレポートは、静的サーバーで公開して視覚化できます。
Pesterは、PowerShellのテストおよびモックフレームワークです。
Pesterは、テストを作成して実行するためのフレームワークを提供します。Pesterは、ユニットテストと統合テストの作成に最も一般的に使用されますが、これに限定されるものではありません。また、環境全体、コンピューターの展開、データベース構成などを検証するツールのベースでもあります。
ペスターテストの作成
BeforeAll {
function Get-Planet ([string]$Name = '*') {
$planets = @(
@{ Name = 'Mercury' }
@{ Name = 'Venus' }
@{ Name = 'Earth' }
@{ Name = 'Mars' }
@{ Name = 'Jupiter' }
@{ Name = 'Saturn' }
@{ Name = 'Uranus' }
@{ Name = 'Neptune' }
) | ForEach-Object { [PSCustomObject] $_ }
$planets | Where-Object { $_.Name -like $Name }
}
}
Describe 'Get-Planet' {
It 'Given no parameters, it lists all 8 planets' {
$allPlanets = Get-Planet
$allPlanets.Count | Should -Be 8
}
}
バッシュ
pesterを使用してPowerShellスクリプトのテストケースを作成する方法について詳しくは、https: //pester-docs.netlify.app/docs/quick-startをご覧ください。
Persterは、ヒットコマンド(ヒットされた行)のコードカバレッジ統計も生成します。コメントの欠落(テストではカバーされません)これは、コードを分析する場合に便利な機能です。
次にテストケースを作成したら、コードカバレッジとスクリプト分析でルール違反をチェックします。
PSScriptAnalyzerは、PowerShellモジュールおよびスクリプトの静的コードチェッカーです。PSScriptAnalyzerは、一連のルールを実行してPowerShellコードの品質をチェックします。ルールは、PowerShellチームとコミュニティによって特定されたPowerShellのベストプラクティスに基づいています。DiagnosticResults(エラーと警告)を生成して、潜在的なコードの欠陥についてユーザーに通知し、改善のための可能な解決策を提案します。
PSScriptAnalyzerには、初期化されていない変数の存在、PSCredentialタイプの使用、Invoke-Expressionの使用など、PowerShellコードのさまざまな側面をチェックする組み込みルールのコレクションが付属しています。特定のルールの除外/包含などの追加機能もサポートされています。
詳細はこちらをご覧ください-https://github.com/PowerShell/PSScriptAnalyzer
今肉!!!!!!!!
perter、PSSCriptAnalyzerを使用してテストケースを作成する方法がわかったので、。\TestExecutor.ps1を深く掘り下げます。
Import-Module Pester
# paths to include for code coverage report
$filesCovered = @("$PSScriptRoot\scripts\*.psm1","$PSScriptRoot\scripts\*.ps1")
#check and create artifacts folder
$artifactFolder = "$PSScriptRoot\artifacts"
if (!(test-path -path $artifactFolder)) {new-item -path $artifactFolder -itemtype directory}
# run pester test cases
$testOutputFile = "$PSScriptRoot\artifacts\TestResults.xml"
$results = Invoke-Pester -EnableExit -OutputFile $testOutputFile -OutputFormat NUnitXml -PassThru -CodeCoverage $filesCovered
#run reportunit.exe to generate test report using input '$testOutputFile' in same folder
.\reportgenerator\ReportUnit.exe "$testOutputFile"
#output coverage result to different files from '$results.CodeCoverage' variable
$results.CodeCoverage.HitCommands | ConvertTo-Html | Out-File -FilePath "$PSScriptRoot\artifacts\HitCommands.html"
if($results.CodeCoverage.MissedCommands -ne $null){
$results.CodeCoverage.MissedCommands | ConvertTo-Html | Out-File -FilePath "$PSScriptRoot\artifacts\MissedCommands.html"}
$results.CodeCoverage.AnalyzedFiles | Out-File -FilePath "$PSScriptRoot\artifacts\AnalyzedFiles.txt"
#calculate coverage percentage
$Percentage = ($results.CodeCoverage.NumberOfCommandsExecuted / $results.CodeCoverage.NumberOfCommandsAnalyzed)*100
$results.CodeCoverage | Add-Member Percentage ($Percentage | % { '{0:0.##}' -f $_ })
$results.CodeCoverage | ConvertTo-Html | Out-File -FilePath "$PSScriptRoot\artifacts\CoverageReport.html"
バッシュ
上記のスクリプトでは、最初にテストが必要なすべてのファイルを取得し、persterモジュールを実行して、個別のスクリプトで記述されたテストケースを使用してスクリプトをテストします。
結果は、レポートジェネレータが使用できるようにXMLファイルに保存されます。
レポートジェネレータにはこのファイルが提供され、視覚化する静的HTMLが生成されます。
エラーレポートのサンプル
このページに、スクリプトのどの行にエラーがあるかが実際に表示されていることを確認できます。
GitHub:https ://github.com/santoshkaranam/PSUnitTestFramework
このフレームワークが気に入った場合は、このリポジトリのクローンを作成して、チームで使用できます。このコードはMITライセンスの下でライセンスされています。コードに貢献することでフレームワークを改善できます。
PowerShellスクリプトは、すべてのプラットフォームで機能するため、紺碧の.netバックグラウンドからのものである場合、DevOpsが自動化する最も簡単な方法です。しかし、これらのスクリプトも保守可能である必要があることを忘れがちです。このためには、スクリプトを保守可能に保つために、すべてのコーディングガイドライン、テストケース、およびテストカバレッジを実行する必要があります。
ここでは、PesterとPSSCriptAnalyzerおよびReportGeneratorを使用して作成したスクリプトを維持するための簡単な方法を示しました。これを使用すると、テストケースを作成できるだけでなく、ReportUnit.Exeによって提供される美しいHTMLでカバレッジレポートとテストケースの実行ステータスを生成できます。チームアクセス用にビルドサーバーで公開できます。
githubリポジトリからコードをダウンロードしてローカルで実行し、フィードバックを知らせてください。
参考文献
ソース:https ://www.c-sharpcorner.com/article/test-coverage-for-powershell-scripts-with-pester/
1648078260
Si usa un sistema operativo Windows, es probable que haya usado la versión más reciente de Windows PowerShell al menos una vez.
Cada vez que abre PowerShell, recibe un mensaje de texto dentro de la terminal que muestra la versión de la terminal, el enlace para descargar la última versión de PowerShell, etc.
A veces, esto puede ser molesto y es posible que desee eliminar ese texto para que el mensaje nunca vuelva a aparecer. ¡Hay una manera de hacerlo, y en este artículo le mostraré cómo puede eliminar el texto inicial de la terminal de una vez por todas! ✌️
En primer lugar, abra PowerShell. Obtendrá el texto inicial como de costumbre.
Haga clic en el botón desplegable para obtener el menú debajo de él.
Ve a Ajustes .
Obtendrá una interfaz como la siguiente:
Haga clic en Abrir archivo JSON .
El relleno JSON se abrirá en un editor de texto. Para mí, es el Bloc de notas, pero para usted, podría ser VS Code o cualquier otro editor de texto que desee.
Desplácese hacia abajo hasta que encuentre el bloque PowerShell como se muestra a continuación.
Agregar "commandline": "pwsh.exe -nologo",
como a continuación.
El comando debería ser así para el bloque de PowerShell:
Luego guarde el archivo. También puede usar las teclas de método abreviado Ctrl
+ S
para esto.
Haga clic en Guardar .
Cierra todas las pestañas.
¡Reabra la terminal y vea la magia! 🪄
Gracias por leer todo el artículo.
Fuente: https://www.freecodecamp.org/news/how-to-remove-starting-text-from-powershell/
1648078020
Windowsオペレーティングシステムを使用している場合は、最新のWindowsPowerShellを少なくとも1回使用したことがある可能性があります。
PowerShellを開くと、端末のバージョン、最新のPowerShellをダウンロードするためのリンクなどを示すテキストメッセージが端末内に表示されます。
これは煩わしい場合があり、メッセージが二度と表示されないように、そのテキストを削除することをお勧めします。これを行う方法があります。この記事では、ターミナルから開始テキストを完全に削除する方法を紹介します。✌️
まず、PowerShellを開きます。通常どおり開始テキストが表示されます。
ドロップダウンボタンをクリックして、その下のメニューを表示します。
[設定]に移動します。
次のようなインターフェイスが表示されます。
[ JSONファイルを開く]をクリックします。
JSONの塗りつぶしがテキストエディタで開きます。私にとってはメモ帳ですが、あなたにとってはVSCodeやその他のテキストエディタである可能性があります。
以下のようなPowerShellブロックが見つかるまで下にスクロールします。
以下のように追加"commandline": "pwsh.exe -nologo",
します。
PowerShellブロックのコマンドは次のようになります。
次に、ファイルを保存します。Ctrl
+これにもショートカットキーを使用できますS
。
[保存]をクリックします。
すべてのタブを閉じます。
ターミナルを再度開いて、魔法を見てください!🪄
記事全体を読んでいただきありがとうございます。
ソース:https ://www.freecodecamp.org/news/how-to-remove-starting-text-from-powershell/
1648020721
Nếu bạn đang sử dụng hệ điều hành Windows, bạn có thể đã sử dụng Windows PowerShell mới nhất ít nhất một lần.
Bất cứ khi nào bạn mở PowerShell, bạn sẽ nhận được một tin nhắn văn bản bên trong thiết bị đầu cuối hiển thị phiên bản thiết bị đầu cuối, liên kết tải xuống PowerShell mới nhất, v.v.
Đôi khi điều này có thể gây khó chịu và bạn có thể muốn xóa văn bản đó để thông báo đó không bao giờ xuất hiện nữa. Có một cách để làm điều đó và trong bài viết này tôi sẽ chỉ cho bạn cách bạn có thể xóa văn bản bắt đầu khỏi terminal một lần và mãi mãi! ✌️
Đầu tiên, hãy mở PowerShell. Bạn sẽ nhận được văn bản bắt đầu như bình thường.
Nhấp vào nút thả xuống để xem menu bên dưới.
Đi tới Cài đặt .
Bạn sẽ nhận được một giao diện như dưới đây:
Nhấp vào Mở tệp JSON .
Phần điền JSON sẽ được mở trong trình soạn thảo văn bản. Đối với tôi, đó là Notepad - nhưng đối với bạn, nó có thể là VS Code hoặc bất kỳ trình soạn thảo văn bản nào khác mà bạn muốn.
Cuộn xuống cho đến khi bạn tìm thấy khối PowerShell như bên dưới.
Thêm "commandline": "pwsh.exe -nologo",
như bên dưới.
Lệnh sẽ giống như thế này đối với khối PowerShell:
Sau đó, lưu tệp. Bạn cũng có thể sử dụng phím tắt Ctrl
+ S
cho việc này.
Nhấp vào Lưu .
Đóng tất cả các tab.
Mở lại thiết bị đầu cuối và xem điều kỳ diệu! 🪄
Cảm ơn vì đã đọc toàn bộ bài báo. Nếu nó hữu ích cho bạn thì bạn cũng có thể xem các bài viết khác của tôi tại freeCodeCamp .
Nguồn: https://www.freecodecamp.org/news/how-to-remove-starting-text-from-powershell/
1648010641
Si vous utilisez un système d'exploitation Windows, vous avez probablement utilisé la dernière version de Windows PowerShell au moins une fois.
Chaque fois que vous ouvrez le PowerShell, vous recevez un message texte à l'intérieur du terminal qui indique la version du terminal, le lien pour télécharger le dernier PowerShell, etc.
Parfois, cela peut être ennuyeux et vous voudrez peut-être supprimer ce texte afin que le message n'apparaisse plus jamais. Il existe un moyen de le faire, et dans cet article, je vais vous montrer comment vous pouvez supprimer le texte de départ du terminal une fois pour toutes ! ✌️
Tout d'abord, ouvrez le PowerShell. Vous obtiendrez le texte de départ comme d'habitude.
Cliquez sur le bouton déroulant pour obtenir le menu en dessous.
Allez dans Paramètres .
Vous obtiendrez une interface comme ci-dessous :
Cliquez sur Ouvrir le fichier JSON .
Le remplissage JSON sera ouvert dans un éditeur de texte. Pour moi, c'est le Bloc-notes - mais pour vous, il peut s'agir de VS Code ou de tout autre éditeur de texte de votre choix.
Faites défiler vers le bas jusqu'à ce que vous trouviez le bloc PowerShell comme ci-dessous.
Ajouter "commandline": "pwsh.exe -nologo",
comme ci-dessous.
La commande devrait ressembler à ceci pour le bloc PowerShell :
Enregistrez ensuite le fichier. Vous pouvez également utiliser les touches de raccourci Ctrl
+ S
pour cela.
Cliquez sur Enregistrer .
Fermez tous les onglets.
Rouvrez le terminal et voyez la magie ! 🪄
Merci d'avoir lu tout l'article. Si cela vous aide, vous pouvez également consulter mes autres articles sur freeCodeCamp .
Link: https://www.freecodecamp.org/news/how-to-remove-starting-text-from-powershell/
1644467236
The Azure PowerShell module is used to create and manage Azure resources from the PowerShell command line or in scripts. This quickstart shows you how to use the Azure PowerShell module to deploy a Linux virtual machine (VM) in Azure. This quickstart uses the Ubuntu 18.04 LTS marketplace image from Canonical. To see your VM in action, you'll also SSH to the VM and install the NGINX web server.
1642681740
Azure Pipelines | GitHub Actions | Documentation | PS Gallery | License |
---|---|---|---|---|
[![Azure Pipelines Build Status][azure-pipeline-badge]][azure-pipeline-build] | [![GitHub Actions Status][github-actions-badge]][github-actions-build] | [![Documentation Status][docs-badge]][docs] | [![PowerShell Gallery][psgallery-badge]][psgallery] | [![License][license-badge]][license] |
PoshBot is a chat bot written in PowerShell. It makes extensive use of classes introduced in PowerShell 5.0. PowerShell modules are loaded into PoshBot and instantly become available as bot commands. PoshBot currently supports connecting to Slack to provide you with awesome ChatOps goodness.
Pretty much anything you want :) No seriously. PoshBot executes functions or cmdlets from PowerShell modules. Use PoshBot to connect to servers and report status, deploy code, execute runbooks, query APIs, etc. If you can write it in PowerShell, PoshBot can execute it.
Detailed documentation can be found at ReadTheDocs.
See Building PoshBot for documentation on how to build PoshBot from source.
Detailed changes for each release are documented in the release notes.
To get started now, get a SLACK-API-TOKEN for your bot:
https://my.slack.com/services/new/bot
# Install the module from PSGallery
Install-Module -Name PoshBot -Repository PSGallery
# Import the module
Import-Module -Name PoshBot
# Create a bot configuration
$botParams = @{
Name = 'name'
BotAdmins = @('<SLACK-CHAT-HANDLE>')
CommandPrefix = '!'
LogLevel = 'Info'
BackendConfiguration = @{
Name = 'SlackBackend'
Token = '<SLACK-API-TOKEN>'
}
AlternateCommandPrefixes = 'bender', 'hal'
}
$myBotConfig = New-PoshBotConfiguration @botParams
# Start a new instance of PoshBot interactively or in a job.
Start-PoshBot -Configuration $myBotConfig #-AsJob
Basic usage:
# Create a Slack backend
$backendConfig = @{Name = 'SlackBackend'; Token = '<SLACK-API-TOKEN>'}
$backend = New-PoshBotSlackBackend -Configuration $backendConfig
# Create a PoshBot configuration
$pbc = New-PoshBotConfiguration -BotAdmins @('<MY-SLACK-HANDLE>') -BackendConfiguration $backendConfig
# Save configuration
Save-PoshBotConfiguration -InputObject $pbc -Path .\PoshBotConfig.psd1
# Load configuration
$pbc = Get-PoshBotConfiguration -Path .\PoshBotConfig.psd1
# Create an instance of the bot
$bot = New-PoshBotInstance -Configuration $pbc -Backend $backend
# Start the bot
$bot.Start()
# Available commands
Get-Command -Module PoshBot
CommandType Name Version Source
----------- ---- ------- ------
Function Get-PoshBot 0.12.0 poshbot
Function Get-PoshBotConfiguration 0.12.0 poshbot
Function Get-PoshBotStatefulData 0.12.0 poshbot
Function New-PoshBotCardResponse 0.12.0 poshbot
Function New-PoshBotConfiguration 0.12.0 poshbot
Function New-PoshBotDiscordBackend 0.12.0 poshbot
Function New-PoshBotFileUpload 0.12.0 poshbot
Function New-PoshBotInstance 0.12.0 poshbot
Function New-PoshBotMiddlewareHook 0.12.0 poshbot
Function New-PoshBotScheduledTask 0.12.0 poshbot
Function New-PoshBotSlackBackend 0.12.0 poshbot
Function New-PoshBotTeamsBackend 0.12.0 poshbot
Function New-PoshBotTextResponse 0.12.0 poshbot
Function Remove-PoshBotStatefulData 0.12.0 poshbot
Function Save-PoshBotConfiguration 0.12.0 poshbot
Function Set-PoshBotStatefulData 0.12.0 poshbot
Function Start-PoshBot 0.12.0 poshbot
Function Stop-Poshbot 0.12.0 poshbot
Download Details:
Author: poshbotio
Source Code: https://github.com/poshbotio/PoshBot
License: MIT License