【发布时间】:2020-06-24 04:56:35
【问题描述】:
我正在使用 powershell 从 LAN 上的所有计算机中提取基本计算机信息。这些计算机不是,也永远不会在域中。我在测试运行中取得了一些成功,将所有机器的输出保存到主机上的 c:\scripts 文件夹中。但是,我必须对每个 cmdlet 使用 Invoke-command,以便可以将输出目标放在 {} 之外。
$computers = Get-Content -Path 'c:\scripts\livePCs.txt'
foreach ($computer in $computers) {
$username = '$computer\Administrator'
$password = Get-Content 'C:\scripts\encrypted_password.txt' | ConvertTo-SecureString
$credential = New-Object System.Management.Automation.PSCredential($username, $password)
# Local Mounted Shares Enumeration
Invoke-Command -Computername $computer -Credential $credential {Get-SmbMapping | Format-Table -AutoSize} | Out-File "c:\scripts\ComputerInformation\$computer.mountedshares.ps.txt"
# Local Shares Enumeration
Invoke-Command -Computername $computer -Credential $credential {Get-SmbShare | Format-Table -AutoSize} | Out-File "c:\scripts\ComputerInformation\$computer.localshares.ps.txt"
我宁愿不必这样做,当我必须使用 If/Else 语句时它会出现问题,因为我不能将目标放在大括号之外,所以我得到一个文件找不到错误(因为它是试图保存在远程主机上)。我尝试在下面使用共享,但现在访问文件路径被拒绝错误。
Invoke-Command -Computername $computer -Credential $credential {
$computername = hostname.exe
If ($PSVersionTable.PSVersion -ge '4.0') {
If (([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
Get-WindowsOptionalFeature -Online -FeatureName *Hyper-V* | Format-Table -AutoSize | Out-File -Width 1024 "\\$env:computername\scripts\ComputerInformation\$computername.hyperv.admin.ps.txt"
if (Get-Command Get-VM -ErrorAction SilentlyContinue) {
Get-VM | Format-Table -AutoSize | Out-File -Width 1024 -Append "c:\scripts\ComputerInformation\$computername.hyperv.admin.ps.txt"
Get-VM | Get-VMNetworkAdapter | Format-Table -AutoSize | Out-File -Width 1024 -Append "c:\scripts\ComputerInformation\$computername.hyperv.admin.ps.txt"
} else {
Write-Host -ForegroundColor Yellow " Hyper-V feature not installed on this host"
}
} else {
Write-Host -ForegroundColor Red " You do not have required permissions to complete this task ..."
}
} else {
Write-Host -ForegroundColor Red " This commands requires at least PowerShell 4.0 ... manual inspection is required"
}
如何使用 Invoke-Command 在远程机器上运行此命令,但将输出保存到本地 c:\scripts 文件夹?
【问题讨论】: