来自csv的PowerShell变量

时间:2014-05-19 12:15:26

标签: powershell

我在使用来自csv文件的脚本中的变量时遇到问题。每个文本UNC都找到了,我想做点什么。当找不到UNC文本时,我想做其他事情。这非常适合在本地或远程服务器上运行脚本。

脚本

$File = (Import-Csv -Path S:\Input\Auto_Clean.csv | Select-String -NotMatch "#")

Foreach ($Item in $File) {
    If ( $SERVER -eq "UNC" ) { 
        Write-Host "UNC: $SERVER, $PATH, $OlderThanDays" } 
        else {
        Write-Host "Not UNC: $SERVER, $PATH, $OlderThanDays"}
}

CSV文件

# Input file:
SERVER, PATH, OlderThanDays
Server1, E:\Share\Dir1, 10
Server2, F:\Share\Dir2, 5
UNC, \\Domain\Share\Dir1, 30

cosole中的所需结果

Not UNC: Server1, E:\Share\Dir1, 10
Not UNC: Server2, F:\Share\Dir2, 5
UNC: UNC, \\Domain\Share\Dir1, 30

Write-Host $File的输出正确显示标签/变体:

Write-Host $File
@{SERVER=UNC; PATH=\\domain\Share\Dir1; OlderThanDays=10}

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

我认为这就是你想要的:

Import-Csv -Path "S:\Input\Auto_Clean.csv" | % {
    if ($_.Server -eq "UNC")
    {
        Write-Host "UNC: $($_.Server), $($_.Path), $($_.OlderThanDays)" 
    }
    else
    {
        Write-Host "Not UNC: $($_.Server), $($_.Path), $($_.OlderThanDays)"
    }
}

这会产生以下输出:

Not UNC: Server1, E:\Share\Dir1, 10
Not UNC: Server2, F:\Share\Dir2, 5
UNC: UNC, \\Domain\Share\Dir1, 30

如果您想忽略以#开头的行,您可以使用以下内容:

(Get-Content "S:\Input\Auto_Clean.csv") -notmatch '^#' | ConvertFrom-CSV | % {
    if ($_.Server -eq "UNC")
    {
        Write-Host "UNC: $($_.Server), $($_.Path), $($_.OlderThanDays)" 
    }
    else
    {
        Write-Host "Not UNC: $($_.Server), $($_.Path), $($_.OlderThanDays)"
    }
}