Not getting exact value in Variable becasue value contains $ char - powershell

I have a string "/Name Pa$Name#my"
$myname = GetContent("Name")
GetContent is only gets the key and gives the value for that Key. I cannot modify the GetContent function.
If i execute above, as "Pa$Name#my" contains the '$' char, $myname gives me value as "Pa#my" and ignores "$Name" content.
What can i do to get the $myname = Pa$Name#my ? Can i append some special characters while assigning the $myname variable.

As far as I understand your trouble comes from the fact that the var $name does not exist. You can use single qotes if you don't want Powershell to look for vars :
$a = 'Pa$Name#my'

Related

Powershell - Remove text and capitalise some letters

Been scratching my head on this one...
I'd like to remove .com and capitalize S and T from: "sometext.com"
So output would be Some Text
Thank you in advance
For most of this you can use the replace() member of the String object.
The syntax is:
$string = $string.replace('what you want replaced', 'what you will replace it with')
Replace can be used to erase things by using blank quotes '' for the second argument. That's how you can get rid of .com
$string = $string.replace('.com','')
It can also be used to insert things. You can insert a space between some and text like this:
$string = $string.replace('et', 'e t')
Note that using replace does NOT change the original variable. The command below will print "that" to your screen, but the value of $string will still be "this"
$string = 'this'
$string.replace('this', 'that')
You have to set the variable to the new value with =
$string = "this"
$string = $string.replace("this", "that")
This command will change the value of $string to that.
The tricky part here comes in changing the first t to capital T without changing the last t. With strings, replace() replaces every instance of the text.
$string = "text"
$string = $string.replace('t', 'T')
This will set $string to TexT. To get around this, you can use Regex. Regex is a complex topic. Here just know that Regex objects look like strings, but their replace method works a little differently. You can add a number as a third argument to specify how many items to replace
$string = "aaaaaa"
[Regex]$reggie = 'a'
$string = $reggie.replace($string,'a',3)
This code sets $string to AAAaaa.
So here's the final code to change sometext.com to Some Text.
$string = 'sometext.com'
#Use replace() to remove text.
$string = $string.Replace('.com','')
#Use replace() to change text
$string = $string.Replace('s','S')
#Use replace() to insert text.
$string = $string.Replace('et', 'e t')
#Use a Regex object to replace the first instance of a string.
[regex]$pattern = 't'
$string = $pattern.Replace($string, 'T', 1)
What you're trying to achieve isn't well-defined, but here's a concise PowerShell Core solution:
PsCore> 'sometext.com' -replace '\.com$' -replace '^s|t(?!$)', { $_.Value.ToUpper() }
SomeText
-replace '\.com$' removes a literal trailing .com from your input string.
-replace '^s|t(?!$), { ... } matches an s char. at the start (^), and a t that is not (!) at the end ($); (?!...) is a so-called negative look-ahead assertion that looks ahead in the input string without including what it finds in the overall match.
Script block { $_.Value.ToUpper() } is called for each match, and converts the match to uppercase.
-replace (a.k.a -ireplace) is case-INsensitive by default; use -creplace for case-SENSITIVE replacements.
For more information about PowerShell's -replace operator see this answer.
Passing a script block ({ ... }) to dynamically determine the replacement string isn't supported in Windows PowerShell, so a Windows PowerShell solution requires direct use of the .NET [regex] class:
WinPs> [regex]::Replace('sometext.com' -replace '\.com$', '^s|t(?!$)', { param($m) $m.Value.ToUpper() })
SomeText

Powershell Store Variables into Variable does not work

I need some help with Powershell, i hope somebody can help.
I want to store multiple Variables into one single variable.
Here is my code:
$Content = #"
$Var1 = "1"
$Var2 = "2"
$Var3 = "3"
"#
echo $Content
And thats my output:
echo $Content
= "1"
= "2"
= "3"
It should look like this:
$Var1 = "1", etc...
But every variable gets removed. I don't know why. Could somebody please explain this? Do i need to store them into something like an object?
Thanks in advance!
The quickest fix for your situation is to switch to a single-quoted here-string.
$Content = #'
$Var1 = "1"
$Var2 = "2"
$Var3 = "3"
'#
In general, double quotes around a string instruct PowerShell to interpolate. Single quotes around a string tells PowerShell to treat the content as a literal string. This also applies to here-strings (#""# and #''#).
# Double Quotes
$string = "my string"
"$string"
my string
#"
$string
"#
my string
# Single Quotes
'$string'
$string
#'
$string
'#
$string
When interpolation happens, variables are expanded and evaluated. A variable is identified starting with the $ character until an illegal character for a variable name is read. Notice in the example below, how the variable interpolation stops at the ..
"$string.length"
my string.length
You can use escape characters or other operators to control interpolation within double quoted strings. The subexpression operator $() allows an expression to be evaluated before it is converted into a string.
"$($string.length)"
9
The backtick character is the PowerShell escape character. It can be used to escape $ when you don't want it to be treated as a variable.
"`$string"
$string
Mixing quotes can create certain gotchas. If you surround your string with single quotes, everything inside will be a literal string regardless of using escape characters or subexpressions.
'"$($string.length)"'
"$($string.length)"
'"`$string"'
"`$string"
Surrounding your string with double quotes with inside single quotes will just treat the inside single quotes literally because the outer quotes determine how the string will be interpreted.
"'$string'"
'my string'
Using multiple single quote pairs or double quote pairs requires special treatment. In this unique situation for double quotes, you can use the backtick escape or a two " to print a single ".
"""$string"""
"my string"
"`"$string`""
"my string"
For multiple single quotes, you must use two ' because a backtick will be treated literally and not tell PowerShell to escape anything.
'''$string'''
'$string'
Please reference About_Quoting_Rules for official documentation.

Powershell skip element in array, if it blank

I have a powershell script, where I receive names of elements as a variables from Jenkins:
$IISarray = #("$ENV:Cashier_NAME", "$ENV:Terminal_NAME", "$ENV:Content_Manager_NAME", "$ENV:Kiosk_BO_NAME")
foreach ($string in $IISarray){
"some code goes here"
}
Sometimes random elements can be blank. How can I add a check to see if the current element in array is blank, skip it and go to next element?
It's easiest to use -ne '' to created a filtered copy of the array that excludes empty entries, courtesy of the ability of many PowerShell operators to act as a filter with an array-valued LHS.
Note: I'm assuming you mean to filter out empty strings, not also blank (all-whitespace) ones, given that undefined environment variables expand to an empty string.
# Sample array with empty elements.
# Note: No need for #(...), unless there's just *one* element.
$IISarray = "foo", "", "bar", "baz", ""
# Note the `-ne ''`, which filters out empty elements.
foreach ($string in $IISarray -ne ''){
$string # echo
}
The above yields:
foo
bar
baz
soundstripe's answer offers a Where-Object solution, which potentially provides added flexibility via the ability to specify an arbitrary filter script block, but the use of a pipeline is a bit heavy-handed for this use case.
Fortunately, PSv4+ offers the .Where() collection method, which performs noticeably better.
Let me demonstrate it with a solution that also rules out blank (all-whitespace) elements:
# Note the all-whitespace element, which we want to ignore too.
PS> ("foo", " ", "bar", "baz", "").Where({ $_.Trim() })
foo
bar
baz
Similar to the Where-Object cmdlet, you pass a script block to the .Where() method, inside of which the automatic $_ variable represents the input element at hand.
The .Trim() method trims leading and trailing whitespace from a string and returns the result.
An all-whitespace string therefore results in the empty string.
In a Boolean context (as the .Where() method script block implicitly is), the empty string evaluates to $false, whereas any non-empty string is $true.
You can choose to be explicit, however ($_.Trim() -ne ''), or even use a .NET method ([string]::IsNullOrWhiteSpace($_)).
You can use Where-Object to filter out null or empty values. It is very commonly used, so ? is shorthand for Where-Object.
$IISarray = #("$ENV:Cashier_NAME", "$ENV:Terminal_NAME", "$ENV:Content_Manager_NAME", "$ENV:Kiosk_BO_NAME")
foreach ($string in ($IISarray | ? {$_})){
"some code goes here"
}
The $_ is an automatic variable representing each incoming object in the pipeline. Both $null and the empty string '' are falsy in Powershell, so only non-null values with length > 0 will be passed in to your for loop.
# you can skip the `#` and brackets as well as the quotation marks
$IISarray = $ENV:Cashier_NAME, $ENV:Terminal_NAME, $ENV:Content_Manager_NAME, $ENV:Kiosk_BO_NAME
foreach($String in $IISarray) {
# trim the strings and check the length
if($String.Trim().Length -gt 0) {
"some code goes here"
}
}

Perl - add a variable in a variable

I want add the variable $hostname in the variable $hostame_table appended with _table.
My code:
use Sys::Hostname ();
my $hostname = Sys::Hostname::hostname();
my $hostname_table = "$hostname"+"_table";
print "$hostname_table";
I would like the result to be computername_table.
What you're looking for here is called "string concatenation". Perl uses a dot (.) as the concatenation operator, not the + which you've tried to use.
$hostname_table = $hostname . '_table';
print $hostname_table;
Update: Another common approach would be to just "interpolate" the values in a double-quoted string.
$hostname_table = "$hostname_table"; # This doesn't work.
Unfortunately, this simple approach doesn't work here as "_table" is valid as part of a variable name and, therefore, Perl doesn't know where your variable name ends. You can get around that by using a slightly more complex syntax which wraps the variable name in { ... }.
$hostname_table = "${hostname}_table";

Replace character in pig in HDInsight using powershell

My data is in the following format..
{"Foo":"ABC","Bar":"20090101100000","Quux":"{\"QuuxId\":1234,\"QuuxName\":\"Sam\"}"}
I need it to be in this format:
{"Foo":"ABC","Bar":"20090101100000","Quux":{"QuuxId":1234,"QuuxName":"Sam"}}
I'm trying to using Pig's replace function to get it in the format I need..
So, I tried as in here..
#Specify the cluster name
$clusterName = "CLUSTERNAME"
#Where the output will be saved
$statusFolder = "/tutorial/pig/status"
#Store the Pig Latin into $QueryString
$QueryString = "LOGS = LOAD 'wasb:///example/data/sample.log'as unparsedString:chararray;" +
"REPL1 = foreach LOGS REPLACE($0, '"\\{', '\\{');"
...and so on..
I receive an error at the second line (REPL1 =...)
Unexpected token '\\' in expression or statement.
Now this code works perfectly well when I run it using remote desktop
Any help is sincerely appreciated..
Thanks
I assume you attempt to store the following string value in the variable:
REPL1 = foreach LOGS REPLACE($0, '"\\{', '\\{');
The first "interpretation" of your string is by the PowerShell parser. Since you use double-quotes ("), it's treated as an expandable string.
Since you don't escape the " inside the REPLACE() statement, the parser assumes that the string stops there.
What you're left with is:
"REPL1 = foreach LOGS REPLACE(, '"
# a valid string, $0 expanded to an empty string
\\
# two slashes , PowerShell cannot resolve these to anything meaningful
{
# opening curly brace
', '
# a valid string literal
\\
# two slashes , PowerShell still cannot resolve these to anything meaningful
{
# opening curly brace
');"
# non-terminated string
You need to escape the " inside REPLACE(), either by using a two double-quotes in succession (""), or use the backtick escape sequence (\"`):
$QueryString += "REPL1 = foreach LOGS REPLACE($0, '`"\\{', '\\{');"
or
$QueryString += "REPL1 = foreach LOGS REPLACE($0, '""\\{', '\\{');"
Your might also want to escape $0, to avoid string expansion:
$QueryString += "REPL1 = foreach LOGS REPLACE(`$0, '""\\{', '\\{');"