다음과 같은 간단한 스크립트가 있습니다.
write-output "Calculating Mod Dates . . ."
$path = 'C:\Users\Server\SERVER\Online'
$files = Get-ChildItem -Path '$path' -include "*"
foreach ($file in $files) {
$ModDate = Get-Item $importfile | Foreach {$_.LastWriteTime}
$CurrentDate = Get-Date
$differece = ($CurrentDate - $ModDate).TotalSeconds
write-output "$importfile - $differece seconds ago."
}
그러나 첫 번째 write-output
명령은 작동하지만 두 번째 명령은 작동하지 않습니다. 왜 이런거야?
답변1
세 번째 줄에 작은따옴표를 잘못 사용했습니다. '$path'는 문자열 리터럴 $path로 평가되는데, 이는 실제 경로가 아닐 가능성이 높습니다.
답변2
Poorman의 디버그 세션 접근 방식 - ISE 및/또는 VSCode 사용
채워지지 않고 제자리에 없는 구문 오류와 내용이 있습니다. Write-Output이 기본값이므로 실제로 지정할 필요가 없습니다. 간단한 문자열에는 작은따옴표를 사용하고 변수 확장에는 큰따옴표를 사용하고 -f를 사용하는 특정 형식 지정 시나리오를 사용합니다.
# write-output 'Calculating Mod Dates . . .'
'Calculating Mod Dates . . .'
# What I am showing here is called variable squeezing.
# It assigns to the variable while output to the screen so you can see what is being populated.
# remove the far left and far right parens to eliminate all the extra output
($path = 'E:\Temp')
($files = Get-ChildItem -Path $path)
foreach ($file in $files)
{
# This is not doing anything as $importfile is not declared or populate anywhere that you have shown.
# $ModDate = Get-Item $importfile | Foreach {$_.LastWriteTime}
# This should be
($ModDate = (Get-Item -Path $file.FullName).LastWriteTime)
($CurrentDate = Get-Date)
($difference = ($CurrentDate - $ModDate).TotalSeconds)
# write-output "$importfile - $differece seconds ago."
"$($file.Name) - $difference seconds ago."
}
# Results
'Calculating Mod Dates . . .'
Calculating Mod Dates . . .
($path = 'E:\Temp')
E:\Temp
($files = Get-ChildItem -Path $path)
Directory: E:\Temp
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 1/14/2019 3:42 PM Reports
-a---- 2/25/2019 10:27 AM 81966 Best-practices.jpg
-a---- 2/25/2019 10:28 AM 82919 computer_speed.jpg
-a---- 3/19/2019 3:34 PM 26 csv1.csv
...
foreach ($file in $files)
{
($ModDate = (Get-Item -Path $file.FullName).LastWriteTime)
($CurrentDate = Get-Date)
($difference = ($CurrentDate - $ModDate).TotalSeconds)
"$($file.Name) - $difference seconds ago."
}
Monday, January 14, 2019 3:42:40 PM
Wednesday, March 27, 2019 11:55:21 AM
6207161.4845608
Reports - 6207161.4845608 seconds ago.
Monday, February 25, 2019 10:27:37 AM
Wednesday, March 27, 2019 11:55:21 AM
2597263.7171875
Best-practices.jpg - 2597263.7171875 seconds ago.
Monday, February 25, 2019 10:28:26 AM
Wednesday, March 27, 2019 11:55:21 AM
2597215.0719793
computer_speed.jpg - 2597215.0719793 seconds ago.
Tuesday, March 19, 2019 3:34:04 PM
Wednesday, March 27, 2019 11:55:21 AM
678077.1822375
csv1.csv - 678077.1822375 seconds ago.
Tuesday, March 19, 2019 3:34:34 PM
Wednesday, March 27, 2019 11:55:21 AM
678047.2243663
...