Chris Topher
Chris Topher

Reputation: 23

How to enter and use a variable in the middle of "New-Item" in powershell

So I'm trying to create a simple program that copies files from one location to another. I got that part down just find but I'd like to as ask for user input as to a set aspect to the path I need to create a new folder at.

For example

Ask for user input and store that name in a variable. Then use that variable in the path to create a new folder called test

$inputName = Read-Host 'Enter computer name'
New-Item C:\Users\$inputName\Documents\test -type directory | Out-Null

So if there were multiple users on a computer you could ask which user\documents you would create the new document in.

Very much still learning/teaching myself powershell so sorry if it's something I'm totally missing! Thanks for your help!

Upvotes: 2

Views: 3490

Answers (1)

user4317867
user4317867

Reputation: 2448

-Edit 2, adding notes about CmdletBinding options. And if you leave out the params, powershell prompts for input.

Function My-Test{
[CmdletBinding(SupportsShouldProcess=$true)]
Param(
 [Parameter(Mandatory=$true)]
  [string]$Path,
 [Parameter(Mandatory=$true,
  HelpMessage="Enter ServerName")]
  [String]$server,
)
My-Test -Path C:\Temp -server Server9000

-Edit to add PowerShell will expand variables between double quotes. Single quotes on the other hand will write the $path as exactly that.

As an example:

Write-Host 'Your variable is $path`
 Your variable is $path
Write-Host "Your path is $path"
 Output: Your path is C:\Temp

You can use Read-Host to prompt the user to input something that's assigned to a variable. Additionally, you can specify AsSecureString so the value stored is encrypted.

$path = Read-Host -Prompt "Enter path name"
Write-Host "You chose $path"

Secondly, your script can begin with param($path) which will accept the path as a cmdline parameter.

PS C:\ > Script.ps1 -path "c:\temp"

Upvotes: 1

Related Questions