Showing posts with label PowerShell. Show all posts
Showing posts with label PowerShell. Show all posts

Tuesday, October 12, 2021

Get Disk Space Info Remotely

One of the quick and easy ways to get a remote computer/server's disk space info is to use the PowerShell command GET-PSDrive. 

You can create a batch file that runs the GET-PSDrive command remotely using PSTools' PSExec. 


@echo off

psexec \\{ip_address} cmd /c powershell.exe "Get-PSDrive"

pause


Assign local admin rights remotely

To view the local admin users of  the PC you are currently using: 

net localgroup administrators



After downloading and saving PSTools to a folder, which include psexec.exe, and making it available globally through System Variables -> Path, you can run the "net locagroup" command on remote PCs, given that you already have local admin rights to those PCs.

To view the local admin users of another PC remotely, try

psexec  \\<ip_address>  net  localgroup administrators




To add a user to the local admin group remotely: 

psexec \\<ip_address>  net localgroup administratos "<domain_name>\<username>" /add




To remove a user from the local admin group remotely:

psexec \\<ip_address>  net localgroup administratos "<domain_name>\<username>" /delete


Tuesday, August 21, 2018

Send email notification when free disk space is low

Powershell script that detects local disk drives with less free space than specified value and sends email notifications (I can't recall where I got the following script. It was probably written by a SQL Server admin).

# Get SMTP server info
$smtp=new-object Net.Mail.SmtpClient("myEmailServer.myDomain.com")

# Set thresholds in GB for C: drive and other drives
$driveCthreshold=10
$threshold=10

# Replace settings below with your e-mails
$emailFrom="serverToMinitor@myDomain.com"
$emailTo="myName@myDomain.com"

# -----------------------------------------------------------------------------

# Get server name
$hostname=Get-WMIObject Win32_ComputerSystem | Select-Object -ExpandProperty name

# Get all drives with free space less than a threshold, while excluding System Volumes
$Results = Get-WmiObject -Class Win32_Volume -Filter "SystemVolume='False' AND DriveType=3" | Where-Object {($_.FreeSpace/1GB –lt  $driveCthreshold –and $_.DriveLetter -eq "C:") –or ($_.FreeSpace/1GB –lt  $threshold –and $_.DriveLetter -ne "C:" )}

If ( ($Results | measure).Count -gt 0 ) 
{
    ForEach ($Result In $Results)
    {
        $drive = $Result.DriveLetter
        $space = $Result.FreeSpace
        $thresh = if($drive -eq 'C:'){$driveCthreshold} else {$threshold}

        # Send e-mail if the free space is less than threshold parameter 
        $smtp.Send(
           $emailFrom, 
           $emailTo, 
           # E-mail subject
           "Disk $drive on $hostname has less than $thresh GB of free space left ",
           # E-mail body 
           ("{0:N0}" -f [math]::truncate($space/1MB))+" MB"
        )
    }
}

Monday, May 23, 2016

Copy SharePoint List Items To Another Identical List

The following Powershell script could be useful while importing data into existing list. If such need arises, one can import data from spreadsheet into a new list and then copy its list items to the destination list.

Keep in mind though: ReadOnly fields, such as [CreatedDateTime] or [LastUpdatedDateTime] field, cannot be manipulated through the script below.
try
{
    $web = Get-SPWeb "http://site"

    $sList = $web.Lists["Movies2"]  #source-list
    $dList = $web.Lists["Movies"]   #destination-list

    Write-Host "Working on Web: "$web.Title -ForegroundColor Green

    if($sList)
    {
        Write-Host "    Working on List: " sList.Name -ForegroundColor Cyan

        $spSourceItems = $sList.Items
        $sourceSPFieldCollection = $sList.Fields

        
        foreach($item in $spSourceItems)
        {
            if($dList)
            {
                $newSPListItem = $dList.AddItem()

                #Copy all field data except Attachments
                foreach($spField in $sourceSPFieldCollection)
                {
                    if($spField.ReadOnlyField -ne $True -and $spField.InternalName -ne "Attachments")                   
                    {
                        $newSPListItem[$($spField.InternalName)] = $item[$($spField.InternalName)]
                    }
                }

                #Copy Attachments
                foreach($leafName in $item.Attachments)
                {
                    $spFile = $sList.ParentWeb.GetFile($($item.Attachments.UrlPrefix + $leafName))
                    $newSPListItem.Attachments.Add($leafName, $spFile.OpenBinary())
                }

                #Update new LisItem
                $newSPListItem.Update()
            }
            Write-Host "        Copying $($item["Name"]) completed"
        }
       
    }
    
}
catch
{
    Write-Host "Error: " $_.Exception.ToString() -ForegroundColor Red
}

Friday, May 13, 2016

Turn on or off SharePoint Developer Dashboard

SharePoint developer dashboard can be turned on or off via Powershell script as follows
Make sure that "Usage and Health Data Collection" service application has started first under Manage Service Applications.
Add-PSSnapin "Microsoft.SharePoint.PowerShell"
$contentService = [Microsoft.SharePoint.Administration.SPWebService]::ContentService
$dashboard = $contentService.DeveloperDashboardSettings
$dashboard.DisplayLevel = "On"  # "Off" will turn off dashboard
$dashboard.Update()
After the dashboard is turned on, you will see a perfmon icon in the right upper corner of SharePoint site next to "SHARE", "FOLLOW", 'EDIT" menu items.

***In case the "Usage and Health Data Collection Proxy" has not started, use the following Powershell to start it.
$SAP = Get-SPServiceApplicationProxy | 
 where-object { $_.TypeName -eq "Usage and Health Data Collection Proxy" }

Friday, August 16, 2013

PowerShell - Copy files that contain square brackets in file name.

I tried to copy all mp3 files in iTunes music folder's subfolders onto another folder without subfolder structures. This was relatively straightforward task until I ran into files that contain square brackets in file names (i.e., "Tom's Diner [1990].mp3").  For example,

$folderItems = Get-ChildItem "C:\Users\John Doe\Music\iTunes\iTunes media\Music\" -Recurse
$newFolder = "C:\Users\John Doe\My Documents\MusicTemp\"
$foreach( $item in $folderItems )
{
    if( $item.Attributes -eq "Archive" )
    {
        Copy-Item $item.FullName $newFolder
    }
}

The code above kept failing due to PowerShell's de-escaping the strings multiple times internally and using special characters for pattern matching. Getting PowerShell to correctly recognize a literal square bracket in a path string turned out to be more complex than I thought.

I googled around and found a suitable workaround for this problem. Basically you would have to escape both open-square-bracket "[" and close-square-bracket "]" with backtick characters "`".

When using single-quote for string, two backticks are needed in front of a bracket in the string.
For double-quoted string, four backticks are needed in front of a bracket in the string.

The workaround PowerShell script is show below. I used double backticks to properly escape the square brackets.

$folderItems = Get-ChildItem "C:\Users\John Doe\Music\iTunes\iTunes Media\Music\" -Recurse
$newFolder = "C:\Users\Jone Doe\Music\iTunes\iTunes Media\MusicTemp\"
foreach($item in $folderItems)
{
    if( $item.Attributes -eq "Archive")
    {        
       $escapedFullName = $item.FullName.Replace('[', '``[').Replace(']', '``]')
       Copy-Item $escapedFullName $newFolder       
    }    
}

Here is the link that I got the workaround idea from.