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

Powershell read CSV file line by line and only first header

$
0
0

I have a CSV file, which reads like this:

read, book

read1, book1

read2, book2

I want to read only the first value, before comma one line at time,

meaning first time it will be

read

read1

read2

no headers and i want to pass that value to a variable for a if condition.

I have script it read line by line but it reads both values before coma and after line by line, so instead of having three values i'm ending with 6 values.

$file = Import-CSV c:\script\server.csv

$file | ForEach-Object {
        foreach ($property in $_.PSObject.Properties) 
{        
$property.Name
$property.Value
#replace = $property.Value

}

    }



Error - The remote server returned an error (403) Forbidden

$
0
0

Hello Community,

I'm using PowerShell to upload several files from a local file server into SharePoint Online.  My script was working at one point but now keeps throwing an error:

Exception calling "ExecuteQuery" with "0" argument(s): "The remote server returned an error: (403) Forbidden."
At C:\Users\tsm\Documents\MyScripts\UploadFilesSPO.ps1:52 char:1
+ $Context.ExecuteQuery()
+ ~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : WebException

My script is below:

<#
   Script requirements: O365 tenant, SharePoint Client Components SDK installed to the machine running the script 
   - http://www.microsoft.com/en-us/download/details.aspx?id=35585 
   Variables: Update the $User, $SiteURL, $DocLibName (name of the destination Document library) and 
   $Folder (path to the local folder containing the files to upload) variables   
#>

cls

#Specify tenant admin and site URL
$User = "tsm@tcsc.com"
$SiteURL = "https://mysharepointsite.sharepoint.com/sites/emailenabledlibrary"
$Folder = "C:\UploadFiles"
$DocLibName = "Upload" 
$Password = "MyPassword"


#Add references to SharePoint client assemblies and authenticate to Office 365 site - required for CSOM
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
#$Password = Read-Host -Prompt "Please enter your password" -AsSecureString

#Exit if Local Folder Empty
If ((Get-ChildItem -Force $Folder) -eq $Null) 
{
Exit
}

#Bind to site collection
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User,$Password)
$Context.Credentials = $Creds

#Retrieve list
$List = $Context.Web.Lists.GetByTitle($DocLibName)
$Context.Load($List)
$Context.ExecuteQuery()

#Upload file
Foreach ($File in (dir $Folder -File))
{

$FileStream = New-Object IO.FileStream($File.FullName,[System.IO.FileMode]::Open)
$FileCreationInfo = New-Object Microsoft.SharePoint.Client.FileCreationInformation
$FileCreationInfo.Overwrite = $true
$FileCreationInfo.ContentStream = $FileStream
$FileCreationInfo.URL = $File
$Upload = $List.RootFolder.Files.Add($FileCreationInfo)
$Context.Load($Upload)
$Context.ExecuteQuery()

}

#Pause for Slow Connection
Start-Sleep -s 200

#Delete all Local Folder Files
#$AllFiles = $Folder + "\*"
#Remove-Item $AllFiles -Force

Please provide guidance and code examples.

Thanks!

Tom


Tom Molskow - Senior SharePoint Architect - Microsoft Community Contributor 2011 and 2012 Award - Linked-In - SharePoint Gypsy


PowerShell V2 to SOAP - Trouble Sending Parameters

$
0
0

I am trying to make a PowerShell V2 script to work with an API.  And I am very new to both.   I keep having trouble getting the format of at least one of the parameters required for the API when I try to use the WebserviceProxy method.  So I thought I would try PowerShell to SOAP.  And I am limited to PowerShell V2 on the servers I am working with.  They are not connected to the Internet, and I cannot upgrade them.

This is what the API gives as the example to send it the SOAP POST:

SOAP 1.1
The following is a sample SOAP 1.1 request and response. The placeholders shown need to be replaced with actual values.

POST /ossNotificationsWS/UI.asmx HTTP/1.1
Host: localhost
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "http://tempuri.org/LaunchClientApplication"<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><LaunchClientApplication xmlns="http://tempuri.org/"><externalId /><applicationUri>string</applicationUri></LaunchClientApplication></soap:Body></soap:Envelope>

The "externalId" is the one I am having trouble with.   I pull that down from SQL, and can get it as a string. 

When I have tried the a WebserviceProxy object, I get the error:

New-Object : Constructor not found. Cannot find an appropriate constructor for type Microsoft.PowerShell.Commands.NewWebserviceProxy.AutogeneratedTypes.WebServiceProxy3ssNotifi
cationsWS_UI_asmx_WSDL.ExternalId.
At line:1 char:26+ $deviceValue = New-Object <<<<  ($ns + ".ExternalId")+ CategoryInfo          : ObjectNotFound: (:) [New-Object], PSArgumentException+ FullyQualifiedErrorId : CannotFindAppropriateCtor,Microsoft.PowerShell.Commands.NewObjectCommand

This is my code that I get the above error from:

$uri = "http://STAN01BMGMT101/ossNotificationsWS/UI.asmx"

$proxy = New-WebServiceProxy $uri -Credential $Credential

Try
    {
        Write-Host "Setting up WebProxy using URI and Credentials"
        $script:Proxy = New-WebServiceProxy -Uri $URI -Credential $Credential -ErrorAction Stop
        Write-Host "Successfully connected proxy"
    }
Catch
    {
        Write-Host "Connect-MFASession: $($_.ErrorDetails)"
        Break
    }
$script:Namespace = $Proxy.GetType().Namespace
Write-Host "Set up Namespace for future use"

$ns = $proxy.getType().namespace

$applicationUri = "page:http://stan01mfapplb2.br1.mr.ftc.com/FTCPFApps/STBScrollingMessages/MediaroomPage.aspx"

#Device ExternalID Object 
$ExtID= "002374E4DBEC"

#Add the device value to the device and notify 
#Create the deviceValue object 
$deviceValue = New-Object ($ns + ".ExternalId")

I think I am running into some limitations with PowerShell V2, but not sure.   I would like to use the WebserviceProxy object, but I cannot seem to be able to create it.   I cannot get by the "Constructor not found" error.  

So, any advice or help with this would be greatly appreciated.  I'm stuck.   

Issue with user account creation PS script

$
0
0

I am having an issue with a script that I have been modifying to create AD accounts from a CSV file that gets uploaded on a daily basis. I'll start off by saying that I did not write this script, I found it online and it is available for anyone to use, I have only been modifying it to fit our needs. Also, I am really just getting into using PS more and more and definitely not a pro by any stretch, hence the reason I am here.

I'll try not to make this incredibly long and boring but want you to understand the scripts purpose and where I am having problems at. The script should look for a CSV file and use that file to create/update/disable AD user accounts based on different fields. The script checks for duplicate SAM accounts as part of this process and has a method to come up with a different username if there is a duplicate. Also, based on the "Status" field the script should either enable or disable an existing user account.

The main issue I am currently having is that the account will get created, everything seems to work properly except all accounts will be disabled during the running of the script, regardless of the status field. If I comment out those lines of the script the account will get created and be enabled like it should be so I'm not sure what I am missing.

Also, when a duplicate SAMaccountname is found, the script should come up with a unique name based on defined rules but that does not seem to work properly as I get messages during the New-ADuser command that it fails due to a user with that name already existing. 

I will post the code below and any help or guidance I could get would be greatly appreciated. I am not asking for someone to re-write this and make it work, simply point me in the right direction would be great. Again, I am not great with PS as of yet but do feel I at least understand the flow of this script, just can't seem to understand where it is going wrong at.

# Import the Active Directory functions
Import-Module ActiveDirectory

#Setup some hashtables
#For each school code in your SIS, map it to the appropriate fileserver in the format "schoolcode" = "servername";
#$server = @{"1001" = "fscluster1"; "1002" = "SchoolB-FS"; "1003" = "SchoolC-FS"}
#If you're using standardized abbreviations anywhere (perhaps your groups are named like like SITEA-Students, SITEB-Students etc) It's useful to create a map of those abbreviations
$siteabbr = @{"1001" = "2021"; "1002" = "SITEB"; "1003" = "SITEC"}
#Create a map of codes to Active Directory OUs where students should be moved/created etc. Student grade to grad year mapping.
$orgunits = @{"12" = "2019"; "11" = "2020"; "10" = "2021"; "09" = "2022"; "08" = "2023"; "07" = "2024"; "06" = "2025"; "05" = "2026"; "04" = "2027"; "03" = "2028"; "02" = "2029"; "01" = "2030"; "K" = "2031"; "PK" = "2032"}
#Create a map of grades to email distribution groups.
$emailgroup = @{"12" = "Seniors"; "11" = "Juniors"; "10" = "Sophmores"; "9" = "Freshmen"; "PK" = "PK"}

# Import the Data - This is based on using the accompanying SISsync.sql file to extract data from PowerSchool and expects a tab delimited file, if you're using a CSV from another system or autosend, change `t to , (or omit the delimiter option entirely) and modify the headers appropriately
$sisfile = Import-Csv -delimiter "`t" -Path "C:\TEMP\AD_SYNC\DATA\cts export.txt" -header "grade","givenName","sn","lunchpin","studentid","status"

#Start Processing per file line
foreach ($sisline in $sisfile) {
	#Set the username example below is gradyear+firstinitial+lastname. If a duplicate is found the format will be gradyear+firstthreeletters+lastname.
    $sisline.givenname | ForEach-Object {$firstinitial = $_[0]}
    $givenname = $sisline.givenname
    # $dup variable gets the first three letters of the students first name to use if a duplicate SAMaccountname is found.
    $dup = $sisline.givenname.Substring(0,3)
    $duplicate = $orgunits.Get_Item($sisline.Grade) + $dup + $sisline.sn
   	$sAMAccountName = $orgunits.Get_Item($sisline.Grade) + $firstinitial + $sisline.sn
	#tidy up samaccountName to make it more valid (no spaces, double periods or apostrophies. Helpful for when there's data entry 'issues' in your source
	$sAMAccountName = $sAMAccountName.replace(" ","")
	$sAMAccountName = $sAMAccountName.replace("..",".")
	$sAMAccountName = $sAMAccountName.replace("'","")
    $sAMAccountName = $sAMAccountName.replace("-","")
	#Truncate to 19 characters
	#$sAMAccountName = $sAMAccountName.substring(0,19)
	#Set the displayname for the account in AD example below is firstname space lastname
	$name = $sisline.givenName + " " + $sisline.sn
	#Set a password for the account, example below takes their Lunch PIN (LunchPIN) and assigns it as their initial password
    $pass = "wildcats" + $sisline.lunchPIN 
	$password = ConvertTo-SecureString -AsPlainText $pass -Force
	#Set the UPN for the account for most instances, should be AD Account name + @AD.FQDN. Need to change for each domain!
	$userPrincipalName = $sAMAccountName + "@slater.local"
	#Set the mail attribute for the account (if desired, usually helpful if you're synchronizing to Google Apps/Office 365)
	$mail = $sAMAccountName + "@testschool.net"
	#Set name attributes
	$givenName = $sisline.givenName
	$sn = $sisline.sn
    #Set status variable (if account gets enabled or disabled) Status is determined whether or not there is a value in this field. Only 
    #will have a value if the student has withdrawn from school.
    $status = $sisline.status
	#Store student ID in AD's "EmployeeID" attribute
	$employeeID = $sisline.studentid
	#Optional location attributes, helpful if syncing to Moodle via LDAP
	$c = "US"
	$co = "United States"
	$l = $orgunits.Get_Item($sisline.Grade)
	#Optional other attribute population we set these because they're easy to view with the MMC taskpad we push to secretaries to allow them to reset passwords
	$company = $orgunits.Get_Item($sisline.Grade)
	$physicalDeliveryOfficeName = $sisline.grade
	$description = $orgunits.Get_Item($sisline.Grade)
	$comment = $sAMAccountName + "@slater.local"
	#Create a hashtable of all the "otherattributes" this is used when we create/update the user
	$otherAttributes = @{'userPrincipalName' = "$userPrincipalName"; 'mail' = "$mail"; 'comment' = "$comment"; 'givenName' = "$givenName"; 'sn' = "$sn"; 'employeeID' = "$employeeID"; 'employeeNumber' = "$pass"; 'c' = "$c"; 'l' = "$l"; 'company' = "$company"; 'physicalDeliveryOfficeName' = "$physicalDeliveryOfficeName"; 'description' = "$description"}

	#recast description as a string because AD commands require it and it gets converted to int if it's all numeric.
	$otherAttributes.description = [string]$otherAttributes.description

	#set the path variable to the OU the student should end up in. In the example below the AD OU Structure is Slater -> Test -> Students -> 2021
	$path = "OU=" + $company + ",OU=STUDENT,OU=USERS,OU=MANAGED,DC=slater,DC=local"

	#Check if student exists
	#THIS IS WHERE IT GETS TERRIBLY SLOW IF YOU HAVEN'T ADDED EMPLOYEEID TO THE LIST OF INDEXED AD ATTRIBUTES. STRONGLY CONSIDER THIS.
	$user = Get-ADUser -Filter {employeeID -eq $employeeID}

	if ($user -eq $null) {
		#student doesn't exist, create them
		#find a valid username
		#This is probably the most inelegant backwards way of doing this, but it works. Feel free to improve
		$i = 1 
   		$sAMSearch = $sAMAccountName
		while ((Get-ADUser -Filter {sAMAccountName -eq $sAMSearch}) -ne $null) {		
			$sAMSearch = $duplicate
			$i++
		}
		$i--
		if ($i -ne 0) {
		#name was taken, update constants to reflect new name formart gradyearfirstthreelastname
			$sAMAccountName = $sAMSearch
			$otherAttributes.Set_Item("userPrincipalName", $sAMAccountName + "@slater.local")
			$otherAttributes.Set_Item("mail", $sAMAccountName + "@testschool.net")
			$otherAttributes.Set_Item("comment", $sAMAccountName + "@testschool.net")
			#$name = $name + $i
		}
		#create user using $sAMAccountName and set attributes and assign it to the $user variable
		New-ADUser -sAMAccountName $sAMAccountName -Name $name -Path $path -otherAttributes $otherAttributes -Enable $true -AccountPassword $password -CannotChangePassword $true -PasswordNeverExpires $true 
		$user = Get-ADUser -Filter {employeeID -eq $employeeID}
	} elseif (($user.Surname -ne $sn) -or ($user.givenName -ne $givenName)) {
		#The first or last names were changed in the import source, need to make some changes to the user
		#find a valid username
		#This is probably the most inelegant backwards way of doing this, but it works. Feel free to improve
		$i = 1
		$sAMSearch = $sAMAccountName
		while ((Get-ADUser -Filter {sAMAccountName -eq $sAMSearch}) -ne $null) {		
			$sAMSearch = $duplicate
			$i++
		}
		$i--
		if ($i -ne 0)
		#need to update Name, sAMAccountName, UPN and email because of name collison  
		{
			$sAMAccountName = $sAMSearch
			$otherAttributes.Add("sAMAccountName", $sAMAccountName)
			$otherAttributes.Set_Item("userPrincipalName", $sAMAccountName + "@slater.local")
			$otherAttributes.Set_Item("mail", $sAMAccountName + "@testschool.net")
			$otherAttributes.Set_Item("comment", $sAMAccountName + "@testschool.net")
			$name = $name
		}
		Rename-ADObject -Identity $user $name
		#need to re-key user variable after rename
		$user = Get-ADUser -Filter {employeeID -eq $employeeID}
		#Update AD attributes to reflect changes
		Set-ADUser -Identity $user -replace $otherAttributes -SamAccountName $sAMAccountName
	} else {
		#Update AD Attributes for existing user whos name hasn't changed. Unset anything usernamebased first since the username hasn't changed
		$otherAttributes.Remove("userPrincipalName")
		$otherAttributes.Remove("mail")
		$otherAttributes.Remove("comment")  
		Set-ADUser -Identity $user -replace $otherAttributes
	}
	#reset the samaccountname variable to what it currently queries out of AD as, probably not necessary
	$sAMAccountName = $user.SamAccountName
	#check to see if the DN of the user contains the school name, if not, move it to the correct location
	$properdn = "OU=$company,"
	write-host $properdn
	if ($user.DistinguishedName -notlike "*$properdn*")
	{
		Move-ADObject -Identity $user -TargetPath $path
		$user = Get-ADUser -Filter {employeeID -eq $employeeID}
	}
    # $user = Get-ADUser -Filter {samaccountname -eq $samaccountname}

    write $user
    

    #Enable or disable a user account. This is determined by whether or not there is a value in the 
    #withdrawal date field. If there is a value student is no longer active and should be disabled
    #if there is no value student is active and should be enabled.

    if ($status -ne " "){

    Disable-ADAccount -Identity $user}

    elseif ($status -like " "){

    Enable-ADAccount -Identity $user}

	#Check to see if folders exist on proper server, if not, create them and set permissions.
	#Used to dynamically pick fileserver based on certain field - $servername = $server.Get_Item($sisline.grade)
    $servername = "fscluster1"

	#The example below assumes student home folders exist on \\fileserver\student$\username structure
	$homepath = "\\"  + $servername + "\student$\" + $sAMAccountName
	if ((Test-Path ($homepath)) -ne $true)
	{
		#create folder and set permissions
		#Change DOMAIN below with your AD Domain
		New-Item -ItemType directory -Path $homepath
		$acl = Get-Acl $homepath
		$permission = "slater.local\$sAMAccountName","Modify","ContainerInherit,ObjectInherit","None","Allow"
		$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule $permission
		$acl.SetAccessRule($accessRule)
		$acl | Set-Acl $homepath
	}

	#A quick 100ms pause to make sure the folder has been created and the permissions applied. you may be able to dial that back or remove it entirely	
	Start-Sleep -m 100

	#Set the users homedrive
	Set-ADUser -Identity $user -HomeDirectory $homepath -HomeDrive "H:"

	#Add user to site student group and grad year group also a good place to add any other groups you may require
	#This assumes a security group with the site abbreviation-Students exists and a group called Grad#### exists
	#It doesn't check to see if the user is already a part of these groups, so it will often print an error stating it can't add them because they already exist
	$studentgroup1 = $orgunits.Get_Item($sisline.grade)
    #Add students to the correct email distribution group based on grade level.
    $studentgroup2 = $emailgroup.Get_Item($sisline.grade)
	#$gradgroup = "Grad" + $description
	Add-ADGroupMember $studentgroup1 $user
    #Add-ADGroupMember $studentgroup2 $user
	#Add-ADGroupMember ALL_STUDENT $user

}

#rename.ps1
#Change filename to whatever file needs to be renamed. 
 $fileName = "C:\TEMP\AD_SYNC\DATA\cts export.txt"

# Check the file exists
# if (-not(Test-Path $fileName)) 

# {break}

# Display the original name
"Original filename: $fileName"

$fileObj = get-item $fileName

# Get the date
$DateStamp = get-date -uformat "%Y-%m-%d@%H-%M-%S"

$extOnly = $fileObj.extension

if ($extOnly.length -eq 0) {
   $nameOnly = $fileObj.Name
   rename-item "$fileObj" "$nameOnly-$DateStamp"
   }
else {
   $nameOnly = $fileObj.Name.Replace( $fileObj.Extension,'')
   rename-item "$fileName" "$nameOnly-$DateStamp$extOnly"
   }

# Display the new name
#"New filename: $nameOnly-$DateStamp$extOnly"


#Sorts files by creation date, skips the top twenty newest files and deletes any older than the top twenty. Folder path and number of 
#skipped files can be modified to fit your needs.
Get-ChildItem C:\TEMP\AD_SYNC\DATA\ -Recurse| Where-Object{-not $_.PsIsContainer}| Sort-Object CreationTime -desc| 
    Select-Object -Skip 10| Remove-Item -Force

Here is some of the error messages I get when running the PS script:

PS C:\TEMP\AD_SYNC> C:\TEMP\AD_SYNC\SISsync.ps1
New-ADUser : The server is unwilling to process the request
At C:\TEMP\AD_SYNC\SISsync.ps1:92 char:3
+         New-ADUser -sAMAccountName $sAMAccountName -Name $name -Path  ...
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (CN=GivenName SN...slater,DC=local:String) [New-ADUse 
   r], ADException
    + FullyQualifiedErrorId : ActiveDirectoryServer:0,Microsoft.ActiveDirectory.Management.Comman 
   ds.NewADUser
 
OU=,
Move-ADObject : Cannot validate argument on parameter 'Identity'. The argument is null. Provide a 
valid value for the argument, and then try running the command again.
At C:\TEMP\AD_SYNC\SISsync.ps1:137 char:27
+         Move-ADObject -Identity $user -TargetPath $path
+                                 ~~~~~
    + CategoryInfo          : InvalidData: (:) [Move-ADObject], ParameterBindingValidationExcepti 
   on
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Manageme 
   nt.Commands.MoveADObject
 
Disable-ADAccount : Cannot validate argument on parameter 'Identity'. The argument is null. 
Provide a valid value for the argument, and then try running the command again.
At C:\TEMP\AD_SYNC\SISsync.ps1:152 char:33
+     Disable-ADAccount -Identity $user}
+                                 ~~~~~
    + CategoryInfo          : InvalidData: (:) [Disable-ADAccount], ParameterBindingValidationExc 
   eption
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Manageme 
   nt.Commands.DisableADAccount
 
Set-ADUser : Cannot validate argument on parameter 'Identity'. The argument is null. Provide a 
valid value for the argument, and then try running the command again.
At C:\TEMP\AD_SYNC\SISsync.ps1:180 char:23
+     Set-ADUser -Identity $user -HomeDirectory $homepath -HomeDrive "H ...
+                          ~~~~~
    + CategoryInfo          : InvalidData: (:) [Set-ADUser], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Manageme 
   nt.Commands.SetADUser


Powershell : Checking DNS alias

$
0
0

Hi,

We have 2 servers, one production and one back-up. With a DNS alias everyone connects to the production server. When the backup server becomes operational we just need to change the DNS alias.

Now, I need a script for checking this DNS alias value.

When the DNS alias match with server A, then is this the production server and it must start some services again after a reboot. For server B is not allowed to start some services after reboot because he is the backup server.  The necessary services on both servers will be set on manually. When server B becomes the operational server, we change the DNS alias to server B and reboot both servers. Afterwards the services on server B will start and on server A don't.

Thanks!

Invoke-Restmethod issue with post of Json payload.

$
0
0

I have a problem with Invoke-RestMethod. If I create either a Hashtable or PSCustomObject and convert it to a $Json and then use it in the following expression I get an error.

PS C:\WINDOWS\system32> $response = Invoke-RestMethod 'uri' -ContentType 'application/json' -Method post -Headers $headers –Body $json
Invoke-RestMethod : {"Message":"An error has occurred.","ExceptionMessage":"Object reference not set to an instance 
of an object.","ExceptionType":"System.NullReferenceException","StackTrace":", etc.} 

If I expand the $json and then paste as a value for the -Body parameter I get no error.

$response = Invoke-RestMethod 'uri' -ContentType 'application/json' -Method post -Headers $headers –Body '{}'

I am baffled.

How to add comma to AD displayname

$
0
0

Please could some help me with a powershell script that will make a change in the "Displayname" of  about 300 users in my Active Directory at once. i.e to add comma to the displayname (example Mike Smith to Mike, Smith)

the problem is that its difficult to identify which is the Firstname or the Lastname name when you send an email without the comma added to the displayname.

thanks in advance

Izu

Stuck on a powershell script for SharePoint onine

$
0
0

Background for this request.

Client is looking to move a server based photo library to SharePoint online. The photos are well organised and have been cleaned and a naming convention applied. The photos exist in 2 different folder shares. In one share, the photos are sorted by category and sub category based on the product in the photo. The second share has the identical photos, identically named, but sorted in folders by Customer.

I have written the following powershell to upload the photos from the Category and Sub Category folders, using the folder names they reside in to add metadata.

$connection = Connect-PnPOnline https://some.sharepoint.com -Credentials $me -ReturnConnection
 $MainFolders = get-childitem -directory | where-object {$_.Psiscontainer} | select-object Name
 foreach ($Mfolder in $mainfolders) {
    $LocalFolders = get-childitem -path $Mfolder.Name -Recurse | where-object {$_.Psiscontainer} | select-object FullName    
        foreach ($folder in $localfolders) {
           $files = get-childitem -Path $folder.FullName -Recurse
                foreach ($file in $files) {
                    $value1 = $file.Directory.Name
                Add-PnPFile -Path $file.FullName -Folder Photos -Values @{"Title" = $file.Name;"Category" = $Mfolder.Name;"SubCat" = $value1;} -Connection $connection 
	    }
    }
}

This works and the photos upload and the 2 columns are populated correctly.

I'm now working on a second script to recurse the second folder sorted by company. I want to compare the files and if already exists in SharePoint, then look at which local folder the files is in and use this to update the Customer column.

So far I have this, but I'm sorta at the fringes of my ability in terms of Powershell here.

$connection = Connect-PnPOnline https://somecompany.sharepoint.com -Credentials $me -ReturnConnection
$Folder = "Photos"
$SourcePath = "C:\Test2\"
$Company = get-childitem -directory | where-object {$_.Psiscontainer} | select-object Name 
$DestPath = "$Folder"
$Source = get-childitem -path $SourcePath -Recurse | where-object {-not $_.Psiscontainer} | select-object Name

    foreach ($fileS in $Source) { 
   $Dest = Get-PnPListItem -List $Folder
   Set-PnPListItem -List $Folder -Identity $Dest -Values @{"Customer" = "Company1"}
 }  

Error I am getting is this.

Set-PnPListItem : Cannot convert 'System.Object[]' to the type 'SharePointPnP.PowerShell.Commands.Base.PipeBinds.ListItemPipeBind' required by parameter 'Identity'. Specified method is not supported.
At line:1 char:41+ Set-PnPListItem -List $Folder -Identity $Dest -Values @{"Customer" =  ...+                                         ~~~~~+ CategoryInfo          : InvalidArgument: (:) [Set-PnPListItem], ParameterBindingException+ FullyQualifiedErrorId : CannotConvertArgument,SharePointPnP.PowerShell.Commands.Lists.SetListIte

Any help will be greatly appreciated and I'm keen to learn, so if you have time, please explain the steps you suggest.

Really appreciate this.

Jassen



Get-aduser with some titles

$
0
0
Hi, when I run this command it works but if I want to add another title, how should it looks like then?

$path = "OU=Consultans,DC=domain,DC=net"
$users = get-aduser -SearchBase $path -Filter{title -notlike 'Konsult*' -and enabled -eq $true} -properties * |select employeeNumber,givenname,sn,mail,title,enabled | Out-GridView 

powershell transcript only do with "powershell.exe" pre command

$
0
0
First of all, thanks for the help.

I have enabled the powershell transcript by gpo and in a powershell console, I execute: powershell command and transcribe the file.

If I do not put powershell in front of the command, it is executed (I am in a powershell console) but it does not perform the transcript.

Using the option of start-transcript without GPO, the same thing happens to me.

I would like to know if this behavior is normal, thank you.

http://kinomakino.blogspot.com

Get Multiple variables from psobject into Write-Output string

$
0
0

I am trying to figure out how I can get two columns returned for the following script, as I am only getting one in the resulting text file.

I have a folder full of XML files and need to pull a name value from within each XML, and the date the file was last modified. Both appear to work independently, if I use the script as below.

$path="D:\Data\XML\*.xml"

    Foreach-Object {$array= New-Object psobject -Property @{
        
        Name=Get-ChildItem $path -recurse | % { Get-Content $_} | Select @{n="Name";e={$_ | Select-Xml "//NetBIOSName/text()"}}
        Time=Get-ChildItem $path -recurse | select LastWriteTime 
                }}
                             Write-Output $($array.Name),$($array.Time) | out-file C:\Temp\out2.txt


I get the following result.

Name        
----        
Name1      
Name2
Name3
Name4
Name5
Name6
Name7
Name8
Name9
Name10


If I swap $array.Time and $array.Name around I get the following result.

LastWriteTime      
-------------      
21/01/2019 09:10:24
22/01/2019 13:36:56
22/01/2019 15:05:28
21/01/2019 11:46:00
21/01/2019 15:23:51
21/01/2019 11:26:44
22/01/2019 13:38:18
19/01/2019 10:08:06
21/01/2019 15:07:46
21/01/2019 11:51:03
22/01/2019 13:31:48

What I want is something like this.

Name       LastWriteTime      
-----      -------------      
Name1      21/01/2019 09:10:24
Name2	   22/01/2019 13:36:56
Name3      22/01/2019 15:05:28
Name4      21/01/2019 11:46:00
Name5      21/01/2019 15:23:51
Name6      21/01/2019 11:26:44
Name7      22/01/2019 13:38:18
Name8      19/01/2019 10:08:06
Name9      21/01/2019 15:07:46
Name10     21/01/2019 11:51:03

What am I doing wrong?

Thanks for any help or guidance !




Two Variables for Script to Loop

$
0
0

I'm trying to loop a script I tested which I ran manually. I would like to automate the process by setting up two variables from a list (or csv if it is more efficient to use as 1 file.) 

$PRGNAME = Get-Content C:\temp\names.txt
$PRGID = Get-Content C:\temp\ids.txt

I think I can use a CSV file with headers PRGNAME and PRGID and somehow import those line by line to run the script example I have below. I've just not had success getting a scripted loop to work the way I've attempted. 

Any suggestions?

$PRGIDP = $PRGID + "P"
$PRGIDQ = $PRGID + "Q"
$PRGIDD = $PRGID + "D"

New-item -Name "$PRGNAME" -Path $($SiteCode.name + ":\DeviceCollection\PRGlication Server Collections")
$Collection1 = @{Name = "$PRGNAME | ALL"; Query = "select SMS_R_SYSTEM.ResourceID,SMS_R_SYSTEM.ResourceType,SMS_R_SYSTEM.Name,SMS_R_SYSTEM.SMSUniqueIdentifier,SMS_R_SYSTEM.ResourceDomainORWorkgroup,SMS_R_SYSTEM.Client from SMS_R_System where SMS_R_System.NetbiosName like '%$PRGIDP%' or SMS_R_System.NetbiosName like '%$PRGIDQ%' or SMS_R_System.NetbiosName like '%$PRGIDD%'"}
$Collection2 = @{Name = "$PRGNAME | PROD"; Query = "select SMS_R_SYSTEM.ResourceID,SMS_R_SYSTEM.ResourceType,SMS_R_SYSTEM.Name,SMS_R_SYSTEM.SMSUniqueIdentifier,SMS_R_SYSTEM.ResourceDomainORWorkgroup,SMS_R_SYSTEM.Client from SMS_R_System where SMS_R_System.NetbiosName like '%$PRGIDP%'"}
$Collection3 = @{Name = "$PRGNAME | QA"; Query = "select SMS_R_SYSTEM.ResourceID,SMS_R_SYSTEM.ResourceType,SMS_R_SYSTEM.Name,SMS_R_SYSTEM.SMSUniqueIdentifier,SMS_R_SYSTEM.ResourceDomainORWorkgroup,SMS_R_SYSTEM.Client from SMS_R_System where SMS_R_System.NetbiosName like '%$PRGIDQ%'"}

New-CMDeviceCollection -Name $Collection1.Name -Comment "All Servers" -LimitingCollectionName $LimitingCollectionAll -RefreshSchedule $Schedule -RefreshType 2 | Out-Null
Add-CMDeviceCollectionQueryMembershipRule -CollectionName $Collection1.Name -QueryExpression $Collection1.Query -RuleName $Collection1.Name
Write-host *** Collection $Collection1.Name created ***
New-CMDeviceCollection -Name $Collection2.Name -Comment "All Servers" -LimitingCollectionName $LimitingCollectionAll -RefreshSchedule $Schedule -RefreshType 2 | Out-Null
Add-CMDeviceCollectionQueryMembershipRule -CollectionName $Collection2.Name -QueryExpression $Collection2.Query -RuleName $Collection2.Name
Write-host *** Collection $Collection2.Name created ***
New-CMDeviceCollection -Name $Collection3.Name -Comment "All Servers" -LimitingCollectionName $LimitingCollectionAll -RefreshSchedule $Schedule -RefreshType 2 | Out-Null
Add-CMDeviceCollectionQueryMembershipRule -CollectionName $Collection3.Name -QueryExpression $Collection3.Query -RuleName $Collection3.Name
Write-host *** Collection $Collection3.Name created ***


T.J.

Cut does not remove text from the script pane - PowerShell 5.1 ISE Desktop - Windows 10.0.17134

$
0
0

When I try to cut text in the script pane using either Ctrl+x, Edit>Cut, or the Cut icon in the tool bar the text is not removed from the script pane. It behaves the same as Copy - copies the text to the clipboard, but does not remove the text from the script.

I do not have this problem in any other application, and do not use any special clipboard utilities.

This appears to be the same issue referenced in the topic, "PowerShell 5.1 ISE Cutting out text doesn't work" (https://social.technet.microsoft.com/Forums/en-US/396d9c4e-24f4-4439-aa13-26a99571d1b4/powershell-51-ise-cutting-out-text-doesnt-work?forum=winserverpowershell), but I did not see any way to resolve the problem listed in that thread.


Recreating NTFS permissions for another domain user (Matching) with ICACLS or something

$
0
0

Ok so I have looked all over the internet and haven't found my answer. I am working with an existing file server that has existing permissions to its contents. The problem is they are for an old domain that my users won't use anymore. There are some groups with specific permissions here or there, but I need to create a group out of the new domain and match the permissions of its older counterpart. 

for example:

DomainOld\Group has full access to e:\Accounting . I would like to take this groups EXACT permisions up and down the folders and give them to DomainNew\Group (which will have users from new domain). 

I have the access to the new domain on this file server, where I can add domainNew user and groups. But I'd rather not set them up separately every person who needs it. I want to use the new groups I created. 

Please help, I am not afraid of a powershell solution either. 

Add-WUServiceManager Exception from HResult: 0x8024500C

$
0
0

Where having issues with windows 10 installing updates to the computers. I am going to try to force it with powershell. Not sure if it will work or not but when trying to set it up I get the error above after issues the commandAdd-WUServiceManager -ServiceID 7971f918-a847-4430-9279-4a52d1efe18d -Confirm:$false. Any idea on what is going on here?  I used the commands prior to this one if that helps.

Set-ExectionPolicy Unrestricted -Scope Currentuser

Import-Module PSWindowsUpdate

Get-Command -Module PSWindowsUpdate


Powershell Script Help - Online Shared Mailbox

$
0
0

Hello,

Have this script that our SD use to automate mailbox creation in Exchange Online. Works fine on Room Mailboxes but won't work with Shared Mailboxes. Giving the error "A parameter cannot be found that matches parameter Name "Shared""

But works perfectly fine when I comment out Shared and uncomment Room.. any ideas? Script here:

$exchangeServer = "exchangeserver.example.com" # TODO: modify me
$remoteRoutingAddress = "%samaccountname%@domain.mail.onmicrosoft.com" # TODO: modify me
$mailboxType = "Shared" # TODO: uncomment the type you need
# $mailboxType = "Room"
# $mailboxType = "Equipment"
try
{
    # Connect to Exchange Server
    $session = New-PSSession -Configurationname Microsoft.Exchange –ConnectionUri http://$exchangeServer/powershell
    Import-PSSession $session -DisableNameChecking -AllowClobber
    # Create remote mailbox
    $parameters = @{
        "Identity" = "%distinguishedName%"
        "RemoteRoutingAddress" = $remoteRoutingAddress
        $mailboxType = $True
    }
    Enable-RemoteMailbox @parameters
}
finally
{
    # Close connection to Exchange Server
    if ($session) { Remove-PSSession $session }
}

Could someone take a look and tell me why? I'm totally stumped! Thanks :) 

how to get membership of external domains

$
0
0

Hello experts!

I'm getting crazy trying to solve this, I hope you can give me a hand.

I need to know how I could get the groups of a specific account using powershell, for example:

The AD account was builted in the Domain A and there is a Domain Local group in theDomain B. I know that if I make a search group by group, I will get the account in the groups of the Domain B, but I need to know if there is a way to make a search using the AD account of the Domain A to get the membership of the Domain B?

Thank you in advance!

Regards.

PNP script for all users with Full Control within a Site collection's sub-sites

$
0
0

We are looking to export all users that are of Full Control permission level in an on-premise site collection.  This site collection could have 300+ sub-sites.

We are trying to figure out a way to export that information with all users that have Full Control in these 300+ sub-sites and use the export in Excel to then look at grouping options per users.

 

This whole experience is to begin site auditing, and for someone associated to multiple sub-sites with Full Control, we'd like to meet with them and address multiple sites in one setting if possible...rather than schedule multiple meetings.

How to open a .txt file in a remote computer

$
0
0

I want to open a .txt file in a remote computer using invoke-command, but after execution, only can see the .notepad process in the task manager on the remote computer.

I want to open it and see it visually on the remote computer. is there any way I can do it?

Thanks.

Difference in layout when import a csv-file to excel in code and doing it manually.

$
0
0

Dear Experts,

I have code that exports a SharePoint list to a .csv-file. Then I have a function that converts it to a XLSX. Everything works fine. But when I for example import the csv-file manually in Excel I get my list in a certain layout. And when I use the code it doesn't. Is it possible to get that layout too in code?

Gr. P


Viewing all 21975 articles
Browse latest View live


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