如何在双引号字符串中使用对象的属性? [英] How can you use an object's property in a double-quoted string?

查看:47
本文介绍了如何在双引号字符串中使用对象的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

$DatabaseSettings = @();
$NewDatabaseSetting = "" | select DatabaseName, DataFile, LogFile, LiveBackupPath;
$NewDatabaseSetting.DatabaseName = "LiveEmployees_PD";
$NewDatabaseSetting.DataFile = "LiveEmployees_PD_Data";
$NewDatabaseSetting.LogFile = "LiveEmployees_PD_Log";
$NewDatabaseSetting.LiveBackupPath = '\\LiveServer\LiveEmployeesBackups';
$DatabaseSettings += $NewDatabaseSetting;

当我尝试在字符串执行命令中使用其中一个属性时:

When I try to use one of the properties in a string execute command:

& "$SQlBackupExePath\SQLBackupC.exe" -I $InstanceName -SQL `
  "RESTORE DATABASE $DatabaseSettings[0].DatabaseName FROM DISK = '$tempPath\$LatestFullBackupFile' WITH NORECOVERY, REPLACE, MOVE '$DataFileName' TO '$DataFilegroupFolder\$DataFileName.mdf', MOVE '$LogFileName' TO '$LogFilegroupFolder\$LogFileName.ldf'"

它试图只使用 $DatabaseSettings 的值,而不是 $DatabaseSettings[0].DatabaseName 的值,这是无效的.
我的解决方法是将其复制到一个新变量中.

It tries to just use the value of $DatabaseSettings rather than the value of $DatabaseSettings[0].DatabaseName, which is not valid.
My workaround is to have it copied into a new variable.

如何在双引号字符串中直接访问对象的属性?

How can I access the object's property directly in a double-quoted string?

推荐答案

当你用双引号将变量名括起来时,它会被该变量的值替换:

When you enclose a variable name in a double-quoted string it will be replaced by that variable's value:

$foo = 2
"$foo"

变成

"2"

如果您不想使用单引号:

If you don't want that you have to use single quotes:

$foo = 2
'$foo'

但是,如果您想访问属性,或在双引号字符串中使用变量的索引,则必须将该子表达式包含在 $() 中:

However, if you want to access properties, or use indexes on variables in a double-quoted string, you have to enclose that subexpression in $():

$foo = 1,2,3
"$foo[1]"     # yields "1 2 3[1]"
"$($foo[1])"  # yields "2"

$bar = "abc"
"$bar.Length"    # yields "abc.Length"
"$($bar.Length)" # yields "3"

PowerShell 仅在这些情况下扩展变量,仅此而已.要强制计算更复杂的表达式,包括索引、属性甚至完整的计算,您必须将它们包含在子表达式运算符 $( ) 中,这会导致计算内部的表达式并将其嵌入到字符串中.

PowerShell only expands variables in those cases, nothing more. To force evaluation of more complex expressions, including indexes, properties or even complete calculations, you have to enclose those in the subexpression operator $( ) which causes the expression inside to be evaluated and embedded in the string.

这篇关于如何在双引号字符串中使用对象的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆