I'm having trouble passing file names from batch to a powershell command. I need to change the encoding of all files in a subdirectory of the current directory. Some filenames contain apostrophes, and I would rather leave those intact.
Here is my first go at the code:
for /R "%cd%\Legacy .xml files\" %%f in (*.xml) do (
echo. file: %%~nxf
set filename=%%~nxf
powershell -Command "& {Get-Content '%%f' | Set-Content -Encoding utf8 '%cd%\XML converted to UTF-8\!filename!';}"
)
That gave this error for files with apostrophes in the name, e.g. D'Este.xml
(note - there are several files with apostrophes):
Get-Content : A positional parameter cannot be found that accepts argument 'Este.xml | Set-Content -Encoding utf8
C:\Users\pwessels\Documents\Report'.
At line:1 char:4
+ & {Get-Content 'C:\Users\pwessels\Documents\Report tinkering\Ops-Dail ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-Content], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.GetContentCommand
Then I tried escaped double quotes instead of single quotes in the powershell command, but I receive a different error (on every file this time).
for /R "%cd%\Legacy .xml files\" %%f in (*.xml) do (
echo. file: %%~nxf
set filename=%%~nxf
powershell -Command "& {Get-Content ""%%f"" | Set-Content -Encoding utf8 ""%cd%\XML converted to UTF-8\!filename!"";}"
)
That gave this error:
The string is missing the terminator: ".
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : TerminatorExpectedAtEndOfString
Looking for any insight on how to accomplish this!
EDIT: Powershell attempt doesn't work either - I'm not experienced at all with powershell and I'm getting a Set-ExecutionPolicy error that I couldn't find the solution for.
Get-ChildItem "$PSScriptRoot\Legacy .xml files" -Filter *.xml |
Foreach-Object {
$content = Get-Content $_.FullName
#filter and save content to the original file
$content | Set-Content -Encoding utf8 "$($PSScriptRoot)\XML converted to UTF-8\$($_.ShortName).xml"
}
Read-Host -Prompt "Press Enter to exit"
error:
Set-ExecutionPolicy : Windows PowerShell updated your execution policy successfully, but the setting is overridden by
a policy defined at a more specific scope. Due to the override, your shell will retain its current effective
execution policy of RemoteSigned. Type "Get-ExecutionPolicy -List" to view your execution policy settings. For more
information please see "Get-Help Set-ExecutionPolicy".
At line:1 char:46
+ ... -ne 'AllSigned') { Set-ExecutionPolicy -Scope Process Bypass }; & 'C ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : PermissionDenied: (:) [Set-ExecutionPolicy], SecurityException
+ FullyQualifiedErrorId : ExecutionPolicyOverride,Microsoft.PowerShell.Commands.SetExecutionPolicyCommand