how to remove multiple spaces in multiple file names in a folder in windows 10 using powershell - 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}

Related

How to add a line to .txt file with special characters and variables in PowerShell

I have a PowerShell file e.g. C:\MyPowerShell.ps1 and I would like to have the following line there:
$myNewVariable = "Lukas"
Where string Lukas will be taken from variable $name. The variable $name will be declared before I run a command to do this action. I would like to use another PowerShell command to do that.
$name = "Lukas" <br>
Add-Content C:\MyPowerShell.txt ???
Please help me ;-)
Or use the -f Format operator:
$name = 'Lukas'
Add-Content -Path 'C:\MyPowerShell.txt' -Value ('$myNewVariable = "{0}"' -f $name)
Use an expandable (interpolating) string ("...") in which you individually `-escape $ characters in tokens you do not want to be expanded as variable references / subexpressions; similarly, escape embedded " characters as `" ("" would work too):
$name = 'Lucas'
Add-Content C:\MyPowerShell.txt -Value "`$myNewVariable = `"$name`""
Alternatively, use the -f operator, as shown in Theo's helpful answer.
This answer compares and contrasts these two approaches.

HOWTO remove whitespace from an automation string to export to a SQLPlus SELECT command LockedOut.sql file

This is an automation of a command to SQLPlus 12c on Linux from Windows 18_3 version on PowerShell 5.1 with Microsoft modules loaded.
I need to clean out the whitespace of the string to input wildcard data on an automation Select script (the final script will find a missing TIFF image and reinsert it).
I am UNABLE to remove the white space before the tee.
The latest attempts are in the post but I have tried Trim, Split, Replace, Remove, Substring, >>, Write-Host -NoNewline,... I am SO close.
When I Write-Host -NoNewline I succeeded in removing the CRLF but not so as I can Tee, Write-Out, or Out-File the content that way.
#Add-Type -AssemblyName System.Data.OracleClient
$filefolder = "C:\EMSCadre\iGateway\clint\Input_Images\"
$Files = Get-ChildItem $FileFolder -Name -File
$longname = $Files.Get(2)
$shortname = $longname.Replace("_tiff","").Replace("cns","").Substring(9).Split('".tif"')
echo "select LD_CASE_NUMBER FROM LOG_data where ld_message_3 like %$shortname%" |
tee -Verbose c:\scripts\input\lockedout_test.sql
type c:\scripts\input\lockedout_test.sql
#Failed attempts
#echo "select LD_CASE_NUMBER FROM LOG_data where ld_message_3 like %($shortname1.TrimEnd('_',"")%" |
# tee -Verbose c:\scripts\input\lockedout_test.sql
Latest Results showing Whitespaces before last %:
select LD_CASE_NUMBER FROM LOG_data where ld_message_3 like %100838953_180130001 %
select LD_CASE_NUMBER FROM LOG_data where ld_message_3 like %100838953_180130001 %
Details to help troubleshoot:
PS C:\scripts> $Files
2823910000.tif
2823910002.tif
cns20180827_100838953_180130001_tiff.tif
exposureworks-dynamic-range-test-f16-graded-TIFF-RGB-parade.jpg
PS C:\scripts> $shortname
100838953_180130001
Looks to me like the last step (Split()) of the statement
$longname.Replace("_tiff","").Replace("cns","").Substring(9).Split('".tif"')
is supposed to remove the extension from the file name. That is not how Split() works. The method interprets the string ".tif" as a character array and splits the given string at any of those characters (", ., f, i, t). Splitting the string 100838953_180130001.tif that way gives you an array with 5 elements, the last 4 of which are empty strings:
[ '100838953_180130001', '', '', '', '' ]
Putting the variable with that array into a string mangles the array into a string by concatenating its elements using the output field separator ($OFS), which by default is a single space, thus producing the trailing spaces you observed.
To remove the prefix cns..._ and the substring _tiff as well as the extension .tif from the file name use the following:
$shortname = $longname -replace '^cns\d*_|_tiff|\.tif$'
That regular expression replacement will remove the substring "cns" followed by any number of digits and an underscore from the beginning of a string (^), the substring "_tiff" from anywhere in a string, and the substring ".tif" from the end of a string ($).

Adding variable to text string and adding new line in powershell

I have the following code
$scriptpath = "C:\Test"
$scriptname = "mount.bat"
$myimage = Read-Host 'Enter the file name of your image'
if (Test-Path $scriptpath\$scriptname) {
Remove-Item $scriptpath\$scriptname
}
Add-Content $scriptpath\$scriptname ':Loop 'n "C:\Program
Files\file.exe" -f \\host\"Shared Folders"\$myimage -m V: `n if not
%errorlevel% equal 0 goto :Loop'
I can't get powershell to output the variable correctly in the output batch file it just says "$myimage" and not the file name. I have tried using the break ` ' symbols but no luck. I also cannot get powershell to export onto a separate line. If anyone could help that would be great.
Since you're using (a) variable references ($myimage) and (b) escape sequences such as `n (to represent a newline) in your string, you must use double quotes to get the expected result.
(Single-quoted strings treat their contents literally - no interpolation takes place.[1])
Furthermore, since your string has embedded double quotes, they must be escaped as `"
Here's a fixed version; note that I've used actual line breaks for readability (rather than `n escape sequences in a single-line string):
$myImage = 'test.png'
":Loop
`"C:\ProgramFiles\file.exe`" -f \\host\`"Shared Folders`"\$myimage -m V:
if not %errorlevel% equal 0 goto :Loop"
[1] The only interpretation that takes place is to recognize escape sequence '' as an embedded '.

Find and replace at powershell

My textfile looks like this:
-------------------
Set PRGVER="V1.0.12"
Set PRGDIR=C:\PRGSTD\oif_mes\OIFplus
Set PRGEXE=OIFplus.bat
Set PRGTXT=OIFplus
echo %PRGTXT%, %PRGVER%
start "%PRGTXT%" /D%PRGDIR%\%PRGVER%\ %PRGDIR%\%PRGVER%\%PRGEXE%
----------------------
What I wan't to do, edit this file, only change Set PRGVER="V1.0.12" to a new number, like this Set PRGVER=V1.0.13".
When is start the PS Script, I don't know the whole string, the number between "".
I only know, find string variable: Set PRGVER="".
How can I replace only the first value between ""?
Something like this;
$srt = <your text>
$r = $str -replace "PRGVER=`".*`"", "PRGVER=`"your_replace`""
The following should do it. It finds the a line that starts with 'Set PRGVER="V', followed by any number of digits, then a dot, any number of digits, a dot, any number of digits, and ends with '"'. When found, the line is replaced with 'Set PRGVER="V1.0.13"' and the result is saved back to the file.
(Get-Content file.txt) -replace '^Set PRGVER="V\d+\.\d+.\d+"$','Set PRGVER="V1.0.13"' | Out-File file.txt
Following PoSH will replace PRGVER value:
$newValue = "v123.456.789"
gc D:\temp\text | % { $_ -ireplace '(Set PRGVER=)\"([^"]*)\"', ('$1"' + $newValue + '"') };
You using key: Ctrl + H
More information: https://learn.microsoft.com/en-us/powershell/scripting/windows-powershell/ise/keyboard-shortcuts-for-the-windows-powershell-ise?view=powershell-7

replace exception in 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.