i have this script, but it thorws errors: Exception setting "OutputEncoding":…
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
i have this script, but it thorws errors: Exception setting "OutputEncoding": "Nieprawidłowe dojście. " At line:4 char:1
+ CategoryInfo : NotSpecified: (:) [], SetValueInvocationException
+ FullyQualifiedErrorId : ExceptionWhenSetting
Exception setting "InputEncoding": "Nieprawidłowe dojście. " At line:5 char:1
+ CategoryInfo : NotSpecified: (:) [], SetValueInvocationException
+ FullyQualifiedErrorId : ExceptionWhenSetting
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8 [Console]::InputEncoding = [System.Text.Encoding]::UTF8 $OutputEncoding = [System.Text.Encoding]::UTF8
function Test-StringForEmoji { param ( [string]String ) # This regex targets common Unicode emoji ranges, including those represented by surrogate pairs. # It avoids \U escapes and Unicode properties (\p{}) for broader compatibility with older PowerShell versions. # This should catch most modern emojis without affecting standard punctuation. emojiPattern = '[\u2600-\u27BF\u2B00-\u2BFF\u2300-\u23FF\uFE00-\uFE0F]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|\uD83E[\uDC00-\uDFFF]' return emojiPattern }
$files = Get-ChildItem -Path (Get-Location) -File
$emojiRemovalPattern = '[\u2600-\u27BF\u2B00-\u2BFF\u2300-\u23FF\uFE00-\uFE0F]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|\uD83E[\uDC00-\uDFFF]'
$filesToModify = @()
Write-Host "Scanning for files with emojis in their names..."
foreach (files) { if (Test-StringForEmoji -String file.Name) { # Calculate the new name immediately for display newName = emojiRemovalPattern, ''
# Ensure the new name is not empty or just whitespace after emoji removal
if ([string]::IsNullOrWhiteSpace($newName)) {
Write-Warning "Skipping '$($file.Name)' as removing emojis would result in an empty filename."
continue
}
$filesToModify += [PSCustomObject]@{
OriginalFile = $file
OriginalName = $file.Name
NewName = $newName
}
}
}
if ($filesToModify.Count -eq 0) {
Write-Host "No files with emojis found in their names in the current directory."
} else {
Write-Host "nThe following files contain emojis and will be modified:n"
# Calculate max length for original names for alignment
$maxLength = 0
foreach ($item in $filesToModify) {
if ($item.OriginalName.Length -gt $maxLength) {
$maxLength = $item.OriginalName.Length
}
}
# Add some padding for visual separation
$maxLength += 5 # Increased padding for better separation
Write-Host ("Original Name".PadRight($maxLength) + "--> New Name")
Write-Host ("-".PadRight($maxLength, '-') + "---" + "-".PadRight("--> New Name".Length, '-'))
foreach ($item in $filesToModify) {
# Use direct PadRight and concatenation for robust alignment
Write-Host ($item.OriginalName.PadRight($maxLength) + " --> " + $item.NewName)
}
Write-Host "`nDo you want to proceed with renaming these files? (Y/N)"
$confirmation = Read-Host
if ($confirmation -eq 'Y' -or $confirmation -eq 'y') {
Write-Host "`nRenaming files..."
foreach ($item in $filesToModify) {
$originalFile = $item.OriginalFile
$originalName = $item.OriginalName
$newName = $item.NewName
try {
# Get the file item again using LiteralPath to ensure correct path resolution
$fileToRename = Get-Item -LiteralPath $originalFile.FullName -ErrorAction Stop
Rename-Item -LiteralPath $fileToRename.FullName -NewName $newName -Force -ErrorAction Stop
Write-Host " Renamed '$originalName' to '$newName'"
} catch {
Write-Error "Failed to rename '$originalName': $($_.Exception.Message)"
}
}
Write-Host "`nFile renaming complete."
} else {
Write-Host "`nOperation cancelled by the user."
}
}
The error "Nieprawidłowe dojście" (Invalid handle) occurs when trying to set console encoding properties in an environment where there's no console available. This commonly happens when running PowerShell scripts in ISE, scheduled tasks, or other non-console hosts.
Here's a fixed version of your script that handles this issue:
# Requires PowerShell 5.1 or later for some cmdlets like Get-ChildItem -File
# Set console encoding to UTF-8 for proper Unicode character handling
# Only set if running in a console window
if ($Host.Name -eq 'ConsoleHost') {
try {
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
[Console]::InputEncoding = [System.Text.Encoding]::UTF8
} catch {
Write-Warning "Unable to set console encoding: $_"
}
}
# Always set this for proper output encoding
$OutputEncoding = [System.Text.Encoding]::UTF8
# Function to check if a string contains emojis
function Test-StringForEmoji {
param (
[string]$String
)
# This regex targets common Unicode emoji ranges, including those represented by surrogate pairs.
# It avoids \U escapes and Unicode properties (\p{}) for broader compatibility with older PowerShell versions.
# This should catch most modern emojis without affecting standard punctuation.
$emojiPattern = '[\u2600-\u27BF\u2B00-\u2BFF\u2300-\u23FF\uFE00-\uFE0F]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|\uD83E[\uDC00-\uDFFF]'
return $String -match $emojiPattern
}
# Get all files in the current directory
$files = Get-ChildItem -Path (Get-Location) -File
# Define the emoji removal pattern globally so it's consistent
# Using the same precise emoji-targeting pattern for removal
$emojiRemovalPattern = '[\u2600-\u27BF\u2B00-\u2BFF\u2300-\u23FF\uFE00-\uFE0F]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|\uD83E[\uDC00-\uDFFF]'
$filesToModify = @()
Write-Host "Scanning for files with emojis in their names..."
foreach ($file in $files) {
if (Test-StringForEmoji -String $file.Name) {
# Calculate the new name immediately for display
$newName = $file.Name -replace $emojiRemovalPattern, ''
# Ensure the new name is not empty or just whitespace after emoji removal
if ([string]::IsNullOrWhiteSpace($newName)) {
Write-Warning "Skipping '$($file.Name)' as removing emojis would result in an empty filename."
continue
}
$filesToModify += [PSCustomObject]@{
OriginalFile = $file
OriginalName = $file.Name
NewName = $newName
}
}
}
if ($filesToModify.Count -eq 0) {
Write-Host "No files with emojis found in their names in the current directory."
} else {
Write-Host "`nThe following files contain emojis and will be modified:`n"
# Calculate max length for original names for alignment
$maxLength = 0
foreach ($item in $filesToModify) {
if ($item.OriginalName.Length -gt $maxLength) {
$maxLength = $item.OriginalName.Length
}
}
# Add some padding for visual separation
$maxLength += 5 # Increased padding for better separation
Write-Host ("Original Name".PadRight($maxLength) + "--> New Name")
Write-Host ("-".PadRight($maxLength, '-') + "---" + "-".PadRight("--> New Name".Length, '-'))
foreach ($item in $filesToModify) {
# Use direct PadRight and concatenation for robust alignment
Write-Host ($item.OriginalName.PadRight($maxLength) + " --> " + $item.NewName)
}
Write-Host "`nDo you want to proceed with renaming these files? (Y/N)"
$confirmation = Read-Host
if ($confirmation -eq 'Y' -or $confirmation -eq 'y') {
Write-Host "`nRenaming files..."
foreach ($item in $filesToModify) {
$originalFile = $item.OriginalFile
$originalName = $item.OriginalName
$newName = $item.NewName
try {
# Get the file item again using LiteralPath to ensure correct path resolution
$fileToRename = Get-Item -LiteralPath $originalFile.FullName -ErrorAction Stop
Rename-Item -LiteralPath $fileToRename.FullName -NewName $newName -Force -ErrorAction Stop
Write-Host " Renamed '$originalName' to '$newName'"
} catch {
Write-Error "Failed to rename '$originalName': $($_.Exception.Message)"
}
}
Write-Host "`nFile renaming complete."
} else {
Write-Host "`nOperation cancelled by the user."
}
}
The key changes are:
Added a check for console availability: The script now checks if it's running in a ConsoleHost before trying to set console encoding properties.
Added error handling: If setting the console encoding still fails, it will show a warning but continue with the script.
Kept the $OutputEncoding setting: This variable is always safe to set and helps ensure proper output encoding.
Alternative approaches if you continue having issues:
Option 1: Run the script in a regular PowerShell console window (not ISE):
powershell.exe -File "path\to\your\script.ps1"
Option 2: If you must use ISE or another environment, you can completely remove the console encoding lines:
# Just set the output encoding variable
$OutputEncoding = [System.Text.Encoding]::UTF8
The script should now work properly in various PowerShell environments without throwing the "Invalid handle" errors.