Quantcast
Channel: The Official Scripting Guys Forum! forum
Viewing all 15028 articles
Browse latest View live

PowerShell function to list disk volumes backed by SSD

$
0
0

So one day, I needed to list volumes on a system and I wanted to identify volumes backed by solid state drives. I trolled  various forums and blogs and I found mostly kludgy solutions or solutions based on bad assumption and it became clear I'll have to do the heavy lifting myself. Query of Win32_Volume associations seemed like the best way forward but that opened a couple of problems. CIM & WMI Win32 classes didn't seem to accurately or consistently describe the solid states and I've never worked with associations before so there's that too. 

Fortunately, Windows 2012 R2 added storage class object functionality and MSFT_Volume and MSFT_PhyiscalDisk suddenly looked like my best friends for this solution. There are so many other gems in this namespace it was hard not to get distracted by so much 'shiny'. Anyway, these class objects looked great but issue #2 slapped in the face. Then I found get-CimAssociatedInstance and with a little trolling and experimentation, I put this function together. I just needed basic information but it easy to add more properties to the output as needed.  

function List-Drives {    
    $Disks=[System.Collections.ArrayList]::new()
    $NameSpace = 'Root\Microsoft\Windows\Storage'
    $VolInfo=Get-CimInstance -query "SELECT * FROM MSFT_Volume" -Namespace $NameSpace | Where-Object{($_.driveletter -ne $null) -and ($_.driveletter -ne 0)}
    
    $VolInfo |%{
        $DiskInfo=[PSCustomObject]@{
            'Drive' = $_.driveletter
            'Label' = $_.FileSystemLabel
            'Size' = "{0:N1}" -f $($_.Size/1GB)
            'Remaining' = "{0:N1}" -f $($_.SizeRemaining/1GB)
            'Type'=(Get-CimAssociatedInstance -InputObject $(Get-CimAssociatedInstance -InputObject $_ -Association MSFT_PartitionToVolume) -Association MSFT_DiskToPartition -PipelineVariable SerialNumber | Get-PhysicalDisk).MediaType   
        }
        $Disks+=$DiskInfo
    }    
    Return $disks
}
List-Drives | ft -AutoSize


Script for Auto Run a Service policy in .bat format.

$
0
0

Hi friends,

i just help me to make a Script for Auto Run a Service policy in .bat format for win 7,8,10

Automate Internet Explorer running as different user with VBA

$
0
0

My Windows is logged-in as user1. I have to launch Internet Explorer via runas command as user2user1 executes the cmd line: runas /user:user2"C:\Program Files\Internet Explorer\iexplore.exe". Once IE(user2) is running, with VBA(user1) I am not able to find shell application of IE(user2) with this snippet.

Set objShell = CreateObject("Shell.Application")
Set objShellWindows = objShell.Windows

For Each obj In objShellWindows

next obj

Also I am not able to this with Windows(user1), IE(user2) and VBA(user2).

When the IE is launched as user1, this code works perfectly.

How to manipulate IE(user2) with VBA(user1)? Thx


Set wmi permission 'Execute methods' via powershell for remote computers

$
0
0

I need to add this code to have permission to Execute Methods(MethodExecute).

function get-sid
{Param ($DSIdentity)
$ID = new-object System.Security.Principal.NTAccount($DSIdentity)return $ID.Translate( [System.Security.Principal.SecurityIdentifier] ).toString()}
$sid = get-sid $args[0]
$SDDL = "A;CI;CCWP;;;$sid"
$DCOMSDDL = "A;;CCDCRP;;;$sid"ForEach ($COMPUTER in (Get-ADComputer -Filter '*' | Select -ExpandProperty Name)){if(!(Test-Connection -Cn $COMPUTER -Quiet)) {write-host "cannot reach $computer" -f red} 
else {    $Reg = [WMIClass]"\\$COMPUTER\root\default:StdRegProv"    
$DCOM = $Reg.GetBinaryValue(2147483650,"software\microsoft\ole","MachineLaunchRestriction").uValue    
$security = Get-WmiObject -ComputerName $COMPUTER -Namespace root -Class __SystemSecurity    
$converter = new-object system.management.ManagementClass Win32_SecurityDescriptorHelper    
$binarySD = @($null)    $result = $security.PsBase.InvokeMethod("GetSD",$binarySD)    $outsddl = $converter.BinarySDToSDDL($binarySD[0])    $outDCOMSDDL = $converter.BinarySDToSDDL($DCOM)    
$newSDDL = $outsddl.SDDL += "(" + $SDDL + ")"    $newDCOMSDDL = $outDCOMSDDL.SDDL += "(" + $DCOMSDDL + ")"   $WMIbinarySD = $converter.SDDLToBinarySD($newSDDL)    $WMIconvertedPermissions = ,$WMIbinarySD.BinarySD    $DCOMbinarySD = $converter.SDDLToBinarySD($newDCOMSDDL)    $DCOMconvertedPermissions = ,$DCOMbinarySD.BinarySD    $result = $security.PsBase.InvokeMethod("SetSD",$WMIconvertedPermissions)    
$result = $Reg.SetBinaryValue(2147483650,"software\microsoft\ole","MachineLaunchRestriction", $DCOMbinarySD.binarySD)    write-host "complete" -f green}}

Cannot index into a null array

$
0
0

Hi

I have a script which takes user inputs and sets expiry in AD for a user. I am getting an error while clicking the Select Expiry date button.

#~~< Button4 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$Button4 = New-Object System.Windows.Forms.Button
$Button4.Font = New-Object System.Drawing.Font("Tahoma", 9.75, [System.Drawing.FontStyle]::Regular, [System.Drawing.GraphicsUnit]::Point, ([System.Byte](0)))
$Button4.Location = New-Object System.Drawing.Point(480, 169)
$Button4.Size = New-Object System.Drawing.Size(144, 23)
$Button4.TabIndex = 13
$Button4.Text = "Select Expiry Date"
$Button4.UseVisualStyleBackColor = $true
$Button4.add_Click({Button4Click($Button4)})
function Button4Click( $object ){

$dateTimeString = [regex]::Matches($MonthCalendar1, '(\d\d/\d\d/\d\d\d\d.+): ')[0].Groups[1].Value
$convertedDate = $dateTimeString -replace " 00:00:00, End", " 23:59:00"
$textbox9.Text = "$convertedDate"
$textbox11.Text = "False"

I get the below errors while clicking the Select Expiry Date

Cannot index into a null array.
At D:\Scripts\SAMScripts\User-Expiry-Tool\Newuserexpiry.ps1:487 char:1+ $dateTimeString = [regex]::Matches($MonthCalendar1, '(\d\d/\d\d/\d\d\ ...+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : InvalidOperation: (:) [], RuntimeException+ FullyQualifiedErrorId : NullArray

Get-Date : Cannot bind parameter 'Date'. Cannot convert value "" to type "System.DateTime". Error: "String was not
recognized as a valid DateTime."
At D:\Scripts\SAMScripts\User-Expiry-Tool\Newuserexpiry.ps1:757 char:22+ $Newtime = (Get-Date $convertedDate).AddHours(0).ToString("HH:mm:ss")+                      ~~~~~~~~~~~~~~+ CategoryInfo          : InvalidArgument: (:) [Get-Date], ParameterBindingException+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.GetDateCommand

Get-Date : Cannot bind parameter 'Date'. Cannot convert value "" to type "System.DateTime". Error: "String was not
recognized as a valid DateTime."
At D:\Scripts\SAMScripts\User-Expiry-Tool\Newuserexpiry.ps1:759 char:22+ $newdate = (Get-Date $convertedDate).AddDays(0).ToString("dd/MM/yyyy" ...+                      ~~~~~~~~~~~~~~+ CategoryInfo          : InvalidArgument: (:) [Get-Date], ParameterBindingException+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.GetDateCommand

Get-Date : The input object cannot be bound to any parameters for the command either because the command does not take
pipeline input or the input and its properties do not match any of the parameters that take pipeline input.
At D:\Scripts\SAMScripts\User-Expiry-Tool\Newuserexpiry.ps1:760 char:19+ $DST = $newdate | Get-Date -Format "MM/dd/yyyy HH:mm:ss"+                   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : InvalidArgument: (:) [Get-Date], ParameterBindingException+ FullyQualifiedErrorId : InputObjectNotBound,Microsoft.PowerShell.Commands.GetDateCommand

What i did to troubleshoot - Try to print the $MonthCalendar1 and found no value was passed. I passed a static value (getdate) and was able to get the expiry displayed on the GUI. But still the expiry is not set for the user.

Any suggestions to further troubleshoot or fix the issue would be appreciated.


Justin

Find a program

$
0
0

Hello i am hoping some one could help me with my code. The goal of this code is to find if a program is installed echo "Installed" and start uninstalling program. If the program is not installed do nothing and move to do something else.

$sofware = "Java";
$installed = ((Set-location HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall*).DisplayName -match "Java").Length -gt 0

if(-Not $installed) {
        Write-Host "'$sofware' NOT installed.";

} else {
        Write-Host "'$sofware' is installed."
}

When i run this it displays entire code, and does not display individual answer. What am i doing wrong?

PowerShell: Exporting output in separate sheet in the same file.

$
0
0

Hello,

I was wondering if it is possible to export output in different sheet of a file.

As far as I know csv do not support it, how can this be achieved using Excel.

I tried importing Excel Module with Import-Module -name ImportExcel but it failed.

Then I tried "Install-Module -Name ImportExcel -RequiredVersion ***" but this is asking me to install the NUGET provider version first which I have no idea of. 

Request your help in getting my goal achieved.

Regards,

HR


Problem with export and display all information of mobile phone number for SSPR registered users via Powershell

$
0
0

I'm trying to export the mobile phone number of the users who has registered self service password reset in Office 365 using below command:

Get-Msoluser -All | where {$_.StrongAuthenticationUserDetails -ne $null} | export-csv D:\ExportSSPRRegisteredUsers.csv

Somehow, the report I get does NOT filter out any user in my Office 365 tenant. Thus the command does NOT work as expected.


PSRemoting

$
0
0
Hey folks....Anyone help me...I planned to configure psremoting in my office...configuration done in my system (server) and in remote system...winrm status running in both system...Windows firewall disabled in both system...I couldn't connect both the system...how to solve this?

Ip to Https Redirection

$
0
0
Hi Guys....Can anyone provide me steps for enabling Ip to Https redirection in IIS 10.

Powershell to add domain user to WMI Security Root with specific permissions.

$
0
0

Basically, trying to add a domain user to the WMI Control Security Root. (Computer management>Services and Applications:WMI Control>Properties>Security Tab>Select "ROOT" & hit Security>Add user with "Remote Enable & Read Security" Permissions. Then press Advanced>Select the user>Edit>Change the dropdown for Applies to' to be This namespace and subnamespaces.

I know it's a lot but this will have to be done on all our servers.

Microsoft ActiveDirectory PowerShell Module (Microsoft RSAT Download) Isn't Thread-Safe - Remedy?

$
0
0

The PowerShell ActiveDirectory module doesn't seem to be thread-safe.

We wrote a .NET Framework service. The code opens a PowerShell Runspace (NuGet package "System.Management.Automation.dll") that's executing a PowerShell script which queries Active Directory by means of Active Directory Web Services (ADWS).

Our service spawns a number of threads, so tasks can be processed in parallel. If two threads query Active Directory in parallel (e.g. by both running theGet-ADUser Cmdlet), Active Directory Web Services (ADWS) throws an "invalid enumeration context" SOAP exception.

Did we perhaps misconfigure our Windows domain controller? Or is this a fault that's supposed to be reported to Microsoft? Where would I report this error?

On GitHub I created a repository containing an example console application, making it easy to reproduce this issue. OnUserVoice I submitted a corresponding "idea".

VB Script Help/Questions

$
0
0

Hello, we have a vbscript that controls desktop wallpapers on our client machines.  We have a GPO that deploys this script to all clients.  I recently changed the desktop background and replaced the images that the vbscript calls on.  I used the exact same names, so nothing in the script changed.  Windows 10 machines seem to be updating without any problems, but Windows 7 machines are displaying a black background.  What I'm finding is that the script is not copying the files down to the client as designed.  If I manually delete the existing backgrounds on the client and run the script, it then copies the new files down, but it STILL doesn't apply the background.  If I go into the Control Panel display settings, I can see the background listed as an "Unsaved Theme", and it's selected but the wallpaper is still black.  When I simply click on the theme again, it then applies the background.

I have very little experience with VB and the previous engineer who wrote this is no longer here, so I'm not sure if there's something I'm missing here.  The script is below.  Any help would be appreciated.

Dim WshShell, wpFile, wpStyle, dWidth, dHeight, lngSuccess, dProd, WVersion, filesys

'-------------------------------------Registry Key Function----------------------------------------

 Function RegistryKeyExists(LNGHKEY, strKey, strSubkey)
     Const HKLM = &H80000002
     Const HKCR = &H80000000
     Const HKCU = &H80000001
     Const HKUSERS = &H80000003
     RegistryKeyExists = False
     Dim reg, aSubkeys, s, hkroot
     If LNGHKEY = "HKLM" Then hkRoot = HKLM
     If LNGHKEY = "HKCU" Then hkRoot = HKCU
     If LNGHKEY = "HKCR" Then hkRoot = HKCR
     If LNGHKEY = "HKUSERS" Then hkRoot = HKUSERS
     Set reg = GetObject("WinMgmts:{impersonationLevel=impersonate}!\\.\root\default:StdRegProv")
     reg.EnumKey hkroot, strKey, aSubkeys
     If Not IsNull(aSubkeys) Then
         For Each s In aSubkeys
             If lcase(s)=lcase(strSubkey) Then
                 RegistryKeyExists = True
                 Exit Function
             End If
         Next
     End If
 End Function   
set WshShell = CreateObject("Wscript.Shell")
set filesys=CreateObject("Scripting.FileSystemObject")

wpStyle = 2

set objIe = createObject("internetexplorer.application")

with objIe
	.navigate "about:blank"
	with .document.parentWindow.screen
	dWidth = .width
	dHeight = .height
	end with
end with	

appDataPath = WshShell.ExpandEnvironmentStrings("%APPDATA%")
pathToCopyTo = appDataPath & "\CCHCTheme\"
ThemePath = pathToCopyTo & "CCHC-Standard.bmp"
If (filesys.FolderExists(pathToCopyTo)) Then

	else
	  Filesys.CreateFolder(pathToCopyTo)
	end if

	
	If filesys.FileExists(ThemePath) Then

   	ELSE
		filesys.CopyFile"\\cchdomain1\netlogon\theme\CCHC-Standard1.bmp", pathToCopyTo
		filesys.CopyFile"\\cchdomain1\netlogon\theme\CCHC-Widescreen1.bmp", pathToCopyTo
	End If

dProd = dWidth/dHeight

' WVersion = WshShell.RegRead ("HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProductName")

	If dProd <= 1.4 Then
		wpFile = "\\cchdomain1\netlogon\theme\CCHC-Standard1.bmp"
	Else	
		wpFile = "\\cchdomain1\netlogon\theme\CCHC-Widescreen1.bmp"
	End If

	WshShell.RegWrite "HKCU\Control Panel\Desktop\Wallpaper",wpFile
	WshShell.RegWrite "HKCU\Control Panel\Desktop\WallpaperStyle",wpStyle

		
	If (filesys.FolderExists("C:\SaberCom")) Then

	else
	  Filesys.CreateFolder("C:\SaberCom")
	  Filesys.CreateFolder("C:\SaberCom\ssmedia")	
	end if

	
	If filesys.FileExists("C:\Sabercom\cchc-sabsav.scr") Then

   	ELSE
		filesys.CopyFile"\\cchdomain1\Netlogon\Theme\SaberCom\*.*", "c:\SaberCom\"
		filesys.CopyFile "\\cchdomain1\Netlogon\Theme\SaberCom\ssmedia\*.*", "c:\SaberCom\ssmedia\"

	End If

WshShell.RegWrite "HKCU\Control Panel\Desktop\SCRNSAVE.EXE", "C:\Sabercom\cchc-sabsav.scr"
WshShell.RegWrite "HKCU\Control Panel\Desktop\ScreenSaveTimeout", 600
WshShell.RegWrite "HKCU\Control Panel\Desktop\ScreenSaverIsSecure", 0
WshShell.RegWrite "HKCU\Control Panel\Desktop\ScreenSaveActive",1
WshShell.Run "%windir%\System32\RUNDLL32.EXE user32.dll,UpdatePerUserSystemParameters",1, False


objIe.quit 

Export to CSV no showing all data

$
0
0

Hi

I want to export all global groups with an m in it to Excel.

foreach($group in (Get-ADGroup -filter "name -like 'G*m*'")){Get-ADGroupMember -Identity $group | select @{n='GroupName';e={$group.name}},samaccountname,name}

in powershell i get a list with all the groups and there members . So now i want to export to Excel:

foreach($group in (Get-ADGroup -filter "name -like 'G*m*'")){Get-ADGroupMember -Identity $group | select @{n='GroupName';e={$group.name}},samaccountname,name | export-csv -path d:\groupswithM.csv -Delimiter ";"}

All i get in my sheet is the last group in my variable. 

help I want the same output that i get exported to an excel sheet! Help.

thx in advance.

Powershell Script to Assign Share Permission

$
0
0

Hello,

We are trying to streamline the folder access permissions. We see that on many NAS shares Everyone is provided full share permission, but the NTFS permissions do not have everyone group.

What we wanted is a script that will take the NFTS permissions for the respective folder and apply that as a share permission by overwriting the existing share permission for the respective shared folder.

Thank you.

Raj


Powershell IF true

$
0
0

I will be creating a scheduled task to run against hosts in my env to notify a specified user when a drive has less than 10 gb of space left. I needed help with the IF true send email to statement. Here is the command I put together. ANy help would be greatly appreciated

Get-Volume | Where-Object {([math]::truncate($_.SizeRemaining / 1GB) -lt 10)-and ($_.DriveType -eq “FIXED”) -and ($_.FileSystemLabel -ne “System Reserved”)}


vbs/hta columnize checkboxes

$
0
0

I have a script to install tcp printers. There are about 50 checkboxes that make the window really long. see example below but with 50 of these entries. How can split them into columns? Thank you.

<input type="checkbox" name="CheckBox1" value="ChkBox">
<font face="serif" size="2">printer1</font><br>
<input type="checkbox" name="CheckBox2" value="ChkBox">
<font face="serif" size="2">printer2</font><br>
<input type="checkbox" name="CheckBox3" value="ChkBox">
<font face="serif" size="2">printer3</font><br>
<input type="checkbox" name="CheckBox4" value="ChkBox">
<font face="serif" size="2">printer4</font><br>
<input type="checkbox" name="CheckBox5" value="ChkBox">
<font face="serif" size="2">printer5</font><br>

Get-netadapter in a for each loop

$
0
0

Hi,

I'm trying to create an array using get-netadapter.  My variable is:

$adapter = get-netadapter -physical

When I run the for each loop I'm getting the messy output of: MSFT_Netadapter (CreationClassName = ...), over and over for each one.

What I'm wanting is it to print the output as if you just ran the command without it being in a variable

My code looks like the following:

function Network {

$adapter = get-netadapter -physical

foreach ($a in $adapter) {
Write-Host "$a"
}
}
Network

I know something is off as its an array just can't remember at the moment.  Any thoughts?

Thanks


JCtech1123, Cheers

How do I get the attributes of foreign security principals of an AD Group?

$
0
0

I have N number of domains and I have AD groups created all over them. I am allowing user to select the domain and I am filtering the list of groups. Now, my next step is that I have the members of those groups which can be a user or group or any kind of AD Object from any domain(foreign security principals) whose SID the system stores in the members attribute of the main AD Group/Object. I am able to generate the members list based on the scenario of a single domain however in case of a group having a member from other domain I am not able to find an efficient approach about how to provide link to the code that could fetch attributes using SID.

I am using $groupGUID as a parameter to pass and check for the members. This is my script in PowerShell class:

param($GroupGUID)
Import-Module activedirectory -ErrorAction SilentlyContinue
class MemberList
{

    [string] $DisplayName
    [string] $MemberGUID
    [string] $GroupGUID
    [string] $Enabled

    MemberList()
    {

        $this.DisplayName="Unknown"
        $this.MemberGUID = "Unknown"
        $this.GroupGUID = "Unknown"
        $this.Enabled = "Unknown"
    }
    MemberList([Object] $ADObject)
    {
        $this.DisplayName=$ADObject.Name        
        $this.MemberGUID = $ADObject.objectGUID
        $this.Enabled=(($ADObject.useraccountcontrol -band 2) -eq 0)
    }
}

And I am invoking the object of this class as follows:

$MemberLists=@()
ForEach($ADObject in @(Get-ADGroupMember -Identity $GroupGUID -ErrorAction stop -Server "myDomain.net"))
{ 
            $MemberList = New-Object MemberList -ArgumentList (Get-ADObject -Identity $ADObject -Properties *)
            $MemberList.GroupGUID = $GroupGUID
            $MemberLists += $MemberList

} 
$MemberLists | Select-Object -Property * | Sort-Object -Property DisplayName

myDomain will be the selected domain by the user where the main group lies now where should I put the script to fetch the members that belongs to other domains? Inside the for each loop? Or When I am creating a new-object in side the loop how to implement the script in such a way that it will track down the SID and give me the attributes of the members of various domains? All I found out was that member attribute stores the information like this:

member          : {CN=S-1-5-XX-XXXXXXXXXX-XXXXXXXXXXX-XXXXXXXXXXX-XXXXXXXX,CN=ForeignSecurityPrincipals,DC=myDomain,DC=net,
                   CN=S-1-5-XX-XXXXXXXXXX-XXXXXXXXXXX-XXXXXXXXXXX-XXXX,CN=ForeignSecurityPrincipals,DC=myDomain,DC=net}

I found out that using the code below I can locate the member but can't figure out the connecting part into the loop.

([System.Security.Principal.SecurityIdentifier] "S-1-5-XX-XXXXXXXXX-XXXXXXXXX-XXXXXXXXX-XXXXXXX").Translate([System.Security.Principal.NTAccount]).value

Any kind of suggestion would be appreciated.


adding hyperlinks to AutoCorrect

$
0
0

Hello,

I hope my couple of questions are acceptable to ask here:

I am trying to add some hyperlinks to AutoCorrect via PowerShell, and I based my script on this one:

https://superuser.com/questions/515748/add-formatted-text-to-word-autocorrect-via-powershell

and got the following error:

System.ArgumentException: Exception setting "AddRichText": Cannot convert the "test" value of type "string" to type "Object".

So I tried to add some AutoCorrect entries manually via Word (replacing random words with plain text and hyperlinks)to see how they are saved in .AutoCorrect.Entries, but was not able to find the ones with hyperlinks.

So my questions would be:

Do you know how hyperlinks are saved in AutoCorrect / how to add hyperlinks to AutoCorrect?

And how to check/access the AutoCorrect entries of the other languages than the default one (MSO*.acl ordefault.acl)?

Thank you,

Viewing all 15028 articles
Browse latest View live


Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>