$Computers = get-content C:\temp\computers.txt
$AdminName = Read-Host "Enter your Admin AD username"
$CredsFile = "C:\pass.txt"
$FileExists = Test-Path $CredsFile
if ($FileExists -eq $false) {
Write-Host 'Credential file not found. Enter your password:' -ForegroundColor Red
Read-Host -AsSecureString | ConvertFrom-SecureString | Out-File $CredsFile
$password = get-content $CredsFile | convertto-securestring
$Cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $AdminName,$password}
else
{Write-Host 'Using your stored credential file' -ForegroundColor Green
$password = get-content $CredsFile | convertto-securestring
$Cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $AdminName,$password}
foreach ($computer in $Computers){
if(Test-Connection -ComputerName $Computer -Count 1 -ea 0)``
{
$network = Get-WmiObject win32_networkadapterconfiguration -ComputerName $Computer -Filter ipenabled="true"
$ipaddress = $Network.IpAddress[0]
$subnetmask = $Network.IPSubnet[0]
$DefaultGateway = $Network.DefaultIPGateway
$DNSServers = $Network.DNSServerSearchOrder
$MACAddress = $Network.MACAddress
$OutputObj = New-Object -Type PSObject
$OutputObj | Add-Member -MemberType NoteProperty -Name ComputerName -Value $Computer.ToUpper()
$OutputObj | Add-Member -MemberType NoteProperty -Name IPAddress -Value $IPAddress
$OutputObj | Add-Member -MemberType NoteProperty -Name SubnetMask -Value $SubnetMask
$OutputObj | Add-Member -MemberType NoteProperty -Name Gateway -Value $DefaultGateway
$OutputObj | Add-Member -MemberType NoteProperty -Name DNSServers -Value $DNSServers
$OutputObj | Add-Member -MemberType NoteProperty -Name MACAddress -Value $MACAddress
$Outputobj
$result += $Outputobj
}
}
$result | Export-Csv c:\TEMP\Computerdata.csv
使用上面的代码将密码存储在文本文件c:\ pass.txt中,而不必多次重新输入密码。
尝试此代码时,我看到以下错误:
PS C:\ temp> 。\ passcerds.ps1使用存储的凭据文件 ConvertTo-SecureString:无法处理参数因为值 参数“输入”无效。更改“input”参数的值 并再次运行该操作。在C:\ temp \ passcerds.ps1:12 char:64 + $ password = get-content $ CredsFile | convertto-securestring<<<< + CategoryInfo:InvalidArgument:(:) [ConvertTo-SecureString],PSArgumentException + FullyQualifiedErrorId:ImportSecureString_InvalidArgument,Microsoft.PowerShell.Commands.ConvertToSecureStringC mmand
New-Object:使用“2”参数调用“.ctor”的异常:“不能 process参数,因为参数“ssword”的值为null。 将参数“password”的值更改为非空值。“At C:\ temp \ passcerds.ps1:13 char:23 + $ Cred = new-object<<<< -typename System.Management.Automation.PSCredential -argumentlist domain \ $ AdminName,$ p sword} + CategoryInfo:InvalidOperation:(:) [New-Object],MethodInvocationException + FullyQualifiedErrorId:ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand
答案 0 :(得分:0)
脚本开头的单引号是正确还是拼写错误?因为那可能会让事情搞得一团糟......我能够运行下面的代码,它对我有用:
$CredsFile = "C:\pass.txt"
$FileExists = Test-Path $CredsFile
如果您是从PowerShell运行它而忘记设置$ CredsFile变量,则会出现该错误。对于前者下面会产生同样的错误:
$FileExists = Test-Path $Nothing