Splitting a string powershell version 4? - powershell

this is part of my bigger code.
I have not added any assemblies for this. I want to get '20161207' separately in a different variable. This approach however is failing with: "parsing "*" - Quantifier {x,y} following nothing."
[string]$filter = '20161207*'
$pathPart = $filter -split '*'
echo $pathPart[0]
please help. I am using powershell version 4.0.
I am not sure what is the escape character in my version of powershell. i Have tried '/'
I want to echo out: '20161207'

The -split operator uses regular expressions, not literal strings. Since * is a quantifier in regexes what you got there is invalid. You need to escape it:
$filter -split '\*'
or use the string.Split method instead:
$filter.Split('*')
which splits on single characters.

Related

How do I strip part of a file name?

Suppose I have a file database_partial.xml.
I am trying to strip the file from "_partial" as well as extension (xml) and then capitalize the name so that it becomes DATABASE.
Param($xmlfile)
$xml = Get-ChildItem "C:\Files" -Filter "$xmlfile"
$db = [IO.Path]::GetFileNameWithoutExtension($xml).ToUpper()
That returns DATABASE_PARTIAL, but I don't know how to strip the _PARTIAL part.
You don't need GetFileNameWithoutExtension() for removing the extension. The FileInfo objects returned by Get-ChildItem have a property BaseName that gives you the filename without extension. Uppercase that, then remove the "_PARTIAL" suffix. I would also recommend processing the output of Get-ChildItem in a loop, just in case it doesn't return exactly one result.
Get-ChildItem "C:\Files" -Filter "$xmlfile" | ForEach-Object {
$_.BaseName.ToUpper().Replace('_PARTIAL', '')
}
If the substring after the underscore can vary, use a regular expression replacement instead of a string replacement, e.g. like this:
Get-ChildItem "C:\Files" -Filter "$xmlfile" | ForEach-Object {
$_.BaseName.ToUpper() -replace '_[^_]*$'
}
Ansgar Wiechers's helpful answer provides an effective solution.
To focus on the more general question of how to strip (remove) part of a file name (string):
Use PowerShell's -replace operator, whose syntax is:<stringOrStrings> -replace <regex>, <replacement>:
<regex> is a regex (regular expression) that matches the part to replace,
<replacement> is replacement operand (the string to replace what the regex matched).
In order to effectively remove what the regex matched, specify '' (the empty string) or simply omit the operand altogether - in either case, the matched part is effectively removed from the input string.
For more information about -replace, see this answer.
Applied to your case:
$db = 'DATABASE_PARTIAL' # sample input value
PS> $db -replace '_PARTIAL$', '' # removes suffix '_PARTIAL' from the end (^)
DATABASE
PS> $db -replace '_PARTIAL$' # ditto, with '' implied as the replacement string.
DATABASE
Note:
-replace is case-insensitive by default, as are all PowerShell operators. To explicitly perform case-sensitive matching, use the -creplace variant.
By contrast, the [string] type's .Replace() method (e.g., $db.Replace('_PARTIAL', ''):
matches by string literals only, and therefore offers less flexibility; in this case, you couldn't stipulate that _PARTIAL should only be matched at the end of the string, for instance.
is invariably case-sensitive in the .NET Framework (though .NET Core offers a case-insensitive overload).
Building on Ansgar's answer, your script can therefore be streamlined as follows:
Param($xmlfile)
$db = ((Get-ChildItem C:\Files -Filter $xmlfile).BaseName -replace '_PARTIAL$').ToUpper()
Note that in PSv3+ this works even if $xmlfile should match multiple files, due to member-access enumeration and the ability of -replace to accept an array of strings as input, the desired substring removal would be performed on the base names of all files, as would the subsequent uppercasing - $db would then receive an array of stripped base names.

Powershell reports MissingEndParenthesisInExpression even though the sub-expression is balanced

Here is my sub-expression:
"""$((($l -split " """)[1] -split """ ")[0])"""
I have checked and found no unpaired parentheses. However powershell insists in saying "Missing closing ')' in expression."
Interestingly, the expression
$((($l -split " """)[1] -split """ ")[0])
works fine.
Has anyone had similiar experience before? Is it a bug of Powershell?
This.. is really interesting, and yes I would consider it a bug at least so far.
Here's a much simpler repro:
"$("`"")"
"$("""")"
It seems to be caused by using either form of double quote escaping (backtick or double double quote), inside a sub-expression, inside an expandable string.
It also appears that this is error comes right down to the parser itself:
$sb = #'
"$("`"")"
'#
$tokens = $null
$er = $null
$ast = [System.Management.Automation.Language.Parser]::ParseInput($sb, [ref]$tokens, [ref]$er)
$ast.EndBlock.Statements[0].PipelineElements[0].Expression.NestedExpressions
$tokens[0].NestedTokens
The nested tokens/expressions it finds just aren't correct.
I tested with Windows PowerShell 5.1 and PowerShell Core 6.0.0-rc.2 on WLS.
Relevant Issues
Two double-quotes in inline expressions
String in Sub-Expression incorrectly parsed
Powershell: Doubled double quotes in inline expressions

troubles with powershell where clause

i am trying to parse a website for specific data.
$strings = $body.split(";")
$strings2 = $strings.Where({$_ -like ("*recordData[`"key`"]*")})
i figured out that the square brackets are to blame, i use
$strings2 = $strings.Where({$_ -like ("*recordData*")})
and it works fine, albeit returning way more results then i need.
is there a way i can just search for "recordData[key]"
$body is just the entirety of a returned webpage
thanks.
EDIT:
as requested the input data is like this
rs.currentColumn = 0;
recordData["dataGridExtraRow"] = 0;
recordData["rownum"] = "0";
recordData["key"] = '3354087';
recordData["factory"] = "cr";
in the end i need the 3354087 number, but just picking out the lines i needed was the issue, after that i can pick apart the string fine.
however, i ended up using the .contains, thanks for the suggestion.
sort of facepalmed after i saw it though.
If you are using the like operator then you are going to be having an issue with the open square bracket which is a wildcard character in PowerShell. See About_Wildcards
...
[] - Matches range of characters
...
A use case would be something like this which would return true.
"recordFata" -like "record[DF]ata"
So if you are going to be using -like you need to escape the brackets using backticks in a single quoted sting. You can avoid that by using other methods that function in the same way you intended.
Other options
String .Contains() Method
"sdfafdrecordData[key]asdfasdfas".Contains("recordData[key]")
Fairly basic and no need to worry about special characters for the most part.
Regex
"sdfafdrecordData[key]asdfasdfas" -match "recordData\[key]"
Note that the square braces are also regex metacharacters that need to be escaped as well.
Try using single quotes and escaping with backticks.
You can also simplify using PowerShell syntax:
$strings = $body -split ';' -like '*recordData`[key`]*'

Use powershell to remove a random string of characters from file names

I have a series of files that contain a string of characters such as this
(AEDOGRES)
An example file name would be
"Test 1(DOWKFUET).png"
I want to use a powershell command to get rid of the entire string in the parentheses to get something like this.
"Test 1.png"
I would expect to be able to use a command like this
dir | rename-item –NewName { $_.name –replace “(*)“,”” }
However, this is not working for me. Any help is greatly appreciated!
I am running powershell 3.0
Regex and wildcard matching have different rules. In regex, the * means "match zero or more of the previous character", and the parens are reserved characters used for grouping constructs and have to be escaped (using a backslash) if you want them to be used as a literal match.
See Get-Help about_regular_expressions, and try this:
$name = "Test 1(DOWKFUET).png"
$name -replace '\(.+\)',''

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')}