728x90

Get-DriveSpace.ps1

List the percentage of free disk space for multiple computers.

# Display the drive space on all drives
# if any have < 20% free space, log to a file for review

function DriveSpace {
param( [string] $strComputer) 
"$strComputer ---- Free Space (percentage) ----"

# Does the server responds to a ping (otherwise the WMI queries will fail)

$query = "select * from win32_pingstatus where address = '$strComputer'"
$result = Get-WmiObject -query $query
if ($result.protocoladdress) {

    # Get the Disks for this computer
    $colDisks = get-wmiobject Win32_LogicalDisk -computername $strComputer -Filter "DriveType = 3"

    # For each disk calculate the free space
    foreach ($disk in $colDisks) {
       if ($disk.size -gt 0) {$PercentFree = [Math]::round((($disk.freespace/$disk.size) * 100))}
       else {$PercentFree = 0}

  $Drive = $disk.DeviceID
       "$strComputer - $Drive - $PercentFree"

       # if  < 20% free space, log to a file
       if ($PercentFree -le 20) {"$strComputer - $Drive - $PercentFree" | out-file -append -filepath "C:\logs\Drive Space.txt"}
    }
}
}

foreach ($computer in cat C:\batch\servers.txt) {DriveSpace "$computer"}

This assumes you have saved a list of computernames to check in the file 'servers.txt'

Example

Assuming the script above is saved in the current directory as Get-DriveSpace.ps1:

PS C:\> ./Get-DriveSpace

728x90
728x90

#requires -version 3.0

 

#remote computers must be running PowerShell 3.0

 

$computers = "dc01","ex16","c1","ex10"    -- 서버명

$cred = Get-Credential "mani4u\administrator"   -- 관리자암호

$eventlog = "Application"     -- 추출 할 이벤트로그명

 

invoke-command -ScriptBlock {

  $log = get-wmiobject win32_nteventlogfile -filter "logfilename = '$using:eventlog'"

  $file = "{0}_{1}_{2}.evtx" -f (get-date -f "yyyyMMdd"),$log.CSName,$log.FileName.Replace(" ","")

 

  #map a PSDrive with credentials

  New-PSDrive -name B -PSProvider Filesystem -Root \\ex10\it -Credential $using:cred | Out-Null  --지정서버명\공유폴더명

 

  #backup path must be something Windows can see like a UNC

  $backup = join-path (get-psdrive B).root $file

  write-host "Backing up to $backup" -ForegroundColor cyan

  $r = $log | Invoke-WmiMethod -Name BackupEventlog -ArgumentList $backup

  if ($r.returnValue -eq 0) {

    Get-Item $backup

  }

  else {

   Throw "Backup failed with returnvalue $($r.returnvalue)"

  }

 

 } -ComputerName $computers

728x90
728x90

아래를 잘 할용해서 Mail까지 보낼수 있을 듯하다.

코드

 $freespace = Get-WmiObject -Class Win32_logicalDisk | ? {$_.DriveType -eq '3'}

$drive = ($FreeSpace.DeviceID).Split("=")
#"Your $drive Free Space Percentage is {0:P2}" -f ($freespace.FreeSpace / $freespace.Size)
 
[String]::Format("Your $Drive Free Space Percentage is {0:P2}" -f ($freespace.FreeSpace / $freespace.Size))




728x90
728x90

CSV 파일을 이용한 Foreach Query가 필요해서 한번 해봤습니다.


우선 CSV에 필요한 Filed에 값을 넣어 저장합니다.

예) a.csv


filed1

AppHostSvc

wudfsvc


아래와 같이 파워쉘을 실행하여 csv에 있는 값들만 쿠리 합니다. 아래와 같이 들어 가 있는 것을 확인했습니다.

PS C:\Users\Administrator> $testcsv = Import-Csv d:\a.csv

PS C:\Users\Administrator> foreach($test in $testcsv)

>> {

>> $filed = $test.filed1

>> tasklist /svc | findstr $filed

>> }

>>

svchost.exe                   1492 AppHostSvc

                                   TrkWks, UmRdpService, WlanSvc, wudfsvc 


끝.

728x90
728x90

매번 까먹어서 적어놓네요.

New-ItemProperty “HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip6\Parameters\” -Name “DisabledComponents” -Value 0xffffffff -PropertyType “DWord"



혹은


네트워크 속성에서 ipV6 체크를 빼도 Win2008은 ipV6를 사용합니다.

reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\TCPIP6\Parameters" /v DisabledComponents /t REG_dword /d 4294967295 /f
reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters" /v EnableTCPA /t REG_dword /d 0 /f
netsh int tcp set global chimney=disabled
netsh int tcp set global rss=disabled

netsh int tcp set global netdma=disabled


를 해주시고 네트워크 속성에서 체크를 빼주셔야

정확히 ipV4만 사용하게 됩니다.

몇시간 걸리고 시행착오 거쳐서 만든 스크립트입니다.


반대는

reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\TCPIP6\Parameters" /v DisabledComponents /t REG_dword /d 0 /f
reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters" /v EnableTCPA /t REG_dword /d 1 /f
netsh int tcp set global chimney=enabled
netsh int tcp set global rss=enabled

netsh int tcp set global netdma=enabled

 





참조 - http://support.microsoft.com/kb/929852

728x90
728x90

결과 카운터 수를 하기 위해서 파워쉘로 나름 찾아보았습니다.

 

변수 $total 선언하고 이변수에 조회값을 담습니다.

그후 count를 사용하여 $total 값을 구하면 됩니다.

 

예)

PS C:\Windows\system32> $total = Get-CsUser -Filter {RegistrarPool -eq 'pool.fedev.com'}

PS C:\Windows\system32> $total.count
408

 

결과 값은 408이 떨어지는군요.

728x90
728x90

사용자 만료일자를 추출하는 쿼리입니다.

실제 운영에서 유용하게 사용 할 수 있을 듯 합니다.

 

function Get-XADUserPasswordExpirationDate() {

    Param ([Parameter(Mandatory=$true,  Position=0,  ValueFromPipeline=$true, HelpMessage="Identity of the Account")]

    [Object] $accountIdentity)

    PROCESS {

        $accountObj = Get-ADUser $accountIdentity -properties PasswordExpired, PasswordNeverExpires, PasswordLastSet

        if ($accountObj.PasswordExpired) {

            echo ("Password of account: " + $accountObj.Name + " already expired!")

        } else {

            if ($accountObj.PasswordNeverExpires) {

                echo ("Password of account: " + $accountObj.Name + " is set to never expires!")

            } else {

                $passwordSetDate = $accountObj.PasswordLastSet

                if ($passwordSetDate -eq $null) {

                    echo ("Password of account: " + $accountObj.Name + " has never been set!")

                }  else {

                    $maxPasswordAgeTimeSpan = $null

                    $dfl = (get-addomain).DomainMode

                    if ($dfl -ge 3) {

                        ## Greater than Windows2008 domain functional level

                        $accountFGPP = Get-ADUserResultantPasswordPolicy $accountObj

                        if ($accountFGPP -ne $null) {

                            $maxPasswordAgeTimeSpan = $accountFGPP.MaxPasswordAge

                        } else {

                            $maxPasswordAgeTimeSpan = (Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge

                        }

                    } else {

                        $maxPasswordAgeTimeSpan = (Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge

                    }

                    if ($maxPasswordAgeTimeSpan -eq $null -or $maxPasswordAgeTimeSpan.TotalMilliseconds -eq 0) {

                        echo ("MaxPasswordAge is not set for the domain or is set to zero!")

                    } else {

                        echo ("Password of account: " + $accountObj.Name + " expires on: " + ($passwordSetDate + $maxPasswordAgeTimeSpan))

                    }

                }

            }

        }

    }

}
 

 

사용방법

 

Import-module activedirectory
 
get-aduser -filter {Enabled -eq $True} -properties * | Get-XADUserPasswordExpirationDate 

 

 

출처 : http://blog.sogooday.com/239

728x90
728x90

간혹 배치파일은 만들다 보면 계정의 비밀번호를 넣는 경우가 있다.

하지만 보안적인 문제가 발생 되기에 암호화를 해서 넣을 수가 있다.

Search하니 역시나 원하는 답이 있었다. ㅋㅋㅋ

 

1. 파워쉘을 실행한다.

"password" | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString

The output is luckily not the unencrypted password we entered, it is a string containing the encrypted version of the password.

 

결과

01000000d08c9ddf0115d1118c7a00c04fc297eb01000000b9fe0ca15a2ffb4a9e172d76a87afae40000000002000000000003660000c000000010000000875
eab73cc326c4acb70b609f170da6d0000000004800000a0000000100000001efe13d29355bea97995960f306c0009180000005a906fee5e408ccf685bbc56dd
1c3e3c91472d168c17d38a140000008bf9a9f060d1c46d1d96441d2080218ff0ada1a6

 

 

출처

<http://blog.coretech.dk/rja/store-encrypted-password-in-a-powershell-script/>

 

728x90

+ Recent posts