我正在尝试使用powershell远程访问计算机并获取文件夹的每个子目录的大小。
我正在使用该脚本来获取每个文件夹大小,并且它可以成功运行:
$log = "F:\logfile.txt"
$startFolder = "C:\"
$colItems = Get-ChildItem $startFolder | Where-Object {$_.PSIsContainer -eq $True} | Sort-Object
foreach ($i in $colItems){
$itemSum = Get-ChildItem ("$startFolder\" + $i.Name) -recurse | Measure-Object -property length -sum
"$startFolder\$i -- " + "{0:N2}" -f ($itemSum.sum / 1MB) + " MB" >> $log
}
这是我尝试使用Invoke-Command合并它并且它没有产生结果的方式。
#login info
$username = "domain\user"
$password = 'password'
$log = "C:\logfile.txt"
$startFolder = "comp-name\e"
#setup login credentials
$secstr = New-Object -TypeName System.Security.SecureString
$password.ToCharArray() | ForEach-Object {$secstr.AppendChar($_)}
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $secstr
$session = new-pssession "comp-name" -Credential $cred
Invoke-Command -Session $session -ScriptBlock {$colItems = Get-ChildItem $startFolder | Where-Object {$_.PSIsContainer -eq $True} | Sort-Object
foreach ($i in $colItems){
$itemSum = Get-ChildItem ("$startFolder\" + $i.Name) -recurse | Measure-Object -property length -sum
"$startFolder\$i -- " + "{0:N2}" -f ($itemSum.sum / 1GB) + " GB" >> $log
}
}
我已经完成了在两台计算机上启用ps-remoting的步骤。
提前感谢您的帮助!
答案 0 :(得分:0)
变量$startFolder
需要传递到脚本块,例如:
Invoke-Command -Session $session -ScriptBlock {param($path,$log)
$colItems = Get-ChildItem $path | Where-Object {$_.PSIsContainer} | Sort-Object
foreach ($i in $colItems) {
$itemSum = Get-ChildItem "$path\$($i.Name)" -recurse | Measure-Object -property length -sum
"$startFolder\$i -- " + "{0:N2}" -f ($itemSum.sum / 1GB) + " GB" >> $log
}
} -Arg $startFolder,$logFilePath
我能够正常工作(没有重定向到日志文件):
23# Invoke-Command acme -ScriptBlock {param($path)
>>> $colItems = Get-ChildItem $path | Where-Object {$_.PSIsContainer} | Sort-Object
>>> foreach ($i in $colItems) {
>>> $itemSum = Get-ChildItem $i.FullName -recurse | Measure-Object -property length -sum
>>> "$startFolder\$i -- " + "{0:N2}" -f ($itemSum.sum / 1MB) + " MB"
>>> }
>>> } -Arg c:\bin
>>>
\Orca -- 3.63 MB
\Reg -- 0.06 MB
\Src -- 0.25 MB
\sym -- 19.09 MB
\x64 -- 0.71 MB