I think I have a simple problem but I can't seem to find the answer.
This is a part of the string I am working with
$text = "INDEPENDENT ELECTORAL AND BOUNDARIES COMMISSION
POLLING STATION: "ABC DEF GHIJKL (001)"
STREAM:123"
When I try to work with this, I get an error because of the double quotes in $text. I know I can escape the double quotes using a back tick, but the entire string is too big for me to go through it all.
I wonder if there is a simple way to ignore or remove all double (and single, too) quotes except for the first and last.
You can solve this by using here-strings:
$Text = #'
All the symbols I/ can ` hope for
between " the *>$ opening $() and closing ${}
of the symbols
'#
Use this: #' ... '#
Your string would look like this:
$text = #'
"INDEPENDENT ELECTORAL AND BOUNDARIES COMMISSION
POLLING STATION: "ABC DEF GHIJKL (001)"
STREAM:123"
'#
Related
I have this string
[{listenport:443,connectaddress:10.1.10.20,connectport:443,firewallrulename:port443,direction:Inbound,action:Allow,protocol:TCP},{listenport:80,connectaddress:10.1.10.20,connectport:80,firewallrulename:port80,direction:Inbound,action:Allow,protocol:TCP}]
i'm wondering how can I write a function to convert it to
[{"listenport":"443","connectaddress":"10.1.10.20","connectport":"443","firewallrulename":"port443","direction":"Inbound","action":"Allow","protocol":"TCP"},{"listenport":"80","connectaddress":"10.1.10.20","connectport":"80","firewallrulename":"port80","direction":"Inbound","action":"Allow","protocol":"TCP"}]
I have tried to use insert and indexof , but couldn't figure out how to do for an entire string
If you really have to work with this format and cannot produce well-formed JSON to begin with, at least in your sample input both the property names and values are composed only of characters that are either . or fall into the \w regex category, so a single -replace operation is possible:
#'
[{listenport:443,connectaddress:10.1.10.20,connectport:443,firewallrulename:port443,direction:Inbound,action:Allow,protocol:TCP},{listenport:80,connectaddress:10.1.10.20,connectport:80,firewallrulename:port80,direction:Inbound,action:Allow,protocol:TCP}]
'# -replace '[\w.]+', '"$&"'
The result is well-formed JSON, which you can pipe to ConvertFrom-Json for OO processing in PowerShell.
If you can only assume that the property names are composed of only \w characters:
#'
[{listenport:443,connectaddress:10.1.10.20,connectport:443,firewallrulename:port443,direction:Inbound,action:Allow,protocol:TCP},{listenport:80,connectaddress:10.1.10.20,connectport:80,firewallrulename:port80,direction:Inbound,action:Allow,protocol:TCP}]
'# -replace '(\w+):', '"$1":"' -replace '\}|(?<!\}),', '"$&'
eventually hacked it by using replace
$proxyinfosjson = $proxyinfosjson.Replace(',', '","').Replace('{', '{"').Replace('}', '"}').replace(':', '":"').Replace('}"', '}').Replace('"{', '{')
so ugly.. not proud of it.. but works..
I need to create a String from double the use String.Trim() to remove the full stop, but it doesn't remove it. I think there is also a way to do this numerically but I'd like to do it with the string. Is there a reason it won't remove it? The output from the code is 5.5
$MyDouble = 5.5
[String]$MyDouble2 = $MyDouble
$MyDouble2.Trim(".")
$MyDouble2
String.Trim() only trims from the beginning and end of strings, so it has no effect in your command, because the . only occurs inside your input string.
If you truly want to remove just the . and keep the post-decimal-point digits, use the -replace operator:
$MyDouble2 -replace '\.' # -> '55'
Note:
* -replace takes a regex (regular expression) as the search operand, hence the need to escape regex metacharacter . as \.
* The above is short for $MyDouble2 -replace '\.', ''. Since the replacement string is the empty string in this case, it can be omitted.
If you only want to extract the integer portion, use either 4c74356b41's .Split()-based answer, or adapt the regex passed to -replace to match everything from the . through the end of the string.
$MyDouble2 -replace '\..*' # -> '5'
#Matt mentions the following alternatives:
For removing the . only: Using String.Replace() to perform literal substring replacement (note how . therefore does not need \-escaping, as it did with -replace, and that specifying the replacement string is mandatory):
$MyDouble2.Replace('.', '') # -> '55'
For removing the fractional part of the number (extracting the integer part only), using a numerical operation directly on $MyDouble (as opposed to via the string representation stored in $MyDouble2), via Math.Floor():
[math]::Floor($MyDouble) # -> 5 (still a [double])
Looking at some documentation for .Trim([char[]]) you will see that
Removes all leading and trailing occurrences of a set of characters specified in an array from the current String object.
That does not cover the middle of strings, so using the .Replace() method would accomplish that.
I think there is also a way to do this numerically but I'd like to do it with the string.
Just wanted to mention that converting numbers to strings to then drop decimals via string manipulation is a poor approach. Assuming your example is what you are actually trying to do, I suggest using a static method from the [math] class instead.
$MyDouble = 5.5
[math]::Floor($MyDouble)
$MyDouble = 5.5
[String]$MyDouble2 = $MyDouble
$MyDouble2.Replace(".", "")
Well, why would it trim not the last (or first) character? It wouldn't, what you need (probably) is:
$MyDouble = 5.5
[String]$MyDouble2 = $MyDouble
$MyDouble2.Split(".")[0]
$MyDouble = 5.5
[String]$MyDouble2 = $MyDouble
$res=$MyDouble2 -split "\."
$res[0..($res.Count-1)] -join ""
I need to get some double quotations around the GUID=$ntds output. I have tried encompassing the entire string in double quotes to no avail. Single quotes won't work because of the variable.
$Site=Read-Host "ENTER SITE NAME"
$Server=Read-Host "ENTER SERVER NAME"
$NTDS=Get-ADObject -Identity "CN=NTDS Settings,CN=$server,CN=Servers,CN=$site,CN=Sites,CN=Configuration,$((Get-ADDomain).DistinguishedName)" |foreach {$_.objectguid}
write-host "Repadmin /showobjmeta" * "<GUID=$ntds>"
You can use another pair of double quotes to escape like
Write-Host "hello ""200mg"""
Which will output hello "200mg"
Your case it would be
write-host "Repadmin /showobjmeta""<GUID=$ntds>"""
I do not know powershell, but from other languages, you can try:
you can try using double-double quote "" where you want to have ".
"<GUID=""$ntds"">"
or you can try single quotes if permitted on the outside
'<GUID="$ntds">'
or you can try the backslash as escape character before the " making it
"<GUID=\"$ntds\">"
Just try and let me know if you succeeded.
Assuming:
Function Invoke-Foo {
Param(
[string[]]$Ids
)
Foreach ($Id in $Ids) {
Write-Host $Id
}
}
If I do this:
PS> Invoke-Foo -ids '0000','0001'
0000
0001
If I do this:
PS> Invoke-Foo -ids 0000,0001
0
1
In the second case, is there a way to prevent the coercion, other than make them explicit strings (first case)?
No, unfortunately not.
From the about_Parsing help file:
When processing a command, the Windows PowerShell parser operates
in expression mode or in argument mode:
- In expression mode, character string values must be contained in
quotation marks. Numbers not enclosed in quotation marks are treated
as numerical values (rather than as a series of characters).
- In argument mode, each value is treated as an expandable string
unless it begins with one of the following special characters: dollar
sign ($), at sign (#), single quotation mark ('), double quotation
mark ("), or an opening parenthesis (().
So, the parser evaluates 0001 before anything is passed to the function. We can test the effect of treating 0001 as an "Expandable String" with the ExpandString() method:
PS C:\> $ExecutionContext.InvokeCommand.ExpandString(0001)
1
At least, if you are sure that your ids are in the range [0, 9999], you can do the formatting like this:
Function Invoke-Foo {
Param([int[]]$Ids)
Foreach ($Id in $Ids) {
Write-Host ([System.String]::Format("{0:D4}", $Id))
}
}
More about padding numbers with leading zeros can be found here.
What important to note here:
Padding will work for numbers. I changed the parameter typing to int[] so that if you pass the strings they will be converted to numbers and the padding will work for them too.
This method (as it is now) limits you to the range of ids I mentioned before and it always will give you four-zeros-padded output, even if you pass it '003'
Trying to update a line using the code below.
$dburl = 70.186.192.52
$ptdb = 3388
$Se = "C:\File\location\edit.me"
(Get-Content $Se) |
ForEach-Object { $_ -replace ("http://127.0.0.1:8190/storage/server"), 'http://$dburl:$ptdb/storage/server' } | Set-Content $Se
The output is:
http://$dburl:$ptdb/storage/server or http://\70.186.192.52\:3388/storage/server
I have tried escaping the // and : but no luck in figuring this one out. Anyone have a better way to do this. I have looked through the site and none of the things that I have found address this direct situation. I say this so I don't get any negitive marks for not researching the code.
powershell replace special characters
This one gives me what I am getting. Instead of the variable being substituted they are just printed out exactly as they are typed in. I have tried double quotes and it prints the port but not the address. if I put any escape / or \ it just prints it out in front.
Thanks!
I'm surprised that worked at all. Try using double quotes around the replacement string e.g.:
$dburl = '70.186.192.52'
$ptdb = '3388'
... -replace ("http://127.0.0.1:8190/storage/server"), "http://${dburl}:$ptdb/storage/server"
Also, quote your two variable values.