Powershell: 为什么这里foreach循环不输出?

分享于 

4分钟阅读

电脑

  繁體 雙語

问题:

我有以下简单的脚本:


write-output"Calculating Mod Dates.. ."


$path = 'C:UsersServerSERVEROnline'


$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 evaluates计算结果为字符串 $path,,它不太可能是实际的,um的路径。


回答 2:

使用ISE和/or VSCode调试poorman会话方法

你有语法错误,其中没有填充和放置的内容。 写输出是缺省的,所以没有必要指定它。 对简单字符串使用单引号,对于扩展变量双击,使用表示-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


...





for  POW  OUT  输出  Powershell  loop  
相关文章