• Home
  • PS
  • C#
  • Perl
  • MSSQL
  • MariaDB
  • Linux
  • Docker
  • MacOS
  • PG
  • Exchange Server
  • Windows
  • Other

Get-SharesWithShareAndNTFSPermissions

Details
Written by: po3dno
Category: Windows
Created: 18 September 2023
Hits: 392
<# 
License terms
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/.
#>

#get all Shares
$shares    = Get-WmiObject -Class Win32_Share 
$shareList = New-Object -TypeName System.Collections.ArrayList

foreach ($share in $shares) {
  
  #excluding default shares   
  if (($share.Name -notmatch '(?im)^[a-z]{1,1}\$') -and ($share.Name -notmatch '(?im)^[admin]{5,5}\$') -and ($share.Name -notmatch '(?im)^[ipc]{3,3}\$') -and ($share.Name -notmatch '(?im)^[print]{5,5}\$') )  {      
    
    $shareAccessInfo = ''
    $ntfsAccessInfo  = ''    
    
    #extract permissions from the current share
    $fileAccessControlList = Get-Acl -Path $($share.Path) | Select-Object -ExpandProperty Access | Select-Object -Property FileSystemRights, AccessControlType, IdentityReference    
    
    #excluding uncritical information as Builtin Accounts as Administratrators, System, NT Service and Trusted installer
    foreach ($fileAccessControlEntry in $fileAccessControlList) {
      if (($fileAccessControlEntry.FileSystemRights -notmatch '\d') -and ($fileAccessControlEntry.IdentityReference -notmatch '(?i)Builtin\\Administrators|NT\sAUTHORITY\\SYSTEM|NT\sSERVICE\\TrustedInstaller')) {      
        $ntfsAccessInfo += "$($fileAccessControlEntry.IdentityReference); $($fileAccessControlEntry.AccessControlType); $($fileAccessControlEntry.FileSystemRights)" + ' | '  
      }
    } #END foreach ($fileAccessControlEntry in $fileAccessControlList)

    $ntfsAccessInfo = $ntfsAccessInfo.Substring(0,$ntfsAccessInfo.Length - 3)
    $ntfsAccessInfo = $ntfsAccessInfo -replace ',\s?Synchronize',''   
    
    #getting share permissions   
    $shareSecuritySetting    = Get-WmiObject -Class Win32_LogicalShareSecuritySetting -Filter "Name='$($share.Name)'"               
    $shareSecurityDescriptor = $shareSecuritySetting.GetSecurityDescriptor()
    $shareAcccessControlList = $shareSecurityDescriptor.Descriptor.DACL          
    
    #converting share permissions to be human readable
    foreach($shareAccessControlEntry in $shareAcccessControlList) {
    
      $trustee    = $($shareAccessControlEntry.Trustee).Name      
      $accessMask = $shareAccessControlEntry.AccessMask
      
      if($shareAccessControlEntry.AceType -eq 0) {
        $accessType = 'Allow'
      } else {
        $accessType = 'Deny'
      }
        
      if ($accessMask -match '2032127|1245631|1179817') {          
        if ($accessMask -eq 2032127) {
          $accessMaskInfo = 'FullControl'
        } elseif ($accessMask -eq 1179817) {
          $accessMaskInfo = 'Read'
        } elseif ($accessMask -eq 1245631) {
          $accessMaskInfo = 'Change'
        } else {
          $accessMaskInfo = 'unknown'
        }
        $shareAccessInfo += "$trustee; $accessType; $accessMaskInfo" + ' | '
      }            
    
    } #END foreach($shareAccessControlEntry in $shareAcccessControlList)
    
       
    if ($shareAccessInfo -match '|') {
      $shareAccessInfo = $shareAccessInfo.Substring(0,$shareAccessInfo.Length - 3)
    }               
    
    #putting extracted information together into a custom object    
    $myShareHash = @{'Name'=$share.Name}
    $myShareHash.Add('FileSystemSPath',$share.Path )       
    $myShareHash.Add('Description',$share.Description)        
    $myShareHash.Add('NTFSPermissions',$ntfsAccessInfo)
    $myShareHash.Add('SharePermissions',$shareAccessInfo)
    $myShareObject = New-Object -TypeName PSObject -Property $myShareHash
    $myShareObject.PSObject.TypeNames.Insert(0,'MyShareObject')  
    
    #store the custom object in a list    
    $null = $shareList.Add($myShareObject)
  
  } #END if (($share.Name -notmatch '(?im)^[a-z]{1,1}\$') -and ($share.Name -notmatch '(?im)^[admin]{5,5}\$') -and ($share.Name -notmatch '(?im)^[ipc]{3,3}\$') )

} #END foreach ($share in $shares)

$shareList

Reset-ComputerMachinePassword

Details
Written by: po3dno
Category: Windows
Created: 01 September 2023
Hits: 443

Resets the machine account password for the computer.

Syntax

PowerShell
 
Reset-ComputerMachinePassword
     [-Server <String>]
     [-Credential <PSCredential>]
     [-WhatIf]
     [-Confirm]
     [<CommonParameters>]

Description

The Reset-ComputerMachinePassword cmdlet changes the computer account password that the computers use to authenticate to the domain controllers in the domain. You can use it to reset the password of the local computer.

Examples

Example 1: Reset the password for the local computer

PowerShell
 
Reset-ComputerMachinePassword

This command resets the computer password for the local computer. The command runs with the credentials of the current user.

Example 2: Reset the password for the local computer by using a specified domain controller

PowerShell
 
Reset-ComputerMachinePassword -Server "DC01" -Credential Domain01\Admin01

This command resets the computer password of the local computer by using the DC01 domain controller. It uses the Credential parameter to specify a user account that has permission to reset a computer password in the domain.

Example 3: Reset the password on a remote computer

PowerShell
 
$cred = Get-Credential
Invoke-Command -ComputerName "Server01" -ScriptBlock {Reset-ComputerMachinePassword -Credential $using:cred}

This command uses the Invoke-Command cmdlet to run a Reset-ComputerMachinePassword command on the Server01 remote computer.

For more information about remote commands in Windows PowerShell, see about_Remote and Invoke-Command.

Parameters

-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter
Aliases: cf
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False

-Credential

Specifies a user account that has permission to perform this action. The default is the current user.

Type a user name, such as User01 or Domain01\User01, or enter a PSCredential object, such as one generated by the Get-Credential cmdlet. If you type a user name, this cmdlet prompts you for a password.

This parameter was introduced in Windows PowerShell 3.0.

Type: PSCredential
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False

-Server

Specifies the name of a domain controller to use when this cmdlet sets the computer account password.

This parameter is optional. If you omit this parameter, a domain controller is chosen to service the command.

Type: String
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter
Aliases: wi
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False

Сброс пароля компьютера в домене без перезагрузки

Details
Written by: po3dno
Category: Windows
Created: 01 September 2023
Hits: 419

В таких случаях, системный администратор обычно просто заново включал вылетевший компьютер в домен. Но для этого компьютер нужно перезагружать. Мне захотелось найти альтернативу такому решению, и как оказалось, оно существует. Для этого можно воспользоваться Powershell.

  • Откройте консоль PowerShell
  • Введите команду
    Test-ComputerSecureChannel

    powershell тестируем связьс доменом

  • Если в ответ мы получим False, это означает что невозможно установить безопасный канал между клиентом и контроллером домена. А т.к. не устанавливается безопасный канал, то и залогинится с доменной учетной записью нельзя.
  • Чтобы сбросить и синхронизировать пароль компьютера в домене, воспользуемся командой
    Test-ComputerSecureChannel –Credential  -Repair

    reset computer account in AD

  • В появившемся окне введите имя пользователя, которому разрешено управлять учетной записью компьютера в домене и его пароль
  • После чего еще раз проверим возможность установки безопасного канала первой командой, если все получилось, она вернет True
  • Осталось выйти из системы и зайти под доменной учетной записью

Image optimization

Details
Written by: po3dno
Category: Windows
Created: 03 August 2023
Hits: 375

After applying updates to a Windows image, cleanup the image and then export it to a new file:

md c:\mount\Windows
md C:\mount\temp

Dism /Mount-Image /ImageFile:"C:\Images\install.wim" /Index:1 /MountDir:C:\mount\Windows

Dism /Cleanup-Image /Image=C:\mount\Windows /StartComponentCleanup /ResetBase /ScratchDir:C:\mount\temp

Dism /Unmount-Image /MountDir:C:\mount\Windows /Commit

Dism /Export-Image /SourceImageFile:C:\Images\install.wim /SourceIndex:1 /DestinationImageFile:C:\Images\install_cleaned.wim

WSUS tunning 2

Details
Written by: po3dno
Category: Windows
Created: 15 March 2023
Hits: 459

+ Build new Server 2019 machine

# could be 2016 or even 2012R2

  • vCPU = 4, vSocket = 1, RAM = 12 GB, PageFile = 32768 MB
  • HDD1 = 150 GB, used for C drive (System)
  • HDD2 = 3500 GB, used for D drive (WSUS data & content store, SQL Backup)
  • HDD3 = 50 GB, used for G drive (SQL Data)
  • HDD4 = 40 GB, used for H drive (SQL Temp DB)
  • HDD5 = 40 GB, used for L drive (SQL Log)

 

+ Install SQL Server 2019 Standard

 

+ Update Windows & SQL server with Microsoft Online Updates

 

+ Add WSUS role

 

+ Configure WSUS role 

  • Update Files and Languages: Update Files tab, tick Download express installation files.  Click OK
  • Automatic Approvals: Tick the Default Automatic Approval Rule.  Change the rule so that ONLY “Approve the update for all computers” is shown.  Click the Advanced tab. Ensure all check boxes are ticked.  Click OK
  • E-Mail Notifications: Tick Send status report, set to Weekly, set time to 7.30am, set Recipient
  • Set the outgoing SMTP server
  • Personalization: Click round selector “Show Computer and status from this server alone”

 

+ Install WSUS reporting

  • Find CLR type for SQL Server 2012 MSI and install. Its a challenge as the file is no longer on the Microsoft catalog site.
  • Find Report Viewer MSI and install.

 

+ Optimize WSUS Configuration

# The need is to modify web.config parameters. Within an elevated CMD shell;

  • sc stop wsusservice
  • cd "C:\Program Files\Update Services\WebServices\ClientWebService"
  • takeown /f web.config
  • icacls web.config /grant administrator:(F)
  • copy web.config web.config.org

 

  • notepad web.config

         # Find line;
            <add key="maxInstalledPrerequisites" value="400"/>
         # change this line to
            <add key="maxInstalledPrerequisites" value="800"/>

         # Find remark “MAXREQUESTLENGTH”, and then move to the line starting with
            <httpRuntime maxRequestLength="4096" />
         # change this line to
            <httpRuntime maxRequestLength="204800" executionTimeout="7200" />

         # Save web.config and exit notepad

 

+ Optimize IIS Configuration

# Within an elevated CMD shell;

  • # Run IIS Admin
  • %windir%\system32\inetsrv\inetmgr.exe
  • # Navigate to <servername> \ Application Pools \
  • # Right click on “WsusPool” and select Advanced Settings.
  • # Make the following changes in the respective sub-sections shown in front left column;

         General

                  Queue Length = 25000

         Rapid-Fail Protection
                  “Service Unavailable” Response = TcpLevel
                  Failure Interval (minutes) = 15
                  Maximum Failures = 5
         Recycling
                  Private Memory Limit (KB) = 0
                  Request Limit = 0
                  Virtual Memory Limit (KB) = 0

 

+ Restart Computer

  • After 5 minutes, initiate testing on the WUA machine.  No errors should occur, although scanning may take many minutes, even over an hour of slow low bandwidth WAN links.
  • Results may include either no updates available which most likely means the WSUS is still updating its self (which can take days), or available updates are shown and are available for WUA to download and install.
  1. Language pack offline install
  2. Rebuild search Index
  3. Классические настройки области уведомлений для изменения значков панели задач
  4. Fix heavy memory usage in ReFS

Page 2 of 5

  • 1
  • 2
  • 3
  • 4
  • 5

Login Form

  • Forgot your password?
  • Forgot your username?

Statistics

  • Users 2
  • Articles 164
  • Articles View Hits 149004