Creating multi-line email body in powershell - email

I keep getting error when I am trying to implement multiple line email body. I am suspecting bad syntax. Can't find any example online. Any suggestions?
Error: Unexpected token 'EmployeeName"] to $AccountExpire"' in expression or statement.
$subject = "Email for $item["EmployeeName"]. Date expire $AccountExpire"
$body=#"
Name: $item["Employee"]
Class: Contractor
Depart: $item["Depart"]
Region: $item["Region"]
Manager: $item["Manager"]
New Date: $NewDate
"#
SendUpdateEmail($subject,$Body)

You need to escape those array index operations with a subexpression ($()):
$subject = "Email for $($item["EmployeeName"]). Date expire $AccountExpire"
Same goes for multi-line strings (or here-strings as they're formally called):
$body=#"
Name: $($item["Employee"])
Class: Contractor
# and so on...
"#
Personally, I'd go for a multi-line template and use the -f format operator to fill in the values:
$bodyTemplate=#'
Name: {0}
Class: Contractor
Depart: {1}
Region: {2}
Manager: {3}
New Date: {4}
'#
$body = $bodyTemplate -f $item["Employee"],$item["Depart"],$item["Region"],$item["Manager"],$NewDate
When using -f, you can also format different types of data, so if $NewDate is a [DateTime] object, you could control formatting for that inside the template, eg.:
#'
Date: {0:HH:mm:ss}
'# -f (Get-Date)
which would produce:
Date: 14:55:09
(assuming you did this a five to 3 in the afternoon)

Related

Passing list as an parameter in DRT template of Drools rule engine

I am trying to pass an array/list example- tag =["XYZ","ABC","PQR"] as an parameter to my template to generate drl using the java code and drools template API ObjectDataCompiler.
Template:
template header
tag
template "test for list"
rule "list_#{row.rowNumber}"
when
$list : List(${tag})
$value : String() from $list
then
System.out.println("yeah from template: "+ $value);
System.out.println("yeah from template: "+ $list.size());
System.out.println("yeah from template: "+ $list.get(1));
end
end template
Generate DRL file:
rule "list_0"
when
$list : List([XYZ, ABC, PQR])
$value : String() from $list
then
System.out.println("yeah from template: "+ $value);
System.out.println("yeah from template: "+ $list.size());
System.out.println("yeah from template: "+ $list.get(1));
end
Issue facing: I am unable to access the elements from the list. Is there anything that I am doing wrong?
There is no output printed for any of the System.out.println() why?
I tried evening using the tag[] in the template declaration, and in the template I have something like this "#{tag0}", when the rule is generated I get the values as like this "[XYZ" for the first and "PQR]" the last values.
Can you help me as I am getting an "[" "]" these square brackets for first and last values respectively?

Wazuh child decoder not parsing field correctly

I am trying to parse a log as shown below with a child decoder in wazuh 4.x, for some reason its not parsing the needed field
Log entry
ossec: output: 'domainjoin-cli query|grep -i Domain': Domain = mydomain.local
Child Decoder
<decoder name="ossec-domain">
<parent>ossec</parent>
<type>ossec</type>
<prematch>^ossec: output:</prematch>
<regex type="pcre2">^'domainjoin-cli[ \t]query|grep[ \t]-i[ \t]Domain':[ \t]Domain[ \t]=[ \t](\S+)</regex>
<order>domain</order>
</decoder>
Output
ossec: output: 'domainjoin-cli query|grep -i Domain': Domain = mydomain.local
**Phase 1: Completed pre-decoding.
full event: 'ossec: output: 'domainjoin-cli query|grep -i Domain': Domain = mydomain.local'
**Phase 2: Completed decoding.
name: 'ossec'
parent: 'ossec'
**Phase 3: Completed filtering (rules).
id: '100008'
level: '3'
description: 'Server is in domain '
groups: '['ossec']'
firedtimes: '1'
hipaa: '['164.312.b']'
mail: 'False'
pci_dss: '['10.6.1']'
**Alert to be generated.
Taking into account the parent decoder:
<decoder name="ossec">
<prematch>^ossec: </prematch>
<type>ossec</type>
</decoder>
First of all, you should delete the prematch tag since the parent has already a prematch regex. In case you want to leave the prematch, you can also use the offset field to indicate that the string output comes after ossec: .
<decoder name="ossec-domain">
<parent>ossec</parent>
<type>ossec</type>
<prematch offset="after_parent>^output:</prematch>
<regex type="pcre2">^'domainjoin-cli[ \t]query|grep[ \t]-i[ \t]Domain':[ \t]Domain[ \t]=[ \t](\S+)</regex>
<order>domain</order>
</decoder>
After that, note that the regex is wrong as you are using ^. ^ indicates the beginning of the log and in this case, the string after that character is not the beginning of the log. You have to remove that character from regex.
Also, you have to take into account that | indicates an OR operator which means that one regex (left) or the other (right) should match the log. In your use case, this should indicate the character so you will need to escape it not to use it as an OR operator.
Taking into account these indications, the following decoder is the one you should use:
<decoder name="ossec-domain">
<parent>ossec</parent>
<type>ossec</type>
<prematch offset="after_parent">^output:</prematch>
<regex type="pcre2">'domainjoin-cli[ \t]query\|grep[ \t]-i[ \t]Domain':[ \t]Domain[ \t]=[ \t](\S+)</regex>
<order>domain</order>
</decoder>
Logtest output:
ossec: output: 'domainjoin-cli query|grep -i Domain': Domain = mydomain.local
**Phase 1: Completed pre-decoding.
full event: 'ossec: output: 'domainjoin-cli query|grep -i Domain': Domain = mydomain.local'
**Phase 2: Completed decoding.
name: 'ossec'
parent: 'ossec'
domain: 'mydomain.local'
I hope this helps, if you have more problems please tell me the Wazuh version you are using and I will be glad to help.

Exract a id from git show using power shell

I have the below input from a GIT show:
commit d5089c3135e104c2b508fe58d98596c96b2ae19a Merge: bd82ec4 d36607b Author: Thomas <thomas#gmail> Date: Fri Feb 7 18:48:38 2020 +0000 Merged in test_cicd (pull request #93) PIS-504 id="VN.P.1.0.1"
I need to parse the id and then save to the variable .
EX : VN.P.1.0.1
Mycode is
$build = git show
$id = if ($build -match '\bid=("\d"+)\b') { $Matches[1] }
but not working..help anyone?
After you find the idenclosed in double-quotes, get everything not a double quote:
$id = if ($build -match '\bid="([^"]+)"') { $Matches[1] }
# this ^^^^^
Update: based on comments, guessing the actual git output is different than what's displayed in the OP's example. Replaced with \s whitespace character word boundary metacharacter.

pass json as parameter in power shell script

I have made a function for creating new xml node.there are two parameters in my function on is a existing xml file reference and second one is element value.while running the script its showing an error
code
function createProviderNode($xmlData,$propertyValue){
Write-Host 'inside createProviderNode'
Write-Host ($propertyValue)
#[xml]$xmlData = get-content E:\powershell\data.xml
$newProviderNode = $xmlData.CreateNode("element","provider","")
$newProviderNode.SetAttribute("name",$propertyValue)
$xmlData.SelectSingleNode('providers').AppendChild($newProviderNode)
$xmlData.save("E:\powershell\data.xml")
}
did i miss anything in this code?
The error message implies that while you expected $xmlData to contain an object of type [xml] (System.Xml.XmlDocument) - i.e., an XML document - in reality it was a string ([string]).
In other words: When you called your createProviderNode function, the 1st argument you passed was a string, not an XML document (of type [xml]).
Typing your $xmlData parameter variable as [xml] solves this problem, as that will implicitly covert even a string argument to an XML document on demand - if possible.
A simplified example, using a script block in lieu of a function:
$xmlString = #'
<?xml version="1.0"?><catalog><book id="bk101"><title>De Profundis</title></book></catalog>
'#
# Note how $xmlData is [xml]-typed.
& { param([xml] $xmlData) $xmlData.catalog.book.title } $xmlString
The above yields De Profundis, demonstrating that the string argument was converted to an [xml] instance (which - thanks to PowerShell's type adaptation magic - makes the element names available as direct properties).
It is then safe to call the .CreateNode() method on $xmlData.
Well, you don't show your original XML format.
Why did you comment out that Get-Content? it will not work without it.
So, if we take the below example, it works as expected.
# Simple XML version
$SimpleXml = $null
$SimpleXml = #"
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<name>Apple</name>
<size>1234</size>
</configuration>
"#
# New node code
[xml]$XmlDoc = Get-Content -Path variable:\SimpleXml
$runtime = $XmlDoc.CreateNode("element","runtime","")
$generated = $XmlDoc.CreateNode("element","generatePublisherEvidence","")
$generated.SetAttribute("enabled","false")
$runtime.AppendChild($generated)
$XmlDoc.configuration.AppendChild($runtime)
$XmlDoc.save("$pwd\SimpleXml.xml")
Get-Content -Path "$pwd\SimpleXml.xml"
# Which creates this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<name>Apple</name>
<size>1234</size>
<runtime>
<generatePublisherEvidence enabled="false" />
</runtime>
</configuration>
Also Write-Host is never needed unless you are coloring screen output.
Write-Output is the default and automatically write to the screen, whether you specify Write-Output or not.
So, all of these to the same thing - output to the screen.
$SomeString = 'hello'
Write-Host $SomeString
Write-Output $SomeString
'hello'
"hello"
$SomeString
"$SomeString"
($SomeString)
("$SomeString")
$($SomeString)
# Results
hello
hello
hello
hello
hello
hello
hello
… yet, it's your choice.

How do I use a secret variable in a vsts release task?

I've got a release definition in vsts that needs access to a password I've defined as a secret variable in a variable group. I've linked that group to this release definition but when I run the task the parameter ends up blank. Is there anything special I need to do to get the value of a secret variable?
Definition of the powershell task that uses the password
Linked variable group
Error output:
2017-08-09T14:01:17.9262375Z ##[command]. 'C:\agent_work\r1\a\$(AGENT.BUILDDIRECTORY)\RCV\deploys\common\Get-FromArtifactory.ps1' -repoUsername developer -repoPassword -repoPath libs-snapshot-local
2017-08-09T14:01:18.8168538Z ##[error]C:\agent_work\r1\a\$(AGENT.BUILDDIRECTORY)\RCV\deploys\common\Get-FromArtifactory.ps1 : Missing an argument for parameter 'repoPassword'. Specify a parameter of type 'System.String' and try again.
Edited to add more info as requested.
This is the start of my Get-FromArtifactory.ps1
[CmdletBinding()]
param (
[Parameter(Mandatory)]
[String]
$repoUsername,
[Parameter()]
[String]
$repoPassword,
# Other params
)
#setup credentials object for arty access
$secPassword = $repoPassword | ConvertTo-SecureString -asPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($repoUsername, $secPassword)
Edit 15/08/2017 - I've updated it to use quotes as suggested by #Marina-MSFT but it's still just passing in blank.
Amended script to print out part of password:
[CmdletBinding()]
param (
[Parameter(Mandatory)]
[String]
$repoUsername,
[Parameter()]
[String]
$repoPassword,
#other params
)
write-host "pword $repoPassword"
write-host "1st char: $($repoPassword[0])"
2017-08-15T09:23:00.8606081Z ##[command]. 'C:\agent_work\r1\a\RCV\deploys\common\Get-FromArtifactory.ps1' -repoUsername developer -repoPassword "" -repoPath libs-snapshot-local -artifactName ipo-deposit-accounts_2.11 -artifactPath uk/gov/ipo -artifactVersion 0.1-SNAPSHOT -downloadDir C:\agent_work\r1\a
2017-08-15T09:23:02.3606174Z pword
2017-08-15T09:23:02.3606174Z 1st char:
Same with single quotes
2017-08-15T09:22:10.6573655Z ##[command]. 'C:\agent_work\r1\a\RCV\deploys\common\Get-FromArtifactory.ps1' -repoUsername developer -repoPassword '' -repoPath libs-snapshot-local -artifactName ipo-deposit-accounts_2.11 -artifactPath uk/gov/ipo -artifactVersion 0.1-SNAPSHOT -downloadDir C:\agent_work\r1\a
2017-08-15T09:22:11.2198723Z pword
2017-08-15T09:22:11.3761178Z 1st char:
I've got it working now, there were 2 things going on.
Having . in the name of a secret variable in a variable group
doesn't work. I recreated this issue in a separate release
definition/variable group.
Even after I removed the . in my var
names I still had to recreate the variable group for it to work.
Bug for issue with . in variable name raised here: https://developercommunity.visualstudio.com/content/problem/94475/secret-variable-in-variable-not-group-not-availabl.html