Powershell variable expansion along with a single quote - powershell

In the expression below I would like $key variable to be expanded to
"//configuration[#navtitle='Some Report']"
How do I achieve that? know that $key value is derived from external file
$key = "Some Report"
Xml.SelectNodes("//configuration[#title=$key]")

Single quotes won't be parsed within double quotes. You could put the single quotes in $key or the string:
$key = "'Some Report'"
"//configuration[#title=$key]"
Output:
//configuration[#title='Some Report']
OR
$key = "Some Report"
"//configuration[#title='$key']"

Related

How to cut specific characters in a string and save it to a new file?

I have a string, and I want to cut some characters and store it to a new file.
I tried this code, but it still error.
$a = ";Code=NB"
$b = $a -split "="
$b[1]
$Save = "[AGM]", "CR=JP", "LOC= $b[1]"| Out-File "C:\Users\Out.txt"
Try something like this:
$a = ";Code=NB"
$null, $b, $null = $a -split '=', 3
$b
$Save = "[AGM]", "CR=JP", "LOC= $b"| Out-File "C:\Users\Out.txt"
Something that would be easier to maintain would be this:
#Words to remove from string
$wordsToCut = "This","is"
#Phrase to remove words from
$phrase = "This is a test"
#Running through all words in words to remove
foreach ($word in $wordsToCut){
#Replace current word with nothing
$phrase = $phrase.Replace($word,"")
}
#Output end result
Write-Host $phrase
You would also use trim to remove any leading or trailing spaces. The above code outputs:
a test

Remove duplicate curly braces from string

This one is how I build the string and assign that to a variable:
$package = $package+$component+"=[{"+$componentField+":"+$componentValue+"}"
Write-Host $package
Output:
efc90fde-c75c-d5e5-bd3e-7f7ce358e2e2=[{{artifacturl:http://10.1.18.12:8088/job/Xyz/640/artifact/target/xyz.war}}
Expecting:
efc90fde-c75c-d5e5-bd3e-7f7ce358e2e2=[{artifacturl:http://10.1.18.12:8088/job/Xyz/640/artifact/target/xyz.war}
Just do:
$package = $package+$component+"=[{"+$componentField+":"+$componentValue+"}".Replace("{{", "{")..Replace("}}", "}")
BTW, this should also do the trick:
$package = $package+$component+ "=[$componentField:$componentValue"
You could also use a regex to replace the string:
$package -replace '({|})\1', '$1'
Demo.
However, I would suggest you to build the string using a format string:
$package = '{0}{1}=[{2}:{3}' -f $package, $component, $componentField, $componentValue

Echo string showing escaped characters

Is there a way to echo a string showing the escaped characters in powershell? I am looking for something similar to the repr function in python. I would like to use this for debugging.
For example:
>>$var="abc`ndef"
>>echo $var
Output:
abc
def
Desired output:
"abc`ndef"
or
abc`ndef
This will unescape the ` replacing it with a \
Hence the -replace at the end:
$var="abc`ndef"
$var = [System.Text.RegularExpressions.Regex]::Escape($var) -replace '\\','`'
echo $var
Output:
abc`ndef
I know this is not what you want, but will work fine :)
function Get-EscapedString([string] $String) {
$escape = #{
"`0"='`0';
"`a"='`a';
"`b"='`b';
"`f"='`f';
"`n"='`n';
"`r"='`r';
"`t"='`t';
"`v"='`v'
}
$str = $String
foreach ($char in $escape.Keys) {
$str = $str -replace $char, $escape[$char]
}
$str
}
Surround the string with single-quotes and the escape sequences won't be interpreted:
"abc`ndef"
outputs
abc
def
but
'abc`ndef'
outputs
abc`ndef

get output of execution perl

Usually to get the output of a command I run from perl I use back tick
my $value = `pwd`;
How do I do it though if I need to insert a variable within the back ticks ``?
Text inside backticks is interpolated before it is passed to the operating system in the same way as text inside double quotes. So these statements all do what they look like they do:
$value = `$command`;
$value = `$someCommand $arg`;
$value = `$someOtherCommand #list`;
qx() is another way of running an external command and returning the output. If for some reason you don't want Perl to interpolate your command, you can run qx with the single-quote delimiter.
$value = qx'echo $PATH'; # shell's $PATH, not Perl's $PATH
You can just insert it. E.g.
my $dir = "/home"
my $text = `ls -l $dir`;
print $text;
my $hello = "world";
my $value = ` echo $hello `;
print $value;
Use qx() instead of backticks. Eg. my ($used, $dir); ($used) = qx(du -k $dir);

How to substitute arbitrary fixed strings in Perl

I want to replace a fixed string within another string using Perl. Both strings are contained in variables.
If it was impossible for the replaced string to contain any regex meta-characters, I could do something like this:
my $text = 'The quick brown fox jumps over the lazy dog!';
my $search = 'lazy';
my $replace = 'drowsy';
$text =~ s/$search/$replace/;
Alas, I want this to work for arbitrary fixed strings. E.g., this should leave $text unchanged:
my $text = 'The quick brown fox jumps over the lazy dog!';
my $search = 'dog.';
my $replace = 'donkey.';
$text =~ s/$search/$replace/;
Instead, this replaces dog! with donkey., since the dot matches the exclamation mark.
Assuming that the variable contents themselves are not hardcoded, e.g., they can come from a file or from the command line, is there a way to quote or otherwise markdown the contents of a variable so that they are not interpreted as a regular expression in such substitution operations?
Or is there a better way to handle fixed strings? Preferably something that would still allow me to use regex-like features such as anchors or back-references.
Run your $search through quotemeta:
my $text = 'The quick brown fox jumps over the lazy dog!';
my $search = quotemeta('dog.');
my $replace = 'donkey.';
$text =~ s/$search/$replace/;
This will unfortunately not allow you to use other regex features. If you have a select set of features you want to escape out, perhaps you can just run your $search through a first "cleaning" regex or function, something like:
my $search = 'dog.';
$search = clean($search);
sub clean {
my $str = shift;
$str =~ s/\./\\\./g;
return $str;
}
Wrap your search string with \Q...\E, which quotes any meta characters within.
$text =~ s/\Q$search\E/$replace/;
#Replace a string without using RegExp.
sub str_replace {
my $replace_this = shift;
my $with_this = shift;
my $string = shift;
my $length = length($string);
my $target = length($replace_this);
for(my $i=0; $i<$length - $target + 1; $i++) {
if(substr($string,$i,$target) eq $replace_this) {
$string = substr($string,0,$i) . $with_this . substr($string,$i+$target);
return $string; #Comment this if you what a global replace
}
}
return $string;
}