Docker powershell Install-Module partially added module functions of Microsoft graph - docker

I was trying to build my own custom docker image with azure-powershell docker base image. As an additional feature i need to add Microsoft Graph modules (specially https://www.powershellgallery.com/packages/Microsoft.Graph.Identity.SignIns/1.10.0) in to the docker image. below are some code that i have written to achieve it.
Dockerfile
FROM mcr.microsoft.com/powershell:ubuntu-22.04
RUN pwsh -Command Set-PSRepository -Name PSGallery -InstallationPolicy Trusted && \
pwsh -Command Install-Module -Name Microsoft.Graph.Identity.SignIns -Scope AllUsers -Repository PSGallery && \
pwsh -Command Set-PSRepository -Name PSGallery -InstallationPolicy Untrusted
ADD deployment/powershell/Main.ps1 Main.ps1
CMD ["pwsh", "-File", "Main.ps1"]
Main.ps1
Update-MgPolicyB2CAuthenticationMethodPolicy
Modules path:
ERROR
Line |
32 | Update-MgPolicyB2CAuthenticationMethodPolicy
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| The term 'Update-MgPolicyB2CAuthenticationMethodPolicy' is not
| recognized as a name of a cmdlet, function, script file, or
| executable program. Check the spelling of the name, or if a
| path was included, verify that the path is correct and try
| again.
Info
powershell version: 7.2.5
Find-Module log
Name : Microsoft.Graph.Identity.SignIns
Path : /usr/local/share/powershell/Modules/Microsoft.Graph.Identit
y.SignIns/1.10.0/Microsoft.Graph.Identity.SignIns.psd1
Description : Microsoft Graph PowerShell Cmdlets
Guid : 60f889fa-f873-43ad-b7d3-b7fc1273a44f
Version : 1.10.0
ModuleBase : /usr/local/share/powershell/Modules/Microsoft.Graph.Identit
y.SignIns/1.10.0
ModuleType : Script
PrivateData : {PSData, Profiles}
AccessMode : ReadWrite
ExportedAliases : {}
ExportedCmdlets : {}
ExportedFunctions : {[Confirm-MgInformationProtectionSignature,
Confirm-MgInformationProtectionSignature],
[Confirm-MgRiskyServicePrincipalCompromised,
Confirm-MgRiskyServicePrincipalCompromised],
[Confirm-MgRiskyUserCompromised,
Confirm-MgRiskyUserCompromised],
[Get-MgDataPolicyOperation, Get-MgDataPolicyOperation]…}
ExportedVariables : {}
NestedModules : {}
Question
According to Microsoft.Graph.Identity.SignIns there are many functions present some of the functions worked fine some are not like above. There is no deprecation information given in the docs. What is the main reason for this partial load ?
enter image description here

those commands are available in MS graph powershell beta. so
You need to install the Microsoft.Graph.Beta cmdlets - https://github.com/microsoftgraph/msgraph-sdk-powershell/tree/master

Related

Terraform - Azure - azurerm_virtual_machine_extension - multiline Powershell script

I am preparing VM deployment, and on VMs I need to run some powershell command lets. I need to install Windows Server role, and initialize new ssd disk. I am working on Azure cloud, Terraform deployment has been tested, works as expected, VM is deployed with all required configuration, but facing some problems during multiline powershell commands. I use terraform resource azurerm_virtual_machine_extension, it works when I am trying to install/use one block of code, for example for Windows server role installation. I don't want to use storage account and container and .ps1 script file uploaded to storage container, I need to use inline powershell code. My terraform clode below.
resource "azurerm_virtual_machine_extension" "vmext" {
name = "vmext"
virtual_machine_id = azurerm_windows_virtual_machine.app_vm.id
publisher = "Microsoft.Compute"
type = "CustomScriptExtension"
type_handler_version = "1.10"
settings = <<SETTINGS
{
"commandToExecute": "powershell -ExecutionPolicy Unrestricted Install-windowsfeature -name RoleName -IncludeManagementTools; powershell -ExecutionPolicy Unrestricted Get-Disk | Where-Object -FilterScript {$_.PartitionStyle -eq 'RAW'} | Initialize-Disk -PartitionStyle MBR -PassThru | New-Partition -AssignDriveLetter -UseMaximumSize | Format-Volume -FileSystem NTFS -NewFileSystemLabel 'disk2' -Confirm:$false"
}
SETTINGS
}
Try this:
resource "azurerm_virtual_machine_extension" "vmext" {
name = "vmext"
virtual_machine_id = azurerm_windows_virtual_machine.app_vm.id
publisher = "Microsoft.Compute"
type = "CustomScriptExtension"
type_handler_version = "1.10"
settings = <<SETTINGS
{
"commandToExecute": <<EOF
powershell -ExecutionPolicy Unrestricted Install-windowsfeature -name RoleName -IncludeManagementTools
powershell -ExecutionPolicy Unrestricted Get-Disk | Where-Object -FilterScript {$_.PartitionStyle -eq 'RAW'} | Initialize-Disk -PartitionStyle MBR -PassThru | New-Partition -AssignDriveLetter -UseMaximumSize | Format-Volume -FileSystem NTFS -NewFileSystemLabel 'disk2' -Confirm:$false"
EOF
}
SETTINGS
}
Hope this helps!

Get-PSRepository, powershell warning: "Unable to find module repositories" while trying to install Docker in WindowsServer2016

I want to install Docker and so I tried the below command which gave an error
PS C:\Windows\system32> Install-Module -Name DockerMsftProvider
PackageManagement\Install-Package : No match was found for the specified search criteria and module name 'DockerMsftProvider'. Try Get-PSRepository to see all available registered module repositories.
At C:\Program Files\ WindowsPowerShell\ Modules\ PowerShellGet\ 1.0.0.1\ PSModule .psm1:1772 char:21 $null = PackageManagement\Install-Package #PSBoundParameters CategoryInfo : ObjectNotFound: (Microsoft.Power....InstallPackage:InstallPackage) [Install-Package], Exception + FullyQualifiedErrorId : NoMatchFoundForCriteria, Microsoft.PowerShell.PackageManagement.Cmdlets.InstallPackage
even Install-Module -Name DockerMsftProvider -Repository PSGallery -Force gave the same error.
I tried the below resources and still its the same. I am not able to register a PSRepository. Only when this is installed I can install Docker in Windows Server. I spent hours to solve this still at 0% progress. Registering the PSRepository (Register-PSRepository -Default -InstallationPolicy Trusted) went fine without any errors but still its not visible.
Any possible help to solve this?
https://copdips.com/2018/05/setting-up-powershell-gallery-and-nuget-gallery-for-powershell.html
WARNING: Unable to find module repositories
Unable to find module providers
https://www.powershellgallery.com/packages/PowerShellGet/2.2.1
https://learn.microsoft.com/en-us/virtualization/windowscontainers/quick-start/set-up-environment?tabs=Windows-Server#prerequisites
Try running this, do you still get an error?
[System.Net.WebRequest]::DefaultWebProxy = [System.Net.WebRequest]::GetSystemWebProxy()
[System.Net.WebRequest]::DefaultWebProxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
Install-Module -Name DockerMsftProvider -Scope AllUsers

How to install Powershell Core in aspnet Nanoserver docker container?

Is it possible somehow to add Powershell Core to the AspNet Nano Server base images?
We use a multistage dockerfile to produce an image containing our .net core web application. The final image is based on mcr.microsoft.com/dotnet/core/aspnet:3.1-nanoserver-1809 with our .net core binaries added (in order to keep image size to a minimum).
We would like Powershell Core to be included in the final image, for initialization and debugging purposes, but haven't found a way so far. We have considered all sorts of commandline installation options (msiexec, choco and googled a lot) without finding a solution.
Any help is very much appreciated!
From Microsoft:
PowerShell Core, .NET Core, and WMI are no longer included by default, but you can include PowerShell Core and .NET Core container packages when building your container.
Although there is no official powershell core support for aspnet:3.1-nanoserver-1809, there is an official powershell core support for pure nanoserver-18.09, see this with the image tag: lts-nanoserver-1809
So, the last thing you need to do is:
Just follow microsoft's suggestion to include powershell core when build your own image.
Next is the Dockerfile about how nanoserver-18.09 to include powershell core, you could copy this to write your own dockerfile to add powershell core to your aspnet:3.1-nanoserver-1809:
# escape=`
# Args used by from statements must be defined here:
ARG InstallerVersion=nanoserver
ARG InstallerRepo=mcr.microsoft.com/powershell
ARG NanoServerRepo=mcr.microsoft.com/windows/nanoserver
# Use server core as an installer container to extract PowerShell,
# As this is a multi-stage build, this stage will eventually be thrown away
FROM ${InstallerRepo}:$InstallerVersion AS installer-env
# Arguments for installing PowerShell, must be defined in the container they are used
ARG PS_VERSION=7.0.0-rc.1
ARG PS_PACKAGE_URL=https://github.com/PowerShell/PowerShell/releases/download/v$PS_VERSION/PowerShell-$PS_VERSION-win-x64.zip
# disable telemetry
ENV POWERSHELL_TELEMETRY_OPTOUT="1"
SHELL ["pwsh", "-Command", "$ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue';"]
ARG PS_PACKAGE_URL_BASE64
RUN Write-host "Verifying valid Version..."; `
if (!($env:PS_VERSION -match '^\d+\.\d+\.\d+(-\w+(\.\d+)?)?$' )) { `
throw ('PS_Version ({0}) must match the regex "^\d+\.\d+\.\d+(-\w+(\.\d+)?)?$"' -f $env:PS_VERSION) `
} `
$ProgressPreference = 'SilentlyContinue'; `
if($env:PS_PACKAGE_URL_BASE64){ `
Write-host "decoding: $env:PS_PACKAGE_URL_BASE64" ;`
$url = [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String($env:PS_PACKAGE_URL_BASE64)) `
} else { `
Write-host "using url: $env:PS_PACKAGE_URL" ;`
$url = $env:PS_PACKAGE_URL `
} `
Write-host "downloading: $url"; `
[Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12; `
New-Item -ItemType Directory /installer > $null ; `
Invoke-WebRequest -Uri $url -outfile /installer/powershell.zip -verbose; `
Expand-Archive /installer/powershell.zip -DestinationPath \PowerShell
# Install PowerShell into NanoServer
FROM ${NanoServerRepo}:1809
ARG IMAGE_NAME=mcr.microsoft.com/powershell
# Copy PowerShell Core from the installer container
ENV ProgramFiles="C:\Program Files" `
# set a fixed location for the Module analysis cache
PSModuleAnalysisCachePath="C:\Users\Public\AppData\Local\Microsoft\Windows\PowerShell\docker\ModuleAnalysisCache" `
# Persist %PSCORE% ENV variable for user convenience
PSCORE="$ProgramFiles\PowerShell\pwsh.exe" `
# Set the default windows path so we can use it
WindowsPATH="C:\Windows\system32;C:\Windows" `
POWERSHELL_DISTRIBUTION_CHANNEL="PSDocker-NanoServer-1809"
### Begin workaround ###
# Note that changing user on nanoserver is not recommended
# See, https://learn.microsoft.com/en-us/virtualization/windowscontainers/manage-containers/container-base-images#base-image-differences
# But we are working around a bug introduced in the nanoserver image introduced in 1809
# Without this, PowerShell Direct will fail
# this command sholud be like this: https://github.com/PowerShell/PowerShell-Docker/blob/f81009c42c96af46aef81eb1515efae0ef29ad5f/release/preview/nanoserver/docker/Dockerfile#L76
USER ContainerAdministrator
# This is basically the correct code except for the /M
RUN setx PATH "%PATH%;%ProgramFiles%\PowerShell;" /M
USER ContainerUser
### End workaround ###
COPY --from=installer-env ["\\PowerShell\\", "$ProgramFiles\\PowerShell"]
# intialize powershell module cache
RUN pwsh `
-NoLogo `
-NoProfile `
-Command " `
$stopTime = (get-date).AddMinutes(15); `
$ErrorActionPreference = 'Stop' ; `
$ProgressPreference = 'SilentlyContinue' ; `
while(!(Test-Path -Path $env:PSModuleAnalysisCachePath)) { `
Write-Host "'Waiting for $env:PSModuleAnalysisCachePath'" ; `
if((get-date) -gt $stopTime) { throw 'timout expired'} `
Start-Sleep -Seconds 6 ; `
}"
# re-enable telemetry
ENV POWERSHELL_TELEMETRY_OPTOUT="0"
CMD ["pwsh.exe"]

cannot execute RUN mkdir in a Dockerfile with space in directory name

I want to create a file in C drive while building docker image and using command as below
RUN mkdir "C:\Program Files\Microsoft Passport RPS"
but it throws error:
Step 6/6 : RUN mkdir "C:\Program Files\Microsoft Passport RPS"
---> Running in ab58c6f2948d
[91mmkdir : A positional parameter cannot be found that accepts argument 'Files\Microsoft'.
At line:1 char:76
+ ... e = 'SilentlyContinue'; mkdir C:\Program Files\Microsoft Passport RPS
[0m[91m+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[0m[91m + CategoryInfo : InvalidArgument: (:) [mkdir], ParentContainsErro
[0m[91m rRecordException
+ FullyQualifiedErrorId : PositionalParameterNotFound,mkdir
Tried above command with forward as well as back slash.
I have tried multiple other command as below:
ENV PATH_WITH_SPACE "C:/Program Files/Microsoft Passport RPS"
RUN mkdir $[PATH_WITH_SPACE]
RUN mkdir ["C:\Program Files\Microsoft Passport RPS"]
Can you please help me with appropriate command?
Came across same problem. None of the answers worked for me.
I finally got it working by escaping space with `
RUN mkdir "C:\Program` Files\Microsoft` Passport` RPS"
COPY . "C:\Program` Files\Microsoft` Passport` RPS"
Another approach is to use Shell, and declare escape explictly
While the JSON form is unambiguous and does not use the un-necessary cmd.exe, it does require more verbosity through double-quoting and escaping. The alternate mechanism is to use the SHELL instruction and the shell form, making a more natural syntax for Windows users, especially when combined with the escape parser directive
# escape=`
FROM microsoft/nanoserver
SHELL ["powershell","-command"]
RUN New-Item -ItemType Directory C:\Example
ADD Execute-MyCmdlet.ps1 c:\example\
RUN c:\example\Execute-MyCmdlet -sample 'hello world'
You have to escape the space, some like:
RUN mkdir "C:\Program Files\Microsoft\ Passport\ RPS"
Or using the JSON format:
RUN ["mkdir", "C:\\Program Files\\Microsoft\ Passport\ RPS"]
note: using JSON format is necessary to escape backslashes. This is particularly relevant on Windows where the backslash is the path separator.
We can use PowerShell command to create folder with spaces.
Try this:
RUN powershell -Command New-Item -Path 'C:\Program Files\Microsoft Passport RPS' -ItemType Directory
It Works !!!

Search in/for text in files

I am currently learning LPTHW Ex 46. In his video tutorial, Zed had done the following commands:
Find NAME within files using grep -r "NAME" *.
Find all files with extension ending in .pyc using find . -name "*pyc" -print.
Unfortunately, the above code does not work on Windows PowerShell. May I know what their Windows PowerShell equivalents are?
Based on my search, item 1 can be replaced by Select-String. However, it is not as good as we can only search specific files and not directories. For example, while this would work:
Select-String C:\Users\KMF\Exercises\Projects\gesso\gesso\acrylic.py -pattern "NAME"
this would not:
Select-String C:\Users\KMF\Exercises\Projects\gesso -Pattern "NAME"
and it gives the following error
Select-String : The file C:\Users\KMF\Exercises\Projects\gesso can not be read: Access to the path 'C:\Users\KMF\Exercises\Projects\gesso' is denied.
For item 2 I could not find a similar function.
grep and find are Unix/Linux shell commands. They won't work in PowerShell unless you install a Windows port of them.
As you already found out, Select-String is the PowerShell equivalent for grep. It doesn't recurse by itself, though, so you have to combine it with Get-ChildItem to emulate grep -r:
Get-ChildItem -Recurse | Select-String -Pattern 'NAME'
For emulating find you'd combine Get-ChildItem with a Where-Object filter:
Get-ChildItem -Recurse | Where-Object { $_.Extension -eq '.pyc' }
PowerShell cmdlets can be aliased to help administrators avoid extensive typing (since PowerShell statements tend to be rather verbose). There are several built-in aliases, e.g. ls or dir for Get-ChildItem, and ? or where for Where-Object. You can also define aliases of your own, e.g. New-Alias -Name grep -Value Select-String. Parameter names can be shortened as long as the truncated parameter name remains unique for the cmdlet. When cmdlets allow positional parameters they can even be omitted entirely.
With all of the above your two PowerShell statements can be reduced to the following:
ls -r | grep 'NAME'
ls -r | ? { $_.Extension -eq '.pyc' }
Note however, that aliases and abbreviations are mainly intended as an enhancement for console use. For PowerShell scripts you should always use the full form, not only for readability, but also because aliases may differ from environment to environment. You don't want your scripts to break just because they're run by someone else.

Resources