1
votes
function GpuPreference
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory = $true)]
        [string[]]$app
    )
    $app = $app.Replace("`"", "").Split(",").Trim()
    # $app.GetType()
    New-ItemProperty -Path HKCU:\Software\Microsoft\DirectX\UserGpuPreferences -Name $app -PropertyType String -Value "GpuPreference=2;" -Force
}
$app = Read-Host -Prompt " "
GpuPreference $app

Function works properly but not with New-ItemProperty:

Console output:

Type paths: "D:\", "D:\1", "D:\2"

New-ItemProperty : Cannot convert "System.String[]" to the type "System.String"
required bt parameter "Name". Specified metod is not supported.
line:12 char:83
+ ... KCU:\Software\Microsoft\DirectX\UserGpuPreferences -Name $app -Proper ...
+                                                              ~~~~
    + CategoryInfo          : InvalidArgument: (:) [New-ItemProperty], ParameterBindingException
    + FullyQualifiedErrorId : CannotConvertArgument,Microsoft.PowerShell.Commands.NewItemPropertyCommand

How should the function be modified, if I want to set paths as parameters, separated in commas and taken in quotes?

1
$app is a string array while Name parameter expects a single string to be passed as input. That's why you are getting this error.Chetan
can you show us input and expected output? that would be more clear.Ravi

1 Answers

2
votes

Sanitize/prepare the user input before passing it to your function, and process the function parameter with a loop (since New-ItemProperty expects a single string, not a string array).

function Write-GpuPreference {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$true)]
        [string[]]$Preference
    )

    Begin {
        $path  = 'HKCU:\Software\Microsoft\DirectX\UserGpuPreferences'
        $value = 'GpuPreference=2;'
    }

    Process {
        $Preference | Select-Object -Unique | ForEach-Object {
            New-ItemProperty -Path $path -Name $_ -PropertyType String -Value $value -Force
        }
    }
}

$app = Read-Host -Prompt " "
$app = $app.Replace('"', '').Split(',').Trim()
Write-GpuPreference $app