Raimund Andrée – NTFSSecurity – Usage Scenario – Day 1

Background

Now that we have downloaded and installed Raimund Andrée’s NTFSSecurity in one of the standard PowerShell Module’s folder, we are ready to write a little test code and see how well it works.

Code

Script

getNTFSPermissions.ps1


param (
      [string]$file
    , [string]$folder
    , [string]$fileExt
 )
Set-StrictMode -Version 2.0
 
#Import NTFSSecurity
Import-Module NTFSSecurity

# Declare variables
[string] $CONST_FILEMODE_DIRECTORY = "d-----";
[boolean] $fileCheck = $false;

if ([string]::IsNullOrEmpty($file))
{
    $fileCheck = $false;
}
else
{
    $fileCheck = $true;

}

if ($fileCheck -eq $false)
{

    if ([string]::IsNullOrEmpty($folder))
    {
    
        $folder = Get-Location
        
    }
    
}

function getNTFSFile([string] $_fileLocal)
{

       
    Get-NTFSAccess -Path $_fileLocal

    
} #getNTFSFile()    

function getNTFSFolder([string] $folderLocal, [string] $fileExtLocal)
{

    #Declare Local variables
    [string]$_file = $null;
    [string]$_fileFullName = $null; 
    [string]$_fileExt = $null;
    [string]$_fileMode = $null;   
    [boolean]$_fileExtMatch = $true;

    # Get files
    Get-ChildItem $folderLocal | foreach {

       $_file = $_
       $_fileFullName =  $_.FullName 
       $_fileExt = $_.extension
       $_fileMode = $_.mode    
       
       <# #$_file #$_fileFullName #$_fileMode #>
       
       $_fileExtMatch = $true;

       <# If we are matching on file extensions let us see whether it matches #>
       if ([string]::IsNullOrEmpty($fileExt ))
       {
            $_fileExtMatch = $true;
       }
       else
       {
       
            if ( $_fileExt -eq $fileExtLocal )
            {
                $_fileExtMatch = $true;
            }
            else
            {
                $_fileExtMatch = $false;
                
                #"file extension $_fileExt does not match $fileExt "
            }
       
       }
       
       
       if (`
                 ($_fileMode -ne $CONST_FILEMODE_DIRECTORY )`
            -and ( $_fileExtMatch)`
          )
       {
       
            Get-NTFSAccess -Path $_fileFullName -ExcludeInherited

       }
        
    }
    
} #getNTFSFolder()  

if ($fileCheck -eq $true)
{

    getNTFSFile $file 

}

elseif ($fileCheck -eq $false)
{

    getNTFSFolder $folder $fileExt

}


 

Sample

Get Permissions for Excel files

Code


powershell .\getNTFSPermissions.ps1 -folder C:\temp -fileExt .xlsx

Output

Get Permissions for Scheduled Tasks ( Local to machine)

Code


powershell .\getNTFSPermissions.ps1  -folder C:\Windows\System32\Tasks

Output

Raimund Andrée – NTFSSecurity

Introduction

As  a quick follow-up to our last post, “Task Scheduler – The user account is unknown, the password is incorrect, or the user account does not have permission to modify the task” ( Link ), googled for available utilities that list NTFS permissions.

Utilities

Here are some available options:

  1. Microsoft
    • icacls
  2. Raimund Andrée – NTFSSecurity
    ( powershell module )

Raimund Andrée – NTFSSecurity

We settled on “Raimund Andrée – NTFSSecurity“, we will discuss the reasons later.

Repository

URL

  1. GitHub
    • Releases

Image

Tabulated

Version File Size
NTFSSecurity 4.2.3 NTFSSecurity.zip 183 KB

 

Installation

Prepare Downloaded File

Once downloaded please unblock file…

Obviously to unblock, please click the “Unblock” button.

 

Identify Install Folder

In Powershell parlance the files are delivered as modules and need to be placed in one of the folders listed in the PSModulePath environment variable.

Command


set PSModulePath

Output

Image

Tabulated

  1. C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules\
  2. C:\Program Files\WindowsPowerShell\Modules\
  3. SQL Server
    • C:\Program Files (x86)\Microsoft SQL Server\110\Tools\PowerShell\Modules\
    • C:\Program Files (x86)\Microsoft SQL Server\120\Tools\PowerShell\Modules\
    • C:\Program Files (x86)\Microsoft SQL Server\130\Tools\PowerShell\Modules\
  4. Baseline Configuration Analyzer
    • C:\Program Files\Microsoft Baseline Configuration Analyzer 2\Modules\

 

Vendor’s Installation Guideline – Location

Image

How to install
Link

 

Explanation

  1. Development
    • During development I think it is best to place in the contextual user’s documents\windows\powershell folder
  2. Production
    • In production, depending on your Version of Power
      • <= v4 C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules
      • >= V4
        • C:\Program Files\WindowsPowerShell\Modules

Deploy

Script

Sample


set _folderSrc=C:\downloads\raandree\NTFSSecurity\NTFSSecurity

set _folderDestUserSpecific=C:\Users\%username%\Documents\WindowsPowerShell\Modules\NTFSSecurity
set _folderDestPowerShellModule=C:\Program Files\WindowsPowerShell\Modules

set _folderDest=%_folderDestPowerShellModule%\NTFSSecurity

if not exist "%_folderDest%" mkdir "%_folderDest%"

xcopy "%_folderSrc%" "%_folderDest%" /s /D

Output

Validation

Script

Sample


# Import NTFSSecurity
Import-Module NTFSSecurity

#get help on Get-NTFSAccess
get-help Get-NTFSAccess

Output

Dedicated

Dedicates to MSFT’s own Raimund Andrée.

References

  1. Tutorial
    • NTFSSecurity Tutorial 1 – Getting, adding and removing permissions
      Link
    • NTFSSecurity Tutorial 2 – Managing NTFS Inheritance and Using Privileges
      Link
  2. Script Center
    • File System Security PowerShell Module 4.2.3
      Link

Installing Powershell v5 on Windows 7

Background

In the last few weeks I have wanted to devote a bit of personal time to look more into SSL Certificates.

With LetsEncrypt it is no longer don’t have the money excuse.

The reference implementation for LetsEncrypt on MS Windows Platform is the groundbreaking work done by ebekker.

 

eBekker?

eBekker has in Eugene Bekker

IT is an Interesting Business.  Everyone goes by first initial and their last name.

So who is Eugene Bekker, let us just bring up is profile on the fighting Identity Crime web site.

Link

letsEncrypt On Windows

Here are the Client Options for availing LetsEncrypt on Windows.

Link

 

ACMESharp

To install ACMESharp, I know I need to read the documentation.

And,  some of that information is available as a wiki file here.

ACMESharp Installation

PowerShell Gallery

From everything I am reading I will be better off with PowerShell Gallery.

And, the easiest path to PowerShell Gallery is to b running PowerShell Version 5.

 

Status

What version of Powershell do we currently have in place…

Command

Launched OS Command shell and entered “powershell –$PSVersionTable” and got back the image pasted below.

Image

Powershell-Command-PSVersionTable-20170710--0726PM

Explanation

PSVersion is 2.0.

Download

Download PowerShell v5 from here.

PowerShell is bundled as Windows Management Framework 5.0.

ChooseTheDownloadYouWant_20170710_1021PM

There are two offerings for Windows 7; and those are:

  1. Win7AndW2K8R2-KB3134760-x64.msu
    • 64-bit OS
  2. Win7-KB3134760-x86.msu
    • 32-bit OS

We have a 64-bit OS and so we sip the -x85 package and choose the […….]–x64.msu

 

Installation

Screenshots

Do you want to install KB3134760?

WindowsUpdateStandaloneInstaller-ConfirmInstallation

License Agreement

license

Installing….Stage – Begining

tTheUpdatesAreBeingInstalled

Installing….Stage – Progressing

TheUpdatesAreBeingInstalled_20170710_1027PM

Installation Complete

InstallComplete

Rebooted computer and got some sleep.

Wish I could say beauty sleep, but not so lucky.

 

Confirmation

Command

From OS Shell command line issued “powershell –$PSVersionTable” and got back the image pasted below.

Image

Powershell-Command-PSVersionTable-20170710--0753AM

Explanation

  1. PSVersion is 5.0.10586.1167
  2. CLRVersion is 4.0.30319.4200

Listening

It is a long road to the Heights!

In the word of one Jim Croce…

And give me the number if you can find it
So I can call just to tell ’em I’m fine and to show
I’ve overcome the blow, I’ve learned to take it well

I think about a love that I thought would save me

Music :- Link
Lyrics :- Link

Moral

Though Jim Croce recorded Operator in 72, I know just like he did then.

The love for SSL will not save me.

…. There is no one there that I really I want to talk to.

It is just another software to pile on my machine.

 

References

  1. How to Install Windows Powershell v4.0
    Link
  2. Identify .Net Version
    • Rodney Viana – MSFT
      • Identifying the .NET version you are running (2.0, 4.5, 4.5.1 or 4.5.2)
        Link
    • Techno gyan by Vijayshinva Karnure – Support Escalation Engineer (Microsoft)
      • Where is ASP.NET 4.5 …wait Where is .NET 4.5 ?
        Link
  3. Install Material
    • PowerShell v5.0

PowerShell – Error – “Missing closing ‘)’ in expression” – Param // Set-StrictMode

Background

Getting an error when I try to run a PowerShell script.

The PowerScript accepts parameters and thus it includes the Param Statement.

It also enforces a Strict Mode; principally it requires that all variables should be explicitly declared.

Error Message

Here is the error message:


Missing closing ')' in expression.
+     <<<< [alias("F")]
    + CategoryInfo          : ParserError: (CloseParenToken:TokenId) [], ParseException
    + FullyQualifiedErrorId : MissingEndParenthesisInExpression

 

Code

Original Code

Here is the original code:

Set-StrictMode -Version 1
[CmdletBinding()]
Param
(
   [Parameter(Mandatory=$true, position=0, HelpMessage="Filename input")]
   [alias("F")]
   [string]$filename="services.txt"
)

Revised Code


[CmdletBinding()]
Param
(
	[Parameter(Mandatory = $false, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
	[alias("f")]
	[string]$filename="services.txt"
)

Set-StrictMode -Version 1

Explanation

  1. The very first line needs to be the Function argument definition
    • Param
  2. And, the “Set-StrictMode -Version #” can then follow
    • Set-StrictMode -Version 1
    • Or  “Set-StrictMode -Version 2

Scheduled Task – Powershell Starts, but does not complete

Background

Scheduled a Task, but it is not completing.

 

Task Scheduler

Let us review the Task…

Task Overview

 

Task – Action

TroubleShooting

Task Manager

Launched Task Manager and looked for the Task.

One pointed to do so is to look at Command Line Column.

Image

 

Findings

  1. Command Line
    • C:\Windows\System32\notepad.exe “E:\Scripts\Service\ServiceMgmt\serviceStart.ps1”

 

Interpretation

It seems that ps1 files are attached to notepad.exe

 

Why Notepad?

 

Jacob Zinicola // How To Geek
How to Configure Windows to Work with PowerShell Scripts More Easily
Link

PowerShell is not associated to the .PS1 file extension by default.
Windows sets the default action for .PS1 files to open them in Notepad, instead of sending them to the PowerShell command interpreter.
This is to directly prevent accidental execution of malicious scripts when they’re simply double-clicked.

 

Workaround?

Associate PS1 with Powershell.exe

It is easy enough to associate ps1 files with Powershell.exe and get PS1 files to run directly from the command line.

 

Scheduled Task

But, even after this change, was still unable to get PS1 to run directly as a scheduled task.

 

True Solution

The only true solution is the one where we  a write a command file and invoke the PS1 script in the cmd file…


set "_app=c:\windows\system32\WindowsPowerShell\v1.0\powershell.exe"
set "_PSExecutionPolicy=bypass"

set "_currentFolder=%cd%"
set "_script=serviceStart.ps1"
set "_scriptFullName=%cd%\%_script%"

%_app% -NoProfile -Executionpolicy %_PSExecutionPolicy% -file %_scriptFullName%

 

References

  1. Warren Frame // Cookie Monster
    • Troubleshooting PowerShell Based Scheduled Tasks
      Link
  2. Stack Overflow
    • Powershell script does not run via Scheduled Tasks
      Link
  3. Weekend Scripter: Use the Windows Task Scheduler to Run a Windows PowerShell Script
    Link
  4. How to Geek
    • Jacob Zinicola
      • How to Configure Windows to Work with PowerShell Scripts More Easily
        Link

 

Windows – Start Services thru Powershell

Background

I wish I can be like the rest of these guys who write scripts just for fun.

Oh No, Not yours truly.

Windows Patches were applied to our computers and unfortunately SQL Server Services did not start.

I mean they are set for auto-start, but that didn’t help me out this time.

Code

And, so need to develops scripts that can be ran manually or scheduled.

outline

  1. service.txt
    • Text file that contains the list of Services
  2. serviceStart.ps1
    • PowerShell script that starts each service in above list if service is not running
  3. invoke.cmd
    • Invoke PowerShell Script

service.txt

MSSQLSERVER
SQLSERVERAGENT

serviceStart.ps1

Set-StrictMode -Version 1

[System.Collections.ArrayList] $listofServices = $null;
[string] $log = $null;
[string] $filename =$null;
[string] $fileLog =$null;


[object] $objService=$null;

$listofServices = New-Object System.Collections.ArrayList;

$filename = "services.txt"
$fileLog = "log\serviceAutomation.log";


function folderMgmt($fileLog) 
{

	[string] $logFolder = $null;
	[boolean]$folderExist= $false;
	

	## prepare diagnostic statement
	$log = "Reviewing file {0} ..." -f $fileLog;

	## write debug statement
	Write-Debug -message $log
	Write-Host $log
	
	## Get Log Folder from filename
	$logFolder = Split-Path -Path $fileLog;


	## prepare diagnostic statement
	$log = "Log Folder is  {0} ..." -f $logFolder;

	## write debug statement
	Write-Debug $log
	
	## prepare diagnostic statement
	$log = "Check if folder {0} exist!" -f $logFolder;

	## write debug statement
	Write-Debug -message $log

	
	## Check Folder, if exists
	$folderExist = Test-Path $logFolder
	
	
	# if folder does not exist
	if ($folderExist -eq $false )
	{
	
		## prepare diagnostic statement
		$log = "Find File {0}, create folder {1}" -f $fileLog, $logFolder;

		## write debug statement
		Write-Debug -message $log

		## Create Folder
		New-Item $logFolder -type directory >$null;

	} ## if folder does not exist
	
} ## function folderMgmt


function readFile($filename)
{

	foreach ($service in get-content $filename)
	{

		## Add read line into $listofServices Array
		$listofServices.Add($service) >$null;

		$log = "Read {0}" -f $service;

		Write-Debug -message $log
		
	}

}
 

function processFile($fileLog)
{

	## Iterate list of Services
	$listofServices | ForEach-Object {

		# get service Name
		$service = $_;
		
		# get Service Node
		$objService = Get-Service $service;
		
		# get Service Status
		$serviceStatus = $objService.Status;
		
		# Display Current Step
		$log = "Processing Service {0}, Status {1}" -f $service, $serviceStatus;

		Write-Host $log
		
		# If Service is stopped
		if ($serviceStatus -eq "Stopped")
		{
		
			# Start Service
			Start-Service -InputObject $objService  -PassThru | Format-List >> $fileLog
		
		}

		
	}

}

folderMgmt($fileLog);
  
readFile($filename) >$null;

processFile($fileLog) >$null; 

	

invoke.cmd


set "_app=c:\windows\system32\WindowsPowerShell\v1.0\powershell.exe"
set "_PSExecutionPolicy=bypass"

set "_currentFolder=%cd%"
set "_script=serviceStart.ps1"
set "_scriptFullName=%cd%\%_script%"

%_app% -NoProfile -Executionpolicy %_PSExecutionPolicy% -file %_scriptFullName%

Source Code Control

GitHub

Availed on GitHub here.

References

  1. Microsoft – Developer Network
    • Microsoft.PowerShell.Management
      • Split-Path
        Link
      • Service
  2. Microsoft Technet
    • Hey, Scripting Guy! Blog
      • Avoid PowerShell Errors by Initializing Variables
        Link
    • Technet Magazine
      • Windows PowerShell Scripting One Line at a Time
        Link
  3. Windows IT Pro
    • Creating your own PowerShell Functions
      Link
    • Arrays & Functions
      Link
  4. PwrShell.Net
    • Array
      • Back to Basics Arrays
        Link
  5. ss64.com
    • Arrays
      • Syntax Arrays
        Link