I have written a C# desktop application, using System.Management.Automation, that remotes over to machines in our network and does diagnostics to make sure that they are all configured per our organization's policies.
PSCredential Credentials = new PSCredential(Username, Password);
WSManConnectionInfo ThisConnection = new WSManConnectionInfo(false, ThisSystem.IpName, 5985, "/wsman",
"http://schemas.microsoft.com/powershell/Microsoft.PowerShell", Credentials);
using (Runspace ThisRunspace = RunspaceFactory.CreateRunspace(ThisConnection))
{
ThisRunspace.Open();
using (PowerShell ThisShell = PowerShell.Create())
{
ThisShell.Runspace = ThisRunspace;
To get the banner, which is in the group policy, it does the following code to execute the powershell command
ThisShell.Commands.Clear();
ThisShell.AddScript("echo N | gpupdate /force");
ThisShell.AddScript("gpresult /h c:\\Windows\\Temp\\gpdata.html /F");
ThisShell.AddScript("type c:\\Windows\\Temp\\gpdata.html");
List<String> GroupPolicy = ThisShell.Invoke().Select(x => x.ToString()).ToList();
Which should create that html file with the group policy data for that machine. And it does, as long as I have manually logged into that machine, with the same credentials. If I have not, I get nothing. I run other powershell commands just like this and get the results just fine, but for some reason this command for getting the group policy will only work for machines where I have logged in manually (using remote desktop) at least once, and with thousands of servers to check, this is not an option.
I thought it might be that logging in manually created the home folder for the admin account I am using, but that can't be because I am getting the results of other powershell commands that I piped to files. I thought it might be that logging in manually updated the group policy on that machine, but that also cannot be, I think, because I added the gpupdate /force
, and it made no difference.
Any clues?
From the documentation for gpresult:
Because you can apply overlapping policy settings to any computer or user, the Group Policy feature generates a resulting set of policy settings when the user logs on. gpresult displays the resulting set of policy settings that were enforced on the computer for the specified user when the user logged on.
Since you are talking about enforcing policy on servers, which should not be expected to normally have a user logged in, perhaps you can try adding the /scope computer
option to get just the machine policies, which should always be available.