我有一个 Users.log 文件,其中列出了从 AD 中提取的有关用户名、组成员身份和分配的服务器路径的以下信息:
RandomUser01,RandomGroup01_654321_098765,\\server\data\designs\RandomArea01_654321_098765\data_store
RandomUser02,RandomGroup02_654321_098765,\\server\data\designs\RandomArea02_654321_098765\data_store
RandomUser03,RandomGroup03_654321_098765,\\server\data\designs\RandomArea03_654321_098765\data_store
RandomUser04,RandomGroup04_654321_098765,\\server\data\designs\RandomArea04_654321_098765\data_store
MyUsername,MyGroup01_654321_098765,\\server\data\designs\MyArea01_654321_098765\data_store
MyUsername,MyGroup02_654321_098765,\\server\data\designs\Myrea02_654321_098765\data_store
该脚本旨在首先检查是否存在包含单词“data”的快捷方式,然后隔离 users.log 文件中包含我的用户名的字符串 ( Select-String $env:username
),将结果过滤为 UNC 服务器路径 ( $ServerPath = $Object -replace ”[^,]*,”,””
),并使用它来创建指向该服务器的唯一桌面快捷方式。它还设置为使用组名作为快捷方式名称 ( $ShortcutName = $ProjectName.Substring(0, $ProjectName.IndexOf('_'))
)
脚本:
function Set-ShortCut {
Param (
[string]$SourceLnk,
[string]$DestinationPath
)
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut($SourceLnk)
$Shortcut.TargetPath = $DestinationPath
$Shortcut.Save()
}
$WantFile = "$env:USERPROFILE\Desktop\data*.lnk"
$FileExists = Test-Path $WantFile
$FindUser = Get-Content \\Server\data\logs\Users.log | Select-String $env:username
If ($FileExists -eq $False)
{
Write-Host "Conditions have been satisfied. Running script to create data_store shortcut"
Start-Sleep -Seconds 5
foreach ($Object in $FindUser)
{
$ProjectName = $finduser -split ",", 3 | Select-Object -Index 1
$ShortcutName = $ProjectName.Substring(0, $ProjectName.IndexOf('_'))
$ServerPath = $Object -replace ”[^,]*,”,””
$SourcePath = "$ServerPath"
$ProjectName
$ShortcutName
$ServerPath
$SourcePath
Set-ShortCut -SourceLnk "$env:USERPROFILE\Desktop\$ShortcutName data_store.lnk" -DestinationPath $SourcePath
}
}
Else {
Start-Sleep -Seconds 5
Write-Host "The Script will now EXIT..."
Start-Sleep -Seconds 5
Exit
}
我希望脚本运行一次对于每个字符串在 的结果中找到$FindUser
。这就是我使用 的原因foreach ($Object in $FindUser)
。但我无法让脚本执行此操作。
在此 users.log 文件示例中,当我运行$FindUser
它时会产生两个结果:
MyUsername,MyGroup01_654321_098765,\\server\data\designs\MyArea01_654321_098765\data_store
MyUsername,MyGroup02_654321_098765,\\server\data\designs\Myrea02_654321_098765\data_store
但是,我认为我在使用 时犯了一个错误foreach
。我也试过了ForEach-Object
,但没有成功。有人有什么建议吗?我需要脚本对 中的每个字符串$FindUsers
分别运行。目前,它只对 中的所有结果$FindUsers
集体运行一次。
答案1
该问题似乎与这行代码有关:
$ProjectName = $finduser -split ",", 3 | Select-Object -Index 1
在每次迭代中,您都使用$FindUser
而不是$Object
。您应该将其更改为:
$ProjectName = $Object -split ",", 3 | Select-Object -Index 1