Reputation: 14695
I have a problem with using the variables in my script coming from a csv file. Everytinme the text UNC is found, I want to do something. And when the text UNC is not found, I want to do something else. This is great for running a script locally or on the remote server.
Script
$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-file
# Input file:
SERVER, PATH, OlderThanDays
Server1, E:\Share\Dir1, 10
Server2, F:\Share\Dir2, 5
UNC, \\Domain\Share\Dir1, 30
Desired result in cosole
Not UNC: Server1, E:\Share\Dir1, 10
Not UNC: Server2, F:\Share\Dir2, 5
UNC: UNC, \\Domain\Share\Dir1, 30
The output of Write-Host $File
is correctly displaying the labels/variants:
Write-Host $File
@{SERVER=UNC; PATH=\\domain\Share\Dir1; OlderThanDays=10}
Thank you for your help.
Upvotes: 0
Views: 499
Reputation: 12248
I think this is what you want:
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)"
}
}
This produces the following output:
Not UNC: Server1, E:\Share\Dir1, 10
Not UNC: Server2, F:\Share\Dir2, 5
UNC: UNC, \\Domain\Share\Dir1, 30
If you want to ignore lines starting with # you can use the following:
(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)"
}
}
Upvotes: 1