Get-AzureADAuditSignInLogs returning $null in Automation Accounts - azure

I have a simple script to get the last sign in details for each user in Azure. When running the script from Visual Studio, it all runs fine with no errors.
After uploading the script to an Azure Automation Account, I am getting the error "Object reference not set to an instance of an object".
I have checked and the command 'Get-AzureADAuditSigninLogs' is returning $null
$users = Get-AzureADUser -All $true
foreach ( $user in $users ) {
$userLogs = Get-AzureADAuditSigninLogs -Filter "startsWith(userPrincipalName, '$( $user.UserPrincipalName )')" -All $true
}
Any ideas on the issue that could be causing this to occur in the Automation account but not visual studio?

As per this issue,-All $true parameter is not working for cmdlet Get-AzureADAuditSignInLogs as expected.
To resolve it, you can try upgrading to AzureADPreview v2.0.2.89.
Alternatively, you can also try as suggested by psignoret:
Format string with -f or [String]::Format():
Write-Host ("startsWith(userPrincipalName ,'{0}')" -f $user.userPrincipalName)
Write-Host [String]::Format("startsWith(userPrincipalName ,'{0}')", $user.userPrincipalName)

Related

Assistance needed with powershell script

I am trying the execute the powershell script found at :
https://github.com/amanbedi18/Azure-KeyVault-Automation/tree/master/UploadSecrets
https://github.com/amanbedi18/Azure-KeyVault-Automation
This script is used to automate upload of secrets to azure key-vault.
I have created the below json file and named it /user/kv/AzureSecretsMetaData.json
[
{
"key": "test1",
"value": "1"
},
{
"key": "test2",
"value": "2"
}
]
I then copied contents of setKeyVaultSecrets.ps1 to /user/kv/setKeyVaultSecrets.ps1
I have tried the below commands that were mentioned in the readme and powershell script files and get the below errors, could someone please help me execute this script correctly and point out what I am doing wrong here.
./setkeyVaultSecret.ps1 -KeyVaultName 'avkv01'
setkeyVaultSecret.ps1: Parameter set cannot be resolved using the specified named parameters. One or more parameters issued cannot be used together or an insufficient number of parameters were provided.
./setkeyVaultSecret.ps1 -KeyVaultName 'avkv01' -KVSecretMetadataFilePath '/home/aditya/kv/AzureSecretsMetaData.json'
setkeyVaultSecret.ps1: Parameter set cannot be resolved using the specified named parameters. One or more parameters issued cannot be used together or an insufficient number of parameters were provided.
Any help is greatly appreciated. Thank You
If these are scripts you found, they are very poorly written and I would advise not using them. I would suggest installing the az powershell module and using those scripts as a reference in writing your own script. You can install the az powershell module with powershellget:
Install-module az -force -allowclobber
The way the script that you are trying to call is written very strangely. It defines two different parameter sets, but each of the two parameters are mandatory for BOTH parameter sets?! That doesn't make a lot of sense. If you must run them, you will probably need to modify them a bit. They don't really seem finished.. Why not modify the script and get rid of the parameter sets altogether? Also, the example in the script indicates that the "$KVSecretMetadataFilePath" parameter is not mandatory, since it is not being called, but is defined as being mandatory when defining your parameter. You need to make clear if this parameter is required or not. If it is required Make it look more like this:
<#
.PREREQUISITE
1. An Azure key vault and its name as parameter.
2. Json template should be properly populated with valid json schema in sampleSecretValues.json in KeyVaultjson directory.
.PARAMETER vaultName
The name of the key vault.
.EXAMPLE
. setKeyVaultSecret.ps1 -KeyVaultName 'somekeyvault'
#>
# provision keys and secrets to a key vault
Param(
[Parameter(Mandatory=$true)]
[String]
$KeyVaultName,
[Parameter(Mandatory=$true)]
[String]
$KVSecretMetadataFilePath
)
Install-Module -Name AzureADPreview -ErrorAction SilentlyContinue -Force
Import-Module Azure -ErrorAction SilentlyContinue
Import-Module AzureRM.Resources
Set-StrictMode -Version 3
$json = Get-Content $KVSecretMetadataFilePath | Out-String | ConvertFrom-Json
$json | ForEach {
$secretToSearch = Get-AzureKeyVaultSecret -VaultName $KeyVaultName -Name $_.key -ErrorAction SilentlyContinue
if($secretToSearch -ne $null)
{
echo "The secret $_.key already exists !"
}
Else
{
$NewSecret = Set-AzureKeyVaultSecret -VaultName $KeyVaultName -Name $_.key -SecretValue (ConvertTo-SecureString $_.value -AsPlainText -Force ) -Verbose
Write-Host
Write-Host "Source Vault Resource Id: "$(Get-AzureRmKeyVault -VaultName $KeyVaultName).ResourceId
}
}
If it is not required, remove the line "[Parameter(Mandatory=$true)]" above the $KVSecretMetadataFilePath declaration.

unable to append data to sharepoint file via Azure Automation

Ok I have asked a question like this but now I am trying to perform the task via Azure Automation. I can connect to the SharePoint site via Azure Automation (powershell). with the correct credentials. I can download the file and append data to it. But I can when I try and upload the file back to SharePoint it adds the contents 3 times and then Azure Automation suspends the Runbook after 3 times.
It does run perfect if I upload this file as a different file name.
$siteurl="https://abc.sharepoint.com/sites/xxx/teamsites/os"
$credSP = Get-AutomationPSCredential -Name 'test'
$fileFolder = "$Env:temp"
Connect-PnPOnline -Url $siteurl -Credentials $credSP
Get-PnPFile -Url "/sites/xxx/teamsites/os/Directory and Operating
Systems/test.csv" -Path $fileFolder -Filename test.csv -AsFile -Force
$test = "31-07-2019 -11:35"
Add-Content -Path $fileFolder\test.csv $test
Add-PnPFile -Path $fileFolder\test.csv -Approve -Folder "Directory and
Operating Systems" #-ErrorAction Ignore
Here are the results
test test
31-07-2019 -11:35
31-07-2019 -11:35
31-07-2019 -11:35
As you can see it added $test 3 times. But I dont have this issue if I upload it as a new file name.
Ok after a while I have fix the issue.
After the add-pnpfile ...... you pipe it to | out-null
Thats it. the sript stops after it uploads ,
happy days

How to hide console output from Select-AzureRmSubscription

Does anyone know how to hide output from command Select-AzureRmSubscription inside azure workbook which runs as powershell workflow
Thanks
You can use Out-Null. Works for any PowerShell cmdlet.
Select-AzureRmSubscription | Out-null
The Out-Null cmdlet sends its output to NULL, in effect, removing it
from the pipeline and preventing the output to be displayed at the
screen.
https://msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.core/out-null
Select-AzSubscription -SubscriptionId $s.Id | Out-Null + ~~~~~~~~ Cannot call the 'Out-Null' command. Other commands from this module have been packaged as workflow activities, but this command was specifically excluded. This is likely because the command requires an interactive Windows PowerShell session, or has behavior not suited for workflows. To run this command anyway, place it within an inline-script (InlineScript { Out-Null }) where it will be invoked in isolation

PowerShell Excel Add-in Deployment Issue

I have this script that I have gotten from http://poshcode.org/1811 and modified slightly for my own purposes. The problem I'm having is the user who requested for me to deploy the add-in has informed me that only the initial person that logs on to use the add-in can see it installed. This is an Active Directory environment and the script is set to run as the user logs on.
Here is the script, I will also get the code for the add-in itself later from the person in question.
$Addinfilepath = '\\network\path\to\Excel Add-ins\'
$Addinfilename = Get-ChildItem $Addinfilepath -Name
ForEach ($CustomAddin in $Addinfilename) {
$Excel = New-Object -ComObject excel.application
$ExcelWorkbook = $excel.Workbooks.Add()
if (($ExcelWorkbook.Application.AddIns | Where-Object {$_.name -eq $CustomAddin}) -eq $null) {
$ExcelAddin = $ExcelWorkbook.Application.AddIns.Add("$Addinfilepath$CustomAddin", $True)
$ExcelAddin.Installed = "True"
Write-Host "$CustomAddin added"}
#else{}
#{Write-Host "$Addinfilename already added"}
$Excel.Quit()
}
I'm not quite sure what's wrong with the script, but I believe there's something going on where it's installing to the first person's profile on the PC, but then maybe the script is seeing it as installed period and then no longer installs to the next user that logs on.
Thanks for advice or help you can give.
Not sure if you noticed it but you are missing $ sign in front of CustomAddin when you are trying to match the name.
Where-Object {$_.name -eq CustomAddin})
should be
Where-Object {$_.name -eq $CustomAddin})

IIS: how to undeploy/delete/remove a webapp from command line?

Suppose there's a webapp deployed on local IIS server. When I need to remove/undeploy it, I can go to IIS Manager, right-click on the app, and then select "Delete application and content" - et voila. But, I need to do the same from the command line - how? It can be assumed that the name of the application is known.
Maybe this can be done via MSDeploy somehow?
If you just want to remove the application from the Web Site in IIS without physically deleting the files (like msdeploy does) or if you don't have the WebDeploy-extension installed, you can use the following command:
C:\Windows\System32\inetsrv\appcmd.exe delete app "Default Web Site/MyAppName"
This is what did it:
"C:\Program Files\IIS\Microsoft Web Deploy\msdeploy" -verb:delete -dest:apphostconfig="Default Web Site/<webapp_name>"
I know the question says "command line", but you can use PowerShell and the IIS Administration Cmdlets to do this task. I provide all of the functions and explain the process of how to automate this on my blog. Also, you can easily swap out the IIS Administration Cmdlet calls with calls to msdeploy, appcmd, IIsVdir.vbs, etc.
For your specific question, this PowerShell code should do the trick:
$block = {
Import-Module WebAdministration
$website = "YourWebsiteName"
$applicationName = "PathUnderWebsite\ToYourApplication"
$fullPath = Join-Path $website $applicationName
Write-Host "Checking if we need to remove '$fullPath'..."
if (Get-WebApplication -Site "$website" -Name "$applicationName")
{
Write-Host "Removing '$fullPath'..."
Remove-WebApplication -Site "$website" -Name "$applicationName"
}
Write-Host "Deleting the directory '$fullPath'..."
Remove-Item -Path "IIS:\Sites\$fullPath" -Recurse -Force
}
$session = New-PSSession -ComputerName "Your.WebServer.HostName"
Invoke-Command -Session $session -ScriptBlock $block
Remove-PSSession -Session $session
iisweb /delete WebSite [/s Computer [/u [Domain ]User /p Password ]]

Resources