如何从CSV文件中读取行,并在PowerShell中添加行



我正试图从CSV文件中读取一个文件路径名,但随后我需要在该文件路径中添加"。V2";,删除文件,然后再次使用";。V6";添加和删除文件。

基本上,删除配置文件路径,每个用户都有\adpath\user.name.V2 and\adpath/user.name.v6

CSV文件包含\adpath\user.name目前,我有:

$

Users = Import-Csv -Path 'C:TempLeavers.csv'
$samAccountName = $Users.SamAccountName
$string1 = $Users.ProfilePath
$V2=".V2"
$V6=".V6"
foreach( $User in $Users ){
$profilepathv2 = $String1+$V2
if (Test-Path $profilepathv2){
Write-Host -ForegroundColor Yellow "$profilepathv2 Path Found"
Remove-Item ($profilepathv2)-Force -Confirm:$false
Write-Host -ForegroundColor Green "$profilepathv2 - has been deleted"
}
Else{
Write-Host -ForegroundColor Red ".V2 Path Not found - Skipped"
}
$profilepathV6 = $string1+$V6
if (Test-Path $profilepathv6){
Write-Host -ForegroundColor Yellow "$profilepathv6 Path Found"
Remove-Item ($profilepathv6)-Force -Confirm:$false
Write-Host -ForegroundColor Green "$profilepathv6 - has been deleted"
}
Else{
Write-Host -ForegroundColor Red ".V6 Path Not found - Skipped"
}
}
Write-Host -BackgroundColor Green -ForegroundColor Black "Profiles deleted"

然而,它所做的似乎只是在读入的姓氏后面加上一个空格,然后加上.V2或.V6——这意味着什么都不会被删除。这是输出:

\ad.domain.co.ukdfsPath1PupilProfilesJoe.Bloggs
\ad.domain.co.ukdfsPath1PupilProfilesJane.Doe
\ad.domain.co.ukdfsPath1PupilProfilesJohn.Doe .V6 has been deleted

如何在CSV中循环,在没有空格的情况下附加.V2和.V6,并删除配置文件文件夹?我错过了什么!

您必须在循环中构建目标路径。。。像这样:

Users = Import-Csv -Path 'C:TempLeavers.csv'
$V2 = '.V2'
$V6 = '.V6'
foreach ( $User in $Users ) {
$profilepathv2 = $User.ProfilePath + $V2
if (Test-Path $profilepathv2) {
Write-Host -ForegroundColor Yellow "$profilepathv2 Path Found"
Remove-Item $profilepathv2 -Force -Recurse
Write-Host -ForegroundColor Green "$profilepathv2 - has been deleted"
}
Else {
Write-Host -ForegroundColor Red ".V2 Path Not found - Skipped"
}
$profilepathV6 = $User.ProfilePath + $V6
if (Test-Path $profilepathv6) {
Write-Host -ForegroundColor Yellow "$profilepathv6 Path Found"
Remove-Item $profilepathv6 -Force -Recurse
Write-Host -ForegroundColor Green "$profilepathv6 - has been deleted"
}
Else {
Write-Host -ForegroundColor Red ".V6 Path Not found - Skipped"
}
}
Write-Host -BackgroundColor Green -ForegroundColor Black "Profiles deleted"

您获得的空间可能来自您的CSV文件。你应该检查一下。如果是这种情况,您可以向变量添加.trim()方法,以消除额外的不需要的空间字符。

相关内容

最新更新