Missing a Catch in Powershell

Etan77 1 Reputation point
2021-03-04T17:16:43.887+00:00

Hello again. Yesterday I posted a piece of code and asked for help with finding a missing Catch, and you guys were great and pointed it out. The problem is now the extra "}" was removed I'm getting the issue again, just on the last line. We think the issue is a Catch on line 292 is in "" as part of an "Add-Type" Command. We tried to take it out but when we did it pretty much broke everything. If you someone could take a look and tell us what we are doing wrong we'd appreciate it.

$privUserName=$args[0]
$prefix=$args[1] #this can be a domain or machine name
$privUserName=$prefix+"\"+$privUserName
$privPassword=ConvertTo-SecureString -AsPlainText $args[2] -Force
$creds= New-Object System.Management.Automation.PSCredential -ArgumentList $privUserName, $privPassword
invoke-command -ComputerName $args[3] -Credential $creds -ArgumentList $args[4] 
    param ($Password)
    $Password = ConvertTo-SecureString $Password -AsPlainText -Force
    #region C# Code to P-invoke LSA LsaStorePrivateData function.
    Add-Type @"
        using System;
        using System.Collections.Generic;
        using System.Text;
        using System.Runtime.InteropServices;
        namespace ComputerSystem
        {
            public class LSAutil
            {
                [StructLayout(LayoutKind.Sequential)]
                private struct LSA_UNICODE_STRING
                {
                    public UInt16 Length;
                    public UInt16 MaximumLength;
                    public IntPtr Buffer;
                }
                [StructLayout(LayoutKind.Sequential)]
                private struct LSA_OBJECT_ATTRIBUTES
                {
                    public int Length;
                    public IntPtr RootDirectory;
                    public LSA_UNICODE_STRING ObjectName;
                    public uint Attributes;
                    public IntPtr SecurityDescriptor;
                    public IntPtr SecurityQualityOfService;
                }
                private enum LSA_AccessPolicy : long
                {
                    POLICY_VIEW_LOCAL_INFORMATION = 0x00000001L,
                    POLICY_VIEW_AUDIT_INFORMATION = 0x00000002L,
                    POLICY_GET_PRIVATE_INFORMATION = 0x00000004L,
                    POLICY_TRUST_ADMIN = 0x00000008L,
                    POLICY_CREATE_ACCOUNT = 0x00000010L,
                    POLICY_CREATE_SECRET = 0x00000020L,
                    POLICY_CREATE_PRIVILEGE = 0x00000040L,
                    POLICY_SET_DEFAULT_QUOTA_LIMITS = 0x00000080L,
                    POLICY_SET_AUDIT_REQUIREMENTS = 0x00000100L,
                    POLICY_AUDIT_LOG_ADMIN = 0x00000200L,
                    POLICY_SERVER_ADMIN = 0x00000400L,
                    POLICY_LOOKUP_NAMES = 0x00000800L,
                    POLICY_NOTIFICATION = 0x00001000L
                }
                [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)]
                private static extern uint LsaRetrievePrivateData(
                            IntPtr PolicyHandle,
                            ref LSA_UNICODE_STRING KeyName,
                            out IntPtr PrivateData
                );
                [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)]
                private static extern uint LsaStorePrivateData(
                        IntPtr policyHandle,
                        ref LSA_UNICODE_STRING KeyName,
                        ref LSA_UNICODE_STRING PrivateData
                );
                [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)]
                private static extern uint LsaOpenPolicy(
                    ref LSA_UNICODE_STRING SystemName,
                    ref LSA_OBJECT_ATTRIBUTES ObjectAttributes,
                    uint DesiredAccess,
                    out IntPtr PolicyHandle
                );
                [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)]
                private static extern uint LsaNtStatusToWinError(
                    uint status
                );
                [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)]
                private static extern uint LsaClose(
                    IntPtr policyHandle
                );
                [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)]
                private static extern uint LsaFreeMemory(
                    IntPtr buffer
                );
                private LSA_OBJECT_ATTRIBUTES objectAttributes;
                private LSA_UNICODE_STRING localsystem;
                private LSA_UNICODE_STRING secretName;
                public LSAutil(string key)
                {
                    if (key.Length == 0)
                    {
                        throw new Exception("Key lenght zero");
                    }
                    objectAttributes = new LSA_OBJECT_ATTRIBUTES();
                    objectAttributes.Length = 0;
                    objectAttributes.RootDirectory = IntPtr.Zero;
                    objectAttributes.Attributes = 0;
                    objectAttributes.SecurityDescriptor = IntPtr.Zero;
                    objectAttributes.SecurityQualityOfService = IntPtr.Zero;
                    localsystem = new LSA_UNICODE_STRING();
                    localsystem.Buffer = IntPtr.Zero;
                    localsystem.Length = 0;
                    localsystem.MaximumLength = 0;
                    secretName = new LSA_UNICODE_STRING();
                    secretName.Buffer = Marshal.StringToHGlobalUni(key);
                    secretName.Length = (UInt16)(key.Length * UnicodeEncoding.CharSize);
                    secretName.MaximumLength = (UInt16)((key.Length + 1) * UnicodeEncoding.CharSize);
                }
                private IntPtr GetLsaPolicy(LSA_AccessPolicy access)
                {
                    IntPtr LsaPolicyHandle;
                    uint ntsResult = LsaOpenPolicy(ref this.localsystem, ref this.objectAttributes, (uint)access, out LsaPolicyHandle);
                    uint winErrorCode = LsaNtStatusToWinError(ntsResult);
                    if (winErrorCode != 0)
                    {
                        throw new Exception("LsaOpenPolicy failed: " + winErrorCode);
                    }
                    return LsaPolicyHandle;
                }
                private static void ReleaseLsaPolicy(IntPtr LsaPolicyHandle)
                {
                    uint ntsResult = LsaClose(LsaPolicyHandle);
                    uint winErrorCode = LsaNtStatusToWinError(ntsResult);
                    if (winErrorCode != 0)
                    {
                        throw new Exception("LsaClose failed: " + winErrorCode);
                    }
                }
                public void SetSecret(string value)
                {
                    LSA_UNICODE_STRING lusSecretData = new LSA_UNICODE_STRING();
                    if (value.Length > 0)
                    {
                        //Create data and key
                        lusSecretData.Buffer = Marshal.StringToHGlobalUni(value);
                        lusSecretData.Length = (UInt16)(value.Length * UnicodeEncoding.CharSize);
                        lusSecretData.MaximumLength = (UInt16)((value.Length + 1) * UnicodeEncoding.CharSize);
                    }
                    else
                    {
                        //Delete data and key
                        lusSecretData.Buffer = IntPtr.Zero;
                        lusSecretData.Length = 0;
                        lusSecretData.MaximumLength = 0;
                    }
                    IntPtr LsaPolicyHandle = GetLsaPolicy(LSA_AccessPolicy.POLICY_CREATE_SECRET);
                    uint result = LsaStorePrivateData(LsaPolicyHandle, ref secretName, ref lusSecretData);
                    ReleaseLsaPolicy(LsaPolicyHandle);
                    uint winErrorCode = LsaNtStatusToWinError(result);
                    if (winErrorCode != 0)
                    {
                        throw new Exception("StorePrivateData failed: " + winErrorCode);
                    }
                }
            }
        }
"@
    #endregion
    try 
{

param ($Password)
$Password = ConvertTo-SecureString $Password -AsPlainText -Force
#region C# Code to P-invoke LSA LsaStorePrivateData function.
Add-Type @"
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Runtime.InteropServices;
    namespace ComputerSystem
    {
        $WinlogonPath = "HKLM:\Software\Microsoft\Windows NT\CurrentVersion\Winlogon"
        $insecurePass=Get-ItemProperty -Path $WinlogonPath -Name "DefaultPassword" -ErrorAction SilentlyContinue
        if(!$insecurePass){
            New-ItemProperty -Path $WinlogonPath -Name "DefaultPassword" -PropertyType "string"
        }
        elseif($insecurePass.DefaultPassword.Length -ne 0)
        public class LSAutil
        {
            [StructLayout(LayoutKind.Sequential)]
            private struct LSA_UNICODE_STRING
            {
                public UInt16 Length;
                public UInt16 MaximumLength;
                public IntPtr Buffer;
            }
            [StructLayout(LayoutKind.Sequential)]
            private struct LSA_OBJECT_ATTRIBUTES
            {
                public int Length;
                public IntPtr RootDirectory;
                public LSA_UNICODE_STRING ObjectName;
                public uint Attributes;
                public IntPtr SecurityDescriptor;
                public IntPtr SecurityQualityOfService;
            }
            private enum LSA_AccessPolicy : long
            {
                POLICY_VIEW_LOCAL_INFORMATION = 0x00000001L,
                POLICY_VIEW_AUDIT_INFORMATION = 0x00000002L,
                POLICY_GET_PRIVATE_INFORMATION = 0x00000004L,
                POLICY_TRUST_ADMIN = 0x00000008L,
                POLICY_CREATE_ACCOUNT = 0x00000010L,
                POLICY_CREATE_SECRET = 0x00000020L,
                POLICY_CREATE_PRIVILEGE = 0x00000040L,
                POLICY_SET_DEFAULT_QUOTA_LIMITS = 0x00000080L,
                POLICY_SET_AUDIT_REQUIREMENTS = 0x00000100L,
                POLICY_AUDIT_LOG_ADMIN = 0x00000200L,
                POLICY_SERVER_ADMIN = 0x00000400L,
                POLICY_LOOKUP_NAMES = 0x00000800L,
                POLICY_NOTIFICATION = 0x00001000L
            }
            [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)]
            private static extern uint LsaRetrievePrivateData(
                        IntPtr PolicyHandle,
                        ref LSA_UNICODE_STRING KeyName,
                        out IntPtr PrivateData
            );
            [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)]
            private static extern uint LsaStorePrivateData(
                    IntPtr policyHandle,
                    ref LSA_UNICODE_STRING KeyName,
                    ref LSA_UNICODE_STRING PrivateData
            );
            [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)]
            private static extern uint LsaOpenPolicy(
                ref LSA_UNICODE_STRING SystemName,
                ref LSA_OBJECT_ATTRIBUTES ObjectAttributes,
                uint DesiredAccess,
                out IntPtr PolicyHandle
            );
            [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)]
            private static extern uint LsaNtStatusToWinError(
                uint status
            );
            [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)]
            private static extern uint LsaClose(
                IntPtr policyHandle
            );
            [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)]
            private static extern uint LsaFreeMemory(
                IntPtr buffer
            );
            private LSA_OBJECT_ATTRIBUTES objectAttributes;
            private LSA_UNICODE_STRING localsystem;
            private LSA_UNICODE_STRING secretName;
            public LSAutil(string key)
            {
                if (key.Length == 0)
                {
                    throw new Exception("Key lenght zero");
                }
                objectAttributes = new LSA_OBJECT_ATTRIBUTES();
                objectAttributes.Length = 0;
                objectAttributes.RootDirectory = IntPtr.Zero;
                objectAttributes.Attributes = 0;
                objectAttributes.SecurityDescriptor = IntPtr.Zero;
                objectAttributes.SecurityQualityOfService = IntPtr.Zero;
                localsystem = new LSA_UNICODE_STRING();
                localsystem.Buffer = IntPtr.Zero;
                localsystem.Length = 0;
                localsystem.MaximumLength = 0;
                secretName = new LSA_UNICODE_STRING();
                secretName.Buffer = Marshal.StringToHGlobalUni(key);
                secretName.Length = (UInt16)(key.Length * UnicodeEncoding.CharSize);
                secretName.MaximumLength = (UInt16)((key.Length + 1) * UnicodeEncoding.CharSize);
            }
            private IntPtr GetLsaPolicy(LSA_AccessPolicy access)
            {
                IntPtr LsaPolicyHandle;
                uint ntsResult = LsaOpenPolicy(ref this.localsystem, ref this.objectAttributes, (uint)access, out LsaPolicyHandle);
                uint winErrorCode = LsaNtStatusToWinError(ntsResult);
                if (winErrorCode != 0)
                {
                    throw new Exception("LsaOpenPolicy failed: " + winErrorCode);
                }
                return LsaPolicyHandle;
            }
            private static void ReleaseLsaPolicy(IntPtr LsaPolicyHandle)
            {
                Remove-ItemProperty -Path $WinlogonPath -Name "DefaultPassword" -Force
                uint ntsResult = LsaClose(LsaPolicyHandle);
                uint winErrorCode = LsaNtStatusToWinError(ntsResult);
                if (winErrorCode != 0)
                {
                    throw new Exception("LsaClose failed: " + winErrorCode);
                }
            }
        $decryptedPass = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($Password))
        # Store the password securely.
        $lsaUtil = New-Object ComputerSystem.LSAutil -ArgumentList "DefaultPassword"
        $lsaUtil.SetSecret($decryptedPass)
    } 
    catch 
            public void SetSecret(string value)
            {
                LSA_UNICODE_STRING lusSecretData = new LSA_UNICODE_STRING();
                if (value.Length > 0)
                {
                    //Create data and key
                    lusSecretData.Buffer = Marshal.StringToHGlobalUni(value);
                    lusSecretData.Length = (UInt16)(value.Length * UnicodeEncoding.CharSize);
                    lusSecretData.MaximumLength = (UInt16)((value.Length + 1) * UnicodeEncoding.CharSize);
                }
                else
                {
                    //Delete data and key
                    lusSecretData.Buffer = IntPtr.Zero;
                    lusSecretData.Length = 0;
                    lusSecretData.MaximumLength = 0;
                }
                IntPtr LsaPolicyHandle = GetLsaPolicy(LSA_AccessPolicy.POLICY_CREATE_SECRET);
                uint result = LsaStorePrivateData(LsaPolicyHandle, ref secretName, ref lusSecretData);
                ReleaseLsaPolicy(LsaPolicyHandle);
                uint winErrorCode = LsaNtStatusToWinError(result);
                if (winErrorCode != 0)
                {
                    throw new Exception("StorePrivateData failed: " + winErrorCode);
                }
            }
        }
    }
"@
#endregion
try 
{
    $WinlogonPath = "HKLM:\Software\Microsoft\Windows NT\CurrentVersion\Winlogon"
    $insecurePass=Get-ItemProperty -Path $WinlogonPath -Name "DefaultPassword" -ErrorAction SilentlyContinue
  #  if(!$insecurePass){
  #      New-ItemProperty -Path $WinlogonPath -Name "DefaultPassword" -PropertyType "string"
  #  }
  # Per testing on Windows 2016, if the DefaultPassword Key exists, Autologin will not leverage the LSA Encrypted Password for authentication
    if($insecurePass.DefaultPassword.Length -ne 0)
    {
        throw 'Failed to set auto logon password. The error was: "{0}".' -f $_

        Remove-ItemProperty -Path $WinlogonPath -Name "DefaultPassword" -Force

    $decryptedPass = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($Password))
    # Store the password securely.
    $lsaUtil = New-Object ComputerSystem.LSAutil -ArgumentList "DefaultPassword"
    $lsaUtil.SetSecret($decryptedPass)
} 
catch 
{
    throw 'Failed to set auto logon password. The error was: "{0}".' -f $_
}

}
Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,409 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Rich Matheisen 45,111 Reputation points
    2021-03-04T19:54:08.613+00:00
    1. Missing "{" at line #291 (inside the Here-String beginning on line #162)
    2. Missing "Catch" for the "Try" on line #157 (maybe Catch belongs on line #345? or just after line #321? or maybe in both places?!)

    Try using an editor with "code folding" or the ability to hide regions of code to collapse/hide long sections of text (like your Here-Strings). That makes it a lot easier to identify things like mis-matched parens or braces that are separated by large/cluttered areas of code that don't contain any problems. I'll recommend VS Code and Visual Studio, but there are certainly others.

    0 comments No comments

  2. MotoX80 32,246 Reputation points
    2021-03-04T21:35:16.8+00:00

    Line 6 is missing the -scriptblock and the starting bracket. And you'll need an ending bracket after line 156.

    Like this:

    74551-capture.jpg

    Not sure what you got going on here.

    74543-capture1.jpg

    You have a param statement as the first statement in a try block. I don't think that's going to work. A param should be the first statement in a script or scriptblock to define the parameters that are being passed.

    Looks like you copied your scriptblock and pasted it in the try statement?????

    My guess would be to delete lines 157-322.
    .

    0 comments No comments