How to convert an object to a string?

心不动则不痛 提交于 2021-02-17 05:33:25

问题


I want to assign the name of the current directory to construct the path of a parallel directory (to run some diff commands).

However when I do this:

New-Item -ItemType Directory -Name my_test_dir;
Set-Location my_test_dir;
$a = $( Get-Item . | Select-Object Name ); 
write-host( "x${a}x" );

I get

x@{Name=my_test_dir}x

instead of what I expected:

xmy_test_dirx

So, how do I "unbox" the name of the directory?


PS - for ease of testing I use:

mkdir my_test_dir; cd my_test_dir; $a = $( Get-Item . | Select Name ); echo "x${a}x"; cd ..; rmdir my_test_dir

回答1:


When you use ... |Select-Object PropertyName, it produces an object with a property named PropertyName, copying the value from the corresponding property on the input item.

Use Select-Object -ExpandProperty PropertyName or ForEach-Object MemberName to get just the value of the property:

$a = Get-Item . | Select-Object -ExpandProperty Name 
# or 
$a = Get-Item . | ForEach-Object Name

... or reference the property directly:

$a = (Get-Item .).Name


来源:https://stackoverflow.com/questions/62135330/how-to-convert-an-object-to-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!