简体   繁体   English

Powershell-由函数变量定义的新变量“ -name”

[英]Powershell - New-Variable “-name” defined by function variable

I want to have a function in which the result is stored in a variable where the function defines the variable name - essentially this: 我想拥有一个将结果存储在变量中的函数,该函数定义了变量名称-本质上是这样的:

function testfunction ($varname,$text){
    $readhost = read-host -prompt "$text"
    new-variable -name $varname -value $readhost
}

though when entering: 虽然在输入时:

testfunction outputvar sampletext

get-variable -name outputvar

I just get an error that the variable "outputvar" doesnt exist. 我只是得到一个错误,指出变量“ outputvar”不存在。 what am I missing here? 我在这里想念什么? Tried a number of other stuff but nothing seemed to work - what i want in the end is a variable that is named "outputvar" that contains the prompt input, just to clarify. 尝试了许多其他方法,但似乎没有任何效果-我最后想要的是一个名为“ outputvar”的变量,其中包含提示输入,只是为了澄清。

Your issue is due to scoping. 您的问题是由于范围界定。 The variable created via New-Variable is (by default) scoped so that it is only accessible within your function. 通过New-Variable创建New-Variable (默认情况下)是作用域的,因此只能在函数中访问。 You can override the scope via the -Scope parameter: 您可以通过-Scope参数覆盖范围:

function testfunction ($varname,$text){
    $readhost = read-host -prompt "$text"
    new-variable -name $varname -value $readhost -scope Script
}

This changes the scope to Script and so the variable is now accessible outside of your function. 这会将范围更改为脚本,因此现在可以在函数外部访问该变量。 Defining non-standard scopes for your variables isn't very good practice however. 但是,为变量定义非标准范围不是很好的做法。 You should instead just be doing this: 相反,您应该这样做:

function testfunction ($text){
    read-host -prompt "$text"
}

$outputvar = testfunction sampletext

Use the -OutVariable common parameter. 使用-OutVariable通用参数。 To have your function support common parameters, add the CmdletBinding attribute decorator to the param block: 为了使您的函数支持通用参数,请将CmdletBinding属性装饰器添加到param块中:

function Test-Function {
  [CmdletBinding()]
  param($text)

  return Read-Host -Prompt $text
}

Test-Function -OutVariable sampletext |Out-Null
$sampletext

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM