Looking at Local Groups Using PowerShell on MCPMag

My latest series on MCPMag talks about local groups and using PowerShell (of course Winking smile) to not only report on the groups, but also to manage them. Check them out and let me know what you think!

Managing Local Groups in PowerShell

Reporting on Local Groups in PowerShell

Posted in powershell | Tagged , , , | Leave a comment

Supporting Synchronized Collections in PoshRSJob

I had a question where someone asked if PoshRSJob had support for synchronized variables (or collections) much like I have shown in the past using runspaces. This happened to be something that I touted as an advantage over the use of PSJobs and it would only make sense that you can do this using PoshRSJob as its backend framework is based on the use of runspaces and runspacepools.

Utilizing a synchronized collection for PoshRSJob really isn’t any different than what I have shown in the past. The first thing that we have to do is set up the synchronized collection that will be used to hold all of our variables and values.

$SyncHashTable = [hashtable]::Synchronized(@{})

Now I am going to add a single item to it just for reference.

$SyncHashTable.Initial = $True

We can build a small scriptblock that will be used to add some stuff to this hashtable so it is available in the other runspaces as well. We also need to ensure that the hashtable is locked at the syncroot property. Note that we are using the Enter and Exit methods in System.Threading.Monitor to accomplish this action and specifying the SyncRoot property of the hash table, not the hash table itself.

$ScriptBlock = {

    $SyncHash["Job$($_)"] = [appdomain]::GetCurrentThreadId()
    Start-Sleep -Seconds (Get-Random (1..5))

In this case, I am going to list my job name as well as the thread id that is has. Since we are using runspacepools for PoshRSJob, it is set to reuse the runspace meaning that we should see the same thread ids and should have them even when I group the objects by value.

Next up is actually running the RSjobs and wait for everything to finish up.

1..10|Start-RSjob -Name {$_} -ScriptBlock $ScriptBlock -ArgumentList $SyncHashTable | 
Wait-RSJob –ShowProgress

First time using GifCam, its a work in progress ;)

Once that has completed, we can see if I was right about the thread ids.

$SyncHashTable.GetEnumerator()|Group-Object -Property Value


As predicted, since my default throttle in Start-RSJob is set to 5 and I had 10 RSJobs queued up, we have exactly 5 thread ids that are reused. And at the end of all of this is that my synchronized  hash table was locked prior to being updated using to ensure there is no race condition that would prevent this from not working.

With that we now know how to share synchronized collections across multiple RSJobs using the PoshRSJob module. Just make sure that you utilize the Enter and Exit methods mentioned earlier to avoid possible errors and possible data loss.

Posted in powershell | Tagged , , , | Leave a comment

Managing Privileges using PoshPrivilege

A recent project of mine has been to write a module to manage privileges on a local system. What I came up is a module called PoshPrivilege that allows you to not only look at what user rights are available on a local or remote system, but also provide the ability to Add, Remove, Enable and Disable the privileges as well.

If you are running PowerShell V5, you can download this module from the PowerShell Gallery:

Install-Module –Name PoshPrivilege

Otherwise, check out my GitHub page where I am maintaining this project:


I won’t spend time talking about how I wrote this module and my reasons behind it. What I will say is that instead of writing out C# code and then using Add-Type to compile it, I went with the Reflection approach of building out everything from the pinvoke signatures for methods to the Structs and even the Enums.

Let’s get started by looking at what is available in this module. The first function that is available is Get-Privilege and it comes with a few parameters. This function’s purpose is to let you view what privileges are currently available on the system (local or remote) as well as what is currently applied to your current process token.


A quick run through of using this function with various parameters:



Get-Privilege –Privilege SeAuditPrivilege, SeServiceLogonRight | Format-List


Get-Privilege –CurrentUser


If this one looks familiar, then it is probably likely that you have used the following command:

whoami /priv /fo csv | ConvertFrom-CSV


I opted for boolean values instead to determine the state for easier filtering if needed.

Up next are the Enable/Disable-Privilege functions. These work to Enable or Disable the privileges that are currently available on your local system to your process token. This means that if something like SeDebugPrivilege isn’t available on your system (such as being removed via Group Policy), then you cannot use Enable-Privilege to add your process token to this privilege. As in the previous image where we can see what is enabled and disabled, these are the only privileges that are available for me to work with.

To show this point, I am going to enable both SeSecurityPrivilege and SeDebugPrivilege so you can see that while the first privilege will show as Enabled, the other will not appear as it has not been made available.

Enable-Privilege -Privilege SeSecurityPrivilege,SeDebugPrivilege


As you can see from the picture, SeSecurityPrivilege has been enabled as expected, but SeDebugPrivilege is nowhere to be found. If we want SeDebugPrivilege, we will need to go about this another way which will be shown shortly.

Disabling a privilege can be done using Disable-Privilege as shown in the example below.

Disable-Privilege –Privilege SeSecurityPrivilege


Now that I have covered Enabling and Disabling of the privileges and their limitations, I will move onto the Add/Remove-Privilege functions which allow you to add a privilege for a user or group or remove them on a local system. Note that this only works up until it gets reverted if set by group policy. This will also note show up if you look at the privileges available on your current process token (you will log off and log back in to see it).

Remember that I do not have SeDebugPrivilege available to use? Well, now we can add it to my own account using Add-Privilege.

Add-Privilege –Privilege SeDebugPrivilege –Accountname boe-pc\proxb


We can see it is now available, but as I mentioned before, it doesn’t show up in my current process. A logoff and login now shows that it is not only available, but already enabled.


With this now enabled, we could disable it as well if needed using Disable-Privilege. I added my account for show, but we can also add groups this was as well.

As with Adding a privilege, we can remove privileges as well using Remove-Privilege.

Remove-Privilege –Privilege SeDebugPrivilege –AccountName boe-pc\proxb


As with Add-Privilege, you will need to log off and log back in to see the change take effect on your account.

Again, you can install this module using Install-Module if running PowerShell V5 and this project is out on GitHub to download (and contribute to as well). Enjoy!

Posted in powershell | Tagged , , , , , | 1 Comment

Another Way to Show Bitwise Operation Results

This is something that came to me as I was working to do some bitwise operations for a project that had a lot of pInvoke stuff and required that I do some shifting of bits. Being that I wasn’t all that familiar with this (I’m more familiar with BOR, BAND and XOR), I wanted to learn more about the before and after of the binary representation of the data.

What is a bitwise operation you ask? Well, it is

a bitwise operation operates on one or more bit patterns or binary numerals at the level of their individual bits. It is a fast, primitive action directly supported by the processor, and is used to manipulate values for comparisons and calculations. –From Wikipedia Article on Bitwise Operations

I decided that it would be nice to have a function that would allow you to provide the parameters needed for a bitwise operation, but rather than just outputting a value as a result of the operation, it would instead show you more information about the results such as showing the values in binary and hex form. But that wasn’t all I wanted. I saw the about_Comparison_Operators help file and liked the examples that they showed when doing an operation.


Putting this all together led me to a function I wrote called Invoke-BitwiseOperation which accepts a –First and –Second parameter which is for the two values, a –BitwiseOperator parameter that accepts the following values: BAND,BOR,BXOR,BNOT,SHL,SHR and finally there is the –Graphical parameter which gives you the output like you see in the help files.

I start out by using a helper function called ConvertToBinary which takes an integer, converts it to a binary form and then uses a RegEx pattern to split out the binary data into chunks of 8.

Function ConvertToBinary {
    Process {
        $String = [Convert]::ToString($Item,2)
        $Reverse = -join (-join $string[$String.length..0] -split '(?<=\G.{8})').PadRight(8,'0')
        -join $Reverse[$Reverse.length..0] -split '(?<=\G.{8})'

(8956 | ConvertToBinary) -join ' '


I opted to not join the output prior so I could do some more stuff with the collection of values later on in my code.

If ($BitWiseOperator -eq 'BNOT') {
    $Result = [Math]::Abs((Invoke-Expression "-$($BitWiseOperator) $($First)"))
} Else {
    If ($PSBoundParameters.ContainsKey('First') -AND $PSBoundParameters.ContainsKey('Second')){
        $Result = Invoke-Expression "$($First) -$($BitWiseOperator) $($Second)"
    } Else {
        Write-Warning "You must specify both a First and Second parameter!"
$First_Bin = $First | ConvertToBinary
$First_Hex = "0x{0:x}" -f $First
If ($PSBoundParameters.ContainsKey('Second') -AND $BitWiseOperator -notmatch 'SHL|SHR') {
    $Second_Bin = $Second | ConvertToBinary
    $Second_Hex = "0x{0:x}" -f $Second
$Result_Bin = $Result | ConvertToBinary   
$Result_Hex = "0x{0:x}" -f $Result

This portion looks at what kind of Bitwise operator that I specified and takes an action based on that, such as when using BNOT. I also perform the conversion of the values to binary and also convert the data to hex for later use.

If ($PSBoundParameters.ContainsKey('Graphical')) {
    $Padding = '00000000'
    $FirstList = New-Object System.Collections.ArrayList
    $SecondList = New-Object System.Collections.ArrayList
    $ResultList = New-Object System.Collections.ArrayList

    $FirstHex = "0x{0:x}" -f $First
    $SecondHex = "0x{0:x}" -f $Second
    $ResultHex = "0x{0:x}" -f $Result
    $First_Bin | ForEach {
    $Second_Bin | ForEach {
    $Result_Bin | ForEach {

    $Count = $FirstList, $SecondList, $ResultList | ForEach {
            Count = $_.count
    } | Sort Count -Descending | Select -First 1 -ExpandProperty Count
    $FirstList, $SecondList, $ResultList | ForEach {
        $ToPad = $Count - $_.Count
        If ($ToPad -gt 0) {                
            For ($i=1; $i -le $ToPad; $i++) {
    $Line = '-' * (($ResultList -join ' ').Length)
    "$($FirstList -join ' ')  ($First, $($FirstHex)"
    If ($BitWiseOperator -notmatch 'BNOT|SHL|SHR') {
        "$($SecondList -join ' ')  ($Second, $($SecondHex)"
    "$line  $BitWiseOperator"
    "$($ResultList -join ' ')  ($result, $($ResultHex)"
} Else {
        First = $First
        First_Bin = $First_Bin
        First_Hex = $First_Hex
        BitWiseOperator = $BitWiseOperator
        Second = $Second
        Second_Bin = $Second_Bin
        Second_Hex = $Second_Hex
        Result = $Result
        Result_Bin = $Result_Bin
        Result_Hex = $Result_Hex

The final portion of the script takes a turn based on if the –Graphical parameter is used or not. If used, some more data processing occurs so it can display the data like what you saw in the help file. Otherwise, it just outputs an object with the converted values. Some examples are shown below.

Invoke-BitWiseOperation -First 32 -Second 16 -BitWiseOperator SHL –Graphical


Invoke-BitWiseOperation -First 7 -BitWiseOperator BNOT


Download Invoke-BitwiseOperation


Posted in powershell | Tagged , , , | 5 Comments

Port Checking and Implementing Pipeline Support in Functions on MCPMag

I’ve had a couple of other articles come out on MCPMag with one that deals with port checking using PowerShell while the latest one talks about implementing pipeline support in a PowerShell function. Check them out and let me know what you think!

Port Checking Using PowerShell

Building PowerShell Functions That Support the Pipeline

Posted in powershell | Tagged , , , , | Leave a comment