Covert ObjectID to displayname from Azure - bash

Hi I'm trying to convert objectID to display name from logs in Azure. So the trouble I'm running into is that I have the ps script but can't get it to work for created account for my alerts. It seems that the request body field keeps giving me errors.
$responseBodyObject = ConvertFrom-Json $_.Properties.Content.responseBody
$principalId = $responseBodyObject.properties.principalId
Write-Host "PrincipalID: $($principalId)"
$azUser = Get-AzADUser -ObjectId $principalId
Write-Host "User: $($azUser.DisplayName)"
ERROR MESSAGE
`Get-AzADUser : Cannot bind argument to parameter 'ObjectId' because it is an empty string.
At C:\xxxx\xxxx\xxxxx\xxxxxx.ps1:33 char:36
+ $azUser = Get-AzADUser -ObjectId $principalId
+ ~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Get-AzADUser], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Get-AzADUser

Get-AzADUser : Cannot bind argument to parameter 'ObjectId' because it is an empty string.
The error message shows that Objectid has empty value.
Make sure to check your Principal ObjectID whether it contains the valid ObjectID or not.
To check whether it is valid or not use below command
# use get-azaduser to get the objectid
Get-AzADUser
# Search for specific user using Startwith filter
Get-AzADUser -StartsWith demo
workaround:
Here i am using both ObjectId and UserPrinicipalName
using ObjectID
using UserPrinicipalName

Related

Null-valued expression for script on WSUS?

I am trying to retrieve a list of updates in the scope. My code is as follows:
#Loads Microsoft.UpdateServices.Administration assembly in order to connect to the WSUS server
[reflection.assembly]::LoadWithPartialName(“Microsoft.UpdateServices.Administration”) | Out-Null
#Make the initial WSUS connection by using the .NET accelerator [Microsoft.UpdateServices.Administration.AdminProxy] and the static method getUpdateServer(), which requires two values: the WSUS server name and a Boolean value for a secure connection.
$wsus = [Microsoft.UpdateServices.Administration.AdminProxy]::getUpdateServer()
#Creating the Computer Target Scope object
$computerscope = New-Object Microsoft.UpdateServices.Administration.ComputerTargetScope
#Find all clients using the computer target scope
$wsus.GetComputerTargets($computerscope)
#Gets computer status
$Wsus.GetComputerStatus($computerscope,[Microsoft.UpdateServices.Administration.UpdateSources]::All)
When I try to run the following:
#Provides a summary of whether the clients that are specified in the scope require the update
ForEach($update in $computerscope)
{
$update = $wsus.SearchUpdates($computerscope)
}
$update[0].GetSummary($computerscope)
I receive the following error:
You cannot call a method on a null-valued expression.
At line:6 char:1
+ $update[0].GetSummary($computerscope)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
even though I am passing $computerscope in the GetSummary method.
Any guidance would be appreciated.

How to test if an EventSubscriber exists in Windows Powershell

Before deleting an EventSubscriber with SourceIdentifier "abc", I want to test if it exists and only then delete it. Otherwise there is no need to.
But every time I access it to test if it exists with:
Get-EventSubscriber -SourceIdentifier "abc"
Powershell responds with an error:
get-eventsubscriber : Event subscription with source identifier 'abc' does not exist.
At line:1 char:8
+ $chk = get-eventsubscriber -SourceIdentifier "abc"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-EventSubscriber], Argu
mentException
+ FullyQualifiedErrorId : INVALID_SOURCE_IDENTIFIER,Microsoft.PowerShell.C
ommands.GetEventSubscriberCommand
stating that it does not exist. Is there a way to avoid the error messages and instead set a variable to null or false that can be tested to see if it does not exist?
Something like:
$eventSubscriberExists = Get-EventSubscriber -SourceIdentifier "abc"
if ($eventSubscriberExists) {
Unregeister-Event -SourceIdentifier "abc"
}
In other words instead of sending error messages to the console, set a variable to true or false.

Issue adding to a Substring if a dsquery finds the same sAMAccountName

I am editing a Powershell script that a colleague created before they left which I assume was created on an older version of Powershell/Activedirectoy. It is to create an AD account but I'm having an issue checking if a username already exists then carrying out an action if it does.
$UsernameInteger = 1
$sAMAccountName = $sn+$givenName.substring(0,$UsernameInteger)
# Check to see if the username is available in Active Directory
do
{
if (dsquery user -samid $sAMAccountName)
{
$CreateUser = $False
$UsernameInteger++
$Username = $sn+$givenName.substring(0,$UsernameInteger)
}
Else
{
$CreateUser = $True
}
}
Until ($CreateUser -eq $True)
When I run this code with an account with the same name I get the following error:
Exception calling "Substring" with "2" argument(s): "Index and length must refer to a location within the string.
Parameter name: length"
At C:\AD Account Creation.ps1:43 char:5
+ $Username = $sn+$givenName.substring(0,$UsernameInteger)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ArgumentOutOfRangeException
What I want is when the $createuser = $false then it will add the next letter of their $givenName to the $username and keep doing this until an account with the same $sAMAccountName is not found and the account can be created.
How would I go about doing this?
You've incremented the counter to a value bigger than the length of the $givenName string. You need to change the increment logic to something like:
if ($UsernameInteger -le $givenName.length) {
$UsernameInteger++
}
This won't help if the username you pass in already exists in its entirety though, so you'll also need to handle that scenario

Powershell - Internet Explorer - Get document for a newly opened tab

I am trying to figure out how to login to web-pages in Internet Explorer 9 using PowerShell version 2 on Windows 7 x64. When I run these lines one by one in PowerShell, I get exactly what I want - The page opens and I am able to login.
$internet_explorer = new-object -com "InternetExplorer.Application"
$internet_explorer.visible = $true
$internet_explorer.navigate2("https://abcd.efgh.com/ijkl/Login.jsp")
$this_document = $internet_explorer.document
$username_field = $this_document.getElementByID("usernameField")
$password_field = $this_document.getElementByID("passwordField")
$login_button = $this_document.getElementByID("SubmitButton")
$username_field.value = "username"
$password_field.value = "password"
$login_button.click()
But when I try to open another tab and try to login to the new webpage by executing the below lines one-by-one,
$internet_explorer.navigate2("https://mnop.qrst.com/uvwx/Login.jsp", 0x0800)
$this_document = $internet_explorer.document
$username_field = $this_document.getElementByID("usernameField")
$password_field = $this_document.getElementByID("passwordField")
$login_button = $this_document.getElementByID("SubmitButton")
$username_field.value = "username"
$password_field.value = "password"
$login_button.click()
I get the following errors :
Property 'value' cannot be found on this object; make sure it exists and is settable.
At line:1 char:17
+ $username_field. <<<< value = "username"
+ CategoryInfo : InvalidOperation: (value:String) [], RuntimeException
+ FullyQualifiedErrorId : PropertyNotFound
Property 'value' cannot be found on this object; make sure it exists and is settable.
At line:1 char:17
+ $password_field. <<<< value = "password"
+ CategoryInfo : InvalidOperation: (value:String) [], RuntimeException
+ FullyQualifiedErrorId : PropertyNotFound
You cannot call a method on a null-valued expression.
At line:1 char:20
+ $login_button.click <<<< ()
+ CategoryInfo : InvalidOperation: (click:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
So when I open a new tab, how can I get Document of that newly opened tab? Please help me solve this
EDIT : Alternative methods will do. Please feel free to suggest any other way to login to multiple web pages automatically (like what was attempted above) if they exist
From the documentation for the Navigate method, it would appear that the new tab is not available for automation:
When navOpenInNewWindow or navOpenInNewTab is specified, the caller does not receive a pointer to the IWebBrowser2 interface for the new window, so there is no immediate way to manipulate it.

How do I get an error reason from InstallProductKey (SoftwareLicensingService) in PowerShell?

I'm using some PowerShell functions to configure Windows product keys and activation. I get an instance of the SoftwareLicensingService and call InstallProductKey, like this. The trap block with super formatting is extra to help debugging.
trap [Exception]
{
"=================================================="
"Trapped: $($Error[0])"
"=================================================="
"Exception: $($_.Exception)"
"--------------------------------------------------"
""
break
}
$service = Get-WmiObject -Query "SELECT * FROM SoftwareLicensingService"
$service.InstallProductKey("12345-12345-12345-12345-12345")
$service.RefreshLicenseStatus() | Out-Null
The error condition is an invalid product key. I know this because I entered it manually into the Activate Windows dialog from the System panel. But, the script only ever shows me the WMIMethodException or the COMException.
==================================================
Trapped: Exception calling "InstallProductKey" : ""
==================================================
Exception: System.Runtime.InteropServices.COMException (0xC004F025)
at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
at System.Management.ManagementObject.InvokeMethod(String methodName, ManagementBaseObject inParameters, InvokeMethodOptions options)
at System.Management.Automation.ManagementObjectAdapter.InvokeManagementMethod(ManagementObject obj, String methodName, ManagementBaseObject inParams)
--------------------------------------------------
Exception calling "InstallProductKey" : ""
At line:14 char:31
+ $service.InstallProductKey <<<< ("12345-12345-12345-12345-12345")
+ CategoryInfo : NotSpecified: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : WMIMethodException
I don't get a return code from the method (despite the documentation stating I do, can't find a list of error codes anyway). Do you know how to get the activation (or product key install) error reason?
As far as I can see there's no message there. Adding these to your trap:
$_ | fl * -Force
$_.Exception | fl * -Force
Returns everything that is there in the exception and there is nothing useful. So I googled a bit and found a piece of C# code here: http://www.dozty.com/?tag=change-windows-7-product-key-c-sharp They were cathcing ManagementException and in C# it seemed to work a bit better. I have rewritten that code into PowerShell and was trying to catch ManagementException, but without luck:
trap [Exception]
{
[System.Management.ManagementException] $_
break
}
$classInstance = new-object System.Management.ManagementObject("root\CIMV2","SoftwareLicensingService.Version=`"6.1.7600.16385`"", $null);
$inParams = $classInstance.GetMethodParameters("InstallProductKey")
$inParams["ProductKey"] = "12345-12345-12345-12345-12345"
$classInstance.InvokeMethod("InstallProductKey", $inParams, $null)
It throws: Cannot convert the "System.Runtime.InteropServices.COMException (0xC004F050)"

Resources