PowerShell Script with Clixml and Taskscheduler - powershell

Here's the problem:
When I run my PowerShell script manually, everything works fine. But it doesn't work via task scheduling.
The reason is probably my stored credentials for Active Directory and Mobile Device Management.I stored them with "Export-Clixml" but the xml files cant be read when i open the script with task scheduler. Without it works perfect.
The task scheduler is executed with the same user who saved the credentials in the XML before.
I hope you understand what I mean.
Edit 1:
I've tried the Solution from "Bender the Greatest".
Unfortunately it still doesn't work. I exported my credentials with "Export-Clixml" and import them with "Import-Clixml".
It doesn't matter if I generate them manually via my admin account or via the system account (with psexec). If I then execute it via the corresponding account with which the credentials were generated, it still doesn't work.
But it seems to find the credentials (I saw that in the log). But The import doesn't seem to work.
If I manually include the credentials in the script it works fine, but I would have liked to store them encrypted.
[Lizenzauswertung] Überprüfe Zugangsdaten
[Lizenzauswertung] MDM Zugangsdaten gefunden - Credentials found
[Lizenzauswertung] MDM AccessToken gefunden - Credentials found
[Lizenzauswertung] AD Zugangsdaten gefunden - Credentials found
Here im trying to decrypt the Password from the XML File:
It is not possible to call a method for an expression that has NULL.(Translated)
In C:\Scripts\ADAuswertung\AD_Auswertung_GKZ.ps1:171 Zeichen:1
+ $PSCPW = $CredsMDM.GetNetworkCredential().Password
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
It is not possible to call a method for an expression that has NULL.(Translated)
In C:\Scripts\ADAuswertung\AD_Auswertung_GKZ.ps1:171 Zeichen:1
+ $PSCPW = $CredsMDM.GetNetworkCredential().Password
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
This is a replacement for the username to have the right spelling for a webrequest:
It is not possible to call a method for an expression that has NULL.(Translated)
In C:\Scripts\ADAuswertung\AD_Auswertung_GKZ.ps1:172 Zeichen:1
+ $RPSCUser = $PSCUser.Replace("INTRA","intra.lan")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
It is not possible to call a method for an expression that has NULL.(Translated)
In C:\Scripts\ADAuswertung\AD_Auswertung_GKZ.ps1:172 Zeichen:1
+ $RPSCUser = $PSCUser.Replace("INTRA","intra.lan")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Here you can see the errors that occur when importing the MDM credentials. The reason for the errors is described above. I edit the credentials after importing them before they are passed to the script.
The MDM Access Token is not encrypted and can be read.
The AD credentials are not processed beforehand, but passed directly to the AD commands. Therefore, no error is displayed here. Since it does not finish the AD report, which I saw in the log, these are not imported either.
Here is a little Codesnippet of the Import/Export. Just got the code here for the MDM credentials. The other queries are the same.
If (Test-Path $CredentialsMDM){
$CredsMDM = Import-Clixml -Path $CredentialsMDM
Write-Host "[Lizenzauswertung] MDM Zugangsdaten gefunden" -ForegroundColor Green
} else {
Write-Host "[Lizenzauswertung] MDM Zugangsdaten nicht gefunden" -ForegroundColor Yellow
Get-Credential -Message "Zugangsdaten für MDM / Airwatch" | export-clixml -path $CredentialsMDM
$CredsMDM = Import-Clixml -Path $CredentialsMDM
}
Write-Host "[Lizenzauswertung] Zugangsdaten überprüft" -ForegroundColor Green
$PSCUser = $CredsMDM.UserName
$PSCPW = $CredsMDM.GetNetworkCredential().Password
$RPSCUser = $PSCUser.Replace("INTRA","intra.lan")
$AccessToken = $CredsMDMAT.accesstoken
$Auth = $CredsAD
(I am sorry for the spaghetti code.)

You need to provide the error you're getting but I'm going to take a shot in the dark here. I'm guessing you're either exporting secretAD.xml as one user and running your script as another user from Task Scheduler, or exporting secretAD.xml on another computer/server. By default, credentials are able to be decrypted only by the user that built it on that specific server. This is how Windows' Data Protection API (DPAPI) works.
The easy way to fix this is to generate secretAD.xml as the user you intend to run the script as. You can specify your own key for decryption, which can be used by any user on any box, but you will need to figure out a method of secure delivery of the decryption key to the runtime. If you want/need to run the script as NT Authority\SYSTEM, I recommend using psexec to open an interactive SYSTEM Powershell session, generate the credential, and then use Export-CliXml to serialize the credential to secretAD.xml.
Note that the default DPAPI key gets changed when an account password is rotated, so you'll need to remember to rebuild the credential when that happens.

I've found the solution to my problem.
The reason was that the path to the credentials was ".\secretMDM.xml".
The task scheduler executes the script at a different location.
Therefore I had to specify the whole path of the file.
Thanks for the help anyway.
Edit:
Out of interest I created the "Credential" - XML files with the Task Scheduler. Have a look where it stores the files ;)

Related

InvalidCastException when trying to obtain UserPrincipal.Current

I have a PowerShell script which checks the currently signed in user as part of its start-up process. I'm using .Net to do this by adding the assembly:
Add-Type -AssemblyName System.DirectoryServices.AccountManagement
$cUser = [System.DirectoryServices.AccountManagement.UserPrincipal]::Current
For almost everyone this works fine and I get a UserPrincipal object that I can use elsewhere, however there are a couple of users who get the following error when running it:
Unable to cast object of type 'System.DirectoryServices.AccountManagement.GroupPrincipal' to type 'System.DirectoryServices.AccountManagement.UserPrincipal'. At line:2 char:1
+ [System.DirectoryServices.AccountManagement.UserPrincipal]::Current
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], InvalidCastException
+ FullyQualifiedErrorId : System.InvalidCastException
This is on a standard Windows 10 20H2 install and doesn't matter if PowerShell is running elevated or not. I've never seen this call return anything other than a UserPrincipal before, so I would be grateful for any advice: is this something I can deal with in code, or is there some underlying issue with the machines that are returning this exception?
I don't know if this is what you're looking for:
$cUser = Get-ADUser $Env:Username -Properties *
This has the most important attributes that you can use for whatever you want later on. It provides as much attribute as the code you posted that didn't work for some of the user.

ADSI commands causing Access Denied errors

I'm attempting to set the description attribute in ADSI via PowerShell, but keep getting "access denied". It's executing from a non-privileged user, but the user does have Write All Properties permissions over this object. With those permissions, I don't see why I would need to be a DA to write to that attribute.
Example shown here:
$Computer = [ADSI]"LDAP://cn=TESTER,cn=Computers,dc=lab,dc=local"
$Computer.Put("description", "test")
$Computer.setinfo()
$Computer.setinfo() Exception calling "setinfo" with "0" argument(s): "Access is denied. " At line:1 char:1 + $Computer.setinfo() + ~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : CatchFromBaseAdapterMethodInvokeTI`
When I don't include the parenthesis (eg: $Computer.setinfo), it sets the attribute locally but never pushes it to AD. Yes i'm running in an elevated PS session.
As #Lee_Dailey mentioned, you'd better include the error message in the original post.
About the issue, are you running the script in an elevated prompt? It does not matter whether user has permissions on AD object or not if the resource requires running in elevated prompt. You should explicitly run as administrator if it needs. Can you please check again to see if that is the case here?

ADAL in Azure Automation: Type not loading intermittantly

I'm working on an Azure Automation script where I need to retrieve an access token to call the AAD Graph API. I wanted to use ADAL to do this so I zipped up Microsoft.IdentityModel.Clients.ActiveDirectory.dll and uploaded it as a module. When I run from the test blade, it sometimes works, and sometimes fails with this error:
New-Object : Cannot find type [Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential]: verify that the
assembly containing this type is loaded.
At line:22 char:9
+ $cred = New-Object Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredent ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidType: (:) [New-Object], PSArgumentException
+ FullyQualifiedErrorId : TypeNotFound,Microsoft.PowerShell.Commands.NewObjectCommand
When it fails I just run it again and it works. Now I've published and scheduled this runbook as a daily job 3 days ago. So far it has failed every day with this same error.
Has any one else seen this? Any suggestions on next steps?
I fixed this by adding the following line to my script:
Add-Type -Path "C:\Modules\User\Microsoft.IdentityModel.Clients.ActiveDirectory\Microsoft.IdentityModel.Clients.ActiveDirectory.dll"
Still not sure why it was working intermittently before. I guess depending on what else was going on ADAL may or may not have been loaded?

Access denied adding domain user to local administrators group

When adding a domain user to the local administrators group I receive an access denied, this worked before and now sadly and strangely it no longer does.
$user = "mydomain/user"
$group = [ADSI]"WinNT://./Administrators,group"
$group.Add("WinNT://$user,user")
Exception calling "Add" with "1" argument(s): "Access is denied.
"
At C:\test\Untitled5.ps1:3 char:1
+ $group.Add("WinNT://$user,user")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : CatchFromBaseAdapterMethodInvokeTI
Logged on as a domain administrator
Same error using the PowerShell ISE or the console
Yet, I am able to add the user through the Computer Management MMC snap-in, no problem.
This is most likely User Account Control (UAC) related. Make sure you run PowerShell "As Administrator." Otherwise, if you're not running "as admin," you're running PowerShell under your user's account's standard user token, which doesn't have access to make this change.

Exception creating client using AWS SDK

I am currently using the following sequence of commands in a Windows 7 PowerShell window.
Add-Type -Path "C:\Program Files (x86)\AWS SDK for .NET\bin\Net35\AWSSDK.dll"
$secretKeyID="ABCDEFGHIJKLMNOPQRS"
$secretAccessKeyID="LONGKEYBLAHBLAHBLAHBLAHBLABLAH"
$AWSclient=[Amazon.AWSClientFactory]::CreateAmazonS3Client($secretKeyID,$secretAccessKeyID)
However, I get this exception below. Please let me know what Im doing wrong. This is what I see most people using successfully.
Exception calling "CreateAmazonS3Client" with "2" argument(s): "No RegionEndpoint or ServiceURL configured"
At line:1 char:1
+ $oAWSclient=[Amazon.AWSClientFactory]::CreateAmazonS3Client($secretKeyID,$secret ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : AmazonClientException
One thing that I think is a problem is that my bucket is not checked for 'enable website hosting'. Does this need to be set to true? I just want to upload a file to the bucked via powershell script.
Duh... I realized that I need to use the AWS Powershell because it has all the settings built into it. Im not exactly sure how to properly refer to this version of powershell, but it is available after installing the AWS SDK.
Since the error specifically states that you're missing the RegionEndpoint or ServiceURL, you could also just include one of them. Since you're connecting to S3, all you need is to include the RegionEndpoint.
Add-Type -Path "C:\Program Files (x86)\AWS SDK for .NET\bin\Net35\AWSSDK.dll"
$secretKeyID="ABCDEFGHIJKLMNOPQRS"
$secretAccessKeyID="LONGKEYBLAHBLAHBLAHBLAHBLABLAH"
$client = [Amazon.AWSClientFactory]::CreateAmazonS3Client($secretKeyID, $secretAccessKeyID, [Amazon.RegionEndpoint]::USEast1)
(Replace USEast1 with the value configured with your S3 Bucket)