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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With