如何将对象转换为字符串?

How to convert an object to a string?

我想指定当前目录的名称来构建并行目录的路径(对运行一些diff命令)。

但是当我这样做时:

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

而不是我预期的:

xmy_test_dirx

那么,我如何"unbox"目录的名称?


PS - 为了便于测试我使用:

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 的带有 属性 的对象,复制输入项上相应 属性 的值。

使用 Select-Object -ExpandProperty PropertyNameForEach-Object MemberName 来获取 属性:

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

... 或直接引用 属性:

$a = (Get-Item .).Name