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

Assigning a ServicePlan under O365 without removing what might already be there...

$
0
0

Need some help...

I need to be able to assign a license for a particular Service Plan (SP) - lets say Office 365 ProPlus for this example - to all users. However, SOME users may already have various Service Plans assigned - Yammer or Sharepoint Online, for this example.

From what I have read and tried, I can assign the Office 365 SKU but that gives them access to all Service PLans under that SKU. I can also give then the O365 License, and then DIASBLE everything except O365 ProPlus. This would, of course, also remove any Yammer or SharePoint Online SP they may have enabled.

In my head, i think the answer is to grab all SPs assigned to them, throw it in an array, and then clear everything and add them back from the array with the addition of O365 ProPlus.

That correct? and is it the best way? There doesnt seem to be a way to simply give a certain SP in an additive way...

Any help would be greatly appreciated. Thanks!


Lancer la fenêtre de configuration des horraire d'accès d'un utilisateur de l'AD

$
0
0

Bonjour,

je suis en train de développer en powershell un script pour la création d'un utilisateur dans l'ad.

Je souhaiterais pouvoir assigner au nouveau utilisateur une plage horaire d'accès, mais plutôt que de

coder un script en powershell/batch, j'aurais voulu s'avoir s'il n'était pas tout simplement possible, une fois

l'utilisateur crée, de faire pop sa fenêtre de configuration des horraire d'accès (voir screen ci-dessous) via une commande powershell :

https://puu.sh/rJKfc/459532d60d.png

Merci d'avance pour votre aide, cordialement

PDT Setup.ps1 hangs

$
0
0
I have gotten PDT to the point where it is trying to run the Setup.ps1 script on DC01, but it just sits and never does anything when trying to verify remote access to the very first VMs registry.  Now I can, from the DC01, click on manage and it will allow me to manage the VM so I think that indicates that it should have access to the other VMs registry.

I can't figure out why it is getting hung.

PowerShell Character Matching

$
0
0

I need to create a PowerShell script that sorts computer objects in Active Directory

We are moving to a standardized naming convention and would like to have a script that runs on an interval that searches a particular OU and based upon the name moves the computer to a particular OU.

Our computer naming looks like this

ABC-L1234, XYZ-D1234

I'd like to make a script that matches the first three characters before the hypen, and then looks for the first character (L, D, T) followed by exactly 4 numbers and if it doesn't match exactly that skip it.

I have never fully understood RegEx well, probably because i've never had it explained to me well.

Any guidance would be great.

Powershell crashes on latest windows 10 update

$
0
0

I'm trying to disable ICS (Internet connection sharing)  with powershell. 

This used to work, prior to September 2016.   An update to windows 10 sometime in September or October broke this script, now I see this exception when running 

PowerShell.exe  -ExecutionPolicy UnRestricted  c:\temp\script.ps1

On the console i see:

Unhandled Exception: System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
   at IDispatchInvoke(IntPtr , Int32 , INVOKEKIND , DISPPARAMS& , Variant& , ExcepInfo& , UInt32& )
   at System.Management.Automation.ComInterop.UnsafeMethods.IDispatchInvoke(IntPtr dispatchPointer, Int32 memberDispId, INVOKEKIND flags, DISPPARAMS& dispParams, Variant& result, ExcepInfo& excepInfo, UInt32& argErr)
   at CallSite.Target(Closure , CallSite , ComObject )
   at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0)
   at CallSite.Target(Closure , CallSite , Object )
   at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0)
   at System.Management.Automation.Interpreter.DynamicInstruction`2.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.Interpreter.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.LightLambda.RunVoid1[T0](T0 arg0)
   at System.Management.Automation.DlrScriptCommandProcessor.RunClause(Action`1 clause, Object dollarUnderbar, Object inputToProcess)
   at System.Management.Automation.DlrScriptCommandProcessor.Complete()
   at System.Management.Automation.CommandProcessorBase.DoComplete()
   at System.Management.Automation.Internal.PipelineProcessor.DoCompleteCore(CommandProcessorBase commandRequestingUpstreamCommandsToStop)
   at System.Management.Automation.Internal.PipelineProcessor.SynchronousExecuteEnumerate(Object input)
   at System.Management.Automation.PipelineOps.InvokePipeline(Object input, Boolean ignoreInput, CommandParameterInternal[][] pipeElements, CommandBaseAst[] pipeElementAsts, CommandRedirection[][] commandRedirections, FunctionContext funcContext)
   at System.Management.Automation.Interpreter.ActionCallInstruction`6.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.Interpreter.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.LightLambda.RunVoid1[T0](T0 arg0)
   at System.Management.Automation.DlrScriptCommandProcessor.RunClause(Action`1 clause, Object dollarUnderbar, Object inputToProcess)
   at System.Management.Automation.DlrScriptCommandProcessor.Complete()
   at System.Management.Automation.CommandProcessorBase.DoComplete()
   at System.Management.Automation.Internal.PipelineProcessor.DoCompleteCore(CommandProcessorBase commandRequestingUpstreamCommandsToStop)
   at System.Management.Automation.Internal.PipelineProcessor.SynchronousExecuteEnumerate(Object input)
   at System.Management.Automation.Runspaces.LocalPipeline.InvokeHelper()
   at System.Management.Automation.Runspaces.LocalPipeline.InvokeThreadProc()
   at System.Management.Automation.Runspaces.PipelineThread.WorkerProc()
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()



The script:

# Register the HNetCfg library
regsvr32 /s hnetcfg.dll;
# Get sharing configuration;
$INTERFACE_ID = "{DDA95938-9816-421D-A2C6-36A83DEF6273}";
Write-Output "INTF ID $INTERFACE_ID ";

# Create a NetSharingManager object
$MY_NetShare = New-Object -ComObject HNetCfg.HNetShare;

$Con = $MY_NetShare.EnumEveryConnection |? { $MY_NetShare.NetConnectionProps.Invoke($_).Guid -eq $INTERFACE_ID };

$Sharing_Config = $MY_NetShare.INetSharingConfigurationForINetConnection.Invoke($Con);

# See if sharing is enabled;
Write-Output "Sharing Config before : $Sharing_Config.SharingEnabled ";
$Sharing_Config.DisableSharing();

Additional context shows working a while ago:

https://social.technet.microsoft.com/Forums/lync/en-US/88003b3b-0e5c-49a7-bb20-cdbbbb435d09/enabling-windows-ics-from-powershell?forum=ITCG



Optimize array check

$
0
0

Hi ! I've a little problem, the code that i write working, but is not very dynamic, so my goals are:

1- I would like to perform the check of each object and assign the correct value to the variable $colors

2- If the array $ListDiskUsage contains more than 4 values, manually already stated, I would like that the script create automatically new objects by following the same logic.

$ListDiskUsage is an array that could be contains 1 or 'n' values, actualy there are only 4 values but i want to optimize the code 

if ($ListDiskUsage[0] -ge '80' -and $ListDiskUsage[0] -lt '89'){ $colors = "0000FF|FFFF00" }
if ($ListDiskUsage[0] -ge '89'){ $colors = "0000FF|FF0000" }
if ($ListDiskUsage[0] -le '80'){ $colors = "0000FF|00FF00"}

$values = $ListDiskUsage[0],((100)-($ListDiskUsage[0]))
$text = $ListDeviceId[0],"FreeSpace"
$url = simpleEncoding $values $text "360x150" -Chart3D -title ("Disk Space",$ListDeviceId[0]) -colors $colors
DownloadAndShowImage -localfilename c:\a.png $url
$HTML = $HTML + "<BR><img src=C:\a.png>"


if ($ListDiskUsage[1] -ge '80' -and $ListDiskUsage[1] -lt '89'){ $colors = "0000FF|FFFF00" }
if ($ListDiskUsage[1] -ge '89'){ $colors = "0000FF|FF0000" }
if ($ListDiskUsage[1] -le '80'){ $colors = "0000FF|00FF00"}

$values = $ListDiskUsage[1],((100)-($ListDiskUsage[1]))
$text = $ListDeviceId[1],"FreeSpace"
$url = simpleEncoding $values $text "360x150" -Chart3D -title ("Disk Space",$ListDeviceId[1]) -colors $colors
DownloadAndShowImage -localfilename c:\b.png $url
$HTML = $HTML + "<img src=C:\b.png>"


if ($ListDiskUsage[2] -ge '80' -and $ListDiskUsage[2] -lt '89'){ $colors = "0000FF|FFFF00" }
if ($ListDiskUsage[2] -ge '89'){ $colors = "0000FF|FF0000" }
if ($ListDiskUsage[2] -le '80'){ $colors = "0000FF|00FF00"}

$values = $ListDiskUsage[2],((100)-($ListDiskUsage[2]))
$text = $ListDeviceId[2],"FreeSpace"
$url = simpleEncoding $values $text "360x150" -Chart3D -title ("Disk Space",$ListDeviceId[2]) -colors $colors
DownloadAndShowImage -localfilename c:\c.png $url
$HTML = $HTML + "<img src=C:\c.png>"


if ($ListDiskUsage[3] -ge '80' -and $ListDiskUsage[3] -lt '89'){ $colors = "0000FF|FFFF00" }
if ($ListDiskUsage[3] -ge '89'){ $colors = "0000FF|FF0000" }
if ($ListDiskUsage[3] -le '80'){ $colors = "0000FF|00FF00"}

$values = $ListDiskUsage[3],((100)-($ListDiskUsage[3]))
$text = $ListDeviceId[3],"FreeSpace"
$url = simpleEncoding $values $text "360x150" -Chart3D -title ("Disk Space",$ListDeviceId[3]) -colors $colors
DownloadAndShowImage -localfilename c:\d.png $url
$HTML = $HTML + "<img src=C:\d.png>"



How to set flag in MS Outlook2010 via powershell?

$
0
0

i am a new guy here, and learn Powershell not long. I want to set flag in MS outlook 2010 via powershell. Anyone can give me some advice?  i make some search on google, but cannot find much information. Thanks so much.

the code i wrote is below, how to wrote the code about flag? thx so much.

[void] [Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Core")
[void] [Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Interop.Outlook")
$olApp = New-Object Microsoft.Office.Interop.Outlook.ApplicationClass

$msg = $olApp.CreateItem(0)
$msg.importance=2
$msg.Recipients.Add("xxxxx.xxxxx@xxxxx.com")

$msg.Subject = "testing"

$msg.HTMLBody = "testing"

$msg.HTMLBody += Get-Content ("C:\Users\daniel\AppData\Roaming\Microsoft\Signatures\Daniel-PS.htm")

$msg.Send()

script file

$
0
0
Is there any orders to prevent the user from deleting files from the storage unit

Install SQL Server with Powershell

$
0
0

Hello guys

I want to write a script in that I can install a SQL Server 2012/2014/2016.

I searched in the web but I wasn´t successfull. So my question:
Is it possible to install a SQL Server or multiple SQL Servers with Powershell?
If yes, which pages/commands helps me?

Kind regards

Neverbesuccessfull


mohamedhassan_99@hotmail.com

Need Help with the query

$
0
0

I am trying to write the below mentioned query for doing a database restore dynamically.

I need to take a database backup and restore a new database on the same server with a new name

I am running into the problems in the last statement.

 

Param
(
[Parameter(Mandatory = $true)] [String] $dbname,
[Parameter(Mandatory = $true)] [String] $REQ

)
Import-Module SQLPS -DisableNameChecking
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoExtended") | Out-Null
[Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.ConnectionInfo") | Out-Null
[Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoEnum") | Out-Null

$restoredName = $dbname

if($REQ -ne $null -and $REQ.Length -gt 0) 

{  
       $restoredName = $REQ + '_' + $dbName
}

Else {

 'Not a Valid Database Name'



$networkshare = '\\Domain\Test\'
$dbfilebackup = $networkshare + $DBName + '.bak'
$dblogbackup = $networkshare + $DBName + '.trn'

$backup_path = $dbfilebackup


$MDFLogicalName = Invoke-Sqlcmd -ServerInstance 'TestServer' -Database 'master' -Query " SELECT name  FROM sys.master_files WHERE database_id = DB_ID('$dbname') and type_desc ='ROWS';"  ; $MDFLogicalName
$LDFLogicalName = Invoke-Sqlcmd -ServerInstance 'TestServer' -Database 'master' -Query "SELECT name  FROM sys.master_files WHERE database_id = DB_ID('$dbname') and type_desc ='LOG' ;" ; $LDFLogicalName

$restoredNameMDFFileName = 'C:\Test\SQLData\' +$restoredName + '.mdf' ;$restoredNameMDFFileName
$restoredNameLDFFileName = 'C:\Test\SQLLog\' + $restoredName + '.ldf' ;$restoredNameLDFFileName

$sqlprimary = Invoke-Sqlcmd -ServerInstance 'TestServer' -Database 'TestDB' -Query "SELECT ReplicaServerName FROM [dbo].[Replica_Types] WHERE [Replicas Type] = 'Primary Replica';"  ; $sqlprimary

$sqlstringprimary = 'SQLSERVER:\SQL\' + $sqlprimary.ReplicaServerName + '\DEFAULT' 

Backup-SqlDatabase -Database $dbname -BackupFile $dbfilebackup -ServerInstance $sqlprimary.ReplicaServerName

$DataLogicalName = $REQ + '_' +$MDFLogicalName 

$LogLogicalName = $REQ + '_' +$LDFLogicalName

$query = " EXECUTE [dbo].[sp_Load_filelist_Table]  '$backup_path' "

$Query1 = Invoke-Sqlcmd -ServerInstance 'TestServer' -Database 'TestDB' -Query $query


$query2 = 'RESTORE DATABASE ' + $restoredName + ' FROM DISK = ' + $dbfilebackup + ' WITH MOVE ' + $DataLogicalName + ' To ' + $restoredNameMDFFileName  + ' , ' + ' MOVE ' + $LogLogicalName + ' TO ' + $restoredNameLDFFileName+  ' ; '


$query3 = Invoke-Sqlcmd -ServerInstance 'TestServer' -Database 'TestDB' -Query $query2


I am getting the below meentioned error message.

Invoke-Sqlcmd : Incorrect syntax near '\'.
Incorrect syntax near the keyword 'with'. If this statement is a common table expression, an xmlnamespaces clause or a
change tracking context clause, the previous statement must be terminated with a semicolon.
The label 'D' has already been declared. Label names must be unique within a query batch or stored procedure.
At C:\Test.ps1:61 char:11
+ $query3 = Invoke-Sqlcmd -ServerInstance 'TestServer' -Database 'TestDB ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Invoke-Sqlcmd], SqlPowerShellSqlExecutionException
    + FullyQualifiedErrorId : SqlError,Microsoft.SqlServer.Management.PowerShell.GetScriptCommand

Can you help me please.

Add specific AD group to local administrator group.

$
0
0

I want to add specific user group to local administrator group, My DC is setup is asvd.mydomin.net every machine that i join to this DC have his own group under his own OU. Likevmaccount.vd.mydomin.net. i always use first name of VM to create OU and Group, I just wan that group should get added automatically via powershell script. Can below line of code help me to achieve 

function Add-LocalUser{
     Param(
        $computer=$env:computername,
        $group='Guests',
        $userdomain=$env:userdomain,
        $username=$env:username
    )
        ([ADSI]"WinNT://$computer/$Group,group").psbase.Invoke("Add",([ADSI]"WinNT://$domain/$user").path)
}



Akshay Pate

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

Dynamic Log File Upload

$
0
0

Hi Folks,

I have a powershell script that uploads log files created yesterday to AWS S3 storage, it then deletes all files older than 1 month.

The issue is there are new services added weekly so it is necessary to add a dynamic structure to look at the folder and dynamically react when a new file has been added.

The proposed new structure would be the script looks at the logfiles location:

$localPath = "C:\inetpub\logs\LogFiles\"

Creates a list of all the folders within this file structure and adds the folder name to the S3 bucket location:

$keyPrefix = "applicationlogs/IIS/<FOLDERNAME>/$timestampY/$timestampM/$timestampD/"

The script then runs through the list and processes each uploading their files to the S3 bucket

-------------------------------------------------------------------------

$timestampD = ((Get-Date).adddays(-1).toString("dd"))
$timestampM = ((Get-Date).adddays(-1)).toString("MMM")
$timestampY = ((Get-Date).adddays(-1).year)

$bucket = "<BUCKET NAME>"

$localPath = "C:\inetpub\logs\LogFiles\"

$keyPrefix = "applicationlogs/IIS/<DYNAMICFOLDERNAME>/$timestampY/$timestampM/$timestampD/"

Get-ChildItem $localPath | where { ($_.CreationTime -gt ((get-date).AddDays(-2))) -and ($_.CreationTime -lt ((get-date).AddDays(-1))) }
foreach ($f in Get-ChildItem $localPath  | where { ($_.CreationTime -gt ((get-date).AddDays(-2))) -and ($_.CreationTime -lt ((get-date).AddDays(-1))) }) 
{ $key="$keyPrefix$f"
 Write-S3Object -BucketName $bucket -File $f.FullName -Key $key -AccessKey $accessKey -SecretKey $secretKey -Region $region
}

-----------------------------------------------------------------------------------------------------------------------

Can I have some advice with the dynamic folder list creation?

Need help with PowerShell workflow for SQL backups

$
0
0

Hi Everyone

I've written below script for taking sql server backup using a powershell workflow:

Import-Module PSWorkflow

Workflow BackupSQLDatabase{

    Param(
         [Parameter(Mandatory=$true)]
         [String] $DatabaseName
    )

    InlineScript{
        Import-Module SqlPS -Force
        $fileName = $DatabaseName + $(Get-Date -Format yyMMddhhmmss)
        Backup-SqlDatabase -ServerInstance localhost -Database AdventureWorks2014 -BackupFile "D:\Backups\$fileName.bak"
    }

}

When I'm trying to invoke workflow, I'm getting this error:

PS C:\Windows\system32> BackupSqlDatabase -DatabaseName adventureworks2014
WARNING: [localhost]:The names of some imported commands from the module 'SqlPS' include unapproved verbs that might make them less di
scoverable. To find the commands with unapproved verbs, run the Import-Module command again with the Verbose parameter. For a list of 
approved verbs, type Get-Verb.
Backup-SqlDatabase : System.Data.SqlClient.SqlError: Cannot open backup device 'D:\Backups\161017081747.bak'. Operating system error 
5(Access is denied.).
At BackupSQLDatabase:10 char:10

    + CategoryInfo          : InvalidOperation: (:) [Backup-SqlDatabase], SmoException
    + FullyQualifiedErrorId : ExecutionFailed,Microsoft.SqlServer.Management.PowerShell.BackupSqlDatabaseCommand
    + PSComputerName        : [localhost]

Please advise. 


Unable to Install PowerShell V5 preview on Windows 8.1 X64

$
0
0

Over the weekend, I upgraded my laptop to Windows 8.1 Enterprise (with the 8.1 update). All went well but when I go to install the WMF 5.0 preview, i get :

I have .NET 4.5 loaded and here's my winver:

Any clues to what I need to do to get this to work?


Thomas Lee <DoctorDNS@Gmail.Com>


New-PSSession limited to 25

$
0
0

I am trying to start 50 sessions on a server, but once I pass 25 new sessions, I get this error:

New-PSSession : [MyServer] Connecting to remote server systemarchi failed with the following error message : The WS-
Management service cannot process the request. This user has exceeded the maximum number of concurrent shells allowed f
or this plugin. Close at least one open shell or raise the plugin quota for this user. For more information, see the ab
out_Remote_Troubleshooting Help topic.

WinRM settings:

Config
    MaxEnvelopeSizekb = 500
    MaxTimeoutms = 60000
    MaxBatchItems = 32000
    MaxProviderRequests = 4294967295
    Client
        NetworkDelayms = 5000
        URLPrefix = wsman
        AllowUnencrypted = false
        Auth
            Basic = true
            Digest = true
            Kerberos = true
            Negotiate = true
            Certificate = true
            CredSSP = false
        DefaultPorts
            HTTP = 5985
            HTTPS = 5986
        TrustedHosts
    Service
        RootSDDL = O:NSG:BAD:P(A;;GA;;;BA)(A;;GR;;;IU)S:P(AU;FA;GA;;;WD)(AU;SA;GXGW;;;WD)
        MaxConcurrentOperations = 4294967295
        MaxConcurrentOperationsPerUser = 1500
        EnumerationTimeoutms = 240000
        MaxConnections = 300
        MaxPacketRetrievalTimeSeconds = 120
        AllowUnencrypted = false
        Auth
            Basic = false
            Kerberos = true
            Negotiate = true
            Certificate = false
            CredSSP = false
            CbtHardeningLevel = Relaxed
        DefaultPorts
            HTTP = 5985
            HTTPS = 5986
        IPv4Filter = *
        IPv6Filter = *
        EnableCompatibilityHttpListener = false
        EnableCompatibilityHttpsListener = false
        CertificateThumbprint
        AllowRemoteAccess = true
    Winrs
        AllowRemoteShellAccess = true
        IdleTimeout = 7200000
        MaxConcurrentUsers = 10
        MaxShellRunTime = 2147483647
        MaxProcessesPerShell = 52
        MaxMemoryPerShellMB = 1024
        MaxShellsPerUser = 52

I have other servers, where i'm not limited to 25 sessions. Does anyone have a clue where to fix this?


Powershell GUI for remote-connection

$
0
0

Hi folks

I wrote a script that deploys a new server to ActiveDirectory based on a hostname. It creates a

-computeraccount

-6 securitygroups

-changes membership of those securitygroups

-creates a GPO

-changes GPO filtering

-links the GPO to the server-OU

After some jokes, I wrote a GUI for the script and now everybody seems to like it ;-) .

Until now, the script has to run on a domaincontroller. My last idea was to make it run from our jumphosts. So I tried to add a textbox to specify a hostname and a button that executes something like "enter-pssession -computername $hostname -credentials $creds" .

Is something like this possible? Without the GUI, I think it shouldn't be a big deal - but when using a button?

Thanks a lot for any help and best regards, Sven

Awesync auto configuration WASP

$
0
0

Im trying to make a script that can auto configure a program called Awesync which can sync Calender with Gmail calender

Im using the module WASP for it

It works fine on the first window with the commands here

Select-Window $ProcessName | Set-WindowActive
Select-Window $ProcessName | Send-Keys '{TAB}'
Select-Window $ProcessName | Send-Keys '{ENTER}'

After that it opens the settings window in awesync and from there it dosent respond with the Send-Keys commands

i have tried with Select-ChildWindow command but it dosent seem to work either

Trouble with appending CSV Report

$
0
0

Hi all

I ama having trouble updating a report csv with the error reference. Instead my report shows this under the Error column

Cannot append CSV content to the following file: C:\PS\Reports\SecurityGroups.csv. The appended object does not have a property that corresponds to the following column: Error. To continue with mismatched properties, add the -Force parameter, and then retry the command.

I have also noticed my report doesnt have SUCCESS but the green text is displayed.

$csv = import-csv C:\ps\import\SecurityGroups.csv
#$csv = import-csv C:\ps\import\SecurityGroups_Test.csv


foreach ($row in $csv) {

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

try {
    if ($row.GroupName)

            {

            write-host -ForegroundColor cyan "Group "$($row.GroupName)"with"$($row.members)""

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

            write-host -ForegroundColor green "Group "$($row.GroupName)"was created successfully"

            $row | select GroupName, @{n='Result';e ={"Success"}} | Export-csv C:\PS\Reports\SecurityGroups.csv -NoTypeInformation -Append

            }

            Else

            {

            write-host -ForegroundColor magenta "Group "$($row.GroupName)"failed.See Report"

            $row | select GroupName,@{n ='Result';e={"Failed"}},@{n='Error';e ={$error[0].Exception.Message}} | Export-csv C:\PS\Reports\SecurityGroups.csv -NoTypeInformation -Append

            }

}



            Catch [system.exception] { write-host -ForegroundColor red "Group "$($row.GroupName)"failed.See Report"

                $row | select GroupName, @{n='Result';e={"Failed"}},@{n='Error';e ={$error[0].Exception.Message}} | Export-csv C:\PS\Reports\SecurityGroups.csv -NoTypeInformation -Append
            }


            }
        }
    
 

My Report CSV

"GroupName","Result","Error"
"Group 1 (Domain Local)","Failed","Cannot append CSV content to the following file: C:\PS\Reports\SecurityGroups.csv. The appended object does not have a property that corresponds to the following column: Error. To continue with mismatched properties, add the -Force parameter, and then retry the command."

My report CSV shows the correct headings etc

I have no idea what is going on :( please help!


ForEach loop does not working. Error: Cannot convert value to type System.String.

$
0
0

Hi,

I have written a function to get event logs from multiple machine as below. But getting error 'Cannot convert value to type System.String.' when passing a text file of computers using $comp = Get-Content -path 'file path'.

$Comp = Import-csv -Path 'CSV path'

Get-EventLogReport -Computer $Comp -Before '10/10/2016' -After 10/09/2016 -LogName 'System' -CSVPath C:\3.csv -Newest 5

Scripts:   

Function Get-EventLogReport
{
[CmdletBinding()]
param
(

        [Parameter(Mandatory=$true)][string]$Computers,
        [Parameter(Mandatory=$true)][string]$Before,
        [Parameter(Mandatory=$true)][string]$After,
        [Parameter(Mandatory=$true)][string]$CSVPath,
        [Parameter(Mandatory=$true)][string]$LogName,
        [Parameter(Mandatory=$false)][int]$Newest
        
)
foreach ($Computer in $Computers)
{
Write-verbose 'Processing the Event Logs on each server' -Verbose
if (!($Newest))
{
Get-EventLog -ComputerName $Computers -LogName $LogName -EntryType Warning,Error | Select-Object -Property * | Export-CSV -Path $CSVPath -NoTypeInformation
}
else
{
Get-EventLog -ComputerName $Computers -LogName $LogName -Newest $Newest -EntryType Warning,Error | Select-Object -Property * | Export-CSV -Path $CSVPath -NoTypeInformation
}
}
Write-Verbose 'Event log is processed and exported to CSV file' -Verbose
}


I am sure issue is with foreach but unable to fix it since morning.

Script is working fine when i am using -computername $env:computername

Thanks in advance

Roushan

Viewing all 21975 articles
Browse latest View live


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