Silver_Hammer
Silver_Hammer

Reputation: 23

How do I use a variable in a UNC path in powershell?

I'm trying to count the contents of a folder on a remote server.

I know that:

Get-ChildItem \\ServerName\c$\foldername -recurse | Measure-Object -property length -sum

works a treat.

However I'm trying to make the server name a variable, by user input, but I can't get the path to accept any variable.

Upvotes: 2

Views: 26273

Answers (2)

Jonny
Jonny

Reputation: 2683

If you are doing this in the shell and you want a one-liner, try this:

Get-ChildItem "\\$(Read-Host)\share" -recurse | Measure-Object length -sum

This won't produce a message asking for input, but saves assigning to a variable that you may not need, and if you are running this from the shell then you know the input that is needed anyway!

Also double quotes will mean a variable is evaluated so:

$hello = "Hello World"
Write-Host "$hello"
Hello world

Or as Keith Hill has pointed out:

$hello = "Hello World"
Write-Host $hello
Hello World

Where as single quotes won't evaluate the variable so:

$hello = "Hello World"
Write-Host '$hello'
$hello

So if you are using variables and you have spaces in the path use " ".

Upvotes: 2

Keith Hill
Keith Hill

Reputation: 202032

It's pretty straightforward:

$server = Read-Host "Enter server name"
Get-ChildItem \\$server\users -recurse | measure-object length -sum

Upvotes: 7

Related Questions