我有一个 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
该脚本旨在首先检查是否已存在任何包含“数据”一词的快捷方式,然后隔离包含我的用户名 ( Select-String $env:username
) 的 users.log 文件中的字符串,将结果过滤到仅 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
集中运行一次。
问题似乎与这行代码有关:
在每次迭代期间,您都在使用
$FindUser
而不是$Object
. 您应该将其更改为: