0

在我们开始编写代码之前,我有一个包含 PC 列表且只有 1 列的 CSV。目标是使用 A 列中标记为“计算机”的信息,并获取这些机器的所有服务,并将它们输出到基于 A 列信息创建的文件夹中。到目前为止,脚本如下:

Import-Module activedirectory
$Group=import-csv C:\Users\axb3055\Documents\CSV_Test.csv 
$ServiceList = Test-Path C:\ServiceList
if($ServiceList -eq $true)
{Write-Host "Service List Exists"}
else
{
Write-Host "Creating ServiceList folder"
New-Item C:\ServiceList\$CompName -ItemType directory -ErrorActionSilentlyContinue | Out-Null
}
$Group | foreach {$CompName = $_.Computers New-Item -Path C:\ServiceList\$CompName -ItemType directory | Get-Service -ComputerName  $_.Computers} | Out-File C:\ServiceList\$CompName\$CompName.txt

现在发生的事情是创建了服务列表文件夹,但之后没有任何反应。我在 for-each 块中得到一个指向“New-Item”的错误点,但我不确定它可能是什么。有任何想法吗?

4

2 回答 2

1

有一些改进的余地。您的直接问题是您没有将New-Itemcmdlet 与其周围的代码分开。使用适当的缩进和换行符。如果功能和可读性受到影响,单行是无用的。

$Group = Import-Csv "C:\Users\axb3055\Documents\CSV_Test.csv" 
$serviceListPath = "C:\ServiceList"
if(Test-Path $serviceListPath){
    Write-Host "Service List Exists"
} else {
    Write-Host "Creating ServiceList folder"
    New-Item C:\ServiceList -ItemType directory | Out-Null
}

# Gather info and place int file
ForEach($computer in ($Group.Computers)){
    # Define output folder for this computer
    $outputFolder = "$serviceListPath\$computer"
    $outputFile = "$outputFolder\$computer.csv"
    # Create the output folder if it does not already exist.
    if(!(Test-Path $outputFolder)){New-Item -Path $outputFolder -ItemType directory | Out-Null}
    # Output Service information to file.
    Get-Service -ComputerName $computer | Select-Object Status,Name,DisplayName | Export-CSV -NoTypeInformation $outputFile
}

这应该检查通过的每台计算机的服务,并将结果作为 CSV 记录在各自的文件夹中。

于 2016-03-14T17:18:21.127 回答
-1

我将通过分解您的管道语句开始故障排除。打印整个序列中的值以查看是否有空值并进行相应调整。

Import-Module activedirectory
    $Group=import-csv C:\Users\axb3055\Documents\CSV_Test.csv 
    $ServiceList = Test-Path C:\ServiceList
    if($ServiceList -eq $true)
    {
    Write-Host "Service List Exists"
    }
    else
    {
    Write-Host "Creating ServiceList folder"
    New-Item C:\ServiceList\$CompName -ItemType directory -ErrorActionSilentlyContinue | Out-Null
    }

    foreach ($CompName in $Group.Computers){
     #create file
     New-Item -Path C:\ServiceList\$CompName -ItemType directory 
     #get service and assign to variable
     $service = Get-Service -ComputerName $CompName
     #output the service content to the textfile
     Out-File C:\ServiceList\$CompName\$CompName.txt -value $service        
    }
于 2016-03-14T17:17:43.703 回答