Microsoft Troubleshooting Packs - Advanced...

15
Essential Admin Scripts Contents Microsoft Troubleshooting Packs.....................................2 Establish Remote Session............................................3 Checking ACL Permissions on Files and Folders.......................4 Apply Security Settings for One Folder to Many Other Folders........9

Transcript of Microsoft Troubleshooting Packs - Advanced...

Page 1: Microsoft Troubleshooting Packs - Advanced …advancedtechnologysupportinc.com/website/labfiles/power... · Web viewI thought it would be worth starting off by mentioning the Microsoft

Essential Admin Scripts

Contents

Microsoft Troubleshooting Packs............................................................................................................2

Establish Remote Session........................................................................................................................3

Checking ACL Permissions on Files and Folders.......................................................................................4

Apply Security Settings for One Folder to Many Other Folders...............................................................9

Page 2: Microsoft Troubleshooting Packs - Advanced …advancedtechnologysupportinc.com/website/labfiles/power... · Web viewI thought it would be worth starting off by mentioning the Microsoft

Microsoft Troubleshooting Packs

I thought it would be worth starting off by mentioning the Microsoft Troubleshooting Packs that are bundled with Windows 7, Windows Server 2008 and above. The Microsoft Troubleshooting Packs are a series of detection, resolution and verification PowerShell scripts that you can use to diagnose different aspects of your servers, clients or network. Different packages are available to troubleshoot printers, networks, performance, power, Windows Update, etc.

To see which components are available for troubleshooting, simply run the dir command against the directory that holds the scripts. You will get a list like the one shown in the image below:

dir C:\Windows\diagnostics\system

To run a Troubleshooting Pack, you will first need to import the modules associated with the pack by running the following command from the Windows PowerShell command window:

Import-Module TroubleshootingPack

You then specify the Get-TroubleshootingPack cmdlet along with the desired pack location and pipe it to the Invoke-TroubleshootingPack cmdlet as follows:

Get-TroubleshootingPack <TroubleshootingPackLocation> | Invoke-TroubleshootingPack

The image below shows the options available when the Network Troubleshooting Pack is invoked:

Page 3: Microsoft Troubleshooting Packs - Advanced …advancedtechnologysupportinc.com/website/labfiles/power... · Web viewI thought it would be worth starting off by mentioning the Microsoft

Establish Remote Session

It is likely that you will want to run these scripts on a remote machine (e.g. a Windows 7 client). To do so, you will first need to connect to the remote machine from PowerShell using the “Enter-PSSession” cmdlet, as shown below:

Enter-PSSession -ComputerName remotehost -Credential domain\adminaccount

Replace ‘remotehost’ with the name or IP address of the remote machine and ‘domain\adminaccount’ with an admin level account on the domain. A dialog box will appear asking you to enter the password for the ‘domain\adminaccount’, following which you will have initiated a remote management session within PowerShell to execute commands on the remote machine.

Note: Ensure that the Windows Remote Management service is running and that you have configured the remote machine to allow Remote Management connections (using the winrm quickconfig command).

Page 4: Microsoft Troubleshooting Packs - Advanced …advancedtechnologysupportinc.com/website/labfiles/power... · Web viewI thought it would be worth starting off by mentioning the Microsoft

Checking ACL Permissions on Files and Folders

Whether for troubleshooting or simply for verification purposes, you will often find the need to check ACL permissions on files or folders. In larger environments where permissions are granted on files and folders on a regular basis, a permissions review may take place every quarter for example, and having an ACL report to compare with would come in handy.

To construct this script, you need the following main elements:

1) The path to check permissions on

2) The output path to create the report file

3) An Array to store each enumerated path

4) A ForEach loop to perform an operation on each object in the Array

5) The Get-Acl cmdlet.

The first part of the script asks the user for the path to check permissions on, as well as the path for the output file, and stores the results in a variable called $Path and $OutFilePath respectively. The Get-Date cmdlet is used twice; once to hold the current date and time in the $ReportDate variable and another to store the current date and time in a custom format within the $FileTS variable (which is used to create a timestamp for the output filename). The $ReportUser variable holds the name of the currently logged on user in the domain\username format.

An if statement is used to check if the path stored in the $OutFilePath variable exists. If it doesn’t exist, it will be created automatically using the New-Item (abbreviated to ni) cmdlet. The filename of the report is then appended to the output path and stored in the $FullOutFile variable.

Various variables, such as $RptNameInfo, $DateInfo and $PathInfo, are used to add the main pieces of information to the report. The $NumFolders and $NumFiles variables store the count of folders and files respectively, and uses the Get-ChildItem (or gci for short) cmdlet to pull back all the files and folders that fall under the location stored in $Path.

An Array is then created to store each of the enumerated file and folder paths and a ForEach loop handles the processing of the data within the Array. For each object in the Array, the path is converted from the PowerShell path to a standard system path. The size of each folder and file is obtained using the Measure-Object cmdlet and stored in a variable called $PathSizeCount. $PathSizeCountKB and $PathSizeCountMB store the size in KB and MB respectively. The path and size information for each folder or file is then added to the report.

Page 5: Microsoft Troubleshooting Packs - Advanced …advancedtechnologysupportinc.com/website/labfiles/power... · Web viewI thought it would be worth starting off by mentioning the Microsoft

Finally, the Get-Acl cmdlet is run against all the enumerated paths within $PSPath and formatted using the format-list (or fl for short) command. All this is added to the file specified in the $FullOutFile variable.

Script:

# set variables

$Path = Read-Host “Enter path to check permissions on”

$OutFilePath = Read-Host “Enter path to store output file”

$ReportDate = Get-Date -format F

$ReportUser = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name

$FileTS = Get-Date -format “yyyy.M.dd.hh.mm.ss”

$ReportFileTS = $FileTS.replace(‘.’,”-”)

# check if path to output file exists, if not create it

if(!(Test-Path -Path $OutFilePath))

{

ni -Path $OutFilePath –ItemType Directory -Force

}

# construct full path to output file

$FullOutFile = “$outfilepath\ACLCheckReport.$reportfilets.txt”

# add main report info

$RptNameInfo = “==============================`r`n ACL Permissions Report `r`n==============================”

$RptNameInfo | ft | Out-File $FullOutFile

$DateInfo = “Created on: $reportdate `r`nCreated by: $reportuser`r`n`==============================`r`n”

$DateInfo | ft | Out-File -append $FullOutFile

Page 6: Microsoft Troubleshooting Packs - Advanced …advancedtechnologysupportinc.com/website/labfiles/power... · Web viewI thought it would be worth starting off by mentioning the Microsoft

$NumFolders = (gci $Path -recurse | where {$_.PsIsContainer}).Count

$NumFiles = (gci $Path -recurse | where {$_.GetType() -match “fileInfo”} | measure-object).Count

$PathInfo = “Listing permissions for: $path ( Folders: $numfolders | Files: $numfiles )`r`n”

$PathInfo | ft | Out-File -append $FullOutFile

# fill array with folders and files

[Array] $Objects = gci -path $Path -force -recurse

# fill array with folders only

#[Array] $Objects = gci -path $path -force -recurse | Where {$_.PSIsContainer}

# process data in array

ForEach ($Object in [Array] $Objects)

{

# convert pspath to full system path

$PSPath = (Convert-Path $Object.PSPath)

# get the size of each folder/file

$PathSizeCount = (gci $PSPath -recurse | Measure-Object -property length -sum).Sum

$PathSizeCountKB = “{0:N2}” -f ($PathSizeCount / 1KB)

$PathSizeCountMB = “{0:N2}” -f ($PathSizeCount / 1MB)

# add path and size info for each folder/file to the report

$PathSizeInfo = (“Path: $PSPath `r`nSize (KBytes): $PathSizeCountKB | Size (MBytes): $PathSizeCountMB”)

$PathSizeInfo | ft | Out-File -append $FullOutFile

# run the get-acl command using the list of enumerated paths and format accordingly

Get-Acl -path $PSPath | fl -property Owner,AccessToString | Out-File -append $FullOutFile

Page 7: Microsoft Troubleshooting Packs - Advanced …advancedtechnologysupportinc.com/website/labfiles/power... · Web viewI thought it would be worth starting off by mentioning the Microsoft

}

the following code within the script makes it so that only folders and sub-folders are enumerated as part of the permissions list:

[Array] $folders = gci -path $path -force -recurse | Where {$_.PSIsContainer}

Then, add a comment tag to the following code within the script to disable files from being enumerated as part of the permissions list:

[Array] $objects = gci -path $path -force –recurse

# EOF

Page 8: Microsoft Troubleshooting Packs - Advanced …advancedtechnologysupportinc.com/website/labfiles/power... · Web viewI thought it would be worth starting off by mentioning the Microsoft

The following shows a sample ACL Permissions Report.

Note: The format of the report can be modified by changing the “ft” and “fl” portions of the script accordingly.

Page 9: Microsoft Troubleshooting Packs - Advanced …advancedtechnologysupportinc.com/website/labfiles/power... · Web viewI thought it would be worth starting off by mentioning the Microsoft

Apply Security Settings for One Folder to Many Other Folders

Scenario: In the past when I created a folder I would manually set the security when I was finished. If I had to create 15 folders, I would manually set the security on the 15 folders. Now I need to be able to show that the 15 folders have the same security settings. Let’s create a script that will copy the security settings from one folder, and then apply the same security settings to newly created folders.

The complete CreateFolderSetSecurity.ps1 script is seen here.

CreateFolderSetSecurity.ps1

$templateFolder = "C:\fso" if(-not(Test-Path -path $templateFolder)) { "Folder $templateFolder not found. Check path and try again." Exit } $templateAcl = Get-ACL -path $templateFolder $path = "C:\myTest" $folderName = "TestFolder"

For($i = 0; $i -le 5 ; $i++) { New-Item -path $path -name $folderName$i -itemType Directory -force Set-Acl -path (Join-Path -path $path -childpath $folderName$i) -aclObject $templateAcl }

Let’s break down the script:

The first thing you need to do is to assign the path to use for the template folder. Use the $templateFolder variable to hold the path to the template folder. The template folder is the folder that has been given the security settings you wish to duplicate. To aid in managing the security settings, you may wish to give your template folders a naming convention that will assist in keeping track of the folders. For example, something like __HRGroupTemplate might be useful. By prefixing each folder name with a double underscore (__), you will cause all of your template folders to percolate to the top of the folder listing in Windows Explorer. This is seen in this image:

Page 10: Microsoft Troubleshooting Packs - Advanced …advancedtechnologysupportinc.com/website/labfiles/power... · Web viewI thought it would be worth starting off by mentioning the Microsoft

The template folder that is used in the CreateFolderSetSecurity.ps1 script is the C:\fso folder. The security on this folder has been modified to explicitly deny the guest user account access. This is seen here:

If you are using a different folder than the C:\fso folder for your template folder (which is more than likely), you will need to modify the line of code that is seen here:

$templateFolder = "C:\fso"

If the CreateFolderSetSecurity.ps1 Windows PowerShell script is not able to access the template folder that is referenced by the path stored in the $templateFolder variable, the rest of the script will be meaningless. The Test-Path cmdlet is used to determine if the template folder exists. The Test-Path cmdlet returns true if the folder exists. It returns false if the folder does not exist. This is seen here:

Page 11: Microsoft Troubleshooting Packs - Advanced …advancedtechnologysupportinc.com/website/labfiles/power... · Web viewI thought it would be worth starting off by mentioning the Microsoft

PS C:\> Test-Path -Path c:\fso True PS C:\> Test-Path -Path c:\fso12 False PS C:\>

Because the Test-Path cmdlet returns true or false, the return value can be treated as a Boolean value, and a shortcut version of the if statement can be used. You would read the command as meaning "if the folder exists, do something." This is illustrated here:

PS C:\> if(Test-Path -Path c:\fso) { "it exists" } it exists PS C:\> if(Test-Path -Path c:\fso12) { "it exists" } PS C:\>

If the folder does not exist, a message is displayed on the Windows PowerShell console and the script will exit. The –not operator is used to test for the absence of the folder. This is seen here:

if(-not(Test-Path -path $templateFolder)) { "Folder $templateFolder not found. Check path and try again." Exit }

Once you have ensured that the template folder exists, use the Get-Acl cmdlet to obtain the System.Security.AccessControl.DirectorySecurity .NET Framework class. The DirectorySecurity object will be used when setting the security on the new folders. This is seen here:

$templateAcl = Get-ACL -path $templateFolder

Two more variables are assigned values. The first variable is the path that will hold the newly created folders. The Test-Path cmdlet is not used to check for the existence of the folder referenced by the $path variable because this folder will be created if it does not already exist. The second variable, $folderName, holds the folder name prefix. In this example, each of the five folders that are created will begin with the name TestFolder. This section of the script is shown here:

$path = "C:\myTest" $folderName = "TestFolder"

To create multiple folders with the same base name, use the for statement, which is composed of three parts.

The opening section of the for statement is seen here:

For($i = 0; $i -le 5 ; $i++) {

Inside the script block (curly brackets), the New-Item cmdlet is used to create a new directory. The path is contained in the $path variable, and the name of the new folder is a concatenation of the folder name prefix stored in the $folderName variable and the current value of the $i

Page 12: Microsoft Troubleshooting Packs - Advanced …advancedtechnologysupportinc.com/website/labfiles/power... · Web viewI thought it would be worth starting off by mentioning the Microsoft

variable. The –force parameter is used to ensure the folder will be created even if the parent folder does not exist. This line of code is seen here:

New-Item -path $path -name $folderName$i -itemType Directory –force

Once the new folder is created, the Set-Acl cmdlet is used to set the security on the new folder. The path to the new folder is created by using the Join-Path cmdlet. The -path parameter of the Join-Path cmdlet points to the parent path. The –childpath parameter points to the last portion of the folder path. Because the Join-Path command is placed inside a set of parentheses, this part of the Set-Acl command is evaluated first. The last parameter of the Set-Acl cmdlet that is used is the –aclObject parameter. It receives the DirectorySecurity object that is stored in the $templateAcl variable. This is seen here:

Set-Acl -path (Join-Path -path $path -childpath $folderName$i) -aclObject $templateAcl }

When the script is run, the folder structure shown here is created:

The last thing that needs to be done is to inspect the security on the folders to ensure that the custom access control lists were properly applied. As seen in the following image, the script worked perfectly for our purposes:

Page 13: Microsoft Troubleshooting Packs - Advanced …advancedtechnologysupportinc.com/website/labfiles/power... · Web viewI thought it would be worth starting off by mentioning the Microsoft