Solved

Error on the powershell script Error*** OpenPolicy -1073610729

Posted on 2016-11-17
5
21 Views
Last Modified: 2016-12-01
Hello,
I have powershell remoting enabled and able to run other scripts on the remote servers, but getting this error when trying to execute the script attached. Please advise.

Runing powershell in Admin mode with domain admin creds. All computers are on the same domain and that account has local rights. thank you.

Error I am getting:
UserRight    : System.Management.Automation.RuntimeException:  Granting SeServiceLogonRight to testtarget\username on \\servername 02OpenPolicy:   ***Error*** OpenPolicy -1073610729

Worked on only local computer
ComputerName : Localserver01
ServiceName  : QProcessor
UserRight    : OK
GetService   : OK
Change       : OK
Stop         : OK
Start        : OK

ComputerName : RemoteServer02
ServiceName  : QProcessor
UserRight    : System.Management.Automation.RuntimeException:  Granting SeServiceLogonRight to testtarget\username on \\Remote SErver02OpenPolicy:   ***Error*** OpenPolicy -1073610729
GetService   :
Change       :
Stop         :
Start        :
0
Comment
Question by:creative555
  • 4
5 Comments
 
LVL 4

Expert Comment

by:Kevin Stanush
ID: 41892459
That error means "RPC is unavailable".  Unfortunately, this is one of those 'unhelpful' errors in Windows.  You can get this error is the computer is OFF or not on the network, or if something on the computer is blocking the remote request, making the computer essentially the same as not being on the network.  These things can include a firewall or some other blocking mechanism.  Also check your name resolution for your computer address, ie make sure you can ping the address.
1
 

Accepted Solution

by:
creative555 earned 0 total points
ID: 41893685
I just tried this command invoke-command -computername serverpor02 {get-service *bits*}
and receive access denied.

My account is domain admin and is in the local admin group. Why is it getting access denied?


 Connecting to remote server serverpor02 failed with the following error message : Access is denied. For more information,
see the about_Remote_Troubleshooting Help topic.
    + CategoryInfo          : OpenError: (azdcstpor02:String) [], PSRemotingTransportException
    + FullyQualifiedErrorId : AccessDenied,PSSessionStateBroken
0
 

Assisted Solution

by:creative555
creative555 earned 0 total points
ID: 41902725
Someone helped me to fix this script. If someone can explain why it is working now with this modification than before, would be great!
No more errors.

#Use the following from the command line
#$ComputerList = Get-Content C:\cfscripts\Servers.txt
#Import-Csv .\Services.csv | % {.\Set-ServiceLogon.ps1 -ServiceName $_.ServiceName -ServiceAccount $_.ServiceAccount -ServicePassword $_.ServicePassword -ComputerList $ComputerList}

[CmdletBinding()]
Param(
       [string]$ServiceName,
       [string]$ServiceAccount,
       [string]$ServicePassword,
       [string[]]$ComputerList = @($ENV:ComputerName),
       $TimeoutStop = 120,        # Seconds
       $TimeoutStart = 120        # Seconds
)
$ScriptBlock = {
param($ComputerName,$ServiceName,$ServiceAccount,$ServicePassword,$TimeoutStop,$TimeoutStart)
$SetUserRight = $True
$LSAWrapper = @'
using System;
namespace MyLsaWrapper
{
    using System.ComponentModel;
    using System.Runtime.InteropServices;
    using System.Security;
    using System.Security.Principal;
    using LSA_HANDLE = IntPtr;

    [StructLayout(LayoutKind.Sequential)]
    struct LSA_OBJECT_ATTRIBUTES
    {
        internal int Length;
        internal IntPtr RootDirectory;
        internal IntPtr ObjectName;
        internal int Attributes;
        internal IntPtr SecurityDescriptor;
        internal IntPtr SecurityQualityOfService;
    }

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    struct LSA_UNICODE_STRING
    {
        internal ushort Length;
        internal ushort MaximumLength;
        [MarshalAs(UnmanagedType.LPWStr)]
        internal string Buffer;
    }

    sealed class Win32Sec
    {
        [DllImport("advapi32", CharSet = CharSet.Unicode, SetLastError = true), SuppressUnmanagedCodeSecurityAttribute]
        internal static extern uint LsaOpenPolicy(
           LSA_UNICODE_STRING[] SystemName,
           ref LSA_OBJECT_ATTRIBUTES ObjectAttributes,
           int AccessMask,
           out IntPtr PolicyHandle
        );

        [DllImport("advapi32", CharSet = CharSet.Unicode, SetLastError = true), SuppressUnmanagedCodeSecurityAttribute]
        internal static extern uint LsaAddAccountRights(
           LSA_HANDLE PolicyHandle,
           IntPtr pSID,
           LSA_UNICODE_STRING[] UserRights,
           int CountOfRights
        );

        [DllImport("advapi32")]
        internal static extern int LsaNtStatusToWinError(int NTSTATUS);

        [DllImport("advapi32")]
        internal static extern int LsaClose(IntPtr PolicyHandle);

    }

    sealed class Sid : IDisposable
    {
        public IntPtr pSid = IntPtr.Zero;
        public SecurityIdentifier sid = null;

        public Sid(string account)
        {
            sid = (SecurityIdentifier)(new NTAccount(account)).Translate(typeof(SecurityIdentifier));
            Byte[] buffer = new Byte[sid.BinaryLength];
            sid.GetBinaryForm(buffer, 0);

            pSid = Marshal.AllocHGlobal(sid.BinaryLength);
            Marshal.Copy(buffer, 0, pSid, sid.BinaryLength);
        }

        public void Dispose()
        {
            if (pSid != IntPtr.Zero)
            {
                Marshal.FreeHGlobal(pSid);
               pSid = IntPtr.Zero;
            }
            GC.SuppressFinalize(this);
        }
        ~Sid()
        {
            Dispose();
        }
    }


    public sealed class LsaWrapper : IDisposable
    {
        enum Access : int
        {
            POLICY_READ = 0x20006,
            POLICY_ALL_ACCESS = 0x00F0FFF,
            POLICY_EXECUTE = 0X20801,
            POLICY_WRITE = 0X207F8
        }
        const uint STATUS_ACCESS_DENIED = 0xc0000022;
        const uint STATUS_INSUFFICIENT_RESOURCES = 0xc000009a;
        const uint STATUS_NO_MEMORY = 0xc0000017;

        IntPtr lsaHandle;

        public LsaWrapper()
            : this(null)
        { }
        // // local system if systemName is null
        public LsaWrapper(string systemName)
        {
            LSA_OBJECT_ATTRIBUTES lsaAttr;
            lsaAttr.RootDirectory = IntPtr.Zero;
            lsaAttr.ObjectName = IntPtr.Zero;
            lsaAttr.Attributes = 0;
            lsaAttr.SecurityDescriptor = IntPtr.Zero;
            lsaAttr.SecurityQualityOfService = IntPtr.Zero;
            lsaAttr.Length = Marshal.SizeOf(typeof(LSA_OBJECT_ATTRIBUTES));
            lsaHandle = IntPtr.Zero;
            LSA_UNICODE_STRING[] system = null;
            if (systemName != null)
            {
                system = new LSA_UNICODE_STRING[1];
                system[0] = InitLsaString(systemName);
            }

            uint ret = Win32Sec.LsaOpenPolicy(system, ref lsaAttr,
            (int)Access.POLICY_ALL_ACCESS, out lsaHandle);
            if (ret == 0)
                return;
            if (ret == STATUS_ACCESS_DENIED)
            {
                throw new UnauthorizedAccessException();
            }
            if ((ret == STATUS_INSUFFICIENT_RESOURCES) || (ret == STATUS_NO_MEMORY))
            {
                throw new OutOfMemoryException();
            }
            throw new Win32Exception(Win32Sec.LsaNtStatusToWinError((int)ret));
        }

        public void AddPrivileges(string account, string privilege)
        {
            uint ret = 0;
            using (Sid sid = new Sid(account))
            {
                LSA_UNICODE_STRING[] privileges = new LSA_UNICODE_STRING[1];
                privileges[0] = InitLsaString(privilege);
                ret = Win32Sec.LsaAddAccountRights(lsaHandle, sid.pSid, privileges, 1);
            }
            if (ret == 0)
                return;
            if (ret == STATUS_ACCESS_DENIED)
            {
                throw new UnauthorizedAccessException();
            }
            if ((ret == STATUS_INSUFFICIENT_RESOURCES) || (ret == STATUS_NO_MEMORY))
            {
                throw new OutOfMemoryException();
            }
            throw new Win32Exception(Win32Sec.LsaNtStatusToWinError((int)ret));
        }

        public void Dispose()
        {
            if (lsaHandle != IntPtr.Zero)
            {
               Win32Sec.LsaClose(lsaHandle);
                lsaHandle = IntPtr.Zero;
            }
            GC.SuppressFinalize(this);
        }
        ~LsaWrapper()
        {
            Dispose();
        }
        // helper functions

        static LSA_UNICODE_STRING InitLsaString(string s)
        {
            // Unicode strings max. 32KB
            if (s.Length > 0x7ffe)
                throw new ArgumentException("String too long");
            LSA_UNICODE_STRING lus = new LSA_UNICODE_STRING();
            lus.Buffer = s;
            lus.Length = (ushort)(s.Length * sizeof(char));
            lus.MaximumLength = (ushort)(lus.Length + sizeof(char));
            return lus;
        }
    }
}
'@
$WmiReturnValueMap = @{    ## 'Change method of the Win32_Service class', https://msdn.microsoft.com/en-us/library/windows/desktop/aa384901(v=vs.85).aspx
       [uint32]0 =         'The request was accepted.'
       [uint32]1 =         'The request is not supported.'
       [uint32]2 =         'The user did not have the necessary access.'
       [uint32]3 =         'The service cannot be stopped because other services that are running are dependent on it.'
       [uint32]4 =         'The requested control code is not valid, or it is unacceptable to the service.'
       [uint32]5 =         'The requested control code cannot be sent to the service because the state of the service (Win32_BaseService.State property) is equal to 0, 1, or 2.'
       [uint32]6 =         'The service has not been started.'
       [uint32]7 =         'The service did not respond to the start request in a timely fashion.'
       [uint32]8 =         'Unknown failure when starting the service.'
       [uint32]9 =         'The directory path to the service executable file was not found.'
       [uint32]10 = 'The service is already running.'
       [uint32]11 = 'The database to add a new service is locked.'
       [uint32]12 = 'A dependency this service relies on has been removed from the system.'
       [uint32]13 = 'The service failed to find the service needed from a dependent service.'
       [uint32]14 = 'The service has been disabled from the system.'
       [uint32]15 = 'The service does not have the correct authentication to run on the system.'
       [uint32]16 = 'This service is being removed from the system.'
       [uint32]17 = 'The service has no execution thread.'
       [uint32]18 = 'The service has circular dependencies when it starts.'
       [uint32]19 = 'A service is running under the same name.'
       [uint32]20 = 'The service name has invalid characters.'
       [uint32]21 = 'Invalid parameters have been passed to the service.'
       [uint32]22 = 'The account under which this service runs is either invalid or lacks the permissions to run the service.'
       [uint32]23 = 'The service exists in the database of services available from the system.'
       [uint32]24 = 'The service is currently paused in the system.'
}
    $Return = "" | Select-Object -Property 'ComputerName', 'ServiceName', 'UserRight', 'GetService', 'Change', 'Stop', 'Start'
    $Return.ComputerName = $ComputerName
    $Return.ServiceName = $ServiceName
    Try {
            $Step = 'UserRight'
            If ($SetUserRight) {
                try {
                    Add-Type -TypeDefinition $LSAWrapper -ErrorAction SilentlyContinue 
                    $lsa = New-Object MyLsaWrapper.LsaWrapper($ENV:ComputerName)
                    [Void]$lsa.AddPrivileges($ServiceAccount.Trim('.\'),'SeServiceLogonRight')
                    $Return.$Step = 'OK'
                } catch {
                    Throw $_
                }
            } Else {
                $Return.$Step = 'SKIPPED'
            }
            $Step = 'GetService'
            If (-not ($ServiceWmi = Get-WmiObject -Class Win32_Service -Filter "Name='$($ServiceName)'" -ErrorAction Stop)) {
                Throw "Get-WmiObject -Class Win32_Service : Cannot find any service with service name '$($ServiceName)'."
            }
            $ServiceNet = Get-Service -Name $ServiceName -ErrorAction Stop
            $Return.$Step = 'OK'
            $Step = 'Change'
            $ChangeResult = $ServiceWmi.Change($null, $null, $null, $null, $null, $null, $ServiceAccount, $ServicePassword)
            If ($ChangeResult.ReturnValue -eq 0) {
                $Return.$Step = 'OK'
                $Step = 'Stop'
                If ($ServiceNet.Status -eq 'Running') {
                        $ServiceNet.Stop()
                }
                $ServiceNet.WaitForStatus('Stopped', [Timespan]::FromSeconds($TimeoutStop))
                $Return.$Step = 'OK'
                $Step = 'Start'
                $ServiceNet.Start()
                $ServiceNet.WaitForStatus('Running', [Timespan]::FromSeconds($TimeoutStart))
                $Return.$Step = 'OK'
            } Else {
                $Return.$Step = "$($ChangeResult.ReturnValue): $($WmiReturnValueMap[$ChangeResult.ReturnValue])"
            }
    } Catch {
            $Return.$Step = $_.Exception
    } Finally {
            $Return
    }
}

$ProgressCount = 0
ForEach ($ComputerName In $ComputerList) {
       Write-Progress -Activity "[$($ProgressCount)/$($ComputerList.Count)] Changing service account for '$($ServiceName)' to $($ServiceAccount)'" -Status $ComputerName -PercentComplete (100 * $ProgressCount / $ComputerList.Count)
       $ProgressCount += 1
       Invoke-Command -ComputerName $ComputerName -ScriptBlock $ScriptBlock -ArgumentList $ComputerName,$ServiceName,$ServiceAccount,$ServicePassword,$TimeoutStop,$TimeoutStart
}
Write-Progress -Activity "Done" -Completed 

Open in new window

0
 

Author Comment

by:creative555
ID: 41902728
mistake
0
 

Author Closing Comment

by:creative555
ID: 41908429
Thank you so much for your help!
0

Featured Post

Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Microsoft Windows Server Update Service (WSUS) is free for everyone, but it lacks of some desirable features like send an e-mail to the administrator with the status of all computers on the WSUS server. This article is based on my PowerShell script …
A procedure for exporting installed hotfix details of remote computers using powershell
Learn the basics of modules and packages in Python. Every Python file is a module, ending in the suffix: .py: Modules are a collection of functions and variables.: Packages are a collection of modules.: Module functions and variables are accessed us…
Video by: Mark
This lesson goes over how to construct ordered and unordered lists and how to create hyperlinks.

911 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now