replace exception in powershell - powershell

I'm a beginner in powershell and know C# pretty well. I have this command http://www.f2ko.de/programs.php?lang=en&pid=cmd that downloads stuff. I'm writing this script to download all the sgf go games from this url http://www.gogameworld.com/gophp/pg_samplegames.php, and was trying to write a powershell script to do it for me. So I wrote a script:
Get-Content test.txt|
ForEach-Object
{
if($_ -eq "=`"javascript:viewdemogame(`'*.sgf`')`" tit")
{
$filename = $_ -replace '=`"javascript:viewdemogame(`''
$filename = $filename -replace '`')`" tit'
&"(Path)/download.exe" ("http://www.gogameworld.com/webclient/qipu/" + $filename)
}
}
However, when I run the script, I keep getting this error:
Unexpected token '`'' in expression or statement.
At (PATH)\test.ps1:7 char:37
+ $filename = $filename -replace '`' <<<< )'
+ CategoryInfo : ParserError: (`':String) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : UnexpectedToken
I've looked at the script lots of times and still can't figure out whats wrong. Thanks.

Try this, read the content of the file as one string and then use the Regex.Matches to get all occurrences of the text contained in the parenthesis:
$content = Get-Content test.txt | Out-String
$baseUrl = 'http://www.gogameworld.com/webclient/qipu/'
[regex]::matches($content,"javascript:viewdemogame\('([^\']+)'\)") | Foreach-Object{
$url = '{0}{1}' -f $baseUrl,$_.Groups[1].Value
& "(Path)/download.exe" $url
}
here's an explanation of the regex pattern (created with RegexBuddy):
javascript:viewdemogame\('([^\']+)'\)
Match the characters “javascript:viewdemogame” literally «javascript:viewdemogame»
Match the character “(” literally «\(»
Match the character “'” literally «'»
Match the regular expression below and capture its match into backreference number 1 «([^\']+)»
Match any character that is NOT a ' character «[^\']+»
Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Match the character “'” literally «'»
Match the character “)” literally «\)»
Match the character “"” literally «"»
'{0}{1}' is used with the -f operator to create a string. {0} maps to the first value on the right hand side of the operator (e.g $baseUrl) and {1} is mapped to the second value. Under the hood, PowerShell is suing the .NET String.Format method. You can read more about it here: http://devcentral.f5.com/weblogs/Joe/archive/2008/12/19/powershell-abcs---f-is-for-format-operator.aspx

'')" tit'
The -replace operator takes 2 arguments, comma separated. The first is a regular expression that matches what you want replaced. The second is the string you want to relace that with. You appear to be missing the second argument.

Related

Powershell Command for retrieving the second pattern values

I am facing problem while using multiple patterns to retrieve the values from the second pattern.
The file contains data like below
Explore/CommonServices/AlertService.Folder
Explore/CommonServices/CIHLogger.Folder
What I am trying to do is find the text between two forward slashes i.e CommonServices and find the text between one forward slash and the dot i.e AlertService
I am able to find them using the patterns '/(.+)/' and '/([^/]+)\.' respectively. Now the challenge is how to get them into a single line
My Command is
((get-content "test2.txt") | Select-String -pattern '/(.+)/','/([^/]+)\.' -context 0,2 | foreach {"iics export --podHostName dm-us.informaticacloud
.com -r us -u xxxxxx -p xxxxxxxxx --artifacts " + $_ + " --zipFilePath `"C:\Users\breddy002\Documents\NJR\SVN\" + $_.Matches[0].Groups[1].Value + "\" + $($_.Matches[1].Groups[1].value)
})
I am not sure how to get the second pattern output in the second output
Powershell version is : echo $PSVersionTable
Name Value
---- -----
PSVersion 5.1.17763.771
You could do something like the following:
switch -regex -file 'text2.txt' {
'/(?<Slash>[^/]+)/(?<Dot>[^/\.]+)\.' {
$Slash = $Matches.Slash
$Dot = $Matches.Dot
"First: {0}, Second: {1}" -f $Slash,$Dot
}
}
Explanation:
The switch statement is a robust if statement. With the -regex and -file parameters, you can efficiently read in each line of a file and apply regex pattern matches. Each successful match is stored in the automatic variable $Matches.
The regex pattern /(?<Slash>[^/]+)/(?<Dot>[^/\.]+)\. matches as follows:
/ is a literal match of /
(?<Slash>[^/]+) matches one or more (+) characters that are not / ([^/]). That match is stored as capture group Slash (using syntax (?<Slash>)). It can later be accessed by using the syntax $Matches.Slash.
(?<Dot>[^/\.]+) matches one or more characters that are not / and . ([^/\.]+). That match is stored as capture group Dot. It can later be accessed by using the syntax $Matches.Dot.
\. is a literal . match, which requires escaping with backslash.

Powershell replace last two occurrences of a '/' in file path with '.'

I have a filepath, and I'm trying to remove the last two occurrences of the / character into . and also completely remove the '{}' via Powershell to then turn that into a variable.
So, turn this:
xxx-xxx-xx\xxxxxxx\x\{xxxx-xxxxx-xxxx}\xxxxx\xxxxx
Into this:
xxx-xxx-xx\xxxxxxx\x\xxxx-xxxxx-xxxx.xxxxx.xxxxx
I've tried to get this working with the replace cmdlet, but this seems to focus more on replacing all occurrences or the first/last occurrence, which isn't my issue. Any guidance would be appreciated!
Edit:
So, I have an excel file and i'm creating a powershell script that uses a for each loop over every row, which amounts to thousands of entries. For each of those entries, I want to create a secondary variable that will take the full path, and save that path minus the last two slashes. Here's the portion of the script that i'm working on:
Foreach($script in $roboSource)
{
$logFileName = "$($script.a).txt".Replace('(?<=^[^\]+-[^\]+)-','.')
}
$script.a will output thousands of entries in this format:
xxx-xxx-xx\xxxxxxx\x{xxxx-xxxxx-xxxx}\xxxxx\xxxxx
Which is expected.
I want $logFileName to output this:
xxx-xxx-xx\xxxxxxx\x\xxxx-xxxxx-xxxx.xxxxx.xxxxx
I'm just starting to understand regex, and I believe the capture group between the parenthesis should be catching at least one of the '\', but testing attempts show no changes after adding the replace+regex.
Please let me know if I can provide more info.
Thanks!
You can do this in two fairly simply -replace operations:
Remove { and }
Replace the last two \:
$str = 'xxx-xxx-xx\xxxxxxx\x\{xxxx-xxxxx-xxxx}\xxxxx\xxxxx'
$str -replace '[{}]' -replace '\\([^\\]*)\\([^\\]*)$','.$1.$2'
The second pattern matches:
\\ # 1 literal '\'
( # open first capture group
[^\\]* # 0 or more non-'\' characters
) # close first capture group
\\ # 1 literal '\'
( # open second capture group
[^\\]* # 0 or more non-'\' characters
) # close second capture group
$ # end of string
Which we replace with the first and second capture group values, but with . before, instead of \: .$1.$2
If you're using PowerShell Core version 6.1 or newer, you can also take advantage of right-to-left -split:
($str -replace '[{}]' -split '\\',-3) -join '.'
-split '\\',-3 has the same effect as -split '\\',3, but splitting from the right rather than the left.
A 2-step approach is simplest in this case:
# Input string.
$str = 'xxx-xxx-xx\xxxxxxx\x\{xxxx-xxxxx-xxxx}\xxxxx\xxxxx'
# Get everything before the "{"
$prefix = $str -replace '\{.+'
# Get everything starting with the "{", remove "{ and "}",
# and replace "\" with "."
$suffix = $str.Substring($prefix.Length) -replace '[{}]' -replace '\\', '.'
# Output the combined result (or assign to $logFileName)
$prefix + $suffix
If you wanted to do it with a single -replace operation (with nesting), things get more complicated:
Note: This solution requires PowerShell Core (v6.1+)
$str -replace '(.+)\{(.+)\}(.+)',
{ $_.Groups[1].Value + $_.Groups[2].Value + ($_.Groups[3].Value -replace '\\', '.') }
Also see the elegant PS-Core-only -split based solution with a negative index (to split only a fixed number of tokens off the end) in Mathias R. Jessen's helpful answer.
try this
$str='xxx-xxx-xx\xxxxxxx\x\{xxxx-xxxxx-xxxx}\xxxxx\xxxxx'
#remove bracket and split for get array
$Array=$str -replace '[{}]' -split '\\'
#take all element except 2 last elements, and concat after last elems
"{0}.{1}.{2}" -f ($Array[0..($Array.Length -3)] -join '\'), $Array[-2], $Array[-1]

how to remove multiple spaces in multiple file names in a folder in windows 10 using powershell

For example, how can I change multiple file names in a folder: which are in the format " New file " to "New file" in windows 10 using powershell
From https://blogs.technet.microsoft.com/heyscriptingguy/2014/07/18/trim-your-strings-with-powershell/
The easiest Trim method to use is the Trim() method. It is very useful, and it is the method I use most. It easily removes all whitespace characters from the beginning and from the end of a string. This is shown here:
PS C:\> $string = " a String "
PS C:\> $string.Trim()
# => a String
The method is that easy to use. I just call Trim() on any string, and it will clean it up. Unfortunately, the previous output is a bit hard to understand, so let me try a different approach. This time, I obtain the length of the string before I trim it, and I save the resulting string following the trim operation back into a variable. I then obtain the length of the string a second time. Here is the command:
$string = " a String "
$string.Length
# => 10
$string = $string.Trim()
$string
# => a String
$string.Length
# => 8
try this :
Get-ChildItem "C:\Temp" -Recurse -file | Rename-Item -NewName {"{0}{1}" -f $_.BaseName.Trim(), $_.Extension}

powershell search function with regular expression

the text file content is:
In this script, we have the following variables:
$input_path to hold the path to the input file we want to parse
$output_file to hold the path to the file we want the results to be stored in
$regex to hold the regular expression pattern to be used when the strings are being matched.
The select-string cmdlet contains various parameters as follows:
-Path which takes as input the full path to the input file
-Pattern which takes as input the regular expression used in the matching process
AllMatches which searches for more than one match (without this parameter it would stop after the first match is found) and is piped to $.Matches and then $_.Value which represent using the current values of all the matches.
Code:
$replace_file=#{}
$replace_text_file_path="EMS_checksystem_script\replace.txt"
$replace_file= gc $replace_text_file_path
$result=0
$valr=read-host "please enter the key word"
for($i=0;$i -lt$file_context.length;$i++)
{
$result=$replace_file[$i] -match $valr
if( $result -eq 1)
{
$replace_file[$i]
}
}
Result:
key word: *pression
Bad argument to operator '-match': parsing "*pression" - Quantifier {x,y} following nothing..
At line:11 char:37
+ $result=$replace_file[$i] -match <<<< '*pression'
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : BadOperatorArgument
key word: pression*
key word: press*on
NO result
How can use the press*on and *pression keywords to search?
Read up on regex. You can test regex here > http://www.regexr.com/
Your keyword is wrong, use "." to match any character and "*" to match any number of the previous character.
PS C:\>'expression' -match ".*pression"
PS C:\>True

Trying to run legacy executables from powershell script

I am looking to run net.exe from a script and I am having some trouble with spaces. Here is the code...
# Variables
$gssservers = Import-Csv "gssservers.csv"
$gssservers | Where-Object {$_.Tier -match "DB"} | Foreach-Object {
net.exe use "\\"$_.Name '/user:'$_.Name'\Administrator' $_.Pass
$sqlcheck = sc.exe \\$gsssql[1] query "WUAUSERV"
}
When I set line 5 to Write-Host I see that there are spaces that are added outside of anywhere I have quotes which is breaking the net.exe command. How can I remove those spaces?
For anyone questioning how I am doing this, the net.exe command is the only way I can get to these machines as WMI is blocked in this enclave.
My first guess is that you've got "invisible" spaces in your CSV file. For example their is likely a trailing whitespace after the names of your servers in the CSV that your eyes of course don't see. You can fix that either by fixing the CSV file, or using .Trim() on your imported strings -- i.e. $_.Name.Trim()
If that's not the case, or not the only issue, then this is something I've had issues with to. When I have complicated strings like your desired net.exe arguments I've liked to take precautions and get extra pedantic with defining the string and not rely on PowerShell's automatic guessing of exactly where a string begins and ends.
So, instead of baking your parameters inline on your net.exe command line hand-craft them into a variable first, like so
$args = '\\' + $_.name + '/user:' + $_.name + '\Administrator' + $_.pass
If you write-Host that out you'll see that it no longer has your rogue spaces. Indeed you may notice that it no longer has enough spaces, so you'll have to get a little explicit about where they belong. For instance the above line doesn't put the proper spaces between \\servername and /user, or between the username and password, so you'd have to add that space back in, like so.
$args = '\\' + $_.name + ' /user:' + $_.name + '\Administrator ' + $_.pass
Notice the explicit spaces.
I finally resolved this myself using #EdgeVB's solution. The code ended up like this...
# Variables
$gssservers = Import-Csv "gssservers.csv"
$gssservers | Where-Object {$_.Tier -match "DB"} | Foreach-Object {
$cmd1 = 'use'
$arg1 = '\\' + $_.Name
$arg2 = ' /user:' + $_.Name + '\Administrator '
& net.exe $cmd1 $arg1 $arg2 $_Pass
$cmd2 = 'query'
$svc1 = 'mssqlserver'
& sc.exe $arg1 $cmd2 $svc1 | Write-Host
}
Not only do you need to bake the variables in beforehand, but they also cannot cross certain thresholds (for instance, if "use" and "\" are in the same variable, it breaks.