Read text after last backslash - powershell

I am would like to read in the text after the last backslash from my text file. Currently I have:
$data=Get-Content "C:\temp\users.txt"
The users.txt file contains path from users home directories
\\myserver.home.com\users\user1.test
How can I pick out the users account (user1.test) name at the end of the line of text so I can use it as a variable?

You can use a simple regex to remove everything until and including the last slash:
$user = $data -replace '.*\\'

Since you are dealing with file paths, you can use GetFileName:
$data=Get-Content "C:\temp\users.txt"
$name=[System.IO.Path]::GetFileName($data)

$HomeDirArray = Get-Content "C:\temp\users.txt" | Split-Path -Leaf will give you an array that can be iterated through using ForEach (e.g., ForEach ($User in $HomeDirArray) {...}.

You can use Split and [-1] to get the string after the last backslash:
$data = Get-Content "C:\temp\users.txt"
$file = ($data -split '\\')[-1]
This uses two backslashes as backslash is a regex special character (escape) so the first slash is escaping the second.

Related

Split string in Powershell

I have sth written in a ".ini" file that i want to read from PS. The file gives the value "notepad.exe" and i want to give the value "notepad" into a variable. So i do the following:
$CLREXE = Get-Content -Path "T:\keeran\Test-kill\test.ini" | Select-String -Pattern 'CLREXE'
#split the value from "CLREXE ="
$CLREXE = $CLREXE -split "="
#everything fine untill here
$CLREXE = $CLREXE[1]
#i am trying to omit ".exe" here. But it doesn't work
$d = $CLREXE -split "." | Select-String -NotMatch 'exe'
How can i do this ?
#Mathias R. Jessen is already answered your question.
But instead of splitting on filename you could use the GetFileNameWithoutExtension method from .NET Path class.
$CLREXE = "notepad.exe"
$fileNameWithoutExtension = [System.IO.Path]::GetFileNameWithoutExtension($CLREXE)
Write-Host $fileNameWithoutExtension # this will print just 'notepad'
-split is a regex operator, and . is a special metacharacter in regex - so you need to escape it:
$CLREXE -split '\.'
A better way would be to use the -replace operator to remove the last . and everything after it:
$CLREXE -replace '\.[^\.]+$'
The regex pattern matches one literal dot (\.), then 1 or more non-dots ([^\.]+) followed by the end of the string $.
If you're not comfortable with regular expressions, you can also use .NET's native string methods for this:
$CLREXE.Remove($CLREXE.LastIndexOf('.'))
Here, we use String.LastIndexOf to locate the index (the position in the string) of the last occurrence of ., then removing anything from there on out

Replace a non-unique line of text under a unique line of text in a text file using powershell

I have the following txt file.
[AppRemover]
Enable=0
[CleanWipe]
Enable=0
[RerunSetup]
Enable=0
How do I change the Enable=0 to Enable=1 under [CleanWipe] only?
Below is how I plan on using the code with my file.
$Path = C:\temp\file.txt
$File = Get-Content -Path $Path
# Code to update file
$File | Out-File $Path
You can use -replace to update the value if it is 0.
$Path = C:\temp\file.txt
(Get-Content $Path -Raw) -replace "(?<text>\[CleanWipe\]\r?\nEnable=)0",'${text}1' |
Set-Content $Path
Using a module that parses INI files will be the best solution though. I'd recommend trying PsIni.
Explanation:
The -Raw switch reads the file contents as a single string. This makes it easier to work with newline characters.
-replace performs a regex match and then replace. Below is the regex match breakdown.
(?<text>) is a named capture group. Anything matched within that capture group can be recalled in the replace string as '${text}'.
\[CleanWipe\] is a literal match of [CleanWipe] while escaping the [] characters with \.
\r? is optional carriage return
\n is the newline character
Enable= is a literal match
0 is a literal match
The replace string is the capture group contents and 1 when a match exists. Technically, a capture group is not needed if you want to use a positive lookbehind instead. The positive lookbehind assertion is (?<=). That solution would look like the following:
$Path = C:\temp\file.txt
(Get-Content $Path -Raw) -replace "(?<=\[CleanWipe\]\r?\nEnable=)0",'1' |
Set-Content $Path
The problem with the -replace solutions as they written is they will update the file regardless of a change actually being made to the contents. You would need to add an extra comparison to prevent that. Other issues could be extra white space on any of these lines. You can account for that by adding \s* where you think those possibilities may exist.
Alternative With More Steps:
$file = Get-Content $Path
$TargetIndex = $file.IndexOf('[CleanWipe]') + 1
if ($file[$TargetIndex] -match 'Enable=0') {
$file[$TargetIndex] = 'Enable=1'
$file | Set-Content $Path
}
This solution will only update the file if it meets the match condition. It uses the array method IndexOf() to determine where [CleanWipe] is. Then assumes the line you want to change is in the next index.
IndexOf() is not the only way to find an index. The method requires that your line match the string exactly. You can use Select-String (case-insensitive by default) to return a line number. Since it will be a line number and not an index (indexes start at 0 while line numbers start at 1), it will invariably be the index number you want.
$file = Get-Content $Path
$TargetIndex = ($file | Select-String -Pattern '[CleanWipe]' -SimpleMatch).LineNumber
if ($file[$TargetIndex] -match 'Enable=0') {
$file[$TargetIndex] = 'Enable=1'
$file | Set-Content $Path
}

PowerShell to remove text after a special character in URL list

I am trying to filter list of URL's, where some of the URL's having "/" character after domain name (.com or .pl ..etc). I am trying to write PowerShell script to remove any text after "/" from the URL.
Tried below scripts, but didn't worked.
(Get-Content "C:\Work\url123.txt" -Raw) -replace "/" | Set-Content "C:\Work\url12.txt"
// this removes the "/" character and combine the URL's
Input
www.xyz.com
www.abc.com/dummypage/login
www.123.com/login.php?
Expected Output
www.xyz.com
www.abc.com
www.123.com
You can use the following if your URLs don't contain protocols.
(Get-Content "C:\Work\url123.txt") -Replace "(.*?)/.*",'$1'
If you are expected to have protocols in your listings (URIs and URLs), then the following will work:
(Get-Content "C:\Work\url123.txt") -Replace ".*//|(.*?)/.*",'$1'
Since the -Replace operator uses Regex, I'll explain the syntax.
.*//: Matches all characters up to and including two forward slashes.
|: Alternative character (OR)
(.*?): Match as few characters as possible (lazy matching) and store as capture group 1 ($1).
/: Match forward slash literally
$1: Capture group 1.
You can use split:
$a = "ffff/666666/iiii"
$b = $a.Split('/') #is an array with all the substrings separated by /
$b[0] # is the first element
result: 'ffff'
one line: $b = $a.Split('/')[0]
so the code should look like:
(Get-Content "C:\Work\url123.txt" -Raw) | $_.split('/')[0] | Set-Content "C:\Work\url12.txt"

Data manipulation in PowerShell

I'm wondering if anyone has any suggestions on how to handle what I want to do in PowerShell.
I have this data in a text file:
"0003233","9/1/2017","0241902","$12,145.05"
"FGENERAL","MY VENDOR","VENDOR COMPANY INC.",""
"1","Check(s)","Checks Total:","$12,145.05"
I want to run PowerShell to make it look like this:
"0003233","9/1/2017","0241902","MY VENDOR","VENDOR COMPANY INC.","$12,145.05"
I have experience with simpler data manipulation, but I'm stumped on how to handle this one. Can anyone suggest something?
Thanks
Get contents from file,
Use select-string with regex to split the string at the quotes.
Use the string array to build your final output.
$string = Get-Content "C:\Test\Test.txt"
$StringArray = Select-String "([`"'])(?:(?=(\\?))\2.)*?\1" -input $string -AllMatches | Foreach {$_.matches.Value}
write-output "$($StringArray[0]),$($StringArray[1]),$($StringArray[2]),$($StringArray[5]),$($StringArray[6]),$($StringArray[11])"
You could use Get-Content to read the text file in. At that point you have an array of lines. If you know for sure the order of the lines are the same each time then you can create a new array or string, depending on your needs, from the text file array.
$textFile = Get-Content -Path "C:\..." #reads in the text file
$lineOne = $textFile[0].Split(",") #splits the first line based on commma, repeat for each line
$formattedLine = $lineOne[0] + "," $lineOne[5] #creates new string
This would allow you to restructure the data into the format you want.
$Data = Import-Csv .\Data.txt -Header 0,1,2,3
$Data[0]."0", $Data[0]."1", $Data[0]."2", $Data[0]."3", $Data[1]."1", $Data[1]."2", $Data[2]."3" -Join ","

Remove last character from txt file

I need to remove last character in text file and set this content. First I have to find location the last character.
$dest= "K:\test.txt"
$count_characters= (Get-Content $dest | Measure-Object -Character).Characters
Now I know count of characters - the last one ($count_characters) I must remove and set content. Is it possible?
I would first access the last line using the array index -1. Then, You could use a simple regex which captures the whole line except the last chracter and replace it:
$dest= "K:\test.txt"
$replaceCharacter = 'A'
$content = Get-Content $dest
$content[-1] = $content[-1] -replace '^(.*).$', "`$1$replaceCharacter"
$content | Set-Content $dest