큰 따옴표로 묶인 문자열에서 객체의 속성을 어떻게 사용할 수 있습니까?
다음 코드가 있습니다.
$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;
문자열에서 속성 중 하나를 사용하려고하면 명령을 실행합니다.
& "$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
합니다.
내 해결 방법은 새 변수에 복사하는 것입니다.
큰 따옴표로 묶인 문자열에서 객체의 속성에 직접 액세스하려면 어떻게해야합니까?
큰 따옴표로 묶인 문자열로 변수 이름을 묶으면 해당 변수의 값으로 대체됩니다.
$foo = 2
"$foo"
된다
"2"
작은 따옴표를 사용하지 않으려면 :
$foo = 2
'$foo'
그러나 속성에 액세스하거나 큰 따옴표로 묶인 문자열의 변수에 인덱스를 사용하려면 해당 하위 표현식을 $()
다음 으로 묶어야합니다 .
$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은 이러한 경우에만 변수를 확장합니다. 인덱스, 속성 또는 전체 계산을 포함하여 더 복잡한 식을 강제로 평가하려면 하위 $( )
식 연산자로 묶어야 내부식이 평가되고 문자열에 포함됩니다.
@Joey가 정답을 가지고 있지만 왜 평가를 강제 해야하는지에 대해 조금 더 추가하기 위해 $()
:
귀하의 예제 코드는 옆으로 PowerShell을의 제조 업체가 제한 단순한 변수 참조 확장과뿐만 아니라 속성없는 지원 액세스 선택한 이유를 가리 모호한 (포함 호출하여 수행됩니다 문자열 확장을 ToString()
, 개체에 방법을하는 "이상한"결과를 설명 할 수 있습니다.)
명령 줄의 맨 끝에 포함 된 예제 :
...\$LogFileName.ldf
객체의 속성이 기본적으로 확장 된 경우 위의 내용은
...\
이 참조하는 개체가 이후 $LogFileName
라는 속성이없는 것 ldf
, $null
(또는 빈 문자열) 변수를 대체 할 것입니다.
@Joey는 좋은 대답을 가지고 있습니다. String.Format에 상응하는 .NET 모양의 또 다른 방법이 있습니다. 객체의 속성에 액세스 할 때 선호합니다.
자동차에 관한 사항 :
$properties = @{ 'color'='red'; 'type'='sedan'; 'package'='fully loaded'; }
개체 만들기 :
$car = New-Object -typename psobject -Property $properties
문자열 보간 :
"The {0} car is a nice {1} that is {2}" -f $car.color, $car.type, $car.package
출력 :
# The red car is a nice sedan that is fully loaded
문서 참고 : Get-Help about_Quoting_Rules
문자열 보간을 다루지 만 PSv5부터는 심층적이지 않습니다.
To complement Joey's helpful answer with a pragmatic summary of PowerShell's string expansion (string interpolation in double-quoted strings, including in double-quoted here-strings):
Only references such as
$foo
,$global:foo
(or$script:foo
, ...) and$env:PATH
(environment variables) are recognized when directly embedded in a"..."
string - that is, only the variable reference itself is expanded, irrespective of what follows.To disambiguate a variable name from subsequent characters in the string, enclose it in
{
and}
; e.g.,${foo}
.
This is especially important if the variable name is followed by a:
, as PowerShell would otherwise consider everything between the$
and the:
a scope specifier, typically causing the interpolation to fail; e.g.,"$HOME: where the heart is."
breaks, but"${HOME}: where the heart is."
works as intended.
(Alternatively,`
-escape the:
:"$HOME`: where the heart is."
).To treat a
$
or a"
as a literal, prefix it with escape char.`
(a backtick); e.g.:
"`$HOME's value: `"$HOME`""
For anything else, including using array subscripts and accessing an object variable's properties, you must enclose the expression in
$(...)
, the subexpression operator (e.g.,"PS version: $($PSVersionTable.PSVersion)"
or"1st el.: $($someArray[0])"
)- Using
$(...)
even allows you to embed the output from entire command lines in double-quoted strings (e.g.,"Today is $((Get-Date).ToString('d'))."
).
- Using
Interpolation results don't necessarily look the same as the default output format (what you'd see if you printed the variable / subexpression directly to the console, for instance, which involves the default formatter; see
Get-Help about_format.ps1xml
):Collections, including arrays, are converted to strings by placing a single space between the string representations of the elements (by default; a different separator can be specified by setting
$OFS
) E.g.,"array: $(@(1, 2, 3))"
yieldsarray: 1 2 3
Instances of any other type (including elements of collections that aren't themselves collections) are stringified by either calling the
IFormattable.ToString()
method with the invariant culture, if the instance's type supports theIFormattable
interface[1], or by calling.psobject.ToString()
, which in most cases simply invokes the underlying .NET type's.ToString()
method[2], which may or may not give a meaningful representation: unless a (non-primitive) type has specifically overridden the.ToString()
method, all you'll get is the full type name (e.g.,"hashtable: $(@{ key = 'value' })"
yieldshashtable: System.Collections.Hashtable
).To get the same output as in the console, use a subexpression and pipe to
Out-String
and apply.Trim()
to remove any leading and trailing empty lines, if desired; e.g.,
"hashtable:`n$((@{ key = 'value' } | Out-String).Trim())"
yields:hashtable: Name Value ---- ----- key value
[1] This perhaps surprising behavior means that, for types that support culture-sensitive representations, $obj.ToString()
yields a current-culture-appropriate representation, whereas "$obj"
(string interpolation) always results in a culture-invariant representation - see this answer of mine.
[2] Notable overrides:
* The previously discussed stringification of collections (space-separated list of elements rather than something like System.Object[]
).
* The hashtable-like representation of [pscustomobject]
instances (explained here) rather than the empty string.
'development' 카테고리의 다른 글
mysql을 사용하여 쿼리 결과를 변수에 저장하는 방법 (0) | 2020.10.07 |
---|---|
Gradle 풍미 만 빌드 (0) | 2020.10.07 |
2014 년 12 월 31 일로 설정된 new Date () 대신 12 월 1 일이 표시됨 (0) | 2020.10.06 |
코드 숨김에 정의 된 바인딩 개체 (0) | 2020.10.06 |
보석 명령을 찾을 수 없습니다. (0) | 2020.10.06 |