-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?

3
  • The file should always go to C:\temp ? What happens if the file with the same name already exists in the destination ? Commented Aug 29, 2022 at 21:06
  • 1
    I guess your answer is here stackoverflow.com/questions/32448174/… or pretty close to it Commented Aug 29, 2022 at 21:12
  • any directory, i label the file as a different week by input. Commented Aug 29, 2022 at 21:18

1 Answer 1

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"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.