New-PSDrive : Unable to use a variable in root parameter

Ask your PowerShell-related questions, including questions on cmdlet development!
Forum rules
Do not post any licensing information in this forum.

Any code longer than three lines should be added as code using the 'Select Code' dropdown menu or attached as a file.
This topic is 1 year and 1 month old and has exceeded the time allowed for comments. Please begin a new topic or use the search feature to find a similar but newer topic.
Locked
Fida BenH
Posts: 1
Last visit: Wed Feb 01, 2023 8:35 am

New-PSDrive : Unable to use a variable in root parameter

Post by Fida BenH »

when i use this code :
  1. $ip=$label1.text
  2. $path = "\\$ip\Folder\"
  3. $cred=Get-Credential
  4. New-PSDrive -Name "X" -PSProvider FileSystem -Root $path -Credential $Cred -Scope Global
it returns error :
  1.  
  2. ERROR: New-PSDrive : network path not found
  3. ERROR: Au caractère \\xxx.xxx.xxx.xxx\balabal\Sources Sapien Powershell\blabla\bla_bla.Run.ps1:248 : 3
  4. ERROR: +         New-PSDrive -Name "X" -PSProvider FileSystem -Root $path -Cre ...
  5. ERROR: +         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  6. ERROR:     + CategoryInfo          : InvalidOperation : (X:PSDriveInfo) [New-PSDrive], Win32Exception
  7. ERROR:     + FullyQualifiedErrorId : CouldNotMapNetworkDrive,Microsoft.PowerShell.Commands.NewPSDriveCommand
i think New-PSDrive not undertanding $path variable, so it works when i replace it by a string
  1.  
  2. New-PSDrive -Name "X" -PSProvider FileSystem -Root \\10.0.0.33\d$\bla-bla -Credential $Cred -Scope Global
  3.  
How can i use $path variable in root parameter of New-PSDrive :?: :?: :?:
jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

Re: New-PSDrive : Unable to use a variable in root parameter

Post by jvierra »

If the path is not found, then it is likely that you have an error in you string or you have no access to the path.

Also be careful of how you construct path strings using string expansion. "$" can cause issues with the expansion.

The following method would be safer:

$path = '\\' + $label1.text + '\Folder\'
This topic is 1 year and 1 month old and has exceeded the time allowed for comments. Please begin a new topic or use the search feature to find a similar but newer topic.
Locked