Remove Azure Licence for user from a csv file - azure

I don't know why my script work just for the first line and then I have :
Get-MsolUser : Impossible de convertir «System.Object[]» en type «System.String», requis par le paramètre «UserPrincipalName». La
méthode spécifiée n'est pas prise en charge.
Au caractère Ligne:5 : 34
+ (get-MsolUser -UserPrincipalName $csv2).licenses.AccountSkuId |
+ ~~~~~
+ CategoryInfo : InvalidArgument : (:) [Get-MsolUser], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgument,Microsoft.Online.Administration.Automation.GetUser
My Code :
$csv2 = Import-Csv C:\Tools\LicencesToRemove.csv
for ($i=0; $i -lt $csv2.Count; $i++)
{
(get-MsolUser -UserPrincipalName $csv2).licenses.AccountSkuId |foreach{
Set-MsolUserLicense -UserPrincipalName $csv2 -RemoveLicenses $_
}
}
csv file :
test.delete1#abc.onmicrosoft.com
test.delete2#abc.onmicrosoft.com
test.delete3#abc.onmicrosoft.com
test.delete4#abc.onmicrosoft.com

The issue is here.
get-MsolUser -UserPrincipalName $csv2
The UserPrincipalName must be of type string where as here it is Object[]. I suspect you are intended to write the following within the for loop
get-MsolUser -UserPrincipalName $csv2[$i].YourCsvColumnName

Assuming that your .csv2 file has a header with "UserPrincipalName". You can use the script below.
$csv2 = Import-Csv C:\Tools\LicencesToRemove.csv
foreach($user in $csv2)
{
(get-MsolUser -UserPrincipalName $user.UserPrincipalName).licenses.AccountSkuId |foreach{
Set-MsolUserLicense -UserPrincipalName $user.UserPrincipalName -RemoveLicenses $_
}
}

Related

GetEnumerator error whilst running my script

I am trying to extract and export Azure Webapp settings using the below script
$allWebApps = Get-AzureRmWebApp
$resourceGroups = $allWebApps | Select-Object 'ResourceGroup' -Unique
foreach($r in $resourceGroups)
{
$rgName = $r.ResourceGroup
$webApps = Get-AzureRmWebApp -ResourceGroupName $rgName
foreach($w in $webApps)
{
$webAppName = $w.Name
Write-Host Processing Webapp : $webAppName
$webApp = Get-AzureRmWebApp -ResourceGroupName $rgName -Name $webAppName
$appSettings = $webApps.SiteConfig.AppSettings
# Extract AppSettings to CSV
$appSettings.GetEnumerator() |
Sort-Object -Property Name -Descending |
Select-Object -Property #{n='Key';e={$_.Name}},Value |
Export-Csv -Path "C:\Cloud\$webAppName.csv" -NoTypeInformation -Append
}
}
but I keep getting the below error:
You cannot call a method on a null-valued expression.
At C:\Cloud\ExportsWebApp_config.ps1:17 char:9
+ $appSettings.GetEnumerator() |
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
can someone please assist?
$appSettings = $webApps.SiteConfig.AppSettings
I think this line should be changed, otherwise you're trying to get the properties of the entire array of web apps.
$appSettings = $webApp.SiteConfig.AppSettings

Unable to run the Powershell Script using SQL Server Job Agent

I am trying to execute my PowerShell script using the SQL Server Job Agent but unable to do so. I am able to execute the script successfully via PowerShell Prompt. Here in the Agent I am Operating System (CMDEXEC) and running as Service Account. Job is successfully executed but with following Error.
I am using the following command in command Window:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe "& 'D:\Powershell\triggersinfo.ps1'"
Message
Executed as user: NT Service\SQLSERVERAGENT. ...because it does not exist. At D:\Powershell\triggersinfo.ps1:4 char:98 + ... To-SecureString -Key (Get-Content D:\Triggers_Test\passwords\aes.key) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (D:\Triggers_Test\passwords\aes.key:String) [Get-Content], ItemNotFoundE xception + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetContentCommandConvertTo-SecureString : Input string was not in a correct format. At D:\Powershell\triggersinfo.ps1:4 char:69 + ... sword.txt | ConvertTo-SecureString -Key (Get-Content D:\Triggers_Test ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [ConvertTo-SecureString], FormatException + FullyQualifiedErrorId : System.FormatException,Microsoft.PowerShell.Commands.ConvertToSecureStringCommand New-Object : Exception calling ".ctor" with "2" argument(s): "Cannot process argument because the value of argument "password" is null. Change the value of argument "password" to a non-null value." At D:\Powershell\triggersinfo.ps1:5 char:16 + ... redential = New-Object System.Management.Automation.PsCredential($use ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [New-Object], MethodInvocationException + FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommandConnect-AzAccount : Cannot bind argument to parameter 'Credential' because it is null. At D:\Powershell\triggersinfo.ps1:7 char:32 + Connect-AzAccount -Credential $credential + ~~~~~~~~~~~ + CategoryInfo : InvalidData: (:) [Connect-AzAccount], ParameterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.Azure.Commands.Profile.ConnectA zureRmAccountCommandGet-AzDataFactoryV2Trigger : Run Connect-AzAccount to login. At D:\Powershell\triggersinfo.ps1:16 char:11 + $triggers=Get-AzDataFactoryV2Trigger -DataFactoryName $dataFactoryNam ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : CloseError: (:) [Get-AzDataFactoryV2Trigger], PSInvalidOperationException + FullyQualifiedErrorId : Microsoft.Azure.Commands.DataFactoryV2.GetAzureDataFactoryTriggerCommandGet-AzStorageAccount : No subscription found in the context. Please ensure that the credentials you provided are authorized to access an Azure subscription, then run Connect-AzAccount to login. At D:\Powershell\triggersinfo.ps1:70 char:13 + $account = Get-AzStorageAccount -ResourceGroupName 'DataLake-Gen2' - ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : CloseError: (:) [Get-AzStorageAccount], ApplicationException + FullyQualifiedErrorId : Microsoft.Azure.Commands.Management.Storage.GetAzureStorageAccountCommandNew-AzStorageAccountSASToken : Could not get the storage context. Please pass in a storage context or set the current storage context. At D:\Powershell\triggersinfo.ps1:71 char:8 + $sas= New-AzStorageAccountSASToken -Service Blob -ResourceType Serv ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : CloseError: (:) [New-AzStorageAccountSASToken], InvalidOperationException + FullyQualifiedErrorId : InvalidOperationException,Microsoft.WindowsAzure.Commands.Storage.Common.Cmdlet.NewAzure StorageAccountSasTokenCommandInvoke-RestMethod : {"error":{"code":"AuthenticationFailed","message":"Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.\nRequestId:c5b73384-401f-0061-7f95-b2677600... Process Exit Code 0. The step succeeded.
Any Idea why I a getting this error? If required I can also paste the whole PS Script here. Thanks
Script Used:
# Connect to Azure Account
$username = "xyz#abc.com"
$password = Get-Content D:\Triggers_Test\passwords\password.txt | ConvertTo-SecureString -Key (Get-Content D:\Triggers_Test\passwords\aes.key)
$credential = New-Object System.Management.Automation.PsCredential($username,$password)
Connect-AzAccount -Credential $credential
# Input Variables
$dataFactoryName="dna-production-gen2"
$resourceGroupName="DataLake-Gen2"
# get dataFactory triggers
$triggers=Get-AzDataFactoryV2Trigger -DataFactoryName $dataFactoryName -ResourceGroupName $resourceGroupName
$datas=#()
foreach ($trigger in $triggers) {
# get the trigger run history
$today = Get-Date
$yesterday = $today.AddDays(-1)
$splat = #{
ResourceGroupName = $trigger.ResourceGroupName
DataFactoryName = $trigger.DataFactoryName
TriggerName = $trigger.Name
TriggerRunStartedAfter = $yesterday
TriggerRunStartedBefore = $today
}
$historys =Get-AzDataFactoryV2TriggerRun #splat
if($historys -ne $null){
# create date
foreach($history in $historys){
$obj =[PsCustomObject]#{
'TriggerRunTimestamp ' = $history.TriggerRunTimestamp
'ResourceGroupName ' =$history.ResourceGroupName
'DataFactoryName' =$history.DataFactoryName
'TriggerName ' = $history.TriggerName
'TriggerRunId'= $history.TriggerRunId
'TriggerType'=$history.TriggerType
'Status' =$history.Status
}
# add data to an array
$datas += $obj
}
}
}
# convert data to csv string
$contents =(($datas | ConvertTo-Csv -NoTypeInformation) -join [Environment]::NewLine)
# upload to Azure Data Lake Store Gen2
#1. Create a sas token
$accountName="dna2020gen2"
# $path = New-Item -ItemType Directory -Path ".\$((Get-Date).ToString('yyyy-MM-dd'))"
$YY = (Get-Date).year
$MM = (Get-Date).month
$DD = get-date –f dd
$fileSystemName="dev"
$filePath="triggers/YYYY=$YY/MM=$MM/DD=$DD/data.csv"
$account = Get-AzStorageAccount -ResourceGroupName 'DataLake-Gen2' -Name $accountName
$sas= New-AzStorageAccountSASToken -Service Blob -ResourceType Service,Container,Object `
-Permission "racwdlup" -StartTime (Get-Date).AddMinutes(-10) `
-ExpiryTime (Get-Date).AddHours(2) -Context $account.Context
$baseUrl ="https://{0}.dfs.core.windows.net/{1}/{2}{3}" -f $accountName , $fileSystemName, $filePath, $sas
#2. Create file
$endpoint =$baseUrl +"&resource=file"
Invoke-RestMethod -Method Put -Uri $endpoint -Headers #{"Content-Length" = 0} -UseBasicParsing
#3 append data
$endpoint =$baseUrl +"&action=append&position=0"
Invoke-RestMethod -Method Patch -Uri $endpoint -Headers #{"Content-Length" = $contents.Length} -Body $contents -UseBasicParsing
#4 flush data
$endpoint =$baseUrl + ("&action=flush&position={0}" -f $contents.Length)
Invoke-RestMethod -Method Patch -Uri $endpoint -UseBasicParsing
#Check the result (get data)
Invoke-RestMethod -Method Get -Uri $baseUrl -UseBasicParsing

Enable/Disable availability tests in Azure on Schedule

I'm wondering if there is an easy way to run scheduled automation commands in Azure.
I managed to write Enable/Disable command for availability tests both in
Azure CLI:
az resource update --set properties.enabled=true --name 'someName' --resource-type 'Microsoft.Insights/webtests' --resource-group 'soemResourceGroup'
and
Powershell:
#Get All webTests
$resourceGroupnames = "someGroupName1", "someGroupName2";
$enableTests = "True";
ForEach ($resourceGroupname in $resourceGroupnames) {
$resourceGroupname
$allAvailabilityTestsIds = Get-AzureRmResource -ResourceGroupName $resourceGroupname `
| Where-Object -Property ResourceType -EQ "microsoft.insights/webtests" `
| Select-Object -ExpandProperty ResourceId;
ForEach ($availabilityTestId in $allAvailabilityTestsIds) {
$availabilityTest = Get-AzureRmResource -ResourceId $availabilityTestId;
$availabilityTest.Properties.Enabled = $enableTests;
$availabilityTest | Set-AzureRmResource -Force;
}
}
problem is that I'm not sure to run them outside of Comamnd line and on schedule. I've read that I could use Automation account to use powershell scripts but that seems a nightmare since I got tons of issues with authentication (not sure why).
Is that an only way ?
EDIT:
I post the errror I was/am getting below.
Set-AzureRmResource : Cannot validate argument on parameter 'Sku'. The argument is null or empty. Provide an argument
that is not null or empty, and then try the command again.
At line:37 char:29
+ $availabilityTest | Set-AzureRmResource -Force;
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (Microsoft.Azure...dels.PSResource:PSObject) [Set-AzureRmResource],
ParameterBindingValidationException
+ FullyQualifiedErrorId :
ParameterArgumentValidationError,Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.SetAzureResourceCmdlet
Set-AzureRmResource : Cannot validate argument on parameter 'Sku'. The argument is null or empty. Provide an argument
that is not null or empty, and then try the command again.
At line:37 char:29
+ $availabilityTest | Set-AzureRmResource -Force;
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (Microsoft.Azure...dels.PSResource:PSObject) [Set-AzureRmResource],
ParameterBindingValidationException
+ FullyQualifiedErrorId :
ParameterArgumentValidationError,Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.SetAzureResourceCmdlet
Set-AzureRmResource : Cannot validate argument on parameter 'Sku'. The argument is null or empty. Provide an argument
that is not null or empty, and then try the command again.
At line:37 char:29
+ $availabilityTest | Set-AzureRmResource -Force;
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (Microsoft.Azure...dels.PSResource:PSObject) [Set-AzureRmResource],
ParameterBindingValidationException
+ FullyQualifiedErrorId :
ParameterArgumentValidationError,Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.SetAzureResourceCmdlet
Set-AzureRmResource : Cannot validate argument on parameter 'Sku'. The argument is null or empty. Provide an argument
that is not null or empty, and then try the command again.
At line:37 char:29
+ $availabilityTest | Set-AzureRmResource -Force;
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (Microsoft.Azure...dels.PSResource:PSObject) [Set-AzureRmResource],
ParameterBindingValidationException
+ FullyQualifiedErrorId :
ParameterArgumentValidationError,Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.SetAzureResourceCmdlet
Set-AzureRmResource : Cannot validate argument on parameter 'Sku'. The argument is null or empty. Provide an argument
that is not null or empty, and then try the command again.
At line:37 char:29
+ $availabilityTest | Set-AzureRmResource -Force;
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (Microsoft.Azure...dels.PSResource:PSObject) [Set-AzureRmResource],
ParameterBindingValidationException
+ FullyQualifiedErrorId :
ParameterArgumentValidationError,Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.SetAzureResourceCmdlet
Set-AzureRmResource : Cannot validate argument on parameter 'Sku'. The argument is null or empty. Provide an argument
that is not null or empty, and then try the command again.
At line:37 char:29
+ $availabilityTest | Set-AzureRmResource -Force;
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (Microsoft.Azure...dels.PSResource:PSObject) [Set-AzureRmResource],
ParameterBindingValidationException
+ FullyQualifiedErrorId :
ParameterArgumentValidationError,Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.SetAzureResourceCmdlet
Set-AzureRmResource : Cannot validate argument on parameter 'Sku'. The argument is null or empty. Provide an argument
that is not null or empty, and then try the command again.
At line:37 char:29
+ $availabilityTest | Set-AzureRmResource -Force;
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (Microsoft.Azure...dels.PSResource:PSObject) [Set-AzureRmResource],
ParameterBindingValidationException
+ FullyQualifiedErrorId :
ParameterArgumentValidationError,Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.SetAzureResourceCmdlet
Regards.
You could follow the steps as below to use the azure runbook in automation to do that.
1.Navigate to your automation account -> Runbooks -> Create a runbook -> create a Powershell runbook.
2.In the runbook, add the script to login, your complete script should be like below. (Before running the runbook, make sure you have imported the AzureRM.Resources and AzureRM.Profile powershell module in your automation account -> Modules, if not, in the Modules -> Browse Gallery, search for the modules and import them.)
$connectionName = "AzureRunAsConnection"
try
{
# Get the connection "AzureRunAsConnection "
$servicePrincipalConnection=Get-AutomationConnection -Name $connectionName
"Logging in to Azure..."
Add-AzureRmAccount `
-ServicePrincipal `
-TenantId $servicePrincipalConnection.TenantId `
-ApplicationId $servicePrincipalConnection.ApplicationId `
-CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint
}
catch {
if (!$servicePrincipalConnection)
{
$ErrorMessage = "Connection $connectionName not found."
throw $ErrorMessage
} else{
Write-Error -Message $_.Exception
throw $_.Exception
}
}
#Get All webTests
$resourceGroupnames = "someGroupName1", "someGroupName2";
$enableTests = "True";
ForEach ($resourceGroupname in $resourceGroupnames) {
$resourceGroupname
$allAvailabilityTestsIds = Get-AzureRmResource -ResourceGroupName $resourceGroupname `
| Where-Object -Property ResourceType -EQ "microsoft.insights/webtests" `
| Select-Object -ExpandProperty ResourceId;
ForEach ($availabilityTestId in $allAvailabilityTestsIds) {
$availabilityTest = Get-AzureRmResource -ResourceId $availabilityTestId;
$availabilityTest.Properties.Enabled = $enableTests;
$availabilityTest | Set-AzureRmResource -Force;
}
}
3.After running the script successfully, follow this link Scheduling a runbook in Azure Automation to add a schedule to your runbook.

How to create a loop for Get-AzureADUserAppRoleAssignment?

I want to make a powershell script that would list me Users list from Azure AD and all Enterprise application assigned to every user from the list.
I have tried to set ForEach-Object loop to iterate each object I would get from Get-AzureADUser
This code works:
$UserId = (Get-AzureADUser -Top 1).ObjectId
Get-AzureADUserAppRoleAssignment -ObjectId $UserId
I 'm trying to loop and iterate for every single output:
$UserId = (Get-AzureADUser).ObjectId | ForEach-Object {
Get-AzureADUserAppRoleAssignment -ObjectId $UserId}
Here is the error message:
Get-AzureADUserAppRoleAssignment : Cannot convert 'System.Object[]' to the type 'System.String' required by parameter 'ObjectId'. Specified method is not supported.
At line:1 char:44
+ Get-AzureADUserAppRoleAssignment -ObjectId $UserID
+ ~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-AzureADUserAppRoleAssignment], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgument,Microsoft.Open.AzureAD16.PowerShell.GetUserAppRoleAssignments
You may create the loop for Get-AzureADUserAppRoleAssignment by these commands below:
$UserId = (Get-AzureADUser).ObjectId
foreach ($eachUserId in $UserId)
{
Get-AzureADUserAppRoleAssignment -ObjectId $eachUserId
}

How to use add-member in powershell Workflow?

i need to add item property but i have many error (unlike to my function code)
killprocess padmin7 notepad.exe
Microsoft.PowerShell.Utility\Write-Error : Impossible d'ajouter un membre du type « Property ». Spécifiez un autre type pour le paramètre MemberTypes.
Au caractère killprocess:7 : 7
+
+ CategoryInfo : NotSpecified: (:) [Write-Error], CmdletInvocationException
+ FullyQualifiedErrorId : System.Management.Automation.CmdletInvocationException,Microsoft.PowerShell.Commands.WriteErrorCommand
+ PSComputerName : [localhost]
my workflow source
Workflow killprocess ($srvs ,$process)
{
$Processes = (Get-WmiObject -Class Win32_Process -ComputerName $Srvs -Filter "name='$([string]::join("' or name='", $process))'")
foreach -parallel ($process in $processes) {
$Processes | Add-Member -MemberType Property -Name 'Status' -value 'in Progress'
$returnval = $process.terminate()
if($returnval.returnvalue -eq 0) {
$Processes | Add-Member -MemberType Property -Name 'Status' -value 'Killed'
}
}
}
I suspect the problem is using $process.terminate(). Method invocation of objects is not allowed in workflows.
http://blogs.technet.com/b/heyscriptingguy/archive/2013/01/02/powershell-workflows-restrictions.aspx

Resources