.ToString returns System.Object[] in Error - powershell-2.0

With PowerShell 2.0 if I run the following on a Windows 7 machine:
(Get-WmiObject Win32_NetworkAdapterConfiguration |
Where { $_.IPAddress }
it returns
192.168.83.26
fe80::<IPv6 address>
If I run:
(Get-WmiObject Win32_NetworkAdapterConfiguration |
Where { $_.IPAddress }.ToString()
It returns
System.Object[]
Why? And how can I resolve it?
FYI, I'm actually trying to use .ToString().split('.')[0..2] -join '.' but I'm pretty sure it's the .ToString that's causing the issue
function Get-IPAddress{
(Get-WmiObject Win32_NetworkAdapterConfiguration |
Where { $_.IPAddress } |
Select -Expand IPAddress).split('.')[0..2] -join '.'
}
Get-IPAddress
returns 192.168.10 on PoSh 3. This doesn't seem to work on PoSh 2, and returns the `System.Object[]' that I stated above. The error complains about not having a Method named trim. Others have suggested declaring it as a String, but I've been unable to make it work

Try this:
(Get-WmiObject Win32_NetworkAdapterConfiguration |
? { $_.IPAddress } ).ipaddress | % { ($_ -split '\.')[0..2]}
This:
(Get-WmiObject Win32_NetworkAdapterConfiguration | ? { $_.IPAddress } ).ipaddress
returns always an array of strings also in the case of a single ip address.

The reason it doesnt work is IPAddress property is part of a PropertySet, the console output makes it look like a string but it is not
Not entirely sure what you require for your end result but you can try
(Get-WmiObject Win32_NetworkAdapterConfiguration | %{ $_.IPAddress }) -join " "

As Christian mentioned, the $_.IPAddress property is an array of strings.
Get-WmiObject Win32_NetworkAdapterConfiguration | % {
if($_.IPAddress){
$_.IPAddress[0]
}
}
Using your string manipulation:
$ip = Get-WmiObject Win32_NetworkAdapterConfiguration | % { if($_.IPAddress){$_.IPAddress[0] }}
$ip.ToString().split('.')[0..2] -join '.'
10.15.0
As a one-liner:
(Get-WmiObject Win32_NetworkAdapterConfiguration | % { if($_.IPAddress){$_.IPAddress[0] }}).ToString().split('.')[0..2] -join '.'

toString is causing the problem.
you need to pipe "out-string"
the tostring() gives you the class type to string as defined

Related

Why isn't my Participle parser detecting anything?

I am writing a parser / lexer using Participle (a package for Golang) for use in a game. It's supposed to look like Bash commands, but be easier. (https://github.com/alecthomas/participle)
Here is the code that Participle uses to lex and parse the inputs. (They get processed additionally later.)
type Parsed struct {
Pos lexer.Position
FirstBlock Block ` ## `
Blocks []*BlockWithDelim ` ##* `
}
type Block struct {
Command string ` #Command `
Flags []*ArgFlag ` ##* `
Arguments []string ` #Argument* `
}
type BlockWithDelim struct {
Delimiter string ` #(";" | "|" | "\n" ) `
Block Block ` ## `
}
type ArgFlag struct {
Flag string ` "-" "-"? #Flag `
Value *string ` ("=" #Argument)? `
}
var omegaLexer = lexer.Must(ebnf.New(strings.ReplaceAll(`
Command = alpha {alpha} .
Flag = Ident .
Argument = Ident | String | RawString .
String = "\"" { "\u0000"…"\uffff"-"\""-"\\" | "\\" "\u0000"…"\uffff" } "\"" .
RawString = "§" { "\u0000"…"\uffff" - "§" } "§" .
Ident = (alpha | "_" ) { alpha | digit | "_" } .
Comment = "#" { "\u0000"…"\uffff" - "\n" } .
Whitespace = " " | "\t" | "\r" .
alpha = "a"…"z" | "A"…"Z" .
digit = "0"…"9" .
`, "§", "`"))) //replace § with ` to make reading easier, due to no escapes allowed in raw strings
var omegaParser = participle.MustBuild(&Parsed{},
participle.Lexer(omegaLexer),
participle.Unquote("String", "RawString"),
participle.Elide("Whitespace", "Comment"))
The problem is, it refuses to detect anything except commands with one argument which is a quoted string.
# This works
echo "quoted string"
# This doesn't
echo hello
# Returns this error:
# <source>:1:6: unexpected token "hello"
In addition, it doesn't recognize strings put directly in the struct tags. For example:
help -bool
# <source>:1:6: no match found for -
execute once; then -do="thingy"
# <source>:1:13: no match found for ;
I cannot figure why my code wouldn't work. I've tried to copy the TOML example as much as possible.
Here's the code (with imports and package snipped): https://pastebin.com/QDLiGmnu

Parser accepting corrupt input

I have a simple grammar like this:
grammar RuleDSL with org.eclipse.xtext.common.Terminals
generate ruledsl "http://www.ruledsl.org"
Model:
rules += Rule*;
Rule:
rule = 'Rule' '{' subrules += Subrule* '}'
;
Subrule: fieldA=ID opName=Operator fieldC=INT ';';
Operator:
'<' | '<=' | '=' | '>=' | '>'
;
And I wonder why this input is accepted:
Rule {
field1 > 5
field3 = a
}
This is parsed by
#RunWith(XtextRunner)
#InjectWith(RuledslInjectorProvider)
class RuledslParsingTest{
#Inject
ParseHelper<Model> parseHelper
#Test
def void loadModel() {
val result = parseHelper.parse('''
Rule {
field1 > 5
field3 = a
}
''')
println(result)
}
}
and yields - after some iterating through the tree and printing the Subrule -:
field1>5
field3=0
anull0
I can't figure out why this happens. In the generated Eclipse PlugIn, this input is labeled incorrect as it should be.
You an ask the result for its eResource and the Resource for its errors. you may have a look at ValidationTestHelper as well.

Parse log for Phone number and BYE via powershell

I need to parse phone numbers from a log file (which is a .txt).
I need to find the phone number along with the timestamp and date and then the corresponding terminated request (which is when the caller hangs up) for that phone number. All calls into the system are iniated with DNAME and ended with TERMINATED.
I've used the select-string command but i cant filter the data effectively
the data is as follows :
13/08/2015 08:57:46:849 | L:4831.1[Line:10003<<XXXXXXXXXX]: Updated OutCID:'Conference_Call' and DNName: 'CALLER '
13/08/2015 09:00:42:118 | Leg L:4839.1[Line:10003<<XXXXXXXXXX] is terminated: Cause: BYE from 66.23.190.100:5060
all phone numbers have been replaced by XXXXXXXX for safety.
Does anyone know of a more powerful command to do this?
more data
13/08/2015 08:55:27:554 | Session 1230943 of leg L:4820.1[Line:10003<<180012334545] is confirmed
13/08/2015 08:55:49:766 | Answer to offerer immediateily, other party (L:4820.1[Line:10003<<180012334545]) doesn't support re-invite
13/08/2015 08:55:49:972 | L:4820.1[Line:10003<<18001234545]: Updated OutCID: 'Conference_Call' and DNName: 'Joe Brown '
13/08/2015 08:55:49:972 | L:4820.1[Line:10003<<180012334545]: Target refresh is not possible: Line:10003<<18001334545 doesn't support re-INVITE
13/08/2015 08:55:49:972 | [CM503010]: Call(C:4820): Making route(s) from Line:10003<<18001334545 to <sip:811#127.0.0.1:5060>
13/08/2015 08:55:49:972 | [Flow] Call(C:4820): has built target endpoint: Ivr:811 for call from L:4820.1[Line:10003<<191944345740]
13/08/2015 08:55:49:972 | [CM503004]: Call(C:4820): Route 1: from L:4820.1[Line:10003<<18001233545] to T:Ivr:811#[Dev:sip:811#127.0.0.1:40600;rinstance=19fdaa2fa620113c]
13/08/2015 08:55:49:972 | [CM503027]: Call(C:4820): From: Line:10003<<18001334545 ("Glen Peaks " <sip:180012334545#98.100.70.194:5060>) to T:Ivr:811#[Dev:sip:811#127.0.0.1:40600;rinstance=19fdaa2fa620113c]
13/08/2015 08:55:49:972 | [Flow] Call(C:4820): making call from L:4820.1[Line:10003<<18001233545] to T:Ivr:811#[Dev:sip:811#127.0.0.1:40600;rinstance=19fdaa2fa620113c]
13/08/2015 08:55:50:027 | [CM503025]: Call(C:4820): Calling T:Ivr:811#[Dev:sip:811#127.0.0.1:40600;rinstance=19fdaa2fa620113c] for L:4820.1[Line:10003<<180012334545]
13/08/2015 08:55:50:181 | L:4820.3[Ivr:811] has joined to L:4820.1[Line:10003<<18001234545]
13/08/2015 08:55:50:181 | L:4820.1[Line:10003<<19914345740]: Terminating targets, reason: SIP ;cause=200 ;text="Call completed elsewhere"
Your question is not clear enough, though regarding the TimeStamp and Phone number you can use this:
$Array = #()
$text = cat C:\Test.txt
$TimeStamp = "\d{2}\D\d{2}\D\d{4}\s\d{2}\D\d{2}\D\d{2}\D\d{3}"
$Number = "\d{10}"
foreach ($Line in $text)
{
$Result = "" | Select TimeStamp,Number
$Result.TimeStamp = $Line | select-string -Pattern $TimeStamp -AllMatches | % { $_.Matches } | % { $_.Value }
$result.Number = $Line | select-string -Pattern $Number -AllMatches | % { $_.Matches } | % { $_.Value }
$Array += $Result
}
Please provide more info for the CALLER,Terminated etc. so i can help you find the correct Regex

Matching a "text" in line by line file with XText

I try to write the Xtext BNF for Configuration files (known with the .ini extension)
For instance, I'd like to successfully parse
[Section1]
a = Easy123
b = This *is* valid too
[Section_2]
c = Voilà # inline comments are ignored
My problem is matching the property value (what's on the right of the '=').
My current grammar works if the property matches the ID terminal (eg a = Easy123).
PropertyFile hidden(SL_COMMENT, WS):
sections+=Section*;
Section:
'[' name=ID ']'
(NEWLINE properties+=Property)+
NEWLINE+;
Property:
name=ID (':' | '=') value=ID ';'?;
terminal WS:
(' ' | '\t')+;
terminal NEWLINE:
// New line on DOS or Unix
'\r'? '\n';
terminal ID:
('A'..'Z' | 'a'..'z') ('A'..'Z' | 'a'..'z' | '_' | '-' | '0'..'9')*;
terminal SL_COMMENT:
// Single line comment
'#' !('\n' | '\r')*;
I don't know how to generalize the grammar to match any text (eg c = Voilà).
I certainly need to introduce a new terminal
Property:
name=ID (':' | '=') value=TEXT ';'?;
Question is: how should I define this TEXT terminal?
I have tried
terminal TEXT: ANY_OTHER+;
This raises a warning
The following token definitions can never be matched because prior tokens match the same input: RULE_INT,RULE_STRING,RULE_ML_COMMENT,RULE_ANY_OTHER
(I think it doesn't matter).
Parsing Fails with
Required loop (...)+ did not match anything at input 'à'
terminal TEXT: !('\r'|'\n'|'#')+;
This raises a warning
The following token definitions can never be matched because prior tokens match the same input: RULE_INT
(I think it doesn't matter).
Parsing Fails with
Missing EOF at [Section1]
terminal TEXT: ('!'|'$'..'~'); (which covers most characters, except # and ")
No warning during the generation of the lexer/parser.
However Parsing Fails with
Mismatch input 'Easy123' expecting RULE_TEXT
Extraneous input 'This' expecting RULE_TEXT
Required loop (...)+ did not match anything at 'is'
Thanks for your help (and I hope this grammar can be useful for others too)
This grammar does the trick:
grammar org.xtext.example.mydsl.MyDsl hidden(SL_COMMENT, WS)
generate myDsl "http://www.xtext.org/example/mydsl/MyDsl"
import "http://www.eclipse.org/emf/2002/Ecore"
PropertyFile:
sections+=Section*;
Section:
'[' name=ID ']'
(NEWLINE+ properties+=Property)+
NEWLINE+;
Property:
name=ID value=PROPERTY_VALUE;
terminal PROPERTY_VALUE: (':' | '=') !('\n' | '\r')*;
terminal WS:
(' ' | '\t')+;
terminal NEWLINE:
// New line on DOS or Unix
'\r'? '\n';
terminal ID:
('A'..'Z' | 'a'..'z') ('A'..'Z' | 'a'..'z' | '_' | '-' | '0'..'9')*;
terminal SL_COMMENT:
// Single line comment
'#' !('\n' | '\r')*;
Key is, that you do not try to cover the complete semantics only in the grammar but take other services into account, too. The terminal rule PROPERTY_VALUE consumes the complete value including leading assignment and optional trailing semicolon.
Now just register a value converter service for that language and take care of the insignificant parts of the input, there:
import org.eclipse.xtext.conversion.IValueConverter;
import org.eclipse.xtext.conversion.ValueConverter;
import org.eclipse.xtext.conversion.ValueConverterException;
import org.eclipse.xtext.conversion.impl.AbstractDeclarativeValueConverterService;
import org.eclipse.xtext.conversion.impl.AbstractIDValueConverter;
import org.eclipse.xtext.conversion.impl.AbstractLexerBasedConverter;
import org.eclipse.xtext.nodemodel.INode;
import org.eclipse.xtext.util.Strings;
import com.google.inject.Inject;
public class PropertyConverters extends AbstractDeclarativeValueConverterService {
#Inject
private AbstractIDValueConverter idValueConverter;
#ValueConverter(rule = "ID")
public IValueConverter<String> ID() {
return idValueConverter;
}
#Inject
private PropertyValueConverter propertyValueConverter;
#ValueConverter(rule = "PROPERTY_VALUE")
public IValueConverter<String> PropertyValue() {
return propertyValueConverter;
}
public static class PropertyValueConverter extends AbstractLexerBasedConverter<String> {
#Override
protected String toEscapedString(String value) {
return " = " + Strings.convertToJavaString(value, false);
}
public String toValue(String string, INode node) {
if (string == null)
return null;
try {
String value = string.substring(1).trim();
if (value.endsWith(";")) {
value = value.substring(0, value.length() - 1);
}
return value;
} catch (IllegalArgumentException e) {
throw new ValueConverterException(e.getMessage(), node, e);
}
}
}
}
The follow test case will succeed, after you registered the service in the runtime module like this:
#Override
public Class<? extends IValueConverterService> bindIValueConverterService() {
return PropertyConverters.class;
}
Test case:
import org.junit.runner.RunWith
import org.eclipse.xtext.junit4.XtextRunner
import org.xtext.example.mydsl.MyDslInjectorProvider
import org.eclipse.xtext.junit4.InjectWith
import org.junit.Test
import org.eclipse.xtext.junit4.util.ParseHelper
import com.google.inject.Inject
import org.xtext.example.mydsl.myDsl.PropertyFile
import static org.junit.Assert.*
#RunWith(typeof(XtextRunner))
#InjectWith(typeof(MyDslInjectorProvider))
class ParserTest {
#Inject
ParseHelper<PropertyFile> helper
#Test
def void testSample() {
val file = helper.parse('''
[Section1]
a = Easy123
b : This *is* valid too;
[Section_2]
# comment
c = Voilà # inline comments are ignored
''')
assertEquals(2, file.sections.size)
val section1 = file.sections.head
assertEquals(2, section1.properties.size)
assertEquals("a", section1.properties.head.name)
assertEquals("Easy123", section1.properties.head.value)
assertEquals("b", section1.properties.last.name)
assertEquals("This *is* valid too", section1.properties.last.value)
val section2 = file.sections.last
assertEquals(1, section2.properties.size)
assertEquals("Voilà # inline comments are ignored", section2.properties.head.value)
}
}
The problem (or one problem anyway) with parsing a format like that is that, since the text part may contain = characters, a line like foo = bar will be interpreted as a single TEXT token, not an ID, followed by a '=', followed by a TEXT. I can see no way to avoid that without disallowing (or requiring escaping of) = characters in the text part.
If that is not an option, I think, the only solution would be to make a token type LINE that matches an entire line and then take that apart yourself. You'd do that by removing TEXT and ID from your grammar and replacing them with a token type LINE that matches everything up to the next line break or comment sign and must start with a valid ID. So something like this:
LINE :
('A'..'Z' | 'a'..'z') ('A'..'Z' | 'a'..'z' | '_' | '-' | '0'..'9')*
WS* '=' WS*
!('\r' | '\n' | '#')+
;
This token would basically replace your Property rule.
Of course this is a rather unsatisfactory solution as it will give you the entire line as a string and you still have to pick it apart yourself to separate the ID from the text part. It also prevents you from highlighting the ID part or the = sign as the entire line is one token and you can't highlight part of a token (as far as I know). Overall this does not buy you all that much over not using XText at all, but I don't see a better way.
As a workaround, I have changed
Property:
name=ID ':' value=ID ';'?;
Now, of course, = is not in conflict any more, but this is certainly not a good solution, because properties can usually defined with name=value
Edit: Actually, my input is a specific property file, and the properties are know in advance.
My code now looks like
Section:
'[' name=ID ']'
(NEWLINE (properties+=AbstractProperty)?)+;
AbstractProperty:
ADef
| BDef
ADef:
'A' (':'|'=') ID;
BDef:
'B' (':'|'=') Float;
There is an extra benefit, the property names are know as keywords, and colored as such. However, autocompletion only suggest '[' :(

Antlr whitespace token error

I have the following grammar and I want to match the String "{name1, name2}". I just want lists of names/intergers with at least one element. However I get the error:
line 1:6 no viable alternative at character ' '
line 1:11 no viable alternative at character '}'
line 1:7 mismatched input 'name' expecting SIMPLE_VAR_TYPE
I would expect whitespaces and such are ignored... Also interesting is the error does not occur with input "{name1,name2}" (no space after ',').
Heres my gramar
grammar NusmvInput;
options {
language = Java;
}
#header {
package secltlmc.grammar;
}
#lexer::header {
package secltlmc.grammar;
}
specification :
SIMPLE_VAR_TYPE EOF
;
INTEGER
: ('0'..'9')+
;
SIMPLE_VAR_TYPE
: ('{' (NAME | INTEGER) (',' (NAME | INTEGER))* '}' )
;
NAME
: ('A'..'Z' | 'a'..'z') ('a'..'z' | 'A'..'Z' | '0'..'9' | '_' | '$' | '#' | '-')*
;
WS
: (' ' | '\t' | '\n' | '\r')+ {$channel = HIDDEN;}
;
And this is my testing code
package secltlmc;
public class Main {
public static void main(String[] args) throws
IOException, RecognitionException {
CharStream stream = new ANTLRStringStream("{name1, name2}");
NusmvInputLexer lexer = new NusmvInputLexer(stream);
CommonTokenStream tokenStream = new CommonTokenStream(lexer);
NusmvInputParser parser = new NusmvInputParser(tokenStream);
parser.specification();
}
}
Thanks for your help.
The problem is that you are trying to parse SIMPLE_VAR_TYPE with the lexer, i.e. you are trying to make it a single token. In reality, it looks like you want a multi-token production, since you'd like whitespace to be re-directed to hidden channel through WS.
You should change SIMPLE_VAR_TYPE from a lexer rule to a parser rule by changing its initial letter (or better yet, the entire name) to lower case.
specification :
simple_var_type EOF
;
simple_var_type
: ('{' (NAME | INTEGER) (',' (NAME | INTEGER))* '}' )
;
The defintion of SIMPLE_VAR_TYPE specifies the following expression:
Open {
followed by one of NAME or INTEGER
follwoed by zero or more of:
comma (,) followed by one of NAME or INTEGER
followed by closing }
Nowhere does it allow white-space in the input (neither NAME nor INTEGER allows it either), so you get an error when you supply one
Try:
SIMPLE_VAR_TYPE
: ('{' (NAME | INTEGER) (WS* ',' WS* (NAME | INTEGER))* '}' )
;

Resources