-1

Using PowerShell. Trying to label a filename using a variable that the user enters.

function foo
{ $name = Read-Host -Prompt "Get name"
...
....
}

foo | Out-file -FilePath c:\temp\$name.log

result is a file is made but its just c:\temp\.log. How can I use input to the $name to name the file?

starball
  • 20,030
  • 7
  • 43
  • 238
Rogelio
  • 1
  • 3

1 Answers1

1
  • Creating a variable inside a function creates a local variable and therefore doesn't make it visible to the caller.

    • There are ways to create a variable in the parent scope, but such techniques are best avoided in the interest of encapsulation.
  • Thus, if you want the caller to act on the value of $name, output its value from the function, or output the user response directly, as shown below.

# Define a function that prompts the user for a name
# *and outputs it* - no strict need for a variable.
function foo { Read-Host -Prompt "Get name" }

# Now use an expandable string ("...") with a subexpression ($(...))
# to call the function and embed its output in the string.
# Note that this either creates a new empty file or
# truncates an existing file.
Out-File -FilePath "c:\temp\$(foo).log"
mklement0
  • 382,024
  • 64
  • 607
  • 775