2

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.

2 Answers 2

7

It's pretty straightforward:

$server = Read-Host "Enter server name"
Get-ChildItem \\$server\users -recurse | measure-object length -sum
Sign up to request clarification or add additional context in comments.

5 Comments

I wonder then if this is a powershell version problem, because I can't get that to work. I get a: "Cannot find path '\\servername\C$\foldername' because it does not exist." error
Well I've downloaded v 2.0 and I still can't get that to work. It looks like it -should- work. I must be missing something obvious here.
Dunno. It works for me on V2 gci \\$servername\c$\users. BTW if servername is a variable it must be \\$servername\c$.
Ended up using: $server = Read-Host "Enter server name" $share = Read-Host "Enter share name" Get-ChildItem "\\$server\$share" -recurse | measure-object length -sum Thanks Keith
I just verified this works for me in V1 of PowerShell. I also experimented with various double and single quotes and found that it behaves best without quoting at all.
2

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 " ".

2 Comments

In your Write-Host example no quotes are needed at all. Even in the context of command mode parsing, you don't need double quotes around a variable. Try this on V2 - gci $pshome\modules - look ma - no quotes. :-)
@Keith Thanks for the comment, that is true, but the reason I put them to demonstrate the difference in behaviour between double and single quotes. I have amended the example to demo this out though. Thanks for pointing that out. :-)

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.