Powershell使用凭据

时间:2016-07-14 14:48:30

标签: arrays powershell foreach credentials

我多年来一直潜伏在这个网站上搜索代码答案,但这是我第一次真正提出问题。我实际上并没有为代码付钱,而是使用脚本来简化日常工作。

我一直在使用带有以下代码的powershell脚本(我从这个网站收集了很多内容)来收集客户端服务器上的磁盘使用情况:

$dataColl = @()#Makes an array, or a collection to hold all the object of the same fields

foreach ($serverName in (get-content c:\reporting\Disk_useage\My_servers.txt))

{

   $path = “\\$serverName\d$\folder1\TargetSubdir“

   $dirSize = Get-ChildItem $path -recurse -force | select Length  |Measure-Object -Sum length

   $dirSize.sum = $dirSize.sum/1MB

   $finalResult = “{0:N2} MB” -f $dirsize.sum

   $dataObject = New-Object PSObject

   Add-Member -inputObject $dataObject -memberType NoteProperty -name “ServerName” -value $serverName

   Add-Member -inputObject $dataObject -memberType NoteProperty -name “Dir_Size” -value $finalResult

   $dataColl += $dataObject  

   $dataObject

}

$dataColl | Export-Csv -noTypeInformation -path   c:\reporting\Disk_useage\Svr_disk.csv

这一直运行良好,但我们现在有一个带有客户端服务器的第二个域,所以我需要为第二个域中的服务器添加凭据。我一直在研究传递凭证的方法,并获得了一些代码(PW已经存储在.TXT文件中):

$username = "MyDomain\MyAccount"
$password = cat C:\reporting\securestring.txt | convertto-securestring
$cred = new-object -typename System.Management.Automation.PSCredential `
     -argumentlist $username, $password

但我应该在某处添加这些参数以实际使用已设置的凭据:

-Authentication default -Credential $Cred

我在几个不同的地方尝试过但没有成功。仅供参考,My_servers.txt中的列表包含一堆我不需要凭据的服务器(因为它们位于当前域中),还有一堆我需要凭据的服务器(因为它们&#39 ;在另一个域上)。但我用于脚本的凭据是针对两个域中具有相同ID / PW的服务帐户。任何帮助整理这个将非常感激。

1 个答案:

答案 0 :(得分:0)

Adil在代码中的建议是:

$dataColl = @()#Makes an array, or a collection to hold all the object of the same fields
$username = "MyDomain\MyAccount"
$password = Get-Content C:\reporting\securestring.txt | convertto-securestring
$cred = New-Object -typename System.Management.Automation.PSCredential `
     -argumentlist $username, $password
foreach ($serverName in (get-content c:\reporting\Disk_useage\My_servers.txt))

{
   $dirSize = Invoke-Command -Credential $cred -ComputerName $serverName -ScriptBlock {
        Get-ChildItem “d:\folder1\TargetSubdir“ -recurse -force | select Length  | Measure-Object -Sum length
   }
   $dirSize.sum = $dirSize.sum/1MB

   $finalResult = “{0:N2} MB” -f $dirsize.sum

   $dataObject = New-Object PSObject

   Add-Member -inputObject $dataObject -memberType NoteProperty -name “ServerName” -value $serverName

   Add-Member -inputObject $dataObject -memberType NoteProperty -name “Dir_Size” -value $finalResult

   $dataColl += $dataObject  

   $dataObject

}

$dataColl | Export-Csv -noTypeInformation -path   c:\reporting\Disk_useage\Svr_disk.csv