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

Signing Powershell Script Returns and "UnknownError" Status

$
0
0

I am trying to self sign some scripts  but keep getting a status of "UnknownError" after the script completes successfully. The strange part is, the script does complete and sign the certs, it just gives a UnknownError status afterwards.

Could someone please assist?

$cert = Get-ChildItem -Path Cert:\LocalMachine\My\XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Set-AuthenticodeSignature C:\scripts\patching-TEST-v2.ps1 -Certificate $cert


SignerCertificate                         Status                                                       Path
-----------------                         ------                                                       ----
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX  UnknownError                                                 patching-TEST-v2.ps1                                       

Here is how I created the cert:

New-SelfSignedCertificateEx -Subject "CN=Generic Powershell CSC" -EnhancedKeyUsage "Code Signing" -StoreLocation LocalMachine -Exportable

However, when I do a Get-ChildItem on the cert, the EnhancedKeyUsageList does not list anything

PS C:\Windows\system32> Get-ChildItem -Path Cert:\localmachine\my\XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX | Format-List -Property *


PSPath               : Microsoft.PowerShell.Security\Certificate::localmachine\my\XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
PSParentPath         : Microsoft.PowerShell.Security\Certificate::localmachine\my
PSChildName          : XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
PSDrive              : Cert
PSProvider           : Microsoft.PowerShell.Security\Certificate
PSIsContainer        : False
EnhancedKeyUsageList : {}
DnsNameList          : {}
SendAsTrustedIssuer  : False
Archived             : False
Extensions           : {System.Security.Cryptography.Oid, System.Security.Cryptography.Oid, System.Security.Cryptography.Oid}
FriendlyName         :
IssuerName           : System.Security.Cryptography.X509Certificates.X500DistinguishedName
NotAfter             : 5/24/2017 4:16:03 AM
NotBefore            : 5/24/2016 4:16:03 AM
HasPrivateKey        : True
PrivateKey           : System.Security.Cryptography.RSACryptoServiceProvider
PublicKey            : System.Security.Cryptography.X509Certificates.PublicKey
RawData              : {48, 130, 3, 20...}
SerialNumber         : XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
SubjectName          : System.Security.Cryptography.X509Certificates.X500DistinguishedName
SignatureAlgorithm   : System.Security.Cryptography.Oid
Thumbprint           : XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Version              : 3
Handle               : 641073664
Issuer               : CN=Generic Powershell CSC
Subject              : CN=Generic Powershell CSC



List users in OU - Not Expired and Not Enabled

$
0
0

Hi

I am currently doing a full audit on our AD environment and need reporting back all user accounts that are live within each site OU we have, that meet the following criteria

-Not Disabled
-Not Expired
-User has logged on in the past 90 days

So far i have the following but only shows users that have accounts Enabled in the SITEA ou, i am struggling to add the logged on in last 90 days and account has not expired syntax

Get-ADUser -SearchBase "OU=SITEA,DC=MY,DC=COMPANY,DC=CO,DC=UK" -Filter * |where { $_.enabled -eq $false}| Sort-Object name | select name | Export-Csv 'c:\scripts\sitea.csv'

Any help would be appreciated

Barrie

Can see values from parsed JSON object, but they present as null on PSv2

$
0
0

Code:

[System.Reflection.Assembly]::LoadWithPartialName("System.Web.Extensions") | out-null
$web_client = new-object system.net.webclient
$npi="randomNPInumberfromNPPES"
$jsondownload = "https://npiregistry.cms.hhs.gov/api/?number=" + $npi
$build_info=$web_client.DownloadString($jsondownload)
$ser = New-Object System.Web.Script.Serialization.JavaScriptSerializer
$obj = $ser.DeserializeObject($build_info)
#$obj.results.basic.name
Write-Host "Taxonomies for" $npi
$obj.results.taxonomies.code

(of course, it needs a real NPI number, but that's it)

When I am on my Windows 10 workstation at home with PS5, I can access and call all the elements of the deserialized JSON. When I am on my Windows 7 workstation at work with PS2, I cansee them, but nothing returns when I call them directly.

$obj.results

                                                                                          

Key                Value                                                                                                   
---                -----                                                                                                   
taxonomies         {System.Collections.Generic.Dictionary`2[System.String,System.Object]}                                   
addresses          {System.Collections.Generic.Dictionary`2[System.String,System.Object], System.Collections.Generic.Dict...
created_epoch      1196294400                                                                                              
identifiers        {}                                                                                                      
other_names        {}                                                                                                      
number             randomNPInumberfromNPPES                                                                                              
last_updated_epoch 1387411200                                                                                              
basic              {[status, A], [credential, ANP], [first_name, FakeFirstName], [last_name, FakeLastName]...}                             
enumeration_type   NPI-1        

On my Windows 10 PSv5, I can call $obj.results.created_epoch and 1196294400 returns. I do the exact same thing on the W7 PSv2 desktop, andwhile I can still see it (see above paste) when I do $obj.results, when I do $obj.results.created_epoch, no value returns.

I'm losing my mind - I was so happy when I figured out that my PSv2 could use System.Web.Extensions so I could parse JSON, but now I'm really lost. It's maddening because I can see the results on both installations, but can only access the actual values in v5. I've searched everywhere and I can't find a solution - I'm sure it's something ridiculous.

Please help :(

Failover Clustering - File Share Witness - Policies

$
0
0

Hi,

I'm currently trying to automate some parts of a clustered build and I need to be able to modify the File Share Witness - Policies within PowerShell, can anybody point me in the right direction of the commands please?

To get to these settings I am going to the Policies Tab on the Fire Share Witness and then changing the values under this tab.

I've tried the obvious stuff like get-quorum, set-quorum etc but the settings you can modify seem limited at best...

Please see the screen shot below -

Thanks

Getting Error while running Get-DscConfiguration in Windows Server 2008 R2

$
0
0

Hi ,

I am trying to run "Get-DscConfiguration -Verbose" in server 2008 R2 in order to upload the output of it Pull Server using POST method. But I am getting following error :

Get-DscConfiguration : Current configuration does not exist. Execute Start-DscConfiguration command 
with -Path parameter to specify a configuration file and create a current configuration first.At 
line:1 char:1
+ Get-DscConfiguration -Verbose
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (MSFT_DSCLocalConfigurationManager:root/Microsoft/...gura 
   tionManager) [Get-DscConfiguration], CimException
    + FullyQualifiedErrorId : MI RESULT 1,Get-DscConfiguration

The same works pretty well for 2012 server and I able to upload the same.


Regards,

Sudhakar

Show PSComputerName in a one-liner

$
0
0

Is there a way to include the PSComputerName, which is collected early on in the pipeline, to the final out of this one-liner?

Get-CimInstance Win32_Process -Filter "Name = 'iexplore.exe'" -ComputerName $MyServers | % {Invoke-CimMethod -InputObject $_ -MethodName GetOwner | Select User, PSComputerName} | % {Get-ADUser $_.User -Properties EmailAddress | Select EmailAddress}

So besides EmailAddress of the person, I want to include the server name where that user is running the process?  Or is this just something that require multiple statements?

Thanks

NK

Output DNS Duplicates - Include Name, IP, TimeStamp, RecordType

$
0
0

Hi. I came across this powershell script and would like to modify to include TimeStamp + RecordType values.

I tried adding additional columns. The column headings output but no values so I guess I did it wrong :)

[quote]

# Using WMI, retrieve all the duplicate DNS records


$DNS

=Get-WmiObject-ComputerName'MyServer'`

  

-Namespace'root\MicrosoftDNS'`

  

-ClassMicrosoftDNS_AType`

  

-Filter"ContainerName='MyZone'"|`


Group-Object

OwnerName|Where-Object{$_.Count-gt1}



# Create our CSV file to hold the data


$file

='c:\scripts\DNSDuplicates.csv'


New-Item

-ItemTypefile-Path$file-Force


Add-Content

-Path$file-Value"Name,IPAddress"


# Iterate of the DNS items grabbing the name and IPAddress


foreach

($itemin$DNS) {

   

foreach($IPAddressesin$item.Group) {

       

$value="{0},{1}"-f$item.name,$IPAddresses.IPAddress

       

Add-Content-Path$file-Value$value


    }

}

[/quote]

Can any of you gurus assit?

Kind Regards,

Phil

Trying to use Get-Mailbox

$
0
0

I am trying to get a script that prompts the user to enter a username to search, and then returns with the name, how much storage they have used, and all the quotas set for that user. But I am having troubles using Get-Mailbox a second time in the script. It seems to get completely ignored when I am running it, but compiles perfectly fine and I don't have any errors.

Why is the second Get-Mailbox ignored? What can I do to still have everything in the same script?

I've found that the Get-Mailbox still runs, but the table it should output is being ignored. I have tried using other things such as Write-Output $x after storing my second Get-Mailbox into $x but it still does not display in the script. Can I not show 2 different tables in the same script?

. 'C:\Program Files\Microsoft\Exchange Server\V15\bin\RemoteExchange.ps1'; Connect-ExchangeServer -auto
$user = Read-Host -Prompt 'Enter Username to Check Quota'

Get-Mailbox -Identity $user | Get-MailboxStatistics | Select DisplayName, `

  @{name=”TotalItemSize (MB)”; expression={[math]::Round( `

  ($_.TotalItemSize.ToString().Split(“(“)[1].Split(” “)[0].Replace(“,”,””)/1MB),2)}} `
  , StorageLimitStatus

Get-Mailbox -Identity $user | Select Name,ProhibitSendQuota,IssueWarningQuota,ProhibitSendReceiveQuota 



Unicode \u2019 error

$
0
0

Hi, I am running a cURL to return data. I am getting a txt file that I then translate in to CSV by using this function:

$xslt = New-Object System.Xml.Xsl.XslCompiledTransform;
$xslt.Load($xsl);
$xslt.Transform($xml, $output);

The problem is that I am returning characters other than English, and I am getting an error related to the unicode \u2019.

What would be the best approach to this. In Unix I would use xtslproc and recode html the text file, but somehow, I don't find any equivalence with Powershell.

Thanks


PowerShell 3: Can't execute scripts from Windows Explorer context menu

$
0
0

After updating PowerShell to v3 on my Windows Server 2008 R2 machine I don't seem to be able to run PowerShell scripts from the "Run with PowerShell" context menu item of Windows Explorer for my .ps1 files.

Those scripts did execute perfectly well until now. They still do execute from within ISE and from within an opened PowerShell console window. But they don't execute from that Windows Explorer context menu item anymore.

Why?

This is the error message I'm getting (translated from German):

No parameter found matching name "Command".
   + CategoryInfo  : InvalidArgument (:) [Run.ps1], ParentContainerErrorRecordException
   + FullyQualifiedErrorId  : NamedParameterNotFound,Run.ps1

Microsoft Marketing should care for customer feedback on their consumer products, e.g.Windows& Office.

Write-DFSRHealthReport not working for "Domain System Volume" (SYSVOL)

$
0
0

Hello all,

I'm trying to figure out how to check the DFSR Health of our SYSVOL folder, but theWrite-DFSRHealthReport doesn't seem to work with the Replication Group "Domain System Volume", which is where SYSVOL is. The cmdlet will work with other Replication Groups, but not the "Domain System Volume" Replication Group.

I have tried the following command from one of our Domain Controllers, and I get the error that"no replication groups found named: "Domain System Volume"

Write-DfsrHealthReport -GroupName "Domain System Volume" -MemberComputerName "DC1" -Path "C:\DFSReports" -ReferenceComputerName "DC1"

I know this replication group is present, and it can even be seen by running theGet-DfsReplicationGroup cmdlet.

I was hoping to get this working with the new DFSR PowerShell cmdlets and not use the old CMD DFSR tool, and I was hoping that someone had experienced this issue and found a solution?

GetResponse with "0" argument(s): "The operation has timed out

$
0
0

I have created a job that opens a webpage on our internal LAN. The webpage takes 4 to 5 minutes to complete it's process which is expected so I set a high timeout of 10 minutes.
 The powershell job seems to run fine but I always get an error for getresponse get This is the error
The corresponding line is '$response = $request.GetResponse()   '. Correct the script and reschedule the job. The error information returned by PowerShell is: 'Exception calling "GetResponse" with "0" argument(s): "The operation has timed out" 

Code:

$request =[System.Net.WebRequest]::Create("http://myinternalsite.com")
$request.timeout = 60000; # 10 Minutes
$response = $request.GetResponse()
$response.Close()
I tried searching for a solution but nothing seemed to help me.
How can I resolve this issue? 
Thanks


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?

Calling multiple WmiObject classes; appending results to a single string?

$
0
0

Hi Everyone,

How can I call multiple classes and return the results to a single string?

E.G. If I have:

$CompInfo = Get-WmiObject -Class Win32_ComputerSystem -computername $computer | Select-Object Name, Model | ConvertTo-HTML -fragment

$OS = Get-WmiObject -Class Win32_OperatingSystem -computername $computer | Select-Object Caption, Status | ConvertTo-HTML -fragment

How can I have powershell return:

Name        Model                             Caption                                                             Status
SERVER    ProLiant DL360p Gen8    Microsoft Windows Server 2012 R2 Standard    OK

Instead of

Name       Model

SERVER    ProLiant DL360p Gen8

Caption                                                              Status

Microsoft Windows Server 2012 R2 Standard      OK

Thanks.


Need help on a script i created to provision host name based site collection.

$
0
0
I created a script which provisions a host name based site collection. The issue is when it creates the site collection, it gives it a url as ($webappurl +$sitecollection.url) ie if the web application is test.dev.com and site collection is test2.dev.com then it will create the site collection as test.dev.test2.dev.com  . I tried to modify the script by removing the $webappurl but it gives me all sorts of errors like invalid uri etc. Kinda stuck there . I am attaching the script and the config file which it looks up for. Desired result is creating the site collection with url test2.dev.com 
Param(
 [Parameter(Mandatory=$true)]
 [string]$PathofConfigFile
 )


function DeployFeatures($featureList, $url) {

   Write-Host "Activating Features......" -ForegroundColor Green

   foreach ($feature in $featureList) {
		if ($feature.Name -and $feature.Id) {
			$featurePath = $feature.Name

			Write-Host "Activating Feature: $featurePath"
			$SPFeature = Get-SPFeature | Where-Object { $_.Id -eq $feature.Id }

			if(!$SPFeature.Id) {
				$status = Install-SPFeature $featurePath -force
			}


            $status = Enable-SPFeature -Identity $feature.Id -Url $url -force

		}
		else {
			Write-Host "Failed to enable feature, ensure you have specified Id and Name." -foregroundcolor Red
		}
	}
}

function ProvisionWeb($webList, $url, $rootUrl, [int]$level) {
	foreach($web in $webList) {
		$rootUrl = $rootUrl -replace "/$", ""

		$url = $url -replace "/$", ""
		$WebUrl = $url + $web.Url
		$WebUrl = $WebUrl -replace "/$", ""

		$WebName = $web.Name
		$WebTemplate = $web.Template

		$exists = (Get-SPWeb $WebUrl -ErrorAction SilentlyContinue) -ne $null

        if ($exists)
        {
            Write-Host "Existing the web at $WebUrl" -ForegroundColor Yellow
        }
        else
        {
            Write-Host "Creating new web at $WebUrl" -ForegroundColor Green
		    if($level -eq 0) {
			    #$NewWeb = New-SPWeb $WebUrl -Template $WebTemplate -Addtotopnav -Useparenttopnav -Name $WebName
                $NewWeb = New-SPWeb $WebUrl -Template $WebTemplate -Useparenttopnav -Name $WebName
		    } else {
			    $NewWeb = New-SPWeb $WebUrl -Template $WebTemplate -Useparenttopnav -Name $WebName
		    }
		    # Deploy features
		    DeployFeatures $web.SelectNodes("Features/Feature") $WebUrl

            Write-Host "Title: " $NewWeb.Title -foregroundcolor Green
		    Write-Host "URL: " $NewWeb.Url -foregroundcolor Green

             #Check if Enable Show Subsites
            if ($web.ShowSubsites -eq $true)
            {
                $pubWeb = [Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($NewWeb)

                $pubWeb.Navigation.GlobalIncludeSubSites = $true
                $pubWeb.Navigation.GlobalIncludePages = $false
                $pubWeb.Update()
                $NewWeb.Dispose()
            }

        }

        # Provision Lists
        Write-Host "Provisioning Lists..." -ForegroundColor Green
        ProvisionLists $web.SelectNodes("Lists/List") $WebUrl

		# Create child webs
		foreach($childWeb in $web.SelectNodes("Web")) {
			ProvisionWeb $childWeb $WebUrl $rootUrl ($level + 1)
		}
	}
}


function ProvisionLists($lists, $url)
{
    $CurrentWeb = Get-SPWeb $url

    foreach($list in $lists){

    $checkList = $CurrentWeb.Lists.TryGetList($list.Title)

    if ($checkList -eq $null)
    {
        if ($list.Template -eq "Asset Library")
        {
            $template = $CurrentWeb.ListTemplates[$list.Template]
        }
        elseif ($list.Template -eq "Content Library")
        {
            $template = $CurrentWeb.ListTemplates | Where-Object {$_.Type -eq 30000}
        }
        else
        {
            $template = [Microsoft.SharePoint.SPListTemplateType]::($list.Template)
        }


        $CurrentWeb.Lists.Add($list.Url,$list.Description, $template)
        $CurrentWeb.Update()
        $mylist = $CurrentWeb.Lists[$list.Url]
        $mylist.Title = $list.Title

        if (($list.Template -eq "Asset Library") -or ($list.Template -eq "DocumentLibrary") -or ($list.Template -eq "PictureLibrary"))
        {
            if ($list.EnableVersion -eq $true)
            {
                $mylist.EnableMinorVersions = $true
            }

            if ($list.RequireCheckOut -eq $true)
            {
                $mylist.ForceCheckout = $true
            }

            if ($list.RequireApproval -eq $true)
            {
                $mylist.EnableModeration = $true
            }

        }

        $mylist.Update();
        Write-Host $mylist.Title successfully created -ForegroundColor Green


        #Create Folders
        try{
            foreach($folder in $list.Folders.Folder){
                $mylist.RootFolder.SubFolders.add($folder);
            }
        }catch{
            # if it crashed here, the configuration did not include folders
            Write-Host Configuration did not include folders -ForegroundColor Yellow
        }

    }
    else
    {
        Write-Host $list.Title has already existed -ForegroundColor Yellow
    }

    }
}




function ProvisionSiteCollections($siteCollections, [string]$rootUrl)
{
	if($siteCollections -ne $null)
	{
		if($siteCollections.Item(0).Deploy -eq $false) {
			return
		}

		Write-Host "Provisioning Site Collections" -ForegroundColor Green

		$siteCollectionList = $siteCollections.Item(0).SelectNodes("SiteCollection")

		$webApp = Get-SPWebApplication $rootUrl


		foreach($SiteCollection in $siteCollectionList) {

            $ContentDB = $SiteCollection.SelectNodes("ContentDatabase")
            if ($ContentDB -ne $null)
            {
                $databaseServer = $ContentDB.Server
                $databaseName = $ContentDB.Name

                if ($SiteCollection.Url -eq "/") {
				$SiteUrl = ($WebAppUrl + $SiteCollection.Url)
			    } else {
				    if (($SiteCollection.ManagedPath -eq $null) -or ($SiteCollection.ManagedPath.Trim() -eq "") ) {
                        $SiteUrl = ($WebAppUrl +  $SiteCollection.Url)
				    } else {
					    $SiteUrl = ($WebAppUrl + $SiteCollection.ManagedPath + $SiteCollection.Url)
				    }
			    }

			    $SiteUrl = $SiteUrl -replace "/$", ""


                try
                {
                 $ContentDB = Get-SPContentDatabase -site $SiteUrl -ErrorAction SilentlyContinue
                }
                catch{ $ContentDB = $null}

                #check databas exists?
                if ( $ContentDB -ne $null) { $exists = $true } else { $exists = $false }

                if ($exists) {
                    Write-Host "[Warning] Database with name $databaseName already exists on SQL Server $databaseServer" -ForegroundColor Yellow
                }
                else
                {
                    try
                    {

                    Write-Host "Creating Content database $databaseName on $databaseServer" -ForegroundColor Green

                    $db = New-SPContentDatabase -Name $databaseName -WebApplication $webApp -DatabaseServer $databaseServer
                    }
                    catch
                    {
                        Write-Host "Failed to create content database...." -ForegroundColor Red

                        return
                    }
                }


            }


			$SiteCollectionName = $SiteCollection.Name
			$SiteCollectionOwner = $SiteCollection.OwnerAlias
			$SiteCollectionTemplate = $SiteCollection.Template

            try
            {
             $targetUrl = Get-SPSite -Identity  $SiteUrl -ErrorAction SilentlyContinue
            }
            catch{ $targetUrl="" }

			if ($targetUrl.Url.Length -gt 0) {
				Write-Host "Existing site at" $SiteUrl -ForegroundColor Yellow
                $CurrentSite = Get-SPSite $SiteUrl
                $RootWeb = $CurrentSite.RootWeb
			}
            else
            {
			    Write-Host "Creating new site collection at" $SiteUrl -ForegroundColor Green
                if ($ContentDB -ne $null)
                {
			        $NewSite = New-SPSite -URL $SiteUrl -OwnerAlias $SiteCollectionOwner -ContentDatabase $db -Template $SiteCollectionTemplate -Name $SiteCollectionName -HostHeaderWebApplication $WebAppUrl
                }
                else
                {
                    $NewSite = New-SPSite -URL $SiteUrl -OwnerAlias $SiteCollectionOwner -Template $SiteCollectionTemplate -Name $SiteCollectionName -HostHeaderWebApplication $WebAppUrl
                }

			    $RootWeb = $NewSite.RootWeb


                #Check if Enable Show Subsites
                if ($SiteCollection.ShowSubsites -eq $true)
                {
                    $pubWeb = [Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($RootWeb)

                    $pubWeb.Navigation.GlobalIncludeSubSites = $true
                    $pubWeb.Navigation.GlobalIncludePages = $false
                    $pubWeb.Update()
                }

			    Write-Host "Site collection created successfully" -ForegroundColor Green
			    Write-Host "Title:" $RootWeb.Title -foregroundcolor Green
			    Write-Host "URL:" $RootWeb.Url -foregroundcolor Green
            }

            DeployFeatures $SiteCollection.SelectNodes("Features/Feature") $RootWeb.Url

            # Provision Lists
            Write-Host "Provisioning Lists..." -ForegroundColor Green
            ProvisionLists $SiteCollection.SelectNodes("Lists/List") $RootWeb.Url

            # Provision Sub-Sites
            Write-Host "Provisioning Sub-Sites..." -ForegroundColor Green
			ProvisionWeb $SiteCollection.SelectNodes("Web") $RootWeb.Url $RootWeb.Url "0"
		}
	}
}

function InitApplication()
{
	Write-Host "Initializing ..." -ForegroundColor Green

	$snapin = Get-PSSnapin | Where-Object {$_.Name -eq 'Microsoft.SharePoint.Powershell'}
	if ($snapin -eq $null) {
		Write-Host "Loading SharePoint Powershell Snapin"
		Add-PSSnapin "Microsoft.SharePoint.Powershell"
	}


}

try
{
	[xml]$ConfigFile = Get-Content $PathofConfigFile
}
catch
{
	Write-Host "Failed to load the configuration file (Config.xml), ensure it's in the same directory as the script" -ForegroundColor Red

	return
}

$ServiceAccountId = $ConfigFile.Setup.ServiceAccount.UserId
$ServiceAccountPwd = $ConfigFile.Setup.ServiceAccount.Password

Write-Host $ServiceAccountId " , password is " $ServiceAccountPwd

$WebAppUrl = $ConfigFile.Setup.WebAppUrl -replace "/$", ""

Write-Host $WebAppUrl

# initialize the script
InitApplication

# deploy site collections
ProvisionSiteCollections $ConfigFile.SelectNodes("/Setup/SiteCollections") $WebAppUrl

Write-Host "Site Structure Provisioning Process has been completed ..." -ForegroundColor Green

<?xml version="1.0" encoding="UTF-8"?>

-<Setup WebAppUrl="http://test.dev.com">


-<SiteCollections>


-<SiteCollection ShowSubsites="true" Template="BDR#0" OwnerAlias="dev\spdevfarmsetup" Url="test2.dev.com" Name="Unit Share"><ContentDatabase Name="SP2013_test_ContentDB" WarningSiteCount="80" MaxSiteCount="100" Server="enadev2.dev.com"/>


-<Features><Feature Name="PremiumSite" Id="8581a8a7-cf16-4770-ac54-260265ddb0b2"/><Feature Name="PublishingSite" Id="f6924d36-2fa8-4f0b-b16d-06b7250180fa"/><Feature Name="BaseSite" Id="b21b090c-c796-4b0f-ac0f-7ef1659c20ae"/><Feature Name="PremiumWeb" Id="0806d127-06e6-447a-980e-2e90b03101b8"/><Feature Name="BaseWeb" Id="99fe402e-89a0-45aa-9163-85342e865dc8"/><Feature Name="PublishingWeb" Id="94c94ca6-b32f-4da9-a9e3-1f3d343d7ecb"/></Features>


-<Lists><List Template="DocumentLibrary" Url="UnitShare" RequireApproval="false" RequireCheckOut="false" EnableVersion="false" Description="Unit Share Library" Title="Unit Share"/></Lists><Web ShowSubsites="true" Template="SRCHCEN#0" Url="/search" Name="Search Center"/></SiteCollection></SiteCollections></Setup>


Offce 365: Assigning calendar permissions via security groups/bulk calendar sharing

$
0
0

I originally posted this in the 365 forums but was informed to post it here instead...

I'm looking for a way to do bulk calendar sharing of individual calendars (not Public Folders) in Exchange Online.

I have a client looking to share every employee's calendar with every single employee in their organization.

They have 16 employees so if I did the usual PowerShell command below I'd have to enter it some 250+ times.

Add-MailboxFolderPermission –Identity user1@domain.com:\Calendar -AccessRight Editor -User user2@domain.com

I created a security group and added all of the employees to it.  Now if I can run a PowerShell command to assign calendar permissions to that security group and I can drastically cut down my admin work.  In theory I can run the PowerShell command one time for each staff member (so 16 times) and have all of the necessary permissions assigned.

If that method isn't possible then what's the best practice for getting this done?

Wndows Task Scheduler Not Executing PS Script

$
0
0

Hi I have a script which reads files from a network path and uploads to sharepoint library and then moves to another archive folder.

It works fine if I run it manually

When I schedule it, in the task scheduler it says running and then after sometime ready state with (0x1) as code

When I schedule from task scheduler, I have a service account with admin privileges over the network path.

I have given these paramters

Start Program : Powershell

Add arguments : -executionpolicy bypass -Command & {"\\server1\data02\spscandocs\spupload.ps1"}

Start in : \\server1\data02\spscandocs

Any idea what I m doing wrong here

S



Sharepoint batch delete from cvs file Powershell script not working

$
0
0

Hi,

I'm trying to use a Powershell script to check if a SharePoint list contains items from a cvs file. If there is a match the script should delete the item from the SharePoint list and move on to the next row.

The code was something I found here: http://sharepointcherie.blogspot.nl/2014/01/use-powershell-to-edit-delete-and-add.html

I used the first part of the code and changed the "exists = 0" to "exists =1" and "if ($exists -eq 0)" to "if ($exists -eq 1)". This because the original code was to remove items when the item was not in the csv list. Also I changed the "if ($item.Title -eq $row.PID)" to "if ($item.<columnname> -eq $row.<columnname>)" because I have a different column I needed to compare than the Title or PID.

Unfortunately it didnt work. Can someone help me to make this work?

#specify file and check to see if it exists.  If it does, continue operations
$csvVariable= Import-CSV "\\networkpath\MyFile.csv"
if ($csvVariable) {"File exists"} else {exit}

# Check if the Sharepoint Snapin is loaded already, and load if not
if ( (Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null )
{Add-PSSnapin Microsoft.SharePoint.PowerShell}
$WebURL = "http://mySharePoint/sites/mysharepointsite"#site name
$listName = "MyListName" # list name
$web = Get-SPWeb -identity $WebURL #Get the SPWeb object and save it to a variable
$list = $web.Lists[$listName] #Get the SPList object to retrieve the list
$items = $list.items #Get all items in this list and save them to a variable

#loop through SharePoint list and delete items that don't appear in csv file
    foreach($item in $items)
    {
      $exists = 0
      #loop through csv and compare item to each row
      foreach ($row in $csvVariable)
      {
        if ($item.Title -eq $row.PID)
        {$exists++}
      }
      #if the item hasn't been found, delete from SharePoint list
      if ($exists -eq 0)
      {$list.GetItemById($item.ID).Delete()}
    }

How to move bulk AD Groups between OU's

$
0
0

Hi Everyone,

I would like to move over 50 AD Groups between OU's and stamp the notes box with a comment. 

I am having trouble with the move to start of, this is the script I found:

$Move=import-csv D:\Temp\Em_Groups.csv
Import-module ActiveDirectory
foreach ($Group in $Groups){
    get-adgroup $Group|move-adobject -targetpath "OU=Cleanup,OU=Disabled Accounts,DC=blue,DC=net"
}

The script is not working (not moving the groups to new OU).

Any ideas please?

M


Maelito

Error "Unable to connect to the remote server" when executed "Invoke-WebRequest" command

$
0
0

Hi there,

I am trying to capture .csv file from REST call. For that I have used Invoke-WebRequest cmdlet. The exact command is as follows:

>>Invoke-WebRequest $url -OutFile $cosmos11_Path -UseDefaultCredentials -TimeoutSec 65535

On executing this, I got this error - Unable to connect to the remote server

If I pasted URL in the browser then I get the CSV file. But command not working.

It was previously working fine. But I am facing this issue from last 4-5 days. Please help me out if anybody have any idea.

Thanks,

Prashant


PSA


Viewing all 21975 articles
Browse latest View live


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