You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改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 foreach loop: This iterates over every cleaned application path, ensuring we call New-ItemProperty once per path (fixes the array-to-string conversion error).
  • Filtered empty entries: The Where-Object check 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 06:31:09