1

I want to save the name of folder into a variable.

$foldername = Get-ItemProperty -Path C:\test* | Select-Object Name

Get-Variable -Name foldername

@{Name=test123}

How can i remove the @{} in the output of the variable?

dvdrtb
  • 13
  • 2
  • 1
    What you want is [Get-ChildItem](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/get-childitem), and have a look at the `-ExpandProperty` parameter for Select-Object – Theo Aug 22 '22 at 14:28
  • 1
    Agreeing with Theos comment above. You could also just use `Get-ChildItem -Path C:\Test -Name -Directory`; *assuming you're on PSv3*. Where `-Name` only returns the name property, and `-Directory` only returns folders. Edit: *Believe I misread the question, but still leaving my comment here for educational purposes*. – Abraham Zinala Aug 22 '22 at 14:29
  • In short: [`Select-Object`](https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/select-object) (`select`) by default returns _a `[pscustomobject]` instance_ that has the _requested properties_ - even when you're only asking for a _single_ property. To get only that property's _value_, use `-ExpandProperty $propertyName` instead - see the [linked duplicate](https://stackoverflow.com/q/48807857/45375) for details and alternatives, notably the ability to simply use `(...).$propertyName` – mklement0 Aug 22 '22 at 14:43
  • As for the hashtable-_like_ representation you saw in the display output from `Get-Variable` (`@{Name=test123}`): It is unrelated to hashtables and not meant for programmatic processing. PowerShell uses this format when `[pscustomobject]` instances, such as created by `Select-Object`, are coerced to _strings_ - see [this answer](https://stackoverflow.com/a/53107600/45375) for more information. – mklement0 Aug 22 '22 at 15:10
  • To summarize: Mathias' answer _bypasses_ your original problem via the use of `Get-ItemPropertyValue`, but both `Get-ItemProperty` and `Get-ItemPropertyValue` are rarely used in the context of file-system operations. More idiomatic solutions are (note that due to use of wildcards _multiple_ names may be returned): `$foldername = (Get-ChildItem C:\test*).Name` or `$foldername = Get-ChildItem C:\test* -Name` – mklement0 Aug 22 '22 at 15:15

1 Answers1

1

Use Get-ItemPropertyValue instead of Get-ItemProperty:

$foldername = Get-ItemPropertyValue -Path C:\test* -Name Name
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
  • One more question. How can manipulate the content of the variable. For example if there is "new" in the name of folder and i want to remove the "new" in the variable. – dvdrtb Aug 22 '22 at 15:49
  • `$foldername = $foldername.Substring(3)` in a subsequent statement (or `$foldername = Get-ItemPropertyValue -Path C:\test* -Name Name |ForEach-Object Substring 3`) – Mathias R. Jessen Aug 22 '22 at 15:51