3

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 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

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

4 Comments

I tried that but it still gives me the same information in the variable
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.
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?
The problem is that -outvariable $directory should be -outvariable directory

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.