如何修改PowerShell的GpuPreference函数解决参数类型转换错误
Fix PowerShell
GpuPreference Function for Quoted, Comma-Separated Paths Got it, let's resolve this issue with your function. The error occurs because after processing your input, $app becomes a string array, but the -Name parameter of New-ItemProperty only accepts a single string value—it can't handle arrays directly. We need to loop through each path in the array to create registry properties one by one.
Modified Function Code
function GpuPreference { [CmdletBinding()] Param ( [Parameter(Mandatory = $true)] [string[]]$app ) # Clean input: remove quotes, split by commas, trim whitespace, filter out empty entries $cleanedApps = $app.Replace("`"", "").Split(",").Trim() | Where-Object { $_ -ne "" } # Loop through each cleaned path to create the registry property foreach ($appPath in $cleanedApps) { New-ItemProperty -Path HKCU:\Software\Microsoft\DirectX\UserGpuPreferences ` -Name $appPath ` -PropertyType String ` -Value "GpuPreference=2;" ` -Force } }
Key Changes Explained
- Added a
foreachloop: This iterates over every cleaned application path, ensuring we callNew-ItemPropertyonce per path (fixes the array-to-string conversion error). - Filtered empty entries: The
Where-Objectcheck removes any empty strings that might come from extra commas or whitespace in your input. - Improved readability: Formatted the code with line breaks and indentation to make it easier to debug and modify later.
Usage Example
You can now call the function with your quoted, comma-separated paths as intended:
GpuPreference -app '"D:\", "D:\1", "D:\2"'
This will create separate registry properties for D:\, D:\1, and D:\2, each set to GpuPreference=2;.
内容的提问来源于stack exchange,提问作者Sanctuary
相关产品推荐
相关产品推荐

