views:

581

answers:

2

Hi All, and thanks in advacne for your help large or small.

A bit of a newbie to the powershell world and 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.

Any help would be very appreciated.

+4  A: 

It's pretty straightforward:

$server = Read-Host "Enter server name"
Get-ChildItem \\$server\users -recurse | measure-object length -sum
Keith Hill
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
Dazinuk
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.
Dazinuk
Dunno. It works for me on V2 `gci \\$servername\c$\users`. BTW if servername is a variable it must be `\\$servername\c$`.
Keith Hill
Ended up using:$server = Read-Host "Enter server name"$share = Read-Host "Enter share name"Get-ChildItem "\\$server\$share" -recurse | measure-object length -sumThanks Keith
Dazinuk
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.
Goyuix
+1  A: 

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

Jonny
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 Hill
@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. :-)
Jonny