How do I remove a character from a string in Powershell - powershell

I have a string written in XML which approximates to:
60-894-74987
I need a line in powershell that will remove the '-' in the string to leave me with '6089474987'
I've been trying to utilize the -replace function, but it either errors or breaks powershell.
the basic code is:
$serialnumber= $pcinfo[4] #([4]= <value>60-984-74987</value>)
$serialnumber= $serialnumber replace '-',"
I dont get an error with this, powershell gives me >>

Change
$serialnumber= $serialnumber -replace '-',"
to
$serialnumber= $serialnumber -replace '-'
If you're just deleting characters and not replacing them, you don't need explicit empty quotes.

You can simply write as C# fashion below.
$serialnumber = $serialnumber.replace("-","")

Related

Replace multiple String characters and quotes in a file

I am trying to replace an entry in the Google chrome local state file.
Replace
"browser":{"enabled_labs_experiments":[],"last_redirect_origin":""
with
"browser":{"enabled_labs_experiments":["same-site-by-default-cookies#2"],"last_redirect_origin":""
I am using
(Get-content "$env:USERPROFILE\AppData\Local\Google\Chrome\User Data\local state") -replace '"browser":{"enabled_labs_experiments":[],"last_redirect_origin":"', '"browser":{"enabled_labs_experiments":["same-site-by-default-cookies#2"],"last_redirect_origin":""'
I am getting
The regular expression pattern "browser":{"enabled_labs_experiments":[],"last_redirect_origin":" is not valid. At line:1 char:1
You're trying to do ordinary replace like C#'s string.Replace(), but in posh -replace operates on regexes and seems like your literal unfortunately happens to be invalid regex expression. Try with .Replace(), this way:
(Get-content "$env:USERPROFILE\AppData\Local\Google\Chrome\User Data\local state").Replace( `
'"browser":{"enabled_labs_experiments":[],"last_redirect_origin":"', `
'"browser":{"enabled_labs_experiments":["same-site-by-default-cookies#2"],"last_redirect_origin":""')
Note that I added ` at the end of each line, that's just for better formatting.

How to replace " on a CSV in PowerShell

If I got a CSV file and there are a lot of strings that contain exactly "Name".
How do I get to have only Name and not "Name"? -replace won't work as you can't quote the quotes:
$computername.Name = $computername.Name -replace (""", "") # won't work
edit: example csv export Name,"IPAddress"
SVDCO03,"10.10.15.46"
SVLIC01,"10.10.20.221"
where i need to get those quotas away
not sure why u are trying to parse the csv you can actually quote the quotes :)
enclose the double quotes inside single and use the regex replace
"name" -replace '"'
or use the string replace method.
"name".replace('"','')

How can I remove CRLF if anywhere between double quotes, using PowerShell?

My text file looks like this.
"MikeCRLF","","","Dell","DevelCRLFCRLFoper"CRLF
"SuCRLFsan","","","Apple","ManagCRLFer"CRLF
Desired result:
"Mike","","","Dell","Developer"LF
"Susan","","","Apple","Manager"LF
I tried this on PowerShell:
"C:\Users\abc\Desktop\1.txt"
(Get-Content $path -Raw).Replace("`r`n","`n") | Set-Content $path -Force
When I do this, I don't get the desired result. Also, I am left with one CRLF at the end. I don't want that either.
Please tell me how to do this using PowerShell v3.
This method avoids checking to see if \r\n is in quotes. Instead, it tries to find the "real" end of line situations and converts those first. Then it just purges the rest.
(Get-Content test.txt -Raw) -replace '([^,]")(\s*\r\n\s*)+("[^,])',"`$1`n`$3" -replace '\r\n',''
I think this should handle most of the stuff you throw at it, but let me know if you find a special case.
edited to fix the replacement string
If you are using the PowerShell Community Extensions, you can use the ConvertTo-UnixLineEnding command e.g.:
ConvertTo-UnixLineEnding C:\users\abc\desktop1.txt -dest desktop1-converted.txt -Enc ascii

Using PowerShell to replace string that contains $ in the string

I am trying to use PowerShell do a simple find and replace. I use template text files and use $ in front of values that need to be changed.
Example:
(Get-Content "D:\test") | Foreach-Object {$_ -replace "`$TBQUAL", "DBO"} | Set-Content "D:\test"
It should find the line OWNER=$TBQUAL and make it look like OWNER=DBO.
I am using the escape in front of $TBQUAL with no luck. To test that it is working if I removed the $ from the front, it would replace TBQUAL and made it look like OWNER=$DBO.
Two things to get this to work:
Use single quotes for your strings so that the $ is not interpreted as the start of a variable to be expanded.
Escape the $ using a backslash "\" so the regular expression parser takes it literally.
For example,
PS C:\> 'Has a $sign in it' -replace 'a \$sign', 'no dollar sign'
Has no dollar sign in it
If you aren't using regular expressions in your replacement, you can do a simple (and fast) replace like this:
Foreach-Object {$_.Replace('$TBQUAL', 'DBO')}

How can I replace newlines using PowerShell?

Given test.txt containing:
test
message
I want to end up with:
testing
a message
I think the following should work, but it doesn't:
Get-Content test.txt |% {$_-replace "t`r`n", "ting`r`na "}
How can I do a find and replace where what I'm finding contains CRLF?
A CRLF is two characters, of course, the CR and the LF. However, `n consists of both. For example:
PS C:\> $x = "Hello
>> World"
PS C:\> $x
Hello
World
PS C:\> $x.contains("`n")
True
PS C:\> $x.contains("`r")
False
PS C:\> $x.replace("o`nW","o There`nThe W")
Hello There
The World
PS C:\>
I think you're running into problems with the `r. I was able to remove the `r from your example, use only `n, and it worked. Of course, I don't know exactly how you generated the original string so I don't know what's in there.
In my understanding, Get-Content eliminates ALL newlines/carriage returns when it rolls your text file through the pipeline. To do multiline regexes, you have to re-combine your string array into one giant string. I do something like:
$text = [string]::Join("`n", (Get-Content test.txt))
[regex]::Replace($text, "t`n", "ting`na ", "Singleline")
Clarification: small files only folks! Please don't try this on your 40 GB log file :)
With -Raw you should get what you expect
If you want to remove all new line characters and replace them with some character (say comma) then you can use the following.
(Get-Content test.txt) -join ","
This works because Get-Content returns array of lines. You can see it as tokenize function available in many languages.
You can use "\\r\\n" also for the new line in powershell. I have used this in servicenow tool.
In my case "\r\n" s not working so i tried "\\r\\n" as "\" this symbol work as escape character in powershell.
You can detect if a file is CRLF with this simple Powershell instruction
(cat -Raw $args) -match "\r\n$"
Replacing \n with \r\n is tricky because you have to detect it first and apply the replacement only if it is needed, otherwise it would be a mess. Too complex.
In any case, you can forget detection, to ensure a file is CRLF whatever the original type you can do this in PowerShell:
cat $file > $file