Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

powershell - 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).

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...