2

I'm putting together a script to go to a bunch of domain computers and copy a file.

My code is:

Get-ChildItem -Path \\$computer -Filter $filename -Recurse -ErrorAction SilentlyContinue | Select-Object Directory -outvariable $directory

Now my problem is the result that is stored in the variable is @{Directory=\\Computer\dir

How do i make it output to the variable only the \\Computer\dir

Any help or guidance would be appreciated

2 Answers2

2

In essence, your problem is a duplicate of How do I write the value of a single property of a object? (among others) - in short: use -ExpandProperty <propName> instead of just [-Property] <propName> in order to extract just the property value, rather than creating a custom object with a property of that name.

Additionally, your problem is that you must pass a mere variable name - without the $ sigil - to
-OutVariable
:

Select-Object -ExpandProperty Directory -OutVariable directory

That is, pass just directory to -OutVariable to have it fill variable $directory.
By contrast, -OutVariable $directory would fill a variable whose name is contained in variable $directory.

mklement0
  • 382,024
  • 64
  • 607
  • 775
1

Select-Object by default creates an object that has the properties you selected. So in your case you get an object with a single property called Directory. If you are only selecting a single property you can use the ExpandProperty parameter to "promote", for lack of a better word, a property to an object.

Get-ChildItem -Path \\$computer -Filter $filename -Recurse -ErrorAction SilentlyContinue `
| Select-Object -ExpandProperty Directory -OutVariable directory
Jason Boyd
  • 6,839
  • 4
  • 29
  • 47
  • I tried that but it still gives me the same information in the variable – LostAndConfused Mar 04 '19 at 23:46
  • The `Directory` property is not a basic value type, it is also an object with properties. Try `-ExpandProperty FullName` instead and see if that gives you what you are looking for. – Jason Boyd Mar 04 '19 at 23:52
  • Yeah its still doing the same thing. Maybe this is just the only format of output i can get in to the variable I get @{Directory=\\Computer\Dir} What I want is \\Computer\Dir Maybe i have to convert the variable in to another variable dropping the unwanted information? – LostAndConfused Mar 04 '19 at 23:56
  • The problem is that `-outvariable $directory` should be `-outvariable directory` – mklement0 Mar 06 '19 at 04:03