Powershell Hex, Int and Bit flag checking - powershell

I am trying to process a flag from the MECM command Get-CMTaskSequenceDeployment called 'AdvertFlags'.
The information from Microsoft in relation to this value is HERE
The value returned is designated as : Data type: UInt32
In the table of flags, the one I need to check is listed as :
Hexadecimal (Bit)
Description
0x00000020 (5)
IMMEDIATE. Announce the advertisement to the user immediately.
As part of my Powershell script I am trying to ascertain if this flag is set.
I can see by converting it to Binary that a particular bit gets set.
When the settings is enabled:
DRIVE:\> [convert]::ToString((Get-CMTaskSequenceDeployment -AdvertisementID ABC20723).AdvertFlags, 2)
100110010000000000100000
When the setting is disabled:
DRIVE:\> [convert]::ToString((Get-CMTaskSequenceDeployment -AdvertisementID ABC20723).AdvertFlags, 2)
100110010000000000000000
The 6th bit is changed. Great! So far though, I've been unable to find a way to check if this bit is set. I suspected something in the bitwise operators (-band -bor etc) would help me here but I've been unable to get it to work.
Any bitwise operation I try returns an error:
"System.UInt64". Error: "Value was either too large or too small for a UInt64."
I mean, I can compare the string literally, but other options may be changed at any point.
Any help greatly appreciated.
EDIT: Just as an example of the error I am seeing, I can see that the bit that is set is '32' and from my limited understanding I should be able to:
PS:\> '100110010000000000100000' -band '32'
Cannot convert value "100110010000000000100000" to type "System.UInt64". Error: "Value was either too large or too small for a UInt64."
At line:1 char:1
+ '100110010000000000100000' -band '32'
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvalidCastIConvertible
But I just always return an error

To test bit6 in
$AdvertFlags = (Get-CMTaskSequenceDeployment -AdvertisementID ABC20723).AdvertFlags
Should simply be:
if ($AdvertFlags -band 32) { 'bit6 is set' } else { 'bit6 is not set' }
I do not have access to a deployment environment with Get-CMTaskSequenceDeployment cmdlet, nevertheless to confirm what I am stating:
$AdvertFlags = [Convert]::ToUInt32("100110010000000000100000", 2)
$AdvertFlags
10027040
if ($AdvertFlags -band 32) { 'bit6 is set' } else { 'bit6 is not set' }
bit6 is set
$AdvertFlags = [Convert]::ToUInt32("100110010000000000000000", 2)
$AdvertFlags
10027008
if ($AdvertFlags -band 32) { 'bit6 is set' } else { 'bit6 is not set' }
bit6 is not set
Your self-answer using [bigint]'100110010000000000100000' -band "32" to test for bit6 is merely a coincident that it returns the expected value:
10027035..10027045 |ForEach-Object {
$Binary = [convert]::ToString($_, 2)
[pscustomobject]#{
Binary = $Binary
bAnd = $_ -bAnd 32
Bigint = [bigint]$Binary -band "32"
}
}
Yields:
Binary bAnd Bigint
------ ---- ------
100110010000000000011011 0 0
100110010000000000011100 0 0
100110010000000000011101 0 0
100110010000000000011110 0 32 # ← incorrect
100110010000000000011111 0 32 # ← incorrect
100110010000000000100000 32 32
100110010000000000100001 32 32
100110010000000000100010 32 32
100110010000000000100011 32 32
100110010000000000100100 32 0 # ← incorrect
100110010000000000100101 32 0 # ← incorrect
enumerations as flags
But PowerShell has an even nicer way to test them by name:
[Flags()] enum AdvertFlags {
IMMEDIATE = 0x00000020 # Announce the advertisement to the user immediately.
ONSYSTEMSTARTUP = 0x00000100 # Announce the advertisement to the user on system startup.
ONUSERLOGON = 0x00000200 # Announce the advertisement to the user on logon.
ONUSERLOGOFF = 0x00000400 # Announce the advertisement to the user on logoff.
OPTIONALPREDOWNLOAD = 0x00001000 # If the selected architecture and language matches that of the client, the package content will be downloaded in advance
WINDOWS_CE = 0x00008000 # The advertisement is for a device client.
ENABLE_PEER_CACHING = 0x00010000 # This information applies to System Center 2012 Configuration Manager SP1 or later, and System Center 2012 R2 Configuration Manager or later.
DONOT_FALLBACK = 0x00020000 # Do not fall back to unprotected distribution points.
ENABLE_TS_FROM_CD_AND_PXE = 0x00040000 # The task sequence is available to removable media and the pre-boot execution environment (PXE) service point.
APTSINTRANETONLY = 0x00080000 #
OVERRIDE_SERVICE_WINDOWS = 0x00100000 # Override maintenance windows in announcing the advertisement to the user.
REBOOT_OUTSIDE_OF_SERVICE_WINDOWS = 0x00200000 # Reboot outside of maintenance windows.
WAKE_ON_LAN_ENABLED = 0x00400000 # Announce the advertisement to the user with Wake On LAN enabled.
SHOW_PROGRESS = 0x00800000 # Announce the advertisement to the user showing task sequence progress.
NO_DISPLAY = 0x02000000 # The user should not run programs independently of the assignment.
ONSLOWNET = 0x04000000 # Assignments are mandatory over a slow network connection.
TARGETTOWINPE = 0x10000000 # Target this deployment to WinPE only.
HIDDENINWINPE = 0x20000000 # Target this deployment to WinPE only but hide in WinPE. It can only be used by TS variable SMSTSPreferredAdvertID.
}
# $AdvertFlags = [AdvertFlags](Get-CMTaskSequenceDeployment -AdvertisementID ABC20723).AdvertFlags
$AdvertFlags = [AdvertFlags][Convert]::ToUInt32("100110010000000000100000", 2)
# or: $AdvertFlags = [AdvertFlags]('IMMEDIATE', 'ENABLE_PEER_CACHING', 'APTSINTRANETONLY', 'OVERRIDE_SERVICE_WINDOWS', 'SHOW_PROGRESS')
$AdvertFlags
IMMEDIATE, ENABLE_PEER_CACHING, APTSINTRANETONLY, OVERRIDE_SERVICE_WINDOWS, SHOW_PROGRESS
$AdvertFlags -bAnd [AdvertFlags]'IMMEDIATE'
IMMEDIATE

EDIT: My answer here is incorrect as noted above. Leaving here for prosperity!
As always I BELEIVE I found the answer minutes after posting (After spending a couple hours on this!).
By adjusting the type to [bigint] the comparison was able to complete and return the expected answer:
DRIVE:\> [bigint]'100110010000000000100000' -band "32"
32
So a simple:
If (([bigint]'100110010000000000100000' -band "32") -gt 0){$true}else{$false}
True
and:
If (([bigint]'100110010000000000000000' -band "32") -gt 0){$true}else{$false}
False
Solves my issue. Feel free to give any extra advice if this is not the ideal way to proceed.
I though PS would be smarted when auto defining types etc. This is targeting PS5 on Server 2012 R2 though.

Related

Powershell SNMP converting IP Address: Getting wrong value

How do I properly convert an IP Address gotten via OleSNMP to a useable value?
I'm trying to write a Powershell script to query devices with SNMP and then display the data. Stuff works fine for simple types, but I'm having problems with the IP Addresses (and MAC addresses, but let's stick to IP for now)
Here's what I have (simplified to the problem space):
param ($ipaddr='10.1.128.114', $community='Public')
$snmp = New-Object -ComObject oleprn.OleSNMP
$snmp.open($ipaddr, $community)
$result = $snmp.get(".1.3.6.1.2.1.4.20.1.1.10.1.128.114")
$enc = [system.Text.Encoding]::ASCII
$bytes = $enc.GetBytes($result)
write-host( "bytes:" + $bytes)
Which outputs:
bytes:10 1 63 114
When I expected
bytes:10 1 128 114
For contrast, the snmp-get outputs:
$ snmpget 10.1.128.114 -c Public -v2c -On .1.3.6.1.2.1.4.20.1.1.10.1.128.114
.1.3.6.1.2.1.4.20.1.1.10.1.128.114 = IpAddress: 10.1.128.114
And yes, I realize that in my final script I'll have to walk the table instead of using a direct "get" but I need to fix my parsing first.
As mentioned in the comments, the ASCII encoding substitutes characters outside its valid range with a question mark ?, which is ASCII character 63.
More info is available in the documentation for ASCIIEncoding.GetBytes - search for "?" and you'll find this:
ASCIIEncoding does not provide error detection. Any Unicode character greater than U+007F is encoded as the ASCII question mark ("?").
Note, 0x7F is 127, so since [char] 128 is outside this range, it's being converted to the byte equivalent of ? (which is 63) when you call GetBytes.
Your code is basically doing this this:
$result = ([char] 10) + ([char] 1) + ([char] 128) + ([char] 114)
$encoding = [System.Text.Encoding]::ASCII
$bytes = $encoding.GetBytes($result)
$bytes
# 10
# 1
# 63 (i.e. "?")
# 114
You need to use an encoder which will convert characters higher than 0x7F into the equivalent bytes - something like iso-8859-1 seems to work:
$result = ([char] 10) + ([char] 1) + ([char] 128) + ([char] 114)
$encoding = [System.Text.Encoding]::GetEncoding("iso-8859-1")
$bytes = $encoding.GetBytes($result)
$bytes
# 10
# 1
# 128
# 114

Converting Output to CSV and Out-Grid

I have a file as below.
I want it to convert it to CSV and want to have the out grid view of it for items Drives,Drive Type,Total Space, Current allocation and Remaining space only.
PS C:\> echo $fileSys
Storage system address: 127.0.0.1
Storage system port: 443
HTTPS connection
1: Name = Extreme Performance
Drives = 46 x 3.8T SAS Flash 4
Drive type = SAS Flash
RAID level = 5
Stripe length = 13
Total space = 149464056594432 (135.9T)
Current allocation = 108824270733312 (98.9T)
Remaining space = 40639785861120 (36.9T)
I am new to Powershell but I have tried below code for two of things but it's not even getting me desired output.
$filesys | ForEach-Object {
if ($_ -match '^.+?(?<Total space>[0-9A-F]{4}\.[0-9A-F]{4}\.[0-9A-F]{4}).+?(?<Current allocation>\d+)$') {
[PsCustomObject]#{
'Total space' = $matches['Total space']
'Current allocation' = $matches['Current allocation']
}
}
}
First and foremost, the named capture groups cannot contain spaces.
From the documentation
Named Matched Subexpressions
where name is a valid group name, and subexpression is any valid
regular expression pattern. name must not contain any punctuation
characters and cannot begin with a number.
Assuming this is a single string since your pattern attempts to grab info from multiple lines, you can forego the loop. However, even with that corrected, your pattern does not appear to match the data. It's not clear to me what you are trying to match or your desired output. Hopefully this will get you on the right track.
$filesys = #'
Storage system address: 127.0.0.1
Storage system port: 443
HTTPS connection
1: Name = Extreme Performance
Drives = 46 x 3.8T SAS Flash 4
Drive type = SAS Flash
RAID level = 5
Stripe length = 13
Total space = 149464056594432 (135.9T)
Current allocation = 108824270733312 (98.9T)
Remaining space = 40639785861120 (36.9T)
'#
if($filesys -match '(?s).+total space\s+=\s(?<totalspace>.+?)(?=\r?\n).+allocation\s+=\s(?<currentallocation>.+?)(?=\r?\n)')
{
[PsCustomObject]#{
'Total space' = $matches['totalspace']
'Current allocation' = $matches['currentallocation']
}
}
Total space Current allocation
----------- ------------------
149464056594432 (135.9T) 108824270733312 (98.9T)
Edit
If you just want the values in the parenthesis, modifying to this will achieve it.
if($filesys -match '(?s).+total space.+\((?<totalspace>.+?)(?=\)).+allocation.+\((?<currentallocation>.+?)(?=\))')
{
[PsCustomObject]#{
'Total space' = $matches['totalspace']
'Current allocation' = $matches['currentallocation']
}
}
Total space Current allocation
----------- ------------------
135.9T 36.9T
$unity=[Regex]::Matches($filesys, "\(([^)]*)\)") -replace '[(\)]','' -replace "T",""
$UnityCapacity = [pscustomobject][ordered] #{
Name = "$Display"
"Total" =$unity[0]
"Used" = $unity[1]
"Free" = $unity[2]
'Used %' = [math]::Round(($unity[1] / $unity[0])*100,2)
}``

Check if extended mode screen in Powershell (need help - translate Autoit to Powershell v2)

I want to translate this AutoIt script to Powershell v2.
(AutoIt is a freeware BASIC-like scripting https://www.autoitscript.com/site/autoit/downloads/ )
#include <WinAPIGdi.au3>
Local $objWMIService = ObjGet("winmgmts:{impersonationLevel=impersonate}!\\" & #ComputerName & "\root\cimv2")
Local $colMonitors = $objWMIService.ExecQuery ("Select * from Win32_DesktopMonitor Where Availability=3", "WQL", 0x10 + 0x20)
If NOT IsObj($colMonitors) Then Exit
Local $iCount = 0
For $oMonitor In $colMonitors
$iCount += 1
Next
MsgBox(0, "", "Number of monitors : " & $iCount)
$aMonitor = _WinAPI_EnumDisplayMonitors()
If #error Then Exit
ConsoleWrite ("!! multiscreen mode:" & $aMonitor[0][0]) ;value equal one if there is one screen duplicated or not, if extended the value wille be greater than one. I don’t mind if the computer screen are powered on or not.
If $aMonitor[0][0] > 1 Then
MsgBox(0, "", "extended mode"&$aMonitor[0][0] ) ;give 2
Else
MsgBox(0, "", "duplicate mode"&$aMonitor[0][0] ) ;give 1
EndIf
;---Excerpt from WinAPIGdi.au3 (included with AutoIt) :---
Func _WinAPI_EnumDisplayMonitors($hDC = 0, $tRECT = 0)
Local $hEnumProc = DllCallbackRegister('__EnumDisplayMonitorsProc', 'bool', 'handle;handle;ptr;lparam')
Dim $__g_vEnum[101][2] = [[0]]
Local $aRet = DllCall('user32.dll', 'bool', 'EnumDisplayMonitors', 'handle', $hDC, 'struct*', $tRECT, _
'ptr', DllCallbackGetPtr($hEnumProc), 'lparam', 0)
If #error Or Not $aRet[0] Or Not $__g_vEnum[0][0] Then
$__g_vEnum = #error + 10
EndIf
DllCallbackFree($hEnumProc)
If $__g_vEnum Then Return SetError($__g_vEnum, 0, 0)
__Inc($__g_vEnum, -1)
Return $__g_vEnum
EndFunc ;==>_WinAPI_EnumDisplayMonitors
I tried to begin with this commands in Powershell:
Get-Wmiobject win32_DesktopMonitor |format-list
Get-Wmiobject -query "select Name,DeviceID,DisplayType from win32_DesktopMonitor where Availability=3"
It works but it’s really too short...
Can you please specify what you would like to do? I am not sure what you are trying to achieve.
It works but it’s really too short...
So it works. That's good - right?
If you want to check how many screens are connected you can use the following cmdlet:
Get-CimInstance -Namespace root\wmi -ClassName WmiMonitorBasicDisplayParams
Source: Use PowerShell to Discover Multi-Monitor Information

SHARP Serialport RS232

I am trying get Sony TV model from computer over Serialport.
Here is a documentation (page 80 - how to build query, page 83 - how to get model name).
https://cdn.cnetcontent.com/d1/9d/d19d926b-bb36-4ed3-bd03-af1cad4069da.pdf
Here is my simply script, but, unfortunatelly, always return ERR.
What I did wrong?
$hex = 0x4d,0x4e,0x52,0x44,0x31,0x20,0x20,0x20,0x0d
$com = New-Object System.IO.Ports.Serialport COM4,9600,None,8,one
$com.Open()
$com.Write($hex, 0, $hex.Count)
Start-Sleep -s 2
$read = $com.ReadExisting()
Write-Host "Response: $read" #ERR
$com.Close()
Found response: it return ERR wneh power is off.
When I powered on device over RS-232, script starts respond LE740E insteadof ERR

inf2cat 22.9.10 error

I'm trying to sign old Hitachi driver that makes USB flash drive appear as fixed disk
(Quite useful when you have fast, large thumb drives)
Driver itself works fine but I constantly get same error when try to get it signed:
Errors:
22.9.10: cfadisk.sys in [cfadisk_copyfiles] is missing from [SourceDisksFiles] section in
\cfadisk.inf; driver may not sign correctly until this is resolved.
22.9.10: disk.sys in [gendisk_copyfiles] is missing from [SourceDisksFiles] section in
cfadisk.inf; driver may not sign correctly until this is resolved.
This is my .inf file:
[Version]
Signature="$Windows NT$"
Class=DiskDrive
ClassGuid={4D36E967-E325-11CE-BFC1-08002BE10318}
Provider=%HGST%
DriverVer=10/14/2012,9.9.9.9
CatalogFile=cfadisk.cat
[Manufacturer]
%HGST% = cfadisk_device,ntAMD64
[DestinationDirs]
cfadisk_copyfiles=12 ; %SystemRoot%\system32\drivers
gendisk_copyfiles=12 ; %SystemRoot%\system32\drivers
[cfadisk_copyfiles]
cfadisk.sys
[gendisk_copyfiles]
disk.sys
[cfadisk_device]
%Microdrive_devdesc% = cfadisk_install,USBSTOR\Disk&Ven_SanDisk&Prod_Extreme&Rev_0001
[cfadisk_device.NTamd64]
%Microdrive_devdesc% = cfadisk_install,USBSTOR\Disk&Ven_SanDisk&Prod_Extreme&Rev_0001
[cfadisk_addreg]
HKR,,"LowerFilters",0x00010008,"cfadisk"
[cfadisk_install]
CopyFiles=cfadisk_copyfiles,gendisk_copyfiles
[cfadisk_install.HW]
AddReg=cfadisk_addreg
[cfadisk_install.Services]
AddService=disk,2,gendisk_ServiceInstallSection
AddService=cfadisk,,cfadisk_ServiceInstallSection
[gendisk_ServiceInstallSection]
DisplayName = "Disk Driver"
ServiceType = 1
StartType = 0
ErrorControl = 1
ServiceBinary = %12%\disk.sys
LoadOrderGroup = SCSI Class
[cfadisk_ServiceInstallSection]
DisplayName = "CompactFlash Filter Driver"
ServiceType = 1
StartType = 3
ErrorControl = 1
ServiceBinary = %12%\cfadisk.sys
LoadOrderGroup = Pnp Filter
; -----------------------
[Strings]
HGST = "Hitachi"
Microdrive_devdesc = "SanDisk Extreme"
I was using this tutorial as reference point:
http://www.deploymentresearch.com/Blog/tabid/62/EntryId/63/Sign-your-unsigned-drivers-Damn-It.aspx
cfadisk.inf and sys can be downloaded here:
link is at the beginning of first post
http://hardforum.com/showthread.php?t=1655684
Any help would be greatly appreciated
EDIT:
I just used chkinf utility on this .inf file
Here is the output:
C:\DriversCert\SanDisk\cfadisk.inf: FAILED
NTLOG REPORT--------------
Total Lines: 62 |
Total Errors: 1 |
Total Warnings: 4 |
--------------------------
Line 0: ERROR: (E22.1.1003) Section [SourceDisksNames] not defined.
Line 0: WARNING: (W22.1.2212) No Copyright information found.
Line 0: WARNING: (W22.1.2111) [SourceDisksFiles] section not defined - full CopyFiles checking not done.
Line 17: WARNING: (W22.1.2112) File "cfadisk.sys" is not listed in the [SourceDisksFiles].
Line 20: WARNING: (W22.1.2112) File "disk.sys" is not listed in the [SourceDisksFiles].
I'm really no programer so I really don't understand what does all this mean.
Strange thing is that driver does work, I just can't get i signed.
Thank you!
Best regards,
Walter
It means that some sections are missed. In your case they are [SourceDisksFiles] and [SourceDisksNames]
In this specific situation you just should add:
[SourceDisksFiles]
cfadisk.sys = 1
disk.sys = 1
[SourceDisksNames]
1 = %DiskName%, ,
and also add a record to [String] section in the bottom:
DiskName="Disk Drive"