0

I'm creating a script to access a shared network folder. Sample code looks like this:

[CmdletBinding()]
Param (
    [string]$SharedFolder,

    [ValidateScript({ Test-NetConnection $_ -InformationLevel Quiet })]
    [string]$Hostname
)

[string]$UNCPath = "\\" + $Hostname + "\" + $SharedFolder

# Do stuff
Get-ChildItem $UNCPath # OK

My question is about the $UNCPath variable. Is there a cleaner, better way to accessing the share? Gluing the path together as a string looks ugly.

Is there a better way to access a UNC path using PowerShell?

user9924807
  • 707
  • 5
  • 22
  • 1
    `"\\${Hostname}\${SharedFolder}"`? – Ansgar Wiechers Jun 26 '18 at 15:25
  • You can write `[string]$UNCPath = "\\$Hostname\$SharedFolder"` if you prefer. There are more alternatives at [How do I use join-path to combine more than two strings into a file path?](https://stackoverflow.com/q/25880122/1115360) – Andrew Morton Jun 26 '18 at 15:30
  • As a side note, you should avoid 'typing' your variables. Unlike, say C#, PowerShell is designed to be weakly typed and placing the type in front of a variable doesn't always help with situations of mismatching which would be caught by Visual Studio. In particular using `[string]` is particularly deceptive. In your case, for example, these would be valid syntactically and would generate no error at runtime, but are likely to lead to problems later on: `[string]$UNCPath = [DateTime]::Now`, `[string]$UNCPath = Get-ADUser -Filter {Name -like "*boxdog*"}` – boxdog Jun 26 '18 at 15:45
  • @boxdog Can you elaborate on what the problems would be and how Visual Studio would help if the $UNCPath were untyped? It seems to me that if the language was designed to be weakly typed it wouldn't have been designed to include type specifiers. – veefu Jun 26 '18 at 16:28
  • @veefu In his example, strongly-typing the variable *should* throw errors if you try to store something that doesn't match the type in the variable. – Maximilian Burszley Jun 26 '18 at 16:32
  • @veefu, Visual Studio would help (for, say, c#) because trying to assign, say, an ADUser object to a string would generate an error at compile-time; here it doesn't, so the 'typing' is not helping at all. Also, doing this `[string]$UNCPath` is not really setting `$UNCPath` as a string in the same way as in other languages. It is really a hidden cast operation, which allows you to assign a string to the variable, or _anything that can be cast to a string_. Since everything in .NET can be a string, then anything can be assigned to that variable, defeating the purpose of setting the type. – boxdog Jun 26 '18 at 16:37
  • @boxdog It seems like questionable advice to me. I prefer to provide typing, especially for function parameters. To each their own. – veefu Jun 26 '18 at 16:48

0 Answers0