Quantcast
Channel: Windows PowerShell forum
Viewing all 21975 articles
Browse latest View live

Need to check domain member servers cert stores for SHA1 and SHA256

$
0
0

Good afternoon. I am a novice at scripting and PowerShell.

I need to just check our domain member servers and review their certificate stores for SHA1 and SHA256 certificates. This will be used for compliance and cleanup.

I can check a singular server, and I can recurse through the objects, but not both. Below is my cleaned code for polling AD and getting my machine names:

$Computers = Get-ADComputer -Filter {Enabled -eq $True} -searchbase "OU=servers,DC=xxx,DC=xxx" | select name
foreach($Computer in $Computers)
{
Invoke-Command -ComputerName $Computer.name -scriptblock
    {
    Get-ChildItem cert:\ -Recurse | select thumbprint, subject, @{n="SignatureAlgorithm";e={$_.SignatureAlgorithm.FriendlyName}}
    }
}

This is the error message that comes up:

Invoke-Command : Missing an argument for parameter 'ScriptBlock'. Specify a parameter of type 'System.Management.Automation.ScriptBlock' and try again.
At line:4 char:45
+ Invoke-Command -ComputerName $Computer.name -scriptblock
+                                             ~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Invoke-Command], ParameterBindingException
    + FullyQualifiedErrorId : MissingArgument,Microsoft.PowerShell.Commands.InvokeCommandCommand

Can anyone help me figure out what I'm missing please? Thank you so much in advance.

Chip Seiferman


add uses to Local admin group

$
0
0

I have googled this and all the scripts I've found add Domain\User to the Local Admin group.  Is there a way to read a .TXT file of user names and then add those users to the Local Admin group on a server?     I've even tried Net Localgroup /ADD and that too wants an actual user (either local or from your domain)


mqh7

escape the single quote inside an insert statement

$
0
0

Hi, I've been working on this for a couple of hours trying to follow the examples in Google but none seem to apply.

foreach ($node in $results) {
$sql =  "insert into AUDIT_Backup_History_STG (server_name,instance_name,database_name,backup_start_date,backup_finish_date,backup_type,backup_size,database_creation_date,recovery_model,physical_device_name) VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}')" -f $node.server_name, $node.instance_name, $node.database_name, $node.backup_start_date, $node.backup_finish_date, $node.backup_type, $node.backup_size, $node.database_creation_date, $node.recovery_model, $node.physical_device_name

	$Command.CommandText = $sql
	$Command.ExecuteNonQuery()
}

This is breaking because the last value, $node.physical_device_name, has a single quote in it. Is there some way that the quote can be escaped so it goes into the database without causing a false end to $sql?

Thanks for any help.

Howard


powershell beginner

$
0
0

Hello. I just started using PS for about a week and I am currently making different problems to get used to the functions. I have a question though. I want to list the names and roles of some users and I would also like to do this in a single function.

I know this could be done with:

Get-MsolRole to find the object Id, then use Get-MsolRoleMember -RoleObjectId xxxxxxxxx

but I would like to be able to retrieve the name and the role, like I would get it from this function:

Get-MsolUser | Select-object DisplayName, Role | Export-CSV .\role.csv

I am interested in obtaining the role

creating a custom user object from AD info and office 365 info

$
0
0

Dear technet I am trying to buid a script that does this:

Suppose I need some information from a user that are in the AD, and some information form office 365.

My script looks like this. Th problem is that I am unable to bing the info from Offoce 365, for exampe the parameter HasPciture is empty no matter how I do it. Can you please advise me?

Function Get-CustomUSer
{
    param ([string]$ADuser)
    $MyADUser = Get-ADUser -Identity $ADuser -Properties *
    $UserMailBox = Get-mailbox -Identity  Get-ADUser -Identity $ADuser | Select $_.Mail

    $obj = New-Object -TypeName psobject
    $obj | Add-Member -MemberType NoteProperty -Name Name -Value $MyADUser.Name
    $obj | Add-Member -MemberType NoteProperty -Name SamAccountName -Value $MyADUser.SamAccountName
    $obj | Add-Member -MemberType NoteProperty -Name "Display Name" -Value $MyADUser.CN
    $obj | Add-Member -MemberType NoteProperty -Name Title -Value $MyADUser.Title
    $obj | Add-Member -MemberType NoteProperty -Name Phone -Value $MyADUser.telephoneNumber
    $obj | Add-Member -MemberType NoteProperty -Name OfficePhone -Value $MyADUser.OfficePhone
    $obj | Add-Member -MemberType NoteProperty -Name Location -Value $MyADUser.Office
    $obj | Add-Member -MemberType NoteProperty -Name Manager -Value $MyADUser.Manager
    $obj | Add-Member -MemberType NoteProperty -Name HasPicture -Value $MyO365User.HasPicture

    Write-Output $obj
 }


Scheduled reboot with a message

$
0
0

Hi together,

I'd like to realize following:

1) Restart all member computers in a domain group in a scheduled day / time.

2) Scheduled day / time is on Wednesday each 2 weeks.

3) 15 minutes before the server is rebooted, a user group should get an emailthat the computers will be rebooted in 15 minutes.

4) All applications should be forced to close.

5) In each reboot, a log file of the reboot should be generated and saved in a local folder.

6) The scheduled reboot script will be used with a domain group policy.

I can restart the Computers with following script. But how can I realize others?

Get-ADGroupMember "Domain group to restart" |
    ForEach-Object{
        Restart-Computer -ComputerName $_.Name
    }
 

Best Regards

Birdal





Running a PowerShell Script with the Task Scheduler

$
0
0

Hello

I'm having trouble running a PowerShell Script with the Task Scheduler.

It works just fine when I run it directly in PowerShell but as soon as I try to use the Task Schedular it seems to only work partly.

I already created the desktop Folder as suggested in a post I found
C:\Windows\SysWOW64\config\systemprofile\Desktop

#Starting Transcript to file
$go = "D:\Transcript.txt:"
Start-Transcript -Path $gitgud

#Silently continus the Script incase an error occures
$ErrorActionPreference = "Silentlycontinue"

#Delete last months Excel so folder wont get too big
$path = "D:\Script"
Get-ChildItem -Path $path -include *.xls, *.xlsx -recurse |
foreach($_) { Remove-Item $_.fullname } | Out-Null

#Create excel COM object
$excel = New-Object -ComObject excel.application

#Make Visible
$excel.Visible = $True
$excel.DisplayAlerts = $false

#Add a workbook
$workbook = $excel.Workbooks.Add()

#Remove other worksheets
1..2 | ForEach {
    $Workbook.worksheets.item(2).Delete()
}

#Connect to first worksheet to rename and make active
$serverInfoSheet = $workbook.Worksheets.Item(1)
$serverInfoSheet.Activate() | Out-Null

#Create a Title for the first worksheet
$row = 1
$Column = 1
$serverInfoSheet.Cells.Item($row,$column)= "Disk Space Information $(get-date -f yyyy-MM-dd)"

$Selection = $serverInfoSheet.Range("A1:F2")
$Selection.Merge()
$Selection.VerticalAlignment = -4160

#Give it a nice Style so it stands out
$serverInfoSheet.Cells.Item($row,$column).Font.Size = 18
$serverInfoSheet.Cells.Item($row,$column).Font.Bold=$True
$serverInfoSheet.Cells.Item($row,$column).Font.Name = "Cambria"
$serverInfoSheet.Cells.Item($row,$column).Font.ThemeFont = 1
$serverInfoSheet.Cells.Item($row,$column).Font.ThemeColor = 4
$serverInfoSheet.Cells.Item($row,$column).Font.ColorIndex = 55
$serverInfoSheet.Cells.Item($row,$column).Font.Color = 8210719

#Increment row for next set of data
$row++;$row++

#Save the initial row so it can be used later to create a border
$initalRow = $row

#Create a header for Disk Space Report; set each cell to Bold and add a background color
$serverInfoSheet.Cells.Item($row,$column)= 'Computername'
$serverInfoSheet.Cells.Item($row,$column).Interior.ColorIndex =48
$serverInfoSheet.Cells.Item($row,$column).Font.Bold=$True
$Column++
$serverInfoSheet.Cells.Item($row,$column)= 'DeviceID'
$serverInfoSheet.Cells.Item($row,$column).Interior.ColorIndex =48
$serverInfoSheet.Cells.Item($row,$column).Font.Bold=$True
$Column++
$serverInfoSheet.Cells.Item($row,$column)= 'TotalSizeGB'
$serverInfoSheet.Cells.Item($row,$column).Interior.ColorIndex =48
$serverInfoSheet.Cells.Item($row,$column).Font.Bold=$True
$Column++
$serverInfoSheet.Cells.Item($row,$column)= 'UsedSpaceGB'
$serverInfoSheet.Cells.Item($row,$column).Interior.ColorIndex =48
$serverInfoSheet.Cells.Item($row,$column).Font.Bold=$True
$Column++
$serverInfoSheet.Cells.Item($row,$column)= 'FreeSpaceGB'
$serverInfoSheet.Cells.Item($row,$column).Interior.ColorIndex =48
$serverInfoSheet.Cells.Item($row,$column).Font.Bold=$True
$Column++
$serverInfoSheet.Cells.Item($row,$column)= '%Free'
$serverInfoSheet.Cells.Item($row,$column).Interior.ColorIndex =48
$serverInfoSheet.Cells.Item($row,$column).Font.Bold=$True

#Increment Row and reset Column back to first column
$row++
$Column = 1

#Getting Server Names
$disk = Get-Content D:\servers.txt, D:\testservers.txt
$servers = Get-Content D:\servers.txt, D:\testservers.txt

#Pinging all servers and writing output to Error file
  foreach ($server in $servers) {
  if (test-Connection -ComputerName $server -Count 2 -Quiet ) {
        Write-Output "$server is alive"
         } else
           { Write-Output "$server seems dead"
             }
}

#Get the drives and filter out CD/DVD drives
$diskDrives = Get-WmiObject win32_LogicalDisk -Filter "DriveType='3'" -ComputerName $disk

#Process each disk in the collection and write to spreadsheet
ForEach ($disk in $diskDrives) {
    $serverInfoSheet.Cells.Item($row,$column)= $disk.__Server
    $Column++
    $serverInfoSheet.Cells.Item($row,$column)=  $disk.DeviceID
    $Column++
    $serverInfoSheet.Cells.Item($row,$column)= ($disk.Size /1GB).ToString("#0.00")
    $Column++
    $serverInfoSheet.Cells.Item($row,$column)= (($disk.Size - $disk.FreeSpace)/1GB).ToString("#0.00")
    $Column++
    $serverInfoSheet.Cells.Item($row,$column)= ($disk.FreeSpace / 1GB).ToString("#0.00")
    $Column++
    $serverInfoSheet.Cells.Item($row,$column)= ("{0:P}" -f ($disk.FreeSpace / $disk.Size))
    $Column++

    #Check to see if space is near empty and use appropriate background colors
    $range = $serverInfoSheet.Range(("A{0}" -f $row),("F{0}"  -f $row))
    $range.Select() | Out-Null

    #Determine if disk needs to be flagged for warning or critical alert

    #Critical threshold
    If ($disk.FreeSpace -lt 5GB)  {
        $range.Interior.ColorIndex = 3

    #Warning threshold
    } ElseIf ($disk.FreeSpace -lt 10GB) {
        $range.Interior.ColorIndex = 6
        }
    #Add row and reset Column for the next Server
    $row++
    $Column = 1

  }

    #Creat Borders for the Data
  $row--
$dataRange = $serverInfoSheet.Range(("A{0}" -f $initalRow),("F{0}"  -f $row))
7..12 | ForEach {
    $dataRange.Borders.Item($_).LineStyle = 1
    $dataRange.Borders.Item($_).Weight = 2
    }

#All numbers from right to left for readability
$border = $serverInfoSheet.Range(("C{0}" -f $initalRow),("F{0}"  -f $row))
7..12 | ForEach {
    $border.HorizontalAlignment = -4152
    }

  #Auto fit everything so it looks better
$usedRange = $serverInfoSheet.UsedRange
$usedRange.EntireColumn.AutoFit() | Out-Null

#Save the file
$workbook.SaveAs("D:\Script\$(get-date -f yyyy-MM-dd) DiskSpace.xlsx")

#Closing the file and releasing it
$excel.Quit()
[System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$excel) | Out-Null


#Convert all exels in this Folder and its Subfolders to Pdf
$path = "D:\Script"
$xlFixedFormat = “Microsoft.Office.Interop.Excel.xlFixedFormatType” -as [type]
$excelFiles = Get-ChildItem -Path $path -include *.xls, *.xlsx -recurse
$objExcel = New-Object -ComObject excel.application
$objExcel.visible = $false
foreach($wb in $excelFiles)
{
 $filepath = Join-Path -Path $path -ChildPath ($wb.BaseName + “.pdf”)
 $workbook = $objExcel.workbooks.open($wb.fullname, 3)
 $workbook.ExportAsFixedFormat($xlFixedFormat::xlTypePDF, $filepath)
 $objExcel.Workbooks.close()
}
#Closing the file
$objExcel.Quit()

#Stoping the Transcript
Stop-Transcript

kill -processname Excel

It safes the Transcript file, deletes all excel files in the designated folder  and opens Excel in the Background but wont safe the Excel file.

What are the possible reasons why it wouldnt work as intended with the Task Scheduler?


Forcing inheritance on child items

$
0
0

Hi all,

In a files and folders tree, several files and folders are modifyied outside this tree then copied back to this tree, and these items lose the inheritance from parent folder. This is "by design" as Microsoft says.

So I'm working on a script that allows me to force ACL inheritance on child items. I'm looking for the PowerShell equivalent to the checkbox "Replace all child object permission entries with inheritable permission entries from this object".

Have you an idea please ? Thank you.

Have a nice day.


FXE



How to cycle through all image nodes of a SSRS RDL file

$
0
0

Hi PoSh folks, I need a favour!

I am trying to replace the contents of all image nodes (and their child nodes) in a RDL file (a Reporting Services report definition document).

The problem I am having is that I am unable to work out how to get all the nodes I need (with SelectNodes) then cycle through them. The XML in a RDL file looks something like this:

<Report><ReportSections><ReportSection Name="Section1"><Table><Cell><Image Name="Image1"><FileName>Logo</FileName><Type>png</Type></Image></Cell></Table><Image Name="Image2"><FileName>Sunshine</FileName><Type>png</Type></Image></ReportSection><ReportSection Name="Section2"><Footer><Paragraphs><Paragraph><TextRuns><TextRun><Value><Image Name="Image3"><FileName>Moonlight</FileName><Type>png</Type></Image></Value></TextRun></TextRuns></Paragraph></Paragraphs></Footer></ReportSection></ReportSections></Report>

As you can see, the image node can appear in lots of different places. If I specify the exact position of the node I can access it, but I can't search for it. Here is some example PS code to demonstrate:

#Clear screen
CLS

$fileName = 'test.rdl'
$docPath = [Environment]::GetFolderPath('Desktop') + '\'
$fullPath = $docPath + $fileName

[xml]$RDLFile = Get-Content -Path $FullPath

#This line works (i.e. if I specify where the node is)
$Images = $RDLFile.Report.ReportSections.ReportSection.Page.PageFooter.ReportItems.Image

#This line doesn't work (i.e. where I want to search for all instances of a named node)
#$Images = $RDLFile.SelectNodes('//Image')

#Do something if nodes were found, else write null nodes
If($Images -ne $null)
{
    #Cycle through nodes that were found
    ForEach($Image In $Images)
    {
        #Write out node information
        $ImageName      = $Image.Name
        $ImageSource    = $Image.Source
        $ImageType      = If($Image.MIMEType -eq $null){'.bmp'}Else{$Image.MIMEType}
        $ImageExt       = $ImageType -Replace 'image/','' -Replace 'jpeg','jpg' -Replace 'x-',''
        $ImageFileName  = $Image.Value + $ImageExt

        Write-Host $ImageName
        Write-Host $ImageSource
        Write-Host $ImageType
        Write-Host $ImageFileName
    }
}
Else
{
    Write-Host 'Null nodes'
}

In the code above, the line that specifies the node exactly works, but the SelectNodes command doesn't - it returns null.

I've read that SelectNodes might return null if namespaces are specified in the XML document (and they are in this case), but I'm not sure how to use the namespaces to sort this issue out as all examples I've looked at still specify the exact position on the node....

Help please!!

Splash screen on RunOnce

$
0
0

Hi,

I am trying to run this script from HKCU RunOnce. But even with WindowStyle Hidden, I get a splash screen. Any idea?

Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOnce]
"ParametresWindows8.1Enterprise1.0_Frv1"="C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe -NoProfile -nologo -WindowStyle Hidden -File \"C:\\PROGRA~1\\ORGANI~1\\INSTTR~1\\Trousses\\PARAME~1.0_F\\ACTIVE~1\\HKCURunOnce.ps1\""

By typing that line at command prompt everything is fine but at logon there is a splash screen.

Any idea?

Thanks,

Adding the office location to the Outlook Contacts

$
0
0

Hello,

I need to add what city each user is located in. The best way I know to determine which city each person is located in is by a distribution list that they are part of. So we have a San Diego distribution list for all of the employees located in San Diego and I need to add that city to the Office field of each person's contact information. 

I am trying to find the best way to do this but I'm having difficulty. I've tried different ways to write the script but this is the closet I get. The problem I run into is that I receive a message powershell doesn't recognize the object. I've confirmed that the email address are in the system. 

$UserCredential = Get-Credential
$dl = Read-Host "What is the distribution group name?"
#Creates an Exchange Online session
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection

#Import session commands for Exchange
Import-PSSession $Session -AllowClobber
Connect-MsolService -Credential $UserCredential
get-DistributionGroupMember "$dl" | Select primarysmtpaddress | Sort-Object ID | export-csv c:\users\chendley\desktop\dlmembers.csv

Import-Csv c:\users\chendley\desktop\dlmembers.csv | ForEach-Object {set-contact -identity $_.PrimarySmtpAddress -office "New York"}

Remove-PSSession -Session $session

Trying to export module to remote systems

$
0
0

I am trying to get an inventory of printers installed on about 2000 systems at work and while I have the basic functionality of it worked out, I am unable to get some of the commands to run on remote machines. I downloaded a script from the TechNet Gallery that searched recursively through the Registry to find things, but I am unable to get it to run on the remote computers. I tried copying the modules to the remote system but every time I try to Enter-PSSession, it throws an error. I need to add a Debug statement to see what the exact error is, but I can manually run the steps from the console, but it won't work in my script. We recently got rid of our MS Print server and replaced it with VPSX, which turns each PC into a Print Server, so we are unable to find print jobs if one gets hung up, since we don't know which PC sent it. There are a lot of systems here (Desktops and Thin Clients) that are having an issue where they have only the old printers installed (old print queues are paused), they have no printers installed, or they have a mix of old and new printers installed in Devices and Printers. I found out that VPSX installs the printers as both a Network and Local printer, which makes it a little difficult to find them all. Some of the old printers are showing up in the HKLM:\Software\Microsoft\Windows NT\CurrentVersion\Print\Providers\Client Side Rendering Print Provider\... They don't always just show up in that location though. I'm trying to figure out why they are still in Devices and Printers, which I can't specifically locate, but that's why I'm searching for them. I hope one of you fine folks can give me the nudge I need in order to get this to work.  I'm sure I'm doing something wrong, but I'm just not seeing it.

<#
	.NOTES
	===========================================================================
	 Created with: 	SAPIEN Technologies, Inc., PowerShell Studio 2015 v4.2.85
	 Created on:   	9/29/2016 3:58 PM
	 Created by:   	BEMBREE
	 Organization: 	Legacy Health
	 Filename:
	===========================================================================
	.DESCRIPTION
		This script looks at systems (at GS right now) and finds PCs and Thin Clients, then determines if they have VPSX installed, looks for any printers installed from the old print server, as well as any VPSX printers
#>

#Add-PSSnapin Microsoft.WSMan.Management
Import-Module PSExcel
Import-Module Remote_PSRemoting
#Import-Module Search-Registry


function main
{

	$GSList = gc 'Y:\VPSX Data - GS\GS-AllWorkstations.txt'
	$count = $GSList.Length
	$i = 1

	$GS_PCList = @()

	$GSList | ForEach-Object {
		Write-Output "$i of $count"

		$current = $_
		if (Test-Connection -ComputerName $current -Count 1 -Quiet)
		{
			Set-RemoteAccess -computerName $current

			#Check for VPSX service
			try
			{
				$VPSXService = Get-Service -ComputerName $current -Name LRSDRVX -ErrorAction 'SilentlyContinue'
				if ($VPSXService -ne $null)
				{
					Write-Debug "VPSX: $VPSXService.Status"
					$VPSXServiceInstalled = $true
					$VPSXServiceStatus = $VPSXService.Status
				}
				else
				{
					Write-Debug "VPSX: $VPSXService"
					$VPSXServiceStatus = "VPSX Not installed"
					$VPSXServiceInstalled = "No"
				}
			}
			catch
			{
				$VPSXServiceInstalled = "unknown error"
				$VPSXServiceStatus = "unknown error"
			}

			Get-PrintersFromReg -computerName $current, -vpsxPrinterlist $vpsxPrinterlist, -oldPrinterList $oldPrinterList

			if ($vpsxPrinterlist -ne $null) { $VPSXPrintersInstalled = $true }
			else { $VPSXPrintersInstalled = $false }

			if ($oldPrinterList -ne $null) { $OldPrintersInstalled = $true }
			else { $OldPrintersInstalled = $false }

			$temp = New-Object System.Management.Automation.PSObject -Property @{
				ComputerName = $current
				OldPrintersInstalled = $OldPrintersInstalled
				VPSXServiceInstalled = $VPSXServiceInstalled
				VPSXPrintersInstalled = $VPSXPrintersInstalled
				VPSXServiceStatus = $VPSXServiceStatus
			}

		}
		else #system offline
		{
			$temp = New-Object System.Management.Automation.PSObject -Property @{
				ComputerName = $current
				OldPrintersInstalled = "offline"
				VPSXPrintersInstalled = "offline"
				VPSXServiceInstalled = "offline"
				VPSXServiceStatus = "offline"
			}
		}

		$GS_PCList += $temp
		$i++
	}
	$GS_PCList | Export-XLSX y:\Scripts\ScriptDocs\GS_PCList.xlsx -ClearSheet

}

function Set-RemoteAccess ($computerName)
{

	try
	{

		if ((Test-WSMan -ComputerName $current -ErrorAction 'SilentlyContinue') -eq $null)
		{
			Set-WinRMListener -ComputerName $current -ErrorAction SilentlyContinue
			Restart-WinRM -ComputerName $current -ErrorAction SilentlyContinue
			Set-WinRMStartup -ComputerName $current -ErrorAction SilentlyContinue
			Set-WinRMFirewallRule -ComputerName $current -ErrorAction SilentlyContinue
			Restart-WindowsFirewall -ComputerName $current -ErrorAction SilentlyContinue
			Write-Output "PSRemoting setup on $current"
		}
		else
		{
			Write-Debug "PSRemoting already setup"
		}
	}

	catch
	{
		Write-Output "Unable to setup PSRemoting"
	}
}

function Get-PrintersFromReg ($computerName, $vpsxPrinterlist, $oldPrinterList)
{
	$source = "C:\Windows\System32\WindowsPowerShell\v1.0\Modules\Search-Registry"
	$Destination = "\\$current\c$\Windows\System32\WindowsPowerShell\v1.0\Modules\Search-Registry"

	try
	{
		mkdir -Path $Destination -Force
		Copy-Item -Path "C:\Program Files\WindowsPowerShell\Modules\Search-Registry\*" -Destination $Destination -Force
		Import-Module Search-Registry
		$username = "lhsnt\bembree"
		$PWD = ConvertTo-SecureString -AsPlainText "Macey810" -Force
		$creds = New-Object System.Management.Automation.PSCredential $username, $PWD

		$session = New-PSSession
		#$session = Enter-PSSession -ComputerName $current -Credential $creds -ErrorAction 'SilentlyContinue'

		$localPrinterPath = "HKLM:\Software\Microsoft\Windows NT\CurrentVersion\Print\Printers\"
		$secondaryPrinterPath = "HKLM:\System\CurrentControlSet\Control\Print\Printers"
		$networkPrinterPath = "HKCU:\Printers\Defaults\"

		$vpsxPrinterlist = Invoke-Command -ComputerName $computerName -Session $session -ScriptBlock { Search-Registry -Path $localPrinterPath -Recurse -SearchRegex "secvpsx*" -KeyName } -ErrorAction 'SilentlyContinue'
		$vpsxPrinterlist = $vpsxPrinterlist + (Invoke-Command -ComputerName $computerName -Session $session -ScriptBlock { Search-Registry -Path $secondaryPrinterPath -Recurse -SearchRegex "secvpsx*" -KeyName } -ErrorAction 'SilentlyContinue')
		$vpsxPrinterlist = $vpsxPrinterlist + (Invoke-Command -ComputerName $computerName -Session $session -ScriptBlock { Search-Registry -Path $networkPrinterPath -Recurse -SearchRegex "secvpsx*" -KeyName } -ErrorAction 'SilentlyContinue')

		$oldPrinterList = Invoke-Command -ComputerName $computerName -Session $session -ScriptBlock { Search-Registry -Path $localPrinterPath -Recurse -SearchRegex "sgsprntsrv1*" -KeyName } -ErrorAction 'SilentlyContinue'
		$oldPrinterList = $oldPrinterList + (Invoke-Command -ComputerName $computerName -Session $session -ScriptBlock { Search-Registry -Path $secondaryPrinterPath -Recurse -SearchRegex "sgsprntsrv1*" -KeyName } -ErrorAction 'SilentlyContinue')
		$oldPrinterList = $oldPrinterList + (Invoke-Command -ComputerName $computerName -Session $session -ScriptBlock { Search-Registry -Path $networkPrinterPath -Recurse -SearchRegex "sgsprntsrv1*" -KeyName } -ErrorAction 'SilentlyContinue')


	}
	catch
	{
		Write-Output "Invoke-Command failed"
	}
}


main
#endregion

Error with PS loop

$
0
0

I'm getting the following error with my script:

You cannot call a method on a null-valued expression.                    
At E:\Scripts\Get-registry\PendingReboot.ps1:44 char:2                   
+     $fullreg = $ref.GetValue($regvalue);                               
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~                                
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException 
    + FullyQualifiedErrorId : InvokeMethodOnNull                         

When it runs through the script the first time everything works just fine... when it loops the second time I get the above error.  My understanding is that when you use !$variable it is actually looking for a null value so I don't understand why the script is having such a hard time when it's finding one the second time through...

$computername = "servername";
$Hive = [Microsoft.Win32.RegistryHive]"LocalMachine";
$regKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($Hive, $computername);
$regvalue = "PendingFileRenameOperations";

$Client = Invoke-WmiMethod -NameSpace "ROOT\ccm\ClientSDK" -Class CCM_ClientUtilities -Name "DetermineIfRebootPending" -ComputerName $computername
$RebootPending = $Client.RebootPending


$trigger = $false
Do
{
	$ref = $regKey.OpenSubKey("SYSTEM\CurrentControlSet\Control\Session Manager");
	$fullreg = $ref.GetValue($regvalue);
	If (!$fullreg)
	{

		$host.ui.RawUI.ForegroundColor = "Green"
		Write-Output "No Reboot Pending on $computername"
		Write-Output $RebootPending
		$host.UI.RawUI.ForegroundColor = 'White'
		$trigger = $true
	}
	elseif ($RebootPending.value -eq 'False')	{

		$host.ui.RawUI.ForegroundColor = "Green"
		Write-Output "No SCCM Reboot Pending on $computername"
		Write-Output $RebootPending
		$host.UI.RawUI.ForegroundColor = 'White'
		$trigger = $true
	}

	Else
	{

		$host.ui.RawUI.ForegroundColor = "Yellow"
		Write-Output "$computername is still pending a reboot! Rebooting..."
		$host.UI.RawUI.ForegroundColor = 'White'
		restart-computer -ComputerName $computername -Force -Wait
		$host.ui.RawUI.ForegroundColor = "Yellow"
		Write-Output "Waiting 5 Minutes before continuing the script"
		$host.UI.RawUI.ForegroundColor = 'White'
		Start-Sleep -Seconds 300

	}
}
Until ($trigger)


New-AzureRmStorageAccount

$
0
0

Hello,

I am trying to create a new Azure Storage account in our cloud so that I can do some test deployment using PowerShell.  I'm using the article below as a guide:

https://msdn.microsoft.com/en-us/library/mt607148.aspx?f=255&MSPPError=-2147217396

I'm using the command below:

New-AzureRmStorageAccount -ResourceGroupName "MyResourceGroup" -AccountName "MyStorageAccount" -Location "US West" -Type "Standard_GRS"

I can't find additional information about "Type" anywhere.  I have tried running:

Get-AzureRmStorageAccount

However I don't see a heading called "Type" nor do I see any of the options listed as being applied to my existing disks.  How do I determine what type of storage I should be using?  How do I determine what type of storage I'm using currently? 


Importing multiple groups from a single CSV string into an AD Group

$
0
0

Hi all

I am trying to import a csv that has mutliple groups in a single cell. The values in the CSV are displayed exactly like this in the cell -  "Group1","Group2","Group3"

In PS ISE I have tested by manually entering $Members = "Group1","Group2","Group3" and it works. however the import doesnt treat it the same. I assume I need to use an escape character of some kind?

#$csv = import-csv C:\ps\import\SecurityGroups.csv
$csv = import-csv C:\ps\import\SecurityGroups_Test.csv
$Members = "Group1","Group2","Group3"

foreach ($row in $csv) {

    if ($row.domain -eq "UK") {

    if ($row.GroupName) {


    New-ADGroup -Name $row.groupname -SamAccountName $row.groupname -DisplayName $row.groupname -Description $row.description -GroupCategory $row.groupcategory -GroupScope $row.groupscope -Path "OU=Applications,OU=Groups,DC=UK,,DC=XXX,DC=net" -ManagedBy $row.managedby
    Add-ADGroupMember $row.GroupName -Members $($row.Members)
    #Add-ADGroupMember $row.GroupName -Members $Members

    }
    }

}


#Remove-ADgroup -Identity "MyTest_001(domain local)"
#Remove-ADgroup -Identity "MyTest_001(Global)"






How to get Volume Statistics

$
0
0

Hello Forum

Is there a way to get the following Volume (Disk) information for Servers hosting SQL Server in a domain on a volume by volume basis: -

  • Host Name
  • Disk I/O
  • Reads
  • Writes
  • Queues

We're wanting to grab this information and store it in a Table and then produce average stats.

Note I'm wanting all the system stats, not just those specific to SQL Server.  Ideally we want to run this as a task from one Central Server to interrogate other Servers.


Please click "Mark As Answer" if my post helped. Tony C.

Powershell Bug? Get-VM | Where-object($_.name -eq "*")

$
0
0

Got a question,

Is there something I am missing. Thanks

get-vm #gets me my virtual server

Get-VM | Where-object($_.name -eq "*")  #No Return, no errors

Powershell Version

Major  Minor  Build  Revision
-----  -----  -----  --------
4      0      -1     -1      

how we can Automate our windows server ?

$
0
0

hi,

I want to  Automate my windows server and virtual machine like disk space Usage, Resources Usage, service health and also want to Automate MS exchange server ?

can some one share the process or guideline with some examples.

thanks

Register-ScheduledJob not working anymore ?

$
0
0

Hi,

For about 7-8 months, I use several scripts with "Register-ScheduledJob" on different servers. I never met any problems with it.

Since yesterday, I noticed that the scripts are not working anymore, and especially the "Register-ScheduledJob". I clearly see the Scheduled-Job in the Task Manager, but it notices me that it never has been executed.

If I force it to execute the task through the task manager, then nothing happens...

- I use the credential of an admin user (also tested with several admins users).

- I didn't change anything in my scripts

- I didn't do anything with the servers (no new updates since yesterday)

- I don't have anything special in the logs

Here is a little test I did on different servers, and the txt file never has been created :

$password = ConvertTo-SecureString "ADMINPASSWORD" -AsPlainText -Force
$account = New-Object System.Management.Automation.PSCredential "MYDOM\ADMIN", $password
$opt = New-ScheduledJobOption -RunElevated
$trigger = New-JobTrigger -Once -At (Get-Date).AddSeconds(5)
Register-ScheduledJob -Name "TESTtxt" -Credential $account -ScheduledJobOption $opt -Trigger $trigger -ScriptBlock {Write-Host "test" | Out-File C:\test.txt}

If I put this command in PS console, the txt file is well created..

I did several researches, but nothing worked for me..

Could anyone help me with that problem ?

Thanks !

Get-Service not showing unreachable servers

$
0
0

Hi all,

To make this as simple as possible, I have a script that queries the SCCM DP for the WDSServer service. 

Get-Service -computername Server1,Server2,Server3 -name WDSServer | Select machinename, name, status

If server2 is not reachable for some reason, the network is down or the service does not exist for some reason, the out just ignores the missing server. The output looks Something like this.

MachineName    Name       Status
-----------    ----       ------
Server1        WDSServer Running
Server3        WDSServer Running

What can I do to get server 3 to show up with a status unknown or error? It does may it hard to spot missing servers when you have about 100 that you are checking at one.

If I run the same command for the server that is missing or does not have the service, I get an error message. The error message disappears when multiple servers are queried.

Thank you

Charles


Viewing all 21975 articles
Browse latest View live


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