Posts Tagged ‘powershell’

You will need to update the CompanyName to yours

#Change AutoSaveLocation to OneDrive



$onedrivelocation = %userprofile%\OneDrive - **CompanyName**\



mkdir "$onedrivelocation\Autorecover\Word\"

New-ItemProperty -path "HKCU:\Software\Microsoft\Office\16.0\Word\Options" -Name AUTOSAVE-PATH -PropertyType "ExpandString" -Value "$onedrivelocation\Autorecover\Word\"

mkdir "$onedrivelocation\Autorecover\Excel\"

New-ItemProperty -path "HKCU:\Software\Microsoft\Office\16.0\excel\Options" -Name AutoRecoverPath -PropertyType "ExpandString" -Value "$onedrivelocation\Autorecover\Excel\"

mkdir "$onedrivelocation\Autorecover\Powerpoint\"

New-ItemProperty -path "HKCU:\Software\Microsoft\Office\16.0\PowerPoint\Options" -Name PathToAutoRecoveryInfo -PropertyType "ExpandString" -Value "$onedrivelocation\Autorecover\Powerpoint\"
VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Powershell script to set Registry Key Permissions with Subkeys for a User ( Needs to be run as admin as its changing things in HKCU:\Software\Policies

$acl = Get-Acl HKCU:\Software\Policies\Google
$inherit = [system.security.accesscontrol.InheritanceFlags]"ContainerInherit, ObjectInherit"
$propagation = [system.security.accesscontrol.PropagationFlags]"None"
$rule = New-Object System.Security.AccessControl.RegistryAccessRule ("domain\user","FullControl",$inherit,$propagation,"Allow")
$acl.SetAccessRule($rule)
$acl |Set-Acl -Path HKCU:\Software\Policies\Google
VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Script 1

#Get Active Directory information for current user

$UserName = $env:username

$Filter = “(&(objectCategory=User)(samAccountName=$UserName))”

$Searcher = New-Object System.DirectoryServices.DirectorySearcher

$Searcher.Filter = $Filter

$ADUserPath = $Searcher.FindOne()

$ADUser = $ADUserPath.GetDirectoryEntry()

$ADDisplayName = $ADUser.name

$ADTitle = $ADUser.title

$ADOffice = $ADUser.physicalDeliveryOfficeName

$script:ADMobileNumber = $script:ADUser.mobile

$ADTelePhoneNumber = $ADUser.telephoneNumber

$ADExtension1 = $ADUser.extensionAttribute1

$ADExtension2 = $ADUser.extensionAttribute2

$ADExtension3 = $ADUser.extensionAttribute3

 

#Additional Variables

$AppData=(Get-Item env:appdata).value

$SigPath = ‘\Microsoft\Signatures’

$LocalSignaturePath = $AppData+$SigPath

$SignatureName = '%signaturename%'

$DomainName = '%domainname%'

$fulladdetails = $ADDisplayName+$ADExtension1+$ADTitle+$ADOffice+$script:ADMobileNumber+$ADTelePhoneNumber

 

#Check if signature directory exists and, if not, update it

If (Test-Path $LocalSignaturePath)

{}

Else

{New-Item $LocalSignaturePath -type directory}

 

Write-host $fulladdetails

 

#Check if  Signature has changed

If ("$fulladdetails" -eq "$SigChkDetails")

{ Exit }

Else

{  }

 

#Delete old signature files

Remove-Item "$LocalSignaturePath\$ADDisplayName.htm" -Recurse -Force

 

#Copy over signature template

$SigSource = “\\path\to\signature\source"

$filename = "\\path\to\signature\template.htm"

$filename2 = "\\path\to\logo.jpg"

 

Copy-Item $filename $LocalSignaturePath -Recurse -Force

Copy-Item $filename2 $LocalSignaturePath -Recurse -Force
 

#Modify Signature and Insert Variables

(Get-Content $LocalSignaturePath\template.htm) -replace 'FullName', $ADDisplayName | Set-Content $LocalSignaturePath\template.htm

(Get-Content $LocalSignaturePath\template.htm) -replace 'PositionTitle', $ADTitle | Set-Content $LocalSignaturePath\template.htm

(Get-Content $LocalSignaturePath\template.htm) -replace 'PhoneNumber', $ADTelePhoneNumber | Set-Content $LocalSignaturePath\template.htm

 

If(!$script:ADMobileNumber -or !$ADExtension2){

(Get-Content $LocalSignaturePath\template.htm) -replace '<b>M</b> MobileNumber', $NULL | Set-Content $LocalSignaturePath\template.htm}

ELSE

{(Get-Content $LocalSignaturePath\template.htm) -replace 'MobileNumber', $script:ADMobileNumber | Set-Content $LocalSignaturePath\template.htm}

 

If(!$ADExtension1){

(Get-Content $LocalSignaturePath\template.htm) -replace ', Qualification', $NULL | Set-Content $LocalSignaturePath\template.htm}

ELSE

{(Get-Content $LocalSignaturePath\template.htm) -replace 'Qualification', $ADExtension1 | Set-Content $LocalSignaturePath\template.htm}

 

If($ADOffice -ne 'Singapore'){

If(!$ADExtension3){

(Get-Content $LocalSignaturePath\template.htm) -replace 'ImageRow', '<img src="./logo.jpg" width="259" height="74" border="0" />' | Set-Content $LocalSignaturePath\template.htm}

}ELSE

{(Get-Content $LocalSignaturePath\template.htm) -replace 'ImageRow', $null | Set-Content $LocalSignaturePath\template.htm}



 

Rename-Item -Path $LocalSignaturePath\template.htm -NewName "$ADDisplayName.htm"

 

#Set company signature as default for New messages

[Void] [Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Interop.Word")

$MSWord = New-Object -com word.application

$EmailOptions = $MSWord.EmailOptions

$EmailSignature = $EmailOptions.EmailSignature

$EmailSignatureEntries = $EmailSignature.EmailSignatureEntries

$EmailSignature.NewMessageSignature=$ADDisplayName

$MSWord.Quit()

 

#Set company signature as default for Reply messages

[Void] [Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Interop.Word")

$MSWord = New-Object -com word.application

$EmailOptions = $MSWord.EmailOptions

$EmailSignature = $EmailOptions.EmailSignature

$EmailSignatureEntries = $EmailSignature.EmailSignatureEntries

$EmailSignature.ReplyMessageSignature=$ADDisplayName

$MSWord.Quit() 

 

Script 2

https://pastebin.com/NLJauHgN

 

Script 3

https://github.com/raymix/PowerShell-Outlook-Signatures

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)


Add-PrinterDriver -Name "HP LaserJet 500 color MFP M570 PCL6 Class Driver"

add-printerport -name "HP500" -printerhostaddress "10.0.100.21"

add-printer -name "HP" -drivername "HP LaserJet 500 color MFP M570 PCL6 Class Driver" -port "HP500"

Set-PrintConfiguration -PrinterName "AAL-MEL-PR-01(HP)" -PaperSize A4 -Color $false -DuplexingMode TwoSidedLongEdge

 

Add-PrinterDriver -Name "Lexmark CX920 Series Class Driver"

add-printerport -name "Lexmark" -printerhostaddress "10.0.100.22"

add-printer -name "Lexmark" -drivername "Lexmark CX920 Series Class Driver" -port "Lexmark"

Set-PrintConfiguration -PrinterName "AAL-MEL-PR-02(Lexmark)" -PaperSize A4 -Color $false -DuplexingMode TwoSidedLongEdge
VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Following on from this great article

The Powershell Script History and logs are stored in the following registry location

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\IntuneManagementExtension\Policies

You will need to navigate to a subtree in their GUID

How do I get the GUID for my Intune Script?

Diagnosing Failures

A result was coming Failed with the below

��$ : The term '��$' is not recognized as the name of a cmdlet, function, script file, or operable program. 
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At C:\Program Files (x86)\Microsoft Intune Management
Extension\Policies\Scripts\ee7f18e5-b666-4c11-be72-9d5490a49e23_a39275a0-659c-45a9-9f1a-d312ae484eda.ps1:1 char:1
+ ��$

On running the scripts get copied here briefly then run and deleted : C:\Program Files (x86)\Microsoft Intune Management Extension\Policies\Scripts

You have to be fast but you can copy the .ps1 file to e.g. C:\Temp and check what the machine was getting , to resolve this issue I had to recopy the file into Powershell ISE and resave and upload.

 

How to Run the Scripts Manually

Change DownloadCountand ErrorCode to 0 and set Result and ResultDetails to nothing (empty string). After this we just restart the Microsoft Intune Management Extension Service (IntuneManagementExtension) and the script will rerun again on this device

 

Log Directory

C:\ProgramData\Microsoft\IntuneManagementExtension\Logs

 
VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

In monitoring we recently saw a Scheduled Task for a Shadow Copy Job failing with 0x2.

After running the Action manually in CMD I go the below error

C:\Windows\system32>C:\Windows\system32\vssadmin.exe Create Shadow /AutoRetry=15 /For=\\?\Volume{411116ac-84e511-11116-80d4-11111111111}\


vssadmin 1.1 – Volume Shadow Copy Service administrative command-line tool
(C) Copyright 2001-2013 Microsoft Corp.

Error: Either the specified volume was not found or it is not a local volume.

Running this in powershell listed all the Volumes with their current GID

GWMI -namespace root\cimv2 -class win32_volume | FL -property Label,DriveLetter,DeviceID,SystemVolume,Capacity,Freespace

Turns out the job was for a GUID that didn’t exist anymore on that system. After checking the other ShadowCopyVolume Tasks to make sure all the Disks were accounted for , I deleted the errored job

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Recently after a reboot of a server, it came up as errored in our monitoring. I couldn’t ping it however when I logged into it, I could ping out ( Firewall! ). The network Profile for the Network card had changed from Domain to Private which automatically blocks ICMP and RDP.

The server might have started faster than the Domain Controller due to Windows Updates.

You can change the Profile Category of a Network Adapter per below 

Set-NetConnectionProfile -NetworkCategory DomainAuthenticated

However

Set-NetConnectionProfile : Unable to set NetworkCategory to 'DomainAuthenticated'. This NetworkCategory type will be set automatically when authenticated to a domain network.

Restarting the Network Location Awareness service fixed this and change this backt to Domain

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

All organizations should be using service accounts for Specific Tasks and Services, however, some legacy systems might not be. This script will search all servers listed in servers.txt and come back with any results with the username you search

#run this script as administrator
#create a servers.txt for all the servers you want to query
$Servers = Get-Content servers.txt
#add * infront and behind username for wildcard
$user = "*administrator*"

$findings = foreach ($computername in $Servers){

    $schtask = schtasks.exe /query /s $computername /V /FO CSV | ConvertFrom-Csv | Where { $_."Run As User" -like $user} | Select TaskName
    if ($schtask) {Write-Host "`nTask" + $computername + $schtask }
   
    $displayname = Get-WmiObject -class win32_service -computername $computername |where-object startname -like $user | Select displayname
    if ($displayname){Write-Host "`nService" + $computername + $displayname }
   
}
VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)
<#
.SYNOPSIS
Install Desktop Experience for servers for disk cleanup.
#>


# V2 admin check
If (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
    Write-Warning "Please run this script as an Administrator!"
    Exit 1
}

[version]$OSVersion = [Environment]::OSVersion.Version

#check OS version
If ($OSVersion -gt "6.2") {
#server 2012 and above
   Install-WindowsFeature -Name Desktop-Experience
} ElseIf ($OSVersion -gt "6.1") {
#server 2008r2 and above
    Add-WindowsFeature -Name Desktop-Experience
} ElseIf ($OSVersion -gt "6.0") {
#server 2008 and above
    servermanagercmd.exe -install Desktop-Experience
} Else {
    write-host 'What OS Is this?'
}
VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

List the permissions on all the folders

$OutFile = "C:\temp\Permissions.csv"
Remove-Item $OutFile -ErrorAction SilentlyContinue
$Header = "Folder Path,Exception,IdentityReference,AccessControlType,IsInherited,InheritanceFlags,PropagationFlags"
Add-Content -Value $Header -Path $OutFile 

$RootPath = "D:\Shares\Users$"

try
{
#to add subfolders add - Recurse after $RootPath
    $Folders = dir $RootPath 2>&1 | where {$_.psiscontainer -eq $true} 
}
catch [System.Exception]
{
    $_.Exception.Message
}

foreach ($Folder in $Folders){
    
    try
    { 
        $ACLs = get-acl $Folder.fullname | ForEach-Object { $_.Access  }
        $Exception = $false 
      }
    catch [System.Exception]
    {
        $Exception = $true
        $SystemMessage = $_.Exception.Message 
    }
    Finally
    {
        Foreach ($ACL in $ACLs)
        {
             if ($Exception -eq $false) {
            $OutInfo = $Folder.Fullname + "," + $Exception  + "," + $ACL.IdentityReference  + "," + $ACL.AccessControlType + "," + $ACL.IsInherited + "," + $ACL.InheritanceFlags + "," + $ACL.PropagationFlags
             }
           else {
            $OutInfo = $Folder.Fullname + "," + $Exception  + "," + $SystemMessage
           }
           Add-Content -Value $OutInfo -Path $OutFile
       }
    }
}

Change the permissions

#######################################################
# 
# I put this script together to fix the permissions on users' home folders
# that had gotten messed up when they were moved to a new fileserver
# cluster.  After many attempts that 'almost' worked, I incorporated scripts
# from fellow SpiceHeads, most notably Martin Pugh (Martin9700).  An 
# edit or two from others, (Simon Matthews helped with the Set-ACL syntax 
# and Martin Boyle contributed the Set-Strictmode line for debugging), and
# I fixed up the logging output.
# 
# There's a couple of comments in the script that I left in but really only apply
# to the limited type of environment I was dealing with (2003 functional domain 
# with no access to the ActiveDirectory module).  (I figure I can't be the only 
# with overlords stuck in the past.)
# 
# Mike Schulman (s31064) 11/19/2015
# 
#######################################################

#Set-Strictmode -Version Latest -Verbose	##### Uncomment for configuring to your situation, then comment out again when you've got it right.

$Path = "D:\Shares\Users$"

##### Permissions adds the users/groups and the permissions they should have.  The actual User should not be added here.  
##### What's on the line below is an example only.  The format is domain\user-group:Permission.  
##### Separate additional users/groups with a comma and enclose the list in "".

$Permissions = "%yourdomainname%\Domain Admins:FullControl"

# Setup Access Rules
# $Domain = (Get-ADDomain).NetBIOSName	##### Need to set statically on next line because of 2003 limitations.
$Domain = 'ENCOM'
$AccessRules = @()
ForEach ($Perm in $Permissions.Split(","))
{	$Group = $Perm.Split(":")[0]
	$Level = $Perm.Split(":")[1]
	$AccessRules += New-Object System.Security.AccessControl.FileSystemAccessRule($Group,$Level, "ContainerInherit, ObjectInherit", 

"None", "Allow")
}

##### Setup Logging
##### Pasting this script as text into a PS command line causes the line below to throw an error and place the log file in the C:\ folder.  The script still works.

$Log = "$(Split-Path $MyInvocation.MyCommand.Path)\Set-UserACL-$(Get-Date -format 'MMddyy-hhmm').log"
Add-Content -Value "$(Get-Date): Script begins" -Path $Log
Add-Content -Value "$(Get-Date): Processing folder: $Path" -Path $Log

##### This is where it all starts to happen.
##### You can also modify the -Path in the Get-ChildItem line to limit the number of folders affected during testing.

$Dirs = Get-ChildItem -Path "$Path\*" | Where { $_.PSisContainer }
$UserError = @()
ForEach ($Dir in $Dirs)
{	$User = Split-Path $Dir.Fullname -Leaf
	Try
	{	Add-Content -Value "-----------------------------------------------" -Path $Log
	 	Add-Content -Value "$(Get-Date): Testing $($User): $($Dir.Fullname)" -Path $Log

##### The next line should be        $Test = Get-ADUser $User -ErrorAction Stop
##### It will test for the existence of the user before looping through the script.  I had to take it out because of the limitations of my environment.

	 	$ACL = Get-Acl $Dir -ErrorAction Stop
        
        ##### Set inheritance to no
		#$ACL.SetAccessRuleProtection($true, $false)
        #Add-Content -Value "$(Get-Date): Inheritance for $User set successfully" -Path $Log
        
        ##### Set owner to user
		#$ACL.SetOwner([System.Security.Principal.NTAccount]$User)
        #Add-Content -Value "$(Get-Date): Owner $User set successfully" -Path $Log
        
        ##### Remove old permissions
		$ACL.Access | ForEach { [Void]$ACL.RemoveAccessRule($_) }
        Add-Content -Value "$(Get-Date): Old permissions for $User removed successfully" -Path $Log
        
        ##### Set new permissions
		ForEach ($Rule in $AccessRules)
		{	$ACL.AddAccessRule($Rule)
		}
		$UserRule = New-Object System.Security.AccessControl.FileSystemAccessRule("$Domain\$User","Modify", "ContainerInherit, 

ObjectInherit", "None", "Allow")
		$ACL.AddAccessRule($UserRule)
		Set-Acl -Path $Dir -AclObject $ACL -ErrorAction Stop
        Add-Content -Value "$(Get-Date): New permissions for $User set successfully" -Path $Log
	}
	Catch

##### This is where the errors get logged.  The first line logs them to the console, and the next two lines add them to the log file.

	{	Write-Host "Unable to process $($Dir.Fullname) because $($Error[0])" -ForegroundColor Red
		Add-Content -Value "-----------------------------------------------" -Path $Log
        		Add-Content -Value "$(Get-Date): Unable to process $($Dir.Fullname) because $($Error[0])" -Path $Log
	}
}

##### This just closes the log file.

Add-Content -Value "-----------------------------------------------" -Path $Log
Add-Content -Value "$(Get-Date): Script completed" -Path $Log
VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)