If I have a script (script.ps1) like below:
$dir = Get-Item "C:\Windows"
$dir
and if I call it like:
$myDir = "script.ps1"
I get back the $dir
object in $myDir
and if I use:
$myDir.Name
I get:
Windows
I have a scenario where I need to call scripts using
$myDir = Powershell.exe -File "script.ps1"
With this, I end up getting the output in the form of a string array object and not in the form of the script-returned object as the command is apparently executed in a different session. Due to this, I can't call any property. Eg: $myDir.Name
returns nothing
My question is, how do I get the returned object type back as the result in the above case. ie, even when I execute
$myDir = Powershell.exe -File "script.ps1"
$myDir.Name
should return Windows
. Is it even possible?
Thanks for any help.
You could try like this :
script.ps1 (returns value of $dir
):
$dir = Get-Item "C:\Windows"
return $dir
script2.ps1 (returns name of $dir
) :
$myDir = .\script.ps1
$myDir.Name
$myDir.Name
returns : Windows
You can use the -OutputFormat parameter of powershell.exe.
#Write the command to file
"get-item c:\windows\" | out-file C:\temp\test.ps1
$justastring = powershell.exe -file c:\temp\test.ps1
#this is a string array
$justastring | get-member
$notastring = powershell.exe -outputformat xml -file c:\temp\test.ps1
#this is a Deserialized.System.IO.DirectoryInfo
$notastring | get-member
This output is also able to be saved as a file and brought back in later. See Import-CliXml and Export-CliXml . Note that because they are serialized objects they are no longer "live". Some of the methods you are used to seeing will not be there, property values will no longer update either. Its essentially a snapshot of the command output at the instant that the command ran.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.