如何将对象转换为字符串? [英] How to convert an object to a string?
问题描述
我想分配当前目录的名称来构造并行目录的路径(运行一些差异命令).
I want to assign the name of the current directory to construct the path of a parallel directory (to run some diff commands).
但是当我这样做时:
New-Item -ItemType Directory -Name my_test_dir;
Set-Location my_test_dir;
$a = $( Get-Item . | Select-Object Name );
write-host( "x${a}x" );
我明白
x@{Name=my_test_dir}x
x@{Name=my_test_dir}x
而不是我预期的:
xmy_test_dirx
xmy_test_dirx
那么,我如何拆箱"目录名称?
So, how do I "unbox" the name of the directory?
PS - 为了便于测试,我使用:
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
推荐答案
当您使用 ... |Select-Object PropertyName
时,它会生成一个具有名为 PropertyName
的属性的对象code>,从输入项上的相应属性中复制值.
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.
使用 Select-Object -ExpandProperty PropertyName
或 ForEach-Object MemberName
来获取属性的值:
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
这篇关于如何将对象转换为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!