I need to be able to have a URL stored in a variable in powershell, but the issue comes to the correct formating.
For example I need to format this URL
https://graph.windows.net/mytenantname/users?$top=999?api-version=1.6
But i need to replace mytenantname with a variable
"https://graph.windows.net/$mytenantname/users?$top=999?api-verion=1.6"
but doing this i can't keep the $top as PowerShell treats is as a variable too....
Use a backtick (`) on the dollar sign you want, and leave the variable dollar sign:
"https://graph.windows.net/$mytenantname/users?`$top=999?api-verion=1.6"
Related
I've been messing arround with Powershell and googling various things as I go along. This one is a little hard to put into words that google woule understand. I can get the indevidual lines of a text file in powershell by indexing:
$textFile = Get-Content "myText.txt"
$textFile[0]
This would output the first line of the text file. But when I put the text file in quotes it will output all lines, even with the index
"$textFile[0]"
How can I still get only get the line I want, while wrapping the variable in quotes? If I try "$textFile"[0] it will just give me the whole file as before. The reason I'm trying to do this is because I'm trying to make that one line of the text file part of a bigger string that I can execute
$remote = "Enter-PSSession -ComputerName`", textFile[0]"
Invoke-Expression $remote
This is my way of illustrating what I'm trying to do.
You can use any of the following methods:
# Sub-expression operator
"Some Text $($textFile[0])"
# String format operator
"My Text {0}" -f $textFile[0]
# Concatenation
("Text"+$textFile[0])
Surrounding double quotes tells PowerShell to expand the string inside. Any variables within will be interpolated. Variables begin with $ and their following names can only have certain characters without requiring a special escape. [ would require an escape and since it isn't escaped, PowerShell interprets the variable name ending with the character just before the [. Therefore $textFile is interpolated, the whole file contents are converted into a string, and [0] is appended to the end of the string.
You can see details of the operators at About_Operators.
See About_Variables for how to create a variable including cases with special characters even if that doesn't directly apply here.
This question was asked many times on SO and yet...
All I've seen were solutions where the input string has to be modified. Either by replacing all double quotes with single quotes or by using backticks.
But I have no control over the input string since I have no access to the source. I cannot change Hello "W"orld to Hello 'W'orld or Hello """W"""orld
What I can do is to wrap the whole string with any escaping characters. For example with single quotes around 'Hello "W"orld'. But none of thoses escaping mechanisms I tried worked. And I can change my PowerShell script
Q: How can I pass a string with double quotes to PowerShell as argument and retain the quotes?
How to reproduce
Save this
cls
write-host $args[0]
as PowerShell script echoArgs1.ps1 on your desktop.
Open a CMD window, navigate to your desktop folder and enter
powershell -file echoArgs1.ps1 "Hello "W"orld"
Current Output
Desired Output
You're using the $(CurText) macro to pass the currently selected text in Visual Studio to a PowerShell script file via an external tools definition.
Unfortunately, Visual Studio doesn't offer a way to escape double quotes in the selected text to guarantee that it is ultimately seen as-is by whatever external executable you pass it to.
(For most executables, including PowerShell, embedding literal " chars. in a "..."-enclosed argument requires escaping them as \" - see this answer for the full story.)
Due to this lack of proper escaping, PowerShell won't parse text passed as an argument to a script file (*.ps1) via the -File CLI parameter as expected if it contains literal " chars.
This is Visual Studio's shortcoming, but there is a workaround:
With just one argument being passed, inspect the raw command line via [Environment]::CommandLine, and consider everything after the *.ps1 file the argument, verbatim.
To simplify that process, pass $(CurText) without enclosing it in "..." in the external-tool definition (and make sure that it is separated from the previous token by just one space char.).
Inside of echoArgs1.ps1, use the following command to retrieve the argument verbatim:
$rawText = ([Environment]::CommandLine -split '\.ps1 ', 2)[-1]
The problem is that the command line interpreter has already removed the quotes. In other words, the quotes are already gone before the command reaches the PowerShell interpreter.
What you might try to do is: pulling the original bare command line ($MyInvocation.Line) and resolve the arguments by removing the command itself:
$FileName = [System.IO.Path]::GetFileName($MyInvocation.MyCommand.Path)
$Arguments = $MyInvocation.Line -Replace ("^.*\\" + $FileName.Replace(".", "\.") + "['"" ]\s*")
Write-Host $Arguments
Note that there are a few pitfalls with regards to the command filename in the command line:
it might contain a relative or absolute path
it might be quoted or not
I want replace a Letter with a literal $. I tried:
var s = string.replaceAll("Register","$10")
I want that this text Register saved to be changed to: $10 saved
Illegal group reference is the error I get.
If you look at the scaladoc for replaceAll, you'll see that it takes a regular expression string as the parameter. Escape the $ with a \, or use replaceAllLiterally
replaceAll uses a regular expressions to find the match. In the replacement string $ is a special character that refers to a specific capture group in the matching string. You have no capture groups so this is an error. It's not what you want anyway since you want the literal text "$10".
Usereplaceinstead ofreplaceAll`. It just does a direct string replacement.
I want to call a batch file with powershell, like this:
$databaseUrl = "jdbc:sqlserver://$($databaseConfig.Server):$($databaseConfig.Port);databaseName=$($databaseConfig.Name)"
./database/liquibase/liquibase.bat --url=$databaseUrl
My problem is that the = is replaced with a whitespace, leaving only --url as the first parameter. I try putting it in quotes:
.\database\liquibase\liquibase.bat "--url=$databaseUrl"
...with the same result. I read that I can use backtick to escape characters:
.\database\liquibase\liquibase.bat "--url`=$databaseUrl"
...but the equals sign still disappears. I have also tried using --% to prevent any formatting from happening:
.\database\liquibase\liquibase.bat --% "--url=$databaseUrl"
but then the variable $databaseUrl is interpreted verbatim.
Any help on how to pass the argument, unformatted, but with variables expanded would be greatly appreciated.
maybe tricky, but as the escape operator --% allow environmnent variable expansion you could try this :
$env:databaseUrl ="jdbc:sqlserver://$($databaseConfig.Server):$($databaseConfig.Port)"
$env:db="$($databaseConfig.Name)"
.\database\liquibase\liquibase.bat --% "--url=%databaseUrl%;databasename=%db%"
My PowerShell script has one parameter. It is invoked by a tool, which feeds it the argument. The argument contains special characters such as ', " and %. With special characters, PowerShell expects the argument to be surrounded by single or double quotes. What if the argument contains both single and double quotes? No problem. If the argument is surrounded by single quotes, use two single quotes instead of one inside the argument. If it surrounded by double quotes, use two double quotes instead of one inside the argument.
Problem: I cannot modify the argument before passing it to the script, i.e., I cannot double the single/double quotes in the argument. Is there anything I can do?
-Rohan.
EDIT #1:
Reason I cannot modify the argument is that it is automatically passed to the script by the tool.
EDIT #2:
The argument is a password and so, I need to accept and store it as a secure string in the script.
One option is to pass it as a base64-encoded string, and then decode it in the script:
Using Powershell -encodedcommand to pass parameters