Removing spaces from a variable input using PowerShell 4.0 - string

I've tried a few things already but they don't seem to work for some reason.
Basically what I'm attempting to do is have a user input a value using the
"Read-host" cmdlet, then strip it of any spaces.
I tried:
$answer = read-host
$answer.replace(' ' , '""')
And:
$answer = read-host
$answer -replace (' ')
I'm probably missing something really obvious, but if anyone could help me out or show me an easier way to achieve this I would appreciate it.
I was going to pipeline the variable to a command and strip it in that fashion, but none of the examples I've seen work, although they look much easier.

The Replace operator means Replace something with something else; do not be confused with removal functionality.
Also you should send the result processed by the operator to a variable or to another operator. Neither .Replace(), nor -replace modifies the original variable.
To remove all spaces, use 'Replace any space symbol with empty string'
$string = $string -replace '\s',''
To remove all spaces at the beginning and end of the line, and replace all double-and-more-spaces or tab symbols to spacebar symbol, use
$string = $string -replace '(^\s+|\s+$)','' -replace '\s+',' '
or the more native System.String method
$string = $string.Trim()
Regexp is preferred, because ' ' means only 'spacebar' symbol, and '\s' means 'spacebar, tab and other space symbols'. Note that $string.Replace() does 'Normal' replace, and $string -replace does RegEx replace, which is more heavy but more functional.
Note that RegEx have some special symbols like dot (.), braces ([]()), slashes (\), hats (^), mathematical signs (+-) or dollar signs ($) that need do be escaped. ( 'my.space.com' -replace '\.','-' => 'my-space-com'. A dollar sign with a number (ex $1) must be used on a right part with care
'2033' -replace '(\d+)',$( 'Data: $1')
Data: 2033
UPDATE: You can also use $str = $str.Trim(), along with TrimEnd() and TrimStart(). Read more at System.String MSDN page.

You're close. You can strip the whitespace by using the replace method like this:
$answer.replace(' ','')
There needs to be no space or characters between the second set of quotes in the replace method (replacing the whitespace with nothing).

You also have the Trim, TrimEnd and TrimStart methods of the System.String class. The trim method will strip whitespace (with a couple of Unicode quirks) from the leading and trailing portion of the string while allowing you to optionally specify the characters to remove.
#Note there are spaces at the beginning and end
Write-Host " ! This is a test string !%^ "
! This is a test string !%^
#Strips standard whitespace
Write-Host " ! This is a test string !%^ ".Trim()
! This is a test string !%^
#Strips the characters I specified
Write-Host " ! This is a test string !%^ ".Trim('!',' ')
This is a test string !%^
#Now removing ^ as well
Write-Host " ! This is a test string !%^ ".Trim('!',' ','^')
This is a test string !%
Write-Host " ! This is a test string !%^ ".Trim('!',' ','^','%')
This is a test string
#Powershell even casts strings to character arrays for you
Write-Host " ! This is a test string !%^ ".Trim('! ^%')
This is a test string
TrimStart and TrimEnd work the same way just only trimming the start or end of the string.

You can use:
$answer.replace(' ' , '')
or
$answer -replace " ", ""
if you want to remove all whitespace you can use:
$answer -replace "\s", ""

If the string is
$STR = 'HELLO WORLD'
and you want to remove the empty space between 'HELLO' and 'WORLD'
$STR.replace(' ','')
replace takes the string and replaces white space with empty string (of length 0), in other words the white space is just deleted.

Related

-replace (value) with an escape char?

I need to pull first and last names from accounts that were very poorly named from the previous IT administrator and recreate them in the same source OU.
There are characters in the account name I that I cant seem to get past. I need to pull First,Last and the remaining DN so I can recreate the account in the same OU structure without. For testing I'm only using one user in one OU, but there will be many different OU structures. "\" and "(Vendor)" are causing
My end goal is to feed the script a list of Accounts DN and recreate the account without the undesired "\" and "(vendor)" and do first.last or some variation of that.
$source = "CN=last\, first (Vendor),OU=vendors,DC=somecompany,DC=com"
$arg = "(vendor)"
($source -split ',*..=')[1].Remove($arg)
I've also tried
($source -split ',*..=')[1] -replace "`(Vendor)'", ""
The brackets and \ seem to cause everything I've tried to fail. I've searched and there doesnt seem to be a simple escape char like ^ for Batch files.
The backtick is the escape character usually for just powershell code. In the regex though, you will want to double your backslashes.
$source = "CN=last\, first (Vendor),OU=vendors,DC=somecompany,DC=com","CN=last\, first (Vendor),OU=vendors,DC=somecompany,DC=com"
$r = ($source[0] -split ',*..=|\\,').Replace("(Vendor)","").Where({ $_ -ne ''})
$r
For .remove() the argument is supposed to be a number, the number or characters to display of a string (and removing every character after the number of characters you give specify). Feeding it a string when it's expecting an int will just error so I used .replace() instead.
.remove() takes a number as an argument:
($source -split ',*..=')[1].Remove
OverloadDefinitions
-------------------
string Remove(int startIndex, int count)
string Remove(int startIndex)
Using backslashes to escape regex characters:
($source -split ',*..=')[1] -replace "\(Vendor\)", ""
last\, first
Confirmed by
[regex]::escape("(Vendor)")
\(Vendor\)
Thanks for all of the help.
$source = "CN=Doe\, John (Vendor),OU=vendors,DC=somecompany,DC=com"
$r = ($source -split ',*..=|\\,').Replace("(Vendor)","").Where({ $_ -ne ''})
$first = $r[1].replace(" ","")
$last = $r[0].replace(" ","")
$DN = ($source -split "OU=",2)[1]
$DN = "OU=" + $DN
$first
$last
$DN

Can I remove a substring from a string starting at a known position and ending at a given character?

I need to extract sections of a string but I won't always know the length/content.
I've tried converting the string to XML or JSON for instance, and can't come up with any other way to achieve what I'm looking for.
Example string:
'Other parts of the string Name="SomeRandomAmountOfCharacters" blah blah'
What I need to remove always starts with an attribute name and ends with a closing double quote. So can I say I'd like to remove substring starting at Name=" and go until we reach the closing "?
Expected result:
'Other parts of the string blah blah'
You'll want to do something like this
$s = 'Other parts of the string Name="SomeRandomAmountOfCharacters" blah blah'
$s -replace ' Name=".*?"'
or like this:
$s = 'Other parts of the string Name="SomeRandomAmountOfCharacters" blah blah'
$s -replace ' Name="[^"]*"'
to avoid unintentionally removing other parts of your string in case it contains multiple attributes or additional double quotes. .*? is a non-greedy match for a sequence of any character except newlines, so it'll match up to the next double quote. [^"]* is a character class matching the longest consecutive sequence of characters that aren't double-quotes, so it'll also match up to the next double quote.
You'll also want to add the miscellaneous construct (?ms) to your expression if you have a multiline string.
Here is a good reference: https://www.regular-expressions.info/powershell.html
In your case
$s = 'Other parts of the string Name="SomeRandomAmountOfCharacters" blah blah'
$s -replace '\W*Name=".*"\W*', " "
or
$newString = $s -replace 'W*Name=".*"\W*', " "
This will replace your matching string, including the surrounding whitespace, with a single space.
Look at something like this and understand how it works.
$pattern = '(.*)Name=".*" (.*)'
$str = 'Other parts of the string Name="SomeRandomAmountOfCharacters" blah blah'
$ret = $str -match $pattern
$out = $Matches[1]+$Matches[2]
$str
"===>"
$out
See also: https://regex101.com/r/wM2xlc/1

Drop (substract) last n characters from a variable string length

I need to drop (or replace to nothing) last n characters of a string in powershell code. The variant could be with substraction string form a string (didn't find my answer).
I have something like this (string):
something/something/../lastsomething/NAME
where NAME is a variable text I can extract beforehand and manipulate ($name or $name.length). And the whole string can be counted - $string.length.
How can I substract this NAME from a string ($string)? I've searched many ways, including trim,replace,substring - but all of these mostly work with static words or regex, or with the begining of a string.
I need to get this:
something/something/../lastsomething
I've tried even such constructions:
$string.split('($NAME)')[0]
and
$string.split('[string]($NAME)')[0]
and other with get-AD* functions with join to bypass the strings, but nothing did the trick.
A simple solution is take the substring from beginning (0) to the last occurence of /.
$t = 'something/something/../lastsomething/NAME'
$t.Substring(0, $t.LastIndexOf('/'))
EDIT from your comment the real question is how to get
-replace '($_.Name)',' '
working. The single quotes don't expand variables - so use double quotes.
To force evaluation of $_.Name you have to enclose it with $()
-replace "/$($_.Name)"
With an unknown last element /Name
> $String = 'something/something/../lastsomething/NAME'
> $String.Split('/')[-1]
NAME
> $string = $string -replace "/$($String.Split('/')[-1])"
> $string
something/something/../lastsomething
A much simpler solution is :
> Split-Path $string
something\something\..\lastsomething
> Split-Path $string -Leaf
NAME
but it changes slashes to backslashes
You can replace it with '' (nothing ... empty string) and because -replace works with regular expressions you can make sure that you only get a "match" at the end of the string like this:
$var = '/NAME'
'something/Name/something/../lastsomething/NAME' -replace "$var$",''

Powershell removing characters from string up to last separator

I have a string
Projects\TestEnvironment\11111xx\1111111
and need to get 1111111 from it. What I'm doing now is:
$name = $dir.Substring($dir.IndexOf('\')+1)
where $dir is my string, however it only removes up to first string, is it possible to change direction?
What about using split-path?
$string = 'Projects\TestEnvironment\11111xx\1111111'
Split-Path $string -Leaf
returns 1111111.
Note the -Leaf parameter indicates that this cmdlet returns only the last item or container in the path.
#Robin's answer is good if the string is always a path (separated with "\"); in the general case, where the delimiter may be a different character, you can use
$string = "This-is-a-string-with-delimiters"
$lastword = ($string -split "-")[-1]
The -split operator defaults to splitting on a space, but will split on any character you choose to pass it, returning an array of strings, each string being the material before/between/after delimiters - in the example above, each word would be in a separate string in the array. Negative subscripts to an array count from the end of the array rather than the start, and are 1-origin rather than 0-origin - so $x[-1] is the last element of the array $x.
This technique also works on paths;
$path = "C:\Users\JSmith\Documents\Resume.doc"
$filename = ($path -split "\\")[-1]
will give you $filename -eq Resume.doc. Note that the delimiter passed to -split in this case is escaped, because the delimiter can be a regular expression, and the backslash ("\") is meaningful in regular expressions (it's the character that indicates that another meaningful character is to be "escaped", or its meaning ignored).
other solution
('Projects\TestEnvironment\11111xx\1111111' -split '\\')[-1]
or
'Projects\TestEnvironment\11111xx\1111111'.Split('\')[-1]

PowerShell to remove text from a string

What is the best way to remove all text in a string after a specific character? In my case "=" and after another character in my case a ,, but keep the text between?
Sample input
=keep this,
Another way to do this is with operator -replace.
$TestString = "test=keep this, but not this."
$NewString = $TestString -replace ".*=" -replace ",.*"
.*= means any number of characters up to and including an equals sign.
,.* means a comma followed by any number of characters.
Since you are basically deleting those two parts of the string, you don't have to specify an empty string with which to replace them. You can use multiple -replaces, but just remember that the order is left-to-right.
$a="some text =keep this,but not this"
$a.split('=')[1].split(',')[0]
returns
keep this
This should do what you want:
C:\PS> if ('=keep this,' -match '=([^,]*)') { $matches[1] }
keep this
This is really old, but I wanted to add my slight variation for anyone else who may stumble across this. Regular expressions are powerful things.
To keep the text which falls between the equal sign and the comma:
-replace "^.*?=(.*?),.*?$",'$1'
This regular expression starts at the beginning of the line, wipes all characters until the first equal sign, captures every character until the next comma, then wipes every character until the end of the line. It then replaces the entire line with the capture group (anything within the parentheses). It will match any line that contains at least one equal sign followed by at least one comma. It is similar to the suggestion by Trix, but unlike that suggestion, this will not match lines which only contain either an equal sign or a comma, it must have both in order.
I referenced #benjamin-hubbard 's answer above to parse the output of dnscmd for A records, and generate a PHP "dictionary"/key-value pairs of IPs and Hostnames. I strung multiple -replace args together to replace text with nothing or tab to format the data for the PHP file.
$DnsDataClean = $DnsData `
-match "^[a-zA-Z0-9].+\sA\s.+" `
-replace "172\.30\.","`$P." `
-replace "\[.*\] " `
-replace "\s[0-9]+\sA\s","`t"
$DnsDataTable = ( $DnsDataClean | `
ForEach-Object {
$HostName = ($_ -split "\t")[0] ;
$IpAddress = ($_ -split "\t")[1] ;
"`t`"$IpAddress`"`t=>`t'$HostName', `n" ;
} | sort ) + "`t`"`$P.255.255`"`t=>`t'None'"
"<?php
`$P = '10.213';
`$IpHostArr = [`n`n$DnsDataTable`n];
?>" | Out-File -Encoding ASCII -FilePath IpHostLookups.php
Get-Content IpHostLookups.php

Resources