Is there any PowerShell command to get the details for all Azure VM's that JIT (Just in Times) is assigned or not? - azure

I am working to JIT (Just in time). It should be enabled in all Azure Virtual Machines.
For that, I am retrieving the details to see how many VM's JIT is enabled or disabled.
Is there any script or command to get these details via PowerShell which gives details in Excel?

The command should be Get-AzJitNetworkAccessPolicy
# Sample from microsoft docs
Get-AzJitNetworkAccessPolicy
Id : /subscriptions/487bb485-b5b0-471e-9c0d-10717612f869/resourceGroups/myService1/providers/Microsoft.Security/locations/centralus/jitNetworkAccessPolicies/default
Name : default
Kind : Basic
VirtualMachines : {/subscriptions/487bb485-b5b0-471e-9c0d-10717612f869/resourceGroups/myService1/providers/Microsoft.Compute/virtualMachines/testService}
Requests : {Microsoft.Azure.Commands.Security.Models.JitNetworkAccessPolicies.PSSecurityJitNetworkAccessPolicyRequest}
ProvisioningState : Succeeded
It's part of the Az.Security Module.
The command will show you all Just in Time Policies and the assigned machines (VirtualMachines Property)
Together with Get-AzVM you can create a list of which don't have JIT enabled yet.
Something like this should do the trick:
Import-Module Az.Compute
Import-Module Az.Security
Connect-AzAccount -SubscriptionId "<Id>"
$AzJITPolicies = Get-AzJitNetworkAccessPolicy
$AzVMs = Get-AzVM
$ResultSet = #("VmName;JITEnabled")
foreach($AzVM in $AzVMS) {
# You probably need to filter the rules even further here.
$PolicyExists = $AzJITPolicies | Where-Object { $_.VirtualMachines | Where-Object { $_.Id -eq $AzVm.Id }}
$JITEnabled = $false
if($PolicyExists) {
$JITEnabled = $true
}
$ResultSet += ($AzVM.Name + ";" + $JITEnabled)
}
# export as csv => import in excel
$ResultSet -join "`r`n" | Out-File "c:\result.csv"

Related

Using PowerShell, How to get list of all Azure subscriptions having Azure Data factory Resource in it?

I want to retrieve the list of subscriptions having Azure Data Factory resource in it. I want to use PowerShell and get the subscription list and ADF list.
I have tried Get-AzSubscription, but it does not contain filter for resource type i.e. Microsoft.DataFactory/factories. This filter can be added to only Get-AzResource.
Get-AzSubscription Module
Get-AzResource Module
Ok here you are:
$resType = "Microsoft.DataFactory/factories"
$resTypeName = "DataFactory"
Get-AzSubscription | ForEach-Object {
$subscriptionName = $_.Name
$tenantId = $_.TenantId
Set-AzContext -SubscriptionId $_.SubscriptionId -TenantId $_.TenantId
(Get-AzResource -ResourceType $ResType) | ForEach-Object {
[PSCustomObject] #{
true_sub = $subscriptionName
}
} | get-unique
} | Select-String 'true_sub' | ForEach-Object{ "Found_" + "$resTypeName" + "_In_Subscription= $($subscriptionName)"}
EDIT: Added variables to make it easily reusable for any resource type.
I used the code available here and here to create a custom one based on the requirements. Tested in my environment - it seems to work as expected.
I should disclose that I'm not an advanced PowerShell user, so the code I'm providing could really be sub-optimal.

Azure Powershell Script Force FTPS Set-AzWebApp : Cannot convert 'System.Object[]' to the type 'System.String' required by parameter

I am currently trying to run a script in Azure that would go through all of our Web Apps and turn on FTPS.
This is what I currently have
$Subscriptions = Get-AzSubscription
foreach ($sub in $Subscriptions) {
Get-AzSubscription -SubscriptionName $sub.Name | Set-AzContext
$GetName = (Get-AzWebApp).Name
$GetRG = (Get-AzWebApp).ResourceGroup
Set-AzWebapp -Name $GetName -ResourceGroupName $GetRG -FtpsState FtpsOnly
}
Set-AzWebApp : Cannot convert 'System.Object[]' to the type 'System.String' required by parameter 'Name'. Specified
method is not supported.
I currently am getting this error, which I dont understand as .Name and .ResourceGroup, from my understanding are already strings. I am very new to powershell so any help would be greatly appreciated. Thanks everyone!
Your example calls Az-WebApp with no parameters, which gets all apps in the subscription - this is a collection - and then tries to get the Name of that result, which is what causes your error.
You need to loop through each app in the subscription as well as looping through each subscription, as in:
# Get all subscriptions and iterate them
Get-AzSubscription | ForEach-Object {
Set-AzContext -SubscriptionName $_.Name
# Get all web apps in the subscription and iterate them
Get-AzWebApp | ForEach-Object {
Set-AzWebApp -Name $_.Name -ResourceGroupName $_.ResourceGroup -FtpsState FtpsOnly
}
}

How to detect which version of the Az PowerShell module collection is installed on an Azure DevOps agent?

On Azure DevOps agents there is no Az module collection installed - Get-InstalledModule Az returns $null. But all Az modules are just available - Get-Module Az* -ListAvailable returns them all.
What is the best way to test if a particular version of the Az module collection is available? Unfortunately the Az module itself is not present in the regular module space; it only appears in the list of installed modules if installed: Get-Module Az -ListAvailable always returns $null.
Just to be sure we always test whether a particular minimum version of the Az module collection is installed. And if not, then we install it. As this easily takes a couple of minutes to complete, ideally we only do it when really necessary.
Please check the images of Microsoft-hosted agents, for example, for Windows Server 2019 image, you can get Az PowerShell module from following link:
https://github.com/actions/virtual-environments/blob/master/images/win/Windows2019-Readme.md#az-powershell-module
Screenshot:
We have investigated Microsoft's Azure PowerShell task, as this task's feature is to enable an Az version of choice or choose the latest available. The latter is done by the function Get-LatestModule in Utility.ps1 which can be found here: https://github.com/microsoft/azure-pipelines-tasks/blob/master/Tasks/AzurePowerShellV5/Utility.ps1
Our full logic in the custom task is now capable of finding any installed version when running on a self-hosted agent or picking the latest on the Microsoft agent:
# On our self-hosted agent the Az module is installed
$installedVersion = (Get-InstalledModule -Name 'Az' -AllVersions -ErrorAction SilentlyContinue).Version | Sort-Object -Desc | Select-Object -First 1
if ('2.6.0' -gt $installedVersion) {
# On Microsoft hosted agents the Az module itself is not present, but all the related Az modules are on disk in a specific folder
# This code is taken from Microsoft Azure PowerShell task (https://github.com/microsoft/azure-pipelines-tasks/blob/master/Tasks/AzurePowerShellV5/Utility.ps1)
$hostedAgentAzModulePath = Get-LatestModule -patternToMatch "^az_[0-9]+\.[0-9]+\.[0-9]+$" -patternToExtract "[0-9]+\.[0-9]+\.[0-9]+$"
if (-not $hostedAgentAzModulePath) {
# The hosted Az modules cannot be found. So proceed with installing it from the PowerShell gallery
Write-Information -MessageData "INFO --- Install module 'Az'." -InformationAction Continue
Set-PSRepository -Name 'PSGallery' -InstallationPolicy Trusted
Install-Module -Name 'Az' -AllowClobber -Force -MinimumVersion '2.6.0' -Scope CurrentUser
} else {
# Append the Az modules path to the PowerShell modules path
$env:PSModulePath = $hostedAgentAzModulePath + ";" + $env:PSModulePath
$env:PSModulePath = $env:PSModulePath.TrimStart(';')
}
}
Import-Module -MinimumVersion '2.6.0' -Name 'Az' -Force -Scope 'Global'
Write-Information `
-MessageData "INFO --- Imported Az module version $(Get-Module Az | Select-Object Version | ForEach-Object {$_.Version})." `
-InformationAction Continue
Get-LatestModule copied from Utility.ps1:
function Get-LatestModule {
[CmdletBinding()]
param([string] $patternToMatch,
[string] $patternToExtract)
$resultFolder = ""
$regexToMatch = New-Object -TypeName System.Text.RegularExpressions.Regex -ArgumentList $patternToMatch
$regexToExtract = New-Object -TypeName System.Text.RegularExpressions.Regex -ArgumentList $patternToExtract
$maxVersion = [version] "0.0.0"
$modulePath = $env:SystemDrive + "\Modules";
try {
if (-not (Test-Path -Path $modulePath)) {
return $resultFolder
}
$moduleFolders = Get-ChildItem -Directory -Path $modulePath | Where-Object { $regexToMatch.IsMatch($_.Name) }
foreach ($moduleFolder in $moduleFolders) {
$moduleVersion = [version] $($regexToExtract.Match($moduleFolder.Name).Groups[0].Value)
if($moduleVersion -gt $maxVersion) {
$modulePath = [System.IO.Path]::Combine($moduleFolder.FullName,"Az\$moduleVersion\Az.psm1")
if(Test-Path -LiteralPath $modulePath -PathType Leaf) {
$maxVersion = $moduleVersion
$resultFolder = $moduleFolder.FullName
} else {
Write-Verbose "A folder matching the module folder pattern was found at $($moduleFolder.FullName) but didn't contain a valid module file"
}
}
}
}
catch {
Write-Verbose "Attempting to find the Latest Module Folder failed with the error: $($_.Exception.Message)"
$resultFolder = ""
}
Write-Verbose "Latest module folder detected: $resultFolder"
return $resultFolder
}

Composing a script in Powershell V3

I would like to know how i can create a script using powershell v3 to obtain the names of all the SQL instances. for example Environment 23Dev would have two virtual boxes. ASNAV-DEVSQL-23
and ASNAV-DEVWEB-23. I want to return the info ASNVA-DEVSQL-23 all the way up to Environment 50?
Can anyone assist with this?
Regards,
Joe
here is an example that will list sql instance of SQLSERVER1 and SQLSERVER2 :
"SQLSERVER1","SQLSERVER2" | % {
invoke-command -computername $_ -scriptblock{
"SERVER $env:computername"
(get-itemproperty 'HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server').InstalledInstances
}
}
This one-liner will list all your local instances in the form of a PowerShell object:
[System.Data.Sql.SqlDataSourceEnumerator]::Instance.GetDataSources() | Format-Table -Auto
Taken from: http://tangodude.wordpress.com/2014/02/07/list-local-sql-server-instances-with-powershell/
Edit:
This bit of code should work better than the previous one:
$Current = Get-Location;
Import-Module SQLPS -DisableNameChecking;
Set-Location $Current;
[Microsoft.SqlServer.Management.Smo.SmoApplication]::EnumAvailableSqlServers()
Edit:
This is using WMI to query the services on the target computer.
[Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SqlWmiManagement") | Out-Null;
$MC = New-Object Microsoft.SqlServer.Management.Smo.Wmi.ManagedComputer("COMPUTER_NAME_HERE");
foreach ($Instance in ($MC.Services | Where-Object { $_.Type -Eq "SqlServer" }))
{
Write-Host $Instance.Name;
}

how to operate On List of IIS Application Pools On Remote Server Using Powershell?

I am trying to build powershell program which would:
connect to the remote server
Show number of active IIS app pools on the active server
based on the selection (1,2,3,4,....n etc) it would reset app pool
Can you please give me some tips?
Give this a try:
[Reflection.Assembly]::LoadWithPartialName('Microsoft.Web.Administration')
$sm = [Microsoft.Web.Administration.ServerManager]::OpenRemote('server1')
$sm.ApplicationPools['AppPoolName'].Recycle()
Building upon the answers already given, try the following. It uses powershell remoting, specifically Invoke-Command so you need to familiarise yourself with that.
[cmdletBinding(SupportsShouldProcess=$true,ConfirmImpact="High")]
param
(
[parameter(Mandatory=$true,ValueFromPipeline=$true)]
[string]$ComputerName,
[parameter(Mandatory=$false)]
[System.Management.Automation.PSCredential]$Credential
)
begin
{
if (!($Credential))
{
# Prompt for credentials if not passed in
$Credential = get-credential
}
$scriptBlock = {
Import-Module WebAdministration
# Get all running app pools
$applicationPools = Get-ChildItem IIS:\AppPools | ? {$_.state -eq "Started"}
$i = 0
# Display a basic menu
Write-Host "`nApplication Pools`n"
$applicationPools | % {
"[{0}]`t{1}" -f $i, $($applicationPools[$i].Name)
$i++
}
# Get their choice
$response = Read-Host -Prompt "`nSelect Application Pool to recycle"
# Grab the associated object, which will be null
# if an out of range choice was entered
$appPool = $applicationPools[$response]
if ($appPool)
{
"Recycling '{0}'" -f $appPool.name
$appPool.recycle()
}
}
}
process
{
Invoke-Command -ComputerName $computerName -Credential $credential -ScriptBlock $scriptBlock
}
I cannot help with existing code, but which some links
Check out remote powershell sessions here
Check out the Web Server (IIS) Administration Cmdlets in Windows PowerShell, specialy the Get-WebApplication and Get-WebAppPoolState
If reset means stop, then you could take a look on Stop-WebAppPool

Resources