Sharepoint 2013 OnPrem Export-SPWeb unknown error - sharepoint

We have an On-Prem SharePoint 2013, with a team site on it
Trying to export a document library from this path
https://myportal.mycompany.com/mygroup/
The name of the document library is testDoc, it has only two files with less than 10kb data
The command I am using on the server where Sharepoint 2013 on Prem is located is the following
Export-SPWeb -Identity "https://myportal.mycompany.com/mygroup/" -ItemUrl "/testDoc" -Path "E:\SPBackup\TestDoc.cmp" -NoFileCompression -IncludeVersions 4
This is the error that I receive
Yes I have tried the following permutations of the command too
Export-SPWeb -Identity "https://myportal.mycompany.com/" -ItemUrl "/mygroup/testDoc" -Path "E:\SPBackup\TestDoc.cmp" -NoFileCompression -IncludeVersions 4
With and without the trailing slashes etc and each time I get the same error.
When I try to export a document library on root it works perfectly
Export-SPWeb -Identity "https://myportal.mycompany.com/" -ItemUrl "/testDoc" -Path "E:\SPBackup\TestDoc.cmp" -NoFileCompression -IncludeVersions 4
This works like a charm.
Any idea, suggestions or resolutions for this error.

Make sure the -Identity parameter gets the URL of your subsite and the -ItemUrl should get relative path of the library to be exported.
Export-SPWeb -Identity "https://myportal.mycompany.com/mygroup/" -ItemUrl "/mygroup/testDoc" -Path "E:\SPBackup\TestDoc.cmp" -NoFileCompression -IncludeVersions 4

Related

How can I get a list of Azure AD Users in my PowerShell script within my Azure Function App?

Some context: I have a PowerShell script that gets information about users and their licenses on Azure, and then saves that information to CSV file. It works locally. My goal is to have this script automatically run on Azure (I'm trying to do it in an Azure Function App) once a month, and then have the created CSV file be emailed to a specified email. However all I want to figure out right now is how to get the list of users so that the script can at least just run without errors.
I have very little experience with PowerShell and Azure Function Apps, so I'm stuck on a few errors I'm getting. I have spent the last few days troubleshooting to no luck.
Here is the beginning of the script that I can run from my local PowerShell:
Function main()
{
#Clean up session
Get-PSSession | Remove-PSSession
#Connect AzureAD from PowerShell
Connect-MsolService
#Set output file
$ExportCSV=".\DetailedO365UserLicenseReport_$((Get-Date -format yyyy-MMM-dd-ddd` hh-mm` tt).ToString()).csv"
$ExportSimpleCSV=".\SimpleO365UserLicenseReport_$((Get-Date -format yyyy-MMM-dd-ddd` hh-mm` tt).ToString()).csv"
#FriendlyName list for license plan and service - txt file on local computer
$FriendlyNameHash=Get-Content -Raw -Path .\LicenseFriendlyName.txt -ErrorAction Stop | ConvertFrom-StringData
#txt file on local computer
$ServiceArray=Get-Content -Path .\ServiceFriendlyName.txt -ErrorAction Stop
#Hash table declaration
$Result=""
$Results=#()
$output=""
$outputs=#()
$LicensedUserCount=0
#Get all licensed users
Get-MsolUser -All | where{$_.islicensed -eq "true"} | Foreach{
#this is another function that handles grabbing the user info and writing it to the CSV file
Get_UsersLicenseInfo
$LicensedUserCount++
}
. main
With this script above, it requires some user input for entering credentials. I want this script to be able to run automatically in Azure without any user input, so I've been trying to modify it to do that. I found out that any commands with 'Msol' in the name don't work in Azure Function Apps/Powershell Core, so I found a different module that apparently does work.
This is where I'm currently at with the script to be run in my Azure Function App:
Import-Module AzureAD
Function main()
{
#Clean up session
Get-PSSession | Remove-PSSession
$password = ConvertTo-SecureString "{my password here}" -AsPlainText -Force
$UserCredential = New-Object System.Management.Automation.PSCredential ("myusernamehere", $password)
Connect-AzureAD -Credential $UserCredential
#Set output file
$ExportCSV=".\DetailedO365UserLicenseReport_$((Get-Date -format yyyy-MMM-dd-ddd` hh-mm` tt).ToString()).csv"
$ExportSimpleCSV=".\SimpleO365UserLicenseReport_$((Get-Date -format yyyy-MMM-dd-ddd` hh-mm` tt).ToString()).csv"
#FriendlyName list for license plan and service - hash table here
$FriendlyNameHash= #{AAD_BASIC = "Azure Active Directory Basic"; AAD_PREMIUM= "Azure Active Directory Premium"; AAD_PREMIUM_P1= "Azure Active Directory Premium P1"; AAD_PREMIUM_P2= "Azure Active Directory Premium P2" }
#array of strings, used when getting user info
$ServiceArray= "MCOEV", "Cloud PBX", "MCOPSTN2", "PSTN International", "mcomeetadv"
#Hash table declaration
$Result=""
$Results=#()
$output=""
$outputs=#()
$LicensedUserCount=0
Get-AzureADUser -All | where{$_.islicensed -eq "true"} | Foreach{
Get_UsersLicenseInfo
$LicensedUserCount++}
}
. main
First of all I'm not sure if I even need to authenticate if this script is running from within my Azure account. Second of all, and my main issue, is that when I try to run this script in my Azure Function App, I get this error:
snippet of the azure error
If the picture doesn't work, it says:
The Function app may be missing a module containing the 'Connect-AzureAD' command definition. If this command belongs to a module available on the PowerShell Gallery, add a reference to this module to requirements.psd1. Make sure this module is compatible with PowerShell 7. For more details, see https://aka.ms/functions-powershell-managed-dependency. If the module is installed but you are still getting this error, try to import the module explicitly by invoking Import-Module just before the command that produces the error: this will not fix the issue but will expose the root cause.
2021-06-08T16:48:00.377 [Error] ERROR: The term 'Connect-AzureAD' is not recognized as the name of a cmdlet, function, script file, or operable program.Check the spelling of the name, or if a path was included, verify that the path is correct and try again.Exception
I get that same error for the line with 'Get-AzureADUser' as well. I followed this guide: https://tech.nicolonsky.ch/azure-functions-powershell-modules/ to add the AzureAD module to my managed dependencies, but I still get that same error.
If anything needs clarification, let me know. Any help is appreciated!
Actually, AzureAD needs to be imported a bit differently - it's been a problem for a while per this github issue. This seemed to work for most people:
Setting the application to run as x64 bit: Function App>
Configuration > General Settings > Platform > 64 Bit
Setting the app to run on Powershell 7 instead of 6 on this thread
Use: Import-Module AzureAD -UseWindowsPowerShell

Dynamics AX: How to configure Archive Directory to use Sharepoint Online

We are getting error Error during upload when uploading a file that is configured to save files to SharePoint Online. This is on Microsoft Dynamics AX 2012 R3.
We have document management enabled, we are currently saving files to a local folder on the AOS server but now want to save files to our online sharepoint library in O365.
I created the following folder AXTest in sharepoint, and granted the AX service account access to the sharepoint team.
I set Archive directory appropriately. I tried various veresions of the URL, which were all unsuccessful:
https://xxxxx.sharepoint.com/sites/Dev-Test/AXTest
https://xxxxx.sharepoint.com/sites/Dev-Test/AXTest/Forms
various document folders
All result in error when trying to upload a file that is local to the AOS server:
Through debugging, the error is raised here.
There is no exception stack so I don't know the exact reason why, but we tried various versions of the URL, we tried uploading a file locally, and we know the service account has access to the sharepoint site/team. Any other ideas?
Late but the "solution" is to make sure that a persistent cookie for SharePoint Online exists locally. I have been biting my head off to find a better solution, because it can get pretty complex to get that persistent cookie which makes it not suitable for end-users. To the point that my only solution might be to build a custom connector (or to urge for an upgrade...)
The key is to somehow force login.microsoftonline.com to prompt the user the question to remain signed-in. Only when you click Yes in that dialog is a persistent cookie created for SPO. Then the upload works fine, until the cookie expires / gets deleted.
These are the instructions for our users:
1. Make sure SPO / MS / Azure / ADFS related urls are not in the intranet zone in IE to prevent automatic login with windows credentials.
2. Sign out of SPO
3. Delete browser cookies
3. Restart IE
4. Go to SPO
5. You should be prompted to login with username and password
6. Then you will receive the question to Remain signed in. Click Yes.
Optional if this didnt work: Reset IE to default settings.
There's a KB included in CU13 for AX2012 R3 that seems to address the issue (mentions the vague "Error during upload" error). Haven't tested it myself, because i am trying to solve it in an AX2012 R2 CU9 environment.
I just ran across the same issue and what a NIGHTMARE!
For Windows Server 2012 R2, I wrote this little PowerShell script to help clear the cookies for all users.
We had users sign out of AX, sign off the terminal server(s), and then I ran the below script to just remove all user cookies. Next connection, they were in business.
$Remove = $false
Get-ChildItem -Path "C:\Users" -Directory | % {
$CachePath = Join-Path -Path $_.FullName -ChildPath "\AppData\Local\Microsoft\Windows\INetCache"
$CookiePath = Join-Path -Path $_.FullName -ChildPath "\AppData\Local\Microsoft\Windows\INetCookies"
if (Test-Path -Path $CookiePath)
{
Write-Host $_.FullName -ForegroundColor Green
if ($Remove) {
Get-ChildItem -Path $CookiePath -File -Recurse | Remove-Item -Force -ErrorAction Continue
Get-ChildItem -Path $CachePath -File -Recurse | Remove-Item -Force -ErrorAction Continue
} else {
Get-ChildItem -Path $CookiePath -File -Recurse | Format-Table -AutoSize
Get-ChildItem -Path $CachePath -File -Recurse | Format-Table -AutoSize
}
}
}

"Failed to enumerate SSL bindings" error code 234

Does anybody know how to resolve this issue?
Replicate when you type the following command in PowerShell.
dir iis:\sslbindings
I have comes across this page on Microsoft TechNet which doesn't address the problem.
Edit
When invoking the command I get the error
failed to enumerate SSL bindings
Apparently due to a corrupted registry?
In my case, I've got the error when I had both SslCertStoreName and DefaultSslCtlStoreName in the registry. I deleted DefaultSslCtlStoreName and the error is gone for a while. For some reason, DefaultSslCtlStoreName was created in the registry again, and I've got the error again. So I wrote a simple powershell script that deletes it.
This is the part from my build script.
function CleanupSslBindings()
{
$sslBindingsPath = 'hklm:\SYSTEM\CurrentControlSet\services\HTTP\Parameters\SslBindingInfo\'
$registryItems = Get-ChildItem -Path $sslBindingsPath |
Where-Object -FilterScript { ($_.Property -eq 'DefaultSslCtlStoreName')}
If ($registryItems.Count -gt 0) {
ForEach ($item in $registryItems) {
$item | Remove-ItemProperty -Name DefaultSslCtlStoreName
Write-Host "Deleted DefaultSslCtlStoreName in " $item.Name
}
} Else {
Write-Host "No DefaultSslCtlStoreName found. The SSL Bindings registry is clean."
}
}
In my case, I had built WCF services hosted as windows services. When I did this, I apparently didn't know (and still don't) how to assign things like appid's (noticeable when you netsh http show sslcert), and other items that crop up... including an item related to this error.
Essentially, I read the same page the OP did: https://social.technet.microsoft.com/Forums/windowsserver/en-US/87b1252d-a6a0-4251-bbb6-38e104a8c07a/enumerating-iissslbindings-gives-failure-on-one-machine-works-on-another?forum=winserverpowershell
...and using a regedit, went to the key: HKLM\System\Currentcontrolset\services\http\parameters\sslbindinginfo
I saw all the same entries I see when I do the netsh command above. However, my wcf services are listed first, followed by my IIS sites. None of my wcf services had the SSLCertStoreName key (only the IIS sites had the key). Following the article's explanation that the first entry needs to have that registry key (this is a bug in my opinion), I performed the following PowerShell commands:
Try
{
Get-ChildItem IIS:\SslBindings
}
Catch
{
$1stentry = Get-ChildItem HKLM:\SYSTEM\CurrentControlSet\services\HTTP\Parameters\SslBindingInfo | Select-Object -First 1
$1stentry | New-ItemProperty -Name "SslCertStoreName" -Value "MY"
Get-ChildItem IIS:\SslBindings
}
This code works for me. And that article helped get me here and understand that my root cause of this 234 error code, is an assumed self-inflicted wound by not installing my WCF services correctly. YMMV. Hope this helps.
Apologies for the delay but I resolved the issue with the following script (see below). For some bizarre reason (I don't know why) something was adding two entries in my registry and after removing these the problem went away. I figured this out as I compared my registry to another machine who wasn't having this problem and found the culprit.
Remove-ItemProperty -Path "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\HTTP\Parameters\SslBindingInfo\" -Name "[::1]:26143" -ErrorAction SilentlyContinue
Remove-ItemProperty -Path "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\HTTP\Parameters\SslBindingInfo" -Name "127.0.0.1:26143" -ErrorAction SilentlyContinue
echo "Done."
#Bewc I reckon you are onto something there although I think it affects more than just WCF services. We have a powershell script that builds and deploys a website onto a machine (sounds crazy I know). Who or what creates these entries I have no idea but perhaps some background process in IIS?

Why Powershell's New-WebBinding commandlet creates incorrect HostHeader?

I am trying to add an MSMQ binding for my IIS Web Site, correct binding should look like this:
So I am executing following line in PowerShell:
New-WebBinding -Name "My Site" -Protocol net.msmq -HostHeader "localhost"
and it creates the following binding:
prefixing it with *:80:, so my MSMQ messages don't get picked up by WCF service. Maybe I am doing it wrong? How to create a binding with Binding Information set to just "localhost" using this PowerShell comandlet?
Commandlet codumentaiton can be found here.
Looking at the decompiled code of the cmdlet, looks like it adding the IPAddress and Port information in the binding and there is no workaround to it.
Relevant sections from the code:
private string ipAddress = "*";
...
builder.Append(this.ipAddress);
...
builder.Append(":" + this.sitePort.ToString(CultureInfo.InvariantCulture) + ":");
But you can do what the cmdlet actually does ( below code from cmdlet):
new-itemproperty -path "IIS:\sites\test" -name bindings -value #{protocol="net.msmq"; bindingInformation="localhost"}
Give this a try:
New-ItemProperty "IIS:\sites\NameOfYourSite" -name bindings -value #{protocol="net.msmq";bindingInformation="localhost"}
If your are running PowerShell (Core), a.k.a PowerShell >v7.1.x, you will find yourself in trouble because...
WARNING: Module WebAdministration is loaded in Windows PowerShell using WinPSCompatSession remoting session;
please note that all input and output of commands from this module will be deserialized objects.
If you want to load this module into PowerShell please use 'Import-Module -SkipEditionCheck' syntax.
The IIS provider isn't available via remoting session.
The easiest trick is to redirect string via pipeline to Windows PowerShell.
"Import-Module WebAdministration;New-ItemProperty -Path `"IIS:\Sites\$($configuration.Website.Name)`" -Name Bindings -value #{protocol = `"net.msmq`"; bindingInformation = `"localhost`" }" | PowerShell
In this example, the website name is read from the configuration JSON. You can replace it by a hard-coded site name.

Powershell command to set IIS logging settings

I'm creating a powershell script so I can create website hosting with a single command using the IIS Powershell Management Console.
I have the commands I need to create the IIS Site and add bindings for the domain names etc...
The one piece of the puzzle I'm missing though is how to change the default Logging directory from %SystemDrive%\inetpub\logs\LogFiles to my own folder that's not on the boot drive of the server.
After extensive searching I expected to find a command along the lines of the following pseudo powershell
New-ItemProperty IIS:\Sites\MyNewSite -name logging -value #{format='W3C';directory='d:\sites\site\logs';encoding=UTF-8}
Please could you show me with an example how you change the logging folder in the IIS Powershell Management Console
Thanks in advance
Import-Module WebAdministration
Set-WebConfigurationProperty "/system.applicationHost/sites/siteDefaults" -name logfile.directory -value $logdir
While testing the answer from this thread, toggling options via IIS Manager and PowerShell, I stumbled on something that has been hidden to me. In IIS Manager, choosing Configuration Editor and making a change, allows the IIS Manager to generate and display the script for the change in C#, JavaScript, AppCmd.exe and PowerShell. Just click the Generate Script option.
[]
For changing an individual web site's logFile configuration, the original post was nearly correct. Instead of New-ItemProperty, use Set-ItemProperty, like so...
Set-ItemProperty "IIS:\Sites\$SiteName" -name logFile -value #{directory=$LogPath}
For changing the server-wide default settings, see Andy Schneider's answer.
For more information about the options available, see this IIS.net article.
This works as well, using the WebAdministration Module
Import-Module WebAdministration
$site = gi IIS:\Sites\MyNewSite
$site.Logging.format='W3C'
$site.Logging.directory='d:\sites\site\logs'
$site.Logging.encoding=UTF-8
$site | set-item
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Web.Administration")
$iis = new-object Microsoft.Web.Administration.ServerManager
$web = $iis.Sites["test"]
#set new logpath, must be existing
$web.LogFile.Directory = "F:\Logfiles\"
$iis.CommitChanges()
If you host multiple sites on a single server and want them to all log to the same log file, the process is quite different. It took some digging to find clues here and here, so I thought I would leave a description behind for anyone else with this need.
The following two statements will combine logs for all of your websites into a folder e:\log\w3svc.
Set-WebConfigurationProperty -pspath 'MACHINE/WEBROOT/APPHOST' -filter 'system.applicationHost/log' -name CentralLogFileMode -Value 'CentralW3C'
Set-WebConfigurationProperty -pspath 'MACHINE/WEBROOT/APPHOST' -filter 'system.applicationHost/log' -name centralW3CLogFile.directory -value 'e:\log'

Resources