我有一组Credential
个对象,我想测试这些凭据是否有权将文件写入文件共享。
我打算做
之类的事情$myPath = "\\path\to\my\share\test.txt"
foreach ($cred in $credentialList)
{
"Testing" | Out-File -FilePath $myPath -Credential $cred
}
但后来我发现Out-File
没有将Credential
作为参数。解决这个问题的最佳方法是什么?
答案 0 :(得分:7)
您可以使用New-PSDrive:
$myPath = "\\path\to\my\share"
foreach ($cred in $credentialList)
{
New-PSDrive Test -PSProvider FileSystem -Root $myPath -Credential $Cred
"Testing" | Out-File -FilePath Test:\test.txt
Remove-PSDrive Test
}
答案 1 :(得分:5)
这是asituation,其中旧的exe(net.exe)似乎比powershell更好... 我想您可以尝试使用提供的凭据映射网络驱动器,然后测试将文件写入该驱动器:
$cred=get-credential
$pass=$cred.GetNetworkCredential().Password
net use q: \\servername\share $pass /user:$cred.username
答案 2 :(得分:4)
使用从微软TechNet脚本中心获取的脚本:http://gallery.technet.microsoft.com/scriptcenter/Lists-all-the-shared-5ebb395a
更改以满足您的需求然后从头开始完全开始要容易得多。
打开ListSharedFolderPermissions.ps1,找到三个$Properties
变量。在每个顶部添加一行,以便您可以告诉您正在查看哪个用户,所以它现在应该如下所示:
$Properties = @{'Username' = $Credential.UserName
'ComputerName' = $ComputerName
. . . . . }
接下来,将新的Username属性添加到select-object行(3次):
$Objs|Select-Object Username,ComputerName,ConnectionStatus,SharedFolderName,SecurityPrincipal, `
FileSystemRights,AccessControlType
一旦你在六个适当的位置添加了这些小块,你的脚本就可以使用了:
cd c:\Path\where\you\put\ps1\file
$permissions = @()
$myPath = "computername"
foreach ($cred in $credentialList)
{
$permissions += .\ListAllSharedFolderPermission.ps1 -ComputerName $myPath -Credential $cred
$permissions += " "
}
$permissions | Export-Csv -Path "C:\Permission.csv" -NoTypeInformation
答案 3 :(得分:3)
尝试使用Invoke-Command
功能。它将采用凭证对象并允许您在该命令下运行任意脚本块。你可以用它来测试写文件
Invoke-Command -ScriptBlock { "Testing" | Out-File $myPath } -Credential $cred
答案 4 :(得分:3)
我认为Invoke-command
方法应该有效。但如果没有任何作用,你可以试试powershell impersonation module。它成功地模拟了用户没有-Credential
开关的大多数Powershell命令。
答案 5 :(得分:3)
一些想法:
net use d:...
作为@Kayasax建议我自己对PowerShell提供程序非常感兴趣,但我决定快速创建一些东西,所以我使用了WScript.Network库。我使用哈希表来跟踪用户是否“已经过身份验证”。
$credentials = @() # List of System.Net.NetworkCredential objects
$authLog = @{}
$mappedDrive = 'z:'
$tmpFile = $mappedDrive, '\', [guid]::NewGuid(), '.tmp' -join ''
$path = [io.path]::GetPathRoot('\\server\share\path')
$net = new-object -comObject WScript.Network
foreach ($c in $credentials) {
if ($authLog.ContainsKey($c.UserName)) {
# Skipping because we've already tested this user.
continue
}
try {
if (Test-Path $mappedDrive) {
$net.RemoveNetworkDrive($mappedDrive, 1) # 1 to force
}
# Attempt to map drive and write to it
$net.MapNetworkDrive($mappedDrive, $path, $false, $c.UserName, $c.Password)
out-file $tmpFile -inputObject 'test' -force
# Cleanup
Remove-Item $tmpFile -force
$net.RemoveNetworkDrive($mappedDrive, 1)
# Authenticated.
# We shouldn't have reached this if we failed to mount or write
$authLog.Add($c.UserName, 'Authorized')
}
catch [Exception] {
# Unathenticated
$authLog.Add($c.UserName, 'Unauthorized')
}
}
$authLog
# Output
Name Value
---- -----
desktop01\user01 Authorized
desktop01\user02 Unauthorized