Delete content between 2 lines - powershell

I have a pacfile which I am trying to update and need to remove content between two strings; the strings themselves should be kept:
// OFFICE 365 DIRECT ACCESS
and
// END OFFICE 365 DIRECT ACCESS
example:
// OFFICE 365 DIRECT ACCESS
if (isInNet(hostip, "23.103.132.0","255.255.252.0") || //EOP
isInNet(hostip, "23.103.136.0","255.255.248.0") || //EOP
isInNet(hostip, "23.103.144.0","255.255.240.0") || //EOP
isInNet(hostip, "23.103.191.0","255.255.255.0") || //EOP
// END OFFICE 365 DIRECT ACCESS
I want to remove the lines between the top and bottom lines
$Pacfile = Get-ChildItem .\o365.pac | Get-Content -Raw
$startstring= " \/\/ OFFICE 365 DIRECT ACCESS(.*? )\/\/END OFFICE 365 DIRECT ACCESS"
$NewPacfile = [regex]::match($Pacfile, $startstring).Groups[1].value
$NewPacfile

$regex=#'
(?ms)^(\s*// OFFICE 365 DIRECT ACCESS\s*?\r?\n).*?\r?\n(\s*// END OFFICE 365 DIRECT ACCESS\s*)
'#
(Get-Content -Raw .\o365.pac) -replace $regex, '$1$2'
-replace $regex, '$1$2' replaces what the regex matched with what the 1st ($1) and 2nd capture groups ($2) (parenthesized subexpression, (...)) inside of it matched.
Here, these capture groups capture the strings enclosing the range of interest.
(?ms) sets both the multi-line and the single-line option for the regex:
m means that ^ and $ should match the start and end of each line rather than the input string as a whole.
s means that metacharacter . should match \n characters too, so that an expression such as .* can be used to match across lines.
\r?\n matches a single line break, both the CRLF and the LF variety.
.*? matches the part to remove; note the non-greedy modifier (?) following .*, which ensures that the next occurrence of the end string is matched.

Related

Renaming the 4th character through the 12th

Here is what I have.
get-childitem "\\myfileserver\out\*" | foreach { rename-item $_ $_.Name.Replace("_123456_837P.", ".").Replace(".test.", ".sa.").Replace("_987654_837I." , ".") }
Here is the filename I want to fix
999_987654_837I.74161.test
I want to remove _987654_837I from the file name. I was just going to rename it but those numbers may change. So now I want to remove the 4th character starting at the _ and back to the "I" or 9th character.
You can use a regex pattern to get the required part.
See regex example + explanation:
https://regex101.com/r/xNoBVD/2
I use positive lookbehind to force regex to get the first 3 characters at the very beginning of the line (^) without capturing it. The following 12 characters are captured and can then be replaced with ''
$regexReplacePattern = '(?<=^.{3}).{12}'
'999_987654_837I.74161.test' -replace $regexReplacePattern, ''

Powershell - Split a string on a character

I've got a CSV file full of filepaths like below:
D:\CompanyData\REPORTS\ENQUIRIES\Old House Farm\Images
D:\CompanyData\REPORTS\ENQUIRIES\Quay House\Text
D:\CompanyData\REPORTS\ENQUIRIES\Church Road\Photography
D:\CompanyData\REPORTS\ENQUIRIES\Church Road\Reports\
D:\CompanyData\REPORTS\ENQUIRIES\Church Road\Reports\Images
I want to split them on the 5th '/' character to return the following (including the last trailing '/'
D:\CompanyData\REPORTS\ENQUIRIES\Old House Farm\
D:\CompanyData\REPORTS\ENQUIRIES\Quay House\
D:\CompanyData\REPORTS\ENQUIRIES\Church Road\
D:\CompanyData\REPORTS\ENQUIRIES\Church Road\
D:\CompanyData\REPORTS\ENQUIRIES\Church Road\
So far I've tried the following:
$source = $Item.Source.Split("\")[0]
And various other combinations of the above but can't quite get what I'm after. Can anyone assist?
Try like this:
[string](Split-Path "PATH")+"\"
If you have $Item.Source then:
[string](Split-Path "$($Item.Source)")+"\"
Here is another solution using Select-String
(Note, that the pattern uses regex, so you need to escape the backslash \ with another backslash \)
$source = ($($Item.Source) | Select-String -Pattern '.+\\.+\\.+\\.+\\.+\\' -AllMatches).Matches.Value
Output:
D:\CompanyData\REPORTS\ENQUIRIES\Old House Farm\
D:\CompanyData\REPORTS\ENQUIRIES\Quay House\
D:\CompanyData\REPORTS\ENQUIRIES\Church Road\
D:\CompanyData\REPORTS\ENQUIRIES\Church Road\Reports\
D:\CompanyData\REPORTS\ENQUIRIES\Church Road\Reports\
You can split each file path on the backslash to get an array of parts. Then join a maximum of 5 parts with a backslash and append another backslash tyo that:
$parts = "D:\CompanyData\REPORTS\ENQUIRIES\Old House Farm\Images" -split '\\'
'{0}\' -f ($parts[0..[math]::Min($parts.Count, 4)] -join '\')
Or do this with regex:
"D:\CompanyData\REPORTS\ENQUIRIES\Old House Farm\Images" -replace '^(([^\\]+\\){1,5}).*', '$1'
Regex details:
^ Assert position at the beginning of the string
( Match the regular expression below and capture its match into backreference number 1
( Match the regular expression below and capture its match into backreference number 2
[^\\] Match any character that is NOT a “A \ character”
+ Between one and unlimited times, as many times as possible, giving back as needed (greedy)
\\ Match the character “\” literally
){1,5} Between one and 5 times, as many times as possible, giving back as needed (greedy)
)
. Match any single character that is not a line break character
* Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
Result:
D:\CompanyData\REPORTS\ENQUIRIES\Old House Farm\
Simple regex version:
$Item.Source -replace "(('[^\\]+\\){1,5}).*", '$1'
[^\\]+\\ matches 1-n non-\ followed by \
{1,5} repeat the pattern 5 times

Trim Powershell OutPut

Requirement is to trim the Output. Retain only the output quoted within double quotes from Name and remove/avoid the earlier lines/characters
From:
$R.Output = \\GBVServer1\root\cimv2:Win32_Group.Domain="Contoso",Name="Domain Users"
$R.Output = \\GBVServer1\root\cimv2:Win32_SystemAccount.Domain="GBVServer1",Name="INTERACTIVE"
To:
$R.Output = Domain Users
$R.Output = INTERACTIVE
Could somebody assist with the powershell switch to be used?
You can do this with regex to capture only the Name part between the quotes for these strings:
$regex = [regex]'(?i)Name="([^,]+)"'
$string = '\\GBVServer1\root\cimv2:Win32_Group.Domain="Contoso",Name="Domain Users"'
$R.Output = $regex.Match($string).Groups[1].Value # --> Domain Users
$string = '\\GBVServer1\root\cimv2:Win32_SystemAccount.Domain="GBVServer1",Name="INTERACTIVE"'
$R.Output = $regex.Match($string).Groups[1].Value # --> INTERACTIVE
Regex details:
Name=" Match the characters “Name="” literally
( Match the regular expression below and capture its match into backreference number 1
[^,] Match any character that is NOT a “,”
+ Between one and unlimited times, as many times as possible, giving back as needed (greedy)
)
" Match the character “"” literally
The (?i) makes the match case-insensitive

How to replace a character at the end of a string/file?

I'm trying to remove a rogue comma at the end of my file when formatting with PowerShell. The file in question contains the user's city, region, and country.
Example:
San Diego, California, US,
But I want it to be:
San Diego, California, US
How can I remove this last ', ' at the end using -replace?
My code doesn't work below:
(Get-Content file.txt) | ForEach-Object {
$_ -replace ', ', ''
} | Set-Content file.txt
I just need a way of detecting that last ', ' that appears in my file without removing every comma that exists in the file.
You need to anchor your expression at the end of the string. In regular expressions that is done with a $ character. Add a \s* if you want to ignore trailing whitespace after that last comma:
$_ -replace ',\s*$'
You can also simply use the LastIndexOf function of the String class combined with a Substring.
$test = "San Diego, California, US, "
Write-Host $test.Substring(0, $test.LastIndexOf(','))
output: San Diego, California, US
Pretty self explaining --> You select from the start of the string until the last index of your specified char or string.
This is, assuming you always have your rogue comma at the end of the string, otherwise it will trim the text after a "good" comma.
while the regex solution is likely faster than string methods, you can use string methods to do the job. [grin]
use .Trim() to remove any leading or trailing whitespace
use .TrimEnd(',') to remove any trailing comma chars
like this ...
'San Diego, California, US, '.Trim().TrimEnd(',')
output = San Diego, California, US

Replace string with Powershell

I have a .properties file in which I want to replace the string Compass with BBB. My question is : I want to extract string which is belong
name , JDBC/ , ds_name = '' , java.lang.String then I will update with a new one. BTW, data source name is not fixed its dynamic variable. Just I have written it as sample string.
I have tried the following PowerShell code:
$DName = read-host -prompt "Please Enter Database Name"
ForEach ($client in (Get-Content Clients.txt)) {
(Get-Content "\\$client\D$\Runtime\run.properties") -replace "$old database name which is extract","$DName" |
Out-File "\\$client\D$\Runtime\run.properties"
}
run.properties:
dsid = AdminTask.createDatasource(provider_id, '[-name Compass -jndiName jdbc/Compass
-dataStoreHelperClassName com.ibm.websphere.rsadapter.MicrosoftSQLServerDataStoreHelper
-componentManagedAuthenticationAlias TEMP-HRZEMM01Node01/PlatformDataSource -containerManagedPersistence true
-xaRecoveryAuthAlias TEMP-HRZEMM01Node01/PlatformDataSource -configureResourceProperties [[databaseName java.lang.String Compass] [portNumber java.lang.Integer 1433] [serverName java.lang.String SQLSVR1]]]')
AdminConfig.create('MappingModule', dsid , '[[authDataAlias TEMP-HRZEMM01Node01/PlatformDataSource] [mappingConfigAlias ""]]')
ds_name = 'Compass' #Name copied from your question, update if required
If I understand the question correctly, you would like to first find the database name (which can be anything, Compass is just an example) stored in the .properties file and if found replace that by a value entered in the console.
In that case, I think this should do it:
$newDbName = Read-Host -prompt "Please Enter Database Name"
$clientFile = "Clients.txt"
ForEach ($client in (Get-Content $clientFile)) {
$content = Get-Content "\\$client\D$\Runtime\run.properties" -Raw
# see if we can extract the database name from the file
if ($content -match '(?:-name\s+|jdbc/|databaseName java\.lang\.String\s+|ds_name = '')(?<dbname>[^\s''\]]+)') {
$oldDbName = $matches['dbname']
Write-Host "Replacing '$oldDbName' with '$newDbName' for client '$client'"
($content -replace $oldDbName, $newDbName) |
Out-File "\\$client\D$\Runtime\run.properties"
}
else {
Write-Warning "Could not parse the old database name from '\\$client\D$\Runtime\run.properties'.."
}
}
Regex explanation
(?: Match the regular expression below
Match either the regular expression below (attempting the next alternative only if this one fails)
-name Match the characters “-name” literally
\s Match a single character that is a “whitespace character” (spaces, tabs, line breaks, etc.)
+ Between one and unlimited times, as many times as possible, giving back as needed (greedy)
| Or match regular expression number 2 below (attempting the next alternative only if this one fails)
jdbc/ Match the characters “jdbc/” literally
| Or match regular expression number 3 below (attempting the next alternative only if this one fails)
databaseName\ java Match the characters “databaseName java” literally
\. Match the character “.” literally
lang Match the characters “lang” literally
\. Match the character “.” literally
String Match the characters “String” literally
\s Match a single character that is a “whitespace character” (spaces, tabs, line breaks, etc.)
+ Between one and unlimited times, as many times as possible, giving back as needed (greedy)
| Or match regular expression number 4 below (the entire group fails if this one fails to match)
ds_name\ =\ ' Match the characters “ds_name = '” literally
)
(?<dbname> Match the regular expression below and capture its match into backreference with name “dbname”
[^\s'\]] Match a single character NOT present in the list below
A whitespace character (spaces, tabs, line breaks, etc.)
The character “'”
A ] character
+ Between one and unlimited times, as many times as possible, giving back as needed (greedy)
)