Odd school assignment, about displaying emojis in powershell - powershell

I've had the pleasure to get the assignment of posting emojis in Powershell, the only problem is they have to be on the same line, and there are three. This is, my first assignment, and we have no prior teaching in this subject so after googling and searching YouTube, my best shot was this below, however, it came with some error saying something about either too high value, or too low value.
Full error text: Exception calling "ToInt32" with "2" argument (s): "The value was either too large or too small to a UInt32. "
At C: \ Users \ EG \ Downloads \ Herningsholm \ Powershell H1 \ Hardware Information.ps1: 3 char: 5
$ UnicodeInt = [System.Convert] :: toInt32 ($ StrippedUnicode, 16)
CategoryInfo: NotSpecified: (:) [], MethodInvocationException
FullyQualifiedErrorId: OverflowException
$FullUnicode = ('U+1F60E') + ('U+1F436') + ('U+1F642')
$StrippedUnicode = $FullUnicode -replace 'U\+',''
$UnicodeInt = [System.Convert]::toInt32($StrippedUnicode,16)
[System.Char]::ConvertFromUtf32($UnicodeInt)

Try this out:
Full emoji list > here
# saves unicode for each emoji https://unicode.org/emoji/charts/full-emoji-list.html
$FullUnicode0 = 'U+1F606'
$FullUnicode1 = 'U+1F605'
$FullUnicode2 = 'U+1F605'
# removes the U+ bit
$StrippedUnicode0 = $FullUnicode0 -replace 'U\+',''
$StrippedUnicode1 = $FullUnicode1 -replace 'U\+',''
$StrippedUnicode2 = $FullUnicode2 -replace 'U\+',''
# Converts the value of the specified object to a 32-bit signed integer
$UnicodeInt0 = [System.Convert]::toInt32($StrippedUnicode0,16)
$UnicodeInt1 = [System.Convert]::toInt32($StrippedUnicode1,16)
$UnicodeInt2 = [System.Convert]::toInt32($StrippedUnicode2,16)
# Converts the specified Unicode code point into a UTF-16 encoded string so that you have an emoji
$Emoji0 = [System.Char]::ConvertFromUtf32($UnicodeInt0)
$Emoji1 = [System.Char]::ConvertFromUtf32($UnicodeInt1)
$Emoji2 = [System.Char]::ConvertFromUtf32($UnicodeInt2)
write-host "$($Emoji0), $($Emoji1), $($Emoji2)"

Related

Powershell Hex, Int and Bit flag checking

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.

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)
}``

Drools rule issue after migrating to 6.x from 5.3

I am getting issue in below rule. This is working fine in 5.3 but throwing error (must be boolean expression).
String drl="import com.drools.Applicant;"
+ "rule \"Is of valid age\" "
+ " when $a : Applicant(age > 18 && name matches \"(?i).*\"+ name + \"(.|\n|\r)*\")"
+ " then $a.setValid( true ); "
+ " System.out.println(\"validation: \" + $a.isValid());\n"+
"end";
Issue is with line :
" when $a : Applicant(age > 18 && name matches \"(?i).\"+ name + \"(.|\n|\r)\")"
Any advise.
The expression isn't correct since name cannot be resolved as part of an experssion. Use a binding.
$a : Applicant($n: name, age > 18, name matches \"(?i).*\"+ $name + \"(.|\n|\r)*\")"
(I don't think the the constraint makes much sense - it's merely a test whether a name matches itself, with or without arbitrary characters before and after. Moreover, the ?i is superfluous.)

Advanced Command-Line Replace Command In VBScript

I'm writing a compiler for my won computer language. Now before the language can be compiled i actually need to replace all apostrophes (') with percents (%) via a command-line vbs program. But the apostrophes only need to be replaced if there is NOT a circumflex accent (^) in front of it. So for example, in this code:
color 0a
input twelve = 0a "hi! that^'s great! "
execute :testfornum 'twelve'
exit
:testfornum
if numeric('1) (
return
) ELSE (
print 0a "oops 'twelve' should be numeric"
)
return
the apostrophe at line 2 should not be replaced, but the ones at line 3, 6 and 9 should be.
can anyone help me?
this is what i have so far:
'syntax: (cscript) replace.vbs [filename] "StringToFind" "stringToReplace"
Option Explicit
Dim FileScriptingObject, file, strReplace, strReplacement, fileD, lastContainment, newContainment
file=Wscript.arguments(0)
strReplace=WScript.arguments(1)
strReplacement=WScript.arguments(2)
Set FileScriptingObject=CreateObject("Scripting.FileSystemObject")
if FileScriptingObject.FileExists(file) = false then
wscript.echo "File not found!"
wscript.Quit
end if
set fileD=fileScriptingobject.OpenTextFile(file,1)
lastContainment=fileD.ReadAll
newContainment=replace(lastContainment,strReplace,strReplacement,1,-1,0)
set fileD=fileScriptingobject.OpenTextFile(file,2)
fileD.Write newContainment
fileD.Close
As #Ansgar's solution fails for the special case of a leading ' (no non-^ before that), here is an approach that uses a replace function in a test script that makes further experiments easy:
Option Explicit
Function fpR(m, g1, g2, p, s)
If "" = g1 Then
fpR = "%"
Else
fpR = m
End If
End Function
Function qq(s)
qq = """" & s & """"
End Function
Dim rE : Set rE = New RegExp
rE.Global = True
rE.Pattern = "(\^)?(')"
Dim rA : Set rA = New RegExp
rA.Global = True
rA.Pattern = "([^^])'"
'rA.Pattern = "([^^])?'"
Dim s
For Each s In Split(" 'a^'b' a'b'^'c nix a^''b")
WScript.Echo qq(s), "==>", qq(rE.Replace(s, GetRef("fpR"))), "==>", qq(rA.Replace(s, "$1%"))
Next
output:
cscript 25221565.vbs
"" ==> "" ==> ""
"'a^'b'" ==> "%a^'b%" ==> "'a^'b%" <=== oops
"a'b'^'c" ==> "a%b%^'c" ==> "a%b%^'c"
"nix" ==> "nix" ==> "nix"
"a^''b" ==> "a^'%b" ==> "a^'%b"
You can't do this with a normal string replacement. A regular expression would work, though:
...
Set re = New RegExp
re.Pattern = "(^|[^^])'"
re.Global = True
newContainment = re.Replace(lastContainment, "$1%")
...