2015-10-20 59 views
-1

這可能是問題的標題有點誤導,但我懷疑已經做了一些從2.0到4.0的變化,我不知道......所以這裏去如何在Powershell v4 vs v2中使用Get-ChildItem

下面的代碼將提供給我使用PowerShell 2.0

## Get files/items using above variables 
$LogFiles = @(Get-ChildItem "$IhsLogFolder\*.*" -include $LogFileMatch) 
$log.debugFormat("Found in {0} are {1}", $IhsLogFolder, $LogFiles) 
foreach ($LogFile in $LogFiles) { 
    $log.debugFormat("Found {0}", $LogFile.Name) 
} 

$LogFiles += @(Get-ChildItem "$PluginLogFolder" -recurse -include $LogFileMatch) 
$log.debugFormat("Found in {0} are {1}", $PluginLogFolder, $LogFiles) 

我們的Windows 2008服務器上的預期效果正在執行的命令將

Get-ChildItem e:\logs\HTTPServer\*.* -include error.log,access.log,http_plugin.log 

一第二

Get-ChildItem e:\logs\WebPlugin\webserver\*.* -include error.log,access.log,http_plugin.log 

試圖在同一個腳本在Windows 2012使用PowerShell 4.0上面的代碼將不會返回任何文件,但如果我在PowerShell中嘗試只命令它會找到文件

PS C:\> Get-ChildItem e:\logs\HTTPServer\*.* -include error.log,access.log,http_plugin.log 
Directory: E:\logs\HTTPServer 
Mode    LastWriteTime  Length Name 
----    -------------  ------ ---- 
-a---  20.10.2015  15:35 4296922 access.log 
-a---  19.10.2015  15:26  189102 error.log 

是否有任何@(Get-ChildItem...不在Powershell 4.0中返回文件的明顯原因是什麼?

更新

  1. 參考。評論 - 是的,我敢肯定,$日誌不是問題
  2. 我只是發現下面的工作(硬編碼包括)$LogFiles = @(Get-ChildItem "$IhsLogFolder\*.*" -include error.log,access.log,http_plugin.log),應用包含作爲變量與更多比一個文件不返回我們4.0服務器上的任何結果,但使用變量和只有一個文件的作品。

更好的代碼片段

$pathToFolder = "d:\temp\*.*" 
# This does not return results 
$includeFile = "file1.txt,file2.txt" 
# This will return results 
#$includeFile = "file1.txt" 
Write-Host $includeFile 
# Below does not work if more than one file in the include 
#$result = @(Get-ChildItem $pathToFolder -include $includeFile) 
# Below does work even if more than one file in the include 
$result = @(Get-ChildItem $pathToFolder -include file1.txt,file2.txt) 
Write-Host $result 

if ($result) { 
    Write-Host "Yes" 
} else { 
    Write-Host "No" 
}` 
+1

什麼是'$ log'?你確定它不是'$ log.debugFormat',它的行爲不同嗎? – arco444

回答

0

-include參數需要一個字符串數組:

> Get-Help Get-ChildItem -Full 
    ... 
    -Include <string[]> 

因此,構建$includeFile爲數組應該工作,目前你將其設置爲一個串。

嘗試,而不是:

$includeFile = "file1.txt","file2.txt" 
$result = Get-ChildItem $pathToFolder -include $includeFile 
相關問題