Page 1 of 1

PowerShell Rotate Right with Array issue

Posted: 20 Apr 2023 16:59
by avivariba
The following script to rotate images 90 degrees clockwise works, but it opens a new PowerShell window for every image as it does the looping within XY (which in turn makes it a little less efficient and very hacky looking):

Code: Select all

foreach($item, "<get SelectedItemsPathNames |>") {
 run """C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe""
  -Command ""$path = '$item';
   [Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms');
   $image = new-object System.Drawing.Bitmap $path;
   $image.RotateFlip('Rotate90FlipNone');
   $image.Save($path)""";
}
To do the looping within PowerShell itself, an array needs to be formatted either like
$selected = "C:\File 1.png","C:\File2.png"; or
$selected = @("C:\File 1.png","C:\File2.png");
with quotations (") around each element.

The following does work within PowerShell itself or when triggered by the Command Prompt (either with @($selected) or $selected), but as an XY script it removes any and all quotations from $selected, which makes it so that it doesn't work with multiple images. No matter how many quotations are put around it:

Code: Select all

$selected = quote(<get SelectedItemsPathNames '", "'>);
 run """C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe""
  -Command ""Foreach ($path in @($selected)) {
    [Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms');
    $image = new-object System.Drawing.Bitmap $path;
    $image.RotateFlip('Rotate90FlipNone');
    $image.Save($path);
   }"""
So it turns into $selected = @(C:\File 1.png,C:\File2.png); which makes PowerShell think it are functions (so if it does anything at all, like in case a path doesn't contain any spaces, it will open the image without doing anything else).

For PowerShell troubleshooting, one can put -NoExit in front of -Command.

I have also tried moving the array around, or not defining it at all putting it directly in the Foreach, but with the same result. What would be the proper way to go about it to retain the quotations around the array elements?

Re: PowerShell Rotate Right with Array issue

Posted: 20 Apr 2023 17:35
by highend

Code: Select all

$selected = '"""' . <get SelectedItemsPathNames '""","""'> . '"""';

Re: PowerShell Rotate Right with Array issue

Posted: 20 Apr 2023 18:22
by avivariba
highend wrote: 20 Apr 2023 17:35

Code: Select all

$selected = '"""' . <get SelectedItemsPathNames '""","""'> . '"""';
Perfection! Still wrapping my head around it like you did those quotes, but it definitely works. Thanks!