2011-08-26 5 views
13

Soy nuevo en Powershell y estoy tratando de encontrar la forma de imprimir el valor de una variable [ref] desde dentro de una función.powershell: cómo escribir el valor de host de la variable [ref]

Aquí está mi código de prueba:

function testref([ref]$obj1) { 
    $obj1.value = $obj1.value + 5 
    write-host "the new value is $obj1" 
    $obj1 | get-member 
} 


$foo = 0 
"foo starts with $foo" 
testref([ref]$foo) 
"foo ends with $foo" 

La salida que recibo de esta prueba es el siguiente. Notarás que no obtengo el valor de $ obj1 como esperaba. También intenté pasar $ obj1.value en la llamada a write-host, pero eso generó la misma respuesta.

PS > .\testref.ps1 
foo starts with 0 
the new value is System.Management.Automation.PSReference 


    TypeName: System.Management.Automation.PSReference 

Name  MemberType Definition 
----  ---------- ---------- 
Equals  Method  bool Equals(System.Object obj) 
GetHashCode Method  int GetHashCode() 
GetType  Method  type GetType() 
ToString Method  string ToString() 
Value  Property System.Object Value {get;set;} 
foo ends with 5 

Respuesta

29

Usted probablemente habría intentado:

write-host "the new value is $obj1.value" 

y se puso salida del

the new value is System.Management.Automation.PSReference.value 

correspondiente Creo que no se dio cuenta del .value en el final de la salida.

En cadenas que tienen que hacer algo como esto mientras se accede a las propiedades:

write-host "the new value is $($obj1.value)" 

O usa formato de cadena, así:

write-host ("the new value is {0}" -f $obj1.value) 

o asignar valor fuera como $value = $obj1.value y uso en las cuerdas.

+0

Sí, eso era todo. ¡Gracias! – Denis

+0

@Denis - ¡Acepte como respuesta si resuelve su problema! – manojlds

+0

¿Cómo hago eso? – Denis

Cuestiones relacionadas