开发者

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.


It's pretty straightforward:

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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜