Enable RemoteApp Full Desktop programmatically - windows-server-2008-r2

I am writing a powershell script to set up some HyperV VM's however there is one step I am having trouble automating. How do I check the box to allow Remote desktop access from the RemoteApp settings programmatically?
I can set up all of my customizations I need by doing
#build the security descriptor so the desktop only shows up for people who should be allowed to see it
$remoteDesktopUsersSid = New-Object System.Security.Principal.SecurityIdentifier($remoteDesktopUsersGroup.objectSid[0],0)
#get a copy of the WMI instance
$tsRemoteDesktop = Get-WmiObject -Namespace root\CIMV2\TerminalServices -Class Win32_TSRemoteDesktop
#set settings
$tsRemoteDesktop.Name=$ServerDisplayName
$tsRemoteDesktop.SecurityDescriptor= "O:WDG:WDD:ARP(A;CIOI;CCLCSWLORCGR;;;$remoteDesktopUsersSid)"
$tsRemoteDesktop.IconPath = $IconPath
$tsRemoteDesktop.IconIndex = $IconIndex
#push settings back to server
Set-WmiInstance -InputObject $tsRemoteDesktop -PutType UpdateOnly
however the instance of that WMI object does not exist until after you have the above box checked.
I attempted to use Set-WmiInstance to instantiate and set the settings at the same time but I keep getting errors like:
Set-WmiInstance :
At line:53 char:16
+ Set-WmiInstance <<<< -Namespace root\CIMV2\TerminalServices -Class Win32_TSRemoteDesktop -Arguments #{Alias='TSRemoteDesktop';Name=$ServerDisplayName;ShowInPortal=$true;SecurityDescriptor=$securityDescriptor}
+ CategoryInfo : NotSpecified: (:) [Set-WmiInstance], ArgumentException
+ FullyQualifiedErrorId : System.ArgumentException,Microsoft.PowerShell.Commands.SetWmiInstance
(also after running the command and getting the error it will delete the instance of Win32_TSRemoteDesktop if it already exited and un-check the box in the properties setting)
Is there any way to programmatically check that box or can anyone help with why Set-WmiInstance throws that error?

You could use the Remote Desktop Services Provider for Windows PowerShell module if you are running windows server 2008 R2.
You can read up about it on technet hear is the link.
I used this guide for all my needs .

Related

Powershell Azure Function Fails

First and foremost I'm new to Azure Functions and have only been working with it for a couple of weeks, so please bear with me. I was tasked with taking one of our Powershell script that gets users and licenses from our Office 365 Tenants, output them to CSV and then email them to a monitored email box, and porting it over to an Azure Function.
After a lot of work I've managed to get it to work using a call to Powershell.exe from within my script, due to the fact that some objects are returned "Un-serialized", preventing them from being iterated. (Known Issue on GitHub)
Everything was working via Test + Code and I set the time trigger to run at 12:00am, however when I checked my inbox the following day I had no emails. When I checked monitoring on function, I had the following listed for each of the Tenants that was iterated, which would seems to be something failing with the call to Powershell.exe:
HResult : -2146233087 CategoryInfo : OperationStopped: (:) [],
CryptographicException FullyQualifiedErrorId :
System.Security.Cryptography.CryptographicException InvocationInfo :
ScriptLineNumber : 77 OffsetInLine : 5 HistoryId : -1 ScriptName :
C:\home\site\wwwroot\License_Report_a-f\run.ps1 Line : $ScriptResult =
(&$64bitPowerShellPath -WindowStyle Hidden -NonInteractive -Command
$Script -Args
$ApplicationId,$credential,$refreshToken,$tenantID,$client.TenantID)
PositionMessage : At
C:\home\site\wwwroot\License_Report_a-f\run.ps1:77 char:5 +
$ScriptResult = (&$64bitPowerShellPath -WindowStyle Hidden -NonIn … +
PSScriptRoot : C:\home\site\wwwroot\License_Report_a-f PSCommandPath :
C:\home\site\wwwroot\License_Report_a-f\run.ps1 CommandOrigin :
Internal ScriptStackTrace : at ,
C:\home\site\wwwroot\License_Report_a-f\run.ps1: line 77
I did some investigation on this and found someone elude that there were occasions where the Function can't read "Profile.ps1", which is where I'd but the declaration of the Powershell.exe env variable, so as a test I moved the assignment locally within the script. I then set an hourly schedule on the TimeTrigger and it was running fine on the hour. However, changing the TimeTrigger back to only run at 12:00am, I was greeted with no emails again this morning and the same error, seemingly ruling out the "Profile.ps1" issue.
My frustration at the moment is that the function works fine in Code + Test, but it seems like if the the function is idle for an extended period of time, when it spins up again it can't load something properly. I had successful running on the hour yesterday at 10:00, 11:00, 12:00, 13:00, 14:00 and 15:00. It was then left with no spin ups for 9 hours and then it failed. This morning, I have updated the TimeTrigger again to run every hour to see what happens and now once again, I'm getting the emails coming through to me, so I'm baffled. Again, I've made a change and almost "woke the machine up" and now everything works fine again.
Has anyone seen this before or anything similar as I'm not sure where to look next. Is there maybe some sort of cache that get's cleared if you don't run a function for x minutes / x hours which is causing the issue? I've had a couple of hours looking on the net, but I can't see anything similar. Any help / points are gratefully appreciated.
So it seems like I may have found the issue myself, however it doesn't really explain what exactly is going on, but it seems to be related to Generating the "Graph Access Tokens" to access Office 365 itself.
After some playing around last week, I got to a point where I was no longer able to run the script without the above error, even in "Test + Run" on the Azure Functions interface. I decided to do some testing on the script that was ran by the External PowerShell call and when I removed the code that was generating the "Graph Access Tokens", the script executed successfully. I then re-structured the whole code so that I would generate the tokens before calling the External PS script, and then pass in the access tokens instead.
After testing over the weekend, I can confirm that I've correctly generated and sent the export files via email so it looks to be all working fine now. Below is a rough outlay of the start of the script, just to showcase what I've ended up with.
# Import Modules
Import-Module MsOnline -UseWindowsPowershell
Import-Module PartnerCenter -UseWindowsPowershell
# Get Tokens
$aadGraphToken = New-PartnerAccessToken -ApplicationId $ApplicationId -Credential $credential -RefreshToken $refreshToken -Scopes 'https://graph.windows.net/.default' -ServicePrincipal -Tenant $tenantID
$graphToken = New-PartnerAccessToken -ApplicationId $ApplicationId -Credential $credential -RefreshToken $refreshToken -Scopes 'https://graph.microsoft.com/.default' -ServicePrincipal -Tenant $tenantID
#Connect to Msol
Connect-MsolService -AdGraphAccessToken $aadGraphToken.AccessToken -MsGraphAccessToken $graphToken.AccessToken
# Get Client List
$clientList = Get-MsolPartnerContract -All | Sort-Object -Property Name
# Loop Clients
ForEach ($client in $clientList)
{
$Script = {
param (
[Object]$aadGraphTkn,
[Object]$graphTkn,
[string]$clientTenantID
)
# Import Modules
Import-Module MsOnline
Import-Module PartnerCenter
#Connect to Msol
Connect-MsolService -AdGraphAccessToken $aadGraphTkn.AccessToken -MsGraphAccessToken $graphTkn.AccessToken
# DO OTHER THINGS HERE AND RETURN SOMETHING
}
$ScriptResult = (&$env:64bitPowerShellPath -WindowStyle Hidden -NonInteractive -Command $Script -Args $aadGraphToken,$graphTkn)
}

Receiving 'Value cannot be null' error on Parameter: source while trying to change a users profile picture in PowerShell

I'm trying to change a user's profile picture using PowerShell and I'm receiving the following error:
Error on proxy command 'Set-UserPhoto -Identity:'username_removed'
-PictureData:'255','216','255','224','0','16','74','70','73','70','0','1','1','1','0','72','0','72','0','0','2...
-Confirm:$False' to server ME3P282MB4196.AUSP282.PROD.OUTLOOK.COM: Server version 15.20.4713.0000, Proxy method RPS:
Processing data from remote server me3p282mb4196.ausp282.prod.outlook.com failed with the following error message:
[AuthZRequestId=aa213d1b-1ea1-4b2a-91b0-20d1ee30a6f7][FailureCategory=AuthZ-ArgumentNullException] Value cannot be
null.
Parameter name: source For more information, see the about_Remote_Troubleshooting Help topic.
[Server=MEYP282MB3499,RequestId=3929eae2-fd6c-4892-905d-274c7dd8b8a3,TimeStamp=3/12/2021 5:04:10 AM] .
+ CategoryInfo : NotSpecified: (:) [Set-UserPhoto], CmdletProxyException
+ FullyQualifiedErrorId : [Server=MEYP282MB3499,RequestId=3929eae2-fd6c-4892-905d-274c7dd8b8a3,TimeStamp=3/12/2021
5:04:10 AM] [FailureCategory=Cmdlet-CmdletProxyException] 503E4E16,Microsoft.Exchange.Management.RecipientTasks.S
etUserPhoto
+ PSComputerName : outlook.office365.com
I'm only doing this through PowerShell as a last resort as I received a similar error while trying to change the picture in Microsoft 365, the Azure portal and the user was unable to change it on their end.
edit: These are the commands I was running in PowerShell:
Connect-ExchangeOnline -UserPrincipalName <myemailaddress_removed> -DelegatedOrganization <tenant_id_removed>
Set-UserPhoto -Identity "IdentityRemoved" -PictureData ([System.IO.File]::ReadAllBytes("<path to file removed>"))
edit: I've tried uploading the profile picture to a test account in Azure and it was applied without issue so the trouble seems to be with this particular user's account

Not able to disable Azure AD Connect

I'm looking for a solution to my problem and I am not able to find it. I've tried everything online.
I'm trying to disable our on premise AD connect, I ran it as a test but it turns out our environment is not setup correctly for this to work and requires some restructuring.
I've followed the standard instructions of
Connect-MsolService and Set-MsolDirSyncEnabled -EnableDirSync $false
Connect works fine but when I try to run the disable command it returns back the error Set-MsolDirSyncEnabled : You cannot turn off Active Directory synchronization.
I've been told it could take a while but I had enabled it last week and most resources I've found say "24 - 72 hours".
The command (Get-MSOLCompanyInformation).DirectorySynchronizationStatus shows Enabled and not syncing.
Can anyone assist me with this issue?
Thank you!
You try to enable (or disable) Directory synchronization in Office 365, and you are greeted by the following error message.
PS C:\> Set-MsolDirSyncEnabled -EnableDirSync $false
Set-MsolDirSyncEnabled : You cannot turn off Active Directory synchronization.
At line:1 char:1
+ Set-MsolDirSyncEnabled -EnableDirSync $false
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [Set-MsolDirSyncEnabled], MicrosoftOnlineException
+ FullyQualifiedErrorId : Microsoft.Online.Administration.Automation.DirSyncStatusChangeNotAllowedException,Microsoft.Online.Administration.Automation.SetDirSyncEnabled
The DirSyncStatusChangeNotAllowedException error in particular means that you have changed the status recently, and the service is simply preventing you from changing it back too soon
Note : The error message detailed is different and will occur even if the
DirSync status has been updated. It’s a simple block on Microsoft’s
side to prevent you from changing the status too often
check now or wait for atleast 12 hours to 72hr to reflect.
MSOLCompanyInformation | select DirectorySynchronizationStatus
NO FIX: Unfortunately, there is no way around this error. It simply means that your directory is still doing a full initial synch with Azure AD. This error message will clear once the initial sync is complete. The time will vary depending on the size of your on-premises AD but should take no longer than 72 hours for very large environments.
Reference : https://www.michev.info/Blog/Post/1797/you-cannot-turn-off-active-directory-synchronization
Note : If still problem is not getting solved would suggest you to reach out to MS Support. They can able to track down where the exact. issue

Backup Sharepoint 2010 (using Powershell - Backup-SPFarm)

I asked this on ServerFault, but didn't get any reply's, I know it's command line, but they should still be able to answer it, anyone here have any idea's?
I've ran the following (task description):
> Add-PsSnapin Microsoft.SharePoint.Powershell
> Backup-SPFarm -Directory E:\Backups -BackupMethod Full
But get this error:
Backup-SPFarm : Object reference not set to an instance of an object.
At line:1 char:14
+ Backup-SPFarm <<<< -Directory \\SHAREPOINTSERV\Backups -BackupMethod full
+ CategoryInfo : InvalidData: (Microsoft.Share...mdletBackupFarm:SPCmdletBackupFarm) [Backup-SPFarm], NullReferenceException
+ FullyQualifiedErrorId : Microsoft.SharePoint.PowerShell.SPCmdletBackupFarm
I can backup manually through the Admin site, so all the services/permissions are setup correctly.
I can't find much helpful info on this does anyone know why I'm getting this error message?
running SQL Server 2008 R2 and Win2008 Standard (x64).
tried setting the directory to a UNC path and a local path.
tried set-executionpolicy ByPass (and RemoteSigned)
I'm logged on as a user with enterprise admin security credentials
SharePoint & SQL Server are installed on the same machine
Not sure if relevent, but I'm a developer and have never used power-shell before (nor has it been used on this machine before)... so my only guess is there is some sort of pre-requisite that I am supposed to have run or know about?
EDIT:
VERBOSE OUTPUT
PS E:\Backups\Script> Backup-SPFarm -Directory E:\Backups -BackupMethod Full -Verbose
VERBOSE: Leaving BeginProcessing Method of Backup-SPFarm.
VERBOSE: Performing operation "Backup-SPFarm" on Target "SHAREPOINTSERV".
Backup-SPFarm : Object reference not set to an instance of an object.
At line:1 char:14
+ Backup-SPFarm <<<< -Directory E:\Backups -BackupMethod Full -Verbose
+ CategoryInfo : InvalidData: (Microsoft.Share...mdletBackupFarm:SPCmdletBackupFarm) [Backup-SPFarm], NullReferenceException
+ FullyQualifiedErrorId : Microsoft.SharePoint.PowerShell.SPCmdletBackupFarm
VERBOSE: Leaving ProcessRecord Method of Backup-SPFarm.
VERBOSE: Leaving EndProcessing Method of Backup-SPFarm.
Do you have the SQL Server and the SharePoint products installed on the same system? Or is this a farm deployment with multiple servers?
In case of a farm deployment, you have the provide a UNC path of the backup folder. At least, that is what
Get-Help Backup-SPFarm -Parameter Directory
says.
Also, can you post the output of
Backup-SPFarm -Directory E:\Backups -BackupMethod Full -Verbose
Unfortunately, as I suspected this was something simple, but took a long time to work out (thanks to Microsoft's amazingly useful error message :p )
I had opened Sharepoint Management Shell before, but as a different user, which meant I did see a vital message that would point me in the right direction...
When I set up the server, there was no need to log into SQL Server other than to set up the service accounts (I think I logged in as my user, not the enterprise admin) and the enterprise admin didn't have any SQL Server permissions.
I suspected the line Add-PsSnapin Microsoft.SharePoint.Powershell hadn't worked properly, even though it said it did.
As I was trying to create a powershell script through the powershell editor I never opened Sharepoint Management Shell as the admin user I had logged in as.
Once I had seen the message in Sharepoint Management Shell, I googled it, and problem solved.
It would have been nice of Microsoft to display this instead of the object reference message!
In the question on the technet site, you have dumped a stack trace that shows an error accessing the configuration DB info from the registry (at, I guess, HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Shared Tools\Web Server Extensions\14.0\Secure\ConfigDB).
Could you check the permissions of this key and the identity of the w3wp processes ?

Using PowerShell and WMI to read Security log

I'm building a script to read the Security Log from several computers. I can read the Security log from my local machine with no problem when using the Get-EventLog command, but the problem with it is that I can't run it against a remote machine (the script is for powershell v1). The command below never returns any results, although that with any other LogFile, it works perfectly:
gwmi -Class Win32_NTLogEvent | where {$_.LogFile -eq "Security"}
I've done some research, and I seems to be a impersonation issue, but the -Impersonation option for the Get-WmiObject does not seem to be implemented. Is there anyway around this problem? The solution could be running the Get-EventLog on a remote machine somehow, or dealing with the impersonation issue so that the security log can be accessed.
Thanks
You could use .NET directly instead of going through WMI. The scriptblock below will give you the first entry in the security log
$logs = [System.Diagnostics.EventLog]::GetEventLogs('computername')
$security = $logs | ? {$_.log -like 'Security'}
$security.entries[0]
Have you tried to use the -Credential parameter? Also, use the filter parameter instead of where-object, it gets just the security events (where-object gets ALL events from all logs and only then performs the filtering)
gwmi Win32_NTLogEvent -filter "LogFile='Security'" -computer comp1,comp2 -credential domain\user

Resources