简体   繁体   English

功能内的PowerShell foreach

[英]PowerShell foreach within function

I'm writing a function to collect logs for analysis. 我正在编写一个收集日志以进行分析的功能。

I'm trying to use variables to keep it as tight as possible, but for some reason the function won't create, moans about brackets and variables. 我正在尝试使用变量来使其尽可能紧密,但是由于某种原因,该函数将无法创建,因此会抱怨括号和变量。

Any assistance would be appreciated. 任何援助将不胜感激。

FUNCTION GetLogs ($CompName)
{
$LOGS    = "CcmExec.log,Scheduler.log,WUAHandler.log"
$CCMPath = "C$\Windows\CCM\Logs"
$Target  = "C:\Temp\Logs"

foreach (file$ IN $LOGS ) {file$ = Copy-Item \\$CompName\$CCMPath\$LOGS $Target\$CompName-$LOGS}    
}

You $Logs is just a string, not a string array thus you can't iterate over it. $Logs只是一个字符串,而不是字符串数组,因此您无法对其进行迭代。 You can fix that using: 您可以使用以下方法解决此问题:

$LOGS    = "CcmExec.log", "Scheduler.log","WUAHandler.log"

Also you are assigning the result of the CopyItem to an invalid variable and don't use the current loop variable. 另外,您正在将CopyItem的结果分配给无效变量,并且不要使用当前循环变量。 Your function probably should look like this: 您的函数可能应如下所示:

function Get-Logs
{
    Param
    (
        [string]$CompName
    )

    $logs    = "CcmExec.log", "Scheduler.log","WUAHandler.log"
    $ccmPath = "C$\Windows\CCM\Logs"
    $target  = "C:\Temp\Logs"

    $logs | ForEach-Object {
        Copy-Item -Path  "\\$CompName\$ccmPath\$_" -Destination "$target\$CompName-$_"
    } 
}

Note: You should probably rename your function to Copy-LogsToLocal or something... 注意:您可能应该将函数重命名为Copy-LogsToLocal或其他名称。

That code won't work. 该代码无效。

I think you meant to define an array in $LOGS, but you are actually defining just one String. 我想您打算在$ LOGS中定义一个数组,但实际上您仅定义了一个String。

Try this: $LOGS = "CcmExec.log", "Scheduler.log", "WUAHandler.log" 试试这个: $LOGS = "CcmExec.log", "Scheduler.log", "WUAHandler.log"

Also it looks like you are trying to copy those 3 Files somewhere, but what you are doing is setting the var $file each turn to something else. 同样,您似乎正在尝试将这3个文件复制到某个地方,但是您正在做的是将var $ file设置为每次转其他位置。 The statement $file In $LOGS means that the variable $file will be "CcmExec.log" the first time of the loop, then "Scheduler.log" and so on. $file In $LOGS的语句$file In $LOGS表示变量$ file在第一次循环时将是“ CcmExec.log”,然后是“ Scheduler.log”,依此类推。

So what I think you want to do is this: 所以我想你要做的是:

Function GetLogs ($CompName) {

$LOGS    = "CcmExec.log","Scheduler.log","WUAHandler.log"
$CCMPath = "C$\Windows\CCM\Logs"
$Target  = "C:\Temp\Logs"

foreach ($file In $LOGS ) {
       Copy-Item -Path \\$CompName\$CCMPath\$file -Destination $Target\$CompName-$file
    }    
}

I also removed some typos. 我还删除了一些错别字。

Is that about right? 那是对的吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM