Showing posts with label Powershell. Show all posts
Showing posts with label Powershell. Show all posts

Saturday, February 12, 2022

Azure VMSS VM Instance Status using powershell - Get-AzureRmVmssVM

 The below powershell script helps you to check the status of VM Instances inside a Virtual Machine Scale Sets. This will check the Status whether the Instance is Running or Deallocated/Stopped as some actions will not be allowed on a deallocated instance while performing on VMSS.


For Instance, I'm checking if the status is Running and then do any operation on the instance.

Get-AzureRmVmssVM -ResourceGroupName $nameprefix  -VMScaleSetName $key | foreach { $Id = $_.InstanceId; $vmssvm = Get-AzureRmVmssVM -ResourceGroupName $nameprefix  -VMScaleSetName $key -InstanceView -InstanceId $_.InstanceId; if($vmssvm.Statuses[$vmssvm.Statuses.Count-1].Code.Contains("running")){ Write-Host "vmid: " $vmssvm.Statuses[$vmssvm.Statuses.Count-1].Code}}






Friday, January 28, 2022

Pass List of users and get Azure AD Signin logs

 Pass List of users and get Azure AD Signin logs. You can loop through AD users in case of no list of users to pass. Note that this gives logs for last 30 days and if you want previous logs then need to get from Security Centre Audit Logs.


Connect-AzureAD

$Headers = "Email`tInteractive`tLastLogon" >><folderpath>\ADUsersSignIns.csv


#$SetDate = (Get-Date).AddDays(-1);

#$SetDate = Get-Date($SetDate) -format yyyy-MM-dd 


foreach($line in Get-Content <folderpath>\ADUsers.txt) 

    {

     $UPN = $line

     try

     {

     #$LoginTime = Get-AzureAdAuditSigninLogs -filter "userprincipalname eq '$UPN' and createdDateTime gt 2022-01-21T00:30:00.0Z" -top 1 | select CreatedDateTime, UserPrincipalName, IsInteractive

     $LoginTime = Get-AzureAdAuditSigninLogs -filter "userprincipalname eq '$UPN'" -top 1 | select CreatedDateTime, UserPrincipalName, IsInteractive

     $NewLine = $UPN + "`t" + $LoginTime.IsInteractive + "`t" + $LoginTime.CreatedDateTime

     $NewLine >><folderpath>\ADUsersSignIns.csv

     }

     catch{

     $NewLine = $UPN + "`t" + "" + "`t" + "Too Many Requests"

     $NewLine >><folderpath>\ADUsersSignIns.csv


     }

    

    }


Monday, December 6, 2021

Powershell script to export certificate from Azure Keyvault

 # Replace these variables with your own values

$vaultName = "<key vault name>"

$certificateName = "<certificate name>"

$pfxPath = "<folder path>\<certname>.pfx"

$password = "<exportpassword>"

 

$cert = Get-AzKeyVaultCertificate -VaultName $vaultName -Name $certificateName

 

$pfxSecret = Get-AzKeyVaultSecret -VaultName $vaultName -Name $cert.Name -AsPlainText

 

 

$pfxUnprotectedBytes = [Convert]::FromBase64String($pfxSecret)

$pfx = New-Object Security.Cryptography.X509Certificates.X509Certificate2Collection

$pfx.Import($pfxUnprotectedBytes, $null, [Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable)

$pfxProtectedBytes = $pfx.Export([Security.Cryptography.X509Certificates.X509ContentType]::Pkcs12, $password)

[IO.File]::WriteAllBytes($pfxPath, $pfxProtectedBytes)


Sunday, October 17, 2021

Powershell to update Azure DevOps pipeline variables automatically during the execution

 

Sometimes we have a scenario to update the devops pipeline variables dynamically during the task execution without having to update manually and create new release. you can use the below approach by adding Powershell task to the pipeline.

# Write your PowerShell commands here.

$cosmosconnstr = "$(cosmosconnstring)"

if("$(cosmosconnstring)".Chars("$(cosmosconnstring)".Length - 1) -eq ';')

{

  $cosmosconnstr = "$(cosmosconnstring)".TrimEnd(';')

}



Write-Output("##vso[task.setvariable variable=ApplicationSettings.CacheConnection;]$cosmosconnstr")


#End


#Run the below script in another stage to make sure you get the updated value

Write-host "CacheConnection Variable in previous task is: $(ApplicationSettings.CacheConnection)"

Friday, June 4, 2021

Restore a search service application to another SharePoint farm

 The below script helps in restoring a search service application to another sharepoint farm. Before running below script, you need to take a back up of existing Search DB's ( with or without crawl db) to the new farms SQL server.


$saAppPoolName = "SearchService_AdminAppPool"


# Search Specifics, we are single server farm

$searchServerName = (Get-ChildItem env:computername).value


#Web Front End servers


$hostA = ""Server1"

$hostB = ""Server2"



#Servers hosting Search Components


$hostD = "Server1"

$hostE = "Server2" #In case of running components on multiple servers.


$IndexLocation = "F:\Apps\SearchIndex"


$serviceAppName = "Search Service Application"

$searchDBName = "Search Admin DB"

# Grab the Appplication Pool for Service Application Endpoint

$saAppPool = Get-SPServiceApplicationPool $saAppPoolName


# Start Search Service Instances

Write-Host "Starting Search Service Instances..."

#Start-SPEnterpriseSearchServiceInstance $searchServerName

#Start-SPEnterpriseSearchQueryAndSiteSettingsServiceInstance $searchServerName


# Create the Search Service Application and Proxy

Write-Host "Creating Search Service Application and Proxy..."

$searchInstance = Get-SPEnterpriseSearchServiceInstance -local

$searchServiceApp = Restore-SPEnterpriseSearchServiceApplication -Name $serviceAppName -ApplicationPool $saAppPoolName -AdminSearchServiceInstance $searchInstance -DatabaseName $searchDBName

$searchProxy = New-SPEnterpriseSearchServiceApplicationProxy -Name "Service Application and Proxy" -SearchApplication $searchServiceApp


# Clone the default Topology (which is empty) and create a new one and then activate it

Write-Host "Configuring Search Component Topology..."

$clone = $searchServiceApp.ActiveTopology.Clone()


#$searchServiceInstance = Get-SPEnterpriseSearchServiceInstance


$searchServiceInstance1 = Get-SPEnterpriseSearchServiceInstance -Identity $hostD

$searchServiceInstance2 = Get-SPEnterpriseSearchServiceInstance -Identity $hostE



#We need only two admin component


New-SPEnterpriseSearchAdminComponent -SearchTopology  $clone -SearchServiceInstance $searchServiceInstance1

New-SPEnterpriseSearchAdminComponent -SearchTopology  $clone -SearchServiceInstance $searchServiceInstance2


#We need two content processing components


New-SPEnterpriseSearchContentProcessingComponent -SearchTopology  $clone -SearchServiceInstance $searchServiceInstance1

#New-SPEnterpriseSearchContentProcessingComponent -SearchTopology $clone -SearchServiceInstance $searchServiceInstance2



#We need two analytics processing components


New-SPEnterpriseSearchAnalyticsProcessingComponent -SearchTopology  $clone -SearchServiceInstance $searchServiceInstance1

#New-SPEnterpriseSearchAnalyticsProcessingComponent -SearchTopology  $clone -SearchServiceInstance $searchServiceInstance2



#We need two crawl components


New-SPEnterpriseSearchCrawlComponent -SearchTopology  $clone -SearchServiceInstance $searchServiceInstance1

#New-SPEnterpriseSearchCrawlComponent -SearchTopology  $clone -SearchServiceInstance $searchServiceInstance2



#We need two query processing components


New-SPEnterpriseSearchQueryProcessingComponent -SearchTopology  $clone -SearchServiceInstance $searchServiceInstance1

New-SPEnterpriseSearchQueryProcessingComponent -SearchTopology  $clone -SearchServiceInstance $searchServiceInstance2



New-SPEnterpriseSearchIndexComponent -SearchTopology $clone -SearchServiceInstance $searchServiceInstance1 -RootDirectory $IndexLocation -IndexPartition 0

New-SPEnterpriseSearchIndexComponent -SearchTopology $clone -SearchServiceInstance $searchServiceInstance2 -RootDirectory $IndexLocation -IndexPartition 0



#New-SPEnterpriseSearchAdminComponent –SearchTopology $clone -SearchServiceInstance $searchServiceInstance

#New-SPEnterpriseSearchContentProcessingComponent –SearchTopology $clone -SearchServiceInstance $searchServiceInstance

#New-SPEnterpriseSearchAnalyticsProcessingComponent –SearchTopology $clone -SearchServiceInstance $searchServiceInstance

#New-SPEnterpriseSearchCrawlComponent –SearchTopology $clone -SearchServiceInstance $searchServiceInstance

#New-SPEnterpriseSearchIndexComponent –SearchTopology $clone -SearchServiceInstance $searchServiceInstance

#New-SPEnterpriseSearchQueryProcessingComponent –SearchTopology $clone -SearchServiceInstance $searchServiceInstance



$clone.Activate()


Get-SPEnterpriseSearchTopology -SearchApplication $ssa



# Additional


$ssa = Get-SPEnterpriseSearchServiceApplication "Search Service Application" 

 $admin = Get-SPEnterpriseSearchAdministrationComponent -SearchApplication $ssa

 $admin | Set-SPEnterpriseSearchAdministrationComponent -SearchServiceInstance $searchServiceInstance1 -Force 


 $si = Get-SPEnterpriseSearchServiceInstance -Identity a007f95c-e67e-4150-ab8f-7fff8a71d5b6

$varSearchApp = get-spenterprisesearchserviceapplication

Set-SPEnterpriseSearchAdministrationComponent -SearchApplication $varSearchApp -SearchServiceInstance $si



Feel free to reply in case of any queries

Wednesday, June 7, 2017

PowerShell to automate turning on two-step verification in azure

To change the state using Azure AD PowerShell, you can use the following. You can change $st.State to equal one of the following states:
  • Enabled
  • Enforced
  • Disabled
Note: It's not recommended to move users directly from the Disable state to the Enforced state. Non-browser-based apps will stop working because the user has not gone through MFA registration and obtained an app password. If you have non-browser-based apps and require app passwords, we recommend that you go from a Disabled state to Enabled. This allows users to register and obtain their app passwords. After that, you can move them to Enforced.

PowerShell would be an option for bulk enabling users. Currently there is no bulk enable feature in the Azure portal and you need to select each user individually. This can be quite a task if you have many users. By creating a PowerShell script using the following, you can loop through a list of users and enable them

$st = New-Object -TypeName Microsoft.Online.Administration.StrongAuthenticationRequirement
    $st.RelyingParty = "*"
    $st.State = "Enabled"
    $sta = @($st)
    Set-MsolUser -UserPrincipalName jo@sharepoint.com -StrongAuthenticationRequirements $sta


Below is an example

$users = "jo@sharepoint.com","jol@sharepoint.com"
foreach ($user in $users)
{
    $st = New-Object -TypeName Microsoft.Online.Administration.StrongAuthenticationRequirement
    $st.RelyingParty = "*"
    $st.State = "Enabled"
    $sta = @($st)
    Set-MsolUser -UserPrincipalName $user -StrongAuthenticationRequirements $sta
}

Monday, May 22, 2017

Hide Ribbon in SharePoint Online using JS Link

Create a new js file and name it as DetailsView.js. Add the below script to it


window.onload = function () {

if (window.location.href.indexOf("user.aspx?obj") > -1) {

document.getElementById('Ribbon.Permission.Manage.Inherit-Large').style.display = "none";

}
};

upload it to a cdn location.

Here I'm hiding the Delete Unique Permissions Ribbon element from lists/libraries permission page. You can change code based on your ribbon id.


Below is the powershell to add the above js file as a link to SharePoint online site.

Add-Type -Path "c:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "c:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
Add-Type -Path "c:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Publishing.dll"

# Authenticate with the SharePoint site.
#
$actionName = "EM_SPO_ZIN_JS_Injection"
$actionType = "ScriptLink"
$actionSourceFile ="https://cdnpath/Detailsview.js"


$siteUrl = Read-Host -Prompt "Enter web url:"
$username = Read-Host -Prompt "Enter Username:"
$password = Read-Host -Prompt "Enter password" -AsSecureString
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl)

# SharePoint Online
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $password)
$ctx.Credentials = $credentials

$rootWeb = $ctx.Web
$ctx.Load($rootWeb)
$actions = $rootWeb.get_userCustomActions()
$ctx.Load($actions)
$ctx.ExecuteQuery()
if($actions)
{
$actionsToDelete = @()

foreach($action in $actions)
{
if($action.get_description() -eq $actionName -and $action.get_location() -eq $actionType) {

Write-Host "Action found:" $action.get_description() -foregroundcolor white -backgroundcolor Green
$actionsToDelete += $action

}
}

foreach($actionToDelete in $actionsToDelete) {
    $actionToDelete.deleteObject()
Write-Host "Action deleted" -foregroundcolor white -backgroundcolor Green
}
$ctx.ExecuteQuery()
}


Write-Host "Installing action"  -foregroundcolor white -backgroundcolor Green
$newAction = $actions.add();
$newAction.set_description($actionName);
$newAction.set_location('ScriptLink');
$scriptBlock = 'var headID = document.getElementsByTagName("head")[0];var newScript = document.createElement("script");newScript.type = "text/javascript";newScript.src="';
$scriptBlock += $actionSourceFile + '?ver=' + (Get-Date);
$scriptBlock += '";headID.appendChild(newScript);';
$newAction.set_scriptBlock($scriptBlock);
$newAction.update();
$ctx.ExecuteQuery();

Write-Host "Action" $newAction.Description "installed" -foregroundcolor white -backgroundcolor Green

Powershell to add JS Link in SharePoint Online

Add-Type -Path "c:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "c:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
Add-Type -Path "c:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Publishing.dll"

# Authenticate with the SharePoint site.
#
$actionName = "EM_SPO_ZIN_JS_Injection"
$actionType = "ScriptLink"
$actionSourceFile ="https://cdnpath/Detailsview.js"


$siteUrl = Read-Host -Prompt "Enter web url:"
$username = Read-Host -Prompt "Enter Username:"
$password = Read-Host -Prompt "Enter password" -AsSecureString
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl)

# SharePoint Online
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $password)
$ctx.Credentials = $credentials

$rootWeb = $ctx.Web
$ctx.Load($rootWeb)
$actions = $rootWeb.get_userCustomActions()
$ctx.Load($actions)
$ctx.ExecuteQuery()
if($actions)
{
$actionsToDelete = @()

foreach($action in $actions)
{
if($action.get_description() -eq $actionName -and $action.get_location() -eq $actionType) {

Write-Host "Action found:" $action.get_description() -foregroundcolor white -backgroundcolor Green
$actionsToDelete += $action

}
}

foreach($actionToDelete in $actionsToDelete) {
    $actionToDelete.deleteObject()
Write-Host "Action deleted" -foregroundcolor white -backgroundcolor Green
}
$ctx.ExecuteQuery()
}


Write-Host "Installing action"  -foregroundcolor white -backgroundcolor Green
$newAction = $actions.add();
$newAction.set_description($actionName);
$newAction.set_location('ScriptLink');
$scriptBlock = 'var headID = document.getElementsByTagName("head")[0];var newScript = document.createElement("script");newScript.type = "text/javascript";newScript.src="';
$scriptBlock += $actionSourceFile + '?ver=' + (Get-Date);
$scriptBlock += '";headID.appendChild(newScript);';
$newAction.set_scriptBlock($scriptBlock);
$newAction.update();
$ctx.ExecuteQuery();

Write-Host "Action" $newAction.Description "installed" -foregroundcolor white -backgroundcolor Green