Are there any known limitations with Windows Forms button scriptblocks? - azure

I would like to build a Windows Forms application that uses the MicrosoftTeams module in the background and performs bulk actions.
To start with, a connection to Azure must always be established. For this I want to use the integrated Windows authentication.
For example, in the PowerShell Console I simply execute the following line to establish a connection:
Connect-MicrosoftTeams -AccountId ' user#contoso.com'
Now I wanted to execute this scriptsnipped when a button is clicked.
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.DImport-Module -Name MicrosoftTeams
$window = New-Object System.Windows.Forms.Form
$window.Width = 200
$window.Height = 200
$windowButton = New-Object System.Windows.Forms.Button
$windowButton.Location = New-Object System.Drawing.Size(10,10)
$windowButton.Size = New-Object System.Drawing.Size(100,50)
$windowButton.Text = "connect teams"
$windowButton.Add_Click({
write-host 'connecting'
Connect-MicrosoftTeams -AccountId 'user#contoso.com'
Write-Host 'connected'
})
$window.Controls.Add($windowButton)
[void]$window.ShowDialog()
However, the command cannot be executed correctly. PowerShell simply hangs on the command. There is no error message and no timeout.
Do you have any idea what the problem could be? Are these limitations of Windows Forms and if so, how can I work around them?
Edit:
I think my question was not formulated precisely enough. But it is very difficult for me to describe the problem. So I will share some additional codes/logs in hope that this will avoid misunderstanding.
If I change the authentication method from this:
Connect-MicrosoftTeams -AccountId 'user#contoso.com'
to this
Connect-MicrosoftTeams -Credential (Get-Credential)
the code works fine (also in the script block for the Windows form event button). Unfortunately, the user is then prompted to enter their username and password. I would like to avoid this at all costs.
So my guess is that the code inside the Windows Forms Button Event script block is not accessing the integrated Windows authentication.
To investigate the issue, I enabled the event logging feature for this cmdlet.
First, the log of the stuck cmdlet (within a Windows Forms Button Event script block).
2022-12-26T10:22:17.5531799Z,Info ,Logger.Initialize ,
Logging initialized at level: Verbose
2022-12-26T10:22:17.5531799Z,Info ,Logger.Initialize ,
Logged in at: DEVPCName
2022-12-26T10:22:17.5531799Z,Info ,LogAssemblyInfo ,
Running assembly assemblyInfo : Microsoft.TeamsCmdlets.PowerShell.Connect, Version=1.2.5.0, Culture=neutral, PublicKeyToken=null assemblyLocation : C:\Users\lukas\Documents\WindowsPowerShell\Modules\MicrosoftTeams\4.9.1\net472\Microsoft.TeamsCmdlets.PowerShell.Connect.dll assemblyName : Microsoft.TeamsCmdlets.PowerShell.Connect, Version=1.2.5.0, Culture=neutral, PublicKeyToken=null assemblyVersion : 1.2.5.0 fileVersion : 1.2.5.0 productVersion : 1.2.5
2022-12-26T10:22:17.5531799Z,Info ,Connect-MicrosoftTeams.BeginProcessing ,
Connecting to the AzureCloud environment.
2022-12-26T10:22:17.5790454Z,Info ,Connect-MicrosoftTeams.ProcessRecord ,
Connect to MicrosoftTeams with UserCredential.
2022-12-26T10:22:17.5790454Z,Info ,Connect-MicrosoftTeams.ProcessRecord ,
Azure account type: IntegratedWindows
The log of a normal execution of the same cmdlet with the same parameters (outside a Windows Forms button click event script block).
2022-12-26T10:21:34.3697523Z,Info ,Logger.Initialize ,
Logging initialized at level: Verbose
2022-12-26T10:21:34.3697523Z,Info ,Logger.Initialize ,
Logged in at: DEVPCName
2022-12-26T10:21:34.3697523Z,Info ,LogAssemblyInfo ,
Running assembly assemblyInfo : Microsoft.TeamsCmdlets.PowerShell.Connect, Version=1.2.5.0, Culture=neutral, PublicKeyToken=null assemblyLocation : C:\Users\lukas\Documents\WindowsPowerShell\Modules\MicrosoftTeams\4.9.1\net472\Microsoft.TeamsCmdlets.PowerShell.Connect.dll assemblyName : Microsoft.TeamsCmdlets.PowerShell.Connect, Version=1.2.5.0, Culture=neutral, PublicKeyToken=null assemblyVersion : 1.2.5.0 fileVersion : 1.2.5.0 productVersion : 1.2.5
2022-12-26T10:21:34.3697523Z,Info ,Connect-MicrosoftTeams.BeginProcessing ,
Connecting to the AzureCloud environment.
2022-12-26T10:21:34.3697523Z,Info ,Connect-MicrosoftTeams.ProcessRecord ,
Connect to MicrosoftTeams with UserCredential.
2022-12-26T10:21:34.3697523Z,Info ,Connect-MicrosoftTeams.ProcessRecord ,
Azure account type: IntegratedWindows
2022-12-26T10:21:34.6700461Z,Info , ,
Sending request :https://api.interfaces.records.teams.microsoft.com/Teams.InternalSupport/TelemetryRelay 01234567-8901-2345-6789-012345678901 SendAsync C:\a_work\7\s\Microsoft.Teams.ConfigAPI.Cmdlets\generated\custom\Infrastructure\ModuleCustom.cs:79
2022-12-26T10:21:34.6700461Z,Info , ,
RequestUri: https://api.interfaces.records.teams.microsoft.com/Teams.InternalSupport/TelemetryRelay AttachTargetUriHeaderToAutoRestCmdlets C:\a_work\7\s\Microsoft.Teams.ConfigAPI.Cmdlets\generated\custom\Infrastructure\SendAsyncCallback.cs:198
2022-12-26T10:21:34.6700461Z,Info , ,
X-MS-Target-Uri: https://admin1e.online.lync.com/ AttachTargetUriHeaderToAutoRestCmdlets C:\a_work\7\s\Microsoft.Teams.ConfigAPI.Cmdlets\generated\custom\Infrastructure\SendAsyncCallback.cs:210
2022-12-26T10:21:35.3499509Z,Info , ,
CsInternalPsTelemetry flightEnabledCommands=(Get-CsTeamsEducationConfiguration,Set-CsTeamsEducationConfiguration,Grant-CsTeamsEventsPolicy,Get-CsOnlineTelephoneNumber,Grant-CsConferencingPolicy,Get-CsClientPolicy,Grant-CsHostedVoicemailPolicy,Grant-CsClientPolicy,Grant-CsMobilityPolicy,Get-CsBroadcastMeetingConfiguration,Grant-CsVoiceRoutingPolicy,Get-CsConferencingPolicy,Get-CsMobilityPolicy,Get-CsBroadcastMeetingPolicy,Get-CsCloudMeetingPolicy,Get-CsVoiceRoutingPolicy,Get-CsGraphPolicy,Get-CsExternalUserCommunicationPolicy,Grant-CsBroadcastMeetingPolicy,Get-CsHostedVoicemailPolicy,Get-CsIPPhonePolicy,Get-CsUserServicesPolicy,Get-CsAudioConferencingProvider,Grant-CsExternalUserCommunicationPolicy,Get-CsOAuthConfiguration,Get-CsMeetingConfiguration,Get-CsTenantCatalogApp,Get-CsDefaultCatalogApp,Get-CsGlobalCatalogApp,Set-CsTeamsAppPermissionPolicy,Set-CsTeamsAppSetupPolicy,Get-CsPushNotificationConfiguration,Get-CsTeamsUpgradeStatus,Get-CsTeamsPinnedApp,Get-CsUCPhoneConfiguration,Get-CsImFilterConfiguration,Set-CsPushNotificationConfiguration,Get-CsTenantUpdateTimeWindow,New-CsTeamsAppSetupPolicy,Grant-CsCloudMeetingPolicy,Get-CsTeamsAppPreset,New-CsTeamsAppPermissionPolicy,Set-CsOAuthConfiguration,Grant-CsIPPhonePolicy,Set-CsClientPolicy,Grant-CsGraphPolicy,Set-CsIPPhonePolicy,New-CsTeamsPinnedApp,New-CsDefaultCatalogApp,Set-CsConferencingPolicy,New-CsClientPolicy,Set-CsMeetingConfiguration,Set-CsUCPhoneConfiguration,New-CsConferencingPolicy,Set-CsExternalUserCommunicationPolicy,Remove-CsClientPolicy,New-CsExternalUserCommunicationPolicy,Set-CsMobilityPolicy,Remove-CsTeamsAppPreset,Set-CsBroadcastMeetingConfiguration,Remove-CsConferencingPolicy,Remove-CsTeamsPinnedApp,New-CsMobilityPolicy,Remove-CsExternalUserCommunicationPolicy,Set-CsTeamsUpgradeStatus,Remove-CsMobilityPolicy,Remove-CsDefaultCatalogApp,Set-CsDefaultCatalogApp,New-CsGlobalCatalogApp,Remove-CsGlobalCatalogApp,Set-CsGlobalCatalogApp,New-CsTeamsAppPreset,Set-CsTeamsAppPreset,Set-CsTeamsPinnedApp,New-CsTenantCatalogApp,Remove-CsTenantCatalogApp,Set-CsTenantCatalogApp,New-CsTenantUpdateTimeWindow,Remove-CsTenantUpdateTimeWindow,Set-CsTenantUpdateTimeWindow,Invoke-CsUcsRollback,Get-CsMeetingRoom,Enable-CsMeetingRoom,Set-CsMeetingRoom,Disable-CsMeetingRoom,New-CsTeamsComplianceRecordingPairedApplication,New-CsTeamsEmergencyCallingPolicy,Set-CsTeamsEmergencyCallingPolicy,New-CsTeamsEmergencyNumber,New-CsTeamsCallHoldPolicy,Set-CsTeamsCallHoldPolicy,Get-CsTeamsComplianceRecordingApplication,Remove-CsTeamsComplianceRecordingApplication,Get-CsOnlineNumberPortOutOrderPin,Set-CsOnlineNumberPortOutOrderPin,Get-CsOnlineNumberPortInOrder,New-CsOnlineNumberPortInOrder,Test-CsOnlineCarrierPortabilityIn,Test-CsOnlinePortabilityIn,Remove-CsOnlineNumberPortInOrder,Set-CsOnlineNumberPortInOrder,Remove-CsOnlineTelephoneNumber,Get-CsOnlineApplicationInstanceAssociationStatus,Remove-CsOnlineApplicationInstanceAssociation,New-CsOnlineApplicationInstanceAssociation,Get-CsOnlineApplicationInstanceAssociation,Find-CsOnlineApplicationInstance,Find-CsGroup,Remove-CsCallQueue,New-CsCallQueue,Set-CsCallQueue,Get-CsCallQueue,Get-CsAutoAttendantTenantInformation,Get-CsAutoAttendantSupportedTimeZone,Get-CsAutoAttendantSupportedLanguage,Export-CsAutoAttendantHolidays,Import-CsAutoAttendantHolidays,Get-CsAutoAttendantHolidays,Update-CsAutoAttendant,Remove-CsAutoAttendant,Get-CsOnlineApplicationEndpoint,Set-CsOnlineApplicationEndpoint,Remove-CsOnlineApplicationEndpoint,New-CsOnlineApplicationEndpoint,Switch-CsOnlineApplicationEndpoint,Get-CsUserPstnSettings,Set-CsUserPstnSettings,Get-CsOnlineDialInConferencingUser,Test-CsVoiceNormalizationRule,Sync-CsOnlineApplicationInstance,Get-CsTenant,Test-CsInboundBlockedNumberPattern,Get-CsOnlineDialInConferencingLanguagesSupported,Set-CsOnlineDialInConferencingUser,Get-CsOnlineDialInConferencingBridge,Set-CsOnlineDialInConferencingBridge,Get-CsOnlineLisPort,Set-CsOnlineLisPort,Remove-CsOnlineLisPort,Set-CsOnlineLisLocation,New-CsOnlineLisLocation,Set-CsOnlineEnhancedEmergencyServiceDisclaimer,New-CsCallingLineIdentity,Set-CsCallingLineIdentity,Get-CsOnlineLisSubnet,Set-CsOnlineLisSubnet,Remove-CsOnlineLisSubnet,Get-CsOnlineLisSwitch,Set-CsOnlineLisSwitch,Remove-CsOnlineLisSwitch,Get-CsOnlineLisWirelessAccessPoint,Set-CsOnlineLisWirelessAccessPoint,Remove-CsOnlineLisWirelessAccessPoint,Get-CsOnlineLisCivicAddress,Set-CsOnlineLisCivicAddress,Remove-CsOnlineLisCivicAddress,Get-CsOnlineLisLocation,Remove-CsOnlineLisLocation,Get-CsOnlineEnhancedEmergencyServiceDisclaimer,New-CsOnlineLisCivicAddress,Set-CsOnlineApplicationInstance,Set-CsOnlineVoiceApplicationInstance,Set-CsOnlineVoiceUser,Test-CsEffectiveTenantDialPlan,Get-CsMeetingMigrationStatus,Grant-CsApplicationAccessPolicy,Grant-CsExternalAccessPolicy,Grant-CsOnlineAudioConferencingRoutingPolicy,Grant-CsOnlineVoicemailPolicy,Grant-CsTeamsAppPermissionPolicy,Grant-CsTeamsAppSetupPolicy,Grant-CsTeamsCallHoldPolicy,Grant-CsTeamsCallingPolicy,Grant-CsTeamsCallParkPolicy,Grant-CsTeamsChannelsPolicy,Grant-CsTeamsComplianceRecordingPolicy,Grant-CsTeamsCortanaPolicy,Set-CsUser,Grant-CsTeamsEmergencyCallingPolicy,Grant-CsTeamsFeedbackPolicy,Grant-CsTeamsIPPhonePolicy,Grant-CsTeamsMeetingBroadcastPolicy,Grant-CsTeamsMeetingPolicy,Grant-CsTeamsMessagingPolicy,Grant-CsTeamsMobilityPolicy,Grant-CsTeamsShiftsPolicy,Grant-CsTeamsUpdateManagementPolicy,Grant-CsTeamsUpgradePolicy,Grant-CsTeamsVdiPolicy,Grant-CsTeamsVideoInteropServicePolicy,Get-CsOnlineUser,Get-CsOnlineVoiceUser,Get-CsEffectiveTenantDialPlan,New-CsOnlineApplicationInstance,Get-CsOnlineApplicationInstance,Start-CsExMeetingMigration,Grant-CsCallingLineIdentity,Grant-CsDialoutPolicy,Grant-CsTeamsAudioConferencingPolicy,Grant-CsTeamsEmergencyCallRoutingPolicy,Grant-CsTeamsEnhancedEncryptionPolicy,Grant-CsTeamsWorkLoadPolicy,Grant-CsTenantDialPlan,Grant-CsTeamsFilesPolicy,Remove-CsApplicationAccessPolicy,Remove-CsCallingLineIdentity,Remove-CsExternalAccessPolicy,Remove-CsOnlineVoicemailPolicy,Remove-CsTeamsAudioConferencingPolicy,Remove-CsTeamsCallHoldPolicy,Remove-CsTeamsCallingPolicy,Remove-CsTeamsCallParkPolicy,Remove-CsTeamsChannelsPolicy,Remove-CsTeamsEmergencyCallingPolicy,Remove-CsTeamsEmergencyCallRoutingPolicy,Remove-CsTeamsEnhancedEncryptionPolicy,Remove-CsTeamsIPPhonePolicy,Remove-CsTeamsMeetingBroadcastPolicy,Remove-CsTeamsMeetingPolicy,Remove-CsTeamsMessagingPolicy,Remove-CsTeamsUpdateManagementPolicy,Remove-CsTenantDialPlan,Remove-CsTeamsComplianceRecordingPolicy,Remove-CsTeamsCortanaPolicy,Remove-CsTeamsFeedbackPolicy,Remove-CsTeamsMobilityPolicy,Remove-CsTeamsShiftsPolicy,Remove-CsTeamsVdiPolicy,Remove-CsTeamsWorkLoadPolicy,Remove-CsOnlineAudioConferencingRoutingPolicy,Remove-CsTeamsFilesPolicy,Grant-CsTeamsSurvivableBranchAppliancePolicy,Remove-CsTeamsSurvivableBranchAppliancePolicy,Remove-CsTeamsAppPermissionPolicy,Remove-CsTeamsAppSetupPolicy,Set-CsOnlineDialinConferencingUserDefaultNumber,Get-CsOnlineDialInConferencingServiceNumber,Set-CsOnlineDialInConferencingServiceNumber,Get-CsDialPlan,Get-CsExternalAccessPolicy,Get-CsOnlineDialInConferencingTenantSettings,Get-CsOnlineVoiceRoutingPolicy,Get-CsPrivacyConfiguration,Get-CsTeamsAudioConferencingPolicy,Get-CsTeamsCallingPolicy,Get-CsTeamsCallParkPolicy,Get-CsTeamsChannelsPolicy,Get-CsTeamsClientConfiguration,Get-CsTeamsCortanaPolicy,Get-CsTeamsEducationAssignmentsAppPolicy,Get-CsTeamsFeedbackPolicy,Get-CsTeamsGuestCallingConfiguration,Get-CsTeamsGuestMeetingConfiguration,Get-CsTeamsGuestMessagingConfiguration,Get-CsTeamsIPPhonePolicy,Get-CsTeamsMeetingBroadcastPolicy,Get-CsTeamsMeetingConfiguration,Get-CsTeamsMigrationConfiguration,Get-CsTeamsMobilityPolicy,Get-CsTeamsNotificationAndFeedsPolicy,Get-CsTeamsShiftsAppPolicy,Get-CsTeamsShiftsPolicy,Get-CsTeamsTargetingPolicy,Get-CsTeamsUpgradeConfiguration,Get-CsTeamsVdiPolicy,Get-CsTeamsWorkLoadPolicy,Get-CsTenantMigrationConfiguration,Get-CsTeamsFilesPolicy,New-CsExternalAccessPolicy,New-CsOnlineVoiceRoutingPolicy,New-CsTeamsAudioConferencingPolicy,New-CsTeamsCallingPolicy,New-CsTeamsCallParkPolicy,New-CsTeamsChannelsPolicy,New-CsTeamsCortanaPolicy,New-CsTeamsFeedbackPolicy,New-CsTeamsIPPhonePolicy,New-CsTeamsMeetingBroadcastPolicy,New-CsTeamsMobilityP...
2022-12-26T10:21:35.3499509Z,Info ,Connect-MicrosoftTeams.ProcessRecord ,
Session created with. Account: user#contoso.com, Environment: AzureCloud, Tenant: 01234567-8901-2345-6789-012345678901, domainName: contoso.onmicrosoft.com, AccountType: IntegratedWindows.
So now my more specific question is: Is this phenomenon known to anyone or is this a known limitation of Windows Forms? Or is there a way to work around this problem?

You can create a function, of course, locate that at the top of your code, and call that in the click event as well.
Add-Type -AssemblyName System.Windows.Forms
# Add-Type -AssemblyName System.DImport-Module -Name MicrosoftTeams
function ConnectTo-MSTeams
{
[CmdletBinding(SupportsShouldProcess)]
Param()
Write-Host 'connecting'
Get-Date |
Out-Host
Write-Host 'connected'
}
$window = New-Object System.Windows.Forms.Form
$window.Width = 200
$window.Height = 200
$window.StartPosition = 'CenterScreen'
$windowButton = New-Object System.Windows.Forms.Button
$windowButton.Location = New-Object System.Drawing.Size(10,10)
$windowButton.Size = New-Object System.Drawing.Size(100,50)
$windowButton.Text = 'connect teams'
$windowButton.Add_Click({ConnectTo-MSTeams})
$window.Controls.Add($windowButton)
[void]$window.ShowDialog()
# Results
<#
connecting
Monday, December 26, 2022 13:14:01
connected
#>
I don't have Teams installed, so, you need to test.

Related

Error when Running an Excel Macro from a Windows Service Application

I have created a Windows Service Application that does many things but a part of it is producing an error. My service runs a PowerShell script that opens an Excel document (I know Microsoft does not support this, but opening the Excel doc is actually not whats giving me an issue). I get the error below when I try to run a macro on it and I have no idea how to fix it.
Exception calling "Run" with "1" argument(s): "'C:\WINDOWS\system32\PERSONAL.XLSB' could not be found.
Check the spelling of the file name, and verify that the file location is correct.
If you are trying to open the file from your list of most recently used files,
make sure that the file has not been renamed, moved, or deleted."
At line:54 char:1
+ $excel.Run("PERSONAL.XLSB!MacroForSoftwareFeatureLicensesXLS")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
I have applied other solutions already like adding a 'Desktop' folder to C:\Windows\System32\config\systemprofile and C:\Windows\SysWOW64\config\systemprofile. This worked for allowing me to open the excel doc.
I have tried putting the PERSONAL.XLSB file in the C:\WINDOWS\system32 folder but this does nothing. Similarly, I also tried putting the PERSONAL.XLSB file in C:\WINDOWS\sysWOW64 but this completely halts my service.
My PowerShell script is the following:
$myLocalXLS = "C:\Users\aUser\Desktop\aFolder\myLocalXLS.xls"
$excel = New-Object -ComObject excel.application
$excel.DisplayAlerts = $FALSE
$myXLSWorkbook = $excel.Workbooks.Open($mylocalXLS)
$excel.Run("PERSONAL.XLSB!MacroForMyLocalXLS")
$myXLSWorkbook.Save()
$excel.DisplayAlerts = $TRUE
$excel.Quit()
I think you actually have to open the PERSONAL.XLSB manually, e.g. something like this worked for me:
$myLocalXLS = "C:\Users\aUser\Desktop\aFolder\myLocalXLS.xls"
$myPersonalXLSB = "C:\Users\aUser\AppData\Roaming\Microsoft\Excel\XLSTART\PERSONAL.XLSB"
$excel = New-Object -ComObject excel.application
$excel.DisplayAlerts = $FALSE
$myXLSWorkbook = $excel.Workbooks.Open($mylocalXLS)
$myPersonalWorkbook = $excel.Workbooks.Open($myPersonalXLSB)
$excel.Run("PERSONAL.XLSB!MacroForMyLocalXLS")

"Upload of file '...' was successful, but error occurred while setting the permissions and/or timestamp" when using WinSCP .NET assembly in PowerShell

Exception calling "Check" with "0" argument(s): "Upload of file '2019-06-11.zip'
was successful, but error occurred while setting the permissions and/or
timestamp.
If the problem persists, turn off setting permissions or preserving timestamp.
Alternatively you can turn on 'Ignore permission errors' option.
Permission denied.
Error code: 3
Error message from server: This server does not support operations to modify
file attributes."
At line:12 char:84
+ $session.PutFiles("D:\Users\bin\*.zip", "/Outbox/").Check <<<< ()
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
I keep on getting above error file transferring file from Window Server to Linux. I got the same error when using the WinSCP GUI as well. I asked MFT team and they didn't any set permission. Below are my script for file transferring and some of intro version of software I'm using. Anything I missed out for my script or version of software is too old? I will have an update of server soon but have to wait another 2 yrs. This task will be set as scheduler to transfer file daily to MFT server.
Version of software:
Use .NET 4.0
Use PowerShell v2.0
Window Server 2008
Placed private.ppk, WinSCPNet.dll and WinSCP.exe at same folder
#Load WinSCP .NET assembly
Add-Type -Path "D:\Users\WinSCPnet.dll" -Verbose
$session = New-Object WinSCP.Session
$sessionOptions = New-Object WinSCP.SessionOptions
$sessionOptions.Protocol = [WinSCP.Protocol]::Sftp
$sessionOptions.HostName = "[Linux server IP]"
$sessionOptions.UserName = "[username]"
$sessionOptions.PortNumber = "[linux port number]"
$sessionOptions.Password = ""
$sessionOptions.SshPrivateKeyPath = "D:\Users\bin.ppk"
$sessionOptions.SshHostKeyFingerprint = "ssh-rsa 2048 ....="
try {
# Open the WinSCP.Session object using the WinSCP.SessionOptions object.
$session.Open($sessionOptions)
# Upload
$session.PutFiles("D:\Users\bin\*.zip", "/Outbox/").Check()
} finally {
# Disconnect, clean up
$session.Dispose()
}
The error is documented here:
https://winscp.net/eng/docs/message_preserve_time_perm
Your server does not support updating timestamps of uploaded remote files. So you need to instruct WinSCP not to attempt it:
$transferOptions = New-Object WinSCP.TransferOptions
...
$transferOptions.PreserveTimestamp = $False
$session.PutFiles("D:\Users\bin\*.zip", "/Outbox/", $False, $transferOptions).Check()

Can't enable IIS logging without using the GUI

IIS logging has been disable via the GUI:
I just want to enable it, but apparently this is impossible without using the GUI.
Commands I have tried:
appcmd set config /section:httpLogging /dontLog:False /selectiveLogging:LogAll
Set-ItemProperty "IIS:\Sites\MySite" -name logFile -value #{enabled=$true}
Set-WebConfigurationProperty -pspath 'MACHINE/WEBROOT/APPHOST' -filter "system.applicationHost/sites/site[#name='MySite']/logFile" -name "LogExtFileFlags" -value #{enabled=$true}
When I do a Get-Windowsfeature I can see IIS-HttpLogging is marked as enabled.
Nothing I have tried has enabled IIS logging, I have to use the GUI and click enable.
When I run this it returns true:
PS C:\Windows\System32\inetsrv> (Get-WebConfiguration -PSPath 'MACHINE/WEBROOT/APPHOST' -filter "/system.applicationHost/sites/MYSite" ).logfile.enabled
Edit:
So logging seems to work even though the GUI displays it as "disabled". Perhaps this is a bug in the GUI?
Edit2:
OK so if I try the appcmd command and target my specific site I get this error:
.\appcmd set config "MySite" /section:httpLogging /dontLog:False
PS C:\Windows\System32\inetsrv> .\appcmd set config "MySite" /section:httpLogging /dontLog:False
ERROR ( message:Can not set attribute "dontLog" to value "False".. Reason: This configuration section cannot be used at this path. This happens when the section is locked at a parent level. Locking is either by default (overrideModeDefault="Deny"), or set explicitly by a location tag with overrideMode="Deny" or the legacy allowOverride="false
Is says the section is locked at the parent level, but I was able to click enable for the site's logging in the GUI and did not get any errors.
As I wrote the clone of IIS Manager, I can tell you the "Enable/Disable" button links to an attribute called "dontLog", https://github.com/jexuswebserver/JexusManager/blob/master/JexusManager.Features.Logging/LoggingFeature.cs
Its reference can be found at
https://www.iis.net/configreference/system.webserver/httplogging

Refresh Excel dataset in SharePoint Online with PowerShell 403 error

I have been attempting to implement a PowerShell script that will access an Excel workbook, check it out, refresh the dataset in the workbook and finally check it back in again.
I've combined this with a task in Windows Task Scheduler to run the script daily from a server with a user account that has access to the SharePoint Online site.
My issue is that the script will not run. When I view the Windows Event logs I can see it is getting a 403 error
The script was taken from the document found here document:
Link to download document
The the task gets the following script and the location of the Excel Workbook from arguments in the action config of the task (detailed in the document above)
try
{
# Creating the excel COM Object
$xl = New-Object -ComObject Excel.Application;
# Setting up Excel to run without UI and without alerts
$xl.DisplayAlerts = $false;
$xl.Visible = $false;
}
Catch
{
Write-EventLog -EventId "5001" -LogName "Application" -Message "Failed to start Excel" -Source "Application"
Exit
}
foreach ($i in $args)
{
write-host "handling $i"
try
{
# Allow update only if we can perform check out
If ($xl.workbooks.CanCheckOut($i))
{
# Opening the workbook, can be local path or SharePoint URL
$wb = $xl.workbooks.open($i);
# Perform the check out
$xl.workbooks.checkout($i)
# Calling the refresh
$wb.RefreshAll();
# Saving and closing the workbook
$wb.CheckInWithVersion();
# in case you are not using checkout/checkin perform a save and close
#$wb.Save();
#$wb.Close();
#Release Workbook
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($wb)
}
else
{
write-host "Check out failed for: $i"
Write-EventLog -EventId "5001" -LogName "Application" -Message "Workbook can't be checked out $i" -Source "Application"
}
}
catch
{
Write-EventLog -EventId "5001" -LogName "Application" -Message "Failed refreshing the workbook $i $_" -Source "Application"
}
}
#Quiting Excel
$xl.quit();
#Release Excel
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($xl)
Am I missing something here?
Thanks in advance and please let me know if more info is required.
EDIT: The script works if run manually from cmd with the correct arguments. Problem seems to be that Task Scheduler cannot access PowerShell.
So I got this working finally. Issue was that it wasn't running the script when the option 'User logged on or not' in the general settings of the task was selected. Worked fine when 'User logged on' was selected.
Here are the steps I had to take to get this to run properly.
First the script needed to run from the System32 folder (also specify that directory in the tasks "Start In" box. Also make sure that you are pointing to the 32-bit version of PowerShell since Excel won't work with 64-bit
And second, turns out there is a bug with Excel where you have to create a folder called “Desktop” in the \SysWOW64\config\systemprofile\ and \System32\config\systemprofile\ directories(both folders need to be created if running Excel 64-bit).
This is the final argument string I ended up using: C:\Windows\System32\WindowsPowerShell\v1.0\Powershell.exe -nologo –noprofile -noninteractive -executionpolicy bypass path\to\script 'path\to\excelworkbook'

Powershell and System.Security.Cryptography.X509Certificates.X509Certificate2

i'm getting this error when i run the system.security namespace. This is what i am running after
$cert=New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("C:\mycert.cer")
New-Object: Cannot find type [System.Security.Cryptography.X509Certificates.X509Certificate2("C:\mycert.cer")]: make sure the assembly containing this type is loaded.
At line:1 char:19
+ $cert = New-Object <<<<
+ CategoryInfo : InvalidType: (:) [New-Object], PSArgumentException
+ FullyQualifiedErrorId : TypeNotFound,Microsoft.PowerShell.Commands.NewObjectCommand**
What am i doing wrong?
Try running this to see if you have the System.dll loaded (should be by default):
[AppDomain]::CurrentDomain.GetAssemblies() |
Where {$_.Location -match '\\System\\'}
If it is loaded then this command should show the X509Certificate2 type:
[AppDomain]::CurrentDomain.GetAssemblies() |
Where {$_.Location -match '\\System\\'} |
%{$_.GetExportedTypes()} | Where {$_.Name -match 'X509Cert'}
If the System.dll isn't loaded (which would be odd) try loading it:
Add-Type -AssemblyName System
See: http://technet.microsoft.com/en-us/library/hh849914.aspx
FYI ... I got error:
Unable to find type [System.Security.Cryptography.x509Certificates.X509Certificate2UI]
when using:
$certSelect = [System.Security.Cryptography.x509Certificates.X509Certificate2UI]::SelectFromCollection($certCollection, $title, $msg, 0)
However, I had no error creating the collection earlier on in my script:
$certCollection = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2Collection
To make the error go away I had to include the following at some point earlier on:
Add-Type -AssemblyName System.Security
I've solved my problem. It's easily:
cd\
$cert=New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("C:\mycert.cer")
cd\ is necessary
I ran into this in the ISE (but seems to apply to the normal command window too) and it seems that using autocomplete will automatically Add-Type for whatever you're looking for. If you start a new instance and run:
[AppDomain]::CurrentDomain.GetAssemblies() | grep Security
it will not return System.Security, but if you then type this and let intellisense do its thing:
[System.
You can then run this again:
[AppDomain]::CurrentDomain.GetAssemblies() | grep Security
And it will then return System.Security. So this is why you can write a script that works fine, and then revisit it later and it's broken. Using intellisense doesn't fix your script though, instead you have to add this line:
Add-Type System.Security
Or whatever library is not getting auto-added (it seems to need the dll filename, e.g. C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\System.Security.dll).
I'm pretty sure IseSteroids (a paid ISE add-in) can detect this, maybe others as well.

Resources