Add-Content to txt - powershell

I'm trying to make a GUI that will print the information from a textbox into a .txt in a way that I will try to explain as well as I can.
$TextBox_UsbName.text = "TestingTesting"
$Button_SetUsbName.Add_Click({ $Value_UsbName = $TextBox_UsbName.text; add-content -path $Value_NewScriptPath -value "$usbname = $Value_UsbName" })
After this is run I was hoping the text file would contain this:
$usbname = "TestingTesting"
I am still new to Powershell as well as coding in general and now I am really stuck I have tried a lot of different ways.
Any ideas and help would be much appreciated.
Edit: My result is
=

In Powershell double quoted string literals, string interpolation takes place each time an unescaped $ appears with a valid identifier characters after it. To introduce a literal $ that should not be parsed as part of an interpolated variable, you should escape it with a backtick, `.
Here is some quick string interpolation help:
How do I expand an expression in a string?
Windows PowerShell will expand a variable or an expression in a string.
Variables look like: $variable
Expressions look like: $(expression)
So, your "$usbname = $Value_UsbName" is interpreted by the engine as value of $usbname variable followded with = enclosed with spaces, and then a value of $Value_UsbName variable.
What you want to add is a literal $usbname substring and the value of $TextBox_UsbName.text expression.
So, either use
"`$usbname = $($TextBox_UsbName.text)"
Or just concatenate values (in a culture independent way):
$usbname + ' = ' + $TextBox_UsbName.text

Related

Putting Powershell variable in double quotes shows Object type instead of value

I see this problem in several area, but here is an example
I read an xml document like this and print out a value
[xml]$pom = get-content -path pom.xml
PS C:\> $pom.project.artifactId
nexus-peter-test-service
However, if I put the value in double quotes, I get this
"$pom.project.artifactId"
System.Xml.XmlDocument.project.artifactId
I need the value in double quotes because it's part of a long string. In my case, a url. So I'm using it like this:
"/$pom.project.artifactId/"
Why does Powershell change the meaning of the variable when in it's double quotes? And how can I fix this?
The problem is that the interpolation stops at the period. It interpolates "$pom" - which stringifies as the class name - followed by the literal string ".project.artifactId".
To interpolate anything more complex than a simple variable name, you need to wrap $(...) around the expression:
"$($pom.project.artifactId)"

How to identify a character in a string?

I am trying to write a Powershell code to identify a string with a specific character from a filename from multiple files.
An example of a filename
20190902091031_202401192_50760_54206_6401.pdf
$Variable = $Filename.Substring(15,9)
Results:
202401192 (this is what I am after)
However in some instances the filename will be like below
20190902091031_20240119_50760_54206_6401.pdf
$Variable = $Filename.Substring(15,9)
Results:
20240119_ (this is NOT what I am after)
I am trying to find a code to identify the 9th character,
IF the 9th character = "_"
THEN Set
$Variable = $Filename.Substring(15,8)
Results:
20240119
All credit to TheMadTechnician who beat me to the punch with this answer.
To expand on the technique a bit, use the split method or operator to split a string every time a certain character shows up. Your data is separated by the underscore character, so is a perfect example of using this technique. By using either of the following:
$FileName.Split('_')
$FileName -split '_'
You can turn your long string into an array of shorter strings, each containing one of the parts of your original string. Since you want the 2nd one, you use the array descriptor [1] (0 is 1st) and you're done.
Good luck

Powershell - add variables inside a json string

I have the following json code in my powershell script.
I set the $variable to 1111111111
$jsonfile = '{"Version": "2012-10-17","Statement": {"Effect": "Allow","Action": "sts:AssumeRole","Resource": "arn:aws:iam::$variable:role/xxxxxx"}}'
The output gives ....arn:aws:iam::$variable:role/xxxxxx..... instead of ....arn:aws:iam::1111111111:role/xxxxxx
The problem is that I must use the single quote for the json string otherwise I will get an error. If I use single quote I wont be able to put the variables inside the string. How do I workaround this problem?
There are various ways to solve your problem, but perhaps the easiest approach is to use PowerShell's string interpolation:
use a double-quoted string overall to enable interpolation of embedded variable references and subexpressions ($(...)).
escape embedded " chars. as `" (using backticks)
disambiguate variable references by enclosing the variable name in {...}.
Simplified example:
PS> $variable='111'
PS> "{`"Version`": `"arn:aws:iam::${variable}:role/xxxxxx`"}}"
{"Version": "arn:aws:iam::111:role/xxxxxx"}}
Note that enclosing variable names in {...} in interpolated strings is only necessary if the following char. could be misinterpreted as part of the variable name.
A : following the variable name - as is the case here - is such a case, because PS variables can have a scope specifier preceding the variable name that is separated from the variable name with :, such as in $env:USERNAME.
DAXaholic's helpful answer shows an alternative based on PowerShell's binary -f operator, which is essentially the same as the .NET framework's String.Format method; as such:
it introduces additional complexity, such as needing to know what its escaping rules are ({ chars. must be escape as {{, and how to format its arguments specified on the RHS of -r ({0} refers to the 1st RHS argument, ...)
on the flip side, -f offers many sophisticated formatting options.
Also, consider use of the Convert*-Json cmdlets his answer demonstrates: even though they're less performant, they ultimately make manipulation of JSON much easier and more robust.
Alternatives in the realm of native PowerShell code:
String concatenation with the binary + operator:
'{"Version": "arn:aws:iam::' + $variable + ':role/xxxxxx"}}'
String templating with $ExecutionContext.InvokeCommand.ExpandString():
$variable='111'
$tmpl = '{"Version": "arn:aws:iam::${variable}:role/xxxxxx"}}' # string template *literal*
$ExecutionContext.InvokeCommand.ExpandString($tmpl) # performs on-demand interpolation
Another solution would be
$jsonfile = '{{"Version": "2012-10-17","Statement": {{"Effect": "Allow","Action": "sts:AssumeRole","Resource": "arn:aws:iam::{0}:role/xxxxxx"}}}}' -f $variable
So you have to escape the braces with another brace but in your case you have fewer braces than quotes so it is "less obfuscation" :)
In your case, maybe the simplest solution is just concatenating the strings together instead of using string formatting / interpolation.
In addition you could also go the way with the JSON cmdlets:
$jsonfile |
ConvertFrom-Json |
% { $_.Statement.Resource = "arn:aws:iam::${variable}:role/xxxxxx"; $_ } |
ConvertTo-Json

Ignore space in string stored in argument perl

I'm trying to execute a .VB script along with some other arguments.
I'm calling system("$cmd"), where
my $cmd = "Report.exe $app_env $rpt_Dir $eff_date";
and
my $rpt_Dir = "\\\\server\\folder\\Target Report\\test";
The problem I am having is that (I think) the space between "Target Report" is making the script treating it as 2 arguments.
And the reason why I didn't just surround the path with "" and pass it as an argument instead of saving it to a variable is that the path changes based on the date.
And it's not a first choice that I change the code in the .VB script.
On Windows, the system call uses cmd.exe to process commands, so you need double quotes around any parameters that contain spaces
Set your $cmd up like this
my $cmd = qq{Report.exe $app_env "$rpt_Dir" $eff_date};
The qq{...} construction is identical to ordinary double quotes, but it allows you to choose your own delimiters so that you don't have to escape any embedded double quotes
Then you can write
system($cmd);
It is wrong to put quotes around a solitary scalar variable
You can pass an array of args to system. If you do this, you won't be tripped over by quote interpolation.
system ( "Report.exe", $app_env, $rpt_Dir, $eff_date );
You can simply enclose the $rpt_Dir variable in single quotes:
my $cmd = "Report.exe $app_env '$rpt_Dir' $eff_date";
and it will be treated as a single arguement

Powershell: Doubled double quotes in inline expressions

Please could anyone explain me why the following happens:
"Fancy string - Hor""ray"
# outputs correctly (only one double quote): Fancy string - Hor"ray
'Hor"ray'.Replace('"', '""')
# outputs correctly (two double quotes): Hor""ray
"Fancy string - $('Hor"ray'.Replace('"', '"'+'"'))"
#outputs correctly (two double quotes): Hor""ray
"Fancy string - $('Hor"ray'.Replace('"', '""'))"
# outputs INCORRECTLY (only one double quote): Fancy string - Hor"ray
In my opinion, developers would intuitively expect, that within "$(inline expressions)" Powershell would treat text as statements and won't interfere with the last argument of Replace('"', '""') converting it into '"' (unless the statement interpreter decides to do so).
Do I miss something here?
This appears to be a bug in how PowerShell parses expandable string literals.
From ยง2.3.5.2 on string literals in the PowerShell 3.0 Language Specification, the expandable-string-literal explicitly rejects the $( sequence so that sub-expression parsing will occur instead.
So it seems reasonable to expect $('""') to parse consistently, whether or not it happens to be embedded in a string literal. And clearly sub-expressions are parsed separately, since they support values that would be illegal on their own in an expandable string (e.g. you can write "$('"')" or "$('`""')", where " '"' " or " '`""' " would fail).
However, comparing the AST from [Management.Automation.Language.Parser]::ParseInput for both $('""') and "$('""')", we get two different results. Both have a final StringConstantExpressionAst element with an Extent of '""', but the Value for the stand-alone sub-expression is "" while the Value for the embedded sub-expression is ".
Its because the inline expression is evaluated and its string value is then placed in the string and evaluated.
#Breaking "Fancy string - $('Hor"ray'.Replace('"', '""'))" down
#This inline expression is evaluated first
$('Hor"ray'.Replace('"', '""'))
#giving
Hor""ray
#That value is then interpreted as part of the string
"Fancy string - Hor""ray"
#giving
Fancy string - Hor"ray
This is exactly what I would expect to see. The inline expression evaluated and its resulting value then being used.
Could this not be done by simply using things like below:
`'$($RemFiles[$i].FullName)`'
`"$($RemFiles[$i].FullName)`"
Use the backtick and either a single or double quote to then prevent powershell from using this as an open comment, thus putting the actual symbol in...
The above outputs:
'F:\portable\adobe'
or
"F:\portable\adobe"
I noticed that it seems you are telling it to literally add two double quotes rather than just using the backtick to force it. Therefore telling it to add nothing surely :S So could you change this to something like this:
"Fancy string - $('Hor"ray'.Replace('"', '`"`"'))"
Though that may make 3, as you have one present in Hor"ray anyway.
Just got to test it, was busy with something:
PS D:\> "Fancy string - $('Hor"ray'.Replace('"', '`"`"'))"
Fancy string - Hor""ray
Scroll down on the site below to find out about the backtick and how/where it can be used.
http://www.neolisk.com/techblog/powershell-specialcharactersandtokens