Powershell hashtable problem - powershell

I'm writing a script to take a string of letters and convert them to phonetic values. The problem I'm having is that I am unable to reference a value in a hashtable (see error below). I'm not sure why as the code looks fine to me.
Index operation failed; the array index evaluated to null.
At C:\Scripts\test.ps1:8 char:23
+ write-host $alphabet[ <<<< $char]
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : NullArrayIndex
}
param($string = $(throw 'Enter a string'))
$alphabet = #{
"A" = "Alfa";
"B" = "Bravo ";
"C" = "Charlie ";
"D" = "Delta ";
"E" = "Echo ";
"F" = "Foxtrot ";
"G" = "Golf ";
"H" = "Hotel ";
"I" = "India ";
"J" = "Juliett";
"K" = "Kilo ";
"L" = "Lima ";
"M" = "Mike ";
"N" = "November ";
"O" = "Oscar ";
"P" = "Papa ";
"Q" = "Quebec ";
"R" = "Romeo ";
"S" = "Sierra ";
"T" = "Tango ";
"U" = "Uniform ";
"V" = "Victor ";
"W" = "Whiskey ";
"X" = "X-ray";
"Y" = "Yankee ";
"Z" = "Zulu ";
}
clear-host
$charArray = $string.ToCharArray()
foreach ($char in $charArray)
{
write-host $alphabet[$char]
}

Each Char is a rich object, Change:
write-host $alphabet[$char]
to
write-host $alphabet["$char"]
or
write-host $alphabet[$char.ToString()]

Your problem is that in $alphabet[$char], $char is null. Where does $chararray come from?

Methinks you need to lose the space after each letter in your array. And you are also missing a space after Alfa, Juliett (sp), and X-ray.
$alphabet = #{
"A" = "Alfa ";
"B" = "Bravo ";
"C" = "Charlie ";
"D" = "Delta ";
"E" = "Echo ";
"F" = "Foxtrot ";
"G" = "Golf ";
"H" = "Hotel ";
"I" = "India ";
"J" = "Juliet ";
"K" = "Kilo ";
"L" = "Lima ";
"M" = "Mike ";
"N" = "November ";
"O" = "Oscar ";
"P" = "Papa ";
"Q" = "Quebec ";
"R" = "Romeo ";
"S" = "Sierra ";
"T" = "Tango ";
"U" = "Uniform ";
"V" = "Victor ";
"W" = "Whiskey ";
"X" = "X-ray ";
"Y" = "Yankee ";
"Z" = "Zulu ";
}

Related

Digit's Values not getting extracted from Dictionary

I have a dictionary that contains Letters and Digits and i can get the values of the letter keys just fine but not the ones from digits even though they're enclosed in " . It isn't important for the question but just in case you're wondering what the bluscream.ahk file that's included looks like: https://github.com/Bluscream/ahk-scripts/blob/master/Lib/bluscream.ahk
I tried what can be seen in the code. I have no idea what to do
; Version 1
; Date 02/02/2019
#Include <bluscream>
#SingleInstance Force
Process Priority,, Below Normal
SetWorkingDir %A_ScriptDir%
#Warn
#Persistent
SetKeyDelay, 150
game_name := "LEGO" ; LEGO Jurassic World
game_title := "ahk_class TTalesWindow" ; ahk_exe LEGOJurassicWorld_DX11.EXE
chars := { "B" : "{Up}", "C" : "{Up 2}", "D" : "{Up 3}", "E" : "{Up 4}", "F" : "{Up 5}", "G" : "{Up 6}", "H" : "{Up 7}", "J" : "{Up 8}", "K" : "{Up 9}", "L" : "{Up 10}", "M" : "{Up 11}", "N" : "{Up 12}", "O" : "{Up 13}", "P" : "{Up 14}", "Q" : "{Up 15}", "R" : "{Up 16}", "S" : "{Down 18}", "T" : "{Down 17}", "U" : "{Down 16}", "V" : "{Down 15}", "W" : "{Down 14}", "X" : "{Down 13}", "Y" : "{Down 12}", "Z" : "{Down 11}", "0" : "{Down 10}", "1" : "{Down 9}", "2" : "{Down 8}", "3" : "{Down 7}", "4" : "{Down 6}", "5" : "{Down 5}", "6" : "{Down 4}", "7" : "{Down 3}", "8" : "{Down 2}", "9" : "{Down}" }
file := "codes.txt"
global noui := false
scriptlog("Started logging here...")
FileRead, LoadedText, %file%
codes := StrSplit(LoadedText, "`n", "`r")
Loop, % codes.MaxIndex()
{
if !(WinActive(game_title)) {
TrayTip, AutoHotKey, Bringing %game_name% to front to enter code...
Sleep, 1000
WinWaitActive, %game_title%
}
code := StrStrip(codes[A_Index])
length := StrLen(code)
FormatTime, timestamp, A_Now, hh:mm:ss
scriptlog("[" . timestamp . "] Now processing code: " . code . " [" . length . "] (`r`n", "", true)
splitted_code := StrSplit(code)
for i, char in splitted_code {
tosend := chars[char]
scriptlog("i:" . i . " char:" . char . " tosend:" . tosend . "`r`n", "", true)
if (tosend){
SendEvent, % tosend
}
if (i < length)
SendInput, {Right}
}
scriptlog(")`r`n","",true)
SendInput, {Enter}
}
Expected results:
[11:17:43] Started logging here...
[11:17:46] Now processing code: 28SPSR [6] (
i:1 char:2 tosend:{Down 8}
i:2 char:8 tosend:{Down 2}
i:3 char:S tosend:{Down 18}
i:4 char:P tosend:{Up 14}
i:5 char:S tosend:{Down 18}
i:6 char:R tosend:{Up 16}
)
Actual Results:
[11:17:43] Started logging here...
[11:17:46] Now processing code: 28SPSR [6] (
i:1 char:2 tosend:
i:2 char:8 tosend:
i:3 char:S tosend:{Down 18}
i:4 char:P tosend:{Up 14}
i:5 char:S tosend:{Down 18}
i:6 char:R tosend:{Up 16}
)
Looks like a bug of the object declaration. A problem about string vs numbers.
Using numbers without quotes removes the problem.
But also, doing this after declaring the object fixes the problem too:
for k,v in chars
chars[k] := v
You could fill a bug on the official board: https://www.autohotkey.com/boards/

Perl get array element from mongodb

I wanted to fetch array element and store in Perl variable. If I put 0 in replace of ? in $cur->{Type}[?]->{_id} I'm able to get only one array element but I want all. below is my collection
{
"_id" : ObjectId("5b7fdb050cc3c23478005741"),
"DBName" : "sample",
"DBServerURL" : "mongodb://localhost:27017/",
"Type" : [
{
"_id" : ObjectId("5b801dc963f8c81df83891bd")
},
{
"_id" : ObjectId("5b801dc963f8c81df83891be")
},
{
"_id" : ObjectId("5b801dc963f8c81df83891bf")
},
{
"_id" : ObjectId("5b801dc963f8c81df83891c0")
}
]
}
I'm trying to get ObjectId from all fields
$cursor = $CustColl->find(
{DBName => "sample",DBServerURL => "mongodb://localhost:27017/"},{'_id' => 1, 'Type.$._id' => 1, 'DBServerURL' => 1, 'DBName' => 1}
);
while(my $cur = $cursor->next){
my $cid = "$cur->{_id}" ;
my $jid = "$cur->{Type}[?]->{_id}" ;
my $url = "$cur->{DBServerURL}" ;
my $name = "$cur->{DBName}" ;
print "$cid : $jid : $url : $name\n" ;
}
I wanted an output like below:
5b7fdb050cc3c23478005741 : 5b801dc963f8c81df83891bd : mongodb://localhost:27017/ sample
5b7fdb050cc3c23478005741 : 5b801dc963f8c81df83891be : mongodb://localhost:27017/ sample
5b7fdb050cc3c23478005741 : 5b801dc963f8c81df83891bf : mongodb://localhost:27017/ sample
5b7fdb050cc3c23478005741 : 5b801dc963f8c81df83891c0 : mongodb://localhost:27017/ sample
You are almost there. First, I fixed up your data to make it JSON but that's not a big deal:
my $json = q([{
"_id" : "5b7fdb050cc3c23478005741",
"DBName" : "sample",
"DBServerURL" : "mongodb://localhost:27017/",
"Type" : [
{
"_id" : "5b801dc963f8c81df83891bd"
},
{
"_id" : "5b801dc963f8c81df83891be"
},
{
"_id" : "5b801dc963f8c81df83891bf"
},
{
"_id" : "5b801dc963f8c81df83891c0"
}
]
} ]);
use JSON::XS;
my $perl = decode_json( $json );
That's a JSON array so you can go through it one element at a time. In Perl that shows up as an array reference Using the postfix dereference introduced in v5.20 makes this palatable (but not so hard without it):
while(my $cur = shift $perl->#*){ # or #$perl
my $cid = $cur->{_id} ;
my $url = $cur->{DBServerURL} ;
my $name = $cur->{DBName} ;
foreach my $hash ( $cur->{Type}->#* ) { # or #{ $cur->{Type} }
my $jid = $hash->{_id};
print "$cid : $jid : $url : $name\n" ;
}
}
The trick is that the $jid stuff is in another array and you want to go through those individually. There's a foreach inside the while to do that. It runs once for each of those and outputs the lines.

Convert Json Object to string with PowerShell

I'm trying to convert this :
tags: [
{ tagName : "O365" },
{ tagName : "Skype for Business" }
]
to "O365,Skype for Business" as a string.
Could anyone help me to accomplish this using Powershell ?
Works only if you have only one "tags" property in your JSON :
$json = #"
{
tags: [
{ tagName : "O365" },
{ tagName : "Skype for Business" }
]
}
"#
(ConvertFrom-Json $json | % tags | % tagName) -Join ", "
# result : O365, Skype for Business
Similarly,
$separator = ","
$tagname = (ConvertFrom-Json $json).tags.tagName
[String]::Join($separator,$tagname)
Or as a one-liner
[String]::Join(",",(ConvertFrom-Json $json).tags.tagName)

how to query sub document in mongodb?

how to query the sub document in sub document.?
how to retreive the name of the city in commercial document.
{
"_id" : " c2 ",
"commercial" : {
" type " : " restaurant ",
" sale_type " : " sale ",
" owner_name " : " josi schmit",
" address " : {
" street " : " kleine rittergasse ",
" plot_no " : 4,
" city " : " frankfurt ",
" state " : " hessen ",
" country " : "germany ",
"postal_code " : 60329,
"email" : " josi123#gmail.com"
},
" total_area " : " 300 sq meters ",
" sale_price(EUR) " : 100000,
" features " : {
" lifts " : 1,
" heating " : true,
" parking " : true,
" kitchen " : true,
" security_cameras " : true,
" furniture " : true
}
}
}
here is my query but i knew i'm wrong please help me.
db.property.find( {"_id": "c2" , "address.city": "c2"})
Regards
Sreekanth
Actualy there are two methods to do that:
db.property.find ( { "_id": "c2", "commercial.address.city": "c2" }, {"commercial.address.city": true} )
db.property.find ( { "_id": "c2", "commercial": { "address" : { "city": "c2" }}} )
The difference in both cases is that in first case mongo will follow the index if you have an index commercial.address.city, the second one will not, so I sugest you use the first one

Perl Newbie - Printing value from array

I am brand new to perl. I am trying to grab a string out of some JSON output. My code below works, but seems like there is a smarter way to do this. Here is a sample of the JSON
$VAR1 = '{
"hasDetailRows" : true,
"reportMetadata" : {
"reportFormat" : "TABULAR",
"detailColumns" : [ "SUBJECT", "COMMENT_CREATED_DATE", "CASE_COMMENT_CREATED_BY" ],
"reportBooleanFilter" : null,
"reportFilters" : [ {
"column" : "CASE_COMMENT_CREATED_BY",
"operator" : "equals",
"value" : "Username"
} ],
"aggregates" : [ "RowCount" ],
"groupingsDown" : [ ],
"groupingsAcross" : [ ],
"developerName" : "My_Comments",
"reportType" : {
"type" : "CaseList",
"label" : "Cases"
},
"name" : "My Comments",
"id" : "REDCATED",
"currency" : null
},
"factMap" : {
"T!T" : {
"rows" : [ {
"dataCells" : [ {
"value" : "ID",
"label" : "Description"
}, {
"value" : "2014-02-17T22:01:17Z",
"label" : "2/17/2014 4:01 PM"
}, {
"value" : "USER ID",
"label" : "User Name"
} ]
}`
What I need is that label with the timestamp.
And here is my code
#!/usr/bin/perl
use warnings;
use strict;
use WWW::Mechanize;
use WWW::Salesforce;
use Data::Dumper;
use JSON -support_by_pp;
use 5.010;
use Date::Parse;
my $mech = WWW::Mechanize->new();
$mech->agent('Mozilla/5.0');
# Authenticate first via SOAP interface to get a session ID:
my $sforce = eval { WWW::Salesforce->login(
username => 'REDACTED',
password => 'REDACTED' ); };
die "Could not login to SFDC: $#" if $#;
# Get the session ID:
my $hdr = $sforce->get_session_header();
my $sid = ${$hdr->{_value}->[0]}->{_value}->[0];
#Our request
$mech->add_header( "Authorization" => "OAuth $sid" );
$mech->add_header( "X-PrettyPrint" => '1' );
$mech->get("SOME URL THAT RETURNS JSON");
my $content = $mech->content;
my $json = new JSON;
my $json_text = $json->allow_nonref->utf8->relaxed->escape_slash->loose->allow_singlequote->allow_barekey->decode($content);
Here is what I have currently that grabs the value that I want from $content. All I need is the first result which is why I am killing the loop after the first run. Everytime I have tried this without a loop I get "Not a HASH reference". So all I need to know is the correct syntax for printing out the value of $timestamp.
foreach my $field(#{$json_text->{factMap}->{'T!T'}->{rows}}){
my $now = time();
my $timestamp = str2time($field->{dataCells}[1]->{'label'});
my $diff = int (($now - $timestamp)/60);
my $current = getLoggingTime();
print $current . " \t";
say "Time since last activity: " . $diff . " minutes!" ;
last;
}
sub getLoggingTime {
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime(time);
my $nice_timestamp = sprintf ( "%04d-%02d-%02d %02d:%02d:%02d",
$year+1900,$mon+1,$mday,$hour,$min,$sec);
return $nice_timestamp;
}
I don't know what your without-a-loop version looks like, but this should work:
my $timestamp = str2time(
$json_text->{factMap}{'T!T'}{rows}[0]{dataCells}[1]{label}
);
Currently, you're looping over the elements of the array referenced by
$json_text->{factMap}{'T!T'}{rows}
...and stopping at the first entry
$json_text->{factMap}{'T!T'}{rows}[0]
...and dereferencing that to get to
$json_text->{factMap}{'T!T'}{rows}[0]{dataCells}[1]{label}