Substring is getting too less data - powershell

I want to grab lots of text content from a .sql file between a --Start and --End comment.
Whatever I do somehow I don`t get the substring method correctly to grab only the text within the --Start and --End comment:
text.sql
This text I want not
--Start
this text I want here
--End
This text I want not
This is what I tried:
$insertStartComment = "--Start"
$insertEndComment = "--End"
$content = [IO.File]::ReadAllText("C:\temp\test.sql")
$insertStartPosition = $content.IndexOf($insertStartComment) + $insertStartComment.Length
$insertEndPosition = $content.IndexOf($insertEndComment)
$content1 = $content.Substring($insertStartPosition, $content1.Length - $insertEndPosition)
$content = $content1.Substring(0,$content1.Length - $insertEndPosition)
It would be nice if someone could help me out find my error :-)

There's an attempt to use uninitialized variable in the code:
$content1 = $content.Substring($insertStartPosition, $content1.Length - $insertEndPosition)
The variable $content1 isn't initialized yet, thus the substring call goes haywire. When you run the code again, the variable is set - and results are even more weird.
Use Powershell's Set-StrictMode to enable warnings about uninitialized variables.

It's not the substring approach you are looking for, but I figured that I would toss out a RegEx solution. This will find the text between the --Start and --End on a text file. In this case, I am grouping the matched text with a named capture called LineYouWant and display the matches that it finds. This also works if you have multiple instances of --Start--End blocks in a single file.
$Text = [IO.File]::ReadAllText("C:\users\proxb\desktop\SQL.txt")
[regex]::Matches($Text,'.*--Start\s+(?<LineYouWant>.*)\s+--End.*') | ForEach {
$_.Groups['LineYouWant'].Value
}

Related

Running a for loop in Powershell

I am new o scripting in powershell and am from a Python background. I want to know if I'm doing this right.
I created this array and want to extract each item one by one
$M365_E3_Grps = ("O365-CHN-DomainUser,O365-Vendor-Exchange-User")
ForEach ($Indiv_Grp in $M365_E3_Grps) {
ForEach ($Indiv_Grp in $M365_E3_Grps) {
`$ADGroup = $Indiv_Grp$ADGroup = $Indiv_Grp`
I want to know if we can extract vals with a for loop like this and assign it to a variable like this.
Construct of your array
Your array is not quite correct and will be populated as a string. To create a string array you will need to quote each item in comma separated list. The parentheses are also not required.
$M365_E3_Grps = "O365-CHN-DomainUser","O365-Vendor-Exchange-User"
Your foreach keyword syntax is however correct, even if the formatting in your question was slightly off.
foreach ($Indiv_Grp in $M365_E3_Grps) {
# Assigning $Indiv_Grp to $ADGroup here is kind of redundant since
# the value is already assinged to $Indiv_Grp
$Indiv_Grp
}

Error with Substring()

$fileName = "Name of TheFolder_NE_ED"
$lengthFileName = $fileName.length
$shortenLengthFileName = $lengthFileName - 5
Write-Host("Name of TheFolder_NE_ED").Substring($shortenLengthFileName,$lengthFileName)
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
I am having a problem with SubString() function, it errors with:
I tried printing out values of my variables but they seemed fine.
In PowerShell, substring works in a slightly different way.
With your existing code you could try this:
$fileName = "Name of TheFolder_NE_ED"
$lengthFileName = $fileName.length
$shortenLengthFileName = $lengthFileName - 5
Write-Host("Name of TheFolder_NE_ED").Substring($shortenLengthFileName)
Explanation:
The first parameter inside Substring should be the starting index of the character(in this case 18). Now from that letter it will start counting till the character (which you have to pass as a second parameter). Else it will by default go to the end of the string.
So, if you want to pass 2 parameters and do that, then change it to:
Write-Host("Name of TheFolder_NE_ED").Substring($shortenLengthFileName,5)
For further reference, follow Substring Use
Hope it helps.

perl script for find and replace or insert if blank

I am trying to write a perl script to search a config file for the following line:
remote_phonebook.data.1.url =
and do 1 of 2 things:
if the right of side of the = is blank add someString
if there is something there, replace anything there with someString
This will insert just fine:
s/remote_phonebook\.data\.1\.url = /remote_phonebook.data.1.url = someString/;
however if someString already exists, it will append it to look like this:
remote_phonebook.data.1.url = someString someString
This will replace just fine if someString already exists, but wont insert if its blank.
s/remote_phonebook\.data\.1\.url = someString/remote_phonebook.data.1.url = someString/;
.* is your friend, here. It means "match 0 or more (*) of any character (.)":
s/remote_phonebook\.data\.1\.url =.*/remote_phonebook.data.1.url = someString/;
So whether or not there is anything after the =, you'll end up with the contents you want. To make sure that you're matching from the start of the line (so "xxxremote_phonebook..." won't match), and to allow for more (or less) space before the "=", I'd use:
s/^remote_phonebook\.data\.1\.url\s*=.*/remote_phonebook.data.1.url = someString/;
s/^\s*remote_phonebook\.data\.1\.url\s*=\K.*/someString/;
The .* will match anything up to a newline.
The \K makes it so you don't have to repeat everything.

Saving specific areas of a filename

I have a list of pdf files in this format "123 - Test - English.pdf". I want to be able to set "111", "Test" and "English.pdf" in their own individual variables. I tried running the code below but I don't think it accounts for multiple dashes "-". How can I do this? Please help Thanks in advance.
Loop,C:\My Documents\Notes\*.pdf, 0, 0
{
NewVariable = Trim(Substr(A_LoopFileName,1, Instr(A_LoopFileName, "-")-1))
I would recommend using a parse loop to get your variables. The following loops through values between the dashes and removes the whitespace.
FileName = Test - file - name.pdf
Loop, parse, FileName, `-
MyVar%A_Index% := RegExReplace(A_LoopField, A_Space, "")
msgbox % Myvar1 "`n" Myvar2 "`n" MyVar3
First, I don't know if it was a typo, but if you use a { under your loop statement, you also need to close it. If your next statement is just one line, you don't need any brackets at all.
Second, if you just use = then your code will output as just that very code text. You need to use a :=
Third, your present code, if coded correctly would result in this:
somepdffile.pd
if it found any pdf files without a dash. Instr() will return the position of a dash. If there is no dash, it returns 0 - in which case, your substr() statement will add 0 and your -1 which adds up to -1 and if you use a negative number with substr(), it will search from the end of the string instead of the beginning - which is why your string would get cut off.
Loop, C:\My Documents\Notes\*.pdf, 0, 0
{
;look at the docs (http://www.autohotkey.com/docs/) for `substr`
}
So there is an explanation of why your code doesn't work. To get it to do what you want to do, can you explain a bit more as to how you want NewVariable to look like?
; here is another way (via RegExMatch)
src:="123 - Test - English.pdf", pat:="[^\s|-]+"
While, mPos:=RegExMatch(src, pat, match, mPos ? mPos+StrLen(match):1)
match%A_Index%:=match
MsgBox, 262144, % "result", % match1 ", "match2 ", "match3

Powershell URL replace

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.