Desmond  Gerber

Desmond Gerber


Clean Node_modules with PowerShell

Clean Node_modules with PowerShell

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:

#powershell #node #modules 

Clean Node_modules with PowerShell
Monty  Boehm

Monty Boehm


Fix for PowerShell Script Not Digitally Signed


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

The File PS1 Cannot Be Run Because The File Is Not Digitally Signed


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

The File PS1 Cannot Be Run Because The File Is Not Digitally Signed

After running this command, you should be able to run the unsigned PowerShell scripts for this user.

Original article source at:

#powershell #digital 

Fix for PowerShell Script Not Digitally Signed

How to Easily Unzip Multiple Zips using PowerShell

Problem: Unzip mulitple files in one go.


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.

      [-Path] <String>
      [[-DestinationPath] <String>]


  1. Save the commands mentioned in ps1 file: myscript.ps1
  2. Open windows PowerShell and run the script file: .\myscript.ps1

If this fails, then set the execution policy to unrestricted for this session and try again.


If you are using a windows machine and need a quick way to unzip files, then go with expand-archive.



Original article source at:

#powershell #zip 

How to Easily Unzip Multiple Zips using PowerShell
Desmond  Gerber

Desmond Gerber


How to Find List Of Inactive Users in Microsoft 365 Using PowerShell

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
            sleep 10
            GetLastSignInDate $upn
    finally {
        $AllUsers | Out-File "c:\LastLogin.csv" -Append
Import-Module AzureADPreview
$Result = ""
$output = ""
$filter = ""

#Connect to Azure AD
$user = ""
$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:

#powershell #microsoft 

How to Find List Of Inactive Users in Microsoft 365 Using PowerShell

Install PowerShell Modules In Offline Mode


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".

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.


  • PowerShell version 5.1 or newer

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”

How to install PowerShell modules in offline mode

Step 2

Download and save module to local folder path using Save-Module command.

Save-Module –Name “module name” –Path “local folder path”

How to install PowerShell modules in offline mode

Downloaded module to the specified location:

How to install PowerShell modules in offline mode

Step 3

Now copy the downloaded module to C:\Program Files\WindowsPowerShell\Modules path.

How to install PowerShell modules in offline mode

Step 4

Offline installation is complete, now you can validate if this module is available.

Get-Module -ListAvailable “module name”

How to install PowerShell modules in offline mode

Step 5

We can get list of available commands for installed modules.

Get-Command -Module “module name”

How to install PowerShell modules in offline mode


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:

#powershell #installs 

Install PowerShell Modules In Offline Mode
Jammie  Yost

Jammie Yost


Docker PowerShell: PowerShell Module for Docker


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!

Development Builds

build status

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 To install the latest build, in PowerShell 5.0 run:

> Register-PSRepository -Name DockerPS-Dev -SourceLocation

> 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

Linux and Mac OS X

As of the v6.0.0-alpha.10 release of PowerShell, the instructions listed above for development builds work as expected on Linux.

Need an offline workflow?

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 with any additional questions or comments.


Before Compiling: Git submodules for Docker.DotNet

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.

Compiling with DotNet CLI

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.

Updating Help Markdown Files

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.

Visual Studio Code

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.

Download Details:

Author: Microsoft
Source code:

License: MIT license
#docker #powershell 

Docker PowerShell: PowerShell Module for Docker
Nat  Grady

Nat Grady


A Fully Dockerized, Self-hosted Development Environment for Teams


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:

  • a secured, collaborative development environment for R, Python, PowerShell, and more.
  • a secured, convenient way to share apps and documents written in Shiny, RMarkdown, plain Markdown, or HTML.
  • easily reproducible, cross-platform setup leveraging Docker for all components.

There are two distributions of ShinyStudio, the image and the stack, explained below.

ShinyStudio Image

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.

Get Started with the Image


ShinyStudio Stack

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.

Get Started with the Stack

Getting Started

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:

  • Bash (Linux/Mac)
docker run -d --restart always --name shinyproxy \
    --network shinystudio-net \
    -v /var/run/docker.sock:/var/run/docker.sock \
    -e USER=$USER \
    -e PASSWORD=password \
    -e CONTENT_PATH="${HOME}/ShinyStudio" \
    -e SITE_NAME=shinystudio \
    -p 8080:8080 \
  • PowerShell (Windows)
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 `

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.ps1 for Windows) to create a self-signed certificate, or to request one from LetsEncrypt (more on that).

Minimal setup:

# copy the setup files.
git clone

# enter the directory.
cd ShinyStudio

# run certify to generate self-signed cert.

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.


Customized setup:

There are three files essential to a customized configuration:


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.


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:

  • readers: can only view content from “Apps & Reports”, “Documents”, and “Personal”.
  • admins: can view all site content and develop content with RStudio and VS Code.
  • superadmins: can view and develop site content across multiple instances of ShinyStudio. Can also manage all user files.

Review the ShinyProxy configuration documentation for all options.


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.


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 (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:

./ <domain name>

# e.g., ./

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:

./ <domain name> <email>

# e.g., ./

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:

  • __ShinyStudio__
  • __Personal__

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…

  • R
  • Python 3
  • PowerShell

…and ODBC drivers for:

  • SQL Server
  • PostgresSQL
  • Cloudera Impala.

These are persistent because they are built into the image.

__ShinyStudio__ directoryYes
__Personal__ directoryYes
Other directoriesNo
R LibrariesYes
Python PackagesYes
PowerShell ModulesYes
RStudio User SettingsYes
VS Code User SettingsYes
Installed AppsNo
Installed DriversNo


Download Details:

Author: fresh2dev
Source Code: 
License: MIT license

#r #docker #powershell #rstudio #vscode 

A Fully Dockerized, Self-hosted Development Environment for Teams

Cobertura De Prueba Para Scripts De PowerShell Con Pester

Antes de comenzar, el código completo utilizado para este artículo está disponible aquí:

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.

Potencia Shell

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.

Shell de línea de comandos

El caparazón incluye las siguientes características:

  1. Sólido historial de línea de comandos
  2. Predicción de finalización de pestañas y comandos (Ver about_PSReadLine)
  3. Admite alias de comandos y parámetros
  4. Pipeline para encadenar comandos
  5. Sistema de ayuda en la consola, similar a las páginas man de Unix

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

Plataforma de automatización

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:


    Azure Windows Exchange SQL


    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.

¿Qué es Pester?

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


Puede leer más sobre cómo escribir casos de prueba de secuencias de comandos de powershell usando pester aquí:

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 para análisis de secuencias de comandos estáticas

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í:

Ahora la Carne!!!!!!!!

Generación del informe

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"


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 :

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.




 #powershell  #pester 

Cobertura De Prueba Para Scripts De PowerShell Con Pester









  1. 堅牢なコマンドライン履歴
  2. タブ補完とコマンド予測(about_PSReadLineを参照)
  3. コマンドおよびパラメーターのエイリアスをサポート
  4. コマンドを連鎖させるためのパイプライン
  5. Unixのマニュアルページに似たコンソール内のヘルプシステム



Set-ExecutionPolicy Unrestricted




    Azure Windows Exchange SQL


    AWS VMWare Google Cloud









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: //をご覧ください。










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"







GitHubhttps ://








ソース:https ://

#powershell  #pester 


Cómo Quitar El Texto De Inicio De PowerShell

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.

Captura de pantalla--3--1

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.

Captura de pantalla--3--2

Haga clic en el botón desplegable para obtener el menú debajo de él.

Captura de pantalla--4-

Ve a Ajustes .

Captura de pantalla--5-

Obtendrá una interfaz como la siguiente:

Captura de pantalla--6-

Haga clic en Abrir archivo JSON .

Captura de pantalla--7-

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.

Captura de pantalla--9-

Desplácese hacia abajo hasta que encuentre el bloque PowerShell como se muestra a continuación.

Captura de pantalla--12-

Agregar "commandline": "pwsh.exe -nologo",como a continuación.

Captura de pantalla--14--1

El comando debería ser así para el bloque de PowerShell:

Captura de pantalla--15-

Luego guarde el archivo. También puede usar las teclas de método abreviado Ctrl+ Spara esto.

Haga clic en Guardar .

Captura de pantalla--16-

Cierra todas las pestañas.

Captura de pantalla--17--1

¡Reabra la terminal y vea la magia! 🪄

Captura de pantalla--19--1


Gracias por leer todo el artículo.



Cómo Quitar El Texto De Inicio De PowerShell
藤本  結衣

藤本 結衣















[ JSONファイルを開く]をクリックします。






以下のように追加"commandline": "pwsh.exe -nologo",します。













ソース:https :// 


Thai  Son

Thai Son


Cách Xóa Văn Bản Bắt Đầu Khỏi PowerShell

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.

Ảnh chụp màn hình - 3--1

Đô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 chụp màn hình - 3--2

Nhấp vào nút thả xuống để xem menu bên dưới.

Ảnh chụp màn hình - 4-

Đi tới Cài đặt .

Ảnh chụp màn hình - 5-

Bạn sẽ nhận được một giao diện như dưới đây:

Ảnh chụp màn hình - 6-

Nhấp vào Mở tệp JSON .

Ảnh chụp màn hình - 7-

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.

Ảnh chụp màn hình - 9-

Cuộn xuống cho đến khi bạn tìm thấy khối PowerShell như bên dưới.

Ảnh chụp màn hình - 12-

Thêm "commandline": "pwsh.exe -nologo",như bên dưới.

Ảnh chụp màn hình - 14--1

Lệnh sẽ giống như thế này đối với khối PowerShell:

Ảnh chụp màn hình - 15-

Sau đó, lưu tệp. Bạn cũng có thể sử dụng phím tắt Ctrl+ Scho việc này.

Nhấp vào Lưu .

Ảnh chụp màn hình - 16-

Đóng tất cả các tab.

Ảnh chụp màn hình - 17--1

Mở lại thiết bị đầu cuối và xem điều kỳ diệu! 🪄

Ảnh chụp màn hình - 19--1

Phần kết luận

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 .



Cách Xóa Văn Bản Bắt Đầu Khỏi PowerShell

Comment Supprimer Le Texte De Démarrage De PowerShell

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.

Capture d'écran--3--1

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.

Capture d'écran--3--2

Cliquez sur le bouton déroulant pour obtenir le menu en dessous.

Capture d'écran--4-

Allez dans Paramètres .

Capture d'écran--5-

Vous obtiendrez une interface comme ci-dessous :

Capture d'écran--6-

Cliquez sur Ouvrir le fichier JSON .

Capture d'écran--7-

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.

Capture d'écran--9-

Faites défiler vers le bas jusqu'à ce que vous trouviez le bloc PowerShell comme ci-dessous.

Capture d'écran--12-

Ajouter "commandline": "pwsh.exe -nologo",comme ci-dessous.

Capture d'écran--14--1

La commande devrait ressembler à ceci pour le bloc PowerShell :

Capture d'écran--15-

Enregistrez ensuite le fichier. Vous pouvez également utiliser les touches de raccourci Ctrl+ Spour cela.

Cliquez sur Enregistrer .

Capture d'écran--16-

Fermez tous les onglets.

Capture d'écran--17--1

Rouvrez le terminal et voyez la magie ! 🪄

Capture d'écran--19--1


Merci d'avoir lu tout l'article. Si cela vous aide, vous pouvez également consulter mes autres articles sur freeCodeCamp .



Comment Supprimer Le Texte De Démarrage De PowerShell

How to Create A Linux Virtual Machine in Azure with PowerShell

How to Create A Linux Virtual Machine in Azure with PowerShell

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.

#linux #azure #powershell 

How to Create A Linux Virtual Machine in Azure with PowerShell

PoshBot: Powershell-based Bot Framework


Azure PipelinesGitHub ActionsDocumentationPS GalleryLicense
[![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.

What Can PoshBot Do?

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.

Building PoshBot

See Building PoshBot for documentation on how to build PoshBot from source.


Detailed changes for each release are documented in the release notes.

[YouTube] PowerShell Summit 2018 - Invoke-ChatOps: Level up and change your culture with chat and PowerShell

Alt text


To get started now, get a SLACK-API-TOKEN for your 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

# 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:
License: MIT License

#chatbot #powershell 

PoshBot: Powershell-based Bot Framework