【问题标题】:Cannot process argument transformation on parameter 'machine'. Cannot convert value to type System.String无法处理参数“机器”上的参数转换。无法将值转换为 System.String 类型
【发布时间】:2017-08-22 08:06:52
【问题描述】:

我对 Powershell 很陌生。我基本上只是使用我的 C# 逻辑和 .net 经验以及谷歌来创建这个脚本。我不明白为什么我会收到错误:

无法处理参数“机器”上的参数转换。无法将值转换为 System.String 类型

function IterateThroughMachineSubkeys{
(
    [Parameter()]
    [string]$machine,
    [Microsoft.Win32.RegistryKey]$subKey
)

    foreach($subKeyName in $subKey.GetSubKeyNames())
    {
        Write-Host -Object ([System.String]::Format("Machine: {0} Module: {1} Version: {2}",
                            $machine.ToString(), $subKeyName.ToString(), 
                            $subKey.OpenSubKey([string]$subKeyName).GetValue("Version", "Not found", [Microsoft.Win32.RegistryValueOptions]::None)))
    }
}

这是我调用函数的地方:

switch -CaseSensitive (ValidateConsoleInput((Read-Host).ToString()))
{
   "E" 
   {
    IterateThroughMachineSubkeys($machine.ToString(), $subKey)
   }
   "C"
   {
    Write-Host -Object "Enter the module name to be queried in the registry:"
    GetSpecificSubkey($machine, $subkey, [string](Read-Host))
   }

}

【问题讨论】:

标签: .net powershell scripting


【解决方案1】:

您的代码存在几个问题。

1) 函数参数指定不正确;应该是:

function IterateThroughMachineSubkeys([string]$machine, [Microsoft.Win32.RegistryKey]$subKey)
{
  ...
}

2) 函数调用不正确;应该是:

IterateThroughMachineSubkeys -machine $machine.ToString() -subKey $subKey

这是完整的功能:

function IterateThroughMachineSubkeys([string]$machine, [Microsoft.Win32.RegistryKey]$subKey)
{
    foreach($subKeyName in $subKey.GetSubKeyNames())
    {
        Write-Host -Object ([System.String]::Format("Machine: {0} Module: {1} Version: {2}",
                            $machine.ToString(), $subKeyName.ToString(), 
                            $subKey.OpenSubKey([string]$subKeyName).GetValue("Version", "Not found", [Microsoft.Win32.RegistryValueOptions]::None)))
    }
}

$testKey = get-item "HKCU:\Software"
IterateThroughMachineSubkeys -machine . -subKey $testKey

或使用 PowerShell cmdlet:

$key = get-item "hkcu:\Software\Google\Chrome"
$key | get-childitem | foreach-object { 
    write-host "Machine: $machine Module: $($_.PSChildName) Version: " `
    $key.OpenSubKey($_.PSChildName).GetValue("Version", "Not found", [Microsoft.Win32.RegistryValueOptions]::None) 
}

【讨论】:

  • 感谢您花时间解释。就像我说的那样,我是 powershell 的新手,我只是想尝试一些东西。我很感激。
【解决方案2】:

有这个问题,只是想指出为我解决了什么问题:

打印出变量(echo、Write-Host 等等)并非常注意它打印出的内容。

在我的例子中,我没有为函数内的正则表达式搜索分配返回值,所以它会在我的函数内自动打印出“True”,并尽可能地与您的实际返回值一起返回打印输出在 Powershell 中告诉,所以我的返回值是“True [实际返回值]”,它抛出了这个错误。

【讨论】:

    猜你喜欢
    • 2023-03-29
    • 1970-01-01
    • 2014-02-26
    • 2015-01-21
    • 2012-09-07
    • 1970-01-01
    • 1970-01-01
    • 2016-03-21
    • 1970-01-01
    相关资源
    最近更新 更多