From 135e94d6cb1d73b41f23785a790a97615c714f20 Mon Sep 17 00:00:00 2001 From: Jordan Borean Date: Tue, 9 Aug 2022 08:49:29 +1000 Subject: [PATCH 001/779] Migrate `WinTrust` functions to a common location (#17598) --- .../security/Authenticode.cs | 193 +++--- .../security/CatalogHelper.cs | 355 ++++++----- .../security/Win32Native/WinTrust.cs | 440 +++++++++++++ .../security/nativeMethods.cs | 593 ------------------ 4 files changed, 716 insertions(+), 865 deletions(-) create mode 100644 src/System.Management.Automation/security/Win32Native/WinTrust.cs diff --git a/src/System.Management.Automation/security/Authenticode.cs b/src/System.Management.Automation/security/Authenticode.cs index 1906d18bf6b..0b205cc6634 100644 --- a/src/System.Management.Automation/security/Authenticode.cs +++ b/src/System.Management.Automation/security/Authenticode.cs @@ -7,14 +7,15 @@ #if !UNIX using Microsoft.Security.Extensions; #endif +using System.ComponentModel; using System.IO; using System.Management.Automation.Internal; using System.Management.Automation.Security; +using System.Management.Automation.Win32Native; using System.Runtime.InteropServices; using System.Security.Cryptography.X509Certificates; using Dbg = System.Management.Automation; -using DWORD = System.UInt32; namespace System.Management.Automation { @@ -52,6 +53,8 @@ public enum SigningOption /// internal static class SignatureHelper { + private static Guid WINTRUST_ACTION_GENERIC_VERIFY_V2 = new Guid("00AAC56B-CD44-11d0-8CC2-00C04FC295EE"); + /// /// Tracer for SignatureHelper. /// @@ -103,7 +106,7 @@ internal static Signature SignFile(SigningOption option, bool result = false; Signature signature = null; IntPtr pSignInfo = IntPtr.Zero; - DWORD error = 0; + uint error = 0; string hashOid = null; Utils.CheckArgForNullOrEmpty(fileName, "fileName"); @@ -190,7 +193,7 @@ internal static Signature SignFile(SigningOption option, // able to see that. #pragma warning disable 56523 result = NativeMethods.CryptUIWizDigitalSign( - (DWORD)NativeMethods.CryptUIFlags.CRYPTUI_WIZ_NO_UI, + (uint)NativeMethods.CryptUIFlags.CRYPTUI_WIZ_NO_UI, IntPtr.Zero, IntPtr.Zero, pSignInfo, @@ -246,7 +249,7 @@ internal static Signature SignFile(SigningOption option, } else { - signature = new Signature(fileName, (DWORD)error); + signature = new Signature(fileName, (uint)error); } } finally @@ -330,7 +333,7 @@ private static Signature GetSignatureFromMSSecurityExtensions(string filename) } } - DWORD error = GetErrorFromSignatureState(fileSigInfo.State); + uint error = GetErrorFromSignatureState(fileSigInfo.State); if (fileSigInfo.SigningCertificate is null) { @@ -374,7 +377,7 @@ private static Signature GetSignatureFromMSSecurityExtensions(string filename) } #if !UNIX - private static DWORD GetErrorFromSignatureState(SignatureState signatureState) + private static uint GetErrorFromSignatureState(SignatureState signatureState) { switch (signatureState) { @@ -401,8 +404,8 @@ private static Signature GetSignatureFromWinVerifyTrust(string fileName, string { Signature signature = null; - NativeMethods.WINTRUST_DATA wtd; - DWORD error = Win32Errors.E_FAIL; + WinTrustMethods.WINTRUST_DATA wtd; + uint error = Win32Errors.E_FAIL; if (fileContent == null) { @@ -422,7 +425,10 @@ private static Signature GetSignatureFromWinVerifyTrust(string fileName, string signature = GetSignatureFromWintrustData(fileName, error, wtd); - error = NativeMethods.DestroyWintrustDataStruct(wtd); + wtd.dwStateAction = WinTrustAction.WTD_STATEACTION_CLOSE; + error = WinTrustMethods.WinVerifyTrust(IntPtr.Zero, + ref WINTRUST_ACTION_GENERIC_VERIFY_V2, + ref wtd); if (error != Win32Errors.NO_ERROR) { @@ -438,89 +444,83 @@ private static Signature GetSignatureFromWinVerifyTrust(string fileName, string } [ArchitectureSensitive] - private static DWORD GetWinTrustData(string fileName, string fileContent, - out NativeMethods.WINTRUST_DATA wtData) + private static uint GetWinTrustData(string fileName, string fileContent, + out WinTrustMethods.WINTRUST_DATA wtData) { - DWORD dwResult = Win32Errors.E_FAIL; - IntPtr WINTRUST_ACTION_GENERIC_VERIFY_V2 = IntPtr.Zero; - IntPtr wtdBuffer = IntPtr.Zero; - - Guid actionVerify = - new Guid("00AAC56B-CD44-11d0-8CC2-00C04FC295EE"); - - try + wtData = new() { - WINTRUST_ACTION_GENERIC_VERIFY_V2 = - Marshal.AllocCoTaskMem(Marshal.SizeOf(actionVerify)); - Marshal.StructureToPtr(actionVerify, - WINTRUST_ACTION_GENERIC_VERIFY_V2, - false); - - NativeMethods.WINTRUST_DATA wtd; - - if (fileContent == null) - { - NativeMethods.WINTRUST_FILE_INFO wfi = NativeMethods.InitWintrustFileInfoStruct(fileName); - wtd = NativeMethods.InitWintrustDataStructFromFile(wfi); - } - else + cbStruct = (uint)Marshal.SizeOf(), + dwUIChoice = WinTrustUIChoice.WTD_UI_NONE, + dwStateAction = WinTrustAction.WTD_STATEACTION_VERIFY, + }; + + byte[] contentBytes = fileContent == null + ? Array.Empty() + : System.Text.Encoding.Unicode.GetBytes(fileContent); + unsafe + { + fixed (char* fileNamePtr = fileName) { - NativeMethods.WINTRUST_BLOB_INFO wbi = NativeMethods.InitWintrustBlobInfoStruct(fileName, fileContent); - wtd = NativeMethods.InitWintrustDataStructFromBlob(wbi); - } - - wtdBuffer = Marshal.AllocCoTaskMem(Marshal.SizeOf(wtd)); - Marshal.StructureToPtr(wtd, wtdBuffer, false); - - // The result is returned to the caller, and handled generically. - // Disable the PreFast check for Win32 error codes, as we don't care. -#pragma warning disable 56523 - dwResult = NativeMethods.WinVerifyTrust( - IntPtr.Zero, - WINTRUST_ACTION_GENERIC_VERIFY_V2, - wtdBuffer); -#pragma warning restore 56523 + if (fileContent == null) + { + WinTrustMethods.WINTRUST_FILE_INFO wfi = new() + { + cbStruct = (uint)Marshal.SizeOf(), + pcwszFilePath = fileNamePtr, + }; + wtData.dwUnionChoice = WinTrustUnionChoice.WTD_CHOICE_FILE; + wtData.pChoice = &wfi; + + return WinTrustMethods.WinVerifyTrust(IntPtr.Zero, + ref WINTRUST_ACTION_GENERIC_VERIFY_V2, + ref wtData); + } - wtData = Marshal.PtrToStructure(wtdBuffer); - } - finally - { - Marshal.DestroyStructure(WINTRUST_ACTION_GENERIC_VERIFY_V2); - Marshal.FreeCoTaskMem(WINTRUST_ACTION_GENERIC_VERIFY_V2); - Marshal.DestroyStructure(wtdBuffer); - Marshal.FreeCoTaskMem(wtdBuffer); + fixed (byte* contentPtr = contentBytes) + { + Guid pwshSIP = new("603BCC1F-4B59-4E08-B724-D2C6297EF351"); + WinTrustMethods.WINTRUST_BLOB_INFO wbi = new() + { + cbStruct = (uint)Marshal.SizeOf(), + gSubject = pwshSIP, + pcwszDisplayName = fileNamePtr, + cbMemObject = (uint)contentBytes.Length, + pbMemObject = contentPtr, + }; + wtData.dwUnionChoice = WinTrustUnionChoice.WTD_CHOICE_BLOB; + wtData.pChoice = &wbi; + + return WinTrustMethods.WinVerifyTrust(IntPtr.Zero, + ref WINTRUST_ACTION_GENERIC_VERIFY_V2, + ref wtData); + } + } } - - return dwResult; } [ArchitectureSensitive] private static X509Certificate2 GetCertFromChain(IntPtr pSigner) { - X509Certificate2 signerCert = null; - - // We don't care about the Win32 error code here, so disable - // the PreFast complaint that we're not retrieving it. -#pragma warning disable 56523 - IntPtr pCert = - NativeMethods.WTHelperGetProvCertFromChain(pSigner, 0); -#pragma warning restore 56523 - - if (pCert != IntPtr.Zero) + try { + IntPtr pCert = WinTrustMethods.WTHelperGetProvCertFromChain(pSigner, 0); NativeMethods.CRYPT_PROVIDER_CERT provCert = Marshal.PtrToStructure(pCert); - signerCert = new X509Certificate2(provCert.pCert); + return new X509Certificate2(provCert.pCert); + } + catch (Win32Exception) + { + // We don't care about the Win32 error code here, so return + // null on a failure and let the caller handle it. + return null; } - - return signerCert; } [ArchitectureSensitive] private static Signature GetSignatureFromWintrustData( string filePath, - DWORD error, - NativeMethods.WINTRUST_DATA wtd) + uint error, + WinTrustMethods.WINTRUST_DATA wtd) { s_tracer.WriteLine("GetSignatureFromWintrustData: error: {0}", error); @@ -568,39 +568,36 @@ private static bool TryGetProviderSigner(IntPtr wvtStateData, out IntPtr pProvSi pProvSigner = IntPtr.Zero; timestamperCert = null; - // The GetLastWin32Error of this is checked, but PreSharp doesn't seem to be - // able to see that. -#pragma warning disable 56523 - IntPtr pProvData = - NativeMethods.WTHelperProvDataFromStateData(wvtStateData); -#pragma warning restore 56523 - - if (pProvData != IntPtr.Zero) + try { - pProvSigner = - NativeMethods.WTHelperGetProvSignerFromChain(pProvData, 0, 0, 0); + IntPtr pProvData = WinTrustMethods.WTHelperProvDataFromStateData(wvtStateData); - if (pProvSigner != IntPtr.Zero) - { - NativeMethods.CRYPT_PROVIDER_SGNR provSigner = - Marshal.PtrToStructure(pProvSigner); - if (provSigner.csCounterSigners == 1) - { - // - // time stamper cert available - // - timestamperCert = GetCertFromChain(provSigner.pasCounterSigners); - } + pProvSigner = WinTrustMethods.WTHelperGetProvSignerFromChain( + pProvData, + signerIdx: 0, + counterSigner: false, + counterSignerIdx: 0); - return true; + NativeMethods.CRYPT_PROVIDER_SGNR provSigner = + Marshal.PtrToStructure(pProvSigner); + if (provSigner.csCounterSigners == 1) + { + // + // time stamper cert available + // + timestamperCert = GetCertFromChain(provSigner.pasCounterSigners); } - } - return false; + return true; + } + catch (Win32Exception) + { + return false; + } } [ArchitectureSensitive] - private static DWORD GetLastWin32Error() + private static uint GetLastWin32Error() { int error = Marshal.GetLastWin32Error(); diff --git a/src/System.Management.Automation/security/CatalogHelper.cs b/src/System.Management.Automation/security/CatalogHelper.cs index 585ef801881..5f71d1f86be 100644 --- a/src/System.Management.Automation/security/CatalogHelper.cs +++ b/src/System.Management.Automation/security/CatalogHelper.cs @@ -6,12 +6,13 @@ using System.Security.Cryptography; using System.Collections.Generic; using System.Collections.ObjectModel; +using System.ComponentModel; using System.IO; using System.Linq; using System.Management.Automation.Internal; using System.Management.Automation.Security; +using System.Management.Automation.Win32Native; using System.Runtime.InteropServices; -using DWORD = System.UInt32; namespace System.Management.Automation { @@ -83,12 +84,11 @@ internal static class CatalogHelper /// /// Handle to open catalog file. /// Version of the catalog. - private static int GetCatalogVersion(IntPtr catalogHandle) + private static int GetCatalogVersion(SafeCATHandle catalogHandle) { int catalogVersion = -1; - IntPtr catalogData = NativeMethods.CryptCATStoreFromHandle(catalogHandle); - NativeMethods.CRYPTCATSTORE catalogInfo = Marshal.PtrToStructure(catalogData); + WinTrustMethods.CRYPTCATSTORE catalogInfo = WinTrustMethods.CryptCATStoreFromHandle(catalogHandle); if (catalogInfo.dwPublicVersion == catalogVersion2) { @@ -248,20 +248,32 @@ internal static void ProcessFileToBeAddedInCatalogDefinitionFile(FileInfo fileTo /// Path to the Input .cdf file. internal static void GenerateCatalogFile(string cdfFilePath) { - string pwszFilePath = cdfFilePath; - NativeMethods.CryptCATCDFOpenCallBack catOpenCallBack = new NativeMethods.CryptCATCDFOpenCallBack(ParseErrorCallback); - // Open CDF File - IntPtr resultCDF = NativeMethods.CryptCATCDFOpen(pwszFilePath, catOpenCallBack); + SafeCATCDFHandle resultCDF; + try + { + resultCDF = WinTrustMethods.CryptCATCDFOpen(cdfFilePath, ParseErrorCallback); + } + catch (Win32Exception e) + { + // If we are not able to open CDF file we can not continue generating catalog + ErrorRecord errorRecord = new ErrorRecord( + new InvalidOperationException(CatalogStrings.UnableToOpenCatalogDefinitionFile, e), + "UnableToOpenCatalogDefinitionFile", + ErrorCategory.InvalidOperation, + null); + _cmdlet.ThrowTerminatingError(errorRecord); + return; + } // navigate CDF header and files sections - if (resultCDF != IntPtr.Zero) + using (resultCDF) { // First navigate all catalog level attributes entries first, they represent zero size files IntPtr catalogAttr = IntPtr.Zero; do { - catalogAttr = NativeMethods.CryptCATCDFEnumCatAttributes(resultCDF, catalogAttr, catOpenCallBack); + catalogAttr = WinTrustMethods.CryptCATCDFEnumCatAttributes(resultCDF, catalogAttr, ParseErrorCallback); if (catalogAttr != IntPtr.Zero) { @@ -272,51 +284,38 @@ internal static void GenerateCatalogFile(string cdfFilePath) // navigate all the files hash entries in the .cdf file IntPtr memberInfo = IntPtr.Zero; - try + IntPtr memberFile = IntPtr.Zero; + string fileName = string.Empty; + do { - IntPtr memberFile = IntPtr.Zero; - NativeMethods.CryptCATCDFEnumMembersByCDFTagExErrorCallBack memberCallBack = new NativeMethods.CryptCATCDFEnumMembersByCDFTagExErrorCallBack(ParseErrorCallback); - string fileName = string.Empty; - do - { - memberFile = NativeMethods.CryptCATCDFEnumMembersByCDFTagEx(resultCDF, memberFile, memberCallBack, ref memberInfo, true, IntPtr.Zero); - fileName = Marshal.PtrToStringUni(memberFile); + memberFile = WinTrustMethods.CryptCATCDFEnumMembersByCDFTagEx(resultCDF, memberFile, ParseErrorCallback, ref memberInfo, + fContinueOnError: true, pvReserved: IntPtr.Zero); + fileName = Marshal.PtrToStringUni(memberFile); - if (!string.IsNullOrEmpty(fileName)) + if (!string.IsNullOrEmpty(fileName)) + { + IntPtr memberAttr = IntPtr.Zero; + string fileRelativePath = string.Empty; + do { - IntPtr memberAttr = IntPtr.Zero; - string fileRelativePath = string.Empty; - do - { - memberAttr = NativeMethods.CryptCATCDFEnumAttributesWithCDFTag(resultCDF, memberFile, memberInfo, memberAttr, memberCallBack); + memberAttr = WinTrustMethods.CryptCATCDFEnumAttributesWithCDFTag(resultCDF, memberFile, memberInfo, memberAttr, ParseErrorCallback); - if (memberAttr != IntPtr.Zero) + if (memberAttr != IntPtr.Zero) + { + fileRelativePath = ProcessFilePathAttributeInCatalog(memberAttr); + if (!string.IsNullOrEmpty(fileRelativePath)) { - fileRelativePath = ProcessFilePathAttributeInCatalog(memberAttr); - if (!string.IsNullOrEmpty(fileRelativePath)) - { - // Found the attribute we are looking for - // Filename we read from the above API has appended to its name as per CDF file tags convention - // Truncating that Information from the string. - string itemName = fileName.Substring(6); - _cmdlet.WriteVerbose(StringUtil.Format(CatalogStrings.AddFileToCatalog, itemName, fileRelativePath)); - break; - } + // Found the attribute we are looking for + // Filename we read from the above API has appended to its name as per CDF file tags convention + // Truncating that Information from the string. + string itemName = fileName.Substring(6); + _cmdlet.WriteVerbose(StringUtil.Format(CatalogStrings.AddFileToCatalog, itemName, fileRelativePath)); + break; } - } while (memberAttr != IntPtr.Zero); - } - } while (fileName != null); - } - finally - { - NativeMethods.CryptCATCDFClose(resultCDF); - } - } - else - { - // If we are not able to open CDF file we can not continue generating catalog - ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(CatalogStrings.UnableToOpenCatalogDefinitionFile), "UnableToOpenCatalogDefinitionFile", ErrorCategory.InvalidOperation, null); - _cmdlet.ThrowTerminatingError(errorRecord); + } + } while (memberAttr != IntPtr.Zero); + } + } while (fileName != null); } } @@ -374,7 +373,7 @@ internal static string ProcessFilePathAttributeInCatalog(IntPtr memberAttrInfo) { string relativePath = string.Empty; - NativeMethods.CRYPTCATATTRIBUTE currentMemberAttr = Marshal.PtrToStructure(memberAttrInfo); + WinTrustMethods.CRYPTCATATTRIBUTE currentMemberAttr = Marshal.PtrToStructure(memberAttrInfo); // check if this is the attribute we are looking for // catalog generated other way not using New-FileCatalog can have attributes we don't understand @@ -400,69 +399,65 @@ internal static string ProcessFilePathAttributeInCatalog(IntPtr memberAttrInfo) internal static string CalculateFileHash(string filePath, string hashAlgorithm) { string hashValue = string.Empty; - IntPtr catAdmin = IntPtr.Zero; // To get handle to the hash algorithm to be used to calculate hashes - if (!NativeMethods.CryptCATAdminAcquireContext2(ref catAdmin, IntPtr.Zero, hashAlgorithm, IntPtr.Zero, 0)) + SafeCATAdminHandle catAdmin; + try { - ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(CatalogStrings.UnableToAcquireHashAlgorithmContext, hashAlgorithm)), "UnableToAcquireHashAlgorithmContext", ErrorCategory.InvalidOperation, null); - _cmdlet.ThrowTerminatingError(errorRecord); + catAdmin = WinTrustMethods.CryptCATAdminAcquireContext2(hashAlgorithm); } + catch (Win32Exception e) + { + ErrorRecord errorRecord = new ErrorRecord( + new InvalidOperationException(StringUtil.Format(CatalogStrings.UnableToAcquireHashAlgorithmContext, hashAlgorithm), e), + "UnableToAcquireHashAlgorithmContext", + ErrorCategory.InvalidOperation, + null); + _cmdlet.ThrowTerminatingError(errorRecord); - const DWORD GENERIC_READ = 0x80000000; - const DWORD OPEN_EXISTING = 3; - IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1); + // The method returns an empty string on a failure. + return hashValue; + } // Open the file that is to be hashed for reading and get its handle - IntPtr fileHandle = NativeMethods.CreateFile(filePath, GENERIC_READ, 0, 0, OPEN_EXISTING, 0, IntPtr.Zero); - if (fileHandle != INVALID_HANDLE_VALUE) + FileStream fileStream; + try { - try - { - DWORD hashBufferSize = 0; - IntPtr hashBuffer = IntPtr.Zero; - - // Call first time to get the size of expected buffer to hold new hash value - if (!NativeMethods.CryptCATAdminCalcHashFromFileHandle2(catAdmin, fileHandle, ref hashBufferSize, hashBuffer, 0)) - { - ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(CatalogStrings.UnableToCreateFileHash, filePath)), "UnableToCreateFileHash", ErrorCategory.InvalidOperation, null); - _cmdlet.ThrowTerminatingError(errorRecord); - } + fileStream = File.Open(filePath, FileMode.Open, FileAccess.Read); + } + catch (Exception e) + { + // If we are not able to open file that is to be hashed we can not continue with catalog validation + ErrorRecord errorRecord = new ErrorRecord( + new InvalidOperationException(StringUtil.Format(CatalogStrings.UnableToReadFileToHash, filePath), e), + "UnableToReadFileToHash", + ErrorCategory.InvalidOperation, + null); + _cmdlet.ThrowTerminatingError(errorRecord); - int size = (int)hashBufferSize; - hashBuffer = Marshal.AllocHGlobal(size); - try - { - // Call second time to actually get the hash value - if (!NativeMethods.CryptCATAdminCalcHashFromFileHandle2(catAdmin, fileHandle, ref hashBufferSize, hashBuffer, 0)) - { - ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(CatalogStrings.UnableToCreateFileHash, filePath)), "UnableToCreateFileHash", ErrorCategory.InvalidOperation, null); - _cmdlet.ThrowTerminatingError(errorRecord); - } + // The method returns an empty string on a failure. + return hashValue; + } - byte[] hashBytes = new byte[size]; - Marshal.Copy(hashBuffer, hashBytes, 0, size); - hashValue = BitConverter.ToString(hashBytes).Replace("-", string.Empty); - } - finally - { - if (hashBuffer != IntPtr.Zero) - { - Marshal.FreeHGlobal(hashBuffer); - } - } + using (catAdmin) + using (fileStream) + { + byte[] hashBytes = Array.Empty(); + try + { + hashBytes = WinTrustMethods.CryptCATAdminCalcHashFromFileHandle2(catAdmin, fileStream.SafeFileHandle); } - finally + catch (Win32Exception e) { - NativeMethods.CryptCATAdminReleaseContext(catAdmin, 0); - NativeMethods.CloseHandle(fileHandle); + ErrorRecord errorRecord = new ErrorRecord( + new InvalidOperationException(StringUtil.Format(CatalogStrings.UnableToCreateFileHash, filePath), e), + "UnableToCreateFileHash", + ErrorCategory.InvalidOperation, + null); + _cmdlet.ThrowTerminatingError(errorRecord); } - } - else - { - // If we are not able to open file that is to be hashed we can not continue with catalog validation - ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(CatalogStrings.UnableToReadFileToHash, filePath)), "UnableToReadFileToHash", ErrorCategory.InvalidOperation, null); - _cmdlet.ThrowTerminatingError(errorRecord); + + hashValue = BitConverter.ToString(hashBytes).Replace("-", string.Empty); } return hashValue; @@ -477,90 +472,92 @@ internal static string CalculateFileHash(string filePath, string hashAlgorithm) /// Dictionary mapping files relative paths to HashValues. internal static Dictionary GetHashesFromCatalog(string catalogFilePath, WildcardPattern[] excludedPatterns, out int catalogVersion) { - IntPtr resultCatalog = NativeMethods.CryptCATOpen(catalogFilePath, 0, IntPtr.Zero, 1, 0); - IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1); Dictionary catalogHashes = new Dictionary(StringComparer.CurrentCultureIgnoreCase); catalogVersion = 0; - if (resultCatalog != INVALID_HANDLE_VALUE) + SafeCATHandle resultCatalog; + try { - try + resultCatalog = WinTrustMethods.CryptCATOpen(catalogFilePath, 0, IntPtr.Zero, 1, 0); + } + catch (Win32Exception e) + { + ErrorRecord errorRecord = new ErrorRecord( + new InvalidOperationException(StringUtil.Format(CatalogStrings.UnableToOpenCatalogFile, catalogFilePath), e), + "UnableToOpenCatalogFile", + ErrorCategory.InvalidOperation, + null); + _cmdlet.ThrowTerminatingError(errorRecord); + return catalogHashes; + } + + using (resultCatalog) + { + IntPtr catAttrInfo = IntPtr.Zero; + + // First traverse all catalog level attributes to get information about zero size file. + do { - IntPtr catAttrInfo = IntPtr.Zero; + catAttrInfo = WinTrustMethods.CryptCATEnumerateCatAttr(resultCatalog, catAttrInfo); - // First traverse all catalog level attributes to get information about zero size file. - do + // If we found attribute it is a file information retrieve its relative path + // and add it to catalog hash collection if its not in excluded files criteria + if (catAttrInfo != IntPtr.Zero) { - catAttrInfo = NativeMethods.CryptCATEnumerateCatAttr(resultCatalog, catAttrInfo); - - // If we found attribute it is a file information retrieve its relative path - // and add it to catalog hash collection if its not in excluded files criteria - if (catAttrInfo != IntPtr.Zero) + string relativePath = ProcessFilePathAttributeInCatalog(catAttrInfo); + if (!string.IsNullOrEmpty(relativePath)) { - string relativePath = ProcessFilePathAttributeInCatalog(catAttrInfo); - if (!string.IsNullOrEmpty(relativePath)) - { - ProcessCatalogFile(relativePath, string.Empty, excludedPatterns, ref catalogHashes); - } + ProcessCatalogFile(relativePath, string.Empty, excludedPatterns, ref catalogHashes); } - } while (catAttrInfo != IntPtr.Zero); + } + } while (catAttrInfo != IntPtr.Zero); - catalogVersion = GetCatalogVersion(resultCatalog); + catalogVersion = GetCatalogVersion(resultCatalog); - IntPtr memberInfo = IntPtr.Zero; - // Next Navigate all members in Catalog files and get their relative paths and hashes - do + IntPtr memberInfo = IntPtr.Zero; + // Next Navigate all members in Catalog files and get their relative paths and hashes + do + { + memberInfo = WinTrustMethods.CryptCATEnumerateMember(resultCatalog, memberInfo); + if (memberInfo != IntPtr.Zero) { - memberInfo = NativeMethods.CryptCATEnumerateMember(resultCatalog, memberInfo); - if (memberInfo != IntPtr.Zero) - { - NativeMethods.CRYPTCATMEMBER currentMember = Marshal.PtrToStructure(memberInfo); - NativeMethods.SIP_INDIRECT_DATA pIndirectData = Marshal.PtrToStructure(currentMember.pIndirectData); + WinTrustMethods.CRYPTCATMEMBER currentMember = Marshal.PtrToStructure(memberInfo); + WinTrustMethods.SIP_INDIRECT_DATA pIndirectData = Marshal.PtrToStructure(currentMember.pIndirectData); - // For Catalog version 2 CryptoAPI puts hashes of file attributes(relative path in our case) in Catalog as well - // We validate those along with file hashes so we are skipping duplicate entries - if (!((catalogVersion == 2) && (pIndirectData.DigestAlgorithm.pszObjId.Equals(new Oid("SHA1").Value, StringComparison.OrdinalIgnoreCase)))) + // For Catalog version 2 CryptoAPI puts hashes of file attributes(relative path in our case) in Catalog as well + // We validate those along with file hashes so we are skipping duplicate entries + if (!((catalogVersion == 2) && (pIndirectData.DigestAlgorithm.pszObjId.Equals(new Oid("SHA1").Value, StringComparison.OrdinalIgnoreCase)))) + { + string relativePath = string.Empty; + IntPtr memberAttrInfo = IntPtr.Zero; + do { - string relativePath = string.Empty; - IntPtr memberAttrInfo = IntPtr.Zero; - do - { - memberAttrInfo = NativeMethods.CryptCATEnumerateAttr(resultCatalog, memberInfo, memberAttrInfo); + memberAttrInfo = WinTrustMethods.CryptCATEnumerateAttr(resultCatalog, memberInfo, memberAttrInfo); - if (memberAttrInfo != IntPtr.Zero) + if (memberAttrInfo != IntPtr.Zero) + { + relativePath = ProcessFilePathAttributeInCatalog(memberAttrInfo); + if (!string.IsNullOrEmpty(relativePath)) { - relativePath = ProcessFilePathAttributeInCatalog(memberAttrInfo); - if (!string.IsNullOrEmpty(relativePath)) - { - break; - } + break; } } - while (memberAttrInfo != IntPtr.Zero); - - // If we did not find any Relative Path for the item in catalog we should quit - // This catalog must not be valid for our use as catalogs generated using New-FileCatalog - // always contains relative file Paths - if (string.IsNullOrEmpty(relativePath)) - { - ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(CatalogStrings.UnableToOpenCatalogFile, catalogFilePath)), "UnableToOpenCatalogFile", ErrorCategory.InvalidOperation, null); - _cmdlet.ThrowTerminatingError(errorRecord); - } + } + while (memberAttrInfo != IntPtr.Zero); - ProcessCatalogFile(relativePath, currentMember.pwszReferenceTag, excludedPatterns, ref catalogHashes); + // If we did not find any Relative Path for the item in catalog we should quit + // This catalog must not be valid for our use as catalogs generated using New-FileCatalog + // always contains relative file Paths + if (string.IsNullOrEmpty(relativePath)) + { + ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(CatalogStrings.UnableToOpenCatalogFile, catalogFilePath)), "UnableToOpenCatalogFile", ErrorCategory.InvalidOperation, null); + _cmdlet.ThrowTerminatingError(errorRecord); } + + ProcessCatalogFile(relativePath, currentMember.pwszReferenceTag, excludedPatterns, ref catalogHashes); } - } while (memberInfo != IntPtr.Zero); - } - finally - { - NativeMethods.CryptCATClose(resultCatalog); - } - } - else - { - ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(CatalogStrings.UnableToOpenCatalogFile, catalogFilePath)), "UnableToOpenCatalogFile", ErrorCategory.InvalidOperation, null); - _cmdlet.ThrowTerminatingError(errorRecord); + } + } while (memberInfo != IntPtr.Zero); } return catalogHashes; @@ -785,14 +782,18 @@ internal static bool CheckExcludedCriteria(string filename, WildcardPattern[] ex /// /// Call back when error is thrown by catalog API's. /// - private static void ParseErrorCallback(DWORD dwErrorArea, DWORD dwLocalError, string pwszLine) + private static void ParseErrorCallback(uint dwErrorArea, uint dwLocalError, string pwszLine) { switch (dwErrorArea) { - case NativeConstants.CRYPTCAT_E_AREA_HEADER: break; - case NativeConstants.CRYPTCAT_E_AREA_MEMBER: break; - case NativeConstants.CRYPTCAT_E_AREA_ATTRIBUTE: break; - default: break; + case NativeConstants.CRYPTCAT_E_AREA_HEADER: + break; + case NativeConstants.CRYPTCAT_E_AREA_MEMBER: + break; + case NativeConstants.CRYPTCAT_E_AREA_ATTRIBUTE: + break; + default: + break; } switch (dwLocalError) @@ -815,18 +816,24 @@ private static void ParseErrorCallback(DWORD dwErrorArea, DWORD dwLocalError, st _cmdlet.ThrowTerminatingError(errorRecord); break; } - case NativeConstants.CRYPTCAT_E_CDF_BAD_GUID_CONV: break; - case NativeConstants.CRYPTCAT_E_CDF_ATTR_TYPECOMBO: break; - case NativeConstants.CRYPTCAT_E_CDF_ATTR_TOOFEWVALUES: break; - case NativeConstants.CRYPTCAT_E_CDF_UNSUPPORTED: break; + case NativeConstants.CRYPTCAT_E_CDF_BAD_GUID_CONV: + break; + case NativeConstants.CRYPTCAT_E_CDF_ATTR_TYPECOMBO: + break; + case NativeConstants.CRYPTCAT_E_CDF_ATTR_TOOFEWVALUES: + break; + case NativeConstants.CRYPTCAT_E_CDF_UNSUPPORTED: + break; case NativeConstants.CRYPTCAT_E_CDF_DUPLICATE: { ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(CatalogStrings.FoundDuplicateFileMemberInCatalog, pwszLine)), "FoundDuplicateFileMemberInCatalog", ErrorCategory.InvalidOperation, null); _cmdlet.ThrowTerminatingError(errorRecord); break; } - case NativeConstants.CRYPTCAT_E_CDF_TAGNOTFOUND: break; - default: break; + case NativeConstants.CRYPTCAT_E_CDF_TAGNOTFOUND: + break; + default: + break; } } } diff --git a/src/System.Management.Automation/security/Win32Native/WinTrust.cs b/src/System.Management.Automation/security/Win32Native/WinTrust.cs new file mode 100644 index 00000000000..c3b7bb85d91 --- /dev/null +++ b/src/System.Management.Automation/security/Win32Native/WinTrust.cs @@ -0,0 +1,440 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.ComponentModel; +using System.Runtime.InteropServices; + +namespace System.Management.Automation.Win32Native; + +internal class SafeCATAdminHandle : SafeHandle +{ + internal SafeCATAdminHandle() : base(IntPtr.Zero, true) { } + + public override bool IsInvalid => handle == IntPtr.Zero; + + protected override bool ReleaseHandle() => WinTrustMethods.CryptCATAdminReleaseContext(handle, 0); +} + +internal class SafeCATHandle : SafeHandle +{ + internal SafeCATHandle() : base(IntPtr.Zero, true) { } + + public override bool IsInvalid => handle == (IntPtr)(-1); + + protected override bool ReleaseHandle() => WinTrustMethods.CryptCATClose(handle); +} + +internal class SafeCATCDFHandle : SafeHandle +{ + internal SafeCATCDFHandle() : base(IntPtr.Zero, true) { } + + public override bool IsInvalid => handle == IntPtr.Zero; + + protected override bool ReleaseHandle() => WinTrustMethods.CryptCATCDFClose(handle); +} + +[Flags] +internal enum WinTrustUIChoice +{ + WTD_UI_ALL = 1, + WTD_UI_NONE = 2, + WTD_UI_NOBAD = 3, + WTD_UI_NOGOOD = 4 +} + +[Flags] +internal enum WinTrustUnionChoice +{ + WTD_CHOICE_FILE = 1, + WTD_CHOICE_CATALOG = 2, + WTD_CHOICE_BLOB = 3, + WTD_CHOICE_SIGNER = 4, + WTD_CHOICE_CERT = 5, +} + +[Flags] +internal enum WinTrustAction +{ + WTD_STATEACTION_IGNORE = 0x00000000, + WTD_STATEACTION_VERIFY = 0x00000001, + WTD_STATEACTION_CLOSE = 0x00000002, + WTD_STATEACTION_AUTO_CACHE = 0x00000003, + WTD_STATEACTION_AUTO_CACHE_FLUSH = 0x00000004 +} + +[Flags] +internal enum WinTrustProviderFlags +{ + WTD_PROV_FLAGS_MASK = 0x0000FFFF, + WTD_USE_IE4_TRUST_FLAG = 0x00000001, + WTD_NO_IE4_CHAIN_FLAG = 0x00000002, + WTD_NO_POLICY_USAGE_FLAG = 0x00000004, + WTD_REVOCATION_CHECK_NONE = 0x00000010, + WTD_REVOCATION_CHECK_END_CERT = 0x00000020, + WTD_REVOCATION_CHECK_CHAIN = 0x00000040, + WTD_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT = 0x00000080, + WTD_SAFER_FLAG = 0x00000100, + WTD_HASH_ONLY_FLAG = 0x00000200, + WTD_USE_DEFAULT_OSVER_CHECK = 0x00000400, + WTD_LIFETIME_SIGNING_FLAG = 0x00000800, + WTD_CACHE_ONLY_URL_RETRIEVAL = 0x00001000 +} + +/// +/// Pinvoke methods from wintrust.dll +/// +internal static class WinTrustMethods +{ + private const string WinTrustDll = "wintrust.dll"; + + [StructLayout(LayoutKind.Sequential)] + internal struct CRYPT_ATTR_BLOB + { + public uint cbData; + public IntPtr pbData; + } + + [StructLayoutAttribute(LayoutKind.Sequential)] + internal struct CRYPT_ALGORITHM_IDENTIFIER + { + [MarshalAsAttribute(UnmanagedType.LPStr)] public string pszObjId; + public CRYPT_ATTR_BLOB Parameters; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct CRYPT_ATTRIBUTE_TYPE_VALUE + { + [MarshalAs(UnmanagedType.LPStr)] public string pszObjId; + public CRYPT_ATTR_BLOB Value; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct SIP_INDIRECT_DATA + { + public CRYPT_ATTRIBUTE_TYPE_VALUE Data; + public CRYPT_ALGORITHM_IDENTIFIER DigestAlgorithm; + public CRYPT_ATTR_BLOB Digest; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct CRYPTCATMEMBER + { + public uint cbStruct; + [MarshalAs(UnmanagedType.LPWStr)] public string pwszReferenceTag; + [MarshalAs(UnmanagedType.LPWStr)] public string pwszFileName; + public Guid gSubjectType; + public uint fdwMemberFlags; + public IntPtr pIndirectData; + public uint dwCertVersion; + public uint dwReserved; + public IntPtr hReserved; + public CRYPT_ATTR_BLOB sEncodedIndirectData; + public CRYPT_ATTR_BLOB sEncodedMemberInfo; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct CRYPTCATATTRIBUTE + { + public uint cbStruct; + [MarshalAs(UnmanagedType.LPWStr)] public string pwszReferenceTag; + public uint dwAttrTypeAndAction; + public uint cbValue; + public IntPtr pbValue; + public uint dwReserved; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct CRYPTCATSTORE + { + public uint cbStruct; + public uint dwPublicVersion; + [MarshalAs(UnmanagedType.LPWStr)] public string pwszP7File; + public IntPtr hProv; + public uint dwEncodingType; + public uint fdwStoreFlags; + public IntPtr hReserved; + public IntPtr hAttrs; + public IntPtr hCryptMsg; + public IntPtr hSorted; + } + + [StructLayoutAttribute(LayoutKind.Sequential)] + internal struct WINTRUST_DATA + { + public uint cbStruct; + public IntPtr pPolicyCallbackData; + public IntPtr pSIPClientData; + public WinTrustUIChoice dwUIChoice; + public uint fdwRevocationChecks; + public WinTrustUnionChoice dwUnionChoice; + public unsafe void* pChoice; + public WinTrustAction dwStateAction; + public IntPtr hWVTStateData; + public IntPtr pwszURLReference; + public WinTrustProviderFlags dwProvFlags; + public uint dwUIContext; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct WINTRUST_FILE_INFO + { + public uint cbStruct; + public unsafe char* pcwszFilePath; + public IntPtr hFile; + public IntPtr pgKnownSubject; + } + + [StructLayoutAttribute(LayoutKind.Sequential)] + internal struct WINTRUST_BLOB_INFO + { + public uint cbStruct; + public Guid gSubject; + public unsafe char* pcwszDisplayName; + public uint cbMemObject; + public unsafe byte* pbMemObject; + public uint cbMemSignedMsg; + public IntPtr pbMemSignedMsg; + } + + [DllImport( + WinTrustDll, + CharSet = CharSet.Unicode, + EntryPoint = "CryptCATAdminAcquireContext2", + SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool NativeCryptCATAdminAcquireContext2( + out SafeCATAdminHandle phCatAdmin, + IntPtr pgSubsystem, + [MarshalAs(UnmanagedType.LPWStr)] string pwszHashAlgorithm, + IntPtr pStrongHashPolicy, + uint dwFlags + ); + + internal static SafeCATAdminHandle CryptCATAdminAcquireContext2(string hashAlgorithm) + { + if (!NativeCryptCATAdminAcquireContext2(out var adminHandle, IntPtr.Zero, hashAlgorithm, IntPtr.Zero, 0)) + { + throw new Win32Exception(); + } + + return adminHandle; + } + + [DllImport( + WinTrustDll, + CharSet = CharSet.Unicode, + EntryPoint = "CryptCATAdminCalcHashFromFileHandle2", + SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern unsafe bool NativeCryptCATAdminCalcHashFromFileHandle2( + SafeCATAdminHandle hCatAdmin, + SafeHandle hFile, + [In, Out] ref int pcbHash, + byte* pbHash, + uint dwFlags + ); + + internal static byte[] CryptCATAdminCalcHashFromFileHandle2(SafeCATAdminHandle catAdmin, SafeHandle file) + { + unsafe + { + int hashLength = 0; + NativeCryptCATAdminCalcHashFromFileHandle2(catAdmin, file, ref hashLength, null, 0); + + byte[] hash = new byte[hashLength]; + fixed (byte* hashPtr = hash) + { + if (!NativeCryptCATAdminCalcHashFromFileHandle2(catAdmin, file, ref hashLength, hashPtr, 0)) + { + throw new Win32Exception(); + } + } + + return hash; + } + } + + [DllImport(WinTrustDll, CharSet = CharSet.Unicode)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool CryptCATAdminReleaseContext( + IntPtr phCatAdmin, + uint dwFlags + ); + + [DllImport(WinTrustDll, CharSet = CharSet.Unicode, EntryPoint = "CryptCATCDFOpen")] + private static extern SafeCATCDFHandle NativeCryptCATCDFOpen( + [MarshalAs(UnmanagedType.LPWStr)] string pwszFilePath, + CryptCATCDFParseErrorCallBack pfnParseError + ); + + internal static SafeCATCDFHandle CryptCATCDFOpen(string filePath, CryptCATCDFParseErrorCallBack parseError) + { + SafeCATCDFHandle handle = NativeCryptCATCDFOpen(filePath, parseError); + if (handle.IsInvalid) + { + throw new Win32Exception(); + } + + return handle; + } + + [DllImport(WinTrustDll, CharSet = CharSet.Unicode)] + internal static extern IntPtr CryptCATCDFEnumCatAttributes( + SafeCATCDFHandle pCDF, + IntPtr pPrevAttr, + CryptCATCDFParseErrorCallBack pfnParseError + ); + + [DllImport(WinTrustDll)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool CryptCATCDFClose( + IntPtr pCDF + ); + + [DllImport(WinTrustDll, CharSet = CharSet.Unicode)] + internal static extern IntPtr CryptCATCDFEnumMembersByCDFTagEx( + SafeCATCDFHandle pCDF, + IntPtr pwszPrevCDFTag, + CryptCATCDFParseErrorCallBack fn, + ref IntPtr ppMember, + bool fContinueOnError, + IntPtr pvReserved + ); + + [DllImport(WinTrustDll, CharSet = CharSet.Unicode)] + internal static extern IntPtr CryptCATCDFEnumAttributesWithCDFTag( + SafeCATCDFHandle pCDF, + IntPtr pwszMemberTag, + IntPtr pMember, + IntPtr pPrevAttr, + CryptCATCDFParseErrorCallBack fn + ); + + [DllImport(WinTrustDll, CharSet = CharSet.Unicode)] + internal static extern IntPtr CryptCATEnumerateCatAttr( + SafeCATHandle hCatalog, + IntPtr pPrevAttr + ); + + [DllImport(WinTrustDll, CharSet = CharSet.Unicode, EntryPoint = "CryptCATOpen", SetLastError = true)] + internal static extern SafeCATHandle NativeCryptCATOpen( + [MarshalAs(UnmanagedType.LPWStr)] string pwszFilePath, + uint fdwOpenFlags, + IntPtr hProv, + uint dwPublicVersion, + uint dwEncodingType + ); + + internal static SafeCATHandle CryptCATOpen(string filePath, uint openFlags, IntPtr provider, uint publicVersion, + uint encodingType) + { + SafeCATHandle handle = NativeCryptCATOpen(filePath, openFlags, provider, publicVersion, encodingType); + if (handle.IsInvalid) + { + throw new Win32Exception(); + } + + return handle; + } + + [DllImport(WinTrustDll)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool CryptCATClose( + IntPtr hCatalog + ); + + [DllImport(WinTrustDll, CharSet = CharSet.Unicode, EntryPoint = "CryptCATStoreFromHandle")] + private static extern IntPtr NativeCryptCATStoreFromHandle( + SafeCATHandle hCatalog + ); + + internal static CRYPTCATSTORE CryptCATStoreFromHandle(SafeCATHandle catalog) + { + IntPtr catStore = NativeCryptCATStoreFromHandle(catalog); + return Marshal.PtrToStructure(catStore); + } + + [DllImport(WinTrustDll, CharSet = CharSet.Unicode)] + internal static extern IntPtr CryptCATEnumerateMember( + SafeCATHandle hCatalog, + IntPtr pPrevMember + ); + + [DllImport(WinTrustDll, CharSet = CharSet.Unicode)] + internal static extern IntPtr CryptCATEnumerateAttr( + SafeCATHandle hCatalog, + IntPtr pCatMember, + IntPtr pPrevAttr + ); + + [DllImport(WinTrustDll, CharSet = CharSet.Unicode)] + internal static extern uint WinVerifyTrust( + IntPtr hWnd, + ref Guid pgActionID, + ref WINTRUST_DATA pWVTData + ); + + [DllImport(WinTrustDll, CharSet = CharSet.Unicode, EntryPoint = "WTHelperGetProvCertFromChain")] + private static extern IntPtr NativeWTHelperGetProvCertFromChain( + IntPtr pSgnr, + uint idxCert + ); + + internal static IntPtr WTHelperGetProvCertFromChain(IntPtr signer, uint certIdx) + { + IntPtr data = NativeWTHelperGetProvCertFromChain(signer, certIdx); + if (data == IntPtr.Zero) + { + throw new Win32Exception("WTHelperGetProvCertFromChain failed"); + } + + return data; + } + + [DllImport(WinTrustDll, CharSet = CharSet.Unicode, EntryPoint = "WTHelperGetProvSignerFromChain")] + private static extern IntPtr NativeWTHelperGetProvSignerFromChain( + IntPtr pProvData, + uint idxSigner, + bool fCounterSigner, + uint idxCounterSigner + ); + + internal static IntPtr WTHelperGetProvSignerFromChain(IntPtr providerData, uint signerIdx, bool counterSigner, + uint counterSignerIdx) + { + IntPtr data = NativeWTHelperGetProvSignerFromChain(providerData, signerIdx, counterSigner, counterSignerIdx); + if (data == IntPtr.Zero) + { + throw new Win32Exception("WTHelperGetProvSignerFromChain failed"); + } + + return data; + } + + [DllImport(WinTrustDll, CharSet = CharSet.Unicode, EntryPoint = "WTHelperProvDataFromStateData")] + private static extern IntPtr NativeWTHelperProvDataFromStateData( + IntPtr hStateData + ); + + internal static IntPtr WTHelperProvDataFromStateData(IntPtr stateData) + { + IntPtr data = NativeWTHelperProvDataFromStateData(stateData); + if (data == IntPtr.Zero) + { + throw new Win32Exception("WTHelperProvDataFromStateData failed"); + } + + return data; + } + + /// + /// Signature of call back function used by CryptCATCDFOpen, + /// CryptCATCDFEnumCatAttributes, CryptCATCDFEnumAttributesWithCDFTag, and + /// and CryptCATCDFEnumMembersByCDFTagEx. + /// + internal delegate void CryptCATCDFParseErrorCallBack( + uint dwErrorArea, + uint dwLocalArea, + [MarshalAs(UnmanagedType.LPWStr)] string pwszLine + ); +} diff --git a/src/System.Management.Automation/security/nativeMethods.cs b/src/System.Management.Automation/security/nativeMethods.cs index 69ed655963d..782b6f43393 100644 --- a/src/System.Management.Automation/security/nativeMethods.cs +++ b/src/System.Management.Automation/security/nativeMethods.cs @@ -779,312 +779,6 @@ internal static CRYPTUI_WIZ_DIGITAL_SIGN_INFO return si; } - // ----------------------------------------------------------------- - // wintrust.dll stuff - // - - // - // WinVerifyTrust() function and associated structures/enums - // - - [DllImport("wintrust.dll", SetLastError = true, CharSet = CharSet.Unicode)] - internal static extern - DWORD WinVerifyTrust( - IntPtr hWndNotUsed, // HWND - IntPtr pgActionID, // GUID* - IntPtr pWinTrustData // WINTRUST_DATA* - ); - - [StructLayout(LayoutKind.Sequential)] - internal struct WINTRUST_FILE_INFO - { - internal DWORD cbStruct; // = sizeof(WINTRUST_FILE_INFO) - - [MarshalAs(UnmanagedType.LPWStr)] - internal string pcwszFilePath; // LPCWSTR - - internal IntPtr hFileNotUsed; // optional, HANDLE to pcwszFilePath - internal IntPtr pgKnownSubjectNotUsed; // optional: GUID* : fill if the - // subject type is known - } - - [StructLayoutAttribute(LayoutKind.Sequential)] - internal struct WINTRUST_BLOB_INFO - { - /// DWORD->unsigned int - internal uint cbStruct; - - /// GUID->_GUID - internal Guid gSubject; - - /// LPCWSTR->WCHAR* - [MarshalAsAttribute(UnmanagedType.LPWStr)] - internal string pcwszDisplayName; - - /// DWORD->unsigned int - internal uint cbMemObject; - - /// BYTE* - internal System.IntPtr pbMemObject; - - /// DWORD->unsigned int - internal uint cbMemSignedMsg; - - /// BYTE* - internal System.IntPtr pbMemSignedMsg; - } - - [ArchitectureSensitive] - internal static WINTRUST_FILE_INFO InitWintrustFileInfoStruct(string fileName) - { - WINTRUST_FILE_INFO fi = new WINTRUST_FILE_INFO(); - - fi.cbStruct = (DWORD)Marshal.SizeOf(fi); - fi.pcwszFilePath = fileName; - fi.hFileNotUsed = IntPtr.Zero; - fi.pgKnownSubjectNotUsed = IntPtr.Zero; - - return fi; - } - - [ArchitectureSensitive] - internal static WINTRUST_BLOB_INFO InitWintrustBlobInfoStruct(string fileName, string content) - { - WINTRUST_BLOB_INFO bi = new WINTRUST_BLOB_INFO(); - byte[] contentBytes = System.Text.Encoding.Unicode.GetBytes(content); - - // The GUID of the PowerShell SIP - bi.gSubject = new Guid(0x603bcc1f, 0x4b59, 0x4e08, new byte[] { 0xb7, 0x24, 0xd2, 0xc6, 0x29, 0x7e, 0xf3, 0x51 }); - bi.cbStruct = (DWORD)Marshal.SizeOf(bi); - bi.pcwszDisplayName = fileName; - bi.cbMemObject = (uint)contentBytes.Length; - bi.pbMemObject = Marshal.AllocCoTaskMem(contentBytes.Length); - Marshal.Copy(contentBytes, 0, bi.pbMemObject, contentBytes.Length); - - return bi; - } - - [Flags] - internal enum WintrustUIChoice - { - WTD_UI_ALL = 1, - WTD_UI_NONE = 2, - WTD_UI_NOBAD = 3, - WTD_UI_NOGOOD = 4 - } - - [Flags] - internal enum WintrustUnionChoice - { - WTD_CHOICE_FILE = 1, - // WTD_CHOICE_CATALOG = 2, - WTD_CHOICE_BLOB = 3, - // WTD_CHOICE_SIGNER = 4, - // WTD_CHOICE_CERT = 5, - } - - [Flags] - internal enum WintrustProviderFlags - { - WTD_PROV_FLAGS_MASK = 0x0000FFFF, - WTD_USE_IE4_TRUST_FLAG = 0x00000001, - WTD_NO_IE4_CHAIN_FLAG = 0x00000002, - WTD_NO_POLICY_USAGE_FLAG = 0x00000004, - WTD_REVOCATION_CHECK_NONE = 0x00000010, - WTD_REVOCATION_CHECK_END_CERT = 0x00000020, - WTD_REVOCATION_CHECK_CHAIN = 0x00000040, - WTD_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT = 0x00000080, - WTD_SAFER_FLAG = 0x00000100, - WTD_HASH_ONLY_FLAG = 0x00000200, - WTD_USE_DEFAULT_OSVER_CHECK = 0x00000400, - WTD_LIFETIME_SIGNING_FLAG = 0x00000800, - WTD_CACHE_ONLY_URL_RETRIEVAL = 0x00001000 - } - - [Flags] - internal enum WintrustAction - { - WTD_STATEACTION_IGNORE = 0x00000000, - WTD_STATEACTION_VERIFY = 0x00000001, - WTD_STATEACTION_CLOSE = 0x00000002, - WTD_STATEACTION_AUTO_CACHE = 0x00000003, - WTD_STATEACTION_AUTO_CACHE_FLUSH = 0x00000004 - } - - [StructLayoutAttribute(LayoutKind.Explicit)] - internal struct WinTrust_Choice - { - /// WINTRUST_FILE_INFO_* - [FieldOffsetAttribute(0)] - internal System.IntPtr pFile; - - /// WINTRUST_CATALOG_INFO_* - [FieldOffsetAttribute(0)] - internal System.IntPtr pCatalog; - - /// WINTRUST_BLOB_INFO_* - [FieldOffsetAttribute(0)] - internal System.IntPtr pBlob; - - /// WINTRUST_SGNR_INFO_* - [FieldOffsetAttribute(0)] - internal System.IntPtr pSgnr; - - /// WINTRUST_CERT_INFO_* - [FieldOffsetAttribute(0)] - internal System.IntPtr pCert; - } - - [StructLayoutAttribute(LayoutKind.Sequential)] - internal struct WINTRUST_DATA - { - /// DWORD->unsigned int - internal uint cbStruct; - - /// LPVOID->void* - internal System.IntPtr pPolicyCallbackData; - - /// LPVOID->void* - internal System.IntPtr pSIPClientData; - - /// DWORD->unsigned int - internal uint dwUIChoice; - - /// DWORD->unsigned int - internal uint fdwRevocationChecks; - - /// DWORD->unsigned int - internal uint dwUnionChoice; - - /// WinTrust_Choice struct - internal WinTrust_Choice Choice; - - /// DWORD->unsigned int - internal uint dwStateAction; - - /// HANDLE->void* - internal System.IntPtr hWVTStateData; - - /// WCHAR* - [MarshalAsAttribute(UnmanagedType.LPWStr)] - internal string pwszURLReference; - - /// DWORD->unsigned int - internal uint dwProvFlags; - - /// DWORD->unsigned int - internal uint dwUIContext; - } - - [ArchitectureSensitive] - internal static WINTRUST_DATA InitWintrustDataStructFromFile(WINTRUST_FILE_INFO wfi) - { - WINTRUST_DATA wtd = new WINTRUST_DATA(); - - wtd.cbStruct = (DWORD)Marshal.SizeOf(wtd); - wtd.pPolicyCallbackData = IntPtr.Zero; - wtd.pSIPClientData = IntPtr.Zero; - wtd.dwUIChoice = (DWORD)WintrustUIChoice.WTD_UI_NONE; - wtd.fdwRevocationChecks = 0; - wtd.dwUnionChoice = (DWORD)WintrustUnionChoice.WTD_CHOICE_FILE; - - IntPtr pFileBuffer = Marshal.AllocCoTaskMem(Marshal.SizeOf(wfi)); - Marshal.StructureToPtr(wfi, pFileBuffer, false); - wtd.Choice.pFile = pFileBuffer; - - wtd.dwStateAction = (DWORD)WintrustAction.WTD_STATEACTION_VERIFY; - wtd.hWVTStateData = IntPtr.Zero; - wtd.pwszURLReference = null; - wtd.dwProvFlags = 0; - - return wtd; - } - - [ArchitectureSensitive] - internal static WINTRUST_DATA InitWintrustDataStructFromBlob(WINTRUST_BLOB_INFO wbi) - { - WINTRUST_DATA wtd = new WINTRUST_DATA(); - - wtd.cbStruct = (DWORD)Marshal.SizeOf(wbi); - wtd.pPolicyCallbackData = IntPtr.Zero; - wtd.pSIPClientData = IntPtr.Zero; - wtd.dwUIChoice = (DWORD)WintrustUIChoice.WTD_UI_NONE; - wtd.fdwRevocationChecks = 0; - wtd.dwUnionChoice = (DWORD)WintrustUnionChoice.WTD_CHOICE_BLOB; - - IntPtr pBlob = Marshal.AllocCoTaskMem(Marshal.SizeOf(wbi)); - Marshal.StructureToPtr(wbi, pBlob, false); - wtd.Choice.pBlob = pBlob; - - wtd.dwStateAction = (DWORD)WintrustAction.WTD_STATEACTION_VERIFY; - wtd.hWVTStateData = IntPtr.Zero; - wtd.pwszURLReference = null; - wtd.dwProvFlags = 0; - - return wtd; - } - - [ArchitectureSensitive] - internal static DWORD DestroyWintrustDataStruct(WINTRUST_DATA wtd) - { - DWORD dwResult = Win32Errors.E_FAIL; - IntPtr WINTRUST_ACTION_GENERIC_VERIFY_V2 = IntPtr.Zero; - IntPtr wtdBuffer = IntPtr.Zero; - - Guid actionVerify = - new Guid("00AAC56B-CD44-11d0-8CC2-00C04FC295EE"); - - try - { - WINTRUST_ACTION_GENERIC_VERIFY_V2 = - Marshal.AllocCoTaskMem(Marshal.SizeOf(actionVerify)); - Marshal.StructureToPtr(actionVerify, - WINTRUST_ACTION_GENERIC_VERIFY_V2, - false); - - wtd.dwStateAction = (DWORD)WintrustAction.WTD_STATEACTION_CLOSE; - wtdBuffer = Marshal.AllocCoTaskMem(Marshal.SizeOf(wtd)); - Marshal.StructureToPtr(wtd, wtdBuffer, false); - - // The GetLastWin32Error of this is checked, but PreSharp doesn't seem to be - // able to see that. -#pragma warning disable 56523 - dwResult = WinVerifyTrust( - IntPtr.Zero, - WINTRUST_ACTION_GENERIC_VERIFY_V2, - wtdBuffer); -#pragma warning restore 56523 - - wtd = Marshal.PtrToStructure(wtdBuffer); - } - finally - { - Marshal.DestroyStructure(wtdBuffer); - Marshal.FreeCoTaskMem(wtdBuffer); - Marshal.DestroyStructure(WINTRUST_ACTION_GENERIC_VERIFY_V2); - Marshal.FreeCoTaskMem(WINTRUST_ACTION_GENERIC_VERIFY_V2); - } - - // Clear the blob or file info, depending on the type of - // verification that was done. - if (wtd.dwUnionChoice == (DWORD)WintrustUnionChoice.WTD_CHOICE_BLOB) - { - WINTRUST_BLOB_INFO originalBlob = - (WINTRUST_BLOB_INFO)Marshal.PtrToStructure(wtd.Choice.pBlob); - Marshal.FreeCoTaskMem(originalBlob.pbMemObject); - - Marshal.DestroyStructure(wtd.Choice.pBlob); - Marshal.FreeCoTaskMem(wtd.Choice.pBlob); - } - else - { - Marshal.DestroyStructure(wtd.Choice.pFile); - Marshal.FreeCoTaskMem(wtd.Choice.pFile); - } - - return dwResult; - } - [StructLayout(LayoutKind.Sequential)] internal struct CRYPT_PROVIDER_CERT { @@ -1122,29 +816,6 @@ internal struct CRYPT_PROVIDER_SGNR private readonly IntPtr _pChainContext; // PCCERT_CHAIN_CONTEXT } - [DllImport("wintrust.dll", SetLastError = true, CharSet = CharSet.Unicode)] - internal static extern - IntPtr // CRYPT_PROVIDER_DATA* - WTHelperProvDataFromStateData(IntPtr hStateData); - - [DllImport("wintrust.dll", SetLastError = true, CharSet = CharSet.Unicode)] - internal static extern - IntPtr // CRYPT_PROVIDER_SGNR* - WTHelperGetProvSignerFromChain( - IntPtr pProvData, // CRYPT_PROVIDER_DATA* - DWORD idxSigner, - BOOL fCounterSigner, - DWORD idxCounterSigner - ); - - [DllImport("wintrust.dll", SetLastError = true, CharSet = CharSet.Unicode)] - internal static extern - IntPtr // CRYPT_PROVIDER_CERT* - WTHelperGetProvCertFromChain( - IntPtr pSgnr, // CRYPT_PROVIDER_SGNR* - DWORD idxCert - ); - // // stuff required for getting cert extensions // @@ -1799,42 +1470,6 @@ internal static extern bool AdjustTokenPrivileges( internal const uint LOAD_LIBRARY_SEARCH_USER_DIRS = 0x00000400; internal const uint LOAD_LIBRARY_SEARCH_SYSTEM32 = 0x00000800; internal const uint LOAD_LIBRARY_SEARCH_DEFAULT_DIRS = 0x00001000; - - [DllImport(PinvokeDllNames.LoadLibraryEx, CharSet = CharSet.Unicode, SetLastError = true)] - internal static extern IntPtr LoadLibraryExW( - string DllName, - IntPtr reserved, - uint Flags); - - [DllImport(PinvokeDllNames.FreeLibrary, CharSet = CharSet.Unicode, SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool FreeLibrary( - IntPtr Module); - - internal static bool IsSystem32DllPresent(string DllName) - { - bool DllExists = false; - - try - { - IntPtr module = LoadLibraryExW( - DllName, - IntPtr.Zero, - NativeMethods.LOAD_LIBRARY_AS_DATAFILE | - NativeMethods.LOAD_LIBRARY_AS_IMAGE_RESOURCE | - NativeMethods.LOAD_LIBRARY_SEARCH_SYSTEM32); - if (module != IntPtr.Zero) - { - FreeLibrary(module); - DllExists = true; - } - } - catch (Exception) - { - } - - return DllExists; - } } // Constants needed for Catalog Error Handling @@ -1876,234 +1511,6 @@ internal partial class NativeConstants // CRYPTCAT_E_CDF_ATTR_TYPECOMBO = "0x00020004"; public const int CRYPTCAT_E_CDF_ATTR_TYPECOMBO = 131076; } - - /// - /// Pinvoke methods from wintrust.dll - /// These are added to Generate and Validate Window Catalog Files. - /// - internal static partial class NativeMethods - { - [StructLayout(LayoutKind.Sequential)] - internal struct CRYPT_ATTRIBUTE_TYPE_VALUE - { - [MarshalAs(UnmanagedType.LPStr)] - internal string pszObjId; - - internal CRYPT_ATTR_BLOB Value; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct SIP_INDIRECT_DATA - { - internal CRYPT_ATTRIBUTE_TYPE_VALUE Data; - internal CRYPT_ALGORITHM_IDENTIFIER DigestAlgorithm; - internal CRYPT_ATTR_BLOB Digest; - } - - [StructLayout(LayoutKind.Sequential)] - internal readonly struct CRYPTCATCDF - { - private readonly DWORD _cbStruct; - private readonly IntPtr _hFile; - private readonly DWORD _dwCurFilePos; - private readonly DWORD _dwLastMemberOffset; - private readonly BOOL _fEOF; - - [MarshalAs(UnmanagedType.LPWStr)] - private readonly string _pwszResultDir; - - private readonly IntPtr _hCATStore; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct CRYPTCATMEMBER - { - internal DWORD cbStruct; - - [MarshalAs(UnmanagedType.LPWStr)] - internal string pwszReferenceTag; - - [MarshalAs(UnmanagedType.LPWStr)] - internal string pwszFileName; - - internal Guid gSubjectType; - internal DWORD fdwMemberFlags; - internal IntPtr pIndirectData; - internal DWORD dwCertVersion; - internal DWORD dwReserved; - internal IntPtr hReserved; - internal CRYPT_ATTR_BLOB sEncodedIndirectData; - internal CRYPT_ATTR_BLOB sEncodedMemberInfo; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct CRYPTCATATTRIBUTE - { - private readonly DWORD _cbStruct; - - [MarshalAs(UnmanagedType.LPWStr)] - internal string pwszReferenceTag; - - private readonly DWORD _dwAttrTypeAndAction; - internal DWORD cbValue; - internal System.IntPtr pbValue; - private readonly DWORD _dwReserved; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct CRYPTCATSTORE - { - private readonly DWORD _cbStruct; - internal DWORD dwPublicVersion; - - [MarshalAs(UnmanagedType.LPWStr)] - internal string pwszP7File; - - private readonly IntPtr _hProv; - private readonly DWORD _dwEncodingType; - private readonly DWORD _fdwStoreFlags; - private readonly IntPtr _hReserved; - private readonly IntPtr _hAttrs; - private readonly IntPtr _hCryptMsg; - private readonly IntPtr _hSorted; - } - - [DllImport("wintrust.dll", CharSet = CharSet.Unicode)] - internal static extern IntPtr CryptCATCDFOpen( - [MarshalAs(UnmanagedType.LPWStr)] - string pwszFilePath, - CryptCATCDFOpenCallBack pfnParseError - ); - - [DllImport("wintrust.dll")] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool CryptCATCDFClose( - IntPtr pCDF - ); - - [DllImport("wintrust.dll", CharSet = CharSet.Unicode)] - internal static extern IntPtr CryptCATCDFEnumCatAttributes( - IntPtr pCDF, - IntPtr pPrevAttr, - CryptCATCDFOpenCallBack pfnParseError - ); - - [DllImport("wintrust.dll", CharSet = CharSet.Unicode)] - internal static extern IntPtr CryptCATCDFEnumMembersByCDFTagEx( - IntPtr pCDF, - IntPtr pwszPrevCDFTag, - CryptCATCDFEnumMembersByCDFTagExErrorCallBack fn, - ref IntPtr ppMember, - bool fContinueOnError, - IntPtr pvReserved - ); - - [DllImport("wintrust.dll", CharSet = CharSet.Unicode)] - internal static extern IntPtr CryptCATCDFEnumAttributesWithCDFTag( - IntPtr pCDF, - IntPtr pwszMemberTag, - IntPtr pMember, - IntPtr pPrevAttr, - CryptCATCDFEnumMembersByCDFTagExErrorCallBack fn - ); - - [DllImport("wintrust.dll", CharSet = CharSet.Unicode)] - internal static extern IntPtr CryptCATOpen( - [MarshalAs(UnmanagedType.LPWStr)] - string pwszFilePath, - DWORD fdwOpenFlags, - IntPtr hProv, - DWORD dwPublicVersion, - DWORD dwEncodingType - ); - - [DllImport("wintrust.dll")] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool CryptCATClose( - IntPtr hCatalog - ); - - [DllImport("wintrust.dll", CharSet = CharSet.Unicode)] - internal static extern IntPtr CryptCATStoreFromHandle( - IntPtr hCatalog - ); - - [DllImport("wintrust.dll", CharSet = CharSet.Unicode)] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool CryptCATAdminAcquireContext2( - ref IntPtr phCatAdmin, - IntPtr pgSubsystem, - [MarshalAs(UnmanagedType.LPWStr)] - string pwszHashAlgorithm, - IntPtr pStrongHashPolicy, - DWORD dwFlags - ); - - [DllImport("wintrust.dll", CharSet = CharSet.Unicode)] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool CryptCATAdminReleaseContext( - IntPtr phCatAdmin, - DWORD dwFlags - ); - - [DllImport("kernel32", SetLastError = true, CharSet = CharSet.Unicode)] - internal static extern unsafe IntPtr CreateFile( - string lpFileName, - DWORD dwDesiredAccess, - DWORD dwShareMode, - DWORD lpSecurityAttributes, - DWORD dwCreationDisposition, - DWORD dwFlagsAndAttributes, - IntPtr hTemplateFile - ); - - [DllImport("wintrust.dll", SetLastError = true, CharSet = CharSet.Unicode)] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool CryptCATAdminCalcHashFromFileHandle2( - IntPtr hCatAdmin, - IntPtr hFile, - [In, Out] ref DWORD pcbHash, - IntPtr pbHash, - DWORD dwFlags - ); - - [DllImport("wintrust.dll", CharSet = CharSet.Unicode)] - internal static extern IntPtr CryptCATEnumerateCatAttr( - IntPtr hCatalog, - IntPtr pPrevAttr - ); - - [DllImport("wintrust.dll", CharSet = CharSet.Unicode)] - internal static extern IntPtr CryptCATEnumerateMember( - IntPtr hCatalog, - IntPtr pPrevMember - ); - - [DllImport("wintrust.dll", CharSet = CharSet.Unicode)] - internal static extern IntPtr CryptCATEnumerateAttr( - IntPtr hCatalog, - IntPtr pCatMember, - IntPtr pPrevAttr - ); - - /// - /// Signature of call back function used by CryptCATCDFOpen. - /// - internal delegate - void CryptCATCDFOpenCallBack(DWORD NotUsedDWORD1, - DWORD NotUsedDWORD2, - [MarshalAs(UnmanagedType.LPWStr)] - string NotUsedString); - - /// - /// Signature of call back function used by CryptCATCDFEnumMembersByCDFTagEx. - /// - internal delegate - void CryptCATCDFEnumMembersByCDFTagExErrorCallBack(DWORD NotUsedDWORD1, - DWORD NotUsedDWORD2, - [MarshalAs(UnmanagedType.LPWStr)] - string NotUsedString); - } } #pragma warning restore 56523 From 15dcf634e26acb4c2210c450f339d3a6c7326a79 Mon Sep 17 00:00:00 2001 From: MartinGC94 <42123497+MartinGC94@users.noreply.github.com> Date: Tue, 9 Aug 2022 19:37:56 +0200 Subject: [PATCH 002/779] Improve enumeration of inferred types in pipeline (#17799) --- .../CommandCompletion/CompletionCompleters.cs | 41 +++++++++++------- .../engine/parser/TypeInferenceVisitor.cs | 42 ++----------------- .../TabCompletion/TabCompletion.Tests.ps1 | 9 +++- .../engine/Api/TypeInference.Tests.ps1 | 6 +++ 4 files changed, 43 insertions(+), 55 deletions(-) diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs index 2ddb472f2dd..1bf0919cf97 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs @@ -3963,7 +3963,7 @@ private static IEnumerable GetInferenceTypes(CompletionContext conte private static void NativeCompletionMemberName(CompletionContext context, List result, CommandAst commandAst, AstParameterArgumentPair parameterInfo, bool propertiesOnly = true) { - IEnumerable prevType = GetInferenceTypes(context, commandAst); + IEnumerable prevType = TypeInferenceVisitor.GetInferredEnumeratedTypes(GetInferenceTypes(context, commandAst)); if (prevType is not null) { HashSet excludedMembers = null; @@ -3973,7 +3973,7 @@ private static void NativeCompletionMemberName(CompletionContext context, List filter = propertiesOnly ? IsPropertyMember : null; - CompleteMemberByInferredType(context.TypeInferenceContext, prevType, result, context.WordToComplete + "*", filter, isStatic: false, excludedMembers); + CompleteMemberByInferredType(context.TypeInferenceContext, prevType, result, context.WordToComplete + "*", filter, isStatic: false, excludedMembers, addMethodParenthesis: false); } result.Add(CompletionResult.Null); @@ -5901,22 +5901,25 @@ internal static List CompleteMember(CompletionContext context, /// /// Complete members against extension methods 'Where' and 'ForEach' /// - private static void CompleteExtensionMethods(string memberName, List results) + private static void CompleteExtensionMethods(string memberName, List results, bool addMethodParenthesis = true) { var pattern = WildcardPattern.Get(memberName, WildcardOptions.IgnoreCase); - CompleteExtensionMethods(pattern, results); + CompleteExtensionMethods(pattern, results, addMethodParenthesis); } /// /// Complete members against extension methods 'Where' and 'ForEach' based on the given pattern. /// - private static void CompleteExtensionMethods(WildcardPattern pattern, List results) + private static void CompleteExtensionMethods(WildcardPattern pattern, List results, bool addMethodParenthesis) { - results.AddRange(from member in s_extensionMethods - where pattern.IsMatch(member.Item1) - select - new CompletionResult(member.Item1 + "(", member.Item1, - CompletionResultType.Method, member.Item2)); + foreach (var member in s_extensionMethods) + { + if (pattern.IsMatch(member.Item1)) + { + string completionText = addMethodParenthesis ? $"{member.Item1}(" : member.Item1; + results.Add(new CompletionResult(completionText, member.Item1, CompletionResultType.Method, member.Item2)); + } + } } /// @@ -6035,7 +6038,15 @@ private static void CompleteFormatViewByInferredType(CompletionContext context, } } - internal static void CompleteMemberByInferredType(TypeInferenceContext context, IEnumerable inferredTypes, List results, string memberName, Func filter, bool isStatic, HashSet excludedMembers = null) + internal static void CompleteMemberByInferredType( + TypeInferenceContext context, + IEnumerable inferredTypes, + List results, + string memberName, + Func filter, + bool isStatic, + HashSet excludedMembers = null, + bool addMethodParenthesis = true) { bool extensionMethodsAdded = false; HashSet typeNameUsed = new HashSet(StringComparer.OrdinalIgnoreCase); @@ -6051,7 +6062,7 @@ internal static void CompleteMemberByInferredType(TypeInferenceContext context, var members = context.GetMembersByInferredType(psTypeName, isStatic, filter); foreach (var member in members) { - AddInferredMember(member, memberNamePattern, results, excludedMembers); + AddInferredMember(member, memberNamePattern, results, excludedMembers, addMethodParenthesis); } // Check if we need to complete against the extension methods 'Where' and 'ForEach' @@ -6059,7 +6070,7 @@ internal static void CompleteMemberByInferredType(TypeInferenceContext context, { // Complete extension methods 'Where' and 'ForEach' for Enumerable types extensionMethodsAdded = true; - CompleteExtensionMethods(memberNamePattern, results); + CompleteExtensionMethods(memberNamePattern, results, addMethodParenthesis); } } @@ -6077,7 +6088,7 @@ internal static void CompleteMemberByInferredType(TypeInferenceContext context, } } - private static void AddInferredMember(object member, WildcardPattern memberNamePattern, List results, HashSet excludedMembers) + private static void AddInferredMember(object member, WildcardPattern memberNamePattern, List results, HashSet excludedMembers, bool addMethodParenthesis) { string memberName = null; bool isMethod = false; @@ -6149,7 +6160,7 @@ private static void AddInferredMember(object member, WildcardPattern memberNameP var completionResultType = isMethod ? CompletionResultType.Method : CompletionResultType.Property; string completionText; - if (isMethod) + if (isMethod && addMethodParenthesis) { completionText = $"{memberName}("; } diff --git a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs index 25bd7f999a5..a1e761c1cce 100644 --- a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs +++ b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs @@ -1288,7 +1288,7 @@ private void InferTypesFromPreviousCommand(CommandAst commandAst, List 0) { - inferredTypes.AddRange(InferTypes(parentPipeline.PipelineElements[i - 1])); + inferredTypes.AddRange(GetInferredEnumeratedTypes(InferTypes(parentPipeline.PipelineElements[i - 1]))); } } } @@ -1931,7 +1931,7 @@ private void InferTypeFrom(VariableExpressionAst variableExpressionAst, List results) - { - foreach (var result in InferTypes(parentExpression)) - { - if (result.Type != null) - { - // Assume (because we're looking at $_ and we're inside a script block that is an - // argument to some command) that the type we're getting is actually unrolled. - // This might not be right in all cases, but with our simple analysis, it's - // right more often than it's wrong. - if (result.Type.IsArray) - { - results.Add(new PSTypeName(result.Type.GetElementType())); - continue; - } - - if (result.Type != typeof(string) && typeof(IEnumerable).IsAssignableFrom(result.Type)) - { - // We can't deduce much from IEnumerable, but we can if it's generic. - var enumerableInterfaces = result.Type.GetInterfaces(); - foreach (var t in enumerableInterfaces) - { - if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(IEnumerable<>)) - { - results.Add(new PSTypeName(t.GetGenericArguments()[0])); - } - } - - continue; - } - } - - results.Add(result); - } - } - /// /// Gets the most specific array type possible from a group of inferred types. /// @@ -2363,7 +2327,7 @@ private IEnumerable InferTypeFrom(IndexExpressionAst indexExpression /// The potentially enumerable types to infer enumerated type from. /// /// The enumerated item types. - private static IEnumerable GetInferredEnumeratedTypes(IEnumerable enumerableTypes) + internal static IEnumerable GetInferredEnumeratedTypes(IEnumerable enumerableTypes) { foreach (PSTypeName maybeEnumerableType in enumerableTypes) { diff --git a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 index 2134d64530a..4ff31245a31 100644 --- a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 +++ b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 @@ -504,7 +504,7 @@ switch ($x) It 'ForEach-Object member completion results should include methods' { $res = TabExpansion2 -inputScript '1..10 | ForEach-Object -MemberName ' - $res.CompletionMatches.CompletionText | Should -Contain "GetType(" + $res.CompletionMatches.CompletionText | Should -Contain "GetType" } It 'Should not complete void instance members' { @@ -571,6 +571,13 @@ ConstructorTestClass(int i, bool b) $res.CompletionMatches[0].CompletionText | Should -BeExactly '-Directory' } + It 'Should enumerate types when completing member names for Select-Object' { + $TestString = '"Hello","World" | select-object ' + $res = TabExpansion2 -inputScript $TestString + $res | Should -HaveCount 1 + $res.CompletionMatches[0].CompletionText | Should -BeExactly 'Length' + } + Context "Format cmdlet's View paramter completion" { BeforeAll { $viewDefinition = @' diff --git a/test/powershell/engine/Api/TypeInference.Tests.ps1 b/test/powershell/engine/Api/TypeInference.Tests.ps1 index cd99abaf46e..1c41ef72e84 100644 --- a/test/powershell/engine/Api/TypeInference.Tests.ps1 +++ b/test/powershell/engine/Api/TypeInference.Tests.ps1 @@ -1342,6 +1342,12 @@ Describe "Type inference Tests" -tags "CI" { $res.Count | Should -Be 1 $res.Name | Should -Be 'System.Security.AccessControl.AuthorizationRule' } + + It 'Enumerates the inferred type after *-Object commands' { + $res = [AstTypeInference]::InferTypeOf( { (([System.Management.Automation.Language.Ast]$null).FindAll() | Select-Object -First 1) }.Ast) + $res.Count | Should -Be 1 + $res.Name | Should -Be 'System.Management.Automation.Language.Ast' + } } Describe "AstTypeInference tests" -Tags CI { From d75d3b6178a062c96d59a05b7b7019b3a11fcb88 Mon Sep 17 00:00:00 2001 From: WJKM <54790970+wmentha@users.noreply.github.com> Date: Wed, 10 Aug 2022 03:48:08 +1000 Subject: [PATCH 003/779] Add the `ValidateNotNullOrWhiteSpace` attribute (#17191) --- .../engine/Attributes.cs | 83 +++++++++++++++++-- .../engine/TypeMetadata.cs | 9 ++ .../engine/parser/TypeResolver.cs | 1 + .../resources/Metadata.resx | 6 ++ .../Language/Parser/TypeAccelerator.Tests.ps1 | 8 +- .../engine/Basic/ValidateAttributes.Tests.ps1 | 50 ++++++++++- .../engine/Basic/assets/standardtypes.csv | 1 + 7 files changed, 147 insertions(+), 11 deletions(-) diff --git a/src/System.Management.Automation/engine/Attributes.cs b/src/System.Management.Automation/engine/Attributes.cs index 9965824a927..0e11dc7aac3 100644 --- a/src/System.Management.Automation/engine/Attributes.cs +++ b/src/System.Management.Automation/engine/Attributes.cs @@ -2072,15 +2072,30 @@ protected override void Validate(object arguments, EngineIntrinsics engineIntrin } /// - /// Validates that the parameters's argument is not null, is not an empty string, and is not - /// an empty collection. + /// Validates that the parameters's argument is not null, is not an empty string or a + /// string with white-space characters only, and is not an empty collection. /// - [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] - public sealed class ValidateNotNullOrEmptyAttribute : NullValidationAttributeBase + public abstract class ValidateNotNullOrAttributeBase : NullValidationAttributeBase { + /// + /// Used to check the type of string validation to perform. + /// + protected readonly bool _checkWhiteSpace; + + /// + /// Validates that the parameters's argument is not null, is not an empty string or a + /// string with white-space characters only, and is not an empty collection. + /// + protected ValidateNotNullOrAttributeBase(bool checkWhiteSpace) + { + _checkWhiteSpace = checkWhiteSpace; + } + /// /// Validates that the parameters's argument is not null, is not an empty string, and is /// not an empty collection. If argument is a collection, each argument is verified. + /// It can also validate that the parameters's argument is not a string that consists + /// only of white-space characters. /// /// The arguments to verify. /// @@ -2100,7 +2115,17 @@ protected override void Validate(object arguments, EngineIntrinsics engineIntrin } else if (arguments is string str) { - if (string.IsNullOrEmpty(str)) + if (_checkWhiteSpace) + { + if (string.IsNullOrWhiteSpace(str)) + { + throw new ValidationMetadataException( + "ArgumentIsEmptyOrWhiteSpace", + null, + Metadata.ValidateNotNullOrWhiteSpaceFailure); + } + } + else if (string.IsNullOrEmpty(str)) { throw new ValidationMetadataException( "ArgumentIsEmpty", @@ -2131,7 +2156,17 @@ protected override void Validate(object arguments, EngineIntrinsics engineIntrin if (element is string elementAsString) { - if (string.IsNullOrEmpty(elementAsString)) + if (_checkWhiteSpace) + { + if (string.IsNullOrWhiteSpace(elementAsString)) + { + throw new ValidationMetadataException( + "ArgumentCollectionContainsEmptyOrWhiteSpace", + null, + Metadata.ValidateNotNullOrWhiteSpaceCollectionFailure); + } + } + else if (string.IsNullOrEmpty(elementAsString)) { throw new ValidationMetadataException( "ArgumentCollectionContainsEmpty", @@ -2163,6 +2198,42 @@ protected override void Validate(object arguments, EngineIntrinsics engineIntrin } } + /// + /// Validates that the parameters's argument is not null, is not an empty string, and is + /// not an empty collection. If argument is a collection, each argument is verified. + /// + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] + public sealed class ValidateNotNullOrEmptyAttribute : ValidateNotNullOrAttributeBase + { + /// + /// Validates that the parameters's argument is not null, is not an empty string, and is + /// not an empty collection. If argument is a collection, each argument is verified. + /// + public ValidateNotNullOrEmptyAttribute() + : base(checkWhiteSpace: false) + { + } + } + + /// + /// Validates that the parameters's argument is not null, is not an empty string, is not a string that + /// consists only of white-space characters, and is not an empty collection. If argument is a collection, + /// each argument is verified. + /// + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] + public sealed class ValidateNotNullOrWhiteSpaceAttribute : ValidateNotNullOrAttributeBase + { + /// + /// Validates that the parameters's argument is not null, is not an empty string, is not a string that + /// consists only of white-space characters, and is not an empty collection. If argument is a collection, + /// each argument is verified. + /// + public ValidateNotNullOrWhiteSpaceAttribute() + : base(checkWhiteSpace: true) + { + } + } + #endregion NULL validation attributes #endregion Data validate Attributes diff --git a/src/System.Management.Automation/engine/TypeMetadata.cs b/src/System.Management.Automation/engine/TypeMetadata.cs index 6981640a165..3c2515183f1 100644 --- a/src/System.Management.Automation/engine/TypeMetadata.cs +++ b/src/System.Management.Automation/engine/TypeMetadata.cs @@ -770,6 +770,7 @@ internal bool IsMatchingType(PSTypeName psTypeName) private const string ValidateSetFormat = @"{0}[ValidateSet({1})]"; private const string ValidateNotNullFormat = @"{0}[ValidateNotNull()]"; private const string ValidateNotNullOrEmptyFormat = @"{0}[ValidateNotNullOrEmpty()]"; + private const string ValidateNotNullOrWhiteSpaceFormat = @"{0}[ValidateNotNullOrWhiteSpace()]"; private const string AllowNullFormat = @"{0}[AllowNull()]"; private const string AllowEmptyStringFormat = @"{0}[AllowEmptyString()]"; private const string AllowEmptyCollectionFormat = @"{0}[AllowEmptyCollection()]"; @@ -1031,6 +1032,14 @@ private static string GetProxyAttributeData(Attribute attrib, string prefix) return result; } + ValidateNotNullOrWhiteSpaceAttribute notNullWhiteSpaceAttrib = attrib as ValidateNotNullOrWhiteSpaceAttribute; + if (notNullWhiteSpaceAttrib != null) + { + result = string.Format(CultureInfo.InvariantCulture, + ValidateNotNullOrWhiteSpaceFormat, prefix); + return result; + } + ValidateSetAttribute setAttrib = attrib as ValidateSetAttribute; if (setAttrib != null) { diff --git a/src/System.Management.Automation/engine/parser/TypeResolver.cs b/src/System.Management.Automation/engine/parser/TypeResolver.cs index e93719a3fb4..8a12aefe159 100644 --- a/src/System.Management.Automation/engine/parser/TypeResolver.cs +++ b/src/System.Management.Automation/engine/parser/TypeResolver.cs @@ -783,6 +783,7 @@ internal static class CoreTypes { typeof(ValidateLengthAttribute), new[] { "ValidateLength" } }, { typeof(ValidateNotNullAttribute), new[] { "ValidateNotNull" } }, { typeof(ValidateNotNullOrEmptyAttribute), new[] { "ValidateNotNullOrEmpty" } }, + { typeof(ValidateNotNullOrWhiteSpaceAttribute), new[] { "ValidateNotNullOrWhiteSpace" } }, { typeof(ValidatePatternAttribute), new[] { "ValidatePattern" } }, { typeof(ValidateRangeAttribute), new[] { "ValidateRange" } }, { typeof(ValidateScriptAttribute), new[] { "ValidateScript" } }, diff --git a/src/System.Management.Automation/resources/Metadata.resx b/src/System.Management.Automation/resources/Metadata.resx index 61aad9f57b5..4aac4753bcb 100644 --- a/src/System.Management.Automation/resources/Metadata.resx +++ b/src/System.Management.Automation/resources/Metadata.resx @@ -210,6 +210,12 @@ The argument is null, empty, or an element of the argument collection contains a null value. Supply a collection that does not contain any null values and then try the command again. + + The argument is null, empty, or consists of only white-space characters. Provide an argument that contains non white-space characters, and then try the command again. + + + An element of the argument collection is null, empty, or consists of only white-space characters. Supply a collection that does not contain any those values and then try the command again. + A parameter with the name '{0}' was defined multiple times for the command. diff --git a/test/powershell/Language/Parser/TypeAccelerator.Tests.ps1 b/test/powershell/Language/Parser/TypeAccelerator.Tests.ps1 index 26bc8d430a6..018f5af55c6 100644 --- a/test/powershell/Language/Parser/TypeAccelerator.Tests.ps1 +++ b/test/powershell/Language/Parser/TypeAccelerator.Tests.ps1 @@ -282,6 +282,10 @@ Describe "Type accelerators" -Tags "CI" { Accelerator = 'ValidateNotNullOrEmpty' Type = [System.Management.Automation.ValidateNotNullOrEmptyAttribute] } + @{ + Accelerator = 'ValidateNotNullOrWhiteSpace' + Type = [System.Management.Automation.ValidateNotNullOrWhiteSpaceAttribute] + } @{ Accelerator = 'ValidatePattern' Type = [System.Management.Automation.ValidatePatternAttribute] @@ -410,11 +414,11 @@ Describe "Type accelerators" -Tags "CI" { if ( !$IsWindows ) { - $totalAccelerators = 100 + $totalAccelerators = 101 } else { - $totalAccelerators = 105 + $totalAccelerators = 106 $extraFullPSAcceleratorTestCases = @( @{ diff --git a/test/powershell/engine/Basic/ValidateAttributes.Tests.ps1 b/test/powershell/engine/Basic/ValidateAttributes.Tests.ps1 index 7ca68b62db4..310465a03c2 100644 --- a/test/powershell/engine/Basic/ValidateAttributes.Tests.ps1 +++ b/test/powershell/engine/Basic/ValidateAttributes.Tests.ps1 @@ -263,7 +263,7 @@ Describe 'Validate Attributes Tests' -Tags 'CI' { } } - Context "ValidateNotNull, ValidateNotNullOrEmpty and Not-Null-Or-Empty check for Mandatory parameter" { + Context "ValidateNotNull, ValidateNotNullOrEmpty, ValidateNotNullOrWhiteSpace and Not-Null-Or-Empty check for Mandatory parameter" { BeforeAll { function MandatoryFunc { @@ -314,6 +314,22 @@ Describe 'Validate Attributes Tests' -Tags 'CI' { } } + function NotNullOrWhiteSpaceFunc { + param( + [ValidateNotNullOrWhiteSpace()] + $Value, + [string] $TestType + ) + + switch ($TestType) { + "COM-Enumerable" { $Value | ForEach-Object Name } + "Enumerator" { + $items = foreach ($i in $Value) { $i } + $items -join "," + } + } + } + $filePath = Join-Path -Path $PSHOME -ChildPath System.Management.Automation.dll $byteArray = [System.IO.File]::ReadAllBytes($filePath) $byteList = [System.Collections.Generic.List[byte]] $byteArray @@ -343,6 +359,9 @@ Describe 'Validate Attributes Tests' -Tags 'CI' { @{ ScriptBlock = { NotNullOrEmptyFunc -Value $byteArray } } @{ ScriptBlock = { NotNullOrEmptyFunc -Value $byteList } } @{ ScriptBlock = { NotNullOrEmptyFunc -Value $byteCollection } } + @{ ScriptBlock = { NotNullOrWhiteSpaceFunc -Value $byteArray } } + @{ ScriptBlock = { NotNullOrWhiteSpaceFunc -Value $byteList } } + @{ ScriptBlock = { NotNullOrWhiteSpaceFunc -Value $byteCollection } } ) } @@ -351,19 +370,21 @@ Describe 'Validate Attributes Tests' -Tags 'CI' { (Measure-Command $ScriptBlock).Milliseconds | Should -BeLessThan $UpperBoundTime } - It "COM enumerable argument should work with 'ValidateNotNull' and 'ValidateNotNullOrEmpty'" -Skip:(!$IsWindows) { + It "COM enumerable argument should work with 'ValidateNotNull', 'ValidateNotNullOrEmpty' and 'ValidateNotNullOrWhiteSpace'" -Skip:(!$IsWindows) { $shell = New-Object -ComObject "Shell.Application" $folder = $shell.Namespace("$TESTDRIVE") $items = $folder.Items() NotNullFunc -Value $items -TestType "COM-Enumerable" | Should -Be "file1" NotNullOrEmptyFunc -Value $items -TestType "COM-Enumerable" | Should -Be "file1" + NotNullOrWhiteSpaceFunc -Value $items -TestType "COM-Enumerable" | Should -Be "file1" } - It "Enumerator argument should work with 'ValidateNotNull' and 'ValidateNotNullOrEmpty'" { + It "Enumerator argument should work with 'ValidateNotNull', 'ValidateNotNullOrEmpty' and 'ValidateNotNullOrWhiteSpace'" { $data = @(1,2,3) NotNullFunc -Value $data.GetEnumerator() -TestType "Enumerator" | Should -Be "1,2,3" NotNullOrEmptyFunc -Value $data.GetEnumerator() -TestType "Enumerator" | Should -Be "1,2,3" + NotNullOrWhiteSpaceFunc -Value $data.GetEnumerator() -TestType "Enumerator" | Should -Be "1,2,3" } It "'ValidateNotNull' should throw on null element of a collection argument" { @@ -382,6 +403,29 @@ Describe 'Validate Attributes Tests' -Tags 'CI' { { NotNullOrEmptyFunc -Value @{} } | Should -Throw -ErrorId "ParameterArgumentValidationError,NotNullOrEmptyFunc" } + It "'ValidateNotNullOrWhiteSpace' should throw on null element of a collection argument, white-space only string element of a collection argument or empty collection/dictionary" { + { NotNullOrWhiteSpaceFunc -Value @("string", $null, 2) } | Should -Throw -ErrorId "ParameterArgumentValidationError,NotNullOrWhiteSpaceFunc" + { NotNullOrWhiteSpaceFunc -Value @("string", "", 2) } | Should -Throw -ErrorId "ParameterArgumentValidationError,NotNullOrWhiteSpaceFunc" + { NotNullOrWhiteSpaceFunc -Value @("string", " ", 2) } | Should -Throw -ErrorId "ParameterArgumentValidationError,NotNullOrWhiteSpaceFunc" + { NotNullOrWhiteSpaceFunc -Value @() } | Should -Throw -ErrorId "ParameterArgumentValidationError,NotNullOrWhiteSpaceFunc" + { NotNullOrWhiteSpaceFunc -Value @{} } | Should -Throw -ErrorId "ParameterArgumentValidationError,NotNullOrWhiteSpaceFunc" + } + + It "'ValidateNotNull' should throw on a scalar null value" { + { NotNullFunc -Value $null } | Should -Throw -ErrorId "ParameterArgumentValidationError,NotNullFunc" + } + + It "'ValidateNotNullOrEmpty' should throw on a scalar null value and scalar empty string" { + { NotNullOrEmptyFunc -Value $null } | Should -Throw -ErrorId "ParameterArgumentValidationError,NotNullOrEmptyFunc" + { NotNullOrEmptyFunc -Value "" } | Should -Throw -ErrorId "ParameterArgumentValidationError,NotNullOrEmptyFunc" + } + + It "'ValidateNotNullOrWhiteSpace' should throw on a scalar null value, scalar empty string and scalar white-space string" { + { NotNullOrWhiteSpaceFunc -Value $null } | Should -Throw -ErrorId "ParameterArgumentValidationError,NotNullOrWhiteSpaceFunc" + { NotNullOrWhiteSpaceFunc -Value "" } | Should -Throw -ErrorId "ParameterArgumentValidationError,NotNullOrWhiteSpaceFunc" + { NotNullOrWhiteSpaceFunc -Value " " } | Should -Throw -ErrorId "ParameterArgumentValidationError,NotNullOrWhiteSpaceFunc" + } + It "Mandatory parameter should throw on empty collection" { { MandatoryFunc -ByteArray ([byte[]]@()) } | Should -Throw -ErrorId "ParameterArgumentValidationErrorEmptyArrayNotAllowed,MandatoryFunc" { MandatoryFunc -ByteList ([System.Collections.Generic.List[byte]]@()) } | Should -Throw -ErrorId "ParameterArgumentValidationErrorEmptyCollectionNotAllowed,MandatoryFunc" diff --git a/test/powershell/engine/Basic/assets/standardtypes.csv b/test/powershell/engine/Basic/assets/standardtypes.csv index d372000dcb5..197f2d1e3d0 100644 --- a/test/powershell/engine/Basic/assets/standardtypes.csv +++ b/test/powershell/engine/Basic/assets/standardtypes.csv @@ -321,6 +321,7 @@ "System.Management.Automation.ValidateLengthAttribute","False","False","False","False","False","False","False","True","True","False","False","False","False","False","False","False","False","False","False","False","False","True","False","True","False","False","False","False","False","False","False","True","True","False","False","True","False","False","False","False","False","False","False","False","False","False","True" "System.Management.Automation.ValidateNotNullAttribute","False","False","False","False","False","False","False","True","True","False","False","False","False","False","False","False","False","False","False","False","False","True","False","True","False","False","False","False","False","False","False","True","True","False","False","True","False","False","False","False","False","False","False","False","False","False","True" "System.Management.Automation.ValidateNotNullOrEmptyAttribute","False","False","False","False","False","False","False","True","True","False","False","False","False","False","False","False","False","False","False","False","False","True","False","True","False","False","False","False","False","False","False","True","True","False","False","True","False","False","False","False","False","False","False","False","False","False","True" +"System.Management.Automation.ValidateNotNullOrWhiteSpaceAttribute","False","False","False","False","False","False","False","True","True","False","False","False","False","False","False","False","False","False","False","False","False","True","False","True","False","False","False","False","False","False","False","True","True","False","False","True","False","False","False","False","False","False","False","False","False","False","True" "System.Management.Automation.ValidatePatternAttribute","False","False","False","False","False","False","False","True","True","False","False","False","False","False","False","False","False","False","False","False","False","True","False","True","False","False","False","False","False","False","False","True","True","False","False","True","False","False","False","False","False","False","False","False","False","False","True" "System.Management.Automation.ValidateRangeAttribute","False","False","False","False","False","False","False","True","True","False","False","False","False","False","False","False","False","False","False","False","False","True","False","True","False","False","False","False","False","False","False","True","True","False","False","True","False","False","False","False","False","False","False","False","False","False","True" "System.Management.Automation.ValidateScriptAttribute","False","False","False","False","False","False","False","True","True","False","False","False","False","False","False","False","False","False","False","False","False","True","False","True","False","False","False","False","False","False","False","True","True","False","False","True","False","False","False","False","False","False","False","False","False","False","True" From 1ee2f0d7eeae6cb093349880b0d5bd185f307ebb Mon Sep 17 00:00:00 2001 From: Dominik Kaszewski Date: Wed, 10 Aug 2022 00:51:32 +0200 Subject: [PATCH 004/779] Fix `Update-Help` failing silently with implicit non-US culture. (#17780) --- .../engine/Utils.cs | 1 + .../help/UpdatableHelpCommandBase.cs | 17 +++++++++-- .../help/UpdateHelpCommand.cs | 8 ++++++ .../resources/HelpDisplayStrings.resx | 4 +++ .../engine/Help/HelpSystem.Tests.ps1 | 3 +- .../engine/Help/UpdatableHelpSystem.Tests.ps1 | 28 +++++++++++++++++++ 6 files changed, 58 insertions(+), 3 deletions(-) diff --git a/src/System.Management.Automation/engine/Utils.cs b/src/System.Management.Automation/engine/Utils.cs index 331949d2f0f..661bc1e70cf 100644 --- a/src/System.Management.Automation/engine/Utils.cs +++ b/src/System.Management.Automation/engine/Utils.cs @@ -1561,6 +1561,7 @@ public static class InternalTestHooks internal static bool UseDebugAmsiImplementation; internal static bool BypassAppLockerPolicyCaching; internal static bool BypassOnlineHelpRetrieval; + internal static bool ThrowHelpCultureNotSupported; internal static bool ForcePromptForChoiceDefaultOption; internal static bool NoPromptForPassword; internal static bool ForceFormatListFixedLabelWidth; diff --git a/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs b/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs index af410e4bd6d..1c0576c95b6 100644 --- a/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs +++ b/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs @@ -509,6 +509,7 @@ private void ProcessModule(UpdatableHelpModuleInfo module) // Win8: 572882 When the system locale is English and the UI is JPN, // running "update-help" still downs English help content. var cultures = _language ?? _helpSystem.GetCurrentUICulture(); + UpdatableHelpSystemException implicitCultureNotSupported = null; foreach (string culture in cultures) { @@ -558,6 +559,12 @@ private void ProcessModule(UpdatableHelpModuleInfo module) // Display the error message only if we are not using the fallback chain ProcessException(module.ModuleName, culture, e); } + else + { + // Hold first exception, it will be displayed if fallback chain fails + WriteVerbose(StringUtil.Format(HelpDisplayStrings.HelpCultureNotSupportedFallback, e.Message)); + implicitCultureNotSupported ??= e; + } } else { @@ -581,13 +588,19 @@ private void ProcessModule(UpdatableHelpModuleInfo module) } } - // If -Language is not specified, we only install + // If -UICulture is not specified, we only install // one culture from the fallback chain if (_language == null && installed) { - break; + return; } } + + // If the exception is not null and did not return early, then all of the fallback chain failed + if (implicitCultureNotSupported != null) + { + ProcessException(module.ModuleName, cultures.First(), implicitCultureNotSupported); + } } /// diff --git a/src/System.Management.Automation/help/UpdateHelpCommand.cs b/src/System.Management.Automation/help/UpdateHelpCommand.cs index 371a7321492..236ec2877db 100644 --- a/src/System.Management.Automation/help/UpdateHelpCommand.cs +++ b/src/System.Management.Automation/help/UpdateHelpCommand.cs @@ -214,6 +214,14 @@ protected override void ProcessRecord() /// True if the module has been processed, false if not. internal override bool ProcessModuleWithCulture(UpdatableHelpModuleInfo module, string culture) { + // Simulate culture not found + if (InternalTestHooks.ThrowHelpCultureNotSupported) + { + throw new UpdatableHelpSystemException("HelpCultureNotSupported", + StringUtil.Format(HelpDisplayStrings.HelpCultureNotSupported, culture, "en-US"), + ErrorCategory.InvalidOperation, null, null); + } + UpdatableHelpInfo currentHelpInfo = null; UpdatableHelpInfo newHelpInfo = null; string helpInfoUri = null; diff --git a/src/System.Management.Automation/resources/HelpDisplayStrings.resx b/src/System.Management.Automation/resources/HelpDisplayStrings.resx index 8866eea8d61..222c57e3300 100644 --- a/src/System.Management.Automation/resources/HelpDisplayStrings.resx +++ b/src/System.Management.Automation/resources/HelpDisplayStrings.resx @@ -306,6 +306,10 @@ The specified culture is not supported: {0}. Specify a culture from the following list: {{{1}}}. + + Postponing error and trying fallback cultures, will show as error if none of fallbacks are supported: +{0} + The ModuleBase directory cannot be found. Verify the directory and try again. diff --git a/test/powershell/engine/Help/HelpSystem.Tests.ps1 b/test/powershell/engine/Help/HelpSystem.Tests.ps1 index bd523b1033e..e34cd956075 100644 --- a/test/powershell/engine/Help/HelpSystem.Tests.ps1 +++ b/test/powershell/engine/Help/HelpSystem.Tests.ps1 @@ -30,7 +30,8 @@ function UpdateHelpFromLocalContentPath { throw "Unable to find help content at '$helpContentPath'" } - Update-Help -Module $ModuleName -SourcePath $helpContentPath -Force -ErrorAction Stop -Scope $Scope + # Test files are 'en-US', set explicit culture so test does not help on non-US systems + Update-Help -Module $ModuleName -SourcePath $helpContentPath -UICulture 'en-US' -Force -ErrorAction Stop -Scope $Scope } function GetCurrentUserHelpRoot { diff --git a/test/powershell/engine/Help/UpdatableHelpSystem.Tests.ps1 b/test/powershell/engine/Help/UpdatableHelpSystem.Tests.ps1 index f6707147324..f767ff4ea7f 100644 --- a/test/powershell/engine/Help/UpdatableHelpSystem.Tests.ps1 +++ b/test/powershell/engine/Help/UpdatableHelpSystem.Tests.ps1 @@ -434,6 +434,34 @@ Describe "Validate Update-Help -SourcePath for all PowerShell modules for user s RunUpdateHelpTests -Tag "Feature" -useSourcePath -Scope 'CurrentUser' } +Describe "Validate 'Update-Help' shows 'HelpCultureNotSupported' when thrown" -Tags @('Feature') { + BeforeAll { + [System.Management.Automation.Internal.InternalTestHooks]::SetTestHook('ThrowHelpCultureNotSupported', $true) + } + AfterAll { + [System.Management.Automation.Internal.InternalTestHooks]::SetTestHook('ThrowHelpCultureNotSupported', $false) + } + + It 'Shows error if help culture does not match: ' -TestCases @( + @{ 'name' = 'implicit culture'; 'culture' = $null } + @{ 'name' = 'explicit culture en-GB'; 'culture' = 'en-GB' } + @{ 'name' = 'explicit culture de-DE'; 'culture' = 'de-DE' } + ) { + param ($name, $culture) + # Cannot pass null, have to splat to skip argument entirely + $cultureArg = $culture ? @{ 'UICulture' = $culture } : @{} + $cultureUsed = $culture ?? (Get-Culture) + + $ErrorVariable = $null + $VerboseOutput = New-TemporaryFile + Update-Help @cultureArg -ErrorVariable ErrorVariable -ErrorAction SilentlyContinue -Verbose 4>$VerboseOutput + $ErrorVariable | Should -Match "No UI culture was found that matches the following pattern: ${cultureUsed}" + if (-not $culture) { + Get-Content -Raw $VerboseOutput | Should -Match 'Postponing error and trying fallback cultures' + } + } +} + Describe "Validate 'Save-Help -DestinationPath for one PowerShell modules." -Tags @('CI', 'RequireAdminOnWindows') { BeforeAll { $SavedProgressPreference = $ProgressPreference From 2c9c97ac8609c1c3710cb398fe92c4197407e90b Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Wed, 10 Aug 2022 09:36:33 -0700 Subject: [PATCH 005/779] Do not preserve temporary results when no need to do so (#17856) --- .../engine/parser/Compiler.cs | 27 +++++++++---------- .../Scripting/Scripting.Followup.Tests.ps1 | 22 +++++++++++++++ 2 files changed, 35 insertions(+), 14 deletions(-) diff --git a/src/System.Management.Automation/engine/parser/Compiler.cs b/src/System.Management.Automation/engine/parser/Compiler.cs index cdf053dcb2e..cf7527069db 100644 --- a/src/System.Management.Automation/engine/parser/Compiler.cs +++ b/src/System.Management.Automation/engine/parser/Compiler.cs @@ -2278,26 +2278,25 @@ private Expression CaptureAstResults( switch (context) { case CaptureAstContext.AssignmentWithResultPreservation: + result = Expression.Call(CachedReflectionInfo.PipelineOps_PipelineResult, resultList); + + // PipelineResult might get skipped in some circumstances due to an early return or a FlowControlException thrown out, in which case + // we write to the oldPipe. This can happen in cases like: + // $(1;2;return 3) + finallyExprs.Add(Expression.Call(CachedReflectionInfo.PipelineOps_FlushPipe, oldPipe, resultList)); + break; case CaptureAstContext.AssignmentWithoutResultPreservation: result = Expression.Call(CachedReflectionInfo.PipelineOps_PipelineResult, resultList); // Clear the temporary pipe in case of exception, if we are not required to preserve the results - if (context == CaptureAstContext.AssignmentWithoutResultPreservation) + var catchExprs = new List { - var catchExprs = new List - { - Expression.Call(CachedReflectionInfo.PipelineOps_ClearPipe, resultList), - Expression.Rethrow(), - Expression.Constant(null, typeof(object)) - }; - - catches.Add(Expression.Catch(typeof(RuntimeException), Expression.Block(typeof(object), catchExprs))); - } + Expression.Call(CachedReflectionInfo.PipelineOps_ClearPipe, resultList), + Expression.Rethrow(), + Expression.Constant(null, typeof(object)) + }; - // PipelineResult might get skipped in some circumstances due to a FlowControlException thrown out, in which case - // we write to the oldPipe. This can happen in cases like: - // $(1;2;return 3) - finallyExprs.Add(Expression.Call(CachedReflectionInfo.PipelineOps_FlushPipe, oldPipe, resultList)); + catches.Add(Expression.Catch(typeof(RuntimeException), Expression.Block(typeof(object), catchExprs))); break; case CaptureAstContext.Condition: result = DynamicExpression.Dynamic(PSPipelineResultToBoolBinder.Get(), typeof(bool), resultList); diff --git a/test/powershell/Language/Scripting/Scripting.Followup.Tests.ps1 b/test/powershell/Language/Scripting/Scripting.Followup.Tests.ps1 index 933c53de6de..0d4e8245e2c 100644 --- a/test/powershell/Language/Scripting/Scripting.Followup.Tests.ps1 +++ b/test/powershell/Language/Scripting/Scripting.Followup.Tests.ps1 @@ -68,4 +68,26 @@ Describe "Scripting.Followup.Tests" -Tags "CI" { $result = [ordered]@{ key = 1 } $result | Should -BeOfType 'System.Collections.Specialized.OrderedDictionary' } + + It "Don't preserve result when no need to do so in case of flow-control exception" { + function TestFunc1([switch]$p) { + ## No need to preserve and flush the results from the IF statement to the outer + ## pipeline, because the results are supposed to be assigned to a variable. + if ($p) { + $null = if ($true) { "one"; return "two" } + } else { + $a = foreach ($a in 1) { "one"; return; } + } + } + + function TestFunc2 { + ## The results from the sub-expression need to be preserved and flushed to the outer pipeline. + $("1";return "2") + } + + TestFunc1 | Should -Be $null + TestFunc1 -p | Should -Be $null + + TestFunc2 | Should -Be @("1", "2") + } } From 08a514dd14d4fbfe2c5a335c05599483175eef6b Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Wed, 10 Aug 2022 10:17:08 -0700 Subject: [PATCH 006/779] Update the cgmanifest (#17867) Co-authored-by: adityapatwardhan --- tools/cgmanifest.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/cgmanifest.json b/tools/cgmanifest.json index 1f792a61def..f6a977a64ff 100644 --- a/tools/cgmanifest.json +++ b/tools/cgmanifest.json @@ -1235,7 +1235,7 @@ "Type": "nuget", "Nuget": { "Name": "System.Security.Cryptography.Xml", - "Version": "6.0.0" + "Version": "6.0.1" } }, "DevelopmentDependency": false From f10cf1c4dd10086012dd2c34d77c25dd737bff72 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 11 Aug 2022 10:15:37 -0700 Subject: [PATCH 007/779] Bump Microsoft.NET.Test.Sdk from 17.2.0 to 17.3.0 (#17871) Bumps [Microsoft.NET.Test.Sdk](https://github.com/microsoft/vstest) from 17.2.0 to 17.3.0. - [Release notes](https://github.com/microsoft/vstest/releases) - [Commits](https://github.com/microsoft/vstest/compare/v17.2.0...v17.3.0) --- updated-dependencies: - dependency-name: Microsoft.NET.Test.Sdk dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- test/xUnit/xUnit.tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/xUnit/xUnit.tests.csproj b/test/xUnit/xUnit.tests.csproj index 6579631951d..797f1bd52be 100644 --- a/test/xUnit/xUnit.tests.csproj +++ b/test/xUnit/xUnit.tests.csproj @@ -27,7 +27,7 @@ - + From 11da9e8b06394330d976383fd1e4eb869e7a68b0 Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Thu, 11 Aug 2022 14:18:23 -0700 Subject: [PATCH 008/779] Don't block if we fail to create the comment (#17869) --- .github/workflows/backport.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.github/workflows/backport.yml b/.github/workflows/backport.yml index bfa448413ef..0dd8b331051 100644 --- a/.github/workflows/backport.yml +++ b/.github/workflows/backport.yml @@ -29,9 +29,14 @@ jobs: return target_branch[1]; - name: Post backport started comment to pull request uses: actions/github-script@v6 + continue-on-error: true with: script: | const backport_start_body = `Started backporting to ${{ steps.target-branch-extractor.outputs.result }}: https://github.com/${context.repo.owner}/${context.repo.repo}/actions/runs/${process.env.GITHUB_RUN_ID}`; + console.log(`issue_number: ${context.issue.number}`); + console.log(`owner: ${context.repo.owner}`); + console.log(`repo: ${context.repo.repo}`); + console.log(`body: ${backport_start_body}`); await github.issues.createComment({ issue_number: context.issue.number, owner: context.repo.owner, From 7cfcbf10a7afdef499fc05f03f78378234721545 Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Thu, 11 Aug 2022 17:18:14 -0700 Subject: [PATCH 009/779] Update `README.md` and `metadata.json` for the next releases (#17870) --- README.md | 82 ++++++++++++++++++++++----------------------- tools/metadata.json | 12 +++---- 2 files changed, 47 insertions(+), 47 deletions(-) diff --git a/README.md b/README.md index 518bf2ba212..49061b9d33a 100644 --- a/README.md +++ b/README.md @@ -64,49 +64,49 @@ You can also download the PowerShell binary archives for Windows, macOS and Linu | Windows (Arm) | [64-bit][rl-winarm64] (preview) | [64-bit][pv-winarm64] | [Instructions][in-arm] | | Raspbian (Arm) | [32-bit][rl-arm32]/[64-bit][rl-arm64] | [32-bit][pv-arm32]/[64-bit][pv-arm64] | [Instructions][in-raspbian] | -[lts-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.5/PowerShell-7.2.5-win-x86.msi -[lts-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.5/PowerShell-7.2.5-win-x64.msi -[lts-deb]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.5/powershell-lts_7.2.5-1.deb_amd64.deb -[lts-rh]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.5/powershell-lts-7.2.5-1.rh.x86_64.rpm -[lts-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.5/powershell-lts-7.2.5-osx-x64.pkg -[lts-macos-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.5/powershell-lts-7.2.5-osx-arm64.pkg - -[rl-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.5/PowerShell-7.2.5-win-x64.msi -[rl-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.5/PowerShell-7.2.5-win-x86.msi -[rl-ubuntu20]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.5/powershell_7.2.5-1.deb_amd64.deb -[rl-ubuntu18]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.5/powershell_7.2.5-1.deb_amd64.deb -[rl-ubuntu16]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.5/powershell_7.2.5-1.deb_amd64.deb -[rl-debian9]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.5/powershell_7.2.5-1.deb_amd64.deb -[rl-debian10]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.5/powershell_7.2.5-1.deb_amd64.deb -[rl-debian11]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.5/powershell_7.2.5-1.deb_amd64.deb -[rl-centos]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.5/powershell-7.2.5-1.rh.x86_64.rpm -[rl-centos8]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.5/powershell-7.2.5-1.rh.x86_64.rpm -[rl-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.5/powershell-7.2.5-osx-x64.pkg -[rl-macos-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.5/powershell-7.2.5-osx-arm64.pkg -[rl-winarm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.5/PowerShell-7.2.5-win-arm64.zip -[rl-winx86-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.5/PowerShell-7.2.5-win-x86.zip -[rl-winx64-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.5/PowerShell-7.2.5-win-x64.zip -[rl-macos-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.5/powershell-7.2.5-osx-x64.tar.gz -[rl-macos-tar-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.5/powershell-7.2.5-osx-arm64.tar.gz -[rl-linux-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.5/powershell-7.2.5-linux-x64.tar.gz -[rl-arm32]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.5/powershell-7.2.5-linux-arm32.tar.gz -[rl-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.5/powershell-7.2.5-linux-arm64.tar.gz +[lts-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.6/PowerShell-7.2.6-win-x86.msi +[lts-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.6/PowerShell-7.2.6-win-x64.msi +[lts-deb]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.6/powershell-lts_7.2.6-1.deb_amd64.deb +[lts-rh]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.6/powershell-lts-7.2.6-1.rh.x86_64.rpm +[lts-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.6/powershell-lts-7.2.6-osx-x64.pkg +[lts-macos-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.6/powershell-lts-7.2.6-osx-arm64.pkg + +[rl-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.6/PowerShell-7.2.6-win-x64.msi +[rl-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.6/PowerShell-7.2.6-win-x86.msi +[rl-ubuntu20]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.6/powershell_7.2.6-1.deb_amd64.deb +[rl-ubuntu18]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.6/powershell_7.2.6-1.deb_amd64.deb +[rl-ubuntu16]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.6/powershell_7.2.6-1.deb_amd64.deb +[rl-debian9]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.6/powershell_7.2.6-1.deb_amd64.deb +[rl-debian10]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.6/powershell_7.2.6-1.deb_amd64.deb +[rl-debian11]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.6/powershell_7.2.6-1.deb_amd64.deb +[rl-centos]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.6/powershell-7.2.6-1.rh.x86_64.rpm +[rl-centos8]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.6/powershell-7.2.6-1.rh.x86_64.rpm +[rl-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.6/powershell-7.2.6-osx-x64.pkg +[rl-macos-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.6/powershell-7.2.6-osx-arm64.pkg +[rl-winarm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.6/PowerShell-7.2.6-win-arm64.zip +[rl-winx86-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.6/PowerShell-7.2.6-win-x86.zip +[rl-winx64-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.6/PowerShell-7.2.6-win-x64.zip +[rl-macos-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.6/powershell-7.2.6-osx-x64.tar.gz +[rl-macos-tar-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.6/powershell-7.2.6-osx-arm64.tar.gz +[rl-linux-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.6/powershell-7.2.6-linux-x64.tar.gz +[rl-arm32]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.6/powershell-7.2.6-linux-arm32.tar.gz +[rl-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.6/powershell-7.2.6-linux-arm64.tar.gz [rl-snap]: https://snapcraft.io/powershell -[pv-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.6/PowerShell-7.3.0-preview.6-win-x64.msi -[pv-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.6/PowerShell-7.3.0-preview.6-win-x86.msi -[pv-deb]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.6/powershell-preview_7.3.0-preview.6-1.deb_amd64.deb -[pv-rpm]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.6/powershell-preview-7.3.0_preview.6-1.rh.x86_64.rpm -[pv-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.6/powershell-7.3.0-preview.6-osx-x64.pkg -[pv-macos-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.6/powershell-7.3.0-preview.6-osx-arm64.pkg -[pv-winarm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.6/PowerShell-7.3.0-preview.6-win-arm64.zip -[pv-winx86-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.6/PowerShell-7.3.0-preview.6-win-x86.zip -[pv-winx64-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.6/PowerShell-7.3.0-preview.6-win-x64.zip -[pv-macos-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.6/powershell-7.3.0-preview.6-osx-x64.tar.gz -[pv-macos-tar-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.6/powershell-7.3.0-preview.6-osx-arm64.tar.gz -[pv-linux-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.6/powershell-7.3.0-preview.6-linux-x64.tar.gz -[pv-arm32]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.6/powershell-7.3.0-preview.6-linux-arm32.tar.gz -[pv-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.6/powershell-7.3.0-preview.6-linux-arm64.tar.gz +[pv-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.7/PowerShell-7.3.0-preview.7-win-x64.msi +[pv-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.7/PowerShell-7.3.0-preview.7-win-x86.msi +[pv-deb]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.7/powershell-preview_7.3.0-preview.7-1.deb_amd64.deb +[pv-rpm]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.7/powershell-preview-7.3.0_preview.7-1.rh.x86_64.rpm +[pv-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.7/powershell-7.3.0-preview.7-osx-x64.pkg +[pv-macos-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.7/powershell-7.3.0-preview.7-osx-arm64.pkg +[pv-winarm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.7/PowerShell-7.3.0-preview.7-win-arm64.zip +[pv-winx86-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.7/PowerShell-7.3.0-preview.7-win-x86.zip +[pv-winx64-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.7/PowerShell-7.3.0-preview.7-win-x64.zip +[pv-macos-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.7/powershell-7.3.0-preview.7-osx-x64.tar.gz +[pv-macos-tar-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.7/powershell-7.3.0-preview.7-osx-arm64.tar.gz +[pv-linux-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.7/powershell-7.3.0-preview.7-linux-x64.tar.gz +[pv-arm32]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.7/powershell-7.3.0-preview.7-linux-arm32.tar.gz +[pv-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.7/powershell-7.3.0-preview.7-linux-arm64.tar.gz [pv-snap]: https://snapcraft.io/powershell-preview [in-windows]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-windows diff --git a/tools/metadata.json b/tools/metadata.json index 986bd104fab..44192df371d 100644 --- a/tools/metadata.json +++ b/tools/metadata.json @@ -1,10 +1,10 @@ { - "StableReleaseTag": "v7.2.5", - "PreviewReleaseTag": "v7.3.0-preview.6", - "ServicingReleaseTag": "v7.0.11", - "ReleaseTag": "v7.2.5", - "LTSReleaseTag" : ["v7.2.5", "v7.0.11"], - "NextReleaseTag": "v7.3.0-preview.7", + "StableReleaseTag": "v7.2.6", + "PreviewReleaseTag": "v7.3.0-preview.7", + "ServicingReleaseTag": "v7.0.12", + "ReleaseTag": "v7.2.6", + "LTSReleaseTag" : ["v7.2.6", "v7.0.12"], + "NextReleaseTag": "v7.3.0-preview.8", "LTSRelease": { "Latest": false, "Package": false }, "StableRelease": { "Latest": false, "Package": false } } From 9d0f6b26ddbb1024ea78f6426383e9b13d139fb9 Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Tue, 9 Aug 2022 23:09:42 +0000 Subject: [PATCH 010/779] Merged PR 22048: Add change log for 7.3.0-preview.7 and .spelling file Add change log for 7.3.0-preview.7 and .spelling file --- .spelling | 20 ++++++++ CHANGELOG/preview.md | 116 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 136 insertions(+) diff --git a/.spelling b/.spelling index 5bd81a0135b..8f8bbd2ca61 100644 --- a/.spelling +++ b/.spelling @@ -49,6 +49,7 @@ alpha.9 alternatestream alvarodelvalle amd64 +ananya26-vishnoi andschwa anmenaga api @@ -110,6 +111,7 @@ catchable cdxml celsius CentOS +codeql-action cgmanifest CGManifest changelog @@ -124,6 +126,7 @@ checkbox checksum chibi childitem +ChuckieChen945 ChrisLGardner cimsession cimsupport @@ -232,6 +235,7 @@ displaydataquery Distribution_Request.md distro distros +dkaszews dll dlls dlwyatt @@ -294,6 +298,7 @@ fbehrens felixfbecker ffeldhaus ffi +fflaten filecatalog filename filesystem @@ -387,6 +392,7 @@ Higinbotham himura2la hololens homebrew +hostifaces hostname hotfix httpbin.org @@ -506,6 +512,7 @@ markekraus marktiedemann Marusyk MarvTheRobot +mattifestation matt9ucci mcbobke md @@ -522,11 +529,13 @@ Microsoft.ApplicationInsights Microsoft.CodeAnalysis.CSharp Microsoft.CodeAnalysis.NetAnalyzers microsoft.com +Microsoft.Management microsoft.management.infrastructure.cimcmdlets microsoft.management.infrastructure.native Microsoft.Management.Infrastructure.Runtime.Win microsoft.net.test.sdk microsoft.powershell.archive +Microsoft.PowerShell.Commands microsoft.powershell.commands.diagnostics microsoft.powershell.commands.management microsoft.powershell.commands.utility @@ -542,6 +551,7 @@ microsoft.powershell.psreadline microsoft.powershell.security microsoft.powershell.utility Microsoft.Security.Extensions +Microsoft.WSMan microsoft.wsman.management microsoft.wsman.runtime mikeTWC1984 @@ -549,7 +559,9 @@ mirichmo mjanko5 mkdir mklement0 +ModuleCmdletBase.cs MohiTheFish +Molkree move-itemproperty ms-psrp msbuild @@ -639,6 +651,7 @@ parameterbindercontroller parameterbinding ParenExpression ParseError.ToString +Path.Join pathresolution PathResolvedToMultiple patochun @@ -649,6 +662,7 @@ payette perf perfview perfview.exe +peter-evans petseral plaintext pluggable @@ -677,6 +691,7 @@ pre-build pre-compiled pre-generated pre-installed +pre-parse pre-release pre-releases pre-requisites @@ -703,6 +718,7 @@ preview.7.20358.6 preview.7.20364.3 preview.7.20366.2 preview.7.20366.15 +preview.7.22377.5 preview.4.20258.7 preview.4.20229.10 preview.4.22252.9 @@ -821,6 +837,7 @@ runspaceinit runspaces runtime runtimes +Ryan-Hutchison-USAF SA1026CodeMustNotContainSpaceAfterNewKeywordInImplicitlyTypedArrayAllocation Saancreed sample-dotnet1 @@ -914,6 +931,7 @@ System.IO.Packaging System.InvalidOperationException system.manage system.management.automation +System.Management.Automation.utils systemd SytzeAndr tabcompletion @@ -1029,9 +1047,11 @@ v7.2.2 v7.3.0 validatenotnullorempty ValidateSet +varunsh-coder versioned versioning vexx32 +Virtualization visualstudio vmsilvamolina vorobev diff --git a/CHANGELOG/preview.md b/CHANGELOG/preview.md index 56ffbc92083..cf80d139a56 100644 --- a/CHANGELOG/preview.md +++ b/CHANGELOG/preview.md @@ -1,5 +1,121 @@ # Current preview release +## [7.3.0-preview.7] - 2022-08-09 + +### Breaking Changes + +- Move the type data definition of `System.Security.AccessControl.ObjectSecurity` to the `Microsoft.PowerShell.Security` module (#16355) (Thanks @iSazonov!) + +### Engine Updates and Fixes + +- Enable searching for assemblies in `GAC_Arm64` on Windows (#17816) +- Fix parser exception in using statements with empty aliases (#16745) (Thanks @MartinGC94!) +- Do not always collapse space between parameter and value for native arguments. (#17708) +- Remove `PSNativePSPathResolution` experimental feature (#17670) + +### General Cmdlet Updates and Fixes + +- Fix for deserializing imported ordered dictionary (#15545) (Thanks @davidBar-On!) +- Make generated implicit remoting modules backwards compatible with PowerShell 5.1 (#17227) (Thanks @Tadas!) +- Re-enable IDE0031: Use Null propagation (#17811) (Thanks @fflaten!) +- Allow commands to still be executed even if the current working directory no longer exists (#17579) +- Stop referencing `Microsoft.PowerShell.Security` when the core snapin is used (#17771) +- Add support for HTTPS with `Set-AuthenticodeSignature -TimeStampServer` (#16134) (Thanks @Ryan-Hutchison-USAF!) +- Add type accelerator `ordered` for `OrderedDictionary` (#17804) (Thanks @fflaten!) +- Fix the definition of the `PDH_COUNTER_INFO` struct (#17779) +- Adding Virtualization Based Security feature names to Get-ComputerInfo (#16415) (Thanks @mattifestation!) +- Fix `FileSystemProvider` to work with volume and pipe paths (#15873) +- Remove pre-parse for array-based JSON (#15684) (Thanks @strawgate!) +- Improve type inference for `$_` (#17716) (Thanks @MartinGC94!) +- Prevent braces from being removed when completing variables (#17751) (Thanks @MartinGC94!) +- Fix type inference for `ICollection` (#17752) (Thanks @MartinGC94!) +- Fix `Test-Json` not handling non-object types at root (#17741) (Thanks @dkaszews!) +- Change `Get-ChildItem` to treat trailing slash in path as indicating a directory when used with `-Recurse` (#17704) +- Add `find.exe` to legacy argument binding behavior for Windows (#17715) +- Add completion for index expressions for dictionaries (#17619) (Thanks @MartinGC94!) +- Fix enum-ranges for `ValidateRange` in proxy commands (#17572) (Thanks @fflaten!) +- Fix type completion for attribute tokens (#17484) (Thanks @MartinGC94!) +- Add `-noprofileloadtime` switch to `pwsh` (#17535) (Thanks @rkeithhill!) +- Fix legacy `ErrorView` types to use `$host.PrivateData` colors (#17705) +- Improve dynamic parameter tab completion (#17661) (Thanks @MartinGC94!) +- Avoid binding positional parameters when completing parameter in front of value (#17693) (Thanks @MartinGC94!) +- Render decimal numbers in a table using current culture (#17650) + +### Code Cleanup + +
+ + + +

We thank the following contributors!

+

@fflaten, @Molkree, @eltociear

+ +
+ +
    +
  • Fix other path constructions using Path.Join (#17825)
  • +
  • Use null propagation (#17787)(#17789)(#17790)(#17791)(#17792)(#17795) (Thanks @fflaten!)
  • +
  • Re-enable compound assignment preference (#17784) (Thanks @Molkree!)
  • +
  • Use null-coalescing assignment (#17719)(#17720)(#17721)(#17722)(#17723)(#17724)(#17725)(#17726)(#17727)(#17728)(#17729) (Thanks @Molkree!)
  • +
  • Disable the warning IDE0031 to take .NET 7 Preview 7 (#17770)
  • +
  • Fix typo in ModuleCmdletBase.cs (#17714) (Thanks @eltociear!)
  • +
+ +
+ +### Tests + +- Re-enable tests because the corresponding dotnet issues were fixed (#17839) +- Add test for `LanguageMode` using remoting (#17803) (Thanks @fflaten!) +- Fix test perf by stopping ongoing `write-progress` (#17749) (Thanks @fflaten!) +- Re-enable the test `TestLoadNativeInMemoryAssembly` (#17738) + +### Build and Packaging Improvements + +
+ + + +

We thank the following contributors!

+

@varunsh-coder, @dkaszews, @Molkree, @ChuckieChen945

+ +
+ +
    +
  • Update release pipeline to use Approvals and automate some manual tasks (#17837)
  • +
  • Add GitHub token permissions for workflows (#17781) (Thanks @varunsh-coder!)
  • +
  • Bump actions/github-script from 3 to 6 (#17842)
  • +
  • Bump cirrus-actions/rebase from 1.6 to 1.7 (#17843)
  • +
  • Remove unneeded verbose message in build (#17840)
  • +
  • Detect default runtime using dotnet --info in build.psm1 (#17818) (Thanks @dkaszews!)
  • +
  • Bump actions/checkout from 2 to 3 (#17828)
  • +
  • Bump actions/download-artifact from 2 to 3 (#17829)
  • +
  • Bump github/codeql-action from 1 to 2 (#17830)
  • +
  • Bump peter-evans/create-pull-request from 3 to 4 (#17831)
  • +
  • Bump actions/upload-artifact from 2 to 3 (#17832)
  • +
  • Enable Dependabot for GitHub Actions (#17775) (Thanks @Molkree!)
  • +
  • Update .NET SDK version from 7.0.100-preview.6.22352.1 to 7.0.100-preview.7.22377.5 (#17776)
  • +
  • Fix a bug in install-powershell.ps1 (#17794) (Thanks @ChuckieChen945!)
  • +
  • Bump xunit from 2.4.1 to 2.4.2 (#17817)
  • +
  • Update how to update homebrew (#17798)
  • +
  • Don't run link check on forks (#17797)
  • +
  • Update dotnetmetadata.json to start consuming .NET 7 preview 7 builds (#17736)
  • +
  • Bump PackageManagement from 1.4.7 to 1.4.8.1 (#17709)
  • +
  • Exclude ARM images from running in CI (#17713)
  • +
+ +
+ +### Documentation and Help Content + +- Update the comment about why R2R is disabled (#17850) +- Update changelog and `.spelling` for `7.3.0-preview.6` release (#17835) +- Updated `ADOPTERS.md` for Power BI (#17766) +- Update README.md with the current Fedora version (#15717) (Thanks @ananya26-vishnoi!) +- Update `README` and `metadata.json` for next release (#17676) (Thanks @SeeminglyScience!) + +[7.3.0-preview.7]: https://github.com/PowerShell/PowerShell/compare/v7.3.0-preview.6...v7.3.0-preview.7 + ## [7.3.0-preview.6] - 2022-07-18 ### General Cmdlet Updates and Fixes From 46f7b36bfddc03992be6b9022ed45894a1e0013f Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Thu, 11 Aug 2022 15:46:59 -0700 Subject: [PATCH 011/779] Fix script by adding quotes --- .../azureDevOps/templates/release-CreateGitHubDraft.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/releaseBuild/azureDevOps/templates/release-CreateGitHubDraft.yml b/tools/releaseBuild/azureDevOps/templates/release-CreateGitHubDraft.yml index 035adae0c84..426e58e0f64 100644 --- a/tools/releaseBuild/azureDevOps/templates/release-CreateGitHubDraft.yml +++ b/tools/releaseBuild/azureDevOps/templates/release-CreateGitHubDraft.yml @@ -57,7 +57,7 @@ steps: $semanticVersion.Major + "." + $semanticVersion.Minor + ".md" } - $filePath = $env:BUILD_SOURCESDIRECTORY/CHANGELOG/$fileName + $filePath = "$env:BUILD_SOURCESDIRECTORY/CHANGELOG/$fileName" Write-Verbose -Verbose "Selected Log file: $filePath" if (-not (Test-Path $filePath)) { From 2b23cd5405a84c0b7344b29a75795d1c91a3de3b Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Thu, 11 Aug 2022 16:15:03 -0700 Subject: [PATCH 012/779] Remove raw to process changelog line by line --- .../azureDevOps/templates/release-CreateGitHubDraft.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/releaseBuild/azureDevOps/templates/release-CreateGitHubDraft.yml b/tools/releaseBuild/azureDevOps/templates/release-CreateGitHubDraft.yml index 426e58e0f64..b32c812430e 100644 --- a/tools/releaseBuild/azureDevOps/templates/release-CreateGitHubDraft.yml +++ b/tools/releaseBuild/azureDevOps/templates/release-CreateGitHubDraft.yml @@ -64,7 +64,7 @@ steps: throw "$filePath not found" } - $changelog = Get-Content -Raw -Path $filePath + $changelog = Get-Content -Path $filePath $startPattern = "^## \[" + ([regex]::Escape($releaseVersion)) + "\]" $endPattern = "^## \[{0}\.{1}\.{2}*" -f $semanticVersion.Major, $semanticVersion.Minor, $semanticVersion.Patch From 89382e42e310ba11d202170001c579bab3e6266c Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Thu, 11 Aug 2022 16:38:39 -0700 Subject: [PATCH 013/779] Add Out-String to make the description a single string --- .../azureDevOps/templates/release-CreateGitHubDraft.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/releaseBuild/azureDevOps/templates/release-CreateGitHubDraft.yml b/tools/releaseBuild/azureDevOps/templates/release-CreateGitHubDraft.yml index b32c812430e..9e439db7366 100644 --- a/tools/releaseBuild/azureDevOps/templates/release-CreateGitHubDraft.yml +++ b/tools/releaseBuild/azureDevOps/templates/release-CreateGitHubDraft.yml @@ -73,7 +73,7 @@ steps: if ($_ -match $startPattern) { $outputLine = $true } elseif ($_ -match $endPattern) { $outputLine = $false } if ($outputLine) { $_} - } + } | Out-String Write-Verbose -Verbose "Selected content: `n$clContent" From fe79ce8c6fa404de0385b5012efd6507c216e92e Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Thu, 11 Aug 2022 19:53:09 +0000 Subject: [PATCH 014/779] Merged PR 22116: Changelog for v7.0.12 Changelog for v7.0.12 --- .spelling | 7 +++++++ CHANGELOG/7.0.md | 35 +++++++++++++++++++++++++++++++++-- 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/.spelling b/.spelling index 8f8bbd2ca61..a2749c75794 100644 --- a/.spelling +++ b/.spelling @@ -18,6 +18,7 @@ about_ about_debuggers about_jobs about_Telemetry +about_PSDesiredStateConfiguration acl adamdriscoll add-localgroupmember @@ -71,6 +72,7 @@ authenticode authenticodesignature azdevops AzFileCopy +AzureFileCopy azurerm.netcore.preview azurerm.profile.netcore.preview azurerm.resources.netcore.preview @@ -373,6 +375,7 @@ github githug gitter glachancecmaisonneuve +global.json globbing GoogleTest GUIs @@ -508,6 +511,7 @@ maertendmsft mahawar Markdig.Signed markdown.yml +manifest.spdx.json markekraus marktiedemann Marusyk @@ -515,6 +519,7 @@ MarvTheRobot mattifestation matt9ucci mcbobke +mcr.microsoft.com md meir017 memberresolution @@ -744,6 +749,7 @@ PSGalleryModules psm1 psobject psobjects +psoptions.json psproxyjobs psreadline psrp.windows @@ -942,6 +948,7 @@ TargetFramework test-modulemanifest test-pssessionconfigurationfile test-scriptfileinfo +tar.gz test.ps1 test.txt. Tests.ps1 diff --git a/CHANGELOG/7.0.md b/CHANGELOG/7.0.md index 13468c71bc8..3d446b6cf8e 100644 --- a/CHANGELOG/7.0.md +++ b/CHANGELOG/7.0.md @@ -1,6 +1,37 @@ # 7.0 Changelog -## [7.0.11] - 2022-05-17 +## [7.0.12] - 2022-08-11 + +### General Cmdlet Updates and Fixes + +- Fix `Export-PSSession` to not throw error when a rooted path is specified for `-OutputModule` (#17671) + +### Tests + +- Enable more tests to be run in a container. (#17294) +- Switch to using GitHub action to verify markdown links for PRs (#17281) +- Add `win-x86` test package to the build (#15517) + +### Build and Packaging Improvements + +
+ + +

Bump .NET 3.1 SDK to 3.1.28

+
+ +
    +
  • Update wix file
  • +
  • Add a finalize template which causes jobs with issues to fail (#17314)
  • +
  • Make sure we execute tests on LTS package for older LTS releases (#17326)
  • +
  • Update AzureFileCopy task and fix the syntax for specifying pool (#17013)
  • +
+ +
+ +[7.0.12]: https://github.com/PowerShell/PowerShell/compare/v7.0.11...v7.0.12 + +## [7.0.11] - 2022-05-13 ### Build and Packaging Improvements @@ -15,7 +46,7 @@
  • Add explicit job name for approval tasks in Snap stage (#16579)
  • Update to use mcr.microsoft.com (#17272)
  • -
  • Update global.json and wix
  • +
  • Update global.json and wix
  • Put Secure supply chain analysis at correct place (#17273)
  • Partial back-port of: Update a few tests to make them more stable in CI (#16944) (Internal 20648)
  • Replace . in notices container name (#17292)
  • From 66d2a327da60f7934980fc3b7bcdea2e07bd4a2d Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Thu, 11 Aug 2022 00:17:35 +0000 Subject: [PATCH 015/779] Merged PR 22095: Changelog for v7.2.6 Changelog for v7.2.6 --- .spelling | 2 +- CHANGELOG/7.2.md | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/.spelling b/.spelling index a2749c75794..3aa89bb4a69 100644 --- a/.spelling +++ b/.spelling @@ -59,7 +59,7 @@ APIScan appimage applocker appveyor -AppX +appx args argumentlist arm32 diff --git a/CHANGELOG/7.2.md b/CHANGELOG/7.2.md index 77890905734..a5ac6b7f1ed 100644 --- a/CHANGELOG/7.2.md +++ b/CHANGELOG/7.2.md @@ -1,5 +1,45 @@ # 7.2 Changelog +## [7.2.6] - 2022-08-11 + +### Engine Updates and Fixes + +- Fix `ForEach-Object -Parallel` when passing in script block variable (#16564) + +### General Cmdlet Updates and Fixes + +- Make `Out-String` and `Out-File` keep string input unchanged (#17455) +- Update regex used to remove ANSI escape sequences to be more specific to decoration and hyperlinks (#16811) +- Fix legacy `ErrorView` types to use `$host.PrivateData` colors (#17705) +- Fix `Export-PSSession` to not throw error when a rooted path is specified for `-OutputModule` (#17671) + +### Tests + +- Disable RPM SBOM test. (#17532) + +### Build and Packaging Improvements + +
    + + +

    Bump .NET SDK to 6.0.8 (Internal 22065)

    +

    We thank the following contributors!

    +

    @tamasvajk

    +
    + +
      +
    • Update Wix manifest
    • +
    • Add AppX capabilities in MSIX manifest so that PS7 can call the AppX APIs (#17416)
    • +
    • Use Quality only with Channel in dotnet-install (#17847)
    • +
    • Fix build.psm1 to not specify both version and quality for dotnet-install (#17589) (Thanks @tamasvajk!)
    • +
    • Install .NET 3.1 as it is required by the vPack task
    • +
    + +
    + +[7.2.6]: https://github.com/PowerShell/PowerShell/compare/v7.2.5...v7.2.6 + + ## [7.2.5] - 2022-06-21 ### Engine Updates and Fixes From dbffa2766fefd1f05119b4efafe3f9f832130e02 Mon Sep 17 00:00:00 2001 From: Frode Flaten <3436158+fflaten@users.noreply.github.com> Date: Fri, 12 Aug 2022 05:15:42 +0200 Subject: [PATCH 016/779] Stop ongoing progress-bar in Write-Progress test (#17880) --- .../Microsoft.PowerShell.Utility/Write-Progress.Tests.ps1 | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Write-Progress.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Write-Progress.Tests.ps1 index 6e6c9ee57c4..0f62cbcb6a6 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Write-Progress.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Write-Progress.Tests.ps1 @@ -24,6 +24,8 @@ Describe "Write-Progress DRT Unit Tests" -Tags "CI" { } It 'Activity longer than console width works' { - { Write-Progress -Activity ('a' * ([console]::WindowWidth + 1)) -Status ('b' * ([console]::WindowWidth + 1)) -Id 1 } | Should -Not -Throw + $activity = 'a' * ([console]::WindowWidth + 1) + { Write-Progress -Activity $activity -Status ('b' * ([console]::WindowWidth + 1)) -Id 1 } | Should -Not -Throw + Write-Progress -Activity $activity -Id 1 -Completed } } From 70034191ec3dde81f671afb1dcb4580444277ed1 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Fri, 12 Aug 2022 13:19:51 -0700 Subject: [PATCH 017/779] Update to the latest NOTICES file (#17882) Co-authored-by: adityapatwardhan --- ThirdPartyNotices.txt | 39 +-------------------------------------- 1 file changed, 1 insertion(+), 38 deletions(-) diff --git a/ThirdPartyNotices.txt b/ThirdPartyNotices.txt index 64621d33567..cf58fe4e9c8 100644 --- a/ThirdPartyNotices.txt +++ b/ThirdPartyNotices.txt @@ -3118,46 +3118,9 @@ SOFTWARE. --------------------------------------------------------- -System.Security.Cryptography.Xml 6.0.0 - MIT +System.Security.Cryptography.Xml 6.0.1 - MIT -(c) Microsoft Corporation. -Copyright (c) Andrew Arnott -Copyright 2018 Daniel Lemire -Copyright 2012 the V8 project -Copyright (c) .NET Foundation. -Copyright (c) 2011, Google Inc. -Copyright (c) 1998 Microsoft. To -(c) 1997-2005 Sean Eron Anderson. -Copyright (c) 2017 Yoshifumi Kawai -Copyright (c) Microsoft Corporation -Copyright (c) 2007 James Newton-King -Copyright (c) 2012-2014, Yann Collet -Copyright (c) 2013-2017, Alfred Klomp -Copyright (c) 2015-2017, Wojciech Mula -Copyright (c) 2005-2007, Nick Galbreath -Copyright (c) 2018 Alexander Chermyanin -Portions (c) International Organization -Copyright (c) 2015 The Chromium Authors. -Copyright (c) The Internet Society 1997. -Copyright (c) 2004-2006 Intel Corporation -Copyright (c) 2013-2017, Milosz Krajewski -Copyright (c) 2016-2017, Matthieu Darbois -Copyright (c) .NET Foundation Contributors -Copyright (c) The Internet Society (2003). -Copyright (c) .NET Foundation and Contributors -Copyright (c) 2019 Microsoft Corporation, Daan Leijen -Copyright (c) 2011 Novell, Inc (http://www.novell.com) -Copyright (c) 1995-2017 Jean-loup Gailly and Mark Adler -Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) -Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors. -Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com -Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. -Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip. -Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers THIS WORK IS PROVIDED AS -Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California. -Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass. -Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass. To The MIT License (MIT) From 8d25b5ae6e2eb83a957eac823c27546a70c229a0 Mon Sep 17 00:00:00 2001 From: "James Truher [MSFT]" Date: Tue, 16 Aug 2022 09:37:48 -0700 Subject: [PATCH 018/779] Update to use version 2.21.0 of Application Insights. (#17903) Replaces dependabot PR #17733 --- .../System.Management.Automation.csproj | 2 +- src/System.Management.Automation/utils/Telemetry.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/System.Management.Automation/System.Management.Automation.csproj b/src/System.Management.Automation/System.Management.Automation.csproj index cc867501e8b..602c5fbffad 100644 --- a/src/System.Management.Automation/System.Management.Automation.csproj +++ b/src/System.Management.Automation/System.Management.Automation.csproj @@ -14,7 +14,7 @@ - + diff --git a/src/System.Management.Automation/utils/Telemetry.cs b/src/System.Management.Automation/utils/Telemetry.cs index 625f9571651..3d9f3c9e1f7 100644 --- a/src/System.Management.Automation/utils/Telemetry.cs +++ b/src/System.Management.Automation/utils/Telemetry.cs @@ -143,7 +143,7 @@ static ApplicationInsightsTelemetry() { s_sessionId = Guid.NewGuid().ToString(); TelemetryConfiguration configuration = TelemetryConfiguration.CreateDefault(); - configuration.InstrumentationKey = _psCoreTelemetryKey; + configuration.ConnectionString = "InstrumentationKey=" + _psCoreTelemetryKey; // Set this to true to reduce latency during development configuration.TelemetryChannel.DeveloperMode = false; From 9c14a5d9c72204d40fc488537ceddc40d92f3897 Mon Sep 17 00:00:00 2001 From: Patrick Meinecke Date: Wed, 17 Aug 2022 12:35:44 -0400 Subject: [PATCH 019/779] Update list of PowerShell team members in release tools (#17909) --- tools/releaseTools.psm1 | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/tools/releaseTools.psm1 b/tools/releaseTools.psm1 index c900135aaee..388f3654c37 100644 --- a/tools/releaseTools.psm1 +++ b/tools/releaseTools.psm1 @@ -33,15 +33,14 @@ class CommitNode { # These powershell team members don't use 'microsoft.com' for Github email or choose to not show their emails. # We have their names in this array so that we don't need to query GitHub to find out if they are powershell team members. $Script:powershell_team = @( - "Robert Holt" "Travis Plunk" "dependabot-preview[bot]" "dependabot[bot]" - "Joey Aiello" - "Tyler James Leonhardt" + "github-actions[bot]" "Anam Navied" "Andrew Schwartzmeyer" "Jason Helmick" + "Patrick Meinecke" ) # They are very active contributors, so we keep their email-login mappings here to save a few queries to Github. From f38e181fa901430ee93933cfad4916bc8942734b Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Thu, 18 Aug 2022 09:42:45 -0700 Subject: [PATCH 020/779] Update the cgmanifest (#17913) Co-authored-by: adityapatwardhan --- tools/cgmanifest.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/cgmanifest.json b/tools/cgmanifest.json index f6a977a64ff..a290afb3c9c 100644 --- a/tools/cgmanifest.json +++ b/tools/cgmanifest.json @@ -35,7 +35,7 @@ "Type": "nuget", "Nuget": { "Name": "Microsoft.ApplicationInsights", - "Version": "2.20.0" + "Version": "2.21.0" } }, "DevelopmentDependency": false From 378ce9fd72a15da9e20c9c01f41dcf47337e6cda Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Thu, 18 Aug 2022 09:47:09 -0700 Subject: [PATCH 021/779] Make Register Microsoft Update timeout (#17910) * Make Register MU timeout * Update Product.wxs * Update powershell-win-core.csproj * Rename src/PowerShell.Core.Instrumentation/RegisterMicrosoftUpdate.ps1 to assets/MicrosoftUpdate/RegisterMicrosoftUpdate.ps1 * Update src/powershell-win-core/powershell-win-core.csproj * Update RegisterMicrosoftUpdate.ps1 * Update RegisterMicrosoftUpdate.ps1 * Update files.wxs * Update assets/MicrosoftUpdate/RegisterMicrosoftUpdate.ps1 Co-authored-by: Aditya Patwardhan * Update assets/MicrosoftUpdate/RegisterMicrosoftUpdate.ps1 Co-authored-by: Aditya Patwardhan * Update RegisterMicrosoftUpdate.ps1 * Update RegisterMicrosoftUpdate.ps1 * Update RegisterMicrosoftUpdate.ps1 * Update RegisterMicrosoftUpdate.ps1 * Update assets/MicrosoftUpdate/RegisterMicrosoftUpdate.ps1 Co-authored-by: Aditya Patwardhan --- .../RegisterMicrosoftUpdate.ps1 | 70 +++++++++++++++++++ assets/wix/Product.wxs | 2 +- assets/wix/files.wxs | 4 ++ .../powershell-win-core.csproj | 2 +- 4 files changed, 76 insertions(+), 2 deletions(-) create mode 100644 assets/MicrosoftUpdate/RegisterMicrosoftUpdate.ps1 diff --git a/assets/MicrosoftUpdate/RegisterMicrosoftUpdate.ps1 b/assets/MicrosoftUpdate/RegisterMicrosoftUpdate.ps1 new file mode 100644 index 00000000000..fd341d4fbef --- /dev/null +++ b/assets/MicrosoftUpdate/RegisterMicrosoftUpdate.ps1 @@ -0,0 +1,70 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +param( + [ValidateSet('Hang', 'Fail')] + $TestHook +) + +$waitTimeoutSeconds = 300 +switch ($TestHook) { + 'Hang' { + $waitTimeoutSeconds = 10 + $jobScript = { Start-Sleep -Seconds 600 } + } + 'Fail' { + $jobScript = { throw "This job script should fail" } + } + default { + $jobScript = { + # This registers Microsoft Update via a predifened GUID with the Windows Update Agent. + # https://docs.microsoft.com/en-us/windows/win32/wua_sdk/opt-in-to-microsoft-update + + $serviceManager = (New-Object -ComObject Microsoft.Update.ServiceManager) + $isRegistered = $serviceManager.QueryServiceRegistration('7971f918-a847-4430-9279-4a52d1efe18d').Service.IsRegisteredWithAu + + if (!$isRegistered) { + Write-Verbose -Verbose "Opting into Microsoft Update as the Autmatic Update Service" + # 7 is the combination of asfAllowPendingRegistration, asfAllowOnlineRegistration, asfRegisterServiceWithAU + # AU means Automatic Updates + $null = $serviceManager.AddService2('7971f918-a847-4430-9279-4a52d1efe18d', 7, '') + } + else { + Write-Verbose -Verbose "Microsoft Update is already registered for Automatic Updates" + } + + $isRegistered = $serviceManager.QueryServiceRegistration('7971f918-a847-4430-9279-4a52d1efe18d').Service.IsRegisteredWithAu + + # Return if it was successful, which is the opposite of Pending. + return $isRegistered + } + } +} + +Write-Verbose "Running job script: $jobScript" -Verbose +$job = Start-ThreadJob -ScriptBlock $jobScript + +Write-Verbose "Waiting on Job for $waitTimeoutSeconds seconds" -Verbose +$null = Wait-Job -Job $job -Timeout $waitTimeoutSeconds + +if ($job.State -ne 'Running') { + Write-Verbose "Job finished. State: $($job.State)" -Verbose + $result = Receive-Job -Job $job -Verbose + Write-Verbose "Result: $result" -Verbose + if ($result) { + Write-Verbose "Registration succeeded" -Verbose + exit 0 + } + else { + Write-Verbose "Registration failed" -Verbose + # at the time this was written, the MSI is ignoring the exit code + exit 1 + } +} +else { + Write-Verbose "Job timed out" -Verbose + Write-Verbose "Stopping Job. State: $($job.State)" -Verbose + Stop-Job -Job $job + # at the time this was written, the MSI is ignoring the exit code + exit 258 +} diff --git a/assets/wix/Product.wxs b/assets/wix/Product.wxs index bf6ab5d7cd8..85cc0011d36 100644 --- a/assets/wix/Product.wxs +++ b/assets/wix/Product.wxs @@ -87,7 +87,7 @@ + Value=""[VersionFolder]pwsh.exe" -NoProfile -ExecutionPolicy Bypass -File "[VersionFolder]RegisterMicrosoftUpdate.ps1"" /> + + + @@ -4162,6 +4165,7 @@ + diff --git a/src/powershell-win-core/powershell-win-core.csproj b/src/powershell-win-core/powershell-win-core.csproj index 16f625827d4..9879e8485b4 100644 --- a/src/powershell-win-core/powershell-win-core.csproj +++ b/src/powershell-win-core/powershell-win-core.csproj @@ -29,7 +29,7 @@ PreserveNewest PreserveNewest - + PreserveNewest PreserveNewest From 158d3a64e9c6edabb77070074686b8a75027a8a5 Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Thu, 18 Aug 2022 11:12:58 -0700 Subject: [PATCH 022/779] Make sure `Security.types.ps1xml` gets signed in release build (#17916) --- tools/releaseBuild/azureDevOps/templates/windows-packaging.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/tools/releaseBuild/azureDevOps/templates/windows-packaging.yml b/tools/releaseBuild/azureDevOps/templates/windows-packaging.yml index 7cd0f5e33a4..cb5b7ea8e7b 100644 --- a/tools/releaseBuild/azureDevOps/templates/windows-packaging.yml +++ b/tools/releaseBuild/azureDevOps/templates/windows-packaging.yml @@ -104,6 +104,7 @@ jobs: "$($fullSymbolsFolder)\Modules\Microsoft.PowerShell.Host\Microsoft.PowerShell.Host.psd1" = "Modules\Microsoft.PowerShell.Host" "$($fullSymbolsFolder)\Modules\Microsoft.PowerShell.Management\Microsoft.PowerShell.Management.psd1" = "Modules\Microsoft.PowerShell.Management" "$($fullSymbolsFolder)\Modules\Microsoft.PowerShell.Security\Microsoft.PowerShell.Security.psd1" = "Modules\Microsoft.PowerShell.Security" + "$($fullSymbolsFolder)\Modules\Microsoft.PowerShell.Security\Security.types.ps1xml" = "Modules\Microsoft.PowerShell.Security" "$($fullSymbolsFolder)\Modules\Microsoft.PowerShell.Utility\Microsoft.PowerShell.Utility.psd1" = "Modules\Microsoft.PowerShell.Utility" "$($fullSymbolsFolder)\Modules\Microsoft.WSMan.Management\Microsoft.WSMan.Management.psd1" = "Modules\Microsoft.WSMan.Management" "$($fullSymbolsFolder)\Modules\Microsoft.WSMan.Management\WSMan.format.ps1xml" = "Modules\Microsoft.WSMan.Management" From 0337763a922cfffaae660c30b3a76997a1e3c974 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Mon, 22 Aug 2022 11:19:02 -0700 Subject: [PATCH 023/779] Limit searching of `charset` attribute in `meta` tag for HTML to first 1024 characters in webcmdlets (#17813) --- .../commands/utility/WebCmdlet/StreamHelper.cs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs index 43b42066cfa..ec616c72335 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs @@ -431,8 +431,10 @@ internal static string DecodeStream(Stream stream, ref Encoding encoding) { do { - // check for a charset attribute on the meta element to override the default. - Match match = s_metaexp.Match(content); + // check for a charset attribute on the meta element to override the default + // we only look within the first 1k characters as the meta tag is in the head + // tag which is at the start of the document + Match match = s_metaexp.Match(content.Substring(0, Math.Min(content.Length, 1024))); if (match.Success) { Encoding localEncoding = null; From eeaeb83119f9a61004e0b06c61608509153579ed Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 22 Aug 2022 11:33:25 -0700 Subject: [PATCH 024/779] Bump Microsoft.CodeAnalysis.NetAnalyzers (#17945) --- Analyzers.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Analyzers.props b/Analyzers.props index 8360903606e..7531593bdff 100644 --- a/Analyzers.props +++ b/Analyzers.props @@ -1,7 +1,7 @@ - + From 27cc09e1b2686c9e3a12779c97862d455c4eb452 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Mon, 22 Aug 2022 11:34:00 -0700 Subject: [PATCH 025/779] Update to the latest NOTICES file (#17934) --- ThirdPartyNotices.txt | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/ThirdPartyNotices.txt b/ThirdPartyNotices.txt index cf58fe4e9c8..b2e206b7783 100644 --- a/ThirdPartyNotices.txt +++ b/ThirdPartyNotices.txt @@ -141,10 +141,9 @@ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND --------------------------------------------------------- -Microsoft.ApplicationInsights 2.20.0 - MIT +Microsoft.ApplicationInsights 2.21.0 - MIT -(c) Microsoft Corporation. MIT License From a15bfcb5011816eff4f8e38ca3f41697f04ce752 Mon Sep 17 00:00:00 2001 From: Frode Flaten <3436158+fflaten@users.noreply.github.com> Date: Mon, 22 Aug 2022 21:11:17 +0200 Subject: [PATCH 026/779] Throw when too many parameter sets are defined (#17881) --- .../engine/MergedCommandParameterMetadata.cs | 9 ++++++++- .../Language/Scripting/ParameterBinding.Tests.ps1 | 13 +++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/src/System.Management.Automation/engine/MergedCommandParameterMetadata.cs b/src/System.Management.Automation/engine/MergedCommandParameterMetadata.cs index f2d20c68ec9..d2b972a118d 100644 --- a/src/System.Management.Automation/engine/MergedCommandParameterMetadata.cs +++ b/src/System.Management.Automation/engine/MergedCommandParameterMetadata.cs @@ -163,6 +163,13 @@ internal Collection AddMetadataForBinder( ///
private uint _nextAvailableParameterSetIndex; + /// + /// The maximum number of parameter sets allowed. Limit is set by the use + /// of a uint bitmask to store which parameter sets a parameter is included in. + /// See . + /// + private const uint MaxParameterSetCount = 32; + /// /// Gets the number of parameter sets that were declared for the command. /// @@ -228,7 +235,7 @@ private int AddParameterSetToMap(string parameterSetName) // A parameter set name should only be added once if (index == -1) { - if (_nextAvailableParameterSetIndex == uint.MaxValue) + if (_nextAvailableParameterSetIndex >= MaxParameterSetCount) { // Don't let the parameter set index overflow ParsingMetadataException parsingException = diff --git a/test/powershell/Language/Scripting/ParameterBinding.Tests.ps1 b/test/powershell/Language/Scripting/ParameterBinding.Tests.ps1 index 95d62071ad1..8177adab219 100644 --- a/test/powershell/Language/Scripting/ParameterBinding.Tests.ps1 +++ b/test/powershell/Language/Scripting/ParameterBinding.Tests.ps1 @@ -170,6 +170,19 @@ Describe "Tests for parameter binding" -Tags "CI" { ( get-foo -b b a c d ) -join ',' | Should -BeExactly 'a,c,d' } + It 'Too many parameter sets defined' { + $scriptblock = { + param($numSets=1) + $parameters = (1..($numSets) | ForEach-Object { "[Parameter(parametersetname='set$_')]`$a$_" }) -join ', ' + $body = "param($parameters) 'working'" + $sb = [scriptblock]::Create($body) + & $sb -a1 123 + } + + & $scriptblock -numSets 32 | Should -Be 'working' + { & $scriptblock -numSets 33 } | Should -Throw -ErrorId 'ParsingTooManyParameterSets' + } + It 'Default parameter set with value from remaining arguments case 1' { function get-foo { From 1c5e14cf0f1ae41f1194f184bf7dd61d0bc5feaf Mon Sep 17 00:00:00 2001 From: MartinGC94 <42123497+MartinGC94@users.noreply.github.com> Date: Mon, 22 Aug 2022 22:38:21 +0200 Subject: [PATCH 027/779] Fix member completion in attribute argument (#17902) --- .../engine/CommandCompletion/CompletionAnalysis.cs | 2 +- .../Host/TabCompletion/TabCompletion.Tests.ps1 | 9 +++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs index 53ca1f46f3a..d623a10af64 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs @@ -1972,7 +1972,7 @@ private static List GetResultForIdentifier(CompletionContext c } } } - if (completionContext.TokenAtCursor.TokenFlags == TokenFlags.MemberName) + if (completionContext.TokenAtCursor.TokenFlags == TokenFlags.MemberName && (lastAst is NamedAttributeArgumentAst || lastAst.Parent is NamedAttributeArgumentAst)) { result = GetResultForAttributeArgument(completionContext, ref replacementIndex, ref replacementLength); if (result is not null) diff --git a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 index 4ff31245a31..6471b1bf0ac 100644 --- a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 +++ b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 @@ -1458,6 +1458,7 @@ ConstructorTestClass(int i, bool b) $entry = $res.CompletionMatches | Where-Object CompletionText -EQ "Position" $entry.CompletionText | Should -BeExactly "Position" } + It "Test Attribute member completion multiple members" { $inputStr = "function bar { [parameter(Position,]param() }" $res = TabExpansion2 -inputScript $inputStr -cursorColumn ($inputStr.IndexOf(',') + 1) @@ -1466,6 +1467,14 @@ ConstructorTestClass(int i, bool b) $entry.CompletionText | Should -BeExactly "Mandatory" } + It "Should complete member in attribute argument value" { + $inputStr = '[ValidateRange(1,[int]::Maxva^)]$a' + $CursorIndex = $inputStr.IndexOf('^') + $res = TabExpansion2 -cursorColumn $CursorIndex -inputScript $inputStr.Remove($CursorIndex, 1) + $res.CompletionMatches | Should -HaveCount 1 + $res.CompletionMatches[0].CompletionText | Should -BeExactly "MaxValue" + } + It "Test Attribute scriptblock completion" { $inputStr = '[ValidateScript({Get-Child})]$Test=ls' $res = TabExpansion2 -inputScript $inputStr -cursorColumn ($inputStr.IndexOf('}')) From 2bbb4a6650cb76db1545d633883c2d1e76571935 Mon Sep 17 00:00:00 2001 From: Sergey Vasin Date: Tue, 23 Aug 2022 00:41:04 +0300 Subject: [PATCH 028/779] Replace the CIM class used for `-Amended` parameter test (#17884) --- test/powershell/Modules/CimCmdlets/Get-CimClass.Tests.ps1 | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/powershell/Modules/CimCmdlets/Get-CimClass.Tests.ps1 b/test/powershell/Modules/CimCmdlets/Get-CimClass.Tests.ps1 index 71c252f761b..219cf404d76 100644 --- a/test/powershell/Modules/CimCmdlets/Get-CimClass.Tests.ps1 +++ b/test/powershell/Modules/CimCmdlets/Get-CimClass.Tests.ps1 @@ -29,7 +29,7 @@ Describe 'Get-CimClass' -Tags @("Feature") { } It 'can retrieve class amended qualifiers' -Pending:(-not $IsWindows) { - $a = Get-CimClass -Class 'Win32_PrinterConfiguration' -Amended - $a.CimClassProperties['Color'].Qualifiers.Item('Values').Value.Count | Should -Be 2 + $a = Get-CimClass -Class 'Win32_LogicalDisk' -Amended + $a.CimClassProperties['DriveType'].Qualifiers.Item('Values').Value.Count | Should -Be 7 } } From 99c757ff3ea40d0a4310582f0ec0828f6564e6db Mon Sep 17 00:00:00 2001 From: MartinGC94 <42123497+MartinGC94@users.noreply.github.com> Date: Tue, 23 Aug 2022 00:17:55 +0200 Subject: [PATCH 029/779] Fix positional argument completion (#17796) --- .../CommandCompletion/CompletionCompleters.cs | 47 ++++++++++++------- .../TabCompletion/TabCompletion.Tests.ps1 | 21 +++++++++ 2 files changed, 52 insertions(+), 16 deletions(-) diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs index 1bf0919cf97..59e261e6139 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs @@ -1586,13 +1586,20 @@ private static void CompletePositionalArgument( (defaultParameterSetFlag & validParameterSetFlags) != 0; MergedCompiledCommandParameter positionalParam = null; + MergedCompiledCommandParameter bestMatchParam = null; + ParameterSetSpecificMetadata bestMatchSet = null; + + // Finds the parameter with the position closest to the specified position foreach (MergedCompiledCommandParameter param in parameters) { bool isInParameterSet = (param.Parameter.ParameterSetFlags & validParameterSetFlags) != 0 || param.Parameter.IsInAllSets; if (!isInParameterSet) + { continue; + } var parameterSetDataCollection = param.Parameter.GetMatchingParameterSetData(validParameterSetFlags); + foreach (ParameterSetSpecificMetadata parameterSetData in parameterSetDataCollection) { // in the first pass, we skip the remaining argument ones @@ -1604,35 +1611,43 @@ private static void CompletePositionalArgument( // Check the position int positionInParameterSet = parameterSetData.Position; - if (positionInParameterSet == int.MinValue || positionInParameterSet != position) + if (positionInParameterSet < position) { - // The parameter is not positional, or its position is not what we want + // The parameter is not positional (position == int.MinValue), or its position is lower than what we want. continue; } - if (isDefaultParameterSetValid) + if (bestMatchSet is null || bestMatchSet.Position > positionInParameterSet) { - if (parameterSetData.ParameterSetFlag == defaultParameterSetFlag) + bestMatchParam = param; + bestMatchSet = parameterSetData; + if (positionInParameterSet == position) { - ProcessParameter(commandName, commandAst, context, result, param, boundArguments); - isProcessedAsPositional = result.Count > 0; break; } - else - { - positionalParam ??= param; - } + } + } + } + + if (bestMatchParam is not null) + { + if (isDefaultParameterSetValid) + { + if (bestMatchSet.ParameterSetFlag == defaultParameterSetFlag) + { + ProcessParameter(commandName, commandAst, context, result, bestMatchParam, boundArguments); + isProcessedAsPositional = result.Count > 0; } else { - isProcessedAsPositional = true; - ProcessParameter(commandName, commandAst, context, result, param, boundArguments); - break; + positionalParam ??= bestMatchParam; } } - - if (isProcessedAsPositional) - break; + else + { + isProcessedAsPositional = true; + ProcessParameter(commandName, commandAst, context, result, bestMatchParam, boundArguments); + } } if (!isProcessedAsPositional && positionalParam != null) diff --git a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 index 6471b1bf0ac..9ab7d735eea 100644 --- a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 +++ b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 @@ -766,6 +766,27 @@ ConstructorTestClass(int i, bool b) $res.CompletionMatches.CompletionText | Should -Contain "-Path" } + it 'Should find the closest positional parameter match' { + $TestString = @' +function Verb-Noun +{ + Param + ( + [Parameter(Position = 0)] + [string] + $Param1, + [Parameter(Position = 1)] + [System.Management.Automation.ActionPreference] + $Param2 + ) +} +Verb-Noun -Param1 Hello ^ +'@ + $CursorIndex = $TestString.IndexOf('^') + $res = TabExpansion2 -inputScript $TestString.Remove($CursorIndex, 1) -cursorColumn $CursorIndex + $res.CompletionMatches[0].CompletionText | Should -Be "Break" + } + Context "Script name completion" { BeforeAll { Setup -f 'install-powershell.ps1' -Content "" From 4051e097965019fdd681a90eafd63e63aa5219f1 Mon Sep 17 00:00:00 2001 From: MartinGC94 <42123497+MartinGC94@users.noreply.github.com> Date: Tue, 23 Aug 2022 00:18:49 +0200 Subject: [PATCH 030/779] Add completion for values in comparisons when comparing Enums (#17654) --- .../CommandCompletion/CompletionAnalysis.cs | 50 ++++++++++++ .../CommandCompletion/CompletionCompleters.cs | 77 +++++++++++++++++++ .../TabCompletion/TabCompletion.Tests.ps1 | 26 +++++++ 3 files changed, 153 insertions(+) diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs index d623a10af64..24e6873966f 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs @@ -500,6 +500,15 @@ internal List GetResultHelper(CompletionContext completionCont return completions; } } + else if (lastAst.Parent is BinaryExpressionAst binaryExpression) + { + completionContext.WordToComplete = (tokenAtCursor as StringToken).Value; + result = CompletionCompleters.CompleteComparisonOperatorValues(completionContext, binaryExpression.Left); + if (result.Count > 0) + { + return result; + } + } else if (lastAst.Parent is IndexExpressionAst indexExpressionAst) { // Handles quoted string inside index expression like: $PSVersionTable[""] @@ -911,8 +920,27 @@ internal List GetResultHelper(CompletionContext completionCont { result = GetResultForAttributeArgument(completionContext, ref replacementIndex, ref replacementLength); } + break; + case TokenKind.Ieq: + case TokenKind.Ceq: + case TokenKind.Ine: + case TokenKind.Cne: + case TokenKind.Ilike: + case TokenKind.Clike: + case TokenKind.Inotlike: + case TokenKind.Cnotlike: + case TokenKind.Imatch: + case TokenKind.Cmatch: + case TokenKind.Inotmatch: + case TokenKind.Cnotmatch: + if (lastAst is BinaryExpressionAst binaryExpression) + { + completionContext.WordToComplete = string.Empty; + result = CompletionCompleters.CompleteComparisonOperatorValues(completionContext, binaryExpression.Left); + } break; + case TokenKind.LBracket: if (lastAst.Parent is IndexExpressionAst indexExpression) { @@ -921,6 +949,7 @@ internal List GetResultHelper(CompletionContext completionCont result = CompletionCompleters.CompleteIndexExpression(completionContext, indexExpression.Target); } break; + default: break; } @@ -991,6 +1020,26 @@ internal List GetResultHelper(CompletionContext completionCont return result; } break; + + case TokenKind.Ieq: + case TokenKind.Ceq: + case TokenKind.Ine: + case TokenKind.Cne: + case TokenKind.Ilike: + case TokenKind.Clike: + case TokenKind.Inotlike: + case TokenKind.Cnotlike: + case TokenKind.Imatch: + case TokenKind.Cmatch: + case TokenKind.Inotmatch: + case TokenKind.Cnotmatch: + if (lastAst is BinaryExpressionAst binaryExpression) + { + completionContext.WordToComplete = string.Empty; + result = CompletionCompleters.CompleteComparisonOperatorValues(completionContext, binaryExpression.Left); + } + break; + case TokenKind.LBracket: if (lastAst.Parent is IndexExpressionAst indexExpression) { @@ -999,6 +1048,7 @@ internal List GetResultHelper(CompletionContext completionCont result = CompletionCompleters.CompleteIndexExpression(completionContext, indexExpression.Target); } break; + default: break; } diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs index 59e261e6139..3fbbf928ca8 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs @@ -2317,6 +2317,11 @@ private static void NativeCommandArgumentCompletion( { NativeCompletionMemberName(context, result, commandAst, boundArguments?[parameterName]); } + else if (parameterName.Equals("Value", StringComparison.OrdinalIgnoreCase) + && boundArguments?["Property"] is AstPair pair && pair.Argument is StringConstantExpressionAst stringAst) + { + NativeCompletionMemberValue(context, result, commandAst, stringAst.Value); + } break; } @@ -3994,6 +3999,38 @@ private static void NativeCompletionMemberName(CompletionContext context, List result, CommandAst commandAst, string propertyName) + { + string wordToComplete = context.WordToComplete.Trim('"', '\''); + IEnumerable prevTypes = GetInferenceTypes(context, commandAst); + if (prevTypes is not null) + { + foreach (var type in prevTypes) + { + if (type.Type is null) + { + continue; + } + + PropertyInfo property = type.Type.GetProperty(propertyName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance); + if (property is not null && property.PropertyType.IsEnum) + { + foreach (var value in property.PropertyType.GetEnumNames()) + { + if (value.StartsWith(wordToComplete, StringComparison.OrdinalIgnoreCase)) + { + result.Add(new CompletionResult(value, value, CompletionResultType.ParameterValue, value)); + } + } + + break; + } + } + } + + result.Add(CompletionResult.Null); + } + /// /// Returns all string values bound to a parameter except the one the cursor is currently at. /// @@ -5913,6 +5950,46 @@ internal static List CompleteMember(CompletionContext context, return results; } + internal static List CompleteComparisonOperatorValues(CompletionContext context, ExpressionAst operatorLeftValue) + { + var result = new List(); + var resolvedTypes = new List(); + + if (SafeExprEvaluator.TrySafeEval(operatorLeftValue, context.ExecutionContext, out object value) && value is not null) + { + resolvedTypes.Add(value.GetType()); + } + else + { + var inferredTypes = AstTypeInference.InferTypeOf(operatorLeftValue, context.TypeInferenceContext, TypeInferenceRuntimePermissions.AllowSafeEval); + foreach (var type in inferredTypes) + { + if (type.Type is not null) + { + resolvedTypes.Add(type.Type); + } + } + } + + foreach (var type in resolvedTypes) + { + if (type.IsEnum) + { + foreach (var name in type.GetEnumNames()) + { + if (name.StartsWith(context.WordToComplete, StringComparison.OrdinalIgnoreCase)) + { + result.Add(new CompletionResult($"'{name}'", name, CompletionResultType.ParameterValue, name)); + } + } + + break; + } + } + + return result; + } + /// /// Complete members against extension methods 'Where' and 'ForEach' /// diff --git a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 index 9ab7d735eea..725b47138c0 100644 --- a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 +++ b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 @@ -558,6 +558,32 @@ ConstructorTestClass(int i, bool b) $res.CompletionMatches[0].CompletionText | Should -BeExactly Cat } + it 'Should complete "Value" parameter value in "Where-Object" for Enum property with no input' { + $res = TabExpansion2 -inputScript 'Get-Command | where-Object CommandType -eq ' + $res.CompletionMatches[0].CompletionText | Should -BeExactly Alias + } + + it 'Should complete "Value" parameter value in "Where-Object" for Enum property with partial input' { + $res = TabExpansion2 -inputScript 'Get-Command | where-Object CommandType -ne Ali' + $res.CompletionMatches[0].CompletionText | Should -BeExactly Alias + } + + it 'Should complete the right hand side of a comparison operator when left is an Enum with no input' { + $res = TabExpansion2 -inputScript 'Get-Command | Where-Object -FilterScript {$_.CommandType -like ' + $res.CompletionMatches[0].CompletionText | Should -BeExactly "'Alias'" + } + + it 'Should complete the right hand side of a comparison operator when left is an Enum with partial input' { + $TempVar = Get-Command + $res = TabExpansion2 -inputScript '$tempVar[0].CommandType -notlike "Ali"' + $res.CompletionMatches[0].CompletionText | Should -BeExactly "'Alias'" + } + + it 'Should complete the right hand side of a comparison operator when left is an Enum when cursor is on a newline' { + $res = TabExpansion2 -inputScript "Get-Command | Where-Object -FilterScript {`$_.CommandType -like`n" + $res.CompletionMatches[0].CompletionText | Should -BeExactly "'Alias'" + } + it 'Should complete provider dynamic parameters with quoted path' { $Script = if ($IsWindows) { From fdf3c9a31ac11a0afcadc5096c5706827e0ccff1 Mon Sep 17 00:00:00 2001 From: Abin <3484074+AAATechGuy@users.noreply.github.com> Date: Mon, 22 Aug 2022 22:30:47 -0700 Subject: [PATCH 031/779] Remove 1s minimum delay in Invoke-WebRequest for small files, and prevent file-download-error suppression. (#17896) --- .../commands/utility/WebCmdlet/StreamHelper.cs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs index ec616c72335..d298f427960 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs @@ -289,16 +289,14 @@ internal static void WriteToStream(Stream input, Stream output, PSCmdlet cmdlet, ActivityId, WebCmdletStrings.WriteRequestProgressActivity, WebCmdletStrings.WriteRequestProgressStatus); + try { - do + while (!copyTask.Wait(1000, cancellationToken)) { record.StatusDescription = StringUtil.Format(WebCmdletStrings.WriteRequestProgressStatus, output.Position); cmdlet.WriteProgress(record); - - Task.Delay(1000).Wait(cancellationToken); } - while (!copyTask.IsCompleted && !cancellationToken.IsCancellationRequested); if (copyTask.IsCompleted) { From a7559e0987807e6cea87587535f455c1685368c9 Mon Sep 17 00:00:00 2001 From: MartinGC94 <42123497+MartinGC94@users.noreply.github.com> Date: Tue, 23 Aug 2022 08:17:33 +0200 Subject: [PATCH 032/779] Add output type attributes for Get-WinEvent (#17948) --- .../GetEventCommand.cs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs index 10044e29466..587a63683ab 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs @@ -23,6 +23,9 @@ namespace Microsoft.PowerShell.Commands /// /// Class that implements the Get-WinEvent cmdlet. /// + [OutputType(typeof(EventRecord), ParameterSetName = new string[] { "GetLogSet", "GetProviderSet", "FileSet", "HashQuerySet", "XmlQuerySet" })] + [OutputType(typeof(ProviderMetadata), ParameterSetName = new string[] { "ListProviderSet" })] + [OutputType(typeof(EventLogConfiguration), ParameterSetName = new string[] { "ListLogSet" })] [Cmdlet(VerbsCommon.Get, "WinEvent", DefaultParameterSetName = "GetLogSet", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096581")] public sealed class GetWinEventCommand : PSCmdlet { From da7fa3f771a69a75a49d9f18baa35457ec361a90 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Tue, 23 Aug 2022 10:47:01 -0700 Subject: [PATCH 033/779] Make `pwsh` server modes implicitly not show banner (#17921) --- .../host/msh/CommandLineParameterParser.cs | 4 ++++ test/xUnit/csharp/test_CommandLineParser.cs | 8 ++++---- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs index 0b54bcff24a..a946051995f 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs @@ -914,21 +914,25 @@ private void ParseHelper(string[] args) else if (MatchSwitch(switchKey, "socketservermode", "so")) { _socketServerMode = true; + _showBanner = false; ParametersUsed |= ParameterBitmap.SocketServerMode; } else if (MatchSwitch(switchKey, "servermode", "s")) { _serverMode = true; + _showBanner = false; ParametersUsed |= ParameterBitmap.ServerMode; } else if (MatchSwitch(switchKey, "namedpipeservermode", "nam")) { _namedPipeServerMode = true; + _showBanner = false; ParametersUsed |= ParameterBitmap.NamedPipeServerMode; } else if (MatchSwitch(switchKey, "sshservermode", "sshs")) { _sshServerMode = true; + _showBanner = false; ParametersUsed |= ParameterBitmap.SSHServerMode; } else if (MatchSwitch(switchKey, "noprofileloadtime", "noprofileloadtime")) diff --git a/test/xUnit/csharp/test_CommandLineParser.cs b/test/xUnit/csharp/test_CommandLineParser.cs index 70621dfdf0f..966834fd2b3 100644 --- a/test/xUnit/csharp/test_CommandLineParser.cs +++ b/test/xUnit/csharp/test_CommandLineParser.cs @@ -331,7 +331,7 @@ public static void TestParameter_SocketServerMode(params string[] commandLine) Assert.False(cpp.AbortStartup); Assert.True(cpp.NoExit); Assert.False(cpp.ShowShortHelp); - Assert.True(cpp.ShowBanner); + Assert.False(cpp.ShowBanner); Assert.True(cpp.SocketServerMode); Assert.Null(cpp.ErrorMessage); } @@ -348,7 +348,7 @@ public static void TestParameter_ServerMode(params string[] commandLine) Assert.False(cpp.AbortStartup); Assert.True(cpp.NoExit); Assert.False(cpp.ShowShortHelp); - Assert.True(cpp.ShowBanner); + Assert.False(cpp.ShowBanner); Assert.True(cpp.ServerMode); Assert.Null(cpp.ErrorMessage); } @@ -365,7 +365,7 @@ public static void TestParameter_NamedPipeServerMode(params string[] commandLine Assert.False(cpp.AbortStartup); Assert.True(cpp.NoExit); Assert.False(cpp.ShowShortHelp); - Assert.True(cpp.ShowBanner); + Assert.False(cpp.ShowBanner); Assert.True(cpp.NamedPipeServerMode); Assert.Null(cpp.ErrorMessage); } @@ -382,7 +382,7 @@ public static void TestParameter_SSHServerMode(params string[] commandLine) Assert.False(cpp.AbortStartup); Assert.True(cpp.NoExit); Assert.False(cpp.ShowShortHelp); - Assert.True(cpp.ShowBanner); + Assert.False(cpp.ShowBanner); Assert.True(cpp.SSHServerMode); Assert.Null(cpp.ErrorMessage); } From d02c59addc24e13da3b8ee5e1a8e7aa27e00c745 Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Tue, 23 Aug 2022 10:48:04 -0700 Subject: [PATCH 034/779] Update help content about the PowerShell flag `-NonInteractive` (#17952) --- .../resources/ManagedEntranceStrings.resx | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/ManagedEntranceStrings.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/ManagedEntranceStrings.resx index 778584742b6..845fa0cb047 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/resources/ManagedEntranceStrings.resx +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/ManagedEntranceStrings.resx @@ -393,9 +393,10 @@ All parameters are case-insensitive. -NonInteractive | -noni - Does not present an interactive prompt to the user. Any attempts to use - interactive features, like Read-Host or confirmation prompts, result in - statement-terminating errors. + This switch is used to create sessions that shouldn't require user input. + This is useful for scripts that run in scheduled tasks or CI/CD pipelines. + Any attempts to use interactive features, like 'Read-Host' or confirmation + prompts, result in statement terminating errors rather than hanging. -NoProfile | -nop From 543f5209c0372b5ff0ce65fdf74aefc6c1f5ba84 Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Wed, 24 Aug 2022 11:11:18 -0700 Subject: [PATCH 035/779] Support mapping foreground/background `ConsoleColor` values to VT escape sequences (#17938) --- .../commands/utility/MatchString.cs | 4 +- .../PowerShellCore_format_ps1xml.cs | 28 +--- .../FormatAndOutput/common/PSStyle.cs | 130 ++++++++++++++++++ .../utils/VTUtils.cs | 2 + 4 files changed, 139 insertions(+), 25 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs index b6b8cc9bfb6..b9964d92bcb 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs @@ -315,8 +315,8 @@ public string ToEmphasizedString(string directory) /// The matched line with matched text inverted. private string EmphasizeLine() { - string invertColorsVT100 = VTUtility.GetEscapeSequence(VTUtility.VT.Inverse); - string resetVT100 = VTUtility.GetEscapeSequence(VTUtility.VT.Reset); + string invertColorsVT100 = PSStyle.Instance.Reverse; + string resetVT100 = PSStyle.Instance.Reset; char[] chars = new char[(_matchIndexes.Count * (invertColorsVT100.Length + resetVT100.Length)) + Line.Length]; int lineIndex = 0; diff --git a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs index f4b9d03489c..4ab1fa8dd76 100644 --- a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs +++ b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs @@ -816,9 +816,7 @@ private static IEnumerable ViewsOf_System_Management_Autom $errorColor = $psstyle.Formatting.Error } - $resetColor = [System.Management.Automation.VTUtility]::GetEscapeSequence( - [System.Management.Automation.VTUtility+VT]::Reset - ) + $resetColor = $PSStyle.Reset } function Get-VT100Color([ConsoleColor] $color) { @@ -826,7 +824,7 @@ private static IEnumerable ViewsOf_System_Management_Autom return '' } - return [System.Management.Automation.VTUtility]::GetEscapeSequence($color) + return [System.Management.Automation.PSStyle]::MapForegroundColorToEscapeSequence($color) } function Show-ErrorRecord($obj, [int]$indent = 0, [int]$depth = 1) { @@ -1070,9 +1068,7 @@ function Get-ConciseViewPositionMessage { $resetColor = '' if ($Host.UI.SupportsVirtualTerminal -and ([string]::IsNullOrEmpty($env:__SuppressAnsiEscapeSequences))) { - $resetColor = [System.Management.Automation.VTUtility]::GetEscapeSequence( - [System.Management.Automation.VTUtility+VT]::Reset - ) + $resetColor = $PSStyle.Reset } function Get-VT100Color([ConsoleColor] $color) { @@ -1080,21 +1076,7 @@ function Get-ConciseViewPositionMessage { return '' } - return [System.Management.Automation.VTUtility]::GetEscapeSequence($color) - } - - # return length of string sans VT100 codes - function Get-RawStringLength($string) { - $vtCodes = ""`e[0m"", ""`e[2;30m"", ""`e[2;31m"", ""`e[2;32m"", ""`e[2;33m"", ""`e[2;34m"", - ""`e[2;35m"", ""`e[2;36m"", ""`e[2;37m"", ""`e[1;30m"", ""`e[1;31m"", ""`e[1;32m"", - ""`e[1;33m"", ""`e[1;34m"", ""`e[1;35m"", ""`e[1;36m"", ""`e[1;37m"" - - $newString = $string - foreach ($vtCode in $vtCodes) { - $newString = $newString.Replace($vtCode, '') - } - - return $newString.Length + return [System.Management.Automation.PSStyle]::MapForegroundColorToEscapeSequence($color) } # returns a string cut to last whitespace @@ -1217,7 +1199,7 @@ function Get-ConciseViewPositionMessage { # if rendering line information, break up the message if it's wider than the console if ($myinv -and $myinv.ScriptName -or $err.CategoryInfo.Category -eq 'ParserError') { - $prefixLength = Get-RawStringLength -string $prefix + $prefixLength = [System.Management.Automation.Internal.StringDecorated]::new($prefix).ContentLength $prefixVtLength = $prefix.Length - $prefixLength # replace newlines in message so it lines up correct diff --git a/src/System.Management.Automation/FormatAndOutput/common/PSStyle.cs b/src/System.Management.Automation/FormatAndOutput/common/PSStyle.cs index 3a5dcb36f0b..a217063410a 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/PSStyle.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/PSStyle.cs @@ -155,6 +155,16 @@ public string FromRgb(int rgb) return FromRgb(red, green, blue); } + + /// + /// Return the VT escape sequence for a foreground color. + /// + /// The foreground color to be mapped from. + /// The VT escape sequence representing the foreground color. + public string FromConsoleColor(ConsoleColor color) + { + return MapForegroundColorToEscapeSequence(color); + } } /// @@ -270,6 +280,16 @@ public string FromRgb(int rgb) return FromRgb(red, green, blue); } + + /// + /// Return the VT escape sequence for a background color. + /// + /// The background color to be mapped from. + /// The VT escape sequence representing the background color. + public string FromConsoleColor(ConsoleColor color) + { + return MapBackgroundColorToEscapeSequence(color); + } } /// @@ -722,6 +742,116 @@ public static PSStyle Instance return s_psstyle; } } + + /// + /// The map of background console colors to escape sequences. + /// + private static readonly string[] BackgroundColorMap = + { + "\x1b[40m", // Black + "\x1b[44m", // DarkBlue + "\x1b[42m", // DarkGreen + "\x1b[46m", // DarkCyan + "\x1b[41m", // DarkRed + "\x1b[45m", // DarkMagenta + "\x1b[43m", // DarkYellow + "\x1b[47m", // Gray + "\x1b[100m", // DarkGray + "\x1b[104m", // Blue + "\x1b[102m", // Green + "\x1b[106m", // Cyan + "\x1b[101m", // Red + "\x1b[105m", // Magenta + "\x1b[103m", // Yellow + "\x1b[107m", // White + }; + + /// + /// The map of foreground console colors to escape sequences. + /// + private static readonly string[] ForegroundColorMap = + { + "\x1b[30m", // Black + "\x1b[34m", // DarkBlue + "\x1b[32m", // DarkGreen + "\x1b[36m", // DarkCyan + "\x1b[31m", // DarkRed + "\x1b[35m", // DarkMagenta + "\x1b[33m", // DarkYellow + "\x1b[37m", // Gray + "\x1b[90m", // DarkGray + "\x1b[94m", // Blue + "\x1b[92m", // Green + "\x1b[96m", // Cyan + "\x1b[91m", // Red + "\x1b[95m", // Magenta + "\x1b[93m", // Yellow + "\x1b[97m", // White + }; + + /// + /// Return the VT escape sequence for a ConsoleColor. + /// + /// The to be mapped from. + /// Whether or not it's a background color. + /// The VT escape sequence representing the color. + internal static string MapColorToEscapeSequence(ConsoleColor color, bool isBackground) + { + int index = (int)color; + if (index < 0 || index >= ForegroundColorMap.Length) + { + throw new ArgumentOutOfRangeException(paramName: nameof(color)); + } + + return (isBackground ? BackgroundColorMap : ForegroundColorMap)[index]; + } + + /// + /// Return the VT escape sequence for a foreground color. + /// + /// The foreground color to be mapped from. + /// The VT escape sequence representing the foreground color. + public static string MapForegroundColorToEscapeSequence(ConsoleColor foregroundColor) + => MapColorToEscapeSequence(foregroundColor, isBackground: false); + + /// + /// Return the VT escape sequence for a background color. + /// + /// The background color to be mapped from. + /// The VT escape sequence representing the background color. + public static string MapBackgroundColorToEscapeSequence(ConsoleColor backgroundColor) + => MapColorToEscapeSequence(backgroundColor, isBackground: true); + + /// + /// Return the VT escape sequence for a pair of foreground and background colors. + /// + /// The foreground color of the color pair. + /// The background color of the color pair. + /// The VT escape sequence representing the foreground and background color pair. + public static string MapColorPairToEscapeSequence(ConsoleColor foregroundColor, ConsoleColor backgroundColor) + { + int foreIndex = (int)foregroundColor; + int backIndex = (int)backgroundColor; + + if (foreIndex < 0 || foreIndex >= ForegroundColorMap.Length) + { + throw new ArgumentOutOfRangeException(paramName: nameof(foregroundColor)); + } + + if (backIndex < 0 || backIndex >= ForegroundColorMap.Length) + { + throw new ArgumentOutOfRangeException(paramName: nameof(backgroundColor)); + } + + string foreground = ForegroundColorMap[foreIndex]; + string background = BackgroundColorMap[backIndex]; + + return string.Concat( + foreground.AsSpan(start: 0, length: foreground.Length - 1), + ";".AsSpan(), + background.AsSpan(start: 2)); + } } + #endregion PSStyle } diff --git a/src/System.Management.Automation/utils/VTUtils.cs b/src/System.Management.Automation/utils/VTUtils.cs index c91ce24e19d..3a22256f057 100644 --- a/src/System.Management.Automation/utils/VTUtils.cs +++ b/src/System.Management.Automation/utils/VTUtils.cs @@ -1,6 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +using System; using System.Collections.Generic; namespace System.Management.Automation @@ -8,6 +9,7 @@ namespace System.Management.Automation /// /// Class to help with VT escape sequences. /// + [Obsolete("This class is deprecated. Use 'System.Management.Automation.PSStyle' instead.", error: true)] public sealed class VTUtility { /// From 0c63a549528ceb8eef68cef3a441a63401a7f291 Mon Sep 17 00:00:00 2001 From: Ikko Ashimine Date: Thu, 25 Aug 2022 16:54:35 +0900 Subject: [PATCH 036/779] Fix typo in PowerShell.Core.Instrumentation.man (#17963) --- .../PowerShell.Core.Instrumentation.man | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/PowerShell.Core.Instrumentation/PowerShell.Core.Instrumentation.man b/src/PowerShell.Core.Instrumentation/PowerShell.Core.Instrumentation.man index 5d4dd473f4b..ea8fcdc49c5 100644 --- a/src/PowerShell.Core.Instrumentation/PowerShell.Core.Instrumentation.man +++ b/src/PowerShell.Core.Instrumentation/PowerShell.Core.Instrumentation.man @@ -4723,7 +4723,7 @@ /> Date: Mon, 29 Aug 2022 08:41:34 -0700 Subject: [PATCH 037/779] Bump Microsoft.CodeAnalysis.NetAnalyzers (#17983) Bumps [Microsoft.CodeAnalysis.NetAnalyzers](https://github.com/dotnet/roslyn-analyzers) from 7.0.0-preview1.22419.4 to 7.0.0-preview1.22426.2. - [Release notes](https://github.com/dotnet/roslyn-analyzers/releases) - [Changelog](https://github.com/dotnet/roslyn-analyzers/blob/main/PostReleaseActivities.md) - [Commits](https://github.com/dotnet/roslyn-analyzers/commits) --- updated-dependencies: - dependency-name: Microsoft.CodeAnalysis.NetAnalyzers dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- Analyzers.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Analyzers.props b/Analyzers.props index 7531593bdff..8bad89cf71f 100644 --- a/Analyzers.props +++ b/Analyzers.props @@ -1,7 +1,7 @@ - + From 96d0a10e7f22da7657e38488680d01f9bd960cbc Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Mon, 29 Aug 2022 11:06:46 -0700 Subject: [PATCH 038/779] Remove unneeded use of `chmod 777` (#17974) * Update Pester.Commands.Cmdlets.GetCommand.Tests.ps1 * Update Export-Alias.Tests.ps1 * Update test/powershell/Modules/Microsoft.PowerShell.Utility/Export-Alias.Tests.ps1 * Update test/powershell/Modules/Microsoft.PowerShell.Core/Pester.Commands.Cmdlets.GetCommand.Tests.ps1 * Update test/powershell/Modules/Microsoft.PowerShell.Core/Pester.Commands.Cmdlets.GetCommand.Tests.ps1 --- .../Pester.Commands.Cmdlets.GetCommand.Tests.ps1 | 4 ++-- .../Microsoft.PowerShell.Utility/Export-Alias.Tests.ps1 | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/test/powershell/Modules/Microsoft.PowerShell.Core/Pester.Commands.Cmdlets.GetCommand.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Core/Pester.Commands.Cmdlets.GetCommand.Tests.ps1 index 8cbbd2a3390..6f4cf9aa778 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Core/Pester.Commands.Cmdlets.GetCommand.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Core/Pester.Commands.Cmdlets.GetCommand.Tests.ps1 @@ -10,8 +10,8 @@ Describe "Tests Get-Command with relative paths and wildcards" -Tag "CI" { #$null = New-Item -ItemType File -Path (Join-Path $TestDrive WildCardCommandA.exe) -ErrorAction Ignore #$null = New-Item -ItemType File -Path (Join-Path $TestDRive WildCardCommand[B].exe) -ErrorAction Ignore if ( $IsLinux -or $IsMacOS ) { - /bin/chmod 777 "$file1" - /bin/chmod 777 "$file2" + /bin/chmod a+rw "$file1" + /bin/chmod a+rw "$file2" } $commandInfo = Get-Command Get-Date -ShowCommandInfo } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Export-Alias.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Export-Alias.Tests.ps1 index e242ee77492..0b66b284ea5 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Export-Alias.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Export-Alias.Tests.ps1 @@ -120,7 +120,7 @@ Describe "Export-Alias DRT Unit Tests" -Tags "CI" { } else { - chmod 777 $fulltestpath + chmod a+rw $fulltestpath } } From 97ab6bd4fe91aaa6e02c794e494078c9f7c34881 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 09:33:09 -0700 Subject: [PATCH 039/779] Bump `Microsoft.CodeAnalysis.NetAnalyzers` (#17988) --- Analyzers.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Analyzers.props b/Analyzers.props index 8bad89cf71f..fc2c7adb53d 100644 --- a/Analyzers.props +++ b/Analyzers.props @@ -1,7 +1,7 @@ - + From 647f40bb4a543b8e7b7ba72e22f84ec7d7c9b238 Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Wed, 31 Aug 2022 09:36:14 -0700 Subject: [PATCH 040/779] Fix error formatting to use color defined in `$PSStyle.Formatting` (#17987) --- .../PowerShellCore_format_ps1xml.cs | 163 +++++++----------- .../engine/InitialSessionState.cs | 2 +- test/powershell/Host/ConsoleHost.Tests.ps1 | 5 +- 3 files changed, 71 insertions(+), 99 deletions(-) diff --git a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs index 4ab1fa8dd76..9b2f6596bd5 100644 --- a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs +++ b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs @@ -811,31 +811,18 @@ private static IEnumerable ViewsOf_System_Management_Autom $ellipsis = ""`u{2026}"" $resetColor = '' $errorColor = '' - if ($Host.UI.SupportsVirtualTerminal -and ([string]::IsNullOrEmpty($env:__SuppressAnsiEscapeSequences))) { - if ($null -ne $psstyle) { - $errorColor = $psstyle.Formatting.Error - } + $accentColor = '' + if ($Host.UI.SupportsVirtualTerminal -and ([string]::IsNullOrEmpty($env:__SuppressAnsiEscapeSequences))) { $resetColor = $PSStyle.Reset - } - - function Get-VT100Color([ConsoleColor] $color) { - if (!$Host.UI.SupportsVirtualTerminal -or !([string]::IsNullOrEmpty($env:__SuppressAnsiEscapeSequences))) { - return '' - } - - return [System.Management.Automation.PSStyle]::MapForegroundColorToEscapeSequence($color) + $errorColor = $psstyle.Formatting.Error + $accentColor = $PSStyle.Formatting.FormatAccent } function Show-ErrorRecord($obj, [int]$indent = 0, [int]$depth = 1) { $newline = [Environment]::Newline $output = [System.Text.StringBuilder]::new() $prefix = ' ' * $indent - $accentColor = '' - - if ($null -ne $Host.PrivateData) { - $accentColor = Get-VT100Color ($Host.PrivateData.FormatAccentColor ?? $Host.PrivateData.ErrorForegroundColor) - } $expandTypes = @( 'Microsoft.Rest.HttpRequestMessageWrapper' @@ -1064,20 +1051,17 @@ private static IEnumerable ViewsOf_System_Management_Autom Set-StrictMode -Off $newline = [Environment]::Newline - function Get-ConciseViewPositionMessage { - - $resetColor = '' - if ($Host.UI.SupportsVirtualTerminal -and ([string]::IsNullOrEmpty($env:__SuppressAnsiEscapeSequences))) { - $resetColor = $PSStyle.Reset - } + $resetColor = '' + $errorColor = '' + $accentColor = '' - function Get-VT100Color([ConsoleColor] $color) { - if (!$Host.UI.SupportsVirtualTerminal -or !([string]::IsNullOrEmpty($env:__SuppressAnsiEscapeSequences))) { - return '' - } + if ($Host.UI.SupportsVirtualTerminal -and ([string]::IsNullOrEmpty($env:__SuppressAnsiEscapeSequences))) { + $resetColor = $PSStyle.Reset + $errorColor = $PSStyle.Formatting.Error + $accentColor = $PSStyle.Formatting.ErrorAccent + } - return [System.Management.Automation.PSStyle]::MapForegroundColorToEscapeSequence($color) - } + function Get-ConciseViewPositionMessage { # returns a string cut to last whitespace function Get-TruncatedString($string, [int]$length) { @@ -1089,14 +1073,6 @@ function Get-ConciseViewPositionMessage { return ($string.Substring(0,$length) -split '\s',-2)[0] } - $errorColor = '' - $accentColor = '' - - if ($null -ne $Host.PrivateData) { - $errorColor = Get-VT100Color $Host.PrivateData.ErrorForegroundColor - $accentColor = Get-VT100Color ($Host.PrivateData.ErrorAccentColor ?? $errorColor) - } - $posmsg = '' $headerWhitespace = '' $offsetWhitespace = '' @@ -1278,82 +1254,77 @@ function Get-ConciseViewPositionMessage { $myinv = $err.InvocationInfo } - if ($ErrorView -ne 'ConciseView' -and $null -ne $host.PrivateData) { - if ($null -ne $host.PrivateData.ErrorForegroundColor) { - [Console]::ForegroundColor = $host.PrivateData.ErrorForegroundColor - } + if ($err.FullyQualifiedErrorId -eq 'NativeCommandErrorMessage' -or $err.FullyQualifiedErrorId -eq 'NativeCommandError') { + return ""${errorColor}$($err.Exception.Message)${resetcolor}"" + } - if ($null -ne $host.PrivateData.ErrorBackgroundColor) { - [Console]::BackgroundColor = $host.PrivateData.ErrorBackgroundColor - } + $myinv = $err.InvocationInfo + if ($ErrorView -eq 'DetailedView') { + $message = Get-Error | Out-String + return ""${errorColor}${message}${resetcolor}"" } - if ($err.FullyQualifiedErrorId -eq 'NativeCommandErrorMessage' -or $err.FullyQualifiedErrorId -eq 'NativeCommandError') { - $err.Exception.Message + if ($ErrorView -eq 'CategoryView') { + $message = $err.CategoryInfo.GetMessage() + return ""${errorColor}${message}${resetcolor}"" } - else - { - $myinv = $err.InvocationInfo - if ($ErrorView -eq 'DetailedView') { - return (Get-Error | Out-String) - } - elseif ($ErrorView -eq 'ConciseView') { - $posmsg = Get-ConciseViewPositionMessage - } - elseif ($myinv -and ($myinv.MyCommand -or ($err.CategoryInfo.Category -ne 'ParserError'))) { - $posmsg = $myinv.PositionMessage - } else { - $posmsg = '' - } - if ($posmsg -ne '') - { - $posmsg = $newline + $posmsg - } + $posmsg = '' + if ($ErrorView -eq 'ConciseView') { + $posmsg = Get-ConciseViewPositionMessage + } + elseif ($myinv -and ($myinv.MyCommand -or ($err.CategoryInfo.Category -ne 'ParserError'))) { + $posmsg = $myinv.PositionMessage + } - if ($err.PSMessageDetails) { - $posmsg = ' : ' + $err.PSMessageDetails + $posmsg - } + if ($posmsg -ne '') { + $posmsg = $newline + $posmsg + } - if ($ErrorView -eq 'ConciseView') { - return $posmsg + if ($err.PSMessageDetails) { + $posmsg = ' : ' + $err.PSMessageDetails + $posmsg + } + + if ($ErrorView -eq 'ConciseView') { + if ($err.PSMessageDetails) { + $posmsg = ""${errorColor}${posmsg}"" } + return $posmsg + } - $indent = 4 + $indent = 4 - $errorCategoryMsg = $err.ErrorCategory_Message + $errorCategoryMsg = $err.ErrorCategory_Message - if ($null -ne $errorCategoryMsg) - { - $indentString = '+ CategoryInfo : ' + $err.ErrorCategory_Message - } - else - { - $indentString = '+ CategoryInfo : ' + $err.CategoryInfo - } + if ($null -ne $errorCategoryMsg) + { + $indentString = '+ CategoryInfo : ' + $err.ErrorCategory_Message + } + else + { + $indentString = '+ CategoryInfo : ' + $err.CategoryInfo + } - $posmsg += $newline + $indentString + $posmsg += $newline + $indentString - $indentString = ""+ FullyQualifiedErrorId : "" + $err.FullyQualifiedErrorId - $posmsg += $newline + $indentString + $indentString = ""+ FullyQualifiedErrorId : "" + $err.FullyQualifiedErrorId + $posmsg += $newline + $indentString - $originInfo = $err.OriginInfo + $originInfo = $err.OriginInfo - if (($null -ne $originInfo) -and ($null -ne $originInfo.PSComputerName)) - { - $indentString = ""+ PSComputerName : "" + $originInfo.PSComputerName - $posmsg += $newline + $indentString - } + if (($null -ne $originInfo) -and ($null -ne $originInfo.PSComputerName)) + { + $indentString = ""+ PSComputerName : "" + $originInfo.PSComputerName + $posmsg += $newline + $indentString + } - if ($ErrorView -eq 'CategoryView') { - $err.CategoryInfo.GetMessage() - } - elseif (! $err.ErrorDetails -or ! $err.ErrorDetails.Message) { - $err.Exception.Message + $posmsg - } else { - $err.ErrorDetails.Message + $posmsg - } + $finalMsg = if ($err.ErrorDetails.Message) { + $err.ErrorDetails.Message + $posmsg + } else { + $err.Exception.Message + $posmsg } + + ""${errorColor}${finalMsg}${resetcolor}"" ") .EndEntry() .EndControl()); diff --git a/src/System.Management.Automation/engine/InitialSessionState.cs b/src/System.Management.Automation/engine/InitialSessionState.cs index 7a6d09cba67..6bc7e9e0021 100644 --- a/src/System.Management.Automation/engine/InitialSessionState.cs +++ b/src/System.Management.Automation/engine/InitialSessionState.cs @@ -4350,7 +4350,7 @@ static InitialSessionState() SpecialVariables.PSStyle, PSStyle.Instance, RunspaceInit.PSStyleDescription, - ScopedItemOptions.None), + ScopedItemOptions.Constant), // Variable which controls the encoding for piping data to a NativeCommand new SessionStateVariableEntry( diff --git a/test/powershell/Host/ConsoleHost.Tests.ps1 b/test/powershell/Host/ConsoleHost.Tests.ps1 index ff2d537d836..ccec3d7455f 100644 --- a/test/powershell/Host/ConsoleHost.Tests.ps1 +++ b/test/powershell/Host/ConsoleHost.Tests.ps1 @@ -420,14 +420,15 @@ export $envVarName='$guid' It "errors are in text if error is redirected, encoded command, non-interactive, and outputformat specified" { $p = [Diagnostics.Process]::new() $p.StartInfo.FileName = "pwsh" - $encoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes('$ErrorView="NormalView";throw "boom"')) + $encoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes('throw "boom"')) $p.StartInfo.Arguments = "-EncodedCommand $encoded -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile -OutputFormat text" $p.StartInfo.UseShellExecute = $false $p.StartInfo.RedirectStandardError = $true $p.Start() | Out-Null $out = $p.StandardError.ReadToEnd() $out | Should -Not -BeNullOrEmpty - $out.Split([Environment]::NewLine)[0] | Should -BeExactly "boom" + $out = $out.Split([Environment]::NewLine)[0] + [System.Management.Automation.Internal.StringDecorated]::new($out).ToString("PlainText") | Should -BeExactly "Exception: boom" } } From 7f6b78257ebecc44ca2c3847b1241e91a61d0c97 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 1 Sep 2022 08:52:22 +0500 Subject: [PATCH 041/779] Bump Microsoft.NET.Test.Sdk from 17.3.0 to 17.3.1 (#18000) Bumps [Microsoft.NET.Test.Sdk](https://github.com/microsoft/vstest) from 17.3.0 to 17.3.1. - [Release notes](https://github.com/microsoft/vstest/releases) - [Commits](https://github.com/microsoft/vstest/compare/v17.3.0...v17.3.1) --- updated-dependencies: - dependency-name: Microsoft.NET.Test.Sdk dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- test/xUnit/xUnit.tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/xUnit/xUnit.tests.csproj b/test/xUnit/xUnit.tests.csproj index 797f1bd52be..c1710a1aa57 100644 --- a/test/xUnit/xUnit.tests.csproj +++ b/test/xUnit/xUnit.tests.csproj @@ -27,7 +27,7 @@ - + From ed68cd21cc244f8b3dd28b5224f43fb56c4875df Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Fri, 2 Sep 2022 11:40:05 -0700 Subject: [PATCH 042/779] Add XML reference documents to NuPkg files for SDK (#17997) --- tools/packaging/packaging.psm1 | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/tools/packaging/packaging.psm1 b/tools/packaging/packaging.psm1 index 2e278182f9b..775270acaba 100644 --- a/tools/packaging/packaging.psm1 +++ b/tools/packaging/packaging.psm1 @@ -2108,7 +2108,7 @@ function New-ILNugetPackageSource #region ref $refFolder = New-Item (Join-Path $filePackageFolder.FullName "ref/$script:netCoreRuntime") -ItemType Directory -Force - CopyReferenceAssemblies -assemblyName $fileBaseName -refBinPath $refBinPath -refNugetPath $refFolder -assemblyFileList $fileList + CopyReferenceAssemblies -assemblyName $fileBaseName -refBinPath $refBinPath -refNugetPath $refFolder -assemblyFileList $fileList -winBinPath $WinFxdBinPath #endregion ref $packageRuntimesFolderPath = $packageRuntimesFolder.FullName @@ -2257,7 +2257,8 @@ function CopyReferenceAssemblies [string] $assemblyName, [string] $refBinPath, [string] $refNugetPath, - [string[]] $assemblyFileList + [string[]] $assemblyFileList, + [string] $winBinPath ) $supportedRefList = @( @@ -2286,7 +2287,8 @@ function CopyReferenceAssemblies default { $ref_SMA = Join-Path -Path $refBinPath -ChildPath System.Management.Automation.dll $ref_doc = Join-Path -Path $refBinPath -ChildPath System.Management.Automation.xml - Copy-Item $ref_SMA, $ref_doc -Destination $refNugetPath -Force + $self_ref_doc = Join-Path -Path $winBinPath -ChildPath "$assemblyName.xml" + Copy-Item $ref_SMA, $ref_doc, $self_ref_doc -Destination $refNugetPath -Force Write-Log "Copied file '$ref_SMA' and '$ref_doc' to '$refNugetPath'" } } From 1c13c7084b5c295e9ef8bf8b33603e5851853a85 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 6 Sep 2022 10:05:39 -0700 Subject: [PATCH 043/779] Bump `Microsoft.CodeAnalysis.CSharp` from 4.3.0-3.final to 4.3.0 (#18012) --- .../Microsoft.PowerShell.Commands.Utility.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj index a09a69a84ee..13ebe7c3bec 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj +++ b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj @@ -31,7 +31,7 @@ - + From c17fda415af95c0c04fa2d4762538e239389b485 Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Tue, 6 Sep 2022 12:21:53 -0700 Subject: [PATCH 044/779] Add schema for cgmanifest.json (#18036) * Update cgmanifest.json * Update findMissingNotices.ps1 --- tools/cgmanifest.json | 3 ++- tools/findMissingNotices.ps1 | 6 +++++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/tools/cgmanifest.json b/tools/cgmanifest.json index a290afb3c9c..1c67fd7818e 100644 --- a/tools/cgmanifest.json +++ b/tools/cgmanifest.json @@ -1430,5 +1430,6 @@ }, "DevelopmentDependency": false } - ] + ], + "$schema": "https://json.schemastore.org/component-detection-manifest.json" } diff --git a/tools/findMissingNotices.ps1 b/tools/findMissingNotices.ps1 index 658e95212db..c7a6514d723 100644 --- a/tools/findMissingNotices.ps1 +++ b/tools/findMissingNotices.ps1 @@ -275,7 +275,11 @@ foreach ($runtime in "win7-x64", "linux-x64", "osx-x64", "alpine-x64", "win-arm" $newRegistrations = $registrations.Keys | Sort-Object | ForEach-Object { $registrations[$_] } $count = $newRegistrations.Count -$newJson = @{Registrations = $newRegistrations } | ConvertTo-Json -depth 99 +$newJson = @{ + Registrations = $newRegistrations + '$schema' = "https://json.schemastore.org/component-detection-manifest.json" +} | ConvertTo-Json -depth 99 + if ($Fix -and $registrationChanged) { $newJson | Set-Content $cgManifestPath Set-GWVariable -Name CGMANIFEST_PATH -Value $cgManifestPath From 6e36446b6ffbf3d169718a1180d18613dd5c4df1 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Wed, 7 Sep 2022 10:26:21 -0700 Subject: [PATCH 045/779] Make experimental feature `PSCleanBlock` stable (#18043) --- experimental-feature-linux.json | 1 - experimental-feature-windows.json | 1 - .../engine/CommandMetadata.cs | 15 ++++----------- .../ExperimentalFeature/ExperimentalFeature.cs | 4 ---- .../engine/parser/tokenizer.cs | 8 -------- 5 files changed, 4 insertions(+), 25 deletions(-) diff --git a/experimental-feature-linux.json b/experimental-feature-linux.json index b0a5a696381..a8c4e23f155 100644 --- a/experimental-feature-linux.json +++ b/experimental-feature-linux.json @@ -1,7 +1,6 @@ [ "PSAMSIMethodInvocationLogging", "PSAnsiRenderingFileInfo", - "PSCleanBlock", "PSCommandNotFoundSuggestion", "PSExec", "PSLoadAssemblyFromNativeCode", diff --git a/experimental-feature-windows.json b/experimental-feature-windows.json index b0a5a696381..a8c4e23f155 100644 --- a/experimental-feature-windows.json +++ b/experimental-feature-windows.json @@ -1,7 +1,6 @@ [ "PSAMSIMethodInvocationLogging", "PSAnsiRenderingFileInfo", - "PSCleanBlock", "PSCommandNotFoundSuggestion", "PSExec", "PSLoadAssemblyFromNativeCode", diff --git a/src/System.Management.Automation/engine/CommandMetadata.cs b/src/System.Management.Automation/engine/CommandMetadata.cs index 75d02ed59d5..a9094f54b36 100644 --- a/src/System.Management.Automation/engine/CommandMetadata.cs +++ b/src/System.Management.Automation/engine/CommandMetadata.cs @@ -864,15 +864,6 @@ internal string GetProxyCommand(string helpComment, bool generateDynamicParamete ", GetDynamicParamBlock()); } - string cleanBlock = string.Empty; - if (ExperimentalFeature.IsEnabled(ExperimentalFeature.PSCleanBlockFeatureName)) - { - cleanBlock = string.Format(CultureInfo.InvariantCulture, @" -clean -{{{0}}} -", GetCleanBlock()); - } - string result = string.Format(CultureInfo.InvariantCulture, @"{0} param({1}) @@ -884,7 +875,9 @@ internal string GetProxyCommand(string helpComment, bool generateDynamicParamete end {{{5}}} -{6} + +clean +{{{6}}} <# {7} #> @@ -895,7 +888,7 @@ internal string GetProxyCommand(string helpComment, bool generateDynamicParamete GetBeginBlock(), GetProcessBlock(), GetEndBlock(), - cleanBlock, + GetCleanBlock(), CodeGeneration.EscapeBlockCommentContent(helpComment)); return result; diff --git a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs index 8a3e428b9c4..3136d82682d 100644 --- a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs +++ b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs @@ -24,7 +24,6 @@ public class ExperimentalFeature internal const string PSNativeCommandArgumentPassingFeatureName = "PSNativeCommandArgumentPassing"; internal const string PSNativeCommandErrorActionPreferenceFeatureName = "PSNativeCommandErrorActionPreference"; internal const string PSRemotingSSHTransportErrorHandling = "PSRemotingSSHTransportErrorHandling"; - internal const string PSCleanBlockFeatureName = "PSCleanBlock"; internal const string PSAMSIMethodInvocationLogging = "PSAMSIMethodInvocationLogging"; internal const string PSExecFeatureName = "PSExec"; internal const string PSStrictModeAssignment = "PSStrictModeAssignment"; @@ -131,9 +130,6 @@ static ExperimentalFeature() new ExperimentalFeature( name: PSRemotingSSHTransportErrorHandling, description: "Removes the SSH remoting transport stdErr stream message handling as terminating errors, and instead just writes error messages to console."), - new ExperimentalFeature( - name: PSCleanBlockFeatureName, - description: "Add support of a 'Clean' block to functions and script cmdlets for easy resource cleanup"), new ExperimentalFeature( name: PSAMSIMethodInvocationLogging, description: "Provides AMSI notification of .NET method invocations."), diff --git a/src/System.Management.Automation/engine/parser/tokenizer.cs b/src/System.Management.Automation/engine/parser/tokenizer.cs index 1c5654b34c4..9e133016e85 100644 --- a/src/System.Management.Automation/engine/parser/tokenizer.cs +++ b/src/System.Management.Automation/engine/parser/tokenizer.cs @@ -699,16 +699,8 @@ static Tokenizer() Diagnostics.Assert(s_keywordText.Length == s_keywordTokenKind.Length, "Keyword table sizes must match"); Diagnostics.Assert(_operatorText.Length == s_operatorTokenKind.Length, "Operator table sizes must match"); - bool isCleanBlockFeatureEnabled = ExperimentalFeature.IsEnabled(ExperimentalFeature.PSCleanBlockFeatureName); - for (int i = 0; i < s_keywordText.Length; ++i) { - if (!isCleanBlockFeatureEnabled && s_keywordText[i] == "clean") - { - // Skip adding the 'clean' keyword when the feature is disabled. - continue; - } - s_keywordTable.Add(s_keywordText[i], s_keywordTokenKind[i]); } From 918bb8c952af1d461abfc98bc709a1d359168a1c Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Wed, 7 Sep 2022 10:28:17 -0700 Subject: [PATCH 046/779] Make experimental feature `PSExec` stable (#18045) --- experimental-feature-linux.json | 1 - experimental-feature-windows.json | 1 - .../engine/ExperimentalFeature/ExperimentalFeature.cs | 4 ---- .../engine/InitialSessionState.cs | 10 ++-------- .../engine/Modules/SwitchProcessCommand.cs | 1 - .../Modules/Microsoft.PowerShell.Core/Exec.Tests.ps1 | 4 ++-- test/powershell/engine/Basic/DefaultCommands.Tests.ps1 | 2 ++ 7 files changed, 6 insertions(+), 17 deletions(-) diff --git a/experimental-feature-linux.json b/experimental-feature-linux.json index a8c4e23f155..c6d98f416d5 100644 --- a/experimental-feature-linux.json +++ b/experimental-feature-linux.json @@ -2,7 +2,6 @@ "PSAMSIMethodInvocationLogging", "PSAnsiRenderingFileInfo", "PSCommandNotFoundSuggestion", - "PSExec", "PSLoadAssemblyFromNativeCode", "PSNativeCommandArgumentPassing", "PSNativeCommandErrorActionPreference", diff --git a/experimental-feature-windows.json b/experimental-feature-windows.json index a8c4e23f155..c6d98f416d5 100644 --- a/experimental-feature-windows.json +++ b/experimental-feature-windows.json @@ -2,7 +2,6 @@ "PSAMSIMethodInvocationLogging", "PSAnsiRenderingFileInfo", "PSCommandNotFoundSuggestion", - "PSExec", "PSLoadAssemblyFromNativeCode", "PSNativeCommandArgumentPassing", "PSNativeCommandErrorActionPreference", diff --git a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs index 3136d82682d..534c16e7aaf 100644 --- a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs +++ b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs @@ -25,7 +25,6 @@ public class ExperimentalFeature internal const string PSNativeCommandErrorActionPreferenceFeatureName = "PSNativeCommandErrorActionPreference"; internal const string PSRemotingSSHTransportErrorHandling = "PSRemotingSSHTransportErrorHandling"; internal const string PSAMSIMethodInvocationLogging = "PSAMSIMethodInvocationLogging"; - internal const string PSExecFeatureName = "PSExec"; internal const string PSStrictModeAssignment = "PSStrictModeAssignment"; #endregion @@ -133,9 +132,6 @@ static ExperimentalFeature() new ExperimentalFeature( name: PSAMSIMethodInvocationLogging, description: "Provides AMSI notification of .NET method invocations."), - new ExperimentalFeature( - name: PSExecFeatureName, - description: "Add 'exec' built-in command on Linux and macOS"), new ExperimentalFeature( name: PSStrictModeAssignment, description: "Add support of setting Strict-Mode with Invoke-Command"), diff --git a/src/System.Management.Automation/engine/InitialSessionState.cs b/src/System.Management.Automation/engine/InitialSessionState.cs index 6bc7e9e0021..58cd5f2b3f9 100644 --- a/src/System.Management.Automation/engine/InitialSessionState.cs +++ b/src/System.Management.Automation/engine/InitialSessionState.cs @@ -4696,10 +4696,7 @@ internal static SessionStateAliasEntry[] BuiltInAliases }; #if UNIX - if (ExperimentalFeature.IsEnabled(ExperimentalFeature.PSExecFeatureName)) - { - builtInAliases.Add(new SessionStateAliasEntry("exec", "Switch-Process")); - } + builtInAliases.Add(new SessionStateAliasEntry("exec", "Switch-Process")); #endif return builtInAliases.ToArray(); @@ -5341,10 +5338,7 @@ private static void InitializeCoreCmdletsAndProviders( } #if UNIX - if (ExperimentalFeature.IsEnabled(ExperimentalFeature.PSExecFeatureName)) - { - cmdlets.Add("Switch-Process", new SessionStateCmdletEntry("Switch-Process", typeof(SwitchProcessCommand), helpFile)); - } + cmdlets.Add("Switch-Process", new SessionStateCmdletEntry("Switch-Process", typeof(SwitchProcessCommand), helpFile)); #endif foreach (var val in cmdlets.Values) diff --git a/src/System.Management.Automation/engine/Modules/SwitchProcessCommand.cs b/src/System.Management.Automation/engine/Modules/SwitchProcessCommand.cs index 298587679b1..1bad35bfd31 100644 --- a/src/System.Management.Automation/engine/Modules/SwitchProcessCommand.cs +++ b/src/System.Management.Automation/engine/Modules/SwitchProcessCommand.cs @@ -17,7 +17,6 @@ namespace Microsoft.PowerShell.Commands /// /// Implements a cmdlet that allows use of execv API. /// - [Experimental(ExperimentalFeature.PSExecFeatureName, ExperimentAction.Show)] [Cmdlet(VerbsCommon.Switch, "Process", HelpUri = "https://go.microsoft.com/fwlink/?linkid=2181448")] public sealed class SwitchProcessCommand : PSCmdlet { diff --git a/test/powershell/Modules/Microsoft.PowerShell.Core/Exec.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Core/Exec.Tests.ps1 index bd3c87e0f5c..640fb8e0fc9 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Core/Exec.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Core/Exec.Tests.ps1 @@ -4,7 +4,7 @@ Describe 'Switch-Process tests for Unix' -Tags 'CI' { BeforeAll { $originalDefaultParameterValues = $PSDefaultParameterValues.Clone() - if (-not [ExperimentalFeature]::IsEnabled('PSExec') -or $IsWindows) + if ($IsWindows) { $PSDefaultParameterValues['It:Skip'] = $true return @@ -53,7 +53,7 @@ Describe 'Switch-Process tests for Unix' -Tags 'CI' { Describe 'Switch-Process for Windows' { BeforeAll { $originalDefaultParameterValues = $PSDefaultParameterValues.Clone() - if (-not $IsWindows) + if (!$IsWindows) { $PSDefaultParameterValues['It:Skip'] = $true return diff --git a/test/powershell/engine/Basic/DefaultCommands.Tests.ps1 b/test/powershell/engine/Basic/DefaultCommands.Tests.ps1 index aaa6cb432bd..bdcd5af0000 100644 --- a/test/powershell/engine/Basic/DefaultCommands.Tests.ps1 +++ b/test/powershell/engine/Basic/DefaultCommands.Tests.ps1 @@ -58,6 +58,7 @@ Describe "Verify approved aliases list" -Tags "CI" { "Alias", "epsn", "Export-PSSession", $($FullCLR ), "", "", "" "Alias", "erase", "Remove-Item", $($FullCLR -or $CoreWindows -or $CoreUnix), "", "", "" "Alias", "etsn", "Enter-PSSession", $($FullCLR -or $CoreWindows -or $CoreUnix), "", "", "" +"Alias", "exec", "Switch-Process", $( $CoreUnix), "", "", "" "Alias", "exsn", "Exit-PSSession", $($FullCLR -or $CoreWindows -or $CoreUnix), "", "", "" "Alias", "fc", "Format-Custom", $($FullCLR -or $CoreWindows -or $CoreUnix), "ReadOnly", "", "" "Alias", "fhx", "Format-Hex", $($FullCLR -or $CoreWindows -or $CoreUnix), "", "", "" @@ -482,6 +483,7 @@ Describe "Verify approved aliases list" -Tags "CI" { "Cmdlet", "Stop-Transcript", "", $($FullCLR -or $CoreWindows -or $CoreUnix), "", "", "None" "Cmdlet", "Suspend-Job", "", $($FullCLR ), "", "", "" "Cmdlet", "Suspend-Service", "", $($FullCLR -or $CoreWindows ), "", "", "Medium" +"Cmdlet", "Switch-Process", "", $( $CoreUnix), "", "", "None" "Cmdlet", "Tee-Object", "", $($FullCLR -or $CoreWindows -or $CoreUnix), "", "", "Medium" "Cmdlet", "Test-Connection", "", $( $CoreWindows -or $CoreUnix), "", "", "None" "Cmdlet", "Test-ComputerSecureChannel", "", $($FullCLR ), "", "", "" From 3f5c5cd6172113c2ae7757effbf6329588cade8d Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Wed, 7 Sep 2022 15:56:06 -0700 Subject: [PATCH 047/779] Update the cgmanifest (#18051) Co-authored-by: adityapatwardhan --- tools/cgmanifest.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tools/cgmanifest.json b/tools/cgmanifest.json index 1c67fd7818e..0e91c06fca1 100644 --- a/tools/cgmanifest.json +++ b/tools/cgmanifest.json @@ -65,7 +65,7 @@ "Type": "nuget", "Nuget": { "Name": "Microsoft.CodeAnalysis.Common", - "Version": "4.2.0" + "Version": "4.3.0" } }, "DevelopmentDependency": false @@ -75,7 +75,7 @@ "Type": "nuget", "Nuget": { "Name": "Microsoft.CodeAnalysis.CSharp", - "Version": "4.2.0" + "Version": "4.3.0" } }, "DevelopmentDependency": false @@ -725,7 +725,7 @@ "Type": "nuget", "Nuget": { "Name": "System.Collections.Immutable", - "Version": "5.0.0" + "Version": "6.0.0" } }, "DevelopmentDependency": false From 3bf6423a1077ba6d3ab03fc1e81767965e59229e Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Wed, 7 Sep 2022 17:34:30 -0700 Subject: [PATCH 048/779] Make experimental feature `PSRemotingSSHTransportErrorHandling` stable (#18046) --- experimental-feature-linux.json | 1 - experimental-feature-windows.json | 1 - .../ExperimentalFeature.cs | 4 - .../fanin/OutOfProcTransportManager.cs | 99 +++---------------- 4 files changed, 15 insertions(+), 90 deletions(-) diff --git a/experimental-feature-linux.json b/experimental-feature-linux.json index c6d98f416d5..a5b3eba3bf1 100644 --- a/experimental-feature-linux.json +++ b/experimental-feature-linux.json @@ -5,7 +5,6 @@ "PSLoadAssemblyFromNativeCode", "PSNativeCommandArgumentPassing", "PSNativeCommandErrorActionPreference", - "PSRemotingSSHTransportErrorHandling", "PSStrictModeAssignment", "PSSubsystemPluginModel" ] diff --git a/experimental-feature-windows.json b/experimental-feature-windows.json index c6d98f416d5..a5b3eba3bf1 100644 --- a/experimental-feature-windows.json +++ b/experimental-feature-windows.json @@ -5,7 +5,6 @@ "PSLoadAssemblyFromNativeCode", "PSNativeCommandArgumentPassing", "PSNativeCommandErrorActionPreference", - "PSRemotingSSHTransportErrorHandling", "PSStrictModeAssignment", "PSSubsystemPluginModel" ] diff --git a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs index 534c16e7aaf..3f086d1df6d 100644 --- a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs +++ b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs @@ -23,7 +23,6 @@ public class ExperimentalFeature internal const string EngineSource = "PSEngine"; internal const string PSNativeCommandArgumentPassingFeatureName = "PSNativeCommandArgumentPassing"; internal const string PSNativeCommandErrorActionPreferenceFeatureName = "PSNativeCommandErrorActionPreference"; - internal const string PSRemotingSSHTransportErrorHandling = "PSRemotingSSHTransportErrorHandling"; internal const string PSAMSIMethodInvocationLogging = "PSAMSIMethodInvocationLogging"; internal const string PSStrictModeAssignment = "PSStrictModeAssignment"; @@ -126,9 +125,6 @@ static ExperimentalFeature() new ExperimentalFeature( name: PSNativeCommandErrorActionPreferenceFeatureName, description: "Native commands with non-zero exit codes issue errors according to $ErrorActionPreference when $PSNativeCommandUseErrorActionPreference is $true"), - new ExperimentalFeature( - name: PSRemotingSSHTransportErrorHandling, - description: "Removes the SSH remoting transport stdErr stream message handling as terminating errors, and instead just writes error messages to console."), new ExperimentalFeature( name: PSAMSIMethodInvocationLogging, description: "Provides AMSI notification of .NET method invocations."), diff --git a/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs b/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs index 9a1e4ff47e3..e270a3efeb2 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs @@ -1819,50 +1819,30 @@ private void ProcessErrorThread(object state) { string error; - if (ExperimentalFeature.IsEnabled(ExperimentalFeature.PSRemotingSSHTransportErrorHandling)) - { - // Blocking read from StdError stream - error = reader.ReadLine(); - - if (error == null) - { - // Stream is closed unexpectedly. - throw new PSInvalidOperationException(RemotingErrorIdStrings.SSHAbruptlyTerminated); - } - - if (error.Length == 0) - { - // Ignore - continue; - } - - try - { - // Messages in error stream from ssh are unreliable, and may just be warnings or - // banner text. - // So just report the messages but don't act on them. - System.Console.WriteLine(error); - } - catch (IOException) - { } + // Blocking read from StdError stream + error = reader.ReadLine(); - continue; + if (error == null) + { + // Stream is closed unexpectedly. + throw new PSInvalidOperationException(RemotingErrorIdStrings.SSHAbruptlyTerminated); } - error = ReadError(reader); - if (error.Length == 0) { // Ignore continue; } - // Any SSH client error results in a broken session. - PSRemotingTransportException psrte = new PSRemotingTransportException( - PSRemotingErrorId.IPCServerProcessReportedError, - RemotingErrorIdStrings.IPCServerProcessReportedError, - StringUtil.Format(RemotingErrorIdStrings.SSHClientEndWithErrorMessage, error)); - HandleSSHError(psrte); + try + { + // Messages in error stream from ssh are unreliable, and may just be warnings or + // banner text. + // So just report the messages but don't act on them. + System.Console.WriteLine(error); + } + catch (IOException) + { } } } catch (ObjectDisposedException) @@ -1888,55 +1868,6 @@ private void HandleSSHError(PSRemotingTransportException psrte) CloseConnection(); } - private static string ReadError(StreamReader reader) - { - // Blocking read from StdError stream - string error = reader.ReadLine(); - - if (error == null) - { - // Stream is closed unexpectedly. - throw new PSInvalidOperationException(RemotingErrorIdStrings.SSHAbruptlyTerminated); - } - - if ((error.Length == 0) || - error.Contains("WARNING:", StringComparison.OrdinalIgnoreCase)) - { - // Handle as interactive warning message - Console.WriteLine(error); - return string.Empty; - } - - // SSH may return a multi-line error message. - // The StdError pipe stream is open ended causing StreamReader read operations to block - // if there is no incoming data. Since we don't know how many error message lines there - // will be we use an asynchronous read with timeout to prevent blocking indefinitely. - System.Text.StringBuilder sb = new Text.StringBuilder(error); - var running = true; - while (running) - { - try - { - var task = reader.ReadLineAsync(); - if (task.Wait(1000) && (task.Result != null)) - { - sb.Append(Environment.NewLine); - sb.Append(task.Result); - } - else - { - running = false; - } - } - catch (Exception) - { - running = false; - } - } - - return sb.ToString(); - } - private void StartReaderThread( StreamReader reader) { From 397bd87cb30382c56ecdd1a715f05ed2855ca29e Mon Sep 17 00:00:00 2001 From: Rose <83477269+AtariDreams@users.noreply.github.com> Date: Thu, 8 Sep 2022 15:10:38 -0400 Subject: [PATCH 049/779] Remove unused variables (#18058) --- src/Microsoft.PowerShell.Security/security/CmsCommands.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/Microsoft.PowerShell.Security/security/CmsCommands.cs b/src/Microsoft.PowerShell.Security/security/CmsCommands.cs index 9fde804d220..4983ed22722 100644 --- a/src/Microsoft.PowerShell.Security/security/CmsCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/CmsCommands.cs @@ -308,8 +308,7 @@ protected override void EndProcessing() } // Extract out the bytes and Base64 decode them - int startIndex, endIndex; - byte[] contentBytes = CmsUtils.RemoveAsciiArmor(actualContent, CmsUtils.BEGIN_CMS_SIGIL, CmsUtils.END_CMS_SIGIL, out startIndex, out endIndex); + byte[] contentBytes = CmsUtils.RemoveAsciiArmor(actualContent, CmsUtils.BEGIN_CMS_SIGIL, CmsUtils.END_CMS_SIGIL, out int _, out int _); if (contentBytes == null) { ErrorRecord error = new( From eb92c501dac51cd96cdd4ff7d3b3488c62eebbf9 Mon Sep 17 00:00:00 2001 From: Ikko Ashimine Date: Tue, 13 Sep 2022 01:13:28 +0900 Subject: [PATCH 050/779] Fix typos in `EventResource.resx` (#18063) --- .../resources/EventResource.resx | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/System.Management.Automation/resources/EventResource.resx b/src/System.Management.Automation/resources/EventResource.resx index a4f245cde93..d6c3bc5dcd3 100644 --- a/src/System.Management.Automation/resources/EventResource.resx +++ b/src/System.Management.Automation/resources/EventResource.resx @@ -550,7 +550,7 @@ Parameters = {7} Test analytic message - Connection Paramters are + Connection Parameters are Connection URI: {0} Resource URI: {1} User: {2} @@ -707,16 +707,16 @@ Exception StackTrace: {2} Type cast inner exception: {3} - Serialization depth has been overriden. + Serialization depth has been overridden. Serialized type name: {0} Original depth: {1} - Overriden depth: {2} + Overridden depth: {2} Current depth below top level: {3} - Serialization mode has been overriden. + Serialization mode has been overridden. Serialized type name: {0} - Overriden mode: {1} + Overridden mode: {1} Serialization of a script property has been skipped, because there is no runspace to use for evaluation of the property. From 3fbd90a4b04cc785064dc801beac83f60c8676f5 Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Mon, 12 Sep 2022 09:15:14 -0700 Subject: [PATCH 051/779] Handle `PSObject` argument specially in method invocation logging (#18060) --- .../engine/runtime/Operations/MiscOps.cs | 35 ++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs b/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs index a85bc8a8e78..1c15c6510bc 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs @@ -13,6 +13,7 @@ using System.Management.Automation.Internal.Host; using System.Management.Automation.Language; using System.Management.Automation.Runspaces; +using System.Numerics; using System.Reflection; using System.Runtime.CompilerServices; using System.Text.RegularExpressions; @@ -3545,6 +3546,38 @@ internal static class MemberInvocationLoggingOps } ); + private static string ArgumentToString(object arg) + { + object baseObj = PSObject.Base(arg); + if (baseObj is null) + { + // The argument is null or AutomationNull.Value. + return "null"; + } + + // The comparisons below are ordered by the likelihood of arguments being of those types. + if (baseObj is string str) + { + return str; + } + + // Special case some types to call 'ToString' on the object. For the rest, we return its + // full type name to avoid calling a potentially expensive 'ToString' implementation. + Type baseType = baseObj.GetType(); + if (baseType.IsEnum || baseType.IsPrimitive + || baseType == typeof(Guid) + || baseType == typeof(Uri) + || baseType == typeof(Version) + || baseType == typeof(SemanticVersion) + || baseType == typeof(BigInteger) + || baseType == typeof(decimal)) + { + return baseObj.ToString(); + } + + return baseType.FullName; + } + internal static void LogMemberInvocation(string targetName, string name, object[] args) { try @@ -3554,7 +3587,7 @@ internal static void LogMemberInvocation(string targetName, string name, object[ for (int i = 0; i < args.Length; i++) { - string value = args[i] is null ? "null" : args[i].ToString(); + string value = ArgumentToString(args[i]); if (i > 0) { From ce746969ab2da8e92825d25ae62499f4e37c30f9 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Mon, 12 Sep 2022 09:20:20 -0700 Subject: [PATCH 052/779] Make experimental feature `PSAMSIMethodInvocationLogging` stable (#18041) --- experimental-feature-linux.json | 1 - experimental-feature-windows.json | 1 - .../ExperimentalFeature.cs | 4 --- .../engine/runtime/Binding/Binders.cs | 29 +++++++++---------- 4 files changed, 13 insertions(+), 22 deletions(-) diff --git a/experimental-feature-linux.json b/experimental-feature-linux.json index a5b3eba3bf1..c25b0891254 100644 --- a/experimental-feature-linux.json +++ b/experimental-feature-linux.json @@ -1,5 +1,4 @@ [ - "PSAMSIMethodInvocationLogging", "PSAnsiRenderingFileInfo", "PSCommandNotFoundSuggestion", "PSLoadAssemblyFromNativeCode", diff --git a/experimental-feature-windows.json b/experimental-feature-windows.json index a5b3eba3bf1..c25b0891254 100644 --- a/experimental-feature-windows.json +++ b/experimental-feature-windows.json @@ -1,5 +1,4 @@ [ - "PSAMSIMethodInvocationLogging", "PSAnsiRenderingFileInfo", "PSCommandNotFoundSuggestion", "PSLoadAssemblyFromNativeCode", diff --git a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs index 3f086d1df6d..dfb29dfbdeb 100644 --- a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs +++ b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs @@ -23,7 +23,6 @@ public class ExperimentalFeature internal const string EngineSource = "PSEngine"; internal const string PSNativeCommandArgumentPassingFeatureName = "PSNativeCommandArgumentPassing"; internal const string PSNativeCommandErrorActionPreferenceFeatureName = "PSNativeCommandErrorActionPreference"; - internal const string PSAMSIMethodInvocationLogging = "PSAMSIMethodInvocationLogging"; internal const string PSStrictModeAssignment = "PSStrictModeAssignment"; #endregion @@ -125,9 +124,6 @@ static ExperimentalFeature() new ExperimentalFeature( name: PSNativeCommandErrorActionPreferenceFeatureName, description: "Native commands with non-zero exit codes issue errors according to $ErrorActionPreference when $PSNativeCommandUseErrorActionPreference is $true"), - new ExperimentalFeature( - name: PSAMSIMethodInvocationLogging, - description: "Provides AMSI notification of .NET method invocations."), new ExperimentalFeature( name: PSStrictModeAssignment, description: "Add support of setting Strict-Mode with Invoke-Command"), diff --git a/src/System.Management.Automation/engine/runtime/Binding/Binders.cs b/src/System.Management.Automation/engine/runtime/Binding/Binders.cs index e6f7eee438e..8662cc72ecd 100644 --- a/src/System.Management.Automation/engine/runtime/Binding/Binders.cs +++ b/src/System.Management.Automation/engine/runtime/Binding/Binders.cs @@ -6891,22 +6891,19 @@ internal static DynamicMetaObject InvokeDotNetMethod( expr = Expression.Block(expr, ExpressionCache.AutomationNullConstant); } - if (ExperimentalFeature.IsEnabled(ExperimentalFeature.PSAMSIMethodInvocationLogging)) - { - // Expression block runs two expressions in order: - // - Log method invocation to AMSI Notifications (can throw PSSecurityException) - // - Invoke method - string targetName = methodInfo.ReflectedType?.FullName ?? string.Empty; - expr = Expression.Block( - Expression.Call( - CachedReflectionInfo.MemberInvocationLoggingOps_LogMemberInvocation, - Expression.Constant(targetName), - Expression.Constant(name), - Expression.NewArrayInit( - typeof(object), - args.Select(static e => e.Expression.Cast(typeof(object))))), - expr); - } + // Expression block runs two expressions in order: + // - Log method invocation to AMSI Notifications (can throw PSSecurityException) + // - Invoke method + string targetName = methodInfo.ReflectedType?.FullName ?? string.Empty; + expr = Expression.Block( + Expression.Call( + CachedReflectionInfo.MemberInvocationLoggingOps_LogMemberInvocation, + Expression.Constant(targetName), + Expression.Constant(name), + Expression.NewArrayInit( + typeof(object), + args.Select(static e => e.Expression.Cast(typeof(object))))), + expr); // If we're calling SteppablePipeline.{Begin|Process|End}, we don't want // to wrap exceptions - this is very much a special case to help error From b89845145fc85e702d84800dfff34924bc984dc8 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Mon, 12 Sep 2022 09:31:14 -0700 Subject: [PATCH 053/779] Update to the latest `NOTICES` file (#18055) --- ThirdPartyNotices.txt | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/ThirdPartyNotices.txt b/ThirdPartyNotices.txt index b2e206b7783..fec5e8df95e 100644 --- a/ThirdPartyNotices.txt +++ b/ThirdPartyNotices.txt @@ -228,7 +228,7 @@ SOFTWARE. --------------------------------------------------------- -Microsoft.CodeAnalysis.Common 4.2.0 - MIT +Microsoft.CodeAnalysis.Common 4.3.0 - MIT @@ -246,7 +246,7 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI --------------------------------------------------------- -Microsoft.CodeAnalysis.CSharp 4.2.0 - MIT +Microsoft.CodeAnalysis.CSharp 4.3.0 - MIT @@ -1199,7 +1199,7 @@ SOFTWARE. --------------------------------------------------------- -System.Collections.Immutable 5.0.0 - MIT +System.Collections.Immutable 6.0.0 - MIT (c) Microsoft Corporation. @@ -1227,6 +1227,7 @@ Copyright (c) 2016-2017, Matthieu Darbois Copyright (c) .NET Foundation Contributors Copyright (c) The Internet Society (2003). Copyright (c) .NET Foundation and Contributors +Copyright (c) 2019 Microsoft Corporation, Daan Leijen Copyright (c) 2011 Novell, Inc (http://www.novell.com) Copyright (c) 1995-2017 Jean-loup Gailly and Mark Adler Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) From 6744ffb8261c27a2fe3d523df7a216cbab018ce4 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Mon, 12 Sep 2022 09:48:09 -0700 Subject: [PATCH 054/779] Make experimental feature `PSNativeCommandArgumentPassing` stable (#18044) --- experimental-feature-linux.json | 1 - experimental-feature-windows.json | 1 - .../ExperimentalFeature.cs | 4 --- .../engine/InitialSessionState.cs | 36 +++++-------------- .../engine/NativeCommandParameterBinder.cs | 24 +++++-------- .../NativeCommandArguments.Tests.ps1 | 19 +++------- 6 files changed, 23 insertions(+), 62 deletions(-) diff --git a/experimental-feature-linux.json b/experimental-feature-linux.json index c25b0891254..a71c0c3ed21 100644 --- a/experimental-feature-linux.json +++ b/experimental-feature-linux.json @@ -2,7 +2,6 @@ "PSAnsiRenderingFileInfo", "PSCommandNotFoundSuggestion", "PSLoadAssemblyFromNativeCode", - "PSNativeCommandArgumentPassing", "PSNativeCommandErrorActionPreference", "PSStrictModeAssignment", "PSSubsystemPluginModel" diff --git a/experimental-feature-windows.json b/experimental-feature-windows.json index c25b0891254..a71c0c3ed21 100644 --- a/experimental-feature-windows.json +++ b/experimental-feature-windows.json @@ -2,7 +2,6 @@ "PSAnsiRenderingFileInfo", "PSCommandNotFoundSuggestion", "PSLoadAssemblyFromNativeCode", - "PSNativeCommandArgumentPassing", "PSNativeCommandErrorActionPreference", "PSStrictModeAssignment", "PSSubsystemPluginModel" diff --git a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs index dfb29dfbdeb..8c3e1c070ec 100644 --- a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs +++ b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs @@ -21,7 +21,6 @@ public class ExperimentalFeature #region Const Members internal const string EngineSource = "PSEngine"; - internal const string PSNativeCommandArgumentPassingFeatureName = "PSNativeCommandArgumentPassing"; internal const string PSNativeCommandErrorActionPreferenceFeatureName = "PSNativeCommandErrorActionPreference"; internal const string PSStrictModeAssignment = "PSStrictModeAssignment"; @@ -112,9 +111,6 @@ static ExperimentalFeature() new ExperimentalFeature( name: "PSSubsystemPluginModel", description: "A plugin model for registering and un-registering PowerShell subsystems"), - new ExperimentalFeature( - name: PSNativeCommandArgumentPassingFeatureName, - description: "Use ArgumentList when invoking a native command"), new ExperimentalFeature( name: "PSLoadAssemblyFromNativeCode", description: "Expose an API to allow assembly loading from native code"), diff --git a/src/System.Management.Automation/engine/InitialSessionState.cs b/src/System.Management.Automation/engine/InitialSessionState.cs index 58cd5f2b3f9..e75ca018f8e 100644 --- a/src/System.Management.Automation/engine/InitialSessionState.cs +++ b/src/System.Management.Automation/engine/InitialSessionState.cs @@ -4161,13 +4161,7 @@ .FORWARDHELPCATEGORY Cmdlet } else { $pagerCommand = 'less' - # PSNativeCommandArgumentPassing arguments should be constructed differently. - if ($EnabledExperimentalFeatures -contains 'PSNativeCommandArgumentPassing') { - $pagerArgs = '-s','-P','Page %db?B of %D:.\. Press h for help or q to quit\.' - } - else { - $pagerArgs = '-Ps""Page %db?B of %D:.\. Press h for help or q to quit\.$""' - } + $pagerArgs = '-s','-P','Page %db?B of %D:.\. Press h for help or q to quit\.' } # Respect PAGER environment variable which allows user to specify a custom pager. @@ -4207,16 +4201,7 @@ .FORWARDHELPCATEGORY Cmdlet $consoleWidth = [System.Math]::Max([System.Console]::WindowWidth, 20) if ($pagerArgs) { - # Start the pager arguments directly if the PSNativeCommandArgumentPassing feature is enabled. - # Otherwise, supply pager arguments to an application without any PowerShell parsing of the arguments. - # Leave environment variable to help user debug arguments supplied in $env:PAGER. - if ($EnabledExperimentalFeatures -contains 'PSNativeCommandArgumentPassing') { - $help | Out-String -Stream -Width ($consoleWidth - 1) | & $pagerCommand $pagerArgs - } - else { - $env:__PSPAGER_ARGS = $pagerArgs - $help | Out-String -Stream -Width ($consoleWidth - 1) | & $pagerCommand --% %__PSPAGER_ARGS% - } + $help | Out-String -Stream -Width ($consoleWidth - 1) | & $pagerCommand $pagerArgs } else { $help | Out-String -Stream -Width ($consoleWidth - 1) | & $pagerCommand @@ -4492,16 +4477,13 @@ static InitialSessionState() new ArgumentTypeConverterAttribute(typeof(bool)))); } - if (ExperimentalFeature.IsEnabled(ExperimentalFeature.PSNativeCommandArgumentPassingFeatureName)) - { - builtinVariables.Add( - new SessionStateVariableEntry( - SpecialVariables.NativeArgumentPassing, - Platform.IsWindows ? NativeArgumentPassingStyle.Windows : NativeArgumentPassingStyle.Standard, - RunspaceInit.NativeCommandArgumentPassingDescription, - ScopedItemOptions.None, - new ArgumentTypeConverterAttribute(typeof(NativeArgumentPassingStyle)))); - } + builtinVariables.Add( + new SessionStateVariableEntry( + SpecialVariables.NativeArgumentPassing, + Platform.IsWindows ? NativeArgumentPassingStyle.Windows : NativeArgumentPassingStyle.Standard, + RunspaceInit.NativeCommandArgumentPassingDescription, + ScopedItemOptions.None, + new ArgumentTypeConverterAttribute(typeof(NativeArgumentPassingStyle)))); BuiltInVariables = builtinVariables.ToArray(); } diff --git a/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs b/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs index aa0e94a5837..567a00387d5 100644 --- a/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs +++ b/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs @@ -193,23 +193,17 @@ internal NativeArgumentPassingStyle ArgumentPassingStyle { get { - if (ExperimentalFeature.IsEnabled(ExperimentalFeature.PSNativeCommandArgumentPassingFeatureName)) + try { - try - { - // This will default to the new behavior if it is set to anything other than Legacy - var preference = LanguagePrimitives.ConvertTo( - Context.GetVariableValue(SpecialVariables.NativeArgumentPassingVarPath, NativeArgumentPassingStyle.Standard)); - return preference; - } - catch - { - // The value is not convertable send back Legacy - return NativeArgumentPassingStyle.Legacy; - } + var preference = LanguagePrimitives.ConvertTo( + Context.GetVariableValue(SpecialVariables.NativeArgumentPassingVarPath, NativeArgumentPassingStyle.Standard)); + return preference; + } + catch + { + // The value is not convertable send back Legacy + return NativeArgumentPassingStyle.Legacy; } - - return NativeArgumentPassingStyle.Legacy; } } diff --git a/test/powershell/Language/Scripting/NativeExecution/NativeCommandArguments.Tests.ps1 b/test/powershell/Language/Scripting/NativeExecution/NativeCommandArguments.Tests.ps1 index 191f7211f6a..d96720139bb 100644 --- a/test/powershell/Language/Scripting/NativeExecution/NativeCommandArguments.Tests.ps1 +++ b/test/powershell/Language/Scripting/NativeExecution/NativeCommandArguments.Tests.ps1 @@ -4,9 +4,6 @@ param() Describe "Behavior is specific for each platform" -tags "CI" { - BeforeAll { - $skipTests = $EnabledExperimentalFeatures -notcontains 'PSNativeCommandArgumentPassing' - } It "PSNativeCommandArgumentPassing is set to 'Windows' on Windows systems" -skip:(-not $IsWindows) { $PSNativeCommandArgumentPassing | Should -Be "Windows" } @@ -28,8 +25,7 @@ Describe "Behavior is specific for each platform" -tags "CI" { Describe "tests for multiple languages and extensions" -tags "CI" { AfterAll { - if (-not $IsWindows -or - $EnabledExperimentalFeatures -notcontains 'PSNativeCommandArgumentPassing') { + if (-not $IsWindows) { return } $PSNativeCommandArgumentPassing = $passingStyle @@ -126,7 +122,7 @@ echo Argument 4 is: ^<%4^> # determine whether we should skip the tests we just defined # doing it in this order ensures that the test output will show each skipped test - $skipTests = -not $IsWindows -or $EnabledExperimentalFeatures -notcontains 'PSNativeCommandArgumentPassing' + $skipTests = -not $IsWindows if ($skipTests) { return } @@ -162,12 +158,7 @@ echo Argument 4 is: ^<%4^> Describe "Will error correctly if an attempt to set variable to improper value" -tags "CI" { It "will error when setting variable incorrectly" { - if ($EnabledExperimentalFeatures -contains 'PSNativeCommandArgumentPassing') { - { $global:PSNativeCommandArgumentPassing = "zzz" } | Should -Throw -ExceptionType System.Management.Automation.ArgumentTransformationMetadataException - } - else { - Set-Test -State skipped -Because "Experimental feature 'PSNativeCommandArgumentPassing' is not enabled" - } + { $global:PSNativeCommandArgumentPassing = "zzz" } | Should -Throw -ExceptionType System.Management.Automation.ArgumentTransformationMetadataException } } @@ -203,7 +194,7 @@ foreach ( $argumentListValue in "Standard","Legacy","Windows" ) { $a = 'a"b c"d' $lines = testexe -echoargs $a 'a"b c"d' a"b c"d "a'b c'd" $lines.Count | Should -Be 4 - if (($EnabledExperimentalFeatures -contains 'PSNativeCommandArgumentPassing') -and $PSNativeCommandArgumentPassing -ne "Legacy") { + if ($PSNativeCommandArgumentPassing -ne "Legacy") { $lines[0] | Should -BeExactly 'Arg 0 is ' $lines[1] | Should -BeExactly 'Arg 1 is ' } @@ -229,7 +220,7 @@ foreach ( $argumentListValue in "Standard","Legacy","Windows" ) { It "Should handle spaces between escaped quotes (ArgumentList=${PSNativeCommandArgumentPassing})" { $lines = testexe -echoargs 'a\"b c\"d' "a\`"b c\`"d" $lines.Count | Should -Be 2 - if (($EnabledExperimentalFeatures -contains 'PSNativeCommandArgumentPassing') -and $PSNativeCommandArgumentPassing -ne "Legacy") { + if ($PSNativeCommandArgumentPassing -ne "Legacy") { $lines[0] | Should -BeExactly 'Arg 0 is ' $lines[1] | Should -BeExactly 'Arg 1 is ' } From 61b5dceb601ba06178959eeae4ac00bd2e838cd5 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Mon, 12 Sep 2022 10:23:03 -0700 Subject: [PATCH 055/779] Make experimental feature `PSAnsiRenderingFileInfo` stable (#18042) --- experimental-feature-linux.json | 1 - experimental-feature-windows.json | 1 - .../ExperimentalFeature.cs | 3 - .../namespaces/FileSystemProvider.cs | 55 ++++++++----------- .../Get-Item.Tests.ps1 | 13 ----- 5 files changed, 22 insertions(+), 51 deletions(-) diff --git a/experimental-feature-linux.json b/experimental-feature-linux.json index a71c0c3ed21..94d88a4a8da 100644 --- a/experimental-feature-linux.json +++ b/experimental-feature-linux.json @@ -1,5 +1,4 @@ [ - "PSAnsiRenderingFileInfo", "PSCommandNotFoundSuggestion", "PSLoadAssemblyFromNativeCode", "PSNativeCommandErrorActionPreference", diff --git a/experimental-feature-windows.json b/experimental-feature-windows.json index a71c0c3ed21..94d88a4a8da 100644 --- a/experimental-feature-windows.json +++ b/experimental-feature-windows.json @@ -1,5 +1,4 @@ [ - "PSAnsiRenderingFileInfo", "PSCommandNotFoundSuggestion", "PSLoadAssemblyFromNativeCode", "PSNativeCommandErrorActionPreference", diff --git a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs index 8c3e1c070ec..6caea95de54 100644 --- a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs +++ b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs @@ -114,9 +114,6 @@ static ExperimentalFeature() new ExperimentalFeature( name: "PSLoadAssemblyFromNativeCode", description: "Expose an API to allow assembly loading from native code"), - new ExperimentalFeature( - name: "PSAnsiRenderingFileInfo", - description: "Enable coloring for FileInfo objects"), new ExperimentalFeature( name: PSNativeCommandErrorActionPreferenceFeatureName, description: "Native commands with non-zero exit codes issue errors according to $ErrorActionPreference when $PSNativeCommandUseErrorActionPreference is $true"), diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index 3c0aeaddc7b..07625fc2ab0 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -2068,43 +2068,32 @@ string ToModeString(FileSystemInfo fileSystemInfo) /// Name if a file or directory, Name -> Target if symlink. public static string NameString(PSObject instance) { - if (ExperimentalFeature.IsEnabled("PSAnsiRenderingFileInfo")) + if (instance?.BaseObject is FileSystemInfo fileInfo) { - if (instance?.BaseObject is FileSystemInfo fileInfo) + if (InternalSymbolicLinkLinkCodeMethods.IsReparsePointLikeSymlink(fileInfo)) { - if (InternalSymbolicLinkLinkCodeMethods.IsReparsePointLikeSymlink(fileInfo)) - { - return $"{PSStyle.Instance.FileInfo.SymbolicLink}{fileInfo.Name}{PSStyle.Instance.Reset} -> {fileInfo.LinkTarget}"; - } - else if (fileInfo.Attributes.HasFlag(FileAttributes.Directory)) - { - return $"{PSStyle.Instance.FileInfo.Directory}{fileInfo.Name}{PSStyle.Instance.Reset}"; - } - else if (PSStyle.Instance.FileInfo.Extension.ContainsKey(fileInfo.Extension)) - { - return $"{PSStyle.Instance.FileInfo.Extension[fileInfo.Extension]}{fileInfo.Name}{PSStyle.Instance.Reset}"; - } - else if ((Platform.IsWindows && CommandDiscovery.PathExtensions.Contains(fileInfo.Extension.ToLower())) || - (!Platform.IsWindows && Platform.NonWindowsIsExecutable(fileInfo.FullName))) - { - return $"{PSStyle.Instance.FileInfo.Executable}{fileInfo.Name}{PSStyle.Instance.Reset}"; - } - else - { - return fileInfo.Name; - } + return $"{PSStyle.Instance.FileInfo.SymbolicLink}{fileInfo.Name}{PSStyle.Instance.Reset} -> {fileInfo.LinkTarget}"; + } + else if (fileInfo.Attributes.HasFlag(FileAttributes.Directory)) + { + return $"{PSStyle.Instance.FileInfo.Directory}{fileInfo.Name}{PSStyle.Instance.Reset}"; + } + else if (PSStyle.Instance.FileInfo.Extension.ContainsKey(fileInfo.Extension)) + { + return $"{PSStyle.Instance.FileInfo.Extension[fileInfo.Extension]}{fileInfo.Name}{PSStyle.Instance.Reset}"; + } + else if ((Platform.IsWindows && CommandDiscovery.PathExtensions.Contains(fileInfo.Extension.ToLower())) || + (!Platform.IsWindows && Platform.NonWindowsIsExecutable(fileInfo.FullName))) + { + return $"{PSStyle.Instance.FileInfo.Executable}{fileInfo.Name}{PSStyle.Instance.Reset}"; + } + else + { + return fileInfo.Name; } - - return string.Empty; - } - else - { - return instance?.BaseObject is FileSystemInfo fileInfo - ? InternalSymbolicLinkLinkCodeMethods.IsReparsePointLikeSymlink(fileInfo) - ? $"{fileInfo.Name} -> {fileInfo.LinkTarget}" - : fileInfo.Name - : string.Empty; } + + return string.Empty; } /// diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Item.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Item.Tests.ps1 index 35c05b1bb12..4efc250e0d7 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Item.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Item.Tests.ps1 @@ -208,17 +208,12 @@ Describe "Get-Item environment provider on Windows with accidental case-variant Describe 'Formatting for FileInfo objects' -Tags 'CI' { BeforeAll { - $PSDefaultParameterValues.Add('It:Skip', (-not $EnabledExperimentalFeatures.Contains('PSAnsiRenderingFileInfo'))) $extensionTests = [System.Collections.Generic.List[HashTable]]::new() foreach ($extension in @('.zip', '.tgz', '.tar', '.gz', '.nupkg', '.cab', '.7z', '.ps1', '.psd1', '.psm1', '.ps1xml')) { $extensionTests.Add(@{extension = $extension}) } } - AfterAll { - $PSDefaultParameterValues.Remove('It:Skip') - } - It 'File type should have correct color' -TestCases $extensionTests { param($extension) @@ -250,14 +245,6 @@ Describe 'Formatting for FileInfo objects' -Tags 'CI' { } Describe 'Formatting for FileInfo requiring admin' -Tags 'CI','RequireAdminOnWindows' { - BeforeAll { - $PSDefaultParameterValues.Add('It:Skip', (-not $EnabledExperimentalFeatures.Contains('PSAnsiRenderingFileInfo'))) - } - - AfterAll { - $PSDefaultParameterValues.Remove('It:Skip') - } - It 'Symlink should have correct color' { $linkPath = Join-Path -Path $TestDrive -ChildPath 'link' $link = New-Item -ItemType SymbolicLink -Name 'link' -Value $TestDrive -Path $TestDrive From fb9393e0ccc83e381e9deebeb1b1da5a3ee2e8f4 Mon Sep 17 00:00:00 2001 From: MartinGC94 <42123497+MartinGC94@users.noreply.github.com> Date: Mon, 12 Sep 2022 20:34:15 +0200 Subject: [PATCH 056/779] Improve pseudo binding for dynamic parameters (#18030) --- .../PseudoParameterBinder.cs | 43 ++++++++++++++++--- .../TabCompletion/TabCompletion.Tests.ps1 | 5 +++ 2 files changed, 41 insertions(+), 7 deletions(-) diff --git a/src/System.Management.Automation/engine/CommandCompletion/PseudoParameterBinder.cs b/src/System.Management.Automation/engine/CommandCompletion/PseudoParameterBinder.cs index 97b39cf39f5..a581a11af92 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/PseudoParameterBinder.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/PseudoParameterBinder.cs @@ -1211,9 +1211,6 @@ private bool PrepareCommandElements(ExecutionContext context) bool implementsDynamicParameters = commandProcessor != null && commandProcessor.CommandInfo.ImplementsDynamicParameters; - var argumentsToGetDynamicParameters = implementsDynamicParameters - ? new List(_commandElements.Count) - : null; if (commandProcessor != null || scriptProcessor != null) { // Pre-processing the arguments -- command arguments @@ -1222,7 +1219,32 @@ private bool PrepareCommandElements(ExecutionContext context) var parameter = _commandElements[commandIndex] as CommandParameterAst; if (parameter != null) { - argumentsToGetDynamicParameters?.Add(parameter.Extent.Text); + if (implementsDynamicParameters) + { + CommandParameterInternal paramToAdd; + if (parameter.Argument is null) + { + paramToAdd = CommandParameterInternal.CreateParameter(parameter.ParameterName, parameter.Extent.Text); + } + else + { + object value; + if (!SafeExprEvaluator.TrySafeEval(parameter.Argument, context, out value)) + { + value = parameter.Argument.Extent.Text; + } + + paramToAdd = CommandParameterInternal.CreateParameterWithArgument( + parameterAst: null, + parameterName: parameter.ParameterName, + parameterText: parameter.Extent.Text, + argumentAst: null, + value: value, + spaceAfterParameter: false); + } + + commandProcessor.AddParameter(paramToAdd); + } AstPair parameterArg = parameter.Argument != null ? new AstPair(parameter) @@ -1248,7 +1270,11 @@ private bool PrepareCommandElements(ExecutionContext context) } else if (_commandElements[commandIndex] is ExpressionAst expression) { - valueToAdd = expression.Extent.Text; + if (!SafeExprEvaluator.TrySafeEval(expression, context, out valueToAdd)) + { + valueToAdd = expression.Extent.Text; + } + expressionToAdd = expression; } else @@ -1256,7 +1282,11 @@ private bool PrepareCommandElements(ExecutionContext context) continue; } - argumentsToGetDynamicParameters?.Add(valueToAdd); + if (implementsDynamicParameters) + { + commandProcessor.AddParameter(CommandParameterInternal.CreateArgument(valueToAdd)); + } + _arguments.Add(new AstPair(null, expressionToAdd)); } } @@ -1267,7 +1297,6 @@ private bool PrepareCommandElements(ExecutionContext context) _function = false; if (implementsDynamicParameters) { - ParameterBinderController.AddArgumentsToCommandProcessor(commandProcessor, argumentsToGetDynamicParameters.ToArray()); bool retryWithNoArgs = false, alreadyRetried = false; do diff --git a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 index 725b47138c0..5a93d1307ad 100644 --- a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 +++ b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 @@ -597,6 +597,11 @@ ConstructorTestClass(int i, bool b) $res.CompletionMatches[0].CompletionText | Should -BeExactly '-Directory' } + it 'Should complete dynamic parameters while providing values to non-string parameters' { + $res = TabExpansion2 -inputScript 'Get-Content -Path $HOME -Verbose:$false -' + $res.CompletionMatches.CompletionText | Should -Contain '-Raw' + } + It 'Should enumerate types when completing member names for Select-Object' { $TestString = '"Hello","World" | select-object ' $res = TabExpansion2 -inputScript $TestString From 944ed5413d56e778cee888da0195ec0cbb69113f Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Mon, 12 Sep 2022 11:41:57 -0700 Subject: [PATCH 057/779] Revert "Add `-StrictMode` to `Invoke-Command` to allow specifying strict mode when invoking command locally" (#18040) --- experimental-feature-linux.json | 1 - experimental-feature-windows.json | 1 - .../ExperimentalFeature.cs | 4 - .../remoting/commands/InvokeCommandCommand.cs | 122 ++---------------- .../Invoke-Command.Tests.ps1 | 41 ------ 5 files changed, 13 insertions(+), 156 deletions(-) delete mode 100644 test/powershell/Modules/Microsoft.PowerShell.Core/Invoke-Command.Tests.ps1 diff --git a/experimental-feature-linux.json b/experimental-feature-linux.json index 94d88a4a8da..4dee9496504 100644 --- a/experimental-feature-linux.json +++ b/experimental-feature-linux.json @@ -2,6 +2,5 @@ "PSCommandNotFoundSuggestion", "PSLoadAssemblyFromNativeCode", "PSNativeCommandErrorActionPreference", - "PSStrictModeAssignment", "PSSubsystemPluginModel" ] diff --git a/experimental-feature-windows.json b/experimental-feature-windows.json index 94d88a4a8da..4dee9496504 100644 --- a/experimental-feature-windows.json +++ b/experimental-feature-windows.json @@ -2,6 +2,5 @@ "PSCommandNotFoundSuggestion", "PSLoadAssemblyFromNativeCode", "PSNativeCommandErrorActionPreference", - "PSStrictModeAssignment", "PSSubsystemPluginModel" ] diff --git a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs index 6caea95de54..8eaf3822075 100644 --- a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs +++ b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs @@ -22,7 +22,6 @@ public class ExperimentalFeature internal const string EngineSource = "PSEngine"; internal const string PSNativeCommandErrorActionPreferenceFeatureName = "PSNativeCommandErrorActionPreference"; - internal const string PSStrictModeAssignment = "PSStrictModeAssignment"; #endregion @@ -117,9 +116,6 @@ static ExperimentalFeature() new ExperimentalFeature( name: PSNativeCommandErrorActionPreferenceFeatureName, description: "Native commands with non-zero exit codes issue errors according to $ErrorActionPreference when $PSNativeCommandUseErrorActionPreference is $true"), - new ExperimentalFeature( - name: PSStrictModeAssignment, - description: "Add support of setting Strict-Mode with Invoke-Command"), }; EngineExperimentalFeatures = new ReadOnlyCollection(engineFeatures); diff --git a/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs b/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs index 804355d2e8d..a2a2397cb7a 100644 --- a/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs @@ -263,72 +263,6 @@ public override SwitchParameter UseSSL } } - private sealed class ArgumentToPSVersionTransformationAttribute : ArgumentToVersionTransformationAttribute - { - protected override bool TryConvertFromString(string versionString, [NotNullWhen(true)] out Version version) - { - if (string.Equals("off", versionString, StringComparison.OrdinalIgnoreCase)) - { - version = new Version(0, 0); - return true; - } - - if (string.Equals("latest", versionString, StringComparison.OrdinalIgnoreCase)) - { - version = PSVersionInfo.PSVersion; - return true; - } - - return base.TryConvertFromString(versionString, out version); - } - } - - private static readonly Version s_OffVersion = new Version(0, 0); - - private sealed class ValidateVersionAttribute : ValidateArgumentsAttribute - { - protected override void Validate(object arguments, EngineIntrinsics engineIntrinsics) - { - Version version = arguments as Version; - if (version == s_OffVersion) - { - return; - } - - if (version == null || !PSVersionInfo.IsValidPSVersion(version)) - { - // No conversion succeeded so throw an exception... - throw new ValidationMetadataException( - "InvalidPSVersion", - null, - Metadata.ValidateVersionFailure, - arguments); - } - } - } - - /// - /// Gets or sets strict mode. - /// - [Experimental(ExperimentalFeature.PSStrictModeAssignment, ExperimentAction.Show)] - [Parameter(ParameterSetName = InvokeCommandCommand.InProcParameterSet)] - [ArgumentToPSVersionTransformation] - [ValidateVersion] - public Version StrictMode - { - get - { - return _strictmodeversion; - } - - set - { - _strictmodeversion = value; - } - } - - private Version _strictmodeversion = null; - /// /// For WSMan session: /// If this parameter is not specified then the value specified in @@ -908,8 +842,6 @@ public virtual SwitchParameter RemoteDebug #endregion - private Version _savedStrictModeVersion; - #endregion Parameters #region Overrides @@ -1033,12 +965,6 @@ protected override void BeginProcessing() } } - if (_strictmodeversion != null) - { - _savedStrictModeVersion = Context.EngineSessionState.CurrentScope.StrictModeVersion; - Context.EngineSessionState.CurrentScope.StrictModeVersion = _strictmodeversion; - } - return; } @@ -1255,19 +1181,7 @@ protected override void ProcessRecord() } else if (ParameterSetName.Equals(InvokeCommandCommand.InProcParameterSet) && (_steppablePipeline != null)) { - try - { - _steppablePipeline.Process(InputObject); - } - catch - { - if (_strictmodeversion != null) - { - Context.EngineSessionState.CurrentScope.StrictModeVersion = _savedStrictModeVersion; - } - - throw; - } + _steppablePipeline.Process(InputObject); } else { @@ -1298,30 +1212,20 @@ protected override void EndProcessing() { if (ParameterSetName.Equals(InvokeCommandCommand.InProcParameterSet)) { - try - { - if (_steppablePipeline != null) - { - _steppablePipeline.End(); - } - else - { - ScriptBlock.InvokeUsingCmdlet( - contextCmdlet: this, - useLocalScope: !NoNewScope, - errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, - dollarUnder: AutomationNull.Value, - input: _input, - scriptThis: AutomationNull.Value, - args: ArgumentList); - } + if (_steppablePipeline != null) + { + _steppablePipeline.End(); } - finally + else { - if (_strictmodeversion != null) - { - Context.EngineSessionState.CurrentScope.StrictModeVersion = _savedStrictModeVersion; - } + ScriptBlock.InvokeUsingCmdlet( + contextCmdlet: this, + useLocalScope: !NoNewScope, + errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, + dollarUnder: AutomationNull.Value, + input: _input, + scriptThis: AutomationNull.Value, + args: ArgumentList); } } else diff --git a/test/powershell/Modules/Microsoft.PowerShell.Core/Invoke-Command.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Core/Invoke-Command.Tests.ps1 deleted file mode 100644 index 1765e5d8217..00000000000 --- a/test/powershell/Modules/Microsoft.PowerShell.Core/Invoke-Command.Tests.ps1 +++ /dev/null @@ -1,41 +0,0 @@ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. - -Describe "Invoke-Command" -Tags "CI" { - Context "StrictMode tests" { - BeforeAll { - $skipTest = !($EnabledExperimentalFeatures -contains "PSStrictModeAssignment"); - If (Test-Path Variable:InvokeCommand__Test) { - Remove-Item Variable:InvokeCommand__Test - } - } - - It "Setting -StrictMode parameter with uninitialized variable throws error" -skip:$skipTest { - { Invoke-Command -StrictMode 3.0 {$InvokeCommand__Test} } | Should -Throw -ErrorId 'VariableIsUndefined' - } - - It "Setting -StrictMode parameter with initialized variable does not throw error" -skip:$skipTest { - $InvokeCommand__Test = 'Something' - Invoke-Command -StrictMode 3.0 {$InvokeCommand__Test} | Should -Be 'Something' - Remove-Item Variable:InvokeCommand__Test - } - - It "-StrictMode parameter sets StrictMode back to original state after process completes" -skip:$skipTest { - { Invoke-Command -StrictMode 3.0 {$InvokeCommand__Test} } | Should -Throw -ErrorId 'VariableIsUndefined' - { Invoke-Command {$InvokeCommand__Test} } | Should -Not -Throw - } - - It "-StrictMode parameter works on piped input" -skip:$skipTest { - "There" | Invoke-Command -ScriptBlock { "Hello $input" } -StrictMode 3.0 | Should -Be 'Hello There' - { "There" | Invoke-Command -ScriptBlock { "Hello $InvokeCommand__Test" } -StrictMode 3.0 } | Should -Throw -ErrorId 'VariableIsUndefined' - } - - It "-StrictMode latest works" -skip:$skipTest { - { Invoke-Command -StrictMode latest {$InvokeCommand__Test} } | Should -Throw -ErrorId 'VariableIsUndefined' - } - - It "-StrictMode off works" -skip:$skipTest { - { Invoke-Command -StrictMode off {$InvokeCommand__Test} } | Should -Not -Throw - } - } -} From 2ec7aea2ec18d8729dfd9d57c321b05dc97a6737 Mon Sep 17 00:00:00 2001 From: creative-cloud <1001alphatest@gmail.com> Date: Tue, 13 Sep 2022 09:46:52 -0700 Subject: [PATCH 058/779] Fixing `CA2014` warnings and removing the warning suppressions (#17982) --- .../commands/management/Process.cs | 72 +++++++++---------- .../host/msh/ConsoleControl.cs | 48 +++++-------- .../host/msh/ConsoleHostUserInterface.cs | 17 +++-- 3 files changed, 60 insertions(+), 77 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs index 7cbd1eea1f3..fdf3917965d 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs @@ -743,51 +743,46 @@ private static string RetrieveProcessUserName(Process process) try { - do - { - int error; - if (!Win32Native.OpenProcessToken(process.Handle, TOKEN_QUERY, out processTokenHandler)) { break; } + int error; + if (!Win32Native.OpenProcessToken(process.Handle, TOKEN_QUERY, out processTokenHandler)) { return null; } - // Set the default length to be 256, so it will be sufficient for most cases. - int tokenInfoLength = 256; - tokenUserInfo = Marshal.AllocHGlobal(tokenInfoLength); - if (!Win32Native.GetTokenInformation(processTokenHandler, Win32Native.TOKEN_INFORMATION_CLASS.TokenUser, tokenUserInfo, tokenInfoLength, out tokenInfoLength)) + // Set the default length to be 256, so it will be sufficient for most cases. + int tokenInfoLength = 256; + tokenUserInfo = Marshal.AllocHGlobal(tokenInfoLength); + if (!Win32Native.GetTokenInformation(processTokenHandler, Win32Native.TOKEN_INFORMATION_CLASS.TokenUser, tokenUserInfo, tokenInfoLength, out tokenInfoLength)) + { + error = Marshal.GetLastWin32Error(); + if (error == Win32Native.ERROR_INSUFFICIENT_BUFFER) { - error = Marshal.GetLastWin32Error(); - if (error == Win32Native.ERROR_INSUFFICIENT_BUFFER) - { - Marshal.FreeHGlobal(tokenUserInfo); - tokenUserInfo = Marshal.AllocHGlobal(tokenInfoLength); + Marshal.FreeHGlobal(tokenUserInfo); + tokenUserInfo = Marshal.AllocHGlobal(tokenInfoLength); - if (!Win32Native.GetTokenInformation(processTokenHandler, Win32Native.TOKEN_INFORMATION_CLASS.TokenUser, tokenUserInfo, tokenInfoLength, out tokenInfoLength)) { break; } - } - else - { - break; - } + if (!Win32Native.GetTokenInformation(processTokenHandler, Win32Native.TOKEN_INFORMATION_CLASS.TokenUser, tokenUserInfo, tokenInfoLength, out tokenInfoLength)) { return null; } } - - var tokenUser = Marshal.PtrToStructure(tokenUserInfo); - - // Max username is defined as UNLEN = 256 in lmcons.h - // Max domainname is defined as DNLEN = CNLEN = 15 in lmcons.h - // The buffer length must be +1, last position is for a null string terminator. - int userNameLength = 257; - int domainNameLength = 16; -#pragma warning disable CA2014 - Span userNameStr = stackalloc char[userNameLength]; - Span domainNameStr = stackalloc char[domainNameLength]; -#pragma warning restore CA2014 - Win32Native.SID_NAME_USE accountType; - - // userNameLength and domainNameLength will be set to actual lengths. - if (!Win32Native.LookupAccountSid(null, tokenUser.User.Sid, userNameStr, ref userNameLength, domainNameStr, ref domainNameLength, out accountType)) + else { - break; + return null; } + } + + var tokenUser = Marshal.PtrToStructure(tokenUserInfo); + + // Max username is defined as UNLEN = 256 in lmcons.h + // Max domainname is defined as DNLEN = CNLEN = 15 in lmcons.h + // The buffer length must be +1, last position is for a null string terminator. + int userNameLength = 257; + int domainNameLength = 16; + Span userNameStr = stackalloc char[userNameLength]; + Span domainNameStr = stackalloc char[domainNameLength]; + Win32Native.SID_NAME_USE accountType; - userName = string.Concat(domainNameStr.Slice(0, domainNameLength), "\\", userNameStr.Slice(0, userNameLength)); - } while (false); + // userNameLength and domainNameLength will be set to actual lengths. + if (!Win32Native.LookupAccountSid(null, tokenUser.User.Sid, userNameStr, ref userNameLength, domainNameStr, ref domainNameLength, out accountType)) + { + return null; + } + + userName = string.Concat(domainNameStr.Slice(0, domainNameLength), "\\", userNameStr.Slice(0, userNameLength)); } catch (NotSupportedException) { @@ -817,7 +812,6 @@ private static string RetrieveProcessUserName(Process process) Win32Native.CloseHandle(processTokenHandler); } } - #endif return userName; } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs index d5b81cf4dd9..4ebeb7f92c7 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs @@ -2565,39 +2565,29 @@ internal static void WriteConsole(ConsoleHandle consoleHandle, ReadOnlySpan outBuffer; - while (cursor < output.Length) + while (cursor + MaxBufferSize < output.Length) { - ReadOnlySpan outBuffer; - - if (cursor + MaxBufferSize < output.Length) - { - outBuffer = output.Slice(cursor, MaxBufferSize); - cursor += MaxBufferSize; + outBuffer = output.Slice(cursor, MaxBufferSize); + cursor += MaxBufferSize; + WriteConsole(consoleHandle, outBuffer); + } - WriteConsole(consoleHandle, outBuffer); - } - else - { - outBuffer = output.Slice(cursor); - cursor = output.Length; + outBuffer = output.Slice(cursor); - if (newLine) - { - var endOfLine = Environment.NewLine.AsSpan(); - var endOfLineLength = endOfLine.Length; -#pragma warning disable CA2014 - Span outBufferLine = stackalloc char[outBuffer.Length + endOfLineLength]; -#pragma warning restore CA2014 - outBuffer.CopyTo(outBufferLine); - endOfLine.CopyTo(outBufferLine.Slice(outBufferLine.Length - endOfLineLength)); - WriteConsole(consoleHandle, outBufferLine); - } - else - { - WriteConsole(consoleHandle, outBuffer); - } - } + if (newLine) + { + var endOfLine = Environment.NewLine.AsSpan(); + var endOfLineLength = endOfLine.Length; + Span outBufferLine = stackalloc char[outBuffer.Length + endOfLineLength]; + outBuffer.CopyTo(outBufferLine); + endOfLine.CopyTo(outBufferLine.Slice(outBufferLine.Length - endOfLineLength)); + WriteConsole(consoleHandle, outBufferLine); + } + else + { + WriteConsole(consoleHandle, outBuffer); } } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs index 16c83827221..d755e042984 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs @@ -332,20 +332,19 @@ private object ReadLineSafe(bool isSecureString, char? printToken) Coordinates originalCursorPos = _rawui.CursorPosition; + // + // read one char at a time so that we don't + // end up having a immutable string holding the + // secret in memory. + // + const int CharactersToRead = 1; + Span inputBuffer = stackalloc char[CharactersToRead + 1]; + while (true) { - // - // read one char at a time so that we don't - // end up having a immutable string holding the - // secret in memory. - // #if UNIX ConsoleKeyInfo keyInfo = Console.ReadKey(true); #else - const int CharactersToRead = 1; -#pragma warning disable CA2014 - Span inputBuffer = stackalloc char[CharactersToRead + 1]; -#pragma warning restore CA2014 string key = ConsoleControl.ReadConsole(handle, initialContentLength: 0, inputBuffer, charactersToRead: CharactersToRead, endOnTab: false, out _); #endif From 625fc25909b8fb888913e147d5dbd6be318584b3 Mon Sep 17 00:00:00 2001 From: Sean Wheeler Date: Thu, 15 Sep 2022 12:09:58 -0500 Subject: [PATCH 059/779] Add the `ConfigurationFile` option to the PowerShell help content (#18093) --- .../resources/ManagedEntranceStrings.resx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/ManagedEntranceStrings.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/ManagedEntranceStrings.resx index 845fa0cb047..df68fb8e70a 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/resources/ManagedEntranceStrings.resx +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/ManagedEntranceStrings.resx @@ -145,8 +145,8 @@ Usage: pwsh[.exe] [-Login] [[-File] <filePath> [args]] [-Command { - | <script-block> [-args <arg-array>] | <string> [<CommandParameters>] } ] - [-ConfigurationName <string>] [-CustomPipeName <string>] - [-EncodedCommand <Base64EncodedCommand>] + [-ConfigurationName <string>] [-ConfigurationFile <filePath>] + [-CustomPipeName <string>] [-EncodedCommand <Base64EncodedCommand>] [-ExecutionPolicy <ExecutionPolicy>] [-InputFormat {Text | XML}] [-Interactive] [-MTA] [-NoExit] [-NoLogo] [-NonInteractive] [-NoProfile] [-NoProfileLoadTime] [-OutputFormat {Text | XML}] From d702b52168fbd089fe9de842e3efd86314736d53 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 15 Sep 2022 10:12:00 -0700 Subject: [PATCH 060/779] Bump `Microsoft.CodeAnalysis.NetAnalyzers` (#18096) --- Analyzers.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Analyzers.props b/Analyzers.props index fc2c7adb53d..0c88302c9f5 100644 --- a/Analyzers.props +++ b/Analyzers.props @@ -1,7 +1,7 @@ - + From d0a91470c9c24d95f15bc8f4de199af58c59ca3c Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Thu, 15 Sep 2022 13:34:09 -0700 Subject: [PATCH 061/779] Filter out compiler generated types for `Add-Type -PassThru` (#18095) --- .../commands/utility/AddType.cs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs index 6cdfb512dce..00d6b11efcf 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs @@ -13,6 +13,7 @@ using System.Management.Automation.Internal; using System.Management.Automation.Security; using System.Reflection; +using System.Runtime.CompilerServices; using System.Runtime.Loader; using System.Security; using System.Text; @@ -891,7 +892,14 @@ private IEnumerable GetPortableExecutableReferences private void WriteTypes(Assembly assembly) { - WriteObject(assembly.GetTypes(), true); + foreach (Type type in assembly.GetTypes()) + { + // We only write out types that are not auto-generated by compiler. + if (type.GetCustomAttribute() is null) + { + WriteObject(type); + } + } } #endregion LoadAssembly From 29ddf44892fe4bf65f0e1b0a623aa81e0585c503 Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Thu, 15 Sep 2022 14:12:52 -0700 Subject: [PATCH 062/779] Update `DotnetRuntimeMetadata.json` for .NET 7 RC1 build (#18091) --- DotnetRuntimeMetadata.json | 8 ++--- assets/wix/files.wxs | 30 +++++++++---------- global.json | 2 +- ...soft.PowerShell.Commands.Management.csproj | 2 +- ...crosoft.PowerShell.Commands.Utility.csproj | 6 ++-- ...crosoft.PowerShell.CoreCLR.Eventing.csproj | 2 +- .../Microsoft.PowerShell.SDK.csproj | 20 ++++++------- .../Microsoft.WSMan.Management.csproj | 2 +- .../System.Management.Automation.csproj | 14 ++++----- .../BenchmarkDotNet.Extensions.csproj | 4 +-- .../ResultsComparer/ResultsComparer.csproj | 2 +- test/tools/TestService/TestService.csproj | 2 +- test/tools/WebListener/WebListener.csproj | 4 +-- 13 files changed, 49 insertions(+), 49 deletions(-) diff --git a/DotnetRuntimeMetadata.json b/DotnetRuntimeMetadata.json index 7b07dcc16c3..c13bf52cd59 100644 --- a/DotnetRuntimeMetadata.json +++ b/DotnetRuntimeMetadata.json @@ -1,13 +1,13 @@ { "sdk": { - "channel": "7.0.1xx-preview7", + "channel": "7.0.1xx-rc1", "quality": "daily", "qualityFallback": "preview", - "packageVersionPattern": "7.0.0-preview.7", + "packageVersionPattern": "7.0.0-rc.1", "sdkImageVersion": "7.0.100", - "nextChannel": "7.0.1xx-preview7", + "nextChannel": "7.0.1xx-rc1", "azureFeed": "", - "sdkImageOverride": "" + "sdkImageOverride": "7.0.100-rc.1.22431.12" }, "internalfeed": { "url": "" diff --git a/assets/wix/files.wxs b/assets/wix/files.wxs index 4da5773c5e4..4a9c36ad3d7 100644 --- a/assets/wix/files.wxs +++ b/assets/wix/files.wxs @@ -1587,17 +1587,17 @@ - - - - - - - - + + + + + + + + @@ -3141,9 +3141,6 @@ - - - @@ -3153,6 +3150,9 @@ + + + @@ -4157,15 +4157,15 @@ - - - - + + + + diff --git a/global.json b/global.json index 638ff46a12c..fa6c98cbf9e 100644 --- a/global.json +++ b/global.json @@ -1,5 +1,5 @@ { "sdk": { - "version": "7.0.100-preview.7.22377.5" + "version": "7.0.100-rc.1.22431.12" } } diff --git a/src/Microsoft.PowerShell.Commands.Management/Microsoft.PowerShell.Commands.Management.csproj b/src/Microsoft.PowerShell.Commands.Management/Microsoft.PowerShell.Commands.Management.csproj index 483985aee84..48fcd1861c4 100644 --- a/src/Microsoft.PowerShell.Commands.Management/Microsoft.PowerShell.Commands.Management.csproj +++ b/src/Microsoft.PowerShell.Commands.Management/Microsoft.PowerShell.Commands.Management.csproj @@ -47,7 +47,7 @@ - + diff --git a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj index 13ebe7c3bec..18f9c39df02 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj +++ b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj @@ -31,9 +31,9 @@ - - - + + + diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/Microsoft.PowerShell.CoreCLR.Eventing.csproj b/src/Microsoft.PowerShell.CoreCLR.Eventing/Microsoft.PowerShell.CoreCLR.Eventing.csproj index f61abc2f4c5..36317ba86ee 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/Microsoft.PowerShell.CoreCLR.Eventing.csproj +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/Microsoft.PowerShell.CoreCLR.Eventing.csproj @@ -8,7 +8,7 @@ - + diff --git a/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj b/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj index aa699cf5eb3..e2d6644ae25 100644 --- a/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj +++ b/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj @@ -18,19 +18,19 @@ - - - + + + - - - - - - + + + + + + - + diff --git a/src/Microsoft.WSMan.Management/Microsoft.WSMan.Management.csproj b/src/Microsoft.WSMan.Management/Microsoft.WSMan.Management.csproj index a8010f4d216..0ac640d196e 100644 --- a/src/Microsoft.WSMan.Management/Microsoft.WSMan.Management.csproj +++ b/src/Microsoft.WSMan.Management/Microsoft.WSMan.Management.csproj @@ -10,7 +10,7 @@ - + diff --git a/src/System.Management.Automation/System.Management.Automation.csproj b/src/System.Management.Automation/System.Management.Automation.csproj index 602c5fbffad..03414ef381b 100644 --- a/src/System.Management.Automation/System.Management.Automation.csproj +++ b/src/System.Management.Automation/System.Management.Automation.csproj @@ -16,16 +16,16 @@ - - - + + + - + - - - + + + diff --git a/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/BenchmarkDotNet.Extensions.csproj b/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/BenchmarkDotNet.Extensions.csproj index f0c3a35115e..02a372fa115 100644 --- a/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/BenchmarkDotNet.Extensions.csproj +++ b/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/BenchmarkDotNet.Extensions.csproj @@ -6,8 +6,8 @@ - - + + diff --git a/test/perf/dotnet-tools/ResultsComparer/ResultsComparer.csproj b/test/perf/dotnet-tools/ResultsComparer/ResultsComparer.csproj index 3180d45b64a..c40f05d7b77 100644 --- a/test/perf/dotnet-tools/ResultsComparer/ResultsComparer.csproj +++ b/test/perf/dotnet-tools/ResultsComparer/ResultsComparer.csproj @@ -9,7 +9,7 @@ - + diff --git a/test/tools/TestService/TestService.csproj b/test/tools/TestService/TestService.csproj index 579c339efc5..3b8ded97a05 100644 --- a/test/tools/TestService/TestService.csproj +++ b/test/tools/TestService/TestService.csproj @@ -13,7 +13,7 @@ - + diff --git a/test/tools/WebListener/WebListener.csproj b/test/tools/WebListener/WebListener.csproj index 0b42550cd48..972638cbba0 100644 --- a/test/tools/WebListener/WebListener.csproj +++ b/test/tools/WebListener/WebListener.csproj @@ -7,8 +7,8 @@ - - + + From 1b79395fcafca73959eea874bef10b46f4e2e72a Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Thu, 15 Sep 2022 14:13:40 -0700 Subject: [PATCH 063/779] Update the cgmanifest (#18088) --- tools/cgmanifest.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tools/cgmanifest.json b/tools/cgmanifest.json index 0e91c06fca1..836d81c5b9d 100644 --- a/tools/cgmanifest.json +++ b/tools/cgmanifest.json @@ -765,7 +765,7 @@ "Type": "nuget", "Nuget": { "Name": "System.Configuration.ConfigurationManager", - "Version": "6.0.0" + "Version": "6.0.1" } }, "DevelopmentDependency": false @@ -775,7 +775,7 @@ "Type": "nuget", "Nuget": { "Name": "System.Data.Odbc", - "Version": "6.0.0" + "Version": "6.0.1" } }, "DevelopmentDependency": false From f56c4ea9efc67932bce3e374efbea7ed65689557 Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Thu, 15 Sep 2022 16:17:23 -0700 Subject: [PATCH 064/779] Re-enable building with Ready-to-Run (#18105) --- PowerShell.Common.props | 3 +-- test/powershell/Host/Startup.Tests.ps1 | 1 - 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/PowerShell.Common.props b/PowerShell.Common.props index 593570c3589..cf5c11c9ed2 100644 --- a/PowerShell.Common.props +++ b/PowerShell.Common.props @@ -137,9 +137,8 @@ net7.0 10.0 - + true true true diff --git a/test/powershell/Host/Startup.Tests.ps1 b/test/powershell/Host/Startup.Tests.ps1 index 47ad858a801..ddaa2736a5c 100644 --- a/test/powershell/Host/Startup.Tests.ps1 +++ b/test/powershell/Host/Startup.Tests.ps1 @@ -70,7 +70,6 @@ Describe "Validate start of console host" -Tag CI { else { $allowedAssemblies += @( 'System.Net.Sockets.dll' - 'System.Reflection.Emit.dll' ) } From 1a825747436e8703b6db3a13a92be91154e9e93b Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Thu, 15 Sep 2022 17:35:56 -0700 Subject: [PATCH 065/779] Treat `[NullString]::Value` as the string type when resolving methods (#18080) --- .../engine/CoreAdapter.cs | 35 ++++++++++------- .../engine/runtime/Binding/Binders.cs | 28 +++++++++----- .../Scripting/Scripting.Followup.Tests.ps1 | 38 +++++++++++++++++++ 3 files changed, 78 insertions(+), 23 deletions(-) diff --git a/src/System.Management.Automation/engine/CoreAdapter.cs b/src/System.Management.Automation/engine/CoreAdapter.cs index 498cc261e29..b99311baa4a 100644 --- a/src/System.Management.Automation/engine/CoreAdapter.cs +++ b/src/System.Management.Automation/engine/CoreAdapter.cs @@ -833,7 +833,7 @@ private static Type GetArgumentType(object argument, bool isByRefParameter) return GetArgumentType(PSObject.Base(psref.Value), isByRefParameter: false); } - return argument.GetType(); + return GetObjectType(argument, debase: false); } internal static ConversionRank GetArgumentConversionRank(object argument, Type parameterType, bool isByRef, bool allowCastingToByRefLikeType) @@ -1670,18 +1670,21 @@ private static MethodInformation FindBestMethodImpl( internal static Type EffectiveArgumentType(object arg) { - if (arg != null) + arg = PSObject.Base(arg); + if (arg is null) { - arg = PSObject.Base(arg); - object[] argAsArray = arg as object[]; - if (argAsArray != null && argAsArray.Length > 0 && PSObject.Base(argAsArray[0]) != null) + return typeof(LanguagePrimitives.Null); + } + + if (arg is object[] array && array.Length > 0) + { + Type firstType = GetObjectType(array[0], debase: true); + if (firstType is not null) { - Type firstType = PSObject.Base(argAsArray[0]).GetType(); bool allSameType = true; - - for (int j = 1; j < argAsArray.Length; ++j) + for (int j = 1; j < array.Length; ++j) { - if (argAsArray[j] == null || firstType != PSObject.Base(argAsArray[j]).GetType()) + if (firstType != GetObjectType(array[j], debase: true)) { allSameType = false; break; @@ -1693,13 +1696,19 @@ internal static Type EffectiveArgumentType(object arg) return firstType.MakeArrayType(); } } - - return arg.GetType(); } - else + + return GetObjectType(arg, debase: false); + } + + internal static Type GetObjectType(object obj, bool debase) + { + if (debase) { - return typeof(LanguagePrimitives.Null); + obj = PSObject.Base(obj); } + + return obj == NullString.Value ? typeof(string) : obj?.GetType(); } internal static void SetReferences(object[] arguments, MethodInformation methodInformation, object[] originalArguments) diff --git a/src/System.Management.Automation/engine/runtime/Binding/Binders.cs b/src/System.Management.Automation/engine/runtime/Binding/Binders.cs index 8662cc72ecd..76bc2bfd696 100644 --- a/src/System.Management.Automation/engine/runtime/Binding/Binders.cs +++ b/src/System.Management.Automation/engine/runtime/Binding/Binders.cs @@ -7349,11 +7349,15 @@ internal static bool IsHomogenousArray(object[] args) return false; } - return args.All(element => - { - var obj = PSObject.Base(element); - return obj != null && obj.GetType().Equals(typeof(T)); - }); + foreach (object element in args) + { + if (Adapter.GetObjectType(element, debase: true) != typeof(T)) + { + return false; + } + } + + return true; } internal static bool IsHeterogeneousArray(object[] args) @@ -7381,11 +7385,15 @@ internal static bool IsHeterogeneousArray(object[] args) return true; } - return args.Skip(1).Any(element => - { - var obj = PSObject.Base(element); - return obj == null || !firstType.Equals(obj.GetType()); - }); + for (int i = 1; i < args.Length; i++) + { + if (Adapter.GetObjectType(args[i], debase: true) != firstType) + { + return true; + } + } + + return false; } internal static object InvokeAdaptedMember(object obj, string methodName, object[] args) diff --git a/test/powershell/Language/Scripting/Scripting.Followup.Tests.ps1 b/test/powershell/Language/Scripting/Scripting.Followup.Tests.ps1 index 0d4e8245e2c..960c739499d 100644 --- a/test/powershell/Language/Scripting/Scripting.Followup.Tests.ps1 +++ b/test/powershell/Language/Scripting/Scripting.Followup.Tests.ps1 @@ -90,4 +90,42 @@ Describe "Scripting.Followup.Tests" -Tags "CI" { TestFunc2 | Should -Be @("1", "2") } + + It "'[NullString]::Value' should be treated as string type when resolving .NET method" { + $testType = 'NullStringTest' -as [type] + if (-not $testType) { + Add-Type -TypeDefinition @' +using System; +public class NullStringTest { + public static string Test(bool argument) + { + return "bool"; + } + + public static string Test(string argument) + { + return "string"; + } + + public static string Get(T argument) + { + string ret = typeof(T).FullName; + if (argument is string[] array) + { + if (array[1] == null) + { + return ret + "; 2nd element is NULL"; + } + } + + return ret; + } +} +'@ + } + + [NullStringTest]::Test([NullString]::Value) | Should -BeExactly 'string' + [NullStringTest]::Get([NullString]::Value) | Should -BeExactly 'System.String' + [NullStringTest]::Get(@('foo', [NullString]::Value, 'bar')) | Should -BeExactly 'System.String[]; 2nd element is NULL' + } } From 1847e86b9ac493ee2870220d39321de46c4f0195 Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Fri, 16 Sep 2022 10:11:54 -0700 Subject: [PATCH 066/779] Update `WriteConsole` to not use `stackalloc` for buffer with too large size (#18084) --- .../host/msh/ConsoleControl.cs | 64 +++++++++++-------- 1 file changed, 38 insertions(+), 26 deletions(-) diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs index 4ebeb7f92c7..e5197d77ae9 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs @@ -10,9 +10,9 @@ // On the use of DangerousGetHandle: If the handle has been invalidated, then the API we pass it to will return an error. These // handles should not be exposed to recycling attacks (because they are not exposed at all), but if they were, the worse they // could do is diddle with the console buffer. -#pragma warning disable 1634, 1691 using System; +using System.Buffers; using System.Text; using System.Runtime.InteropServices; using System.Management.Automation; @@ -1479,9 +1479,7 @@ private static void WriteConsoleOutputCJK(ConsoleHandle consoleHandle, Coordinat bSize.X++; SMALL_RECT wRegion = writeRegion; wRegion.Right++; - // Suppress the PreFAST warning about not using Marshal.GetLastWin32Error() to - // get the error code. -#pragma warning disable 56523 + result = NativeMethods.WriteConsoleOutput( consoleHandle.DangerousGetHandle(), characterBuffer, @@ -1491,9 +1489,6 @@ private static void WriteConsoleOutputCJK(ConsoleHandle consoleHandle, Coordinat } else { - // Suppress the PreFAST warning about not using Marshal.GetLastWin32Error() to - // get the error code. -#pragma warning disable 56523 result = NativeMethods.WriteConsoleOutput( consoleHandle.DangerousGetHandle(), characterBuffer, @@ -1796,9 +1791,7 @@ private static bool ReadConsoleOutputCJKSmall readRegion.Top = (short)origin.Y; readRegion.Right = (short)(origin.X + bufferSize.X - 1); readRegion.Bottom = (short)(origin.Y + bufferSize.Y - 1); - // Suppress the PreFAST warning about not using Marshal.GetLastWin32Error() to - // get the error code. -#pragma warning disable 56523 + bool result = NativeMethods.ReadConsoleOutput( consoleHandle.DangerousGetHandle(), characterBuffer, @@ -2474,9 +2467,6 @@ internal static string GetConsoleWindowTitle() DWORD result; StringBuilder consoleTitle = new StringBuilder((int)bufferSize); - // Suppress the PreFAST warning about not using Marshal.GetLastWin32Error() to - // get the error code. -#pragma warning disable 56523 result = NativeMethods.GetConsoleTitle(consoleTitle, bufferSize); // If the result is zero, it may mean and error but it may also mean // that the window title has been set to null. Since we can't tell the @@ -2561,12 +2551,16 @@ internal static void WriteConsole(ConsoleHandle consoleHandle, ReadOnlySpan outBuffer; + // In case that a new line is required, we try to write out the last chunk and the new-line string together, + // to avoid one extra call to 'WriteConsole' just for a new line string. while (cursor + MaxBufferSize < output.Length) { outBuffer = output.Slice(cursor, MaxBufferSize); @@ -2575,19 +2569,37 @@ internal static void WriteConsole(ConsoleHandle consoleHandle, ReadOnlySpan buffer = size <= MaxStackAllocSize ? stackalloc char[size] : default; - if (newLine) + try { - var endOfLine = Environment.NewLine.AsSpan(); - var endOfLineLength = endOfLine.Length; - Span outBufferLine = stackalloc char[outBuffer.Length + endOfLineLength]; - outBuffer.CopyTo(outBufferLine); - endOfLine.CopyTo(outBufferLine.Slice(outBufferLine.Length - endOfLineLength)); - WriteConsole(consoleHandle, outBufferLine); + if (buffer.IsEmpty) + { + rentedArray = ArrayPool.Shared.Rent(size); + buffer = rentedArray.AsSpan().Slice(0, size); + } + + outBuffer.CopyTo(buffer); + lineEnding.CopyTo(buffer.Slice(outBuffer.Length)); + WriteConsole(consoleHandle, buffer); } - else + finally { - WriteConsole(consoleHandle, outBuffer); + if (rentedArray is not null) + { + ArrayPool.Shared.Return(rentedArray); + } } } From d3d81c3e4453b0c03307fb488e1b60761edb7ce9 Mon Sep 17 00:00:00 2001 From: Christoph Bergmeister Date: Mon, 19 Sep 2022 19:16:21 +0100 Subject: [PATCH 067/779] Display download progress in human readable format for `Invoke-WebRequest` (#14611) --- .../Common/InvokeRestMethodCommand.Common.cs | 2 +- .../Common/WebResponseObject.Common.cs | 2 +- .../InvokeWebRequestCommand.CoreClr.cs | 8 +++- .../utility/WebCmdlet/StreamHelper.cs | 44 ++++++++++++++----- .../resources/WebCmdletStrings.resx | 8 ++-- .../engine/Utils.cs | 18 ++++++-- test/xUnit/csharp/test_Utils.cs | 17 +++++++ 7 files changed, 78 insertions(+), 21 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs index 8c1ec228bb4..0970ae46e8f 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs @@ -458,7 +458,7 @@ internal override void ProcessResponse(HttpResponseMessage response) } else if (ShouldSaveToOutFile) { - StreamHelper.SaveStreamToFile(baseResponseStream, QualifiedOutFile, this, _cancelToken.Token); + StreamHelper.SaveStreamToFile(baseResponseStream, QualifiedOutFile, this, response.Content.Headers.ContentLength.GetValueOrDefault(), _cancelToken.Token); } if (!string.IsNullOrEmpty(StatusCodeVariable)) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebResponseObject.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebResponseObject.Common.cs index 1d80bcfdb2b..6f9c14638f9 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebResponseObject.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebResponseObject.Common.cs @@ -204,7 +204,7 @@ private void SetResponse(HttpResponseMessage response, Stream contentStream) } int initialCapacity = (int)Math.Min(contentLength, StreamHelper.DefaultReadBuffer); - _rawContentStream = new WebResponseContentMemoryStream(st, initialCapacity, null); + _rawContentStream = new WebResponseContentMemoryStream(st, initialCapacity, cmdlet: null, response.Content.Headers.ContentLength.GetValueOrDefault()); } // set the position of the content stream to the beginning _rawContentStream.Position = 0; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/InvokeWebRequestCommand.CoreClr.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/InvokeWebRequestCommand.CoreClr.cs index 1a46d074048..f13ad1aa4a3 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/InvokeWebRequestCommand.CoreClr.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/InvokeWebRequestCommand.CoreClr.cs @@ -38,7 +38,11 @@ internal override void ProcessResponse(HttpResponseMessage response) if (ShouldWriteToPipeline) { // creating a MemoryStream wrapper to response stream here to support IsStopping. - responseStream = new WebResponseContentMemoryStream(responseStream, StreamHelper.ChunkSize, this); + responseStream = new WebResponseContentMemoryStream( + responseStream, + StreamHelper.ChunkSize, + this, + response.Content.Headers.ContentLength.GetValueOrDefault()); WebResponseObject ro = WebResponseObjectFactory.GetResponseObject(response, responseStream, this.Context); ro.RelationLink = _relationLink; WriteObject(ro); @@ -52,7 +56,7 @@ internal override void ProcessResponse(HttpResponseMessage response) if (ShouldSaveToOutFile) { - StreamHelper.SaveStreamToFile(responseStream, QualifiedOutFile, this, _cancelToken.Token); + StreamHelper.SaveStreamToFile(responseStream, QualifiedOutFile, this, response.Content.Headers.ContentLength.GetValueOrDefault(), _cancelToken.Token); } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs index d298f427960..ad640dcfd41 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs @@ -24,6 +24,7 @@ internal class WebResponseContentMemoryStream : MemoryStream { #region Data + private readonly long? _contentLength; private readonly Stream _originalStreamToProxy; private bool _isInitialized = false; private readonly Cmdlet _ownerCmdlet; @@ -37,9 +38,11 @@ internal class WebResponseContentMemoryStream : MemoryStream /// /// /// Owner cmdlet if any. - internal WebResponseContentMemoryStream(Stream stream, int initialCapacity, Cmdlet cmdlet) + /// Expected download size in Bytes. + internal WebResponseContentMemoryStream(Stream stream, int initialCapacity, Cmdlet cmdlet, long? contentLength) : base(initialCapacity) { + this._contentLength = contentLength; _originalStreamToProxy = stream; _ownerCmdlet = cmdlet; } @@ -218,14 +221,24 @@ private void Initialize() _isInitialized = true; try { - long totalLength = 0; + long totalRead = 0; byte[] buffer = new byte[StreamHelper.ChunkSize]; ProgressRecord record = new(StreamHelper.ActivityId, WebCmdletStrings.ReadResponseProgressActivity, "statusDescriptionPlaceholder"); - for (int read = 1; read > 0; totalLength += read) + string totalDownloadSize = _contentLength is null ? "???" : Utils.DisplayHumanReadableFileSize((long)_contentLength); + for (int read = 1; read > 0; totalRead += read) { if (_ownerCmdlet != null) { - record.StatusDescription = StringUtil.Format(WebCmdletStrings.ReadResponseProgressStatus, totalLength); + record.StatusDescription = StringUtil.Format( + WebCmdletStrings.ReadResponseProgressStatus, + Utils.DisplayHumanReadableFileSize(totalRead), + totalDownloadSize); + + if (_contentLength > 0) + { + record.PercentComplete = Math.Min((int)(totalRead * 100 / (long)_contentLength), 100); + } + _ownerCmdlet.WriteProgress(record); if (_ownerCmdlet.IsStopping) @@ -244,13 +257,13 @@ private void Initialize() if (_ownerCmdlet != null) { - record.StatusDescription = StringUtil.Format(WebCmdletStrings.ReadResponseComplete, totalLength); + record.StatusDescription = StringUtil.Format(WebCmdletStrings.ReadResponseComplete, totalRead); record.RecordType = ProgressRecordType.Completed; _ownerCmdlet.WriteProgress(record); } // make sure the length is set appropriately - base.SetLength(totalLength); + base.SetLength(totalRead); base.Seek(0, SeekOrigin.Begin); } catch (Exception) @@ -276,7 +289,7 @@ internal static class StreamHelper #region Static Methods - internal static void WriteToStream(Stream input, Stream output, PSCmdlet cmdlet, CancellationToken cancellationToken) + internal static void WriteToStream(Stream input, Stream output, PSCmdlet cmdlet, long? contentLength, CancellationToken cancellationToken) { if (cmdlet == null) { @@ -289,12 +302,22 @@ internal static void WriteToStream(Stream input, Stream output, PSCmdlet cmdlet, ActivityId, WebCmdletStrings.WriteRequestProgressActivity, WebCmdletStrings.WriteRequestProgressStatus); + string totalDownloadSize = contentLength is null ? "???" : Utils.DisplayHumanReadableFileSize((long)contentLength); try { while (!copyTask.Wait(1000, cancellationToken)) { - record.StatusDescription = StringUtil.Format(WebCmdletStrings.WriteRequestProgressStatus, output.Position); + record.StatusDescription = StringUtil.Format( + WebCmdletStrings.WriteRequestProgressStatus, + Utils.DisplayHumanReadableFileSize(output.Position), + totalDownloadSize); + + if (contentLength != null && contentLength > 0) + { + record.PercentComplete = Math.Min((int)(output.Position * 100 / (long)contentLength), 100); + } + cmdlet.WriteProgress(record); } @@ -316,13 +339,14 @@ internal static void WriteToStream(Stream input, Stream output, PSCmdlet cmdlet, /// Input stream. /// Output file name. /// Current cmdlet (Invoke-WebRequest or Invoke-RestMethod). + /// Expected download size in Bytes. /// CancellationToken to track the cmdlet cancellation. - internal static void SaveStreamToFile(Stream stream, string filePath, PSCmdlet cmdlet, CancellationToken cancellationToken) + internal static void SaveStreamToFile(Stream stream, string filePath, PSCmdlet cmdlet, long? contentLength, CancellationToken cancellationToken) { // If the web cmdlet should resume, append the file instead of overwriting. FileMode fileMode = cmdlet is WebRequestPSCmdlet webCmdlet && webCmdlet.ShouldResume ? FileMode.Append : FileMode.Create; using FileStream output = new(filePath, fileMode, FileAccess.Write, FileShare.Read); - WriteToStream(stream, output, cmdlet, cancellationToken); + WriteToStream(stream, output, cmdlet, contentLength, cancellationToken); } private static string StreamToString(Stream stream, Encoding encoding) diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/WebCmdletStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/WebCmdletStrings.resx index 976ec531e25..f0ec8a4b02b 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/WebCmdletStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/WebCmdletStrings.resx @@ -199,13 +199,13 @@ The cmdlet cannot run because the following parameter is missing: Proxy. Provide a valid proxy URI for the Proxy parameter when using the ProxyCredential or ProxyUseDefaultCredentials parameters, then retry. - Reading web response completed. (Number of bytes read: {0}) + Reading web response stream completed. Downloaded: {0} - Reading web response + Reading web response stream - Reading response stream... (Number of bytes read: {0}) + Downloaded: {0} of {1} The operation has timed out. @@ -223,7 +223,7 @@ Web request status - Number of bytes processed: {0} + Downloaded: {0} of {1} The ConvertTo-Json and ConvertFrom-Json cmdlets require the 'Json.Net' module. {0} diff --git a/src/System.Management.Automation/engine/Utils.cs b/src/System.Management.Automation/engine/Utils.cs index 661bc1e70cf..bc28b5a5d50 100644 --- a/src/System.Management.Automation/engine/Utils.cs +++ b/src/System.Management.Automation/engine/Utils.cs @@ -5,8 +5,6 @@ using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; -using System.ComponentModel; -using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; @@ -17,7 +15,6 @@ using System.Management.Automation.Security; using System.Numerics; using System.Reflection; -using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; #if !UNIX @@ -1547,6 +1544,21 @@ internal static bool IsComObject(object obj) return oldMode; } + + internal static string DisplayHumanReadableFileSize(long bytes) + { + return bytes switch + { + < 1024 and >= 0 => $"{bytes} Bytes", + < 1048576 and >= 1024 => $"{(bytes / 1024.0).ToString("0.0")} KB", + < 1073741824 and >= 1048576 => $"{(bytes / 1048576.0).ToString("0.0")} MB", + < 1099511627776 and >= 1073741824 => $"{(bytes / 1073741824.0).ToString("0.000")} GB", + < 1125899906842624 and >= 1099511627776 => $"{(bytes / 1099511627776.0).ToString("0.00000")} TB", + < 1152921504606847000 and >= 1125899906842624 => $"{(bytes / 1125899906842624.0).ToString("0.0000000")} PB", + >= 1152921504606847000 => $"{(bytes / 1152921504606847000.0).ToString("0.000000000")} EB", + _ => $"0 Bytes", + }; + } } } diff --git a/test/xUnit/csharp/test_Utils.cs b/test/xUnit/csharp/test_Utils.cs index ea45ce533d6..bf562f3a8a4 100644 --- a/test/xUnit/csharp/test_Utils.cs +++ b/test/xUnit/csharp/test_Utils.cs @@ -22,6 +22,23 @@ public static void TestIsWinPEHost() Assert.False(Utils.IsWinPEHost()); } + [Theory] + [InlineData(long.MinValue, "0 Bytes")] + [InlineData(-1, "0 Bytes")] + [InlineData(0, "0 Bytes")] + [InlineData(1, "1 Bytes")] + [InlineData(1024, "1.0 KB")] + [InlineData(3000, "2.9 KB")] + [InlineData(1024 * 1024, "1.0 MB")] + [InlineData(1024 * 1024 * 1024, "1.000 GB")] + [InlineData((long)(1024 * 1024 * 1024) * 1024, "1.00000 TB")] + [InlineData((long)(1024 * 1024 * 1024) * 1024 * 1024, "1.0000000 PB")] + [InlineData(long.MaxValue, "8.000000000 EB")] + public static void DisplayHumanReadableFileSize(long bytes, string expected) + { + Assert.Equal(expected, Utils.DisplayHumanReadableFileSize(bytes)); + } + [Fact] public static void TestHistoryStack() { From 100e374c71b325e4349142ed56bc536895928bd4 Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Tue, 20 Sep 2022 12:57:11 -0700 Subject: [PATCH 068/779] Update `metadata.json` and `README.md` for v7.3.0-preview.8 release (#18128) --- README.md | 28 ++++++++++++++-------------- tools/metadata.json | 4 ++-- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index 49061b9d33a..6b53bd1f781 100644 --- a/README.md +++ b/README.md @@ -93,20 +93,20 @@ You can also download the PowerShell binary archives for Windows, macOS and Linu [rl-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.6/powershell-7.2.6-linux-arm64.tar.gz [rl-snap]: https://snapcraft.io/powershell -[pv-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.7/PowerShell-7.3.0-preview.7-win-x64.msi -[pv-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.7/PowerShell-7.3.0-preview.7-win-x86.msi -[pv-deb]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.7/powershell-preview_7.3.0-preview.7-1.deb_amd64.deb -[pv-rpm]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.7/powershell-preview-7.3.0_preview.7-1.rh.x86_64.rpm -[pv-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.7/powershell-7.3.0-preview.7-osx-x64.pkg -[pv-macos-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.7/powershell-7.3.0-preview.7-osx-arm64.pkg -[pv-winarm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.7/PowerShell-7.3.0-preview.7-win-arm64.zip -[pv-winx86-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.7/PowerShell-7.3.0-preview.7-win-x86.zip -[pv-winx64-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.7/PowerShell-7.3.0-preview.7-win-x64.zip -[pv-macos-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.7/powershell-7.3.0-preview.7-osx-x64.tar.gz -[pv-macos-tar-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.7/powershell-7.3.0-preview.7-osx-arm64.tar.gz -[pv-linux-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.7/powershell-7.3.0-preview.7-linux-x64.tar.gz -[pv-arm32]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.7/powershell-7.3.0-preview.7-linux-arm32.tar.gz -[pv-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.7/powershell-7.3.0-preview.7-linux-arm64.tar.gz +[pv-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.8/PowerShell-7.3.0-preview.8-win-x64.msi +[pv-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.8/PowerShell-7.3.0-preview.8-win-x86.msi +[pv-deb]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.8/powershell-preview_7.3.0-preview.8-1.deb_amd64.deb +[pv-rpm]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.8/powershell-preview-7.3.0_preview.8-1.rh.x86_64.rpm +[pv-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.8/powershell-7.3.0-preview.8-osx-x64.pkg +[pv-macos-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.8/powershell-7.3.0-preview.8-osx-arm64.pkg +[pv-winarm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.8/PowerShell-7.3.0-preview.8-win-arm64.zip +[pv-winx86-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.8/PowerShell-7.3.0-preview.8-win-x86.zip +[pv-winx64-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.8/PowerShell-7.3.0-preview.8-win-x64.zip +[pv-macos-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.8/powershell-7.3.0-preview.8-osx-x64.tar.gz +[pv-macos-tar-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.8/powershell-7.3.0-preview.8-osx-arm64.tar.gz +[pv-linux-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.8/powershell-7.3.0-preview.8-linux-x64.tar.gz +[pv-arm32]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.8/powershell-7.3.0-preview.8-linux-arm32.tar.gz +[pv-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.8/powershell-7.3.0-preview.8-linux-arm64.tar.gz [pv-snap]: https://snapcraft.io/powershell-preview [in-windows]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-windows diff --git a/tools/metadata.json b/tools/metadata.json index 44192df371d..30b54c8433a 100644 --- a/tools/metadata.json +++ b/tools/metadata.json @@ -1,10 +1,10 @@ { "StableReleaseTag": "v7.2.6", - "PreviewReleaseTag": "v7.3.0-preview.7", + "PreviewReleaseTag": "v7.3.0-preview.8", "ServicingReleaseTag": "v7.0.12", "ReleaseTag": "v7.2.6", "LTSReleaseTag" : ["v7.2.6", "v7.0.12"], - "NextReleaseTag": "v7.3.0-preview.8", + "NextReleaseTag": "v7.3.0-preview.9", "LTSRelease": { "Latest": false, "Package": false }, "StableRelease": { "Latest": false, "Package": false } } From 31a0c29b91df1bf21b1cefc7fcf78e686320649d Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 20 Sep 2022 13:47:22 -0700 Subject: [PATCH 069/779] Bump Microsoft.CodeAnalysis.CSharp from 4.4.0-1.final to 4.4.0-2.final (#18132) --- .../Microsoft.PowerShell.Commands.Utility.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj index 18f9c39df02..390a14193ba 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj +++ b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj @@ -31,7 +31,7 @@ - + From 3b51fe458772d42b13239ecee62adfd79e230eaa Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Tue, 20 Sep 2022 14:11:29 -0700 Subject: [PATCH 070/779] Update the change log for v7.3.0-preview.8 (#18136) --- .spelling | 1 + CHANGELOG/preview.md | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/.spelling b/.spelling index 3aa89bb4a69..35c76464e8d 100644 --- a/.spelling +++ b/.spelling @@ -1582,5 +1582,6 @@ vmImage ci.psm1 jcotton42 centos-7 +Security.types.ps1xml - ADOPTERS.md MicrosoftPowerBIMgmt diff --git a/CHANGELOG/preview.md b/CHANGELOG/preview.md index cf80d139a56..41a27232a2b 100644 --- a/CHANGELOG/preview.md +++ b/CHANGELOG/preview.md @@ -1,5 +1,45 @@ # Current preview release +## [7.3.0-preview.8] - 2022-09-20 + +### General Cmdlet Updates and Fixes + +- Filter out compiler generated types for `Add-Type -PassThru` (#18095) +- Fix error formatting to use color defined in `$PSStyle.Formatting` (#17987) +- Handle `PSObject` argument specially in method invocation logging (#18060) +- Revert the experimental feature `PSStrictModeAssignment` (#18040) +- Make experimental feature `PSAMSIMethodInvocationLogging` stable (#18041) +- Make experimental feature `PSAnsiRenderingFileInfo` stable (#18042) +- Make experimental feature `PSCleanBlock` stable (#18043) +- Make experimental feature `PSNativeCommandArgumentPassing` stable (#18044) +- Make experimental feature `PSExec` stable (#18045) +- Make experimental feature `PSRemotingSSHTransportErrorHandling` stable (#18046) +- Add the `ConfigurationFile` option to the PowerShell help content (#18093) + +### Build and Packaging Improvements + + +

Bump .NET SDK to version `7.0.100-rc.1`

+
+ +
+
    +
  • Update ThirdPartyNotices.txt for 7.3.0-preview.8 (Internal 22553)
  • +
  • Update cgmanifest.json for 7.3.0-preview.8 (Internal 22551)
  • +
  • Re-enable building with Ready-to-Run (#18107)
  • +
  • Make sure Security.types.ps1xml gets signed in release build (#17930)
  • +
  • Update DotnetRuntimeMetadata.json for .NET 7 RC1 build (#18106)
  • +
  • Add XML reference documents to NuPkg files for SDK (#18017)
  • +
  • Make Register MU timeout (#17995)
  • +
  • Bump Microsoft.NET.Test.Sdk from 17.2.0 to 17.3.0 (#17924)
  • +
  • Update list of PS team members in release tools (#17928)
  • +
  • Update to use version 2.21.0 of Application Insights (#17927)
  • +
  • Complete ongoing Write-Progress in test (#17922)
  • +
+
+ +[7.3.0-preview.8]: https://github.com/PowerShell/PowerShell/compare/v7.3.0-preview.7...v7.3.0-preview.8 + ## [7.3.0-preview.7] - 2022-08-09 ### Breaking Changes From fc695d1ff0e15bfd4f7a6238b03db65d2d5149e1 Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Wed, 21 Sep 2022 09:59:39 -0700 Subject: [PATCH 071/779] Update MSI exit message (#18137) --- assets/wix/Product.wxs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/assets/wix/Product.wxs b/assets/wix/Product.wxs index 85cc0011d36..8dc2d3a3f16 100644 --- a/assets/wix/Product.wxs +++ b/assets/wix/Product.wxs @@ -110,7 +110,7 @@ - + From c978d467ab778fe544808227d915408eaba6b22c Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Wed, 21 Sep 2022 10:42:39 -0700 Subject: [PATCH 072/779] Complete the progress bar rendering in `Invoke-WebRequest` when downloading is complete or cancelled (#18130) --- .../utility/WebCmdlet/StreamHelper.cs | 24 +++++++++++++------ .../resources/WebCmdletStrings.resx | 5 +++- 2 files changed, 21 insertions(+), 8 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs index ad640dcfd41..b9345ff2606 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs @@ -298,6 +298,7 @@ internal static void WriteToStream(Stream input, Stream output, PSCmdlet cmdlet, Task copyTask = input.CopyToAsync(output, cancellationToken); + bool wroteProgress = false; ProgressRecord record = new( ActivityId, WebCmdletStrings.WriteRequestProgressActivity, @@ -313,23 +314,32 @@ internal static void WriteToStream(Stream input, Stream output, PSCmdlet cmdlet, Utils.DisplayHumanReadableFileSize(output.Position), totalDownloadSize); - if (contentLength != null && contentLength > 0) + if (contentLength > 0) { record.PercentComplete = Math.Min((int)(output.Position * 100 / (long)contentLength), 100); } cmdlet.WriteProgress(record); - } - - if (copyTask.IsCompleted) - { - record.StatusDescription = StringUtil.Format(WebCmdletStrings.WriteRequestComplete, output.Position); - cmdlet.WriteProgress(record); + wroteProgress = true; } } catch (OperationCanceledException) { } + finally + { + if (wroteProgress) + { + // Write out the completion progress record only if we did render the progress. + record.StatusDescription = StringUtil.Format( + copyTask.IsCompleted + ? WebCmdletStrings.WriteRequestComplete + : WebCmdletStrings.WriteRequestCancelled, + output.Position); + record.RecordType = ProgressRecordType.Completed; + cmdlet.WriteProgress(record); + } + } } /// diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/WebCmdletStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/WebCmdletStrings.resx index f0ec8a4b02b..e4f34c17ea2 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/WebCmdletStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/WebCmdletStrings.resx @@ -199,7 +199,7 @@ The cmdlet cannot run because the following parameter is missing: Proxy. Provide a valid proxy URI for the Proxy parameter when using the ProxyCredential or ProxyUseDefaultCredentials parameters, then retry. - Reading web response stream completed. Downloaded: {0} + Reading web response stream completed. Bytes downloaded: {0} Reading web response stream @@ -219,6 +219,9 @@ Web request completed. (Number of bytes processed: {0}) + + Web request cancelled. (Number of bytes processed: {0}) + Web request status From 79b8140199ad5b5439a4e7ce339f4e4ba3a7058d Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Thu, 22 Sep 2022 10:49:08 -0700 Subject: [PATCH 073/779] Make PowerShell class not affiliate with `Runspace` when declaring the `NoRunspaceAffinity` attribute (#18138) --- .../engine/parser/PSType.cs | 14 +++++ .../engine/parser/TypeResolver.cs | 1 + .../engine/runtime/Operations/ClassOps.cs | 2 +- .../engine/runtime/Operations/MiscOps.cs | 9 +++- ...pting.Classes.NoRunspaceAffinity.Tests.ps1 | 52 +++++++++++++++++++ .../Language/Parser/TypeAccelerator.Tests.ps1 | 8 ++- 6 files changed, 81 insertions(+), 5 deletions(-) create mode 100644 test/powershell/Language/Classes/Scripting.Classes.NoRunspaceAffinity.Tests.ps1 diff --git a/src/System.Management.Automation/engine/parser/PSType.cs b/src/System.Management.Automation/engine/parser/PSType.cs index 1f961af8d11..7f35927af26 100644 --- a/src/System.Management.Automation/engine/parser/PSType.cs +++ b/src/System.Management.Automation/engine/parser/PSType.cs @@ -1472,4 +1472,18 @@ private static void EmitLdarg(ILGenerator emitter, int c) } } } + + /// + /// The attribute for a PowerShell class to not affiliate with a particular Runspace\SessionState. + /// + [AttributeUsage(AttributeTargets.Class)] + public sealed class NoRunspaceAffinityAttribute : ParsingBaseAttribute + { + /// + /// Initializes a new instance of the attribute. + /// + public NoRunspaceAffinityAttribute() + { + } + } } diff --git a/src/System.Management.Automation/engine/parser/TypeResolver.cs b/src/System.Management.Automation/engine/parser/TypeResolver.cs index 8a12aefe159..1b5736df0ae 100644 --- a/src/System.Management.Automation/engine/parser/TypeResolver.cs +++ b/src/System.Management.Automation/engine/parser/TypeResolver.cs @@ -750,6 +750,7 @@ internal static class CoreTypes { typeof(CimConverter), new[] { "cimconverter" } }, { typeof(ModuleSpecification), null }, { typeof(IPEndPoint), new[] { "IPEndpoint" } }, + { typeof(NoRunspaceAffinityAttribute), new[] { "NoRunspaceAffinity" } }, { typeof(NullString), new[] { "NullString" } }, { typeof(OutputTypeAttribute), new[] { "OutputType" } }, { typeof(object[]), null }, diff --git a/src/System.Management.Automation/engine/runtime/Operations/ClassOps.cs b/src/System.Management.Automation/engine/runtime/Operations/ClassOps.cs index d0651719886..fdbb91ec404 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/ClassOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/ClassOps.cs @@ -22,7 +22,7 @@ namespace System.Management.Automation.Internal /// /// Every Runspace in one process contains SessionStateInternal per module (module SessionState). /// Every RuntimeType is associated to only one SessionState in the Runspace, which creates it: - /// it's ever global state or a module state. + /// it's either global state or a module state. /// In the former case, module can be imported from the different runspaces in the same process. /// And so runspaces will share RuntimeType. But in every runspace, Type is associated with just one SessionState. /// We want type methods to be able access $script: variables and module-specific methods. diff --git a/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs b/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs index 1c15c6510bc..bd1eb62f19d 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs @@ -2300,8 +2300,13 @@ internal static void InitPowerShellTypesAtRuntime(TypeDefinitionAst[] types) Diagnostics.Assert(t.Type != null, "TypeDefinitionAst.Type cannot be null"); if (t.IsClass) { - var helperType = - t.Type.Assembly.GetType(t.Type.FullName + "_"); + if (t.Type.IsDefined(typeof(NoRunspaceAffinityAttribute), inherit: true)) + { + // Skip the initialization for session state affinity. + continue; + } + + var helperType = t.Type.Assembly.GetType(t.Type.FullName + "_"); Diagnostics.Assert(helperType != null, "no corresponding " + t.Type.FullName + "_ type found"); foreach (var p in helperType.GetFields(BindingFlags.Static | BindingFlags.NonPublic)) { diff --git a/test/powershell/Language/Classes/Scripting.Classes.NoRunspaceAffinity.Tests.ps1 b/test/powershell/Language/Classes/Scripting.Classes.NoRunspaceAffinity.Tests.ps1 new file mode 100644 index 00000000000..bc08db2a063 --- /dev/null +++ b/test/powershell/Language/Classes/Scripting.Classes.NoRunspaceAffinity.Tests.ps1 @@ -0,0 +1,52 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +Describe "Class can be defined without Runspace affinity" -Tags "CI" { + + It "Applying the 'NoRunspaceAffinity' attribute make the class not affiliate with a particular Runspace/SessionState" { + [NoRunspaceAffinity()] + class NoAffinity { + [string] $Name; + [int] $RunspaceId; + + NoAffinity() { + $this.RunspaceId = [runspace]::DefaultRunspace.Id + } + + static [int] Echo() { + return [runspace]::DefaultRunspace.Id + } + + [int] SetAndEcho([string] $value) { + $this.Name = $value + return [runspace]::DefaultRunspace.Id + } + } + + $t = [NoAffinity] + $o = [NoAffinity]::new() + + ## Running directly should use the current Runspace/SessionState. + $t::Echo() | Should -Be $Host.Runspace.Id + $o.RunspaceId | Should -Be $Host.Runspace.Id + $o.SetAndEcho('Blue') | Should -Be $Host.Runspace.Id + $o.Name | Should -Be 'Blue' + + ## Running in a new Runspace should use that Runspace and its current SessionState. + try { + $ps = [powershell]::Create() + $ps.AddScript('function CallEcho($type) { $type::Echo() }').Invoke() > $null; $ps.Commands.Clear() + $ps.AddScript('function CallSetAndEcho($obj) { $obj.SetAndEcho(''Hello world'') }').Invoke() > $null; $ps.Commands.Clear() + $ps.AddScript('function GetName($obj) { $obj.Name }').Invoke() > $null; $ps.Commands.Clear() + $ps.AddScript('function NewObj($type) { $type::new().RunspaceId }').Invoke() > $null; $ps.Commands.Clear() + + $ps.AddCommand('CallEcho').AddArgument($t).Invoke() | Should -Be $ps.Runspace.Id; $ps.Commands.Clear() + $ps.AddCommand('CallSetAndEcho').AddArgument($o).Invoke() | Should -Be $ps.Runspace.Id; $ps.Commands.Clear() + $ps.AddCommand('GetName').AddArgument($o).Invoke() | Should -Be 'Hello world'; $ps.Commands.Clear() + $ps.AddCommand('NewObj').AddArgument($t).Invoke() | Should -Be $ps.Runspace.Id; $ps.Commands.Clear() + } + finally { + $ps.Dispose() + } + } +} diff --git a/test/powershell/Language/Parser/TypeAccelerator.Tests.ps1 b/test/powershell/Language/Parser/TypeAccelerator.Tests.ps1 index 018f5af55c6..99925600f63 100644 --- a/test/powershell/Language/Parser/TypeAccelerator.Tests.ps1 +++ b/test/powershell/Language/Parser/TypeAccelerator.Tests.ps1 @@ -410,15 +410,19 @@ Describe "Type accelerators" -Tags "CI" { Accelerator = 'ordered' Type = [System.Collections.Specialized.OrderedDictionary] } + @{ + Accelerator = 'NoRunspaceAffinity' + Type = [System.Management.Automation.Language.NoRunspaceAffinityAttribute] + } ) if ( !$IsWindows ) { - $totalAccelerators = 101 + $totalAccelerators = 102 } else { - $totalAccelerators = 106 + $totalAccelerators = 107 $extraFullPSAcceleratorTestCases = @( @{ From 55b079464d0f617308e2ccb866bcb63b6b37890c Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Thu, 22 Sep 2022 11:46:13 -0700 Subject: [PATCH 074/779] Update the cgmanifest (#18111) --- tools/cgmanifest.json | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/tools/cgmanifest.json b/tools/cgmanifest.json index 836d81c5b9d..522535be7b4 100644 --- a/tools/cgmanifest.json +++ b/tools/cgmanifest.json @@ -725,7 +725,7 @@ "Type": "nuget", "Nuget": { "Name": "System.Collections.Immutable", - "Version": "6.0.0" + "Version": "5.0.0" } }, "DevelopmentDependency": false @@ -1015,7 +1015,7 @@ "Type": "nuget", "Nuget": { "Name": "System.Private.ServiceModel", - "Version": "4.9.0" + "Version": "4.10.0" } }, "DevelopmentDependency": false @@ -1265,7 +1265,7 @@ "Type": "nuget", "Nuget": { "Name": "System.ServiceModel.Duplex", - "Version": "4.9.0" + "Version": "4.10.0" } }, "DevelopmentDependency": false @@ -1275,7 +1275,7 @@ "Type": "nuget", "Nuget": { "Name": "System.ServiceModel.Http", - "Version": "4.9.0" + "Version": "4.10.0" } }, "DevelopmentDependency": false @@ -1285,7 +1285,7 @@ "Type": "nuget", "Nuget": { "Name": "System.ServiceModel.NetTcp", - "Version": "4.9.0" + "Version": "4.10.0" } }, "DevelopmentDependency": false @@ -1295,7 +1295,7 @@ "Type": "nuget", "Nuget": { "Name": "System.ServiceModel.Primitives", - "Version": "4.9.0" + "Version": "4.10.0" } }, "DevelopmentDependency": false @@ -1305,7 +1305,7 @@ "Type": "nuget", "Nuget": { "Name": "System.ServiceModel.Security", - "Version": "4.9.0" + "Version": "4.10.0" } }, "DevelopmentDependency": false From 7d6a79891364c1f6f7ed7f661d1110519af4affa Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 22 Sep 2022 12:16:46 -0700 Subject: [PATCH 075/779] Bump `Microsoft.CodeAnalysis.NetAnalyzers` (#18147) --- Analyzers.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Analyzers.props b/Analyzers.props index 0c88302c9f5..e3fcddc0fd8 100644 --- a/Analyzers.props +++ b/Analyzers.props @@ -1,7 +1,7 @@ - + From dfa012d048054bc3e7f25268fff128cf724d3c60 Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Mon, 26 Sep 2022 14:42:28 -0700 Subject: [PATCH 076/779] Make the link to minimal package blob public during release (#18158) --- .../azureDevOps/templates/release-MakeContainerPublic.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tools/releaseBuild/azureDevOps/templates/release-MakeContainerPublic.yml b/tools/releaseBuild/azureDevOps/templates/release-MakeContainerPublic.yml index 870f2794dcb..65d5ea50191 100644 --- a/tools/releaseBuild/azureDevOps/templates/release-MakeContainerPublic.yml +++ b/tools/releaseBuild/azureDevOps/templates/release-MakeContainerPublic.yml @@ -11,6 +11,10 @@ steps: az storage container set-permission --account-name $(StorageAccount) --name $(azureVersion) --public-access blob displayName: Make container public +- pwsh: | + az storage container set-permission --account-name $(StorageAccount) --name $(azureVersion)-gc --public-access blob + displayName: Make guest configuration miminal package container public + - pwsh: | az logout displayName: az logout From fd67038ed88a844c51bcadbd720e6c2335fa4900 Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Tue, 27 Sep 2022 06:47:55 +0100 Subject: [PATCH 077/779] Replace `UTF8Encoding(false)` with `Encoding.Default` (#18144) --- .../engine/InitialSessionState.cs | 2 +- .../engine/NativeCommandProcessor.cs | 9 ++++---- .../engine/Utils.cs | 3 --- .../engine/hostifaces/MshHostUserInterface.cs | 4 ++-- .../remoting/common/RunspaceConnectionInfo.cs | 21 +++++++++++++------ 5 files changed, 23 insertions(+), 16 deletions(-) diff --git a/src/System.Management.Automation/engine/InitialSessionState.cs b/src/System.Management.Automation/engine/InitialSessionState.cs index e75ca018f8e..e5b306a7801 100644 --- a/src/System.Management.Automation/engine/InitialSessionState.cs +++ b/src/System.Management.Automation/engine/InitialSessionState.cs @@ -4340,7 +4340,7 @@ static InitialSessionState() // Variable which controls the encoding for piping data to a NativeCommand new SessionStateVariableEntry( SpecialVariables.OutputEncoding, - Utils.utf8NoBom, + Encoding.Default, RunspaceInit.OutputEncodingDescription, ScopedItemOptions.None, new ArgumentTypeConverterAttribute(typeof(System.Text.Encoding))), diff --git a/src/System.Management.Automation/engine/NativeCommandProcessor.cs b/src/System.Management.Automation/engine/NativeCommandProcessor.cs index 30bde91f1a4..6b8908c03c0 100644 --- a/src/System.Management.Automation/engine/NativeCommandProcessor.cs +++ b/src/System.Management.Automation/engine/NativeCommandProcessor.cs @@ -2057,11 +2057,12 @@ internal void Start(Process process, NativeCommandIOFormat inputFormat) // Get the encoding for writing to native command. Note we get the Encoding // from the current scope so a script or function can use a different encoding // than global value. - Encoding pipeEncoding = _command.Context.GetVariableValue(SpecialVariables.OutputEncodingVarPath) as System.Text.Encoding ?? - Utils.utf8NoBom; + Encoding outputEncoding = _command.Context.GetVariableValue(SpecialVariables.OutputEncodingVarPath) as Encoding; - _streamWriter = new StreamWriter(process.StandardInput.BaseStream, pipeEncoding); - _streamWriter.AutoFlush = true; + _streamWriter = new StreamWriter(process.StandardInput.BaseStream, outputEncoding ?? Encoding.Default) + { + AutoFlush = true + }; _inputFormat = inputFormat; diff --git a/src/System.Management.Automation/engine/Utils.cs b/src/System.Management.Automation/engine/Utils.cs index bc28b5a5d50..6cb51a4ae82 100644 --- a/src/System.Management.Automation/engine/Utils.cs +++ b/src/System.Management.Automation/engine/Utils.cs @@ -1380,9 +1380,6 @@ internal static bool Succeeded(int hresult) // Add-Member ScriptProperty Preamble { $this.GetEncoding().GetPreamble() -join "-" } -PassThru | // Format-Table -Auto - internal static readonly UTF8Encoding utf8NoBom = - new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); - #if !UNIX /// /// Queues a CLR worker thread with impersonation of provided Windows identity. diff --git a/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs index 0feeb73011f..452ae134602 100644 --- a/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs @@ -1243,7 +1243,7 @@ internal void FlushContentToDisk() { static Encoding GetPathEncoding(string path) { - using StreamReader reader = new StreamReader(path, Utils.utf8NoBom, detectEncodingFromByteOrderMarks: true); + using StreamReader reader = new StreamReader(path, Encoding.Default, detectEncodingFromByteOrderMarks: true); _ = reader.Read(); return reader.CurrentEncoding; } @@ -1271,7 +1271,7 @@ static Encoding GetPathEncoding(string path) // file permissions. _contentWriter = new StreamWriter( new FileStream(this.Path, FileMode.Append, FileAccess.Write, FileShare.Read), - Utils.utf8NoBom); + Encoding.Default); } _contentWriter.AutoFlush = true; diff --git a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs index 088bdddcb32..50853d86e7a 100644 --- a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs +++ b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs @@ -18,6 +18,7 @@ using System.Reflection; using System.Runtime.InteropServices; using System.Security.AccessControl; +using System.Text; using System.Threading; using Microsoft.Win32.SafeHandles; @@ -2404,23 +2405,31 @@ internal static int StartSSHProcess( if (startInfo.RedirectStandardInput) { Debug.Assert(stdinFd >= 0, "Invalid Fd"); - standardInput = new StreamWriter(OpenStream(stdinFd, FileAccess.Write), - Utils.utf8NoBom, StreamBufferSize) + standardInput = new StreamWriter( + OpenStream(stdinFd, FileAccess.Write), + Encoding.Default, + StreamBufferSize) { AutoFlush = true }; } if (startInfo.RedirectStandardOutput) { Debug.Assert(stdoutFd >= 0, "Invalid Fd"); - standardOutput = new StreamReader(OpenStream(stdoutFd, FileAccess.Read), - startInfo.StandardOutputEncoding ?? Utils.utf8NoBom, true, StreamBufferSize); + standardOutput = new StreamReader( + OpenStream(stdoutFd, FileAccess.Read), + startInfo.StandardOutputEncoding ?? Encoding.Default, + detectEncodingFromByteOrderMarks: true, + StreamBufferSize); } if (startInfo.RedirectStandardError) { Debug.Assert(stderrFd >= 0, "Invalid Fd"); - standardError = new StreamReader(OpenStream(stderrFd, FileAccess.Read), - startInfo.StandardErrorEncoding ?? Utils.utf8NoBom, true, StreamBufferSize); + standardError = new StreamReader( + OpenStream(stderrFd, FileAccess.Read), + startInfo.StandardErrorEncoding ?? Encoding.Default, + detectEncodingFromByteOrderMarks: true, + StreamBufferSize); } return childPid; From f943426f99cddca3506764445a07c78d1f633189 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 27 Sep 2022 08:48:02 +0000 Subject: [PATCH 078/779] Bump Microsoft.CodeAnalysis.NetAnalyzers (#18164) Bumps [Microsoft.CodeAnalysis.NetAnalyzers](https://github.com/dotnet/roslyn-analyzers) from 7.0.0-preview1.22471.2 to 7.0.0-preview1.22476.2. - [Release notes](https://github.com/dotnet/roslyn-analyzers/releases) - [Changelog](https://github.com/dotnet/roslyn-analyzers/blob/main/PostReleaseActivities.md) - [Commits](https://github.com/dotnet/roslyn-analyzers/commits) --- updated-dependencies: - dependency-name: Microsoft.CodeAnalysis.NetAnalyzers dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- Analyzers.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Analyzers.props b/Analyzers.props index e3fcddc0fd8..32f26d6cd0d 100644 --- a/Analyzers.props +++ b/Analyzers.props @@ -1,7 +1,7 @@ - + From ff244ef98ea4ed455643aa54385a9ff9e894a6aa Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 27 Sep 2022 12:05:15 -0700 Subject: [PATCH 079/779] Bump Microsoft.NET.Test.Sdk from 17.3.1 to 17.3.2 (#18163) --- test/xUnit/xUnit.tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/xUnit/xUnit.tests.csproj b/test/xUnit/xUnit.tests.csproj index c1710a1aa57..2fb87c8e29d 100644 --- a/test/xUnit/xUnit.tests.csproj +++ b/test/xUnit/xUnit.tests.csproj @@ -27,7 +27,7 @@ - + From e6c9ad6b8521949db8c8ccdff5da8f70fe4b0c78 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Tue, 27 Sep 2022 12:05:51 -0700 Subject: [PATCH 080/779] Update to the latest NOTICES file (#18149) --- ThirdPartyNotices.txt | 95 ++++++++++++++++++++----------------------- 1 file changed, 43 insertions(+), 52 deletions(-) diff --git a/ThirdPartyNotices.txt b/ThirdPartyNotices.txt index fec5e8df95e..ceb1155c1b2 100644 --- a/ThirdPartyNotices.txt +++ b/ThirdPartyNotices.txt @@ -1199,7 +1199,7 @@ SOFTWARE. --------------------------------------------------------- -System.Collections.Immutable 6.0.0 - MIT +System.Collections.Immutable 5.0.0 - MIT (c) Microsoft Corporation. @@ -1227,7 +1227,6 @@ Copyright (c) 2016-2017, Matthieu Darbois Copyright (c) .NET Foundation Contributors Copyright (c) The Internet Society (2003). Copyright (c) .NET Foundation and Contributors -Copyright (c) 2019 Microsoft Corporation, Daan Leijen Copyright (c) 2011 Novell, Inc (http://www.novell.com) Copyright (c) 1995-2017 Jean-loup Gailly and Mark Adler Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) @@ -1409,45 +1408,50 @@ SOFTWARE. --------------------------------------------------------- -System.Configuration.ConfigurationManager 6.0.0 - MIT +System.Configuration.ConfigurationManager 6.0.1 - MIT -(c) Microsoft Corporation. +(c) Microsoft Corporation Copyright (c) Andrew Arnott +Copyright 2019 LLVM Project Copyright 2018 Daniel Lemire -Copyright 2012 the V8 project -Copyright (c) .NET Foundation. +Copyright (c) .NET Foundation Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson Copyright (c) 1998 Microsoft. To -(c) 1997-2005 Sean Eron Anderson. Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2005-2020 Rich Felker Copyright (c) Microsoft Corporation Copyright (c) 2007 James Newton-King Copyright (c) 2012-2014, Yann Collet +Copyright (c) 1991-2020 Unicode, Inc. Copyright (c) 2013-2017, Alfred Klomp +Copyright 2012 the V8 project authors +Copyright (c) 2011-2020 Microsoft Corp Copyright (c) 2015-2017, Wojciech Mula Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 Portions (c) International Organization -Copyright (c) 2015 The Chromium Authors. -Copyright (c) The Internet Society 1997. Copyright (c) 2004-2006 Intel Corporation Copyright (c) 2013-2017, Milosz Krajewski Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) Copyright (c) .NET Foundation Contributors -Copyright (c) The Internet Society (2003). Copyright (c) .NET Foundation and Contributors Copyright (c) 2019 Microsoft Corporation, Daan Leijen Copyright (c) 2011 Novell, Inc (http://www.novell.com) Copyright (c) 1995-2017 Jean-loup Gailly and Mark Adler Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) -Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors. +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. -Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip. -Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers THIS WORK IS PROVIDED AS -Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California. -Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass. +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass. To The MIT License (MIT) @@ -1479,45 +1483,50 @@ SOFTWARE. --------------------------------------------------------- -System.Data.Odbc 6.0.0 - MIT +System.Data.Odbc 6.0.1 - MIT -(c) Microsoft Corporation. +(c) Microsoft Corporation Copyright (c) Andrew Arnott +Copyright 2019 LLVM Project Copyright 2018 Daniel Lemire -Copyright 2012 the V8 project -Copyright (c) .NET Foundation. +Copyright (c) .NET Foundation Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson Copyright (c) 1998 Microsoft. To -(c) 1997-2005 Sean Eron Anderson. Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2005-2020 Rich Felker Copyright (c) Microsoft Corporation Copyright (c) 2007 James Newton-King Copyright (c) 2012-2014, Yann Collet +Copyright (c) 1991-2020 Unicode, Inc. Copyright (c) 2013-2017, Alfred Klomp +Copyright 2012 the V8 project authors +Copyright (c) 2011-2020 Microsoft Corp Copyright (c) 2015-2017, Wojciech Mula Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 Portions (c) International Organization -Copyright (c) 2015 The Chromium Authors. -Copyright (c) The Internet Society 1997. Copyright (c) 2004-2006 Intel Corporation Copyright (c) 2013-2017, Milosz Krajewski Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) Copyright (c) .NET Foundation Contributors -Copyright (c) The Internet Society (2003). Copyright (c) .NET Foundation and Contributors Copyright (c) 2019 Microsoft Corporation, Daan Leijen Copyright (c) 2011 Novell, Inc (http://www.novell.com) Copyright (c) 1995-2017 Jean-loup Gailly and Mark Adler Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) -Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors. +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. -Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip. -Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers THIS WORK IS PROVIDED AS -Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California. -Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass. +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass. To The MIT License (MIT) @@ -2577,12 +2586,9 @@ SOFTWARE. --------------------------------------------------------- -System.Private.ServiceModel 4.9.0 - MIT +System.Private.ServiceModel 4.10.0 - MIT -(c) Microsoft Corporation. -Copyright (c) .NET Foundation and Contributors -Copyright (c) 2000-2014 The Legion of the Bouncy Castle Inc. (http://www.bouncycastle.org) The MIT License (MIT) @@ -3290,12 +3296,9 @@ SOFTWARE. --------------------------------------------------------- -System.ServiceModel.Duplex 4.9.0 - MIT +System.ServiceModel.Duplex 4.10.0 - MIT -(c) Microsoft Corporation. -Copyright (c) .NET Foundation and Contributors -Copyright (c) 2000-2014 The Legion of the Bouncy Castle Inc. (http://www.bouncycastle.org) The MIT License (MIT) @@ -3326,12 +3329,9 @@ SOFTWARE. --------------------------------------------------------- -System.ServiceModel.Http 4.9.0 - MIT +System.ServiceModel.Http 4.10.0 - MIT -(c) Microsoft Corporation. -Copyright (c) .NET Foundation and Contributors -Copyright (c) 2000-2014 The Legion of the Bouncy Castle Inc. (http://www.bouncycastle.org) The MIT License (MIT) @@ -3362,12 +3362,9 @@ SOFTWARE. --------------------------------------------------------- -System.ServiceModel.NetTcp 4.9.0 - MIT +System.ServiceModel.NetTcp 4.10.0 - MIT -(c) Microsoft Corporation. -Copyright (c) .NET Foundation and Contributors -Copyright (c) 2000-2014 The Legion of the Bouncy Castle Inc. (http://www.bouncycastle.org) The MIT License (MIT) @@ -3398,12 +3395,9 @@ SOFTWARE. --------------------------------------------------------- -System.ServiceModel.Primitives 4.9.0 - MIT +System.ServiceModel.Primitives 4.10.0 - MIT -(c) Microsoft Corporation. -Copyright (c) .NET Foundation and Contributors -Copyright (c) 2000-2014 The Legion of the Bouncy Castle Inc. (http://www.bouncycastle.org) The MIT License (MIT) @@ -3434,12 +3428,9 @@ SOFTWARE. --------------------------------------------------------- -System.ServiceModel.Security 4.9.0 - MIT +System.ServiceModel.Security 4.10.0 - MIT -(c) Microsoft Corporation. -Copyright (c) .NET Foundation and Contributors -Copyright (c) 2000-2014 The Legion of the Bouncy Castle Inc. (http://www.bouncycastle.org) The MIT License (MIT) From 23500470d95ba69a607f4b791812a167ea2c774a Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Wed, 28 Sep 2022 11:25:16 -0700 Subject: [PATCH 081/779] Add a workaround in automatic rebase workflow to continue on error (#18176) --- .github/workflows/rebase.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/rebase.yml b/.github/workflows/rebase.yml index 2ec027625b6..28d6abac0e1 100644 --- a/.github/workflows/rebase.yml +++ b/.github/workflows/rebase.yml @@ -23,6 +23,7 @@ jobs: fetch-depth: 0 - name: Post rebase started comment to pull request uses: actions/github-script@v6 + continue-on-error: true with: script: | const backport_start_body = `Started rebase: https://github.com/${context.repo.owner}/${context.repo.repo}/actions/runs/${process.env.GITHUB_RUN_ID}`; From 6e00e8a356a547b1d87997747345e5855165ea44 Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Wed, 28 Sep 2022 21:30:43 -0700 Subject: [PATCH 082/779] Fix the verbose message when using `dotnet-install.sh` (#18184) --- build.psm1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.psm1 b/build.psm1 index 819a6573610..e0c067aaa8f 100644 --- a/build.psm1 +++ b/build.psm1 @@ -1896,7 +1896,7 @@ function Install-Dotnet { $bashArgs += @('-skipnonversionedfiles') - $bashArgs | Out-String | Write-Verbose -Verbose + $bashArgs -join ' ' | Write-Verbose -Verbose Start-NativeExecution { bash @bashArgs From d66b2a5b52813e2b8702b24f563b47e4f64e810a Mon Sep 17 00:00:00 2001 From: Jordan Borean Date: Thu, 29 Sep 2022 14:43:40 +1000 Subject: [PATCH 083/779] Fix Parent property on processes with complex name (#17545) --- .../CoreCLR/CorePsPlatform.cs | 38 ++++++++++++++----- .../Get-Process.Tests.ps1 | 36 ++++++++++++++---- 2 files changed, 57 insertions(+), 17 deletions(-) diff --git a/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs b/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs index 1986c4c63be..28b02a6d706 100644 --- a/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs +++ b/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs @@ -883,20 +883,40 @@ public static int GetProcFSParentPid(int pid) { const int invalidPid = -1; - // read /proc//stat - // 4th column will contain the ppid, 92 in the example below - // ex: 93 (bash) S 92 93 2 4294967295 ... - var path = $"/proc/{pid}/stat"; + // read /proc//status + // Row beginning with PPid: \d is the parent process id. + // This used to check /proc//stat but that file was meant + // to be a space delimited line but it contains a value which + // could contain spaces itself. Using the status file is a lot + // simpler because each line contains a record with a simple + // label. + // https://github.com/PowerShell/PowerShell/issues/17541#issuecomment-1159911577 + var path = $"/proc/{pid}/status"; try { - var stat = System.IO.File.ReadAllText(path); - var parts = stat.Split(' ', 5); - if (parts.Length < 5) + using FileStream fs = File.OpenRead(path); + using StreamReader sr = new(fs); + string line; + while ((line = sr.ReadLine()) != null) { - return invalidPid; + if (!line.StartsWith("PPid:\t", StringComparison.OrdinalIgnoreCase)) + { + continue; + } + + string[] lineSplit = line.Split('\t', 2, StringSplitOptions.RemoveEmptyEntries); + if (lineSplit.Length != 2) + { + continue; + } + + if (int.TryParse(lineSplit[1].Trim(), out var ppid)) + { + return ppid; + } } - return int.Parse(parts[3]); + return invalidPid; } catch (Exception) { diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Process.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Process.Tests.ps1 index 345b2affa2e..79b592f31f3 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Process.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Process.Tests.ps1 @@ -22,7 +22,7 @@ Describe "Get-Process for admin" -Tags @('CI', 'RequireAdminOnWindows') { $pwshVersion.FileBuildPart | Should -BeExactly $PSVersionTable.PSVersion.Patch $gitCommitId = $PSVersionTable.GitCommitId if ($gitCommitId.StartsWith("v")) { $gitCommitId = $gitCommitId.Substring(1) } - $productVersion = $pwshVersion.ProductVersion.Replace(" Commits: ","-").Replace(" SHA: ","-g") + $productVersion = $pwshVersion.ProductVersion.Replace(" Commits: ", "-").Replace(" SHA: ", "-g") $productVersion | Should -Match $gitCommitId } else { $pwshVersion.FileVersion | Should -BeNullOrEmpty @@ -46,7 +46,7 @@ Describe "Get-Process" -Tags "CI" { $idleProcessPid = 0 } It "Should return a type of Object[] for Get-Process cmdlet" -Pending:$IsMacOS { - ,$ps | Should -BeOfType System.Object[] + , $ps | Should -BeOfType System.Object[] } It "Should have not empty Name flags set for Get-Process object" -Pending:$IsMacOS { @@ -78,7 +78,7 @@ Describe "Get-Process" -Tags "CI" { (Get-Process -Id $PID).Id | Should -BeExactly $PID } - It "Should fail to run Get-Process with -IncludeUserName without admin" -Skip:(!$IsWindows) { + It "Should fail to run Get-Process with -IncludeUserName without admin" -Skip:(!$IsWindows) { { Get-Process -IncludeUserName } | Should -Throw -ErrorId "IncludeUserNameRequiresElevation,Microsoft.PowerShell.Commands.GetProcessCommand" } @@ -95,7 +95,7 @@ Describe "Get-Process" -Tags "CI" { { Get-Process -FileVersionInfo -ErrorAction Stop } | Should -Throw -ErrorId "CouldNotEnumerateFileVer,Microsoft.PowerShell.Commands.GetProcessCommand" } - It "Should return CommandLine property" -Skip:($IsMacOS) { + It "Should return CommandLine property" -Skip:($IsMacOS) { $command = "(Get-Process -Id `$pid).CommandLine" $result = & "$PSHOME/pwsh" -NoProfile -NonInteractive -Command $command $result | Should -BeLike "*$command*" @@ -105,19 +105,18 @@ Describe "Get-Process" -Tags "CI" { Describe "Get-Process Formatting" -Tags "Feature" { BeforeAll { $skip = $false - if ($IsWindows) - { + if ($IsWindows) { # on Windows skip this test until issue #11016 is resolved $skip = $true } } It "Should not have Handle in table format header" -Skip:$skip { - $types = "System.Diagnostics.Process","System.Diagnostics.Process#IncludeUserName" + $types = "System.Diagnostics.Process", "System.Diagnostics.Process#IncludeUserName" foreach ($type in $types) { $formatData = Get-FormatData -TypeName $type -PowerShellVersion $PSVersionTable.PSVersion - $tableControls = $formatData.FormatViewDefinition | Where-Object {$_.Control -is "System.Management.Automation.TableControl"} + $tableControls = $formatData.FormatViewDefinition | Where-Object { $_.Control -is "System.Management.Automation.TableControl" } foreach ($tableControl in $tableControls) { $tableControl.Control.Headers.Label -match "Handle*" | Should -BeNullOrEmpty # verify that rows without headers isn't the handlecount (as PowerShell will create a header that matches the property name) @@ -138,5 +137,26 @@ Describe "Process Parent property" -Tags "CI" { $powershellexe = (Get-Process -Id $PID).mainmodule.filename & $powershellexe -noprofile -command '(Get-Process -Id $PID).Parent.Id' | Should -Be $PID } + + It "Can find parent with spaces and parenthesis in the name on non-Windows" -Skip:($IsWindows) { + # Bug. See https://github.com/PowerShell/PowerShell/issues/12908 + $commandName = 't ( e ( s ) t )' + + $script = @' +#!/bin/sh + +while true; do sleep 1; done +'@ + + # Can't use testdrive: as unelevated user doesn't have perms in test in CI + Set-Content -Path /tmp/$commandName -Value $script + chmod +x (Resolve-Path -Path /tmp/$commandName -Relative) + try { + $p = Start-Process -FilePath /tmp/$commandName -PassThru + $p.Parent.Id | Should -Be $pid + } finally { + $p | Stop-Process + } + } } From 8973b0c1214a8be792176d76a92ce29ce3c44793 Mon Sep 17 00:00:00 2001 From: Ilya Date: Thu, 29 Sep 2022 21:39:04 +0500 Subject: [PATCH 084/779] Use overload APIs that take `char` instead of `string` when it's possible (#18179) --- .../commands/management/RegisterWMIEventCommand.cs | 2 +- .../commands/management/WMIHelper.cs | 4 ++-- .../security/CertificateProvider.cs | 2 +- src/System.Management.Automation/DscSupport/CimDSCParser.cs | 2 +- src/System.Management.Automation/engine/CommandDiscovery.cs | 2 +- test/tools/WebListener/Controllers/LinkController.cs | 2 +- 6 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/RegisterWMIEventCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/RegisterWMIEventCommand.cs index 0a4d9c6cb34..55a57073efd 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/RegisterWMIEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/RegisterWMIEventCommand.cs @@ -91,7 +91,7 @@ private string GetScopeString(string computer, string namespaceParameter) { StringBuilder returnValue = new StringBuilder("\\\\"); returnValue.Append(computer); - returnValue.Append("\\"); + returnValue.Append('\\'); returnValue.Append(namespaceParameter); return returnValue.ToString(); } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/WMIHelper.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/WMIHelper.cs index eed6efff76a..e15a45c0e9a 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/WMIHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/WMIHelper.cs @@ -1042,7 +1042,7 @@ internal static string GetScopeString(string computer, string namespaceParameter { StringBuilder returnValue = new StringBuilder("\\\\"); returnValue.Append(computer); - returnValue.Append("\\"); + returnValue.Append('\\'); returnValue.Append(namespaceParameter); return returnValue.ToString(); } @@ -1659,7 +1659,7 @@ private string ConstructLocation() foreach (PSWmiChildJob job in ChildJobs) { location.Append(job.Location); - location.Append(","); + location.Append(','); } location.Remove(location.Length - 1, 1); diff --git a/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs b/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs index 3a367283828..1ebaecc8831 100644 --- a/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs +++ b/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs @@ -1568,7 +1568,7 @@ private static string NormalizePath(string path) string[] elts = GetPathElements(path); - path = string.Join("\\", elts); + path = string.Join('\\', elts); } return path; diff --git a/src/System.Management.Automation/DscSupport/CimDSCParser.cs b/src/System.Management.Automation/DscSupport/CimDSCParser.cs index ccefa7e24bb..a91691535d4 100644 --- a/src/System.Management.Automation/DscSupport/CimDSCParser.cs +++ b/src/System.Management.Automation/DscSupport/CimDSCParser.cs @@ -992,7 +992,7 @@ public static List ImportClasses(string path, Tuple m // allow sharing of nested objects. if (!IsSameNestedObject(cimClass, c)) { - var files = string.Join(",", GetFileDefiningClass(className)); + var files = string.Join(',', GetFileDefiningClass(className)); PSInvalidOperationException e = PSTraceSource.NewInvalidOperationException( ParserStrings.DuplicateCimClassDefinition, className, path, files); diff --git a/src/System.Management.Automation/engine/CommandDiscovery.cs b/src/System.Management.Automation/engine/CommandDiscovery.cs index e9de849a4cc..9a126645a7d 100644 --- a/src/System.Management.Automation/engine/CommandDiscovery.cs +++ b/src/System.Management.Automation/engine/CommandDiscovery.cs @@ -454,7 +454,7 @@ internal static void VerifyPSEdition(ExternalScriptInfo scriptInfo) // if (isRequiresPSEditionSpecified && !isCurrentEditionListed) { - var specifiedEditionsString = string.Join(",", scriptInfo.RequiresPSEditions); + var specifiedEditionsString = string.Join(',', scriptInfo.RequiresPSEditions); var message = StringUtil.Format(DiscoveryExceptions.RequiresPSEditionNotCompatible, scriptInfo.Name, specifiedEditionsString, diff --git a/test/tools/WebListener/Controllers/LinkController.cs b/test/tools/WebListener/Controllers/LinkController.cs index e15607d6b9b..75548d8ab2c 100644 --- a/test/tools/WebListener/Controllers/LinkController.cs +++ b/test/tools/WebListener/Controllers/LinkController.cs @@ -87,7 +87,7 @@ public JsonResult Index() } else { - linkHeader = string.Join(",", linkList); + linkHeader = string.Join(',', linkList); } Response.Headers.Add("Link", linkHeader); From 618d1a7c78f0702156d5ba1cd1be31df6d7f54d7 Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Thu, 29 Sep 2022 16:22:53 -0700 Subject: [PATCH 085/779] Minor update to the `FileInfo` table formatting on Unix to make it more concise (#18183) --- .../DefaultFormatters/FileSystem_format_ps1xml.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/FileSystem_format_ps1xml.cs b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/FileSystem_format_ps1xml.cs index 01cba83cd00..0400f99b899 100644 --- a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/FileSystem_format_ps1xml.cs +++ b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/FileSystem_format_ps1xml.cs @@ -46,10 +46,10 @@ private static IEnumerable ViewsOf_FileSystemTypes(CustomC TableControl.Create() .GroupByProperty("PSParentPath", customControl: sharedControls[0]) .AddHeader(Alignment.Left, label: "UnixMode", width: 10) - .AddHeader(Alignment.Left, label: "User", width: 16) - .AddHeader(Alignment.Left, label: "Group", width: 16) - .AddHeader(Alignment.Right, label: "LastWriteTime", width: 18) - .AddHeader(Alignment.Right, label: "Size", width: 14) + .AddHeader(Alignment.Right, label: "User", width: 10) + .AddHeader(Alignment.Left, label: "Group", width: 10) + .AddHeader(Alignment.Right, label: "LastWriteTime", width: 16) + .AddHeader(Alignment.Right, label: "Size", width: 12) .AddHeader(Alignment.Left, label: "Name") .StartRowDefinition(wrap: true) .AddPropertyColumn("UnixMode") From d9d6b7f8de9febc6bc2e3554522e0453c7505614 Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Fri, 30 Sep 2022 14:59:01 -0700 Subject: [PATCH 086/779] Move ApiScan to compliance build (#18191) --- PowerShell.Common.props | 12 +- build.psm1 | 6 +- tools/releaseBuild/azureDevOps/compliance.yml | 7 ++ .../azureDevOps/templates/compliance.yml | 20 +--- .../templates/compliance/apiscan.yml | 112 ++++++++++++++++++ 5 files changed, 133 insertions(+), 24 deletions(-) create mode 100644 tools/releaseBuild/azureDevOps/templates/compliance/apiscan.yml diff --git a/PowerShell.Common.props b/PowerShell.Common.props index cf5c11c9ed2..99b53418049 100644 --- a/PowerShell.Common.props +++ b/PowerShell.Common.props @@ -137,8 +137,6 @@ net7.0 10.0 - true - true true true @@ -171,7 +169,15 @@ + true + true + true + + + + true + full @@ -193,6 +199,8 @@ + true + true portable diff --git a/build.psm1 b/build.psm1 index e0c067aaa8f..4a92627eab3 100644 --- a/build.psm1 +++ b/build.psm1 @@ -319,7 +319,7 @@ function Start-PSBuild { "win7-x86")] [string]$Runtime, - [ValidateSet('Debug', 'Release', 'CodeCoverage', '')] # We might need "Checked" as well + [ValidateSet('Debug', 'Release', 'CodeCoverage', 'StaticAnalysis', '')] # We might need "Checked" as well [string]$Configuration, [ValidatePattern("^v\d+\.\d+\.\d+(-\w+(\.\d{1,2})?)?$")] @@ -814,7 +814,7 @@ function Compress-TestContent { function New-PSOptions { [CmdletBinding()] param( - [ValidateSet("Debug", "Release", "CodeCoverage", '')] + [ValidateSet('Debug', 'Release', 'CodeCoverage', 'StaticAnalysis', '')] [string]$Configuration, [ValidateSet("net7.0")] @@ -2234,7 +2234,7 @@ function Start-DevPowerShell { [string[]]$ArgumentList = @(), [switch]$LoadProfile, [Parameter(ParameterSetName='ConfigurationParamSet')] - [ValidateSet("Debug", "Release", "CodeCoverage", '')] # should match New-PSOptions -Configuration values + [ValidateSet('Debug', 'Release', 'CodeCoverage', 'StaticAnalysis', '')] # should match New-PSOptions -Configuration values [string]$Configuration, [Parameter(ParameterSetName='BinDirParamSet')] [string]$BinDir, diff --git a/tools/releaseBuild/azureDevOps/compliance.yml b/tools/releaseBuild/azureDevOps/compliance.yml index 0b713cb0ae7..19935237216 100644 --- a/tools/releaseBuild/azureDevOps/compliance.yml +++ b/tools/releaseBuild/azureDevOps/compliance.yml @@ -39,6 +39,13 @@ stages: - template: templates/compliance/compliance.yml parameters: parentJobs: [] + - stage: APIScan + displayName: 'ApiScan' + dependsOn: [] + jobs: + - template: templates/compliance/apiscan.yml + parameters: + parentJobs: [] - stage: notice displayName: Generate Notice File dependsOn: [] diff --git a/tools/releaseBuild/azureDevOps/templates/compliance.yml b/tools/releaseBuild/azureDevOps/templates/compliance.yml index 0c4a162bb11..0a416389bf4 100644 --- a/tools/releaseBuild/azureDevOps/templates/compliance.yml +++ b/tools/releaseBuild/azureDevOps/templates/compliance.yml @@ -9,9 +9,6 @@ jobs: - name: NugetSecurityAnalysisWarningLevel value: none - # Defines the variables APIScanClient, APIScanTenant and APIScanSecret - - group: PS-PS-APIScan - displayName: Compliance dependsOn: ${{ parameters.parentJobs }} @@ -20,9 +17,6 @@ jobs: demands: - ImageOverride -equals PSMMS2019-Secure - # APIScan can take a long time - timeoutInMinutes: 180 - steps: - checkout: self clean: true @@ -93,18 +87,6 @@ jobs: # PreFASt is not applicable - - task: securedevelopmentteam.vss-secure-development-tools.build-task-apiscan.APIScan@2 - displayName: 'Run APIScan' - inputs: - softwareFolder: '$(CompliancePath)' - softwareName: PowerShell - softwareVersionNum: '$(ReleaseTagVar)' - isLargeApp: false - preserveTempFiles: true - env: - AzureServicesAuthConnectionString: RunAs=App;AppId=$(APIScanClient);TenantId=$(APIScanTenant);AppKey=$(APIScanSecret) - continueOnError: true - - task: securedevelopmentteam.vss-secure-development-tools.build-task-publishsecurityanalysislogs.PublishSecurityAnalysisLogs@2 displayName: 'Publish Security Analysis Logs to Build Artifacts' continueOnError: true @@ -129,7 +111,7 @@ jobs: displayName: 'Create Security Analysis Report' inputs: TsvFile: false - APIScan: true + APIScan: false BinSkim: true CredScan: true PoliCheck: true diff --git a/tools/releaseBuild/azureDevOps/templates/compliance/apiscan.yml b/tools/releaseBuild/azureDevOps/templates/compliance/apiscan.yml new file mode 100644 index 00000000000..0aa6c498f4c --- /dev/null +++ b/tools/releaseBuild/azureDevOps/templates/compliance/apiscan.yml @@ -0,0 +1,112 @@ +jobs: + - job: APIScan + variables: + - name: runCodesignValidationInjection + value : false + - name: NugetSecurityAnalysisWarningLevel + value: none + - name: ReleaseTagVar + value: fromBranch + # Defines the variables APIScanClient, APIScanTenant and APIScanSecret + - group: PS-PS-APIScan + # PAT permissions NOTE: Declare a SymbolServerPAT variable in this group with a 'microsoft' organizanization scoped PAT with 'Symbols' Read permission. + # A PAT in the wrong org will give a single Error 203. No PAT will give a single Error 401, and individual pdbs may be missing even if permissions are correct. + - group: symbols + + pool: + name: PowerShell1ES + demands: + - ImageOverride -equals PSMMS2019-Secure + + # APIScan can take a long time + timeoutInMinutes: 180 + + steps: + - template: ../SetVersionVariables.yml + parameters: + ReleaseTagVar: $(ReleaseTagVar) + CreateJson: yes + UseJson: no + + - pwsh: | + Import-Module .\build.psm1 -force + Start-PSBootstrap + workingDirectory: '$(Build.SourcesDirectory)' + retryCountOnTaskFailure: 2 + displayName: 'Bootstrap' + + - pwsh: | + Import-Module .\build.psm1 -force + Find-DotNet + dotnet tool install dotnet-symbol --tool-path $(Agent.ToolsDirectory)\tools\dotnet-symbol + $symbolToolPath = Get-ChildItem -Path $(Agent.ToolsDirectory)\tools\dotnet-symbol\dotnet-symbol.exe | Select-Object -First 1 -ExpandProperty FullName + Write-Host "##vso[task.setvariable variable=symbolToolPath]$symbolToolPath" + displayName: Install dotnet-symbol + retryCountOnTaskFailure: 2 + + - pwsh: | + Import-Module .\build.psm1 -force + Find-DotNet + Start-PSBuild -Configuration StaticAnalysis -PSModuleRestore -Clean + + $OutputFolder = Split-Path (Get-PSOutput) + Write-Host "##vso[task.setvariable variable=BinDir]$OutputFolder" + workingDirectory: '$(Build.SourcesDirectory)' + displayName: 'Build PowerShell Source' + + - pwsh: | + Get-ChildItem -Path env: + displayName: Capture Environment + condition: succeededOrFailed() + + # Explicitly download symbols for the drop since the SDL image doesn't have http://SymWeb access and APIScan cannot handle https yet. + - pwsh: | + Import-Module .\build.psm1 -force + Find-DotNet + $pat = '$(SymbolServerPAT)' + if ($pat -like '*PAT*' -or $pat -eq '') + { + throw 'No PAT defined' + } + $url = 'https://microsoft.artifacts.visualstudio.com/defaultcollection/_apis/symbol/symsrv' + $(symbolToolPath) --authenticated-server-path $(SymbolServerPAT) $url --symbols -d "$env:BinDir\*" --recurse-subdirectories + displayName: 'Download Symbols for binaries' + retryCountOnTaskFailure: 2 + workingDirectory: '$(Build.SourcesDirectory)' + + - task: securedevelopmentteam.vss-secure-development-tools.build-task-apiscan.APIScan@2 + displayName: 'Run APIScan' + inputs: + softwareFolder: '$(BinDir)' + softwareName: PowerShell + softwareVersionNum: '$(ReleaseTagVar)' + isLargeApp: false + preserveTempFiles: false + verbosityLevel: standard + # write a status update every 5 minutes. Default is 1 minute + statusUpdateInterval: '00:05:00' + env: + AzureServicesAuthConnectionString: RunAs=App;AppId=$(APIScanClient);TenantId=$(APIScanTenant);AppKey=$(APIScanSecret) + + - task: securedevelopmentteam.vss-secure-development-tools.build-task-report.SdtReport@2 + continueOnError: true + displayName: 'Guardian Export' + inputs: + GdnExportVstsConsole: true + GdnExportSarifFile: true + GdnExportHtmlFile: true + GdnExportAllTools: false + GdnExportGdnToolApiScan: true + #this didn't do anything GdnExportCustomLogsFolder: '$(Build.ArtifactStagingDirectory)/Guardian' + + - pwsh: | + Get-ChildItem -Path env: + displayName: Capture Environment + condition: succeededOrFailed() + + - task: securedevelopmentteam.vss-secure-development-tools.build-task-publishsecurityanalysislogs.PublishSecurityAnalysisLogs@3 + displayName: 'Publish Guardian Artifacts' + inputs: + AllTools: false + APIScan: true + ArtifactName: APIScan From a7a49290a82c75c2b7eb5ce5b809d6c675a87d0a Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Fri, 30 Sep 2022 15:47:51 -0700 Subject: [PATCH 087/779] Remove the extra new line form List formatting (#18185) --- .../FormatAndOutput/common/BaseOutputtingCommand.cs | 13 ++++++++++--- .../Format-List.Tests.ps1 | 4 +--- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs b/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs index 3ab591a7af4..c0c932142db 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs @@ -456,9 +456,16 @@ private void ProcessFormatStart(FormatMessagesContextManager.OutputContext c) /// Current context, with Fs in it. private void ProcessFormatEnd(FormatEndData fe, FormatMessagesContextManager.OutputContext c) { - // Console.WriteLine("ProcessFormatEnd"); - // we just add an empty line to the display - this.LineOutput.WriteLine(string.Empty); + if (c is FormatOutputContext foContext + && foContext.Data.shapeInfo is ListViewHeaderInfo) + { + // Skip writing out a new line for List view, because we already wrote out + // an extra new line after displaying the last list entry. + return; + } + + // We just add an empty line to the display. + LineOutput.WriteLine(string.Empty); } /// diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Format-List.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Format-List.Tests.ps1 index 675d1fd5106..bab0110a9ac 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Format-List.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Format-List.Tests.ps1 @@ -37,7 +37,7 @@ Describe "Format-List" -Tags "CI" { } It "Should produce the expected output" { - $expected = "${nl}testName : testValue${nl}${nl}${nl}" + $expected = "${nl}testName : testValue${nl}${nl}" $in = New-Object PSObject Add-Member -InputObject $in -MemberType NoteProperty -Name testName -Value testValue @@ -201,7 +201,6 @@ dbda : KM 消息 : 千 - "@ $expected = $expected -replace "`r`n", "`n" @@ -224,7 +223,6 @@ float : 9876.543 decimal : 4567.123456789 - "@ $actual = $o | Format-List | Out-String From f67655d96c076966f68b15abdcd3ab9ce00817b8 Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Mon, 3 Oct 2022 10:36:12 -0700 Subject: [PATCH 088/779] Update to use `ComputeCore.dll` for PowerShell Direct (#18194) --- src/System.Management.Automation/utils/PInvokeDllNames.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/System.Management.Automation/utils/PInvokeDllNames.cs b/src/System.Management.Automation/utils/PInvokeDllNames.cs index bff2ca2656e..a1bbe282aa7 100644 --- a/src/System.Management.Automation/utils/PInvokeDllNames.cs +++ b/src/System.Management.Automation/utils/PInvokeDllNames.cs @@ -89,7 +89,7 @@ internal static class PinvokeDllNames internal const string PrivilegeCheckDllName = "api-ms-win-security-base-l1-1-0.dll"; /*76*/ internal const string ImpersonateNamedPipeClientDllName = "api-ms-win-core-namedpipe-l1-1-0.dll"; /*77*/ internal const string RevertToSelfDllName = "api-ms-win-security-base-l1-1-0.dll"; /*78*/ - internal const string CreateProcessInComputeSystemDllName = "vmcompute.dll"; /*79*/ + internal const string CreateProcessInComputeSystemDllName = "ComputeCore.dll"; /*79*/ internal const string CLSIDFromProgIDDllName = "api-ms-win-core-com-l1-1-0.dll"; /*80*/ internal const string LoadLibraryEx = "api-ms-win-core-libraryloader-l1-1-0.dll"; /*81*/ internal const string FreeLibrary = "api-ms-win-core-libraryloader-l1-1-0.dll"; /*82*/ From 50b8f130f476f541ba0d6843e42b5b95eda98298 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 3 Oct 2022 11:35:22 -0700 Subject: [PATCH 089/779] Bump Microsoft.CodeAnalysis.NetAnalyzers (#18201) --- Analyzers.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Analyzers.props b/Analyzers.props index 32f26d6cd0d..5628efac862 100644 --- a/Analyzers.props +++ b/Analyzers.props @@ -1,7 +1,7 @@ - + From d5ed53eba2e8346fd4b2cc2836808cbc5471b6bd Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Mon, 3 Oct 2022 15:05:11 -0700 Subject: [PATCH 090/779] Add `CustomTableHeaderLabel` formatting to differentiate table header labels that are not property names (#17346) --- experimental-feature-linux.json | 1 + experimental-feature-windows.json | 1 + .../common/BaseOutputtingCommand.cs | 6 +- .../common/FormatViewGenerator_Table.cs | 4 + .../common/FormattingObjects.cs | 1 + .../FormatAndOutput/common/PSStyle.cs | 11 +++ .../FormatAndOutput/common/TableWriter.cs | 75 ++++++++++++------- .../ExperimentalFeature.cs | 4 + .../Format-Table.Tests.ps1 | 6 +- .../engine/Formatting/PSStyle.Tests.ps1 | 35 +++++++-- 10 files changed, 103 insertions(+), 41 deletions(-) diff --git a/experimental-feature-linux.json b/experimental-feature-linux.json index 4dee9496504..573cfc1084a 100644 --- a/experimental-feature-linux.json +++ b/experimental-feature-linux.json @@ -1,5 +1,6 @@ [ "PSCommandNotFoundSuggestion", + "PSCustomTableHeaderLabelDecoration", "PSLoadAssemblyFromNativeCode", "PSNativeCommandErrorActionPreference", "PSSubsystemPluginModel" diff --git a/experimental-feature-windows.json b/experimental-feature-windows.json index 4dee9496504..573cfc1084a 100644 --- a/experimental-feature-windows.json +++ b/experimental-feature-windows.json @@ -1,5 +1,6 @@ [ "PSCommandNotFoundSuggestion", + "PSCustomTableHeaderLabelDecoration", "PSLoadAssemblyFromNativeCode", "PSNativeCommandErrorActionPreference", "PSSubsystemPluginModel" diff --git a/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs b/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs index c0c932142db..088a6a76b67 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs @@ -1003,16 +1003,18 @@ internal override void Initialize() // create arrays for widths and alignment Span columnWidths = columns <= StackAllocThreshold ? stackalloc int[columns] : new int[columns]; Span alignment = columns <= StackAllocThreshold ? stackalloc int[columns] : new int[columns]; + Span headerMatchesProperty = columns <= StackAllocThreshold ? stackalloc bool[columns] : new bool[columns]; int k = 0; foreach (TableColumnInfo tci in this.CurrentTableHeaderInfo.tableColumnInfoList) { columnWidths[k] = (columnWidthsHint != null) ? columnWidthsHint[k] : tci.width; alignment[k] = tci.alignment; + headerMatchesProperty[k] = tci.HeaderMatchesProperty; k++; } - this.Writer.Initialize(0, _consoleWidth, columnWidths, alignment, this.CurrentTableHeaderInfo.hideHeader); + this.Writer.Initialize(0, _consoleWidth, columnWidths, alignment, headerMatchesProperty, this.CurrentTableHeaderInfo.hideHeader); } /// @@ -1241,7 +1243,7 @@ internal override void Initialize() alignment[k] = TextAlignment.Left; } - this.Writer.Initialize(0, columnsOnTheScreen, columnWidths, alignment, false, GetConsoleWindowHeight(this.InnerCommand._lo.RowNumber)); + this.Writer.Initialize(leftMarginIndent: 0, columnsOnTheScreen, columnWidths, alignment, headerMatchesProperty: null, suppressHeader: false, screenRows: GetConsoleWindowHeight(this.InnerCommand._lo.RowNumber)); } /// diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Table.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Table.cs index b0efa32dc1f..7c661a5169a 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Table.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Table.cs @@ -172,7 +172,11 @@ private TableHeaderInfo GenerateTableHeaderInfoFromDataBaseInfo(PSObject so) ci.width = colHeader.width; ci.alignment = colHeader.alignment; if (colHeader.label != null) + { + ci.HeaderMatchesProperty = so.Properties[colHeader.label.text] is not null || !ExperimentalFeature.IsEnabled(ExperimentalFeature.PSCustomTableHeaderLabelDecoration); + ci.label = this.dataBaseInfo.db.displayResourceManagerCache.GetTextTokenString(colHeader.label); + } } if (ci.alignment == TextAlignment.Undefined) diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormattingObjects.cs b/src/System.Management.Automation/FormatAndOutput/common/FormattingObjects.cs index f4ac55d1feb..6c999ae33ec 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormattingObjects.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormattingObjects.cs @@ -207,6 +207,7 @@ internal sealed partial class TableColumnInfo : FormatInfoData public int alignment = TextAlignment.Left; public string label = null; public string propertyName = null; + public bool HeaderMatchesProperty = true; } internal sealed class ListViewHeaderInfo : ShapeInfo diff --git a/src/System.Management.Automation/FormatAndOutput/common/PSStyle.cs b/src/System.Management.Automation/FormatAndOutput/common/PSStyle.cs index a217063410a..b6e7b9370e1 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/PSStyle.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/PSStyle.cs @@ -366,6 +366,17 @@ public string TableHeader private string _tableHeader = "\x1b[32;1m"; + /// + /// Gets or sets the style for custom table headers. + /// + public string CustomTableHeaderLabel + { + get => _customTableHeaderLabel; + set => _customTableHeaderLabel = ValidateNoContent(value); + } + + private string _customTableHeaderLabel = "\x1b[32;1;3m"; + /// /// Gets or sets the accent style for errors. /// diff --git a/src/System.Management.Automation/FormatAndOutput/common/TableWriter.cs b/src/System.Management.Automation/FormatAndOutput/common/TableWriter.cs index e21ef5b20d9..49b9005a88e 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/TableWriter.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/TableWriter.cs @@ -22,6 +22,7 @@ private sealed class ColumnInfo internal int startCol = 0; internal int width = 0; internal int alignment = TextAlignment.Left; + internal bool HeaderMatchesProperty = true; } /// /// Class containing information about the tabular layout. @@ -82,9 +83,10 @@ internal static int ComputeWideViewBestItemsPerRowFit(int stringLen, int screenC /// Number of character columns on the screen. /// Array of specified column widths. /// Array of alignment flags. + /// Array of flags where the header label matches a property name. /// If true, suppress header printing. /// Number of rows on the screen. - internal void Initialize(int leftMarginIndent, int screenColumns, Span columnWidths, ReadOnlySpan alignment, bool suppressHeader, int screenRows = int.MaxValue) + internal void Initialize(int leftMarginIndent, int screenColumns, Span columnWidths, ReadOnlySpan alignment, ReadOnlySpan headerMatchesProperty, bool suppressHeader, int screenRows = int.MaxValue) { if (leftMarginIndent < 0) { @@ -139,6 +141,11 @@ internal void Initialize(int leftMarginIndent, int screenColumns, Span colu _si.columnInfo[k].startCol = startCol; _si.columnInfo[k].width = columnWidths[k]; _si.columnInfo[k].alignment = alignment[k]; + if (!headerMatchesProperty.IsEmpty) + { + _si.columnInfo[k].HeaderMatchesProperty = headerMatchesProperty[k]; + } + startCol += columnWidths[k] + ScreenInfo.separatorCharacterCount; } } @@ -156,7 +163,7 @@ internal int GenerateHeader(string[] values, LineOutput lo) foreach (string line in _header) { - lo.WriteLine(style == string.Empty ? line : style + line + reset); + lo.WriteLine(line); } return _header.Count; @@ -234,35 +241,21 @@ internal void GenerateRow(string[] values, LineOutput lo, bool multiLine, ReadOn if (multiLine) { - foreach (string line in GenerateTableRow(values, currentAlignment, lo.DisplayCells)) + foreach (string line in GenerateTableRow(values, currentAlignment, lo.DisplayCells, isHeader)) { generatedRows?.Add(line); - if (isHeader) - { - lo.WriteLine(style == string.Empty ? line : style + line + reset); - } - else - { - lo.WriteLine(line); - } + lo.WriteLine(line); } } else { - string line = GenerateRow(values, currentAlignment, dc); + string line = GenerateRow(values, currentAlignment, dc, isHeader); generatedRows?.Add(line); - if (isHeader) - { - lo.WriteLine(style == string.Empty ? line : style + line + reset); - } - else - { - lo.WriteLine(line); - } + lo.WriteLine(line); } } - private string[] GenerateTableRow(string[] values, ReadOnlySpan alignment, DisplayCells ds) + private string[] GenerateTableRow(string[] values, ReadOnlySpan alignment, DisplayCells ds, bool isHeader) { // select the active columns (skip hidden ones) Span validColumnArray = _si.columnInfo.Length <= OutCommandInner.StackAllocThreshold ? stackalloc int[_si.columnInfo.Length] : new int[_si.columnInfo.Length]; @@ -291,8 +284,7 @@ private string[] GenerateTableRow(string[] values, ReadOnlySpan alignment, } // obtain a set of tokens for each field - scArray[k] = GenerateMultiLineRowField(values[validColumnArray[k]], validColumnArray[k], - alignment[validColumnArray[k]], ds, addPadding); + scArray[k] = GenerateMultiLineRowField(values[validColumnArray[k]], validColumnArray[k], alignment[validColumnArray[k]], ds, addPadding); // NOTE: the following padding operations assume that we // pad with a blank (or any character that ALWAYS maps to a single screen cell @@ -323,7 +315,9 @@ private string[] GenerateTableRow(string[] values, ReadOnlySpan alignment, for (int k = 0; k < scArray.Length; k++) { if (scArray[k].Count > screenRows) + { screenRows = scArray[k].Count; + } } // column headers can span multiple rows if the width of the column is shorter than the header text like: @@ -335,7 +329,6 @@ private string[] GenerateTableRow(string[] values, ReadOnlySpan alignment, // 1 2 3 // // To ensure we don't add whitespace to the end, we need to determine the last column in each row with content - System.Span lastColWithContent = screenRows <= OutCommandInner.StackAllocThreshold ? stackalloc int[screenRows] : new int[screenRows]; for (int row = 0; row < screenRows; row++) { @@ -390,17 +383,36 @@ private string[] GenerateTableRow(string[] values, ReadOnlySpan alignment, for (int row = 0; row < screenRows; row++) { StringBuilder sb = new StringBuilder(); + // for a given row, walk the columns for (int col = 0; col < scArray.Length; col++) { + string value = scArray[col][row]; + // if the column is the last column with content, we need to trim trailing whitespace, unless there is only one row if (col == lastColWithContent[row] && screenRows > 1) { - sb.Append(scArray[col][row].TrimEnd()); + value = value.TrimEnd(); } - else + + if (isHeader) { - sb.Append(scArray[col][row]); + if (_si.columnInfo[col].HeaderMatchesProperty) + { + sb.Append(PSStyle.Instance.Formatting.TableHeader); + } + else if (value.Length > 0) + { + // after the first column, each additional column starts with a whitespace for separation + value = value.Insert(col == 0 ? 0 : 1, PSStyle.Instance.Formatting.CustomTableHeaderLabel); + } + } + + sb.Append(value); + + if (isHeader) + { + sb.Append(PSStyle.Instance.Reset); } } @@ -427,7 +439,7 @@ private StringCollection GenerateMultiLineRowField(string val, int k, int alignm return sc; } - private string GenerateRow(string[] values, ReadOnlySpan alignment, DisplayCells dc) + private string GenerateRow(string[] values, ReadOnlySpan alignment, DisplayCells dc, bool isHeader) { StringBuilder sb = new StringBuilder(); @@ -462,9 +474,14 @@ private string GenerateRow(string[] values, ReadOnlySpan alignment, Display } string rowField = GenerateRowField(values[k], _si.columnInfo[k].width, alignment[k], dc, addPadding); + if (isHeader) + { + sb.Append(PSStyle.Instance.Formatting.TableHeader); + } + sb.Append(rowField); - if (rowField is not null && rowField.Contains(ValueStringDecorated.ESC) && !rowField.AsSpan().TrimEnd().EndsWith(PSStyle.Instance.Reset)) + if (isHeader || (rowField is not null && rowField.Contains(ValueStringDecorated.ESC) && !rowField.AsSpan().TrimEnd().EndsWith(PSStyle.Instance.Reset))) { // Reset the console output if the content of this column contains ESC sb.Append(PSStyle.Instance.Reset); diff --git a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs index 8eaf3822075..d83bd4bc8f3 100644 --- a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs +++ b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs @@ -22,6 +22,7 @@ public class ExperimentalFeature internal const string EngineSource = "PSEngine"; internal const string PSNativeCommandErrorActionPreferenceFeatureName = "PSNativeCommandErrorActionPreference"; + internal const string PSCustomTableHeaderLabelDecoration = "PSCustomTableHeaderLabelDecoration"; #endregion @@ -116,6 +117,9 @@ static ExperimentalFeature() new ExperimentalFeature( name: PSNativeCommandErrorActionPreferenceFeatureName, description: "Native commands with non-zero exit codes issue errors according to $ErrorActionPreference when $PSNativeCommandUseErrorActionPreference is $true"), + new ExperimentalFeature( + name: PSCustomTableHeaderLabelDecoration, + description: "Formatting differentiation for table header labels that aren't property members"), }; EngineExperimentalFeatures = new ReadOnlyCollection(engineFeatures); diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Format-Table.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Format-Table.Tests.ps1 index 47364842b78..67933d2801d 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Format-Table.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Format-Table.Tests.ps1 @@ -876,10 +876,10 @@ Describe 'Table color tests' { $PSStyle.OutputRendering = $originalRendering } - It 'Table header should use FormatAccent' { + It 'Table header should use TableHeader' { ([pscustomobject]@{foo = 1} | Format-Table | Out-String).Trim() | Should -BeExactly @" -$($PSStyle.Formatting.FormatAccent)foo$($PSStyle.Reset) -$($PSStyle.Formatting.FormatAccent)---$($PSStyle.Reset) +$($PSStyle.Formatting.TableHeader)foo$($PSStyle.Reset) +$($PSStyle.Formatting.TableHeader)---$($PSStyle.Reset) 1 "@ } diff --git a/test/powershell/engine/Formatting/PSStyle.Tests.ps1 b/test/powershell/engine/Formatting/PSStyle.Tests.ps1 index e232ebe6d57..c1da9b6b6ab 100644 --- a/test/powershell/engine/Formatting/PSStyle.Tests.ps1 +++ b/test/powershell/engine/Formatting/PSStyle.Tests.ps1 @@ -24,6 +24,7 @@ Describe 'Tests for $PSStyle automatic variable' { $formattingDefaults = @{ FormatAccent = "`e[32;1m" TableHeader = "`e[32;1m" + CustomTableHeaderLabel = "`e[32;1;3m" ErrorAccent = "`e[36;1m" Error = "`e[31;1m" Debug = "`e[33;1m" @@ -191,7 +192,7 @@ Describe 'Tests for $PSStyle automatic variable' { $PSStyle.OutputRendering = 'Ansi' $PSStyle.Formatting.TableHeader = '' $out = $PSVersionTable | Format-Table | Out-String - $out.Contains("`e[") | Should -BeFalse + $out.Replace($PSStyle.Reset,'').Contains("`e[") | Should -BeFalse } finally { $PSStyle.OutputRendering = $oldRender @@ -199,6 +200,25 @@ Describe 'Tests for $PSStyle automatic variable' { } } + It '$PSStyle.Formatting.CustomTableHeaderLabel is applied to Format-Table' { + $old = $PSStyle.Formatting.CustomTableHeaderLabel + $oldRender = $PSStyle.OutputRendering + + try { + $PSStyle.OutputRendering = 'Ansi' + $PSStyle.Formatting.CustomTableHeaderLabel = $PSStyle.Foreground.Blue + $PSStyle.Background.White + $PSStyle.Bold + $out = Get-Process pwsh | Select-Object -First 1 | Format-Table | Out-String + $format = $PSStyle.Formatting.CustomTableHeaderLabel.Replace('[',"``[") + $header = $PSStyle.Formatting.TableHeader.Replace('[',"``[") + $reset = $PSStyle.Reset.Replace('[',"``[") + $out | Should -BeLike "*${format}*NPM(K)${reset}*${format}*PM(M)${reset}*${format}*WS(M)${reset}*${format}*CPU(s)${reset}*${header}*Id${reset}*${header}*SI${reset}*${header}*ProcessName${reset}*" + } + finally { + $PSStyle.OutputRendering = $oldRender + $PSStyle.Formatting.CustomTableHeaderLabel = $old + } + } + It 'Should fail if setting formatting contains printable characters: .' -TestCases @( @{ Submember = 'Reset' } @{ Submember = 'BlinkOff' } @@ -215,6 +235,7 @@ Describe 'Tests for $PSStyle automatic variable' { @{ Submember = 'Strikethrough' } @{ Member = 'Formatting'; Submember = 'FormatAccent' } @{ Member = 'Formatting'; Submember = 'TableHeader' } + @{ Member = 'Formatting'; Submember = 'CustomTableHeaderLabel' } @{ Member = 'Formatting'; Submember = 'ErrorAccent' } @{ Member = 'Formatting'; Submember = 'Error' } @{ Member = 'Formatting'; Submember = 'Warning' } @@ -380,8 +401,8 @@ Describe 'Handle strings with escape sequences in formatting' { It 'Truncation for strings with no escape sequences' { $expected = @" -`e[32;1mName Role YIR`e[0m -`e[32;1m---- ---- ---`e[0m +`e[32;1mName `e[0m`e[32;1m Role `e[0m`e[32;1m YIR`e[0m +`e[32;1m---- `e[0m `e[32;1m---- `e[0m `e[32;1m---`e[0m Bob Saggat Developer 2 John Seym… Sw Engineer 6 Billy Bob… Senior DevOps … 13 @@ -398,8 +419,8 @@ Billy Bob… Senior DevOps … 13 It "Truncation for strings with escape sequences - TableView-1" { $expected = @" -`e[32;1mName Role YIR`e[0m -`e[32;1m---- ---- ---`e[0m +`e[32;1mName `e[0m`e[32;1m Role `e[0m`e[32;1m YIR`e[0m +`e[32;1m---- `e[0m `e[32;1m---- `e[0m `e[32;1m---`e[0m `e[32mBob Saggat`e[39m`e[0m Developer 2 `e[33mJohn Seym…`e[0m Sw Engineer 6 `e[31mBilly Bob…`e[0m Senior DevOps … 13 @@ -420,8 +441,8 @@ Billy Bob… Senior DevOps … 13 It "Truncation for strings with escape sequences - TableView-2" { $expected = @" -`e[32;1mName Role YIR`e[0m -`e[32;1m---- ---- ---`e[0m +`e[32;1mName `e[0m`e[32;1m Role `e[0m`e[32;1m YIR`e[0m +`e[32;1m---- `e[0m `e[32;1m---- `e[0m `e[32;1m---`e[0m `e[32mBob Saggat`e[39m`e[0m Developer`e[0m 2 `e[33mJohn Seym…`e[0m `e[1;33mSw Engineer`e[0m 6 `e[31mBilly Bob…`e[0m `e[42m`e[1;33mSenior DevOps …`e[0m 13 From fd94bea229aae27c91de01fb1daaade5904cdd8d Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 4 Oct 2022 06:31:11 -0700 Subject: [PATCH 091/779] Bump `Microsoft.PowerShell.Native` from `7.3.0-preview.1` to `7.3.0-rc.1` (#18217) --- .../System.Management.Automation.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/System.Management.Automation/System.Management.Automation.csproj b/src/System.Management.Automation/System.Management.Automation.csproj index 03414ef381b..75deb301ba1 100644 --- a/src/System.Management.Automation/System.Management.Automation.csproj +++ b/src/System.Management.Automation/System.Management.Automation.csproj @@ -28,7 +28,7 @@ - + From 3a506b96924d16714e8708c1e034aa81a2259dc2 Mon Sep 17 00:00:00 2001 From: Ilya Date: Tue, 4 Oct 2022 21:33:37 +0500 Subject: [PATCH 092/779] Fix decompression in web cmdlets (#17955) --- .../Common/WebRequestPSCmdlet.Common.cs | 2 +- .../commands/utility/WebCmdlet/StreamHelper.cs | 16 ---------------- .../WebCmdlets.Tests.ps1 | 14 +++++++------- 3 files changed, 8 insertions(+), 24 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index 692c895d211..85932f7eb86 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -992,9 +992,9 @@ private HttpMethod GetHttpMethod(WebRequestMethod method) // and PreserveAuthorizationOnRedirect is NOT set. internal virtual HttpClient GetHttpClient(bool handleRedirect) { - // By default the HttpClientHandler will automatically decompress GZip and Deflate content HttpClientHandler handler = new(); handler.CookieContainer = WebSession.Cookies; + handler.AutomaticDecompression = DecompressionMethods.All; // set the credentials used by this request if (WebSession.UseDefaultCredentials) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs index b9345ff2606..9314cfd1a5d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs @@ -3,7 +3,6 @@ using System; using System.IO; -using System.IO.Compression; using System.Management.Automation; using System.Management.Automation.Internal; using System.Net.Http; @@ -502,21 +501,6 @@ internal static byte[] EncodeToBytes(string str) internal static Stream GetResponseStream(HttpResponseMessage response) { Stream responseStream = response.Content.ReadAsStreamAsync().GetAwaiter().GetResult(); - var contentEncoding = response.Content.Headers.ContentEncoding; - - // HttpClient by default will automatically decompress GZip and Deflate content. - // We keep this decompression logic here just in case. - if (contentEncoding != null && contentEncoding.Count > 0) - { - if (contentEncoding.Contains("gzip")) - { - responseStream = new GZipStream(responseStream, CompressionMode.Decompress); - } - else if (contentEncoding.Contains("deflate")) - { - responseStream = new DeflateStream(responseStream, CompressionMode.Decompress); - } - } return responseStream; } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 index 7a5ad26d545..c7d75bc75ed 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 @@ -587,8 +587,8 @@ Describe "Invoke-WebRequest tests" -Tags "Feature", "RequireAdminOnWindows" { # $dataEncodings = @("Chunked", "Compress", "Deflate", "GZip", "Identity") # Note: These are the supported options, but we do not have a web service to test them all. It "Invoke-WebRequest supports request that returns -encoded data." -TestCases @( - @{ DataEncoding = "gzip"} - @{ DataEncoding = "deflate"} + @{ DataEncoding = "gzip" } + @{ DataEncoding = "deflate" } ) { param($dataEncoding) $uri = Get-WebListenerUrl -Test 'Compression' -TestValue $dataEncoding @@ -598,7 +598,7 @@ Describe "Invoke-WebRequest tests" -Tags "Feature", "RequireAdminOnWindows" { ValidateResponse -response $result # Validate response content - $result.Output.Headers.'Content-Encoding'[0] | Should -BeExactly $dataEncoding + # The content should be de-compressed, and otherwise converting from JSON will fail. $jsonContent = $result.Output.Content | ConvertFrom-Json $jsonContent.Headers.Host | Should -BeExactly $uri.Authority } @@ -2246,15 +2246,15 @@ Describe "Invoke-RestMethod tests" -Tags "Feature", "RequireAdminOnWindows" { # $dataEncodings = @("Chunked", "Compress", "Deflate", "GZip", "Identity") # Note: These are the supported options, but we do not have a web service to test them all. It "Invoke-RestMethod supports request that returns -encoded data." -TestCases @( - @{ DataEncoding = "gzip"} - @{ DataEncoding = "deflate"} + @{ DataEncoding = "gzip" } + @{ DataEncoding = "deflate" } ) { param($dataEncoding) $uri = Get-WebListenerUrl -Test 'Compression' -TestValue $dataEncoding - $result = Invoke-RestMethod -Uri $uri -ResponseHeadersVariable 'headers' + $result = Invoke-RestMethod -Uri $uri # Validate response content - $headers.'Content-Encoding'[0] | Should -BeExactly $dataEncoding + # The content should be de-compressed. Otherwise, the above 'Invoke-RestMethod' would have thrown because converting to JSON internally would fail. $result.Headers.Host | Should -BeExactly $uri.Authority } From 19ea6fb4a5c917070e862622f191a2fc725e9344 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 4 Oct 2022 10:11:26 -0700 Subject: [PATCH 093/779] Bump Microsoft.CodeAnalysis.NetAnalyzers (#18216) --- Analyzers.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Analyzers.props b/Analyzers.props index 5628efac862..71551e0f8db 100644 --- a/Analyzers.props +++ b/Analyzers.props @@ -1,7 +1,7 @@ - + From 0e4358cf930b73fcaa11a5045e2aaac483cff725 Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Tue, 4 Oct 2022 10:17:09 -0700 Subject: [PATCH 094/779] Improve startup time by triggering initialization of additional types on background thread (#18195) --- .../engine/InitialSessionState.cs | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/src/System.Management.Automation/engine/InitialSessionState.cs b/src/System.Management.Automation/engine/InitialSessionState.cs index e5b306a7801..37cd5f19e74 100644 --- a/src/System.Management.Automation/engine/InitialSessionState.cs +++ b/src/System.Management.Automation/engine/InitialSessionState.cs @@ -44,22 +44,28 @@ internal static void Init() // We shouldn't create too many tasks. #if !UNIX - // Amsi initialize can be a little slow + // Amsi initialize can be a little slow. Task.Run(() => AmsiUtils.WinScanContent(content: string.Empty, sourceMetadata: string.Empty, warmUp: true)); #endif + // Initialize the types 'Compiler', 'CachedReflectionInfo', and 'ExpressionCache'. + // Their type initializers do a lot of reflection operations. + // We will access 'Compiler' members when creating the first session state. + Task.Run(() => _ = Compiler.DottedLocalsTupleType); // One other task for other stuff that's faster, but still a little slow. Task.Run(() => { - // Loading the resources for System.Management.Automation can be expensive, so force that to - // happen early on a background thread. + // Loading the resources for System.Management.Automation can be expensive, + // so force that to happen early on a background thread. _ = RunspaceInit.OutputEncodingDescription; // This will init some tables and could load some assemblies. - _ = TypeAccelerators.builtinTypeAccelerators; + // We will access 'LanguagePrimitives' when binding built-in variables for the Runspace. + LanguagePrimitives.GetEnumerator(null); // This will init some tables and could load some assemblies. - LanguagePrimitives.GetEnumerator(null); + // We will access 'TypeAccelerators' when auto-loading the PSReadLine module, which happens last. + _ = TypeAccelerators.builtinTypeAccelerators; }); } } From 67a3830fec18b16ac962b9a5707fc8e0eaec86b5 Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Tue, 4 Oct 2022 10:17:48 -0700 Subject: [PATCH 095/779] Remove XML files for min-size package (#18189) --- build.psm1 | 11 +++++------ tools/packaging/packaging.psm1 | 7 +++---- .../azureDevOps/templates/windows-packaging.yml | 4 ++++ 3 files changed, 12 insertions(+), 10 deletions(-) diff --git a/build.psm1 b/build.psm1 index 4a92627eab3..3d42e66e637 100644 --- a/build.psm1 +++ b/build.psm1 @@ -1602,14 +1602,14 @@ function Show-PSPesterError $description = $testFailure.description $name = $testFailure.name $message = $testFailure.failure.message - $StackTrace = $testFailure.failure."stack-trace" + $stack_trace = $testFailure.failure."stack-trace" } elseif ($PSCmdlet.ParameterSetName -eq 'object') { $description = $testFailureObject.Describe + '/' + $testFailureObject.Context $name = $testFailureObject.Name $message = $testFailureObject.FailureMessage - $StackTrace = $testFailureObject.StackTrace + $stack_trace = $testFailureObject.StackTrace } else { @@ -1621,7 +1621,7 @@ function Show-PSPesterError Write-Log -isError -message "message:" Write-Log -isError -message $message Write-Log -isError -message "stack-trace:" - Write-Log -isError -message $StackTrace + Write-Log -isError -message $stack_trace } @@ -1659,14 +1659,14 @@ function Test-XUnitTestResults $description = $failure.type $name = $failure.method $message = $failure.failure.message - $StackTrace = $failure.failure.'stack-trace' + $stack_trace = $failure.failure.'stack-trace' Write-Log -isError -message ("Description: " + $description) Write-Log -isError -message ("Name: " + $name) Write-Log -isError -message "message:" Write-Log -isError -message $message Write-Log -isError -message "stack-trace:" - Write-Log -isError -message $StackTrace + Write-Log -isError -message $stack_trace Write-Log -isError -message " " } @@ -2846,7 +2846,6 @@ assembly # only create an assembly group if we have tests if ( $tCases.count -eq 0 -and ! $includeEmpty ) { continue } $tGroup = $tCases | Group-Object result - $total = $tCases.Count $asm = [testassembly]::new() $asm.environment = $environment $asm."run-date" = $rundate diff --git a/tools/packaging/packaging.psm1 b/tools/packaging/packaging.psm1 index 775270acaba..d3484793a74 100644 --- a/tools/packaging/packaging.psm1 +++ b/tools/packaging/packaging.psm1 @@ -4587,7 +4587,6 @@ function Invoke-AzDevOpsLinuxPackageBuild { # Remove symbol files, xml document files. Remove-Item "${buildFolder}\*.pdb", "${buildFolder}\*.xml" -Force - ## Build 'linux-arm' and create 'tar.gz' package for it. ## Note that 'linux-arm' can only be built on Ubuntu environment. $buildFolder = "${env:SYSTEM_ARTIFACTSDIRECTORY}/${arm32LinuxBuildFolder}" @@ -4600,14 +4599,14 @@ function Invoke-AzDevOpsLinuxPackageBuild { # Remove symbol files. Remove-Item "${buildFolder}\*.pdb" -Force } elseif ($BuildType -eq 'rpm') { - ## Build 'min-size' + ## Build for Mariner $options = Get-PSOptions - Write-Verbose -Verbose "---- Min-Size ----" + Write-Verbose -Verbose "---- Mariner ----" Write-Verbose -Verbose "options.Output: $($options.Output)" Write-Verbose -Verbose "options.Top $($options.Top)" $binDir = Join-Path -Path $options.Top -ChildPath 'bin' if (Test-Path -Path $binDir) { - Write-Verbose -Verbose "Remove $binDir, to get a clean build for min-size package" + Write-Verbose -Verbose "Remove $binDir, to get a clean build for Mariner package" Remove-Item -Path $binDir -Recurse -Force } diff --git a/tools/releaseBuild/azureDevOps/templates/windows-packaging.yml b/tools/releaseBuild/azureDevOps/templates/windows-packaging.yml index cb5b7ea8e7b..befcebf3bd3 100644 --- a/tools/releaseBuild/azureDevOps/templates/windows-packaging.yml +++ b/tools/releaseBuild/azureDevOps/templates/windows-packaging.yml @@ -202,6 +202,10 @@ jobs: $BuildPath = '$(System.ArtifactsDirectory)\$(SymbolsFolder)' Update-PSSignedBuildFolder -BuildPath $BuildPath -SignedFilesPath $SignedFilesPath + if ($env:BuildConfiguration -eq 'minSize') { + ## Remove XML files when making a min-size package. + Remove-Item "$BuildPath/*.xml" -Force + } displayName: Merge ThirdParty signed files with Build condition: and(succeeded(), eq(variables['SHOULD_SIGN'], 'true')) From b90a1e65a3fd9d4a5092c401469a622a77940e36 Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Tue, 4 Oct 2022 16:17:45 -0700 Subject: [PATCH 096/779] Remove unnecessary native dependencies from the package (#18213) --- PowerShell.Common.props | 16 +--------- assets/wix/files.wxs | 16 +++------- build.psm1 | 67 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 72 insertions(+), 27 deletions(-) diff --git a/PowerShell.Common.props b/PowerShell.Common.props index 99b53418049..5e7e41f1470 100644 --- a/PowerShell.Common.props +++ b/PowerShell.Common.props @@ -172,16 +172,11 @@ true true true + portable - true - full - - - - true full @@ -193,15 +188,6 @@ Debugging the issues resolves the problem --> false - portable - - - - - - true - true - portable diff --git a/assets/wix/files.wxs b/assets/wix/files.wxs index 4a9c36ad3d7..c0ca7d624d4 100644 --- a/assets/wix/files.wxs +++ b/assets/wix/files.wxs @@ -2936,9 +2936,6 @@ - - - @@ -3023,9 +3020,6 @@ - - - @@ -3089,9 +3083,6 @@ - - - @@ -3153,6 +3144,9 @@ + + + @@ -4052,7 +4046,6 @@ - @@ -4081,7 +4074,6 @@ - @@ -4103,7 +4095,6 @@ - @@ -4166,6 +4157,7 @@ + diff --git a/build.psm1 b/build.psm1 index 3d42e66e637..de6a13834b4 100644 --- a/build.psm1 +++ b/build.psm1 @@ -674,6 +674,8 @@ Fix steps: Restore-PSPester -Destination (Join-Path $publishPath "Modules") } + Clear-NativeDependencies -PublishFolder $publishPath + if ($PSOptionsPath) { $resolvedPSOptionsPath = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($PSOptionsPath) $parent = Split-Path -Path $resolvedPSOptionsPath @@ -3357,3 +3359,68 @@ function Find-AzCopy { $azCopy = Get-Command -Name azCopy -ErrorAction Stop | Select-Object -First 1 return $azCopy.Path } + +function Clear-NativeDependencies +{ + param( + [Parameter(Mandatory=$true)] [string] $PublishFolder + ) + + $diasymFileNamePattern = 'microsoft.diasymreader.native.{0}.dll' + + switch -regex ($($script:Options.Runtime)) { + '.*-x64' { + $diasymFileName = $diasymFileNamePattern -f 'amd64' + } + '.*-x86' { + $diasymFileName = $diasymFileNamePattern -f 'x86' + } + '.*-arm' { + $diasymFileName = $diasymFileNamePattern -f 'arm' + } + '.*-arm64' { + $diasymFileName = $diasymFileNamePattern -f 'arm64' + } + 'fxdependent.*' { + Write-Verbose -Message "$($script:Options.Runtime) is a fxdependent runtime, skipping diasymreader removal" -Verbose + $diasymFileName = $null + } + Default { + throw "Unknown runtime $($script:Options.Runtime)" + } + } + + $filesToDeleteCore = @($diasymFileName) + + $filesToDeleteWinDesktop = @('penimc_cor3.dll') + + $deps = Get-Content "$PublishFolder/pwsh.deps.json" -Raw | ConvertFrom-Json -Depth 20 + $targetRuntime = ".NETCoreApp,Version=v7.0/$($script:Options.Runtime)" + + $runtimePackNetCore = $deps.targets.${targetRuntime}.PSObject.Properties.Name -like 'runtimepack.Microsoft.NETCore.App.Runtime*' + $runtimePackWinDesktop = $deps.targets.${targetRuntime}.PSObject.Properties.Name -like 'runtimepack.Microsoft.WindowsDesktop.App.Runtime*' + + if ($runtimePackNetCore) + { + $filesToDeleteCore | ForEach-Object { + Write-Verbose "Removing $_ from pwsh.deps.json" -Verbose + $deps.targets.${targetRuntime}.${runtimePackNetCore}.native.PSObject.Properties.Remove($_) + if (Test-Path $PublishFolder/$_) { + Remove-Item -Path $PublishFolder/$_ -Force -Verbose + } + } + } + + if ($runtimePackWinDesktop) + { + $filesToDeleteWinDesktop | ForEach-Object { + Write-Verbose "Removing $_ from pwsh.deps.json" -Verbose + $deps.targets.${targetRuntime}.${runtimePackWinDesktop}.native.PSObject.Properties.Remove($_) + if (Test-Path $PublishFolder/$_) { + Remove-Item -Path $PublishFolder/$_ -Force -Verbose + } + } + } + + $deps | ConvertTo-Json -Depth 20 | Set-Content "$PublishFolder/pwsh.deps.json" -Force +} From 48f8475826d040ec6d3c67840bf2b857bfd40b95 Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Tue, 4 Oct 2022 16:21:54 -0700 Subject: [PATCH 097/779] Add branch counter to APIScan build (#18214) --- .../releaseBuild/azureDevOps/templates/compliance/apiscan.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tools/releaseBuild/azureDevOps/templates/compliance/apiscan.yml b/tools/releaseBuild/azureDevOps/templates/compliance/apiscan.yml index 0aa6c498f4c..55a40f34e00 100644 --- a/tools/releaseBuild/azureDevOps/templates/compliance/apiscan.yml +++ b/tools/releaseBuild/azureDevOps/templates/compliance/apiscan.yml @@ -12,6 +12,10 @@ jobs: # PAT permissions NOTE: Declare a SymbolServerPAT variable in this group with a 'microsoft' organizanization scoped PAT with 'Symbols' Read permission. # A PAT in the wrong org will give a single Error 203. No PAT will give a single Error 401, and individual pdbs may be missing even if permissions are correct. - group: symbols + - name: branchCounterKey + value: $[format('{0:yyyyMMdd}-{1}', pipeline.startTime,variables['Build.SourceBranch'])] + - name: branchCounter + value: $[counter(variables['branchCounterKey'], 1)] pool: name: PowerShell1ES From 29c27784cb68b2420ffc35445cef3f06dda68419 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Thu, 6 Oct 2022 11:38:45 -0700 Subject: [PATCH 098/779] Update the cgmanifest (#18197) Co-authored-by: adityapatwardhan --- tools/cgmanifest.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tools/cgmanifest.json b/tools/cgmanifest.json index 522535be7b4..0a335fdfbe1 100644 --- a/tools/cgmanifest.json +++ b/tools/cgmanifest.json @@ -65,7 +65,7 @@ "Type": "nuget", "Nuget": { "Name": "Microsoft.CodeAnalysis.Common", - "Version": "4.3.0" + "Version": "4.3.1" } }, "DevelopmentDependency": false @@ -75,7 +75,7 @@ "Type": "nuget", "Nuget": { "Name": "Microsoft.CodeAnalysis.CSharp", - "Version": "4.3.0" + "Version": "4.3.1" } }, "DevelopmentDependency": false From 9e05d675cb83a43e92a7ddb5decc0bc86a0d03a0 Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Thu, 6 Oct 2022 11:42:47 -0700 Subject: [PATCH 099/779] Do not cleanup `pwsh.deps.json` for framework dependent packages (#18226) --- build.psm1 | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/build.psm1 b/build.psm1 index de6a13834b4..17fb59711a9 100644 --- a/build.psm1 +++ b/build.psm1 @@ -3382,8 +3382,8 @@ function Clear-NativeDependencies $diasymFileName = $diasymFileNamePattern -f 'arm64' } 'fxdependent.*' { - Write-Verbose -Message "$($script:Options.Runtime) is a fxdependent runtime, skipping diasymreader removal" -Verbose - $diasymFileName = $null + Write-Verbose -Message "$($script:Options.Runtime) is a fxdependent runtime, no cleanup needed in pwsh.deps.json" -Verbose + return } Default { throw "Unknown runtime $($script:Options.Runtime)" From 7073525059dc245ed3693d515f34fa93052d85a9 Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Thu, 6 Oct 2022 15:26:22 -0700 Subject: [PATCH 100/779] Avoid using `Regex` when not necessary (#18210) --- .../host/msh/ConsoleHostRawUserInterface.cs | 21 ++++------ .../ConsoleHostRawUserInterfaceStrings.resx | 5 +-- .../engine/PSVersionInfo.cs | 40 +++++++++---------- 3 files changed, 28 insertions(+), 38 deletions(-) diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs index 4db0882221c..f5937d21e0f 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs @@ -41,23 +41,16 @@ class ConsoleHostRawUserInterface : System.Management.Automation.Host.PSHostRawU // (we may load resources which can take some time) Task.Run(() => { - WindowsIdentity identity = WindowsIdentity.GetCurrent(); - WindowsPrincipal principal = new WindowsPrincipal(identity); + var identity = WindowsIdentity.GetCurrent(); + var principal = new WindowsPrincipal(identity); if (principal.IsInRole(WindowsBuiltInRole.Administrator)) { - string prefix = ConsoleHostRawUserInterfaceStrings.WindowTitleElevatedPrefix; - - // check using Regex if the window already has Administrator: prefix - // (i.e. from the parent console process) - string titlePattern = ConsoleHostRawUserInterfaceStrings.WindowTitleTemplate; - titlePattern = Regex.Escape(titlePattern) - .Replace(@"\{1}", ".*") - .Replace(@"\{0}", Regex.Escape(prefix)); - if (!Regex.IsMatch(this.WindowTitle, titlePattern)) + // Check if the window already has the "Administrator: " prefix (i.e. from the parent console process). + ReadOnlySpan prefix = ConsoleHostRawUserInterfaceStrings.WindowTitleElevatedPrefix; + ReadOnlySpan windowTitle = WindowTitle; + if (!windowTitle.StartsWith(prefix)) { - this.WindowTitle = StringUtil.Format(ConsoleHostRawUserInterfaceStrings.WindowTitleTemplate, - prefix, - this.WindowTitle); + WindowTitle = string.Concat(prefix, windowTitle); } } }); diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/ConsoleHostRawUserInterfaceStrings.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/ConsoleHostRawUserInterfaceStrings.resx index bf47782fdb0..c640b2c4a89 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/resources/ConsoleHostRawUserInterfaceStrings.resx +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/ConsoleHostRawUserInterfaceStrings.resx @@ -172,9 +172,6 @@ Window title cannot be longer than {0} characters. - Administrator - - - {0}: {1} + Administrator: diff --git a/src/System.Management.Automation/engine/PSVersionInfo.cs b/src/System.Management.Automation/engine/PSVersionInfo.cs index 99740a44d13..0d292c48520 100644 --- a/src/System.Management.Automation/engine/PSVersionInfo.cs +++ b/src/System.Management.Automation/engine/PSVersionInfo.cs @@ -53,20 +53,20 @@ public static class PSVersionInfo /// For each later release of PowerShell, this constant needs to /// be updated to reflect the right version. /// - private static readonly Version s_psV1Version = new Version(1, 0); - private static readonly Version s_psV2Version = new Version(2, 0); - private static readonly Version s_psV3Version = new Version(3, 0); - private static readonly Version s_psV4Version = new Version(4, 0); - private static readonly Version s_psV5Version = new Version(5, 0); - private static readonly Version s_psV51Version = new Version(5, 1, NTVerpVars.PRODUCTBUILD, NTVerpVars.PRODUCTBUILD_QFE); - private static readonly SemanticVersion s_psV6Version = new SemanticVersion(6, 0, 0, preReleaseLabel: null, buildLabel: null); - private static readonly SemanticVersion s_psV61Version = new SemanticVersion(6, 1, 0, preReleaseLabel: null, buildLabel: null); - private static readonly SemanticVersion s_psV62Version = new SemanticVersion(6, 2, 0, preReleaseLabel: null, buildLabel: null); - private static readonly SemanticVersion s_psV7Version = new SemanticVersion(7, 0, 0, preReleaseLabel: null, buildLabel: null); - private static readonly SemanticVersion s_psV71Version = new SemanticVersion(7, 1, 0, preReleaseLabel: null, buildLabel: null); - private static readonly SemanticVersion s_psV72Version = new SemanticVersion(7, 2, 0, preReleaseLabel: null, buildLabel: null); - private static readonly SemanticVersion s_psSemVersion; + private static readonly Version s_psV1Version = new(1, 0); + private static readonly Version s_psV2Version = new(2, 0); + private static readonly Version s_psV3Version = new(3, 0); + private static readonly Version s_psV4Version = new(4, 0); + private static readonly Version s_psV5Version = new(5, 0); + private static readonly Version s_psV51Version = new(5, 1, NTVerpVars.PRODUCTBUILD, NTVerpVars.PRODUCTBUILD_QFE); + private static readonly Version s_psV6Version = new(6, 0, 0); + private static readonly Version s_psV61Version = new(6, 1, 0); + private static readonly Version s_psV62Version = new(6, 2, 0); + private static readonly Version s_psV7Version = new(7, 0, 0); + private static readonly Version s_psV71Version = new(7, 1, 0); + private static readonly Version s_psV72Version = new(7, 2, 0); private static readonly Version s_psVersion; + private static readonly SemanticVersion s_psSemVersion; /// /// A constant to track current PowerShell Edition. @@ -108,13 +108,13 @@ static PSVersionInfo() s_psSemVersion = new SemanticVersion(mainVersion); s_psVersion = (Version)s_psSemVersion; - s_psVersionTable[PSVersionInfo.PSVersionName] = s_psSemVersion; - s_psVersionTable[PSVersionInfo.PSEditionName] = PSEditionValue; + s_psVersionTable[PSVersionName] = s_psSemVersion; + s_psVersionTable[PSEditionName] = PSEditionValue; s_psVersionTable[PSGitCommitIdName] = rawGitCommitId; s_psVersionTable[PSCompatibleVersionsName] = new Version[] { s_psV1Version, s_psV2Version, s_psV3Version, s_psV4Version, s_psV5Version, s_psV51Version, s_psV6Version, s_psV61Version, s_psV62Version, s_psV7Version, s_psV71Version, s_psV72Version, s_psVersion }; - s_psVersionTable[PSVersionInfo.SerializationVersionName] = new Version(InternalSerializer.DefaultVersion); - s_psVersionTable[PSVersionInfo.PSRemotingProtocolVersionName] = RemotingConstants.ProtocolVersion; - s_psVersionTable[PSVersionInfo.WSManStackVersionName] = GetWSManStackVersion(); + s_psVersionTable[SerializationVersionName] = new Version(InternalSerializer.DefaultVersion); + s_psVersionTable[PSRemotingProtocolVersionName] = RemotingConstants.ProtocolVersion; + s_psVersionTable[WSManStackVersionName] = GetWSManStackVersion(); s_psVersionTable[PSPlatformName] = Environment.OSVersion.Platform.ToString(); s_psVersionTable[PSOSName] = Runtime.InteropServices.RuntimeInformation.OSDescription; } @@ -330,12 +330,12 @@ internal static Version PSV51Version get { return s_psV51Version; } } - internal static SemanticVersion PSV6Version + internal static Version PSV6Version { get { return s_psV6Version; } } - internal static SemanticVersion PSV7Version + internal static Version PSV7Version { get { return s_psV7Version; } } From 667e75559dda586917e8f2ea87215378d38d00db Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Thu, 6 Oct 2022 20:07:22 -0700 Subject: [PATCH 101/779] On Unix, only explicitly terminate the native process if not in background (#18215) --- .../engine/NativeCommandProcessor.cs | 30 +++++++++++-------- 1 file changed, 17 insertions(+), 13 deletions(-) diff --git a/src/System.Management.Automation/engine/NativeCommandProcessor.cs b/src/System.Management.Automation/engine/NativeCommandProcessor.cs index 6b8908c03c0..65903305efb 100644 --- a/src/System.Management.Automation/engine/NativeCommandProcessor.cs +++ b/src/System.Management.Automation/engine/NativeCommandProcessor.cs @@ -422,7 +422,7 @@ internal override void Prepare(IDictionary psDefaultParameterValues) catch (Exception) { // Do cleanup in case of exception - CleanUp(); + CleanUp(killBackgroundProcess: true); throw; } } @@ -444,7 +444,7 @@ internal override void ProcessRecord() catch (Exception) { // Do cleanup in case of exception - CleanUp(); + CleanUp(killBackgroundProcess: true); throw; } } @@ -904,7 +904,7 @@ internal override void Complete() finally { // Do some cleanup - CleanUp(); + CleanUp(killBackgroundProcess: false); } // An exception was thrown while attempting to run the program @@ -1161,7 +1161,8 @@ internal void StopProcessing() /// /// Aggressively clean everything up... /// - private void CleanUp() + /// If set, also terminate background process. + private void CleanUp(bool killBackgroundProcess) { // We need to call 'NotifyEndApplication' as appropriate during cleanup if (_hasNotifiedBeginApplication) @@ -1171,17 +1172,20 @@ private void CleanUp() try { - // on Unix, we need to kill the process to ensure it terminates as Dispose() merely - // closes the redirected streams and the processs does not exit on macOS. However, - // on Windows, a winexe like notepad should continue running so we don't want to kill it. + // on Unix, we need to kill the process (if not running in background) to ensure it terminates, + // as Dispose() merely closes the redirected streams and the process does not exit. + // However, on Windows, a winexe like notepad should continue running so we don't want to kill it. #if UNIX - try - { - _nativeProcess?.Kill(); - } - catch + if (killBackgroundProcess || !_isRunningInBackground) { - // Ignore all exception since it is cleanup. + try + { + _nativeProcess?.Kill(); + } + catch + { + // Ignore all exceptions since it is cleanup. + } } #endif _nativeProcess?.Dispose(); From bcde806724b765dcf8a854cadacfac60a7bb1031 Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Fri, 7 Oct 2022 11:07:56 -0700 Subject: [PATCH 102/779] Skip evaluating suggestions at startup (#18232) --- .../host/msh/ConsoleHost.cs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs index 0d647a2ded1..812f42cfd5e 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs @@ -2465,14 +2465,15 @@ private void HandleRunspacePopped(object sender, EventArgs eventArgs) /// internal void Run(bool inputLoopIsNested) { - System.Management.Automation.Host.PSHostUserInterface c = _parent.UI; + PSHostUserInterface c = _parent.UI; ConsoleHostUserInterface ui = c as ConsoleHostUserInterface; Dbg.Assert(ui != null, "Host.UI should return an instance."); bool inBlockMode = false; - bool previousResponseWasEmpty = false; - StringBuilder inputBlock = new StringBuilder(); + // Use nullable so that we don't evaluate suggestions at startup. + bool? previousResponseWasEmpty = null; + var inputBlock = new StringBuilder(); while (!_parent.ShouldEndSession && !_shouldExit) { @@ -2499,7 +2500,7 @@ internal void Run(bool inputLoopIsNested) ui.WriteLine(); // Evaluate any suggestions - if (!previousResponseWasEmpty) + if (previousResponseWasEmpty == false) { EvaluateSuggestions(ui); } From ed1f757728a3bdd3c8b16bb292a587ac96e9076b Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Tue, 11 Oct 2022 16:47:59 +0100 Subject: [PATCH 103/779] Use `MemoryExtensions.IndexOfAny` in `SessionStateInternal` (#18244) * Use `IndexOfAny(ReadOnlySpan, ReadOnlySpan)`. * Avoid unnecessary static initialization of `s_charactersInvalidInDriveName` field. * Refactored `do ... while(false)` loop. cc: @daxian-dbw, @iSazonov --- .../engine/SessionStateDriveAPIs.cs | 22 +++---------------- 1 file changed, 3 insertions(+), 19 deletions(-) diff --git a/src/System.Management.Automation/engine/SessionStateDriveAPIs.cs b/src/System.Management.Automation/engine/SessionStateDriveAPIs.cs index b8a89b9b31f..34c1ac50521 100644 --- a/src/System.Management.Automation/engine/SessionStateDriveAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateDriveAPIs.cs @@ -231,28 +231,12 @@ internal void NewDrive(PSDriveInfo drive, string scopeID, CmdletProviderContext private static bool IsValidDriveName(string name) { - bool result = true; - - do - { - if (string.IsNullOrEmpty(name)) - { - result = false; - break; - } + const string CharactersInvalidInDriveName = ":/\\.~"; - if (name.IndexOfAny(s_charactersInvalidInDriveName) >= 0) - { - result = false; - break; - } - } while (false); - - return result; + return !string.IsNullOrEmpty(name) + && name.AsSpan().IndexOfAny(CharactersInvalidInDriveName) < 0; } - private static readonly char[] s_charactersInvalidInDriveName = new char[] { ':', '/', '\\', '.', '~' }; - /// /// Tries to resolve the drive root as an MSH path. If it successfully resolves /// to a single path then the resolved provider internal path is returned. If it From 80d2fb7e4744fe78c4df96a5818021ec92c1b28e Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Tue, 11 Oct 2022 10:24:31 -0700 Subject: [PATCH 104/779] Some more code cleanup related to the use of `PSVersionInfo` (#18231) --- .../AssemblyInfo.cs | 12 --- .../engine/CommandDiscovery.cs | 4 +- .../engine/InitialSessionState.cs | 2 +- .../engine/InternalCommands.cs | 2 +- .../engine/PSVersionInfo.cs | 101 +++--------------- .../engine/Utils.cs | 39 +------ .../engine/remoting/client/remoterunspace.cs | 4 +- .../RemoteDebuggingCapability.cs | 4 +- .../server/ServerRunspacePoolDriver.cs | 2 +- .../resources/RemotingErrorIdStrings.resx | 2 +- 10 files changed, 29 insertions(+), 143 deletions(-) diff --git a/src/System.Management.Automation/AssemblyInfo.cs b/src/System.Management.Automation/AssemblyInfo.cs index 3c03c22e045..559d809fe72 100644 --- a/src/System.Management.Automation/AssemblyInfo.cs +++ b/src/System.Management.Automation/AssemblyInfo.cs @@ -14,15 +14,3 @@ [assembly: InternalsVisibleTo(@"System.Management.Automation.Remoting" + @",PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] [assembly: InternalsVisibleTo(@"Microsoft.PowerShell.ConsoleHost" + @",PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] [assembly: InternalsVisibleTo(@"Microsoft.PowerShell.DscSubsystem" + @",PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] - -namespace System.Management.Automation -{ - internal static class NTVerpVars - { - internal const int PRODUCTMAJORVERSION = 10; - internal const int PRODUCTMINORVERSION = 0; - internal const int PRODUCTBUILD = 10032; - internal const int PRODUCTBUILD_QFE = 0; - internal const int PACKAGEBUILD_QFE = 814; - } -} diff --git a/src/System.Management.Automation/engine/CommandDiscovery.cs b/src/System.Management.Automation/engine/CommandDiscovery.cs index 9a126645a7d..9ce60e56c04 100644 --- a/src/System.Management.Automation/engine/CommandDiscovery.cs +++ b/src/System.Management.Automation/engine/CommandDiscovery.cs @@ -421,7 +421,7 @@ internal static void VerifyPSVersion(ExternalScriptInfo scriptInfo) // in single shell mode if (requiresPSVersion != null) { - if (!Utils.IsPSVersionSupported(requiresPSVersion)) + if (!PSVersionInfo.IsValidPSVersion(requiresPSVersion)) { ScriptRequiresException scriptRequiresException = new ScriptRequiresException( @@ -458,7 +458,7 @@ internal static void VerifyPSEdition(ExternalScriptInfo scriptInfo) var message = StringUtil.Format(DiscoveryExceptions.RequiresPSEditionNotCompatible, scriptInfo.Name, specifiedEditionsString, - PSVersionInfo.PSEdition); + PSVersionInfo.PSEditionValue); var ex = new RuntimeException(message); ex.SetErrorId("ScriptRequiresUnmatchedPSEdition"); ex.SetTargetObject(scriptInfo.Name); diff --git a/src/System.Management.Automation/engine/InitialSessionState.cs b/src/System.Management.Automation/engine/InitialSessionState.cs index 37cd5f19e74..6fa242ce521 100644 --- a/src/System.Management.Automation/engine/InitialSessionState.cs +++ b/src/System.Management.Automation/engine/InitialSessionState.cs @@ -3732,7 +3732,7 @@ public PSSnapInInfo ImportPSSnapIn(string name, out PSSnapInException warning) // implementation and should be refactored. PSSnapInInfo newPSSnapIn = PSSnapInReader.Read("2", name); - if (!Utils.IsPSVersionSupported(newPSSnapIn.PSVersion.ToString())) + if (!PSVersionInfo.IsValidPSVersion(newPSSnapIn.PSVersion)) { s_PSSnapInTracer.TraceError("MshSnapin {0} and current monad engine's versions don't match.", name); diff --git a/src/System.Management.Automation/engine/InternalCommands.cs b/src/System.Management.Automation/engine/InternalCommands.cs index f1c5f57c88f..2afb9c516c6 100644 --- a/src/System.Management.Automation/engine/InternalCommands.cs +++ b/src/System.Management.Automation/engine/InternalCommands.cs @@ -2654,7 +2654,7 @@ private sealed class ValidateVersionAttribute : ValidateArgumentsAttribute protected override void Validate(object arguments, EngineIntrinsics engineIntrinsics) { Version version = arguments as Version; - if (version == null || !PSVersionInfo.IsValidPSVersion(version)) + if (!PSVersionInfo.IsValidPSVersion(version)) { // No conversion succeeded so throw and exception... throw new ValidationMetadataException( diff --git a/src/System.Management.Automation/engine/PSVersionInfo.cs b/src/System.Management.Automation/engine/PSVersionInfo.cs index 0d292c48520..169024508ed 100644 --- a/src/System.Management.Automation/engine/PSVersionInfo.cs +++ b/src/System.Management.Automation/engine/PSVersionInfo.cs @@ -58,7 +58,7 @@ public static class PSVersionInfo private static readonly Version s_psV3Version = new(3, 0); private static readonly Version s_psV4Version = new(4, 0); private static readonly Version s_psV5Version = new(5, 0); - private static readonly Version s_psV51Version = new(5, 1, NTVerpVars.PRODUCTBUILD, NTVerpVars.PRODUCTBUILD_QFE); + private static readonly Version s_psV51Version = new(5, 1); private static readonly Version s_psV6Version = new(6, 0, 0); private static readonly Version s_psV61Version = new(6, 1, 0); private static readonly Version s_psV62Version = new(6, 2, 0); @@ -193,14 +193,6 @@ internal static string GitCommitId } } - internal static Version[] PSCompatibleVersions - { - get - { - return (Version[])s_psVersionTable[PSCompatibleVersionsName]; - } - } - /// /// Gets the edition of PowerShell. /// @@ -208,7 +200,7 @@ public static string PSEdition { get { - return (string)s_psVersionTable[PSVersionInfo.PSEditionName]; + return PSEditionValue; } } @@ -220,21 +212,6 @@ internal static Version SerializationVersion } } - /// - /// - /// - /// For 2.0 PowerShell, we still use "1" as the registry version key. - /// For >=3.0 PowerShell, we still use "1" as the registry version key for - /// Snapin and Custom shell lookup/discovery. - /// - internal static string RegistryVersion1Key - { - get - { - return "1"; - } - } - /// /// /// @@ -270,76 +247,32 @@ internal static string GetRegistryVersionKeyForSnapinDiscovery(string majorVersi return null; } - internal static string FeatureVersionString - { - get - { - return string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}.{1}", PSVersionInfo.PSVersion.Major, PSVersionInfo.PSVersion.Minor); - } - } - internal static bool IsValidPSVersion(Version version) { - if (version.Major == s_psSemVersion.Major) - { - return version.Minor == s_psSemVersion.Minor; - } - - if (version.Major == s_psV6Version.Major) + if (version is null) { - return version.Minor == s_psV6Version.Minor; + return false; } - if (version.Major == s_psV5Version.Major) + int minor = version.Minor; + switch (version.Major) { - return (version.Minor == s_psV5Version.Minor || version.Minor == s_psV51Version.Minor); - } - - if (version.Major == s_psV4Version.Major) - { - return (version.Minor == s_psV4Version.Minor); - } - else if (version.Major == s_psV3Version.Major) - { - return version.Minor == s_psV3Version.Minor; - } - else if (version.Major == s_psV2Version.Major) - { - return version.Minor == s_psV2Version.Minor; - } - else if (version.Major == s_psV1Version.Major) - { - return version.Minor == s_psV1Version.Minor; + case 1: + case 2: + case 3: + case 4: + return minor == 0; + case 5: + return minor == 0 || minor == 1; + case 6: + return minor >= 0 && minor <= 2; + case 7: + return minor >= 0 && minor <= s_psVersion.Minor; } return false; } - internal static Version PSV4Version - { - get { return s_psV4Version; } - } - - internal static Version PSV5Version - { - get { return s_psV5Version; } - } - - internal static Version PSV51Version - { - get { return s_psV51Version; } - } - - internal static Version PSV6Version - { - get { return s_psV6Version; } - } - - internal static Version PSV7Version - { - get { return s_psV7Version; } - } - internal static SemanticVersion PSCurrentVersion { get { return s_psSemVersion; } diff --git a/src/System.Management.Automation/engine/Utils.cs b/src/System.Management.Automation/engine/Utils.cs index 6cb51a4ae82..a3b6b83dc9a 100644 --- a/src/System.Management.Automation/engine/Utils.cs +++ b/src/System.Management.Automation/engine/Utils.cs @@ -637,41 +637,6 @@ internal static Version StringToVersion(string versionString) return null; } - /// - /// Checks whether current monad session supports version specified - /// by ver. - /// - /// Version to check. - /// True if supported, false otherwise. - internal static bool IsPSVersionSupported(string ver) - { - // Convert version to supported format ie., x.x - Version inputVersion = StringToVersion(ver); - return IsPSVersionSupported(inputVersion); - } - - /// - /// Checks whether current monad session supports version specified - /// by checkVersion. - /// - /// Version to check. - /// True if supported, false otherwise. - internal static bool IsPSVersionSupported(Version checkVersion) - { - if (checkVersion == null) - { - return false; - } - - foreach (Version compatibleVersion in PSVersionInfo.PSCompatibleVersions) - { - if (checkVersion.Major == compatibleVersion.Major && checkVersion.Minor <= compatibleVersion.Minor) - return true; - } - - return false; - } - /// /// Checks whether current PowerShell session supports edition specified /// by checkEdition. @@ -680,7 +645,7 @@ internal static bool IsPSVersionSupported(Version checkVersion) /// True if supported, false otherwise. internal static bool IsPSEditionSupported(string checkEdition) { - return PSVersionInfo.PSEdition.Equals(checkEdition, StringComparison.OrdinalIgnoreCase); + return PSVersionInfo.PSEditionValue.Equals(checkEdition, StringComparison.OrdinalIgnoreCase); } /// @@ -690,7 +655,7 @@ internal static bool IsPSEditionSupported(string checkEdition) /// True if the edition is supported by this runtime, false otherwise. internal static bool IsPSEditionSupported(IEnumerable editions) { - string currentPSEdition = PSVersionInfo.PSEdition; + string currentPSEdition = PSVersionInfo.PSEditionValue; foreach (string edition in editions) { if (currentPSEdition.Equals(edition, StringComparison.OrdinalIgnoreCase)) diff --git a/src/System.Management.Automation/engine/remoting/client/remoterunspace.cs b/src/System.Management.Automation/engine/remoting/client/remoterunspace.cs index ca6d8f7d517..8448007025f 100644 --- a/src/System.Management.Automation/engine/remoting/client/remoterunspace.cs +++ b/src/System.Management.Automation/engine/remoting/client/remoterunspace.cs @@ -2780,8 +2780,8 @@ private void CheckForValidateState() { throw new PSInvalidOperationException( // The remote session to which you are connected does not support remote debugging. - // You must connect to a remote computer that is running PowerShell {0} or greater. - StringUtil.Format(RemotingErrorIdStrings.RemoteDebuggingEndpointVersionError, PSVersionInfo.PSV4Version), + // You must connect to a remote computer that is running PowerShell 4.0 or greater. + RemotingErrorIdStrings.RemoteDebuggingEndpointVersionError, null, "RemoteDebugger:RemoteDebuggingNotSupported", ErrorCategory.NotImplemented, diff --git a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteDebuggingCapability.cs b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteDebuggingCapability.cs index 3162fa3d2bd..2c670b1eaaa 100644 --- a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteDebuggingCapability.cs +++ b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteDebuggingCapability.cs @@ -43,14 +43,14 @@ private RemoteDebuggingCapability(Version powerShellVersion) } // Commands added in v5 - if (PSVersion.Major >= PSVersionInfo.PSV5Version.Major) + if (PSVersion.Major >= 5) { _supportedCommands.Add(RemoteDebuggingCommands.SetDebuggerStepMode); _supportedCommands.Add(RemoteDebuggingCommands.SetUnhandledBreakpointMode); } // Commands added in v7 - if (PSVersion.Major >= PSVersionInfo.PSV7Version.Major) + if (PSVersion.Major >= 7) { _supportedCommands.Add(RemoteDebuggingCommands.GetBreakpoint); _supportedCommands.Add(RemoteDebuggingCommands.SetBreakpoint); diff --git a/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs b/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs index 11c2d6c4d24..83d0ed0755a 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs @@ -472,7 +472,7 @@ private void SetupRemoteDebugger(Runspace runspace) // Remote debugger is created only when client version is PSVersion (4.0) // or greater, and remote session supports debugging. if ((_driverNestedInvoker != null) && - (_clientPSVersion != null && _clientPSVersion >= PSVersionInfo.PSV4Version) && + (_clientPSVersion != null && _clientPSVersion.Major >= 4) && (runspace != null && runspace.Debugger != null)) { _serverRemoteDebugger = new ServerRemoteDebugger(this, runspace, runspace.Debugger); diff --git a/src/System.Management.Automation/resources/RemotingErrorIdStrings.resx b/src/System.Management.Automation/resources/RemotingErrorIdStrings.resx index 57d2a22a0a6..f65d536f639 100644 --- a/src/System.Management.Automation/resources/RemotingErrorIdStrings.resx +++ b/src/System.Management.Automation/resources/RemotingErrorIdStrings.resx @@ -1360,7 +1360,7 @@ All WinRM sessions connected to PowerShell session configurations, such as Micro The remote session command is currently stopped in the debugger. Use the Enter-PSSession cmdlet to connect interactively to the remote session and automatically enter into the console debugger. - The remote session to which you are connected does not support remote debugging. You must connect to a remote computer that is running PowerShell {0} or greater. + The remote session to which you are connected does not support remote debugging. You must connect to a remote computer that is running PowerShell 4.0 or greater. Because the session state for session {0}, {1}, {2} is not equal to Open, you cannot run a command in the session. The session state is {3}. From dd40b59f140823523bd3c0dbad29b3f8938eb188 Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Tue, 11 Oct 2022 10:24:58 -0700 Subject: [PATCH 105/779] Remove ETW trace collection and uploading for CLR CAP (#18253) --- .vsts-ci/windows-daily.yml | 40 -------------------------------------- 1 file changed, 40 deletions(-) diff --git a/.vsts-ci/windows-daily.yml b/.vsts-ci/windows-daily.yml index 15d1a82fc3f..4abcf8ec966 100644 --- a/.vsts-ci/windows-daily.yml +++ b/.vsts-ci/windows-daily.yml @@ -48,8 +48,6 @@ stages: - stage: TestWin displayName: Test for Windows - variables: - - group: CLR-CAP jobs: - job: win_test pool: @@ -77,26 +75,6 @@ stages: displayName: 'Capture Artifacts Directory' continueOnError: true - - pwsh: | - $capRootDir = Join-Path ([System.IO.Path]::GetTempPath()) "CAP" - $capUtilDir = Join-Path $capRootDir "Utils" - - if (Test-Path $capRootDir) { Remove-Item $capRootDir -Recurse -Force } - New-Item $capUtilDir -ItemType Directory > $null - - $capZipFile = Join-Path $capRootDir "cap.zip" - Invoke-WebRequest -Uri https://pscoretestdata.blob.core.windows.net/dotnet-cap/windows.zip -OutFile $capZipFile - Unblock-File -Path $capZipFile - Expand-Archive -Path $capZipFile -DestinationPath $capUtilDir -Force - - Write-Host "=== Capture CAP Util Directory ===" - Get-ChildItem $capUtilDir -Recurse - - Write-Host "##vso[task.setvariable variable=CapRootDir]$capRootDir" - Write-Host "##vso[task.setvariable variable=CapUtilDir]$capUtilDir" - displayName: 'Download CAP package' - condition: succeededOrFailed() - # must be run frow Windows PowerShell - powershell: | # Remove "Program Files\dotnet" from the env variable PATH, so old SDKs won't affect us. @@ -124,13 +102,6 @@ stages: displayName: 'Unzip Build' condition: succeeded() - - pwsh: | - Import-Module $(CapUtilDir)\CAPService.psm1 - $dataDir = Start-TraceCollection -RootDir $(CapRootDir) - Write-Host "##vso[task.setvariable variable=CapDataDir]$dataDir" - displayName: 'Start CLR Trace Collection' - condition: succeeded() - - pwsh: | Import-Module .\build.psm1 Start-PSBootstrap @@ -173,14 +144,3 @@ stages: Test-XUnitTestResults -TestResultsFile $xUnitTestResultsFile displayName: Verify xUnit Test Results condition: succeededOrFailed() - - - pwsh: | - $capDataDir = '$(CapDataDir)' - $capModuleFile = '$(CapUtilDir)\CAPService.psm1' - - if ((Test-Path $capModuleFile) -and (Test-Path $capDataDir)) { - Import-Module $capModuleFile - Stop-TraceCollection -DataDir $capDataDir -RepoRoot $pwd -IngressToken '$(CapIngressToken)' - } - displayName: 'Upload CLR Trace' - condition: always() From dd3a6a10d4e835f4d2d442623b1d93123a4ae9bb Mon Sep 17 00:00:00 2001 From: Ilya Date: Tue, 11 Oct 2022 23:50:16 +0500 Subject: [PATCH 106/779] Use source generator for `PSVersionInfo` to improve startup time (#15603) --- PowerShell.Common.props | 3 + .../PSVersionInfoGenerator.cs | 130 ++++++++++++++++++ .../PSVersionInfoGenerator.csproj | 18 +++ .../System.Management.Automation.csproj | 23 +++- .../engine/PSVersionInfo.cs | 58 +++----- 5 files changed, 190 insertions(+), 42 deletions(-) create mode 100644 src/System.Management.Automation/SourceGenerators/PSVersionInfoGenerator/PSVersionInfoGenerator.cs create mode 100644 src/System.Management.Automation/SourceGenerators/PSVersionInfoGenerator/PSVersionInfoGenerator.csproj diff --git a/PowerShell.Common.props b/PowerShell.Common.props index 5e7e41f1470..8f784ede515 100644 --- a/PowerShell.Common.props +++ b/PowerShell.Common.props @@ -104,6 +104,9 @@ + + + + netstandard2.0 + 10.0 + true + + + + + + + diff --git a/src/System.Management.Automation/System.Management.Automation.csproj b/src/System.Management.Automation/System.Management.Automation.csproj index 75deb301ba1..17938e92941 100644 --- a/src/System.Management.Automation/System.Management.Automation.csproj +++ b/src/System.Management.Automation/System.Management.Automation.csproj @@ -1,4 +1,4 @@ - + PowerShell's System.Management.Automation project @@ -6,6 +6,24 @@ System.Management.Automation + + + true + gen\SourceGenerated + + + + + + + + + + + + @@ -38,6 +56,9 @@ + + + diff --git a/src/System.Management.Automation/engine/PSVersionInfo.cs b/src/System.Management.Automation/engine/PSVersionInfo.cs index 169024508ed..620577d8d43 100644 --- a/src/System.Management.Automation/engine/PSVersionInfo.cs +++ b/src/System.Management.Automation/engine/PSVersionInfo.cs @@ -3,7 +3,6 @@ using System.Collections; using System.Globalization; -using System.Reflection; using System.Text; using System.Text.RegularExpressions; @@ -27,7 +26,7 @@ namespace System.Management.Automation /// The above statement retrieves the PowerShell edition. /// /// - public static class PSVersionInfo + public static partial class PSVersionInfo { internal const string PSVersionTableName = "PSVersionTable"; internal const string PSRemotingProtocolVersionName = "PSRemotingProtocolVersion"; @@ -42,6 +41,18 @@ public static class PSVersionInfo private static readonly PSVersionHashTable s_psVersionTable; + /* + The following constants are generated by the source generator 'PSVersionInfoGenerator': + + internal const string ProductVersion; + internal const string GitCommitId; + + private const int Version_Major + private const int Version_Minor; + private const int Version_Patch; + private const string Version_Label; + */ + /// /// A constant to track current PowerShell Version. /// @@ -78,39 +89,14 @@ static PSVersionInfo() { s_psVersionTable = new PSVersionHashTable(StringComparer.OrdinalIgnoreCase); - Assembly currentAssembly = typeof(PSVersionInfo).Assembly; - ProductVersion = currentAssembly.GetCustomAttribute().InformationalVersion; - - // Get 'GitCommitId' and 'PSVersion' from the 'productVersion' assembly attribute. - // - // The strings can be one of the following format examples: - // when powershell is built from a commit: - // productVersion = '6.0.0-beta.7 Commits: 29 SHA: 52c6b...' convert to GitCommitId = 'v6.0.0-beta.7-29-g52c6b...' - // PSVersion = '6.0.0-beta.7' - // when powershell is built from a release tag: - // productVersion = '6.0.0-beta.7 SHA: f1ec9...' convert to GitCommitId = 'v6.0.0-beta.7' - // PSVersion = '6.0.0-beta.7' - // when powershell is built from a release tag for RTM: - // productVersion = '6.0.0 SHA: f1ec9...' convert to GitCommitId = 'v6.0.0' - // PSVersion = '6.0.0' - string rawGitCommitId; - string mainVersion = ProductVersion.Substring(0, ProductVersion.IndexOf(' ')); - - if (ProductVersion.Contains(" Commits: ")) - { - rawGitCommitId = ProductVersion.Replace(" Commits: ", "-").Replace(" SHA: ", "-g"); - } - else - { - rawGitCommitId = mainVersion; - } - - s_psSemVersion = new SemanticVersion(mainVersion); + s_psSemVersion = Version_Label == string.Empty + ? new SemanticVersion(Version_Major, Version_Minor, Version_Patch) + : new SemanticVersion(Version_Major, Version_Minor, Version_Patch, Version_Label, buildLabel: null); s_psVersion = (Version)s_psSemVersion; s_psVersionTable[PSVersionName] = s_psSemVersion; s_psVersionTable[PSEditionName] = PSEditionValue; - s_psVersionTable[PSGitCommitIdName] = rawGitCommitId; + s_psVersionTable[PSGitCommitIdName] = GitCommitId; s_psVersionTable[PSCompatibleVersionsName] = new Version[] { s_psV1Version, s_psV2Version, s_psV3Version, s_psV4Version, s_psV5Version, s_psV51Version, s_psV6Version, s_psV61Version, s_psV62Version, s_psV7Version, s_psV71Version, s_psV72Version, s_psVersion }; s_psVersionTable[SerializationVersionName] = new Version(InternalSerializer.DefaultVersion); s_psVersionTable[PSRemotingProtocolVersionName] = RemotingConstants.ProtocolVersion; @@ -183,16 +169,6 @@ public static Version PSVersion } } - internal static string ProductVersion { get; } - - internal static string GitCommitId - { - get - { - return (string)s_psVersionTable[PSGitCommitIdName]; - } - } - /// /// Gets the edition of PowerShell. /// From 49579e221ff11e873a2508bb57c4539a33679ba5 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 12 Oct 2022 14:22:34 -0700 Subject: [PATCH 107/779] Bump Microsoft.CodeAnalysis.NetAnalyzers (#18262) --- Analyzers.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Analyzers.props b/Analyzers.props index 71551e0f8db..45a1014850d 100644 --- a/Analyzers.props +++ b/Analyzers.props @@ -1,7 +1,7 @@ - + From 8a45d14fad04acdf2156c0439457e0cba9251cc1 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Wed, 12 Oct 2022 16:08:20 -0700 Subject: [PATCH 108/779] Add `-FuzzyMinimumDistance` parameter to `Get-Command` (#18261) --- .../engine/GetCommandCommand.cs | 29 +++++++++++++++---- .../Get-Command.Tests.ps1 | 9 ++++++ 2 files changed, 33 insertions(+), 5 deletions(-) diff --git a/src/System.Management.Automation/engine/GetCommandCommand.cs b/src/System.Management.Automation/engine/GetCommandCommand.cs index e11b3c30f8c..7beb1f32590 100644 --- a/src/System.Management.Automation/engine/GetCommandCommand.cs +++ b/src/System.Management.Automation/engine/GetCommandCommand.cs @@ -339,7 +339,13 @@ public PSTypeName[] ParameterType [Parameter(ParameterSetName = "AllCommandSet")] public SwitchParameter UseFuzzyMatching { get; set; } - private readonly List _commandScores = new List(); + /// + /// Gets or sets the minimum fuzzy matching distance. + /// + [Parameter(ParameterSetName = "AllCommandSet")] + public uint FuzzyMinimumDistance { get; set; } = 5; + + private List _commandScores = new List(); /// /// Gets or sets the parameter that determines if return cmdlets based on abbreviation expansion. @@ -501,13 +507,16 @@ private void OutputResultsHelper(IEnumerable results) if (UseFuzzyMatching) { - results = _commandScores.OrderBy(static x => x.Score).Select(static x => x.Command).ToList(); + _commandScores = _commandScores + .Where(x => x.Score <= FuzzyMinimumDistance) + .OrderBy(static x => x.Score) + .ToList(); + results = _commandScores.Select(static x => x.Command); } int count = 0; foreach (CommandInfo result in results) { - count += 1; // Only write the command if it is visible to the requestor if (SessionState.IsVisible(origin, result)) { @@ -532,11 +541,21 @@ private void OutputResultsHelper(IEnumerable results) } else { - // Write output as normal command info object. - WriteObject(result); + if (UseFuzzyMatching) + { + PSObject obj = new PSObject(result); + obj.Properties.Add(new PSNoteProperty("Score", _commandScores[count].Score)); + WriteObject(obj); + } + else + { + WriteObject(result); + } } } } + + count += 1; } #if LEGACYTELEMETRY diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-Command.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-Command.Tests.ps1 index 1292992b092..a07ed78e753 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-Command.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-Command.Tests.ps1 @@ -7,6 +7,7 @@ Describe "Get-Command Feature tests" -Tag Feature { $cmds = Get-Command get-hlp -UseFuzzyMatch $cmds.Count | Should -BeGreaterThan 0 $cmds[0].Name | Should -BeExactly 'Get-Help' -Because "This should be closest match so shows up first" + $cmds[0].Score | Should -Be 1 } It "Should match native commands" { @@ -20,6 +21,14 @@ Describe "Get-Command Feature tests" -Tag Feature { $cmds.Count | Should -BeGreaterThan 0 $cmds.Name | Should -Contain $expectedcmd } + + It "Should use minimum distance" { + $cmds = Get-Command get-hlp -UseFuzzyMatch -FuzzyMinimumDistance 3 + $cmds.Count | Should -BeGreaterThan 0 + foreach ($cmd in $cmds) { + $cmd.Score | Should -BeLessOrEqual 3 + } + } } Context "-UseAbbreviationExpansion tests" { From 33bbe7daddb2b9771316c59b89cd8172318eadc5 Mon Sep 17 00:00:00 2001 From: "James Truher [MSFT]" Date: Thu, 13 Oct 2022 12:22:56 -0700 Subject: [PATCH 109/779] Create tasks to collect and publish hashes for build files. (#18276) --- .../templates/compliance/apiscan.yml | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/tools/releaseBuild/azureDevOps/templates/compliance/apiscan.yml b/tools/releaseBuild/azureDevOps/templates/compliance/apiscan.yml index 55a40f34e00..df58aeae1ae 100644 --- a/tools/releaseBuild/azureDevOps/templates/compliance/apiscan.yml +++ b/tools/releaseBuild/azureDevOps/templates/compliance/apiscan.yml @@ -78,6 +78,24 @@ jobs: retryCountOnTaskFailure: 2 workingDirectory: '$(Build.SourcesDirectory)' + - pwsh: | + Get-ChildItem '$(BinDir)' -File | + Foreach-Object { + [pscustomobject]@{ + Path = $_.FullName + Version = $_.VersionInfo.FileVersion + Md5Hash = (Get-FileHash -Algorithm MD5 -Path $_.FullName).Hash + Sha512Hash = (Get-FileHash -Algorithm SHA512 -Path $_.FullName).Hash + } + } | Export-Csv -Path '$(Build.SourcesDirectory)/ReleaseFileHash.csv' + displayName: 'Create release file hash artifact' + + - task: PublishBuildArtifacts@1 + displayName: 'Publish Build File Hash artifact' + inputs: + pathToPublish: '$(Build.SourcesDirectory)/ReleaseFileHash.csv' + artifactName: ReleaseFilesHash + - task: securedevelopmentteam.vss-secure-development-tools.build-task-apiscan.APIScan@2 displayName: 'Run APIScan' inputs: From 50ad429d7cf275754f5b0e6ac134df61fe94b881 Mon Sep 17 00:00:00 2001 From: "James Truher [MSFT]" Date: Thu, 13 Oct 2022 13:38:45 -0700 Subject: [PATCH 110/779] Recurse the file listing. (#18277) --- tools/releaseBuild/azureDevOps/templates/compliance/apiscan.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/releaseBuild/azureDevOps/templates/compliance/apiscan.yml b/tools/releaseBuild/azureDevOps/templates/compliance/apiscan.yml index df58aeae1ae..c972106195d 100644 --- a/tools/releaseBuild/azureDevOps/templates/compliance/apiscan.yml +++ b/tools/releaseBuild/azureDevOps/templates/compliance/apiscan.yml @@ -79,7 +79,7 @@ jobs: workingDirectory: '$(Build.SourcesDirectory)' - pwsh: | - Get-ChildItem '$(BinDir)' -File | + Get-ChildItem '$(BinDir)' -File -Recurse | Foreach-Object { [pscustomobject]@{ Path = $_.FullName From 1228ebc1f55352a7a84ce212c538884ee360cc20 Mon Sep 17 00:00:00 2001 From: Ikko Ashimine Date: Fri, 14 Oct 2022 08:44:10 +0900 Subject: [PATCH 111/779] Fix typo in `RemoteRunspacePoolInternal.cs` (#18263) --- .../engine/remoting/client/RemoteRunspacePoolInternal.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/System.Management.Automation/engine/remoting/client/RemoteRunspacePoolInternal.cs b/src/System.Management.Automation/engine/remoting/client/RemoteRunspacePoolInternal.cs index 6d19c053e90..21ac2d3e278 100644 --- a/src/System.Management.Automation/engine/remoting/client/RemoteRunspacePoolInternal.cs +++ b/src/System.Management.Automation/engine/remoting/client/RemoteRunspacePoolInternal.cs @@ -347,7 +347,7 @@ internal override bool SetMaxRunspaces(int maxRunspaces) return true; } - // sending the message should be done withing the lock + // sending the message should be done within the lock // to ensure that multiple calls to SetMaxRunspaces // will be executed on the server in the order in which // they were called in the client @@ -410,7 +410,7 @@ internal override bool SetMinRunspaces(int minRunspaces) return true; } - // sending the message should be done withing the lock + // sending the message should be done within the lock // to ensure that multiple calls to SetMinRunspaces // will be executed on the server in the order in which // they were called in the client @@ -452,7 +452,7 @@ internal override int GetAvailableRunspaces() // return maxrunspaces if (stateInfo.State == RunspacePoolState.Opened) { - // sending the message should be done withing the lock + // sending the message should be done within the lock // to ensure that multiple calls to GetAvailableRunspaces // will be executed on the server in the order in which // they were called in the client From 19ea81f6be73bc3590f62525346256b70a96252f Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Thu, 13 Oct 2022 20:10:52 -0700 Subject: [PATCH 112/779] Use shortpath instead of multiple quotes in `Get-Item` test relying on node (#18250) --- .../Get-Item.Tests.ps1 | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Item.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Item.Tests.ps1 index 4efc250e0d7..bb701855058 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Item.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Item.Tests.ps1 @@ -191,16 +191,21 @@ Describe "Get-Item environment provider on Windows with accidental case-variant if (-not (Get-Command -ErrorAction Ignore node.exe)) { Write-Warning "Test skipped, because prerequisite Node.js is not installed." } else { - $valDirect, $valGetItem, $unused = node.exe -pe @" + $fso = New-Object -ComObject Scripting.FileSystemObject + $shortPath = $fso.GetFile("$PSHOME\pwsh.exe").ShortPath.Replace('\', '/') + $script = @" env = {} env.testVar = process.env.testVar // include the original case variant with its original value. env.TESTVAR = 'b' // redefine with a case variant name and different value // Note: Which value will win is not deterministic(!); what matters, however, is that both - // $env:testvar and Get-Item env:testvar report the same value. + // `$env:testvar and Get-Item env:testvar report the same value. // The nondeterministic behavior makes it hard to prove that the values are *always* the // same, however. - require('child_process').execSync(\"\\\"$($PSHOME -replace '\\', '/')/pwsh.exe\\\" -noprofile -command `$env:testvar, (Get-Item env:testvar).Value\", { env: env }).toString() + require('child_process').execSync('$shortPath -noprofile -command `$env:testvar, (Get-Item env:testvar).Value', { env: env }).toString() "@ + $valDirect, $valGetItem, $unused = node.exe -pe $script + $LASTEXITCODE | Should -Be 0 + $valDirect | Should -Not -BeNullOrEmpty $valGetItem | Should -BeExactly $valDirect } } From 88ca29235c56d68d7d1b544a6d7994cbbcec267b Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Fri, 14 Oct 2022 13:40:11 -0700 Subject: [PATCH 113/779] Update to the latest NOTICES file (#18237) Co-authored-by: adityapatwardhan --- ThirdPartyNotices.txt | 64 +++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 62 insertions(+), 2 deletions(-) diff --git a/ThirdPartyNotices.txt b/ThirdPartyNotices.txt index ceb1155c1b2..eb30daa0025 100644 --- a/ThirdPartyNotices.txt +++ b/ThirdPartyNotices.txt @@ -20,6 +20,18 @@ required to debug changes to any libraries licensed under the GNU Lesser General Microsoft.Extensions.ObjectPool 5.0.10 - Apache-2.0 +(c) Microsoft Corporation +Copyright (c) Andrew Arnott +Copyright (c) 2019 David Fowler +Copyright (c) 2016 Richard Morris +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) Microsoft Corporation +Copyright (c) 2014-2018 Michael Daines +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2019-2020 West Wind Technologies +Copyright (c) 2010-2019 Google LLC. http://angular.io/license +Copyright (c) Sindre Sorhus (https://sindresorhus.com) Apache License @@ -228,9 +240,11 @@ SOFTWARE. --------------------------------------------------------- -Microsoft.CodeAnalysis.Common 4.3.0 - MIT +Microsoft.CodeAnalysis.Common 4.3.1 - MIT +(c) Microsoft Corporation +Copyright (c) .NET Foundation and Contributors MIT License @@ -246,9 +260,13 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI --------------------------------------------------------- -Microsoft.CodeAnalysis.CSharp 4.3.0 - MIT +Microsoft.CodeAnalysis.CSharp 4.3.1 - MIT +(c) Microsoft Corporation +Copyright (c) Microsoft Corporation +Copyright (c) .NET Foundation and Contributors +Copyright (c) Microsoft Corporation. Alle Rechte MIT License @@ -3024,6 +3042,48 @@ SOFTWARE. System.Security.Cryptography.Pkcs 6.0.1 - MIT +(c) Microsoft Corporation +Copyright (c) Andrew Arnott +Copyright 2019 LLVM Project +Copyright 2018 Daniel Lemire +Copyright (c) .NET Foundation +Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson +Copyright (c) 1998 Microsoft. To +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2005-2020 Rich Felker +Copyright (c) Microsoft Corporation +Copyright (c) 2007 James Newton-King +Copyright (c) 2012-2014, Yann Collet +Copyright (c) 1991-2020 Unicode, Inc. +Copyright (c) 2013-2017, Alfred Klomp +Copyright 2012 the V8 project authors +Copyright (c) 2011-2020 Microsoft Corp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors +Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 +Portions (c) International Organization +Copyright (c) 2004-2006 Intel Corporation +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) +Copyright (c) .NET Foundation Contributors +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2019 Microsoft Corporation, Daan Leijen +Copyright (c) 2011 Novell, Inc (http://www.novell.com) +Copyright (c) 1995-2017 Jean-loup Gailly and Mark Adler +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors +Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass. To The MIT License (MIT) From 5e5b0df8df1dbf11c49e061a203baf1145db1de1 Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Mon, 17 Oct 2022 12:28:36 -0700 Subject: [PATCH 114/779] Add a function to get the PR Back-port report (#18299) * Add a function to get the PR Back-port report * Add version check * update how we pass the fields we want in the json. --- tools/releaseTools.psm1 | 96 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 95 insertions(+), 1 deletion(-) diff --git a/tools/releaseTools.psm1 b/tools/releaseTools.psm1 index 388f3654c37..7755495d6ce 100644 --- a/tools/releaseTools.psm1 +++ b/tools/releaseTools.psm1 @@ -628,4 +628,98 @@ function Update-PsVersionInCode } } -Export-ModuleMember -Function Get-ChangeLog, Get-NewOfficalPackage, Update-PsVersionInCode + +############################## +#.SYNOPSIS +# Test if the GithubCli is in the path +############################## +function Test-GitHubCli { + $gitHubCli = Get-Command -Name 'gh' -ErrorAction SilentlyContinue + + if ($gitHubCli) { + return $true + } else { + return $false + } +} + +############################## +#.SYNOPSIS +# Test if the GithubCli is the required version +############################## +function Test-GitHubCliVersion { + param( + [Parameter(Mandatory)] + [System.Management.Automation.SemanticVersion] + $RequiredVersion + ) + [System.Management.Automation.SemanticVersion] $version = gh --version | ForEach-Object { + if ($_ -match ' (\d+\.\d+\.\d+) ') { + $matches[1] + } + } + + if ($version -ge $RequiredVersion) { + return $true + } else { + return $false + } +} + +############################## +#.SYNOPSIS +# Gets a report of Backport PRs +# +#.PARAMETER Triage state +# The triage states of the PR. Consider, Approved or Done +# +#.PARAMETER Version +# The version of PowerShell the backport is targeting. 7.0, 7.2, 7.3, etc +# +#.PARAMETER Web +# A switch to open all the PRs in the browser +# +############################## +function Get-PRBackportReport { + param( + [ValidateSet('Consider', 'Approved', 'Done')] + [String] $TriageState = 'Approved', + [ValidatePattern('^\d+\.\d+$')] + [string] $Version, + [switch] $Web + ) + + if (!(Test-GitHubCli)) { + throw "GitHub CLI is not installed. Please install it from https://cli.github.com/" + } + + $requiredVersion = '2.17' + if (!(Test-GitHubCliVersion -RequiredVersion $requiredVersion)) { + throw "Please upgrade the GitHub CLI to version $requiredVersion. Please install it from https://cli.github.com/" + } + + if (!(gh auth status 2>&1 | Select-String 'logged in')){ + throw "Please login to GitHub CLI using 'gh auth login'" + } + + $prs = gh pr list --state merged --label "Backport-$Version.x-$TriageState" --json title,number,mergeCommit,mergedAt | + ConvertFrom-Json | + ForEach-Object { + [PScustomObject]@{ + CommitId = $_.mergeCommit.oid + Number = $_.number + Title = $_.title + MergedAt = $_.mergedAt + } + } | Sort-Object -Property MergedAt + + if ($Web) { + $prs | ForEach-Object { + gh pr view $_.Number --web + } + } else { + $prs + } +} + +Export-ModuleMember -Function Get-ChangeLog, Get-NewOfficalPackage, Update-PsVersionInCode, Get-PRBackportReport From 223d9a4d144a80f580e51b3b83108b003b951e5d Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Mon, 17 Oct 2022 23:51:34 +0200 Subject: [PATCH 115/779] Small cleanup of the stub code (#18301) --- .../CoreCLR/Stubs.cs | 252 ------------------ ...oft.PowerShell.Commands.Diagnostics.csproj | 1 + 2 files changed, 1 insertion(+), 252 deletions(-) delete mode 100644 src/Microsoft.PowerShell.Commands.Diagnostics/CoreCLR/Stubs.cs diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/CoreCLR/Stubs.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/CoreCLR/Stubs.cs deleted file mode 100644 index 845179009f7..00000000000 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/CoreCLR/Stubs.cs +++ /dev/null @@ -1,252 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -#if CORECLR - -namespace System.Diagnostics -{ - /// - /// Indicates whether the performance counter category can have multiple instances. - /// - /// 1 - public enum PerformanceCounterCategoryType - { - /// - /// The instance functionality for the performance counter category is unknown. - /// - Unknown = -1, - - /// - /// The performance counter category can have only a single instance. - /// - SingleInstance, - - /// - /// The performance counter category can have multiple instances. - /// - MultiInstance - } - - /// - /// Specifies the formula used to calculate the - /// method for a instance. - /// - /// 2 - public enum PerformanceCounterType - { - /// - /// An instantaneous counter that shows the most recently observed value. - /// Used, for example, to maintain a simple count of items or operations. - /// - NumberOfItems32 = 65536, - - /// - /// An instantaneous counter that shows the most recently observed value. - /// Used, for example, to maintain a simple count of a very large number - /// of items or operations. It is the same as NumberOfItems32 except that - /// it uses larger fields to accommodate larger values. - /// - NumberOfItems64 = 65792, - - /// - /// An instantaneous counter that shows the most recently observed value - /// in hexadecimal format. Used, for example, to maintain a simple count - /// of items or operations. - NumberOfItemsHEX32 = 0, - - /// - /// An instantaneous counter that shows the most recently observed value. - /// Used, for example, to maintain a simple count of a very large number - /// of items or operations. It is the same as NumberOfItemsHEX32 except - /// that it uses larger fields to accommodate larger values. - /// - NumberOfItemsHEX64 = 256, - - /// - /// A difference counter that shows the average number of operations completed - /// during each second of the sample interval. Counters of this type measure - /// time in ticks of the system clock. - RateOfCountsPerSecond32 = 272696320, - - /// - /// A difference counter that shows the average number of operations completed - /// during each second of the sample interval. Counters of this type measure - /// time in ticks of the system clock. This counter type is the same as the - /// RateOfCountsPerSecond32 type, but it uses larger fields to accommodate - /// larger values to track a high-volume number of items or operations per - /// second, such as a byte-transmission rate. - /// - RateOfCountsPerSecond64 = 272696576, - - /// - /// An average counter designed to monitor the average length of a queue - /// to a resource over time. It shows the difference between the queue - /// lengths observed during the last two sample intervals divided by the - /// duration of the interval. This type of counter is typically used to - /// track the number of items that are queued or waiting. - /// - CountPerTimeInterval32 = 4523008, - - /// - /// An average counter that monitors the average length of a queue to a - /// resource over time. Counters of this type display the difference - /// between the queue lengths observed during the last two sample intervals, - /// divided by the duration of the interval. This counter type is the same - /// as CountPerTimeInterval32 except that it uses larger fields to - /// accommodate larger values. This type of counter is typically used - /// to track a high-volume or very large number of items that are queued or waiting. - /// - CountPerTimeInterval64 = 4523264, - - /// - /// An instantaneous percentage counter that shows the ratio of a subset - /// to its set as a percentage. For example, it compares the number of bytes - /// in use on a disk to the total number of bytes on the disk. - /// Counters of this type display the current percentage only, not an average - /// over time. - /// - RawFraction = 537003008, - - /// - /// A base counter that stores the denominator of a counter that presents a - /// general arithmetic fraction. Check that this value is greater than zero - /// before using it as the denominator in a RawFraction value calculation. - /// - RawBase = 1073939459, - - /// - /// An average counter that measures the time it takes, on average, to - /// complete a process or operation. Counters of this type display a - /// ratio of the total elapsed time of the sample interval to the number - /// of processes or operations completed during that time. This counter - /// type measures time in ticks of the system clock. - /// - AverageTimer32 = 805438464, - - /// - /// A base counter that is used in the calculation of time or count averages, - /// such as AverageTimer32 and AverageCount64. Stores the denominator for - /// calculating a counter to present "time per operation" or "count per operation". - /// - AverageBase = 1073939458, - - /// - /// An average counter that shows how many items are processed, on average, - /// during an operation. Counters of this type display a ratio of the items - /// processed to the number of operations completed. The ratio is calculated - /// by comparing the number of items processed during the last interval to - /// the number of operations completed during the last interval. - /// - AverageCount64 = 1073874176, - - /// - /// A percentage counter that shows the average ratio of hits to all - /// operations during the last two sample intervals. - /// - SampleFraction = 549585920, - - /// - /// An average counter that shows the average number of operations completed - /// in one second. When a counter of this type samples the data, each sampling - /// interrupt returns one or zero. The counter data is the number of ones that - /// were sampled. It measures time in units of ticks of the system performance timer. - /// - SampleCounter = 4260864, - - /// - /// A base counter that stores the number of sampling interrupts taken - /// and is used as a denominator in the sampling fraction. The sampling - /// fraction is the number of samples that were 1 (or true) for a sample - /// interrupt. Check that this value is greater than zero before using - /// it as the denominator in a calculation of SampleFraction. - /// - SampleBase = 1073939457, - - /// - /// A percentage counter that shows the average time that a component is - /// active as a percentage of the total sample time. - /// - CounterTimer = 541132032, - - /// - /// A percentage counter that displays the average percentage of active - /// time observed during sample interval. The value of these counters is - /// calculated by monitoring the percentage of time that the service was - /// inactive and then subtracting that value from 100 percent. - /// - CounterTimerInverse = 557909248, - - /// A percentage counter that shows the active time of a component - /// as a percentage of the total elapsed time of the sample interval. - /// It measures time in units of 100 nanoseconds (ns). Counters of this - /// type are designed to measure the activity of one component at a time. - /// - Timer100Ns = 542180608, - - /// - /// A percentage counter that shows the average percentage of active time - /// observed during the sample interval. - /// - Timer100NsInverse = 558957824, - - /// - /// A difference timer that shows the total time between when the component - /// or process started and the time when this value is calculated. - /// - ElapsedTime = 807666944, - - /// - /// A percentage counter that displays the active time of one or more - /// components as a percentage of the total time of the sample interval. - /// Because the numerator records the active time of components operating - /// simultaneously, the resulting percentage can exceed 100 percent. - /// - CounterMultiTimer = 574686464, - - /// - /// A percentage counter that shows the active time of one or more components - /// as a percentage of the total time of the sample interval. It derives - /// the active time by measuring the time that the components were not - /// active and subtracting the result from 100 percent by the number of - /// objects monitored. - /// - CounterMultiTimerInverse = 591463680, - - /// - /// A percentage counter that shows the active time of one or more components - /// as a percentage of the total time of the sample interval. It measures - /// time in 100 nanosecond (ns) units. - CounterMultiTimer100Ns = 575735040, - - /// - /// A percentage counter that shows the active time of one or more components - /// as a percentage of the total time of the sample interval. Counters of - /// this type measure time in 100 nanosecond (ns) units. They derive the - /// active time by measuring the time that the components were not active - /// and subtracting the result from multiplying 100 percent by the number - /// of objects monitored. - CounterMultiTimer100NsInverse = 592512256, - - /// - /// A base counter that indicates the number of items sampled. It is used - /// as the denominator in the calculations to get an average among the - /// items sampled when taking timings of multiple, but similar items. - /// Used with CounterMultiTimer, CounterMultiTimerInverse, CounterMultiTimer100Ns, - /// and CounterMultiTimer100NsInverse. - CounterMultiBase = 1107494144, - - /// - /// A difference counter that shows the change in the measured attribute - /// between the two most recent sample intervals. - /// - CounterDelta32 = 4195328, - - /// - /// A difference counter that shows the change in the measured attribute - /// between the two most recent sample intervals. It is the same as the - /// CounterDelta32 counter type except that is uses larger fields to - /// accommodate larger values. - CounterDelta64 = 4195584 - } -} -#endif diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/Microsoft.PowerShell.Commands.Diagnostics.csproj b/src/Microsoft.PowerShell.Commands.Diagnostics/Microsoft.PowerShell.Commands.Diagnostics.csproj index 02e3b785509..42a66b6d0d3 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/Microsoft.PowerShell.Commands.Diagnostics.csproj +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/Microsoft.PowerShell.Commands.Diagnostics.csproj @@ -8,6 +8,7 @@ + From 074aad6ea99bcc08e2082a2a486ff02cb6ea05bd Mon Sep 17 00:00:00 2001 From: "James Truher [MSFT]" Date: Mon, 17 Oct 2022 15:27:24 -0700 Subject: [PATCH 116/779] Add missing `-Tag 'CI'` to describe blocks. (#18316) --- .../Language/Scripting/CleanBlockErrorHandling.Tests.ps1 | 2 +- .../Scripting/HashtableToPSCustomObjectConversion.Tests.ps1 | 2 +- .../NativeExecution/NativeCommandArguments.Tests.ps1 | 2 +- .../Modules/Microsoft.PowerShell.Core/Exec.Tests.ps1 | 2 +- .../Microsoft.PowerShell.Utility/Format-List.Tests.ps1 | 2 +- .../Microsoft.PowerShell.Utility/Format-Table.Tests.ps1 | 2 +- test/powershell/engine/Formatting/OutputRendering.Tests.ps1 | 2 +- test/powershell/engine/Formatting/PSStyle.Tests.ps1 | 4 ++-- test/powershell/engine/Module/IsolatedModule.Tests.ps1 | 2 +- test/powershell/engine/OrderedHashtable.Tests.ps1 | 2 +- 10 files changed, 11 insertions(+), 11 deletions(-) diff --git a/test/powershell/Language/Scripting/CleanBlockErrorHandling.Tests.ps1 b/test/powershell/Language/Scripting/CleanBlockErrorHandling.Tests.ps1 index 68904d4c79f..0d459da87b8 100644 --- a/test/powershell/Language/Scripting/CleanBlockErrorHandling.Tests.ps1 +++ b/test/powershell/Language/Scripting/CleanBlockErrorHandling.Tests.ps1 @@ -540,7 +540,7 @@ Describe "Error handling within a single 'Clean' block" -Tag 'CI' { } } -Describe "Multiple errors from 'Clean' and another named block" { +Describe "Multiple errors from 'Clean' and another named block" -Tag 'CI' { BeforeAll { function MultipleErrors { diff --git a/test/powershell/Language/Scripting/HashtableToPSCustomObjectConversion.Tests.ps1 b/test/powershell/Language/Scripting/HashtableToPSCustomObjectConversion.Tests.ps1 index 8d0d1ac24fe..6afd2402032 100644 --- a/test/powershell/Language/Scripting/HashtableToPSCustomObjectConversion.Tests.ps1 +++ b/test/powershell/Language/Scripting/HashtableToPSCustomObjectConversion.Tests.ps1 @@ -142,7 +142,7 @@ Describe "Tests for hashtable to PSCustomObject conversion" -Tags "CI" { } } -Describe "Error message with settable Property information" { +Describe "Error message with settable Property information" -Tag 'CI' { BeforeAll { Add-Type @" namespace HashtableConversionTest { diff --git a/test/powershell/Language/Scripting/NativeExecution/NativeCommandArguments.Tests.ps1 b/test/powershell/Language/Scripting/NativeExecution/NativeCommandArguments.Tests.ps1 index d96720139bb..9cf10e8c901 100644 --- a/test/powershell/Language/Scripting/NativeExecution/NativeCommandArguments.Tests.ps1 +++ b/test/powershell/Language/Scripting/NativeExecution/NativeCommandArguments.Tests.ps1 @@ -162,7 +162,7 @@ Describe "Will error correctly if an attempt to set variable to improper value" } } -Describe "find.exe uses legacy behavior on Windows" { +Describe "find.exe uses legacy behavior on Windows" -Tag 'CI' { BeforeAll { $currentSetting = $PSNativeCommandArgumentPassing $PSNativeCommandArgumentPassing = "Windows" diff --git a/test/powershell/Modules/Microsoft.PowerShell.Core/Exec.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Core/Exec.Tests.ps1 index 640fb8e0fc9..858a04fb4e8 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Core/Exec.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Core/Exec.Tests.ps1 @@ -50,7 +50,7 @@ Describe 'Switch-Process tests for Unix' -Tags 'CI' { } } -Describe 'Switch-Process for Windows' { +Describe 'Switch-Process for Windows' -Tag 'CI' { BeforeAll { $originalDefaultParameterValues = $PSDefaultParameterValues.Clone() if (!$IsWindows) diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Format-List.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Format-List.Tests.ps1 index bab0110a9ac..b9079b92139 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Format-List.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Format-List.Tests.ps1 @@ -230,7 +230,7 @@ decimal : 4567.123456789 } } -Describe 'Format-List color tests' { +Describe 'Format-List color tests' -Tag 'CI' { BeforeAll { $originalRendering = $PSStyle.OutputRendering $PSStyle.OutputRendering = 'Ansi' diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Format-Table.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Format-Table.Tests.ps1 index 67933d2801d..6eb1e4fa3c9 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Format-Table.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Format-Table.Tests.ps1 @@ -866,7 +866,7 @@ A Name B } } -Describe 'Table color tests' { +Describe 'Table color tests' -Tag 'CI' { BeforeAll { $originalRendering = $PSStyle.OutputRendering $PSStyle.OutputRendering = 'Ansi' diff --git a/test/powershell/engine/Formatting/OutputRendering.Tests.ps1 b/test/powershell/engine/Formatting/OutputRendering.Tests.ps1 index 7b67f71233c..a1c721e7646 100644 --- a/test/powershell/engine/Formatting/OutputRendering.Tests.ps1 +++ b/test/powershell/engine/Formatting/OutputRendering.Tests.ps1 @@ -1,7 +1,7 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. -Describe 'OutputRendering tests' { +Describe 'OutputRendering tests' -Tag 'CI' { BeforeEach { if ($null -ne $PSStyle) { $oldOutputRendering = $PSStyle.OutputRendering diff --git a/test/powershell/engine/Formatting/PSStyle.Tests.ps1 b/test/powershell/engine/Formatting/PSStyle.Tests.ps1 index c1da9b6b6ab..725fc400cf3 100644 --- a/test/powershell/engine/Formatting/PSStyle.Tests.ps1 +++ b/test/powershell/engine/Formatting/PSStyle.Tests.ps1 @@ -1,7 +1,7 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. -Describe 'Tests for $PSStyle automatic variable' { +Describe 'Tests for $PSStyle automatic variable' -Tag 'CI' { BeforeAll { $styleDefaults = @{ Reset = "`e[0m" @@ -380,7 +380,7 @@ Describe 'Tests for $PSStyle automatic variable' { } } -Describe 'Handle strings with escape sequences in formatting' { +Describe 'Handle strings with escape sequences in formatting' -Tag 'CI' { BeforeAll { function Get-DemoObjects { diff --git a/test/powershell/engine/Module/IsolatedModule.Tests.ps1 b/test/powershell/engine/Module/IsolatedModule.Tests.ps1 index 114b1d1610a..5d1289271de 100644 --- a/test/powershell/engine/Module/IsolatedModule.Tests.ps1 +++ b/test/powershell/engine/Module/IsolatedModule.Tests.ps1 @@ -1,7 +1,7 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. -Describe "Isolated module scenario - load the whole module in custom ALC" { +Describe "Isolated module scenario - load the whole module in custom ALC" -Tag 'CI' { It "Loading 'IsolatedModule' should work as expected" { ## The 'IsolatedModule' module can be found at '\test\tools\Modules'. ## The module assemblies are created and deployed by '\test\tools\TestAlc'. diff --git a/test/powershell/engine/OrderedHashtable.Tests.ps1 b/test/powershell/engine/OrderedHashtable.Tests.ps1 index 4df61c49edb..2ffa84539c4 100644 --- a/test/powershell/engine/OrderedHashtable.Tests.ps1 +++ b/test/powershell/engine/OrderedHashtable.Tests.ps1 @@ -1,7 +1,7 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. -Describe 'Tests for OrderedHashtable' { +Describe 'Tests for OrderedHashtable' -Tag 'CI' { It 'Can create an empty OrderedHashtable' { $oh =[System.Management.Automation.OrderedHashtable]::new() From 0b8c3de40a50e82069df9f0dc455be2dc8717376 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 17 Oct 2022 16:04:41 -0700 Subject: [PATCH 117/779] Bump Microsoft.CodeAnalysis.NetAnalyzers (#18312) --- Analyzers.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Analyzers.props b/Analyzers.props index 45a1014850d..8dd63903e97 100644 --- a/Analyzers.props +++ b/Analyzers.props @@ -1,7 +1,7 @@ - + From bc1f3691f2dcfcc93a184a672449f5216ec94703 Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Mon, 17 Oct 2022 16:40:54 -0700 Subject: [PATCH 118/779] Make the fuzzy searching flexible by passing in the fuzzy matcher (#18270) --- .../engine/CommandPathSearch.cs | 14 ++--- .../engine/CommandSearcher.cs | 62 ++++++++----------- .../engine/GetCommandCommand.cs | 54 ++++++++-------- .../engine/Modules/ModuleUtils.cs | 16 ++--- .../utils/FuzzyMatch.cs | 40 +++++++++--- 5 files changed, 99 insertions(+), 87 deletions(-) diff --git a/src/System.Management.Automation/engine/CommandPathSearch.cs b/src/System.Management.Automation/engine/CommandPathSearch.cs index a5b8a232b23..92a533e6ec0 100644 --- a/src/System.Management.Automation/engine/CommandPathSearch.cs +++ b/src/System.Management.Automation/engine/CommandPathSearch.cs @@ -37,17 +37,17 @@ internal class CommandPathSearch : IEnumerable, IEnumerator /// /// The patterns to search for in the paths. /// - /// - /// Use likely relevant search. + /// + /// The fuzzy matcher to use for fuzzy searching. /// internal CommandPathSearch( string commandName, LookupPathCollection lookupPaths, ExecutionContext context, Collection? acceptableCommandNames, - bool useFuzzyMatch) + FuzzyMatcher? fuzzyMatcher) { - _useFuzzyMatch = useFuzzyMatch; + _fuzzyMatcher = fuzzyMatcher; string[] commandPatterns; if (acceptableCommandNames != null) { @@ -434,13 +434,13 @@ private void GetNewDirectoryResults(string pattern, string directory) // to forcefully use null if pattern is "." if (pattern.Length != 1 || pattern[0] != '.') { - if (_useFuzzyMatch) + if (_fuzzyMatcher is not null) { var files = new List(); var matchingFiles = Directory.EnumerateFiles(directory); foreach (string file in matchingFiles) { - if (FuzzyMatcher.IsFuzzyMatch(Path.GetFileName(file), pattern)) + if (_fuzzyMatcher.IsFuzzyMatch(Path.GetFileName(file), pattern)) { files.Add(file); } @@ -589,7 +589,7 @@ private void GetNewDirectoryResults(string pattern, string directory) private readonly string[] _orderedPathExt; private readonly Collection? _acceptableCommandNames; - private readonly bool _useFuzzyMatch = false; + private readonly FuzzyMatcher? _fuzzyMatcher; #endregion private members } diff --git a/src/System.Management.Automation/engine/CommandSearcher.cs b/src/System.Management.Automation/engine/CommandSearcher.cs index cf798ddabbd..3b1490cb3ab 100644 --- a/src/System.Management.Automation/engine/CommandSearcher.cs +++ b/src/System.Management.Automation/engine/CommandSearcher.cs @@ -24,29 +24,20 @@ internal class CommandSearcher : IEnumerable, IEnumerator - /// - /// The name of the command to look for. - /// - /// - /// Determines which types of commands glob resolution of the name will take place on. - /// - /// - /// The types of commands to look for. - /// - /// - /// The execution context for this engine instance... - /// - /// - /// If is null. - /// - /// - /// If is null or empty. - /// + /// The name of the command to look for. + /// Determines which types of commands glob resolution of the name will take place on. + /// The types of commands to look for. + /// The execution context for this engine instance. + /// The fuzzy matcher to use for fuzzy searching. + /// + /// If is null. + /// If is null or empty. internal CommandSearcher( string commandName, SearchResolutionOptions options, CommandTypes commandTypes, - ExecutionContext context) + ExecutionContext context, + FuzzyMatcher? fuzzyMatcher = null) { Diagnostics.Assert(context != null, "caller to verify context is not null"); Diagnostics.Assert(!string.IsNullOrEmpty(commandName), "caller to verify commandName is valid"); @@ -55,6 +46,7 @@ internal CommandSearcher( _context = context; _commandResolutionOptions = options; _commandTypes = commandTypes; + _fuzzyMatcher = fuzzyMatcher; // Initialize the enumerators this.Reset(); @@ -705,8 +697,7 @@ private static bool checkPath(string path, string commandName) foreach (KeyValuePair aliasEntry in _context.EngineSessionState.GetAliasTable()) { if (aliasMatcher.IsMatch(aliasEntry.Key) || - (_commandResolutionOptions.HasFlag(SearchResolutionOptions.FuzzyMatch) && - FuzzyMatcher.IsFuzzyMatch(aliasEntry.Key, _commandName))) + (_fuzzyMatcher is not null && _fuzzyMatcher.IsFuzzyMatch(aliasEntry.Key, _commandName))) { matchingAliases.Add(aliasEntry.Value); } @@ -785,8 +776,7 @@ private static bool checkPath(string path, string commandName) foreach ((string functionName, FunctionInfo functionInfo) in _context.EngineSessionState.GetFunctionTable()) { if (functionMatcher.IsMatch(functionName) || - (_commandResolutionOptions.HasFlag(SearchResolutionOptions.FuzzyMatch) && - FuzzyMatcher.IsFuzzyMatch(functionName, _commandName))) + (_fuzzyMatcher is not null && _fuzzyMatcher.IsFuzzyMatch(functionName, _commandName))) { matchingFunction.Add(functionInfo); } @@ -1018,10 +1008,8 @@ private static bool ShouldSkipCommandResolutionForConstrainedLanguage(CommandInf { foreach (CmdletInfo cmdlet in cmdletList) { - if (cmdletMatcher != null && - cmdletMatcher.IsMatch(cmdlet.Name) || - (_commandResolutionOptions.HasFlag(SearchResolutionOptions.FuzzyMatch) && - FuzzyMatcher.IsFuzzyMatch(cmdlet.Name, _commandName))) + if ((cmdletMatcher is not null && cmdletMatcher.IsMatch(cmdlet.Name)) || + (_fuzzyMatcher is not null && _fuzzyMatcher.IsFuzzyMatch(cmdlet.Name, _commandName))) { if (string.IsNullOrEmpty(moduleName) || moduleName.Equals(cmdlet.ModuleName, StringComparison.OrdinalIgnoreCase)) { @@ -1496,6 +1484,11 @@ private static CanDoPathLookupResult CanDoPathLookup(string possiblePath) /// private readonly ExecutionContext _context; + /// + /// The fuzzy matcher to use for fuzzy searching. + /// + private readonly FuzzyMatcher? _fuzzyMatcher; + /// /// A routine to initialize the path searcher... /// @@ -1528,7 +1521,7 @@ private void setupPathSearcher() _context.CommandDiscovery.GetLookupDirectoryPaths(), _context, acceptableCommandNames: null, - useFuzzyMatch: _commandResolutionOptions.HasFlag(SearchResolutionOptions.FuzzyMatch)); + _fuzzyMatcher); } else { @@ -1544,7 +1537,7 @@ private void setupPathSearcher() _context.CommandDiscovery.GetLookupDirectoryPaths(), _context, ConstructSearchPatternsFromName(_commandName, commandDiscovery: true), - useFuzzyMatch: false); + fuzzyMatcher: null); } else if (_canDoPathLookupResult == CanDoPathLookupResult.PathIsRooted) { @@ -1568,7 +1561,7 @@ private void setupPathSearcher() directoryCollection, _context, ConstructSearchPatternsFromName(fileName, commandDiscovery: true), - useFuzzyMatch: false); + fuzzyMatcher: null); } else { @@ -1608,7 +1601,7 @@ private void setupPathSearcher() directoryCollection, _context, ConstructSearchPatternsFromName(fileName, commandDiscovery: true), - useFuzzyMatch: false); + fuzzyMatcher: null); } else { @@ -1727,17 +1720,14 @@ internal enum SearchResolutionOptions CommandNameIsPattern = 0x04, SearchAllScopes = 0x08, - /// Use fuzzy matching. - FuzzyMatch = 0x10, - /// /// Enable searching for cmdlets/functions by abbreviation expansion. /// - UseAbbreviationExpansion = 0x20, + UseAbbreviationExpansion = 0x10, /// /// Enable resolving wildcard in paths. /// - ResolveLiteralThenPathPatterns = 0x40 + ResolveLiteralThenPathPatterns = 0x20 } } diff --git a/src/System.Management.Automation/engine/GetCommandCommand.cs b/src/System.Management.Automation/engine/GetCommandCommand.cs index 7beb1f32590..b211744965a 100644 --- a/src/System.Management.Automation/engine/GetCommandCommand.cs +++ b/src/System.Management.Automation/engine/GetCommandCommand.cs @@ -345,7 +345,8 @@ public PSTypeName[] ParameterType [Parameter(ParameterSetName = "AllCommandSet")] public uint FuzzyMinimumDistance { get; set; } = 5; - private List _commandScores = new List(); + private FuzzyMatcher _fuzzyMatcher; + private List _commandScores; /// /// Gets or sets the parameter that determines if return cmdlets based on abbreviation expansion. @@ -367,7 +368,11 @@ protected override void BeginProcessing() #if LEGACYTELEMETRY _timer.Start(); #endif - base.BeginProcessing(); + if (UseFuzzyMatching) + { + _fuzzyMatcher = new FuzzyMatcher(FuzzyMinimumDistance); + _commandScores = new List(); + } if (ShowCommandInfo.IsPresent && Syntax.IsPresent) { @@ -503,14 +508,11 @@ protected override void EndProcessing() private void OutputResultsHelper(IEnumerable results) { - CommandOrigin origin = this.MyInvocation.CommandOrigin; + CommandOrigin origin = MyInvocation.CommandOrigin; if (UseFuzzyMatching) { - _commandScores = _commandScores - .Where(x => x.Score <= FuzzyMinimumDistance) - .OrderBy(static x => x.Score) - .ToList(); + _commandScores = _commandScores.OrderBy(static x => x.Score).ToList(); results = _commandScores.Select(static x => x.Command); } @@ -784,11 +786,6 @@ private void AccumulateMatchingCommands(IEnumerable commandNames) options |= SearchResolutionOptions.UseAbbreviationExpansion; } - if (UseFuzzyMatching) - { - options |= SearchResolutionOptions.FuzzyMatch; - } - if ((this.CommandType & CommandTypes.Alias) != 0) { options |= SearchResolutionOptions.ResolveAliasPatterns; @@ -861,24 +858,25 @@ private void AccumulateMatchingCommands(IEnumerable commandNames) IEnumerable commands; if (UseFuzzyMatching) { - foreach (var commandScore in System.Management.Automation.Internal.ModuleUtils.GetFuzzyMatchingCommands( + foreach (var commandScore in ModuleUtils.GetFuzzyMatchingCommands( plainCommandName, - this.Context, - this.MyInvocation.CommandOrigin, + Context, + MyInvocation.CommandOrigin, + _fuzzyMatcher, rediscoverImportedModules: true, moduleVersionRequired: _isFullyQualifiedModuleSpecified)) { _commandScores.Add(commandScore); } - commands = _commandScores.Select(static x => x.Command).ToList(); + commands = _commandScores.Select(static x => x.Command); } else { - commands = System.Management.Automation.Internal.ModuleUtils.GetMatchingCommands( + commands = ModuleUtils.GetMatchingCommands( plainCommandName, - this.Context, - this.MyInvocation.CommandOrigin, + Context, + MyInvocation.CommandOrigin, rediscoverImportedModules: true, moduleVersionRequired: _isFullyQualifiedModuleSpecified, useAbbreviationExpansion: UseAbbreviationExpansion); @@ -939,12 +937,12 @@ private void AccumulateMatchingCommands(IEnumerable commandNames) private bool FindCommandForName(SearchResolutionOptions options, string commandName, bool isPattern, bool emitErrors, ref int currentCount, out bool isDuplicate) { - CommandSearcher searcher = - new CommandSearcher( - commandName, - options, - this.CommandType, - this.Context); + var searcher = new CommandSearcher( + commandName, + options, + CommandType, + Context, + _fuzzyMatcher); bool resultFound = false; isDuplicate = false; @@ -1032,8 +1030,10 @@ private bool FindCommandForName(SearchResolutionOptions options, string commandN if (UseFuzzyMatching) { - int score = FuzzyMatcher.GetDamerauLevenshteinDistance(current.Name, commandName); - _commandScores.Add(new CommandScore(current, score)); + if (_fuzzyMatcher.IsFuzzyMatch(current.Name, commandName, out int score)) + { + _commandScores.Add(new CommandScore(current, score)); + } } _accumulatedResults.Add(current); diff --git a/src/System.Management.Automation/engine/Modules/ModuleUtils.cs b/src/System.Management.Automation/engine/Modules/ModuleUtils.cs index 8dab2283fc5..a69b89744a0 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleUtils.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleUtils.cs @@ -385,15 +385,15 @@ internal static bool IsOnSystem32ModulePath(string path) /// Command pattern. /// Execution context. /// Command origin. + /// Fuzzy matcher to use. /// If true, rediscovers imported modules. /// Specific module version to be required. /// IEnumerable tuple containing the CommandInfo and the match score. - internal static IEnumerable GetFuzzyMatchingCommands(string pattern, ExecutionContext context, CommandOrigin commandOrigin, bool rediscoverImportedModules = false, bool moduleVersionRequired = false) + internal static IEnumerable GetFuzzyMatchingCommands(string pattern, ExecutionContext context, CommandOrigin commandOrigin, FuzzyMatcher fuzzyMatcher, bool rediscoverImportedModules = false, bool moduleVersionRequired = false) { - foreach (CommandInfo command in GetMatchingCommands(pattern, context, commandOrigin, rediscoverImportedModules, moduleVersionRequired, useFuzzyMatching: true)) + foreach (CommandInfo command in GetMatchingCommands(pattern, context, commandOrigin, rediscoverImportedModules, moduleVersionRequired, fuzzyMatcher: fuzzyMatcher)) { - int score = FuzzyMatcher.GetDamerauLevenshteinDistance(command.Name, pattern); - if (score <= FuzzyMatcher.MinimumDistance) + if (fuzzyMatcher.IsFuzzyMatch(command.Name, pattern, out int score)) { yield return new CommandScore(command, score); } @@ -408,10 +408,10 @@ internal static IEnumerable GetFuzzyMatchingCommands(string patter /// Command origin. /// If true, rediscovers imported modules. /// Specific module version to be required. - /// Use fuzzy matching. + /// Fuzzy matcher for fuzzy searching. /// Use abbreviation expansion for matching. /// Returns matching CommandInfo IEnumerable. - internal static IEnumerable GetMatchingCommands(string pattern, ExecutionContext context, CommandOrigin commandOrigin, bool rediscoverImportedModules = false, bool moduleVersionRequired = false, bool useFuzzyMatching = false, bool useAbbreviationExpansion = false) + internal static IEnumerable GetMatchingCommands(string pattern, ExecutionContext context, CommandOrigin commandOrigin, bool rediscoverImportedModules = false, bool moduleVersionRequired = false, FuzzyMatcher fuzzyMatcher = null, bool useAbbreviationExpansion = false) { // Otherwise, if it had wildcards, just return the "AvailableCommand" // type of command info. @@ -449,7 +449,7 @@ internal static IEnumerable GetMatchingCommands(string pattern, Exe foreach (KeyValuePair entry in psModule.ExportedCommands) { if (commandPattern.IsMatch(entry.Value.Name) || - (useFuzzyMatching && FuzzyMatcher.IsFuzzyMatch(entry.Value.Name, pattern)) || + (fuzzyMatcher is not null && fuzzyMatcher.IsFuzzyMatch(entry.Value.Name, pattern)) || (useAbbreviationExpansion && string.Equals(pattern, AbbreviateName(entry.Value.Name), StringComparison.OrdinalIgnoreCase))) { CommandInfo current = null; @@ -509,7 +509,7 @@ internal static IEnumerable GetMatchingCommands(string pattern, Exe CommandTypes commandTypes = pair.Value; if (commandPattern.IsMatch(commandName) || - (useFuzzyMatching && FuzzyMatcher.IsFuzzyMatch(commandName, pattern)) || + (fuzzyMatcher is not null && fuzzyMatcher.IsFuzzyMatch(commandName, pattern)) || (useAbbreviationExpansion && string.Equals(pattern, AbbreviateName(commandName), StringComparison.OrdinalIgnoreCase))) { bool shouldExportCommand = true; diff --git a/src/System.Management.Automation/utils/FuzzyMatch.cs b/src/System.Management.Automation/utils/FuzzyMatch.cs index 5b21022a6ef..c4e542a3ca5 100644 --- a/src/System.Management.Automation/utils/FuzzyMatch.cs +++ b/src/System.Management.Automation/utils/FuzzyMatch.cs @@ -1,23 +1,38 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +using System.Collections.Generic; using System.Globalization; namespace System.Management.Automation { - internal static class FuzzyMatcher + internal class FuzzyMatcher { - public const int MinimumDistance = 5; + internal readonly uint MinimumDistance; + + internal FuzzyMatcher(uint minimumDistance) + { + MinimumDistance = minimumDistance; + } /// /// Determine if the two strings are considered similar. /// - /// The first string to compare. - /// The second string to compare. + internal bool IsFuzzyMatch(string candidate, string pattern) + { + return IsFuzzyMatch(candidate, pattern, out _); + } + + /// + /// Determine if the two strings are considered similar, and return the similarity score. + /// + /// The candidate string to be compared. + /// The pattern string to be compared with. /// True if the two strings have a distance <= MinimumDistance. - public static bool IsFuzzyMatch(string string1, string string2) + internal bool IsFuzzyMatch(string candidate, string pattern, out int score) { - return GetDamerauLevenshteinDistance(string1, string2) <= MinimumDistance; + score = GetDamerauLevenshteinDistance(candidate, pattern); + return score <= MinimumDistance; } /// @@ -27,7 +42,7 @@ public static bool IsFuzzyMatch(string string1, string string2) /// The first string to compare. /// The second string to compare. /// The distance value where the lower the value the shorter the distance between the two strings representing a closer match. - public static int GetDamerauLevenshteinDistance(string string1, string string2) + internal static int GetDamerauLevenshteinDistance(string string1, string string2) { string1 = string1.ToUpper(CultureInfo.CurrentCulture); string2 = string2.ToUpper(CultureInfo.CurrentCulture); @@ -36,8 +51,15 @@ public static int GetDamerauLevenshteinDistance(string string1, string string2) int[,] matrix = new int[bounds.Height, bounds.Width]; - for (int height = 0; height < bounds.Height; height++) { matrix[height, 0] = height; } - for (int width = 0; width < bounds.Width; width++) { matrix[0, width] = width; } + for (int height = 0; height < bounds.Height; height++) + { + matrix[height, 0] = height; + } + + for (int width = 0; width < bounds.Width; width++) + { + matrix[0, width] = width; + } for (int height = 1; height < bounds.Height; height++) { From cc86f9ffd1a0c6402a5ebdb0a750127325853a2b Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Tue, 18 Oct 2022 11:07:22 -0700 Subject: [PATCH 119/779] Replace win7 runtime with win8 and remove APISets (#18304) --- .../windows/templates/windows-packaging.yml | 2 +- assets/wix/files.wxs | 492 ------------------ build.psm1 | 22 +- .../Microsoft.PowerShell.SDK.csproj | 1 - src/ResGen/ResGen.csproj | 2 +- src/TypeCatalogGen/TypeCatalogGen.csproj | 2 +- .../powershell-win-core.csproj | 2 +- test/hosting/hosting.tests.csproj | 1 - test/packaging/windows/exe.tests.ps1 | 10 +- test/packaging/windows/msi.tests.ps1 | 10 +- .../Get-ExperimentalFeature.Tests.ps1 | 4 +- test/tools/OpenCover/OpenCover.psm1 | 4 +- test/tools/TestExe/TestExe.csproj | 2 +- test/tools/TestService/TestService.csproj | 2 +- test/xUnit/xUnit.tests.csproj | 2 +- tools/ci.psm1 | 2 +- tools/findMissingNotices.ps1 | 10 +- tools/packaging/packaging.psm1 | 8 +- .../PowerShellPackage.ps1 | 4 +- .../azureDevOps/templates/testartifacts.yml | 8 +- .../templates/windows-hosted-build.yml | 4 +- .../templates/windows-packaging.yml | 4 +- 22 files changed, 52 insertions(+), 546 deletions(-) diff --git a/.vsts-ci/windows/templates/windows-packaging.yml b/.vsts-ci/windows/templates/windows-packaging.yml index 832fe73af5e..011a7424291 100644 --- a/.vsts-ci/windows/templates/windows-packaging.yml +++ b/.vsts-ci/windows/templates/windows-packaging.yml @@ -4,7 +4,7 @@ parameters: - name: jobName default: 'win_packaging' - name: runtimePrefix - default: 'win7' + default: 'win81' - name: architecture default: 'x64' - name: channel diff --git a/assets/wix/files.wxs b/assets/wix/files.wxs index c0ca7d624d4..ae7d69c9326 100644 --- a/assets/wix/files.wxs +++ b/assets/wix/files.wxs @@ -77,9 +77,6 @@ - - - @@ -95,9 +92,6 @@ - - - @@ -128,36 +122,18 @@ - - - - - - - - - - - - - - - - - - @@ -173,18 +149,12 @@ - - - - - - @@ -194,15 +164,9 @@ - - - - - - @@ -212,12 +176,6 @@ - - - - - - @@ -227,9 +185,6 @@ - - - @@ -260,24 +215,12 @@ - - - - - - - - - - - - @@ -296,12 +239,6 @@ - - - - - - @@ -317,39 +254,18 @@ - - - - - - - - - - - - - - - - - - - - - @@ -368,33 +284,18 @@ - - - - - - - - - - - - - - - @@ -410,9 +311,6 @@ - - - @@ -431,24 +329,12 @@ - - - - - - - - - - - - @@ -470,21 +356,12 @@ - - - - - - - - - @@ -494,12 +371,6 @@ - - - - - - @@ -512,42 +383,21 @@ - - - - - - - - - - - - - - - - - - - - - @@ -563,9 +413,6 @@ - - - @@ -587,39 +434,21 @@ - - - - - - - - - - - - - - - - - - @@ -638,24 +467,15 @@ - - - - - - - - - @@ -668,57 +488,27 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -731,78 +521,36 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -818,54 +566,27 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -875,21 +596,12 @@ - - - - - - - - - @@ -899,15 +611,9 @@ - - - - - - @@ -929,33 +635,21 @@ - - - - - - - - - - - - @@ -965,69 +659,33 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -1049,24 +707,12 @@ - - - - - - - - - - - - @@ -1079,33 +725,18 @@ - - - - - - - - - - - - - - - @@ -3176,13 +2807,11 @@ - - @@ -3193,40 +2822,27 @@ - - - - - - - - - - - - - @@ -3237,69 +2853,46 @@ - - - - - - - - - - - - - - - - - - - - - - - @@ -3307,38 +2900,25 @@ - - - - - - - - - - - - - @@ -3346,113 +2926,66 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -3460,39 +2993,23 @@ - - - - - - - - - - - - - - - - @@ -3500,25 +3017,16 @@ - - - - - - - - - diff --git a/build.psm1 b/build.psm1 index 17fb59711a9..3c4e8e64914 100644 --- a/build.psm1 +++ b/build.psm1 @@ -270,7 +270,7 @@ function Test-IsReleaseCandidate return $false } -$optimizedFddRegex = 'fxdependent-(linux|alpine|win|win7|osx)-(x64|x86|arm64|arm)' +$optimizedFddRegex = 'fxdependent-(linux|alpine|win|win81|osx)-(x64|x86|arm64|arm)' function Start-PSBuild { [CmdletBinding(DefaultParameterSetName="Default")] @@ -315,8 +315,8 @@ function Start-PSBuild { "osx-x64", "win-arm", "win-arm64", - "win7-x64", - "win7-x86")] + "win81-x64", + "win81-x86")] [string]$Runtime, [ValidateSet('Debug', 'Release', 'CodeCoverage', 'StaticAnalysis', '')] # We might need "Checked" as well @@ -349,8 +349,8 @@ function Start-PSBuild { } if ($ForMinimalSize) { - if ($Runtime -and "linux-x64", "win7-x64", "osx-x64" -notcontains $Runtime) { - throw "Build for the minimal size is enabled only for following runtimes: 'linux-x64', 'win7-x64', 'osx-x64'" + if ($Runtime -and "linux-x64", "win81-x64", "osx-x64" -notcontains $Runtime) { + throw "Build for the minimal size is enabled only for following runtimes: 'linux-x64', 'win81-x64', 'osx-x64'" } } @@ -528,7 +528,7 @@ Fix steps: if ($Options.Runtime -notlike 'fxdependent*' -or $Options.Runtime -match $optimizedFddRegex) { Write-Verbose "Building without shim" -Verbose $sdkToUse = 'Microsoft.NET.Sdk' - if ($Options.Runtime -like 'win7-*' -and !$ForMinimalSize) { + if ($Options.Runtime -like 'win81-*' -and !$ForMinimalSize) { ## WPF/WinForm and the PowerShell GraphicalHost assemblies are included ## when 'Microsoft.NET.Sdk.WindowsDesktop' is used. $sdkToUse = 'Microsoft.NET.Sdk.WindowsDesktop' @@ -721,7 +721,7 @@ function Restore-PSPackage } else { $sdkToUse = 'Microsoft.NET.Sdk' - if ($Options.Runtime -like 'win7-*' -and !$Options.ForMinimalSize) { + if ($Options.Runtime -like 'win81-*' -and !$Options.ForMinimalSize) { $sdkToUse = 'Microsoft.NET.Sdk.WindowsDesktop' } } @@ -836,8 +836,8 @@ function New-PSOptions { "osx-x64", "win-arm", "win-arm64", - "win7-x64", - "win7-x86")] + "win81-x64", + "win81-x86")] [string]$Runtime, # Accept a path to the output directory @@ -871,9 +871,9 @@ function New-PSOptions { switch ($Platform) { 'Windows' { - # For x86 and x64 architectures, we use win7-x64 and win7-x86 RIDs. + # For x86 and x64 architectures, we use win81-x64 and win81-x86 RIDs. # For arm and arm64 architectures, we use win-arm and win-arm64 RIDs. - $Platform = if ($Architecture[0] -eq 'x') { 'win7' } else { 'win' } + $Platform = if ($Architecture[0] -eq 'x') { 'win81' } else { 'win' } $Runtime = "${Platform}-${Architecture}" } diff --git a/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj b/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj index e2d6644ae25..682511ffba9 100644 --- a/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj +++ b/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj @@ -29,7 +29,6 @@ - diff --git a/src/ResGen/ResGen.csproj b/src/ResGen/ResGen.csproj index f86d5328ba8..84bde77f294 100644 --- a/src/ResGen/ResGen.csproj +++ b/src/ResGen/ResGen.csproj @@ -7,7 +7,7 @@ Exe true true - win7-x86;win7-x64;osx-x64;linux-x64 + win81-x86;win81-x64;osx-x64;linux-x64 diff --git a/src/TypeCatalogGen/TypeCatalogGen.csproj b/src/TypeCatalogGen/TypeCatalogGen.csproj index 170819a6bf9..1258bd28ac8 100644 --- a/src/TypeCatalogGen/TypeCatalogGen.csproj +++ b/src/TypeCatalogGen/TypeCatalogGen.csproj @@ -8,7 +8,7 @@ Exe true true - win7-x86;win7-x64;osx-x64;linux-x64 + win81-x86;win81-x64;osx-x64;linux-x64 diff --git a/src/powershell-win-core/powershell-win-core.csproj b/src/powershell-win-core/powershell-win-core.csproj index 9879e8485b4..e44a8a2f42d 100644 --- a/src/powershell-win-core/powershell-win-core.csproj +++ b/src/powershell-win-core/powershell-win-core.csproj @@ -8,7 +8,7 @@ true true true - win7-x86;win7-x64 + win81-x86;win81-x64 Microsoft.PowerShell ..\..\assets\pwsh.manifest Windows diff --git a/test/hosting/hosting.tests.csproj b/test/hosting/hosting.tests.csproj index 3a73e139318..cb72e0a90ef 100644 --- a/test/hosting/hosting.tests.csproj +++ b/test/hosting/hosting.tests.csproj @@ -5,7 +5,6 @@ PowerShell hosting SDK xUnit Tests powershell-hosting-tests - diff --git a/test/packaging/windows/exe.tests.ps1 b/test/packaging/windows/exe.tests.ps1 index 5a72195900e..2e0ffc9e9c1 100644 --- a/test/packaging/windows/exe.tests.ps1 +++ b/test/packaging/windows/exe.tests.ps1 @@ -63,17 +63,17 @@ Describe -Name "Windows EXE" -Fixture { Context "$Channel-$Runtime" { BeforeAll { Write-Verbose "cr-$channel-$runtime" -Verbose - switch ("$channel-$runtime") { - "preview-win7-x64" { + switch -regex ("$channel-$runtime") { + "preview-win\d*-x64" { $msiUpgradeCode = '39243d76-adaf-42b1-94fb-16ecf83237c8' } - "stable-win7-x64" { + "stable-win\d*-x64" { $msiUpgradeCode = '31ab5147-9a97-4452-8443-d9709f0516e1' } - "preview-win7-x86" { + "preview-win\d*-x86" { $msiUpgradeCode = '86abcfbd-1ccc-4a88-b8b2-0facfde29094' } - "stable-win7-x86" { + "stable-win\d*-x86" { $msiUpgradeCode = '1d00683b-0f84-4db8-a64f-2f98ad42fe06' } default { diff --git a/test/packaging/windows/msi.tests.ps1 b/test/packaging/windows/msi.tests.ps1 index 0ee34ca482c..6e4f9ff2f2f 100644 --- a/test/packaging/windows/msi.tests.ps1 +++ b/test/packaging/windows/msi.tests.ps1 @@ -145,23 +145,23 @@ Describe -Name "Windows MSI" -Fixture { $pwshPath = Join-Path $env:ProgramFiles -ChildPath "PowerShell" $pwshx86Path = Join-Path ${env:ProgramFiles(x86)} -ChildPath "PowerShell" - switch ("$channel-$runtime") { - "preview-win7-x64" { + switch -regex ("$channel-$runtime") { + "preview-win\d*-x64" { $versionPath = Join-Path -Path $pwshPath -ChildPath '7-preview' $revisionRange = 0, 99 $msiUpgradeCode = '39243d76-adaf-42b1-94fb-16ecf83237c8' } - "stable-win7-x64" { + "stable-win\d*-x64" { $versionPath = Join-Path -Path $pwshPath -ChildPath '7' $revisionRange = 500, 500 $msiUpgradeCode = '31ab5147-9a97-4452-8443-d9709f0516e1' } - "preview-win7-x86" { + "preview-win\d*-x86" { $versionPath = Join-Path -Path $pwshx86Path -ChildPath '7-preview' $revisionRange = 0, 99 $msiUpgradeCode = '86abcfbd-1ccc-4a88-b8b2-0facfde29094' } - "stable-win7-x86" { + "stable-win\d*-x86" { $versionPath = Join-Path -Path $pwshx86Path -ChildPath '7' $revisionRange = 500, 500 $msiUpgradeCode = '1d00683b-0f84-4db8-a64f-2f98ad42fe06' diff --git a/test/powershell/engine/ExperimentalFeature/Get-ExperimentalFeature.Tests.ps1 b/test/powershell/engine/ExperimentalFeature/Get-ExperimentalFeature.Tests.ps1 index 02c4ad856b7..f561440856f 100644 --- a/test/powershell/engine/ExperimentalFeature/Get-ExperimentalFeature.Tests.ps1 +++ b/test/powershell/engine/ExperimentalFeature/Get-ExperimentalFeature.Tests.ps1 @@ -167,7 +167,7 @@ Describe "Default enablement of Experimental Features" -Tags CI { It "On stable builds, Experimental Features are not enabled" -Skip:($isPreview) { foreach ($expFeature in Get-ExperimentalFeature) { - # In CI, pwsh that is running tests (with $PSHOME like D:\a\1\s\src\powershell-win-core\bin\release\net7.0\win7-x64\publish) + # In CI, pwsh that is running tests (with $PSHOME like D:\a\1\s\src\powershell-win-core\bin\release\net7.0\win81-x64\publish) # is launched from another pwsh (with $PSHOME like C:\program files\powershell\7) # resulting in combined PSModulePath which is used by Get-ExperimentalFeature to enum module-scoped exp.features from both pwsh locations. # So we need to exclude parent's modules' exp.features from verification using filtering on $PSHOME. @@ -184,7 +184,7 @@ Describe "Default enablement of Experimental Features" -Tags CI { foreach ($expFeature in Get-ExperimentalFeature) { - # In CI, pwsh that is running tests (with $PSHOME like D:\a\1\s\src\powershell-win-core\bin\release\net7.0\win7-x64\publish) + # In CI, pwsh that is running tests (with $PSHOME like D:\a\1\s\src\powershell-win-core\bin\release\net7.0\win81-x64\publish) # is launched from another pwsh (with $PSHOME like C:\program files\powershell\7) # resulting in combined PSModulePath which is used by Get-ExperimentalFeature to enum module-scoped exp.features from both pwsh locations. # So we need to exclude parent's modules' exp.features from verification using filtering on $PSHOME. diff --git a/test/tools/OpenCover/OpenCover.psm1 b/test/tools/OpenCover/OpenCover.psm1 index f9130df5ae9..262c1e075bd 100644 --- a/test/tools/OpenCover/OpenCover.psm1 +++ b/test/tools/OpenCover/OpenCover.psm1 @@ -615,7 +615,7 @@ function Install-OpenCover .Description Invoke-OpenCover runs tests under OpenCover by executing tests on PowerShell located at $PowerShellExeDirectory. .EXAMPLE - Invoke-OpenCover -TestPath $PWD/test/powershell -PowerShellExeDirectory $PWD/src/powershell-win-core/bin/CodeCoverage/7.0/win7-x64 + Invoke-OpenCover -TestPath $PWD/test/powershell -PowerShellExeDirectory $PWD/src/powershell-win-core/bin/CodeCoverage/7.0/win81-x64 #> function Invoke-OpenCover { @@ -624,7 +624,7 @@ function Invoke-OpenCover [parameter()]$OutputLog = "$HOME/Documents/OpenCover.xml", [parameter()]$TestPath = "${script:psRepoPath}/test/powershell", [parameter()]$OpenCoverPath = "$HOME/OpenCover", - [parameter()]$PowerShellExeDirectory = "${script:psRepoPath}/src/powershell-win-core/bin/CodeCoverage/net7.0/win7-x64/publish", + [parameter()]$PowerShellExeDirectory = "${script:psRepoPath}/src/powershell-win-core/bin/CodeCoverage/net7.0/win81-x64/publish", [parameter()]$PesterLogElevated = "$HOME/Documents/TestResultsElevated.xml", [parameter()]$PesterLogUnelevated = "$HOME/Documents/TestResultsUnelevated.xml", [parameter()]$PesterLogFormat = "NUnitXml", diff --git a/test/tools/TestExe/TestExe.csproj b/test/tools/TestExe/TestExe.csproj index 8eec2019df3..21f10e03c35 100644 --- a/test/tools/TestExe/TestExe.csproj +++ b/test/tools/TestExe/TestExe.csproj @@ -8,7 +8,7 @@ Exe true true - win7-x86;win7-x64;osx-x64;linux-x64 + win81-x86;win81-x64;osx-x64;linux-x64 diff --git a/test/tools/TestService/TestService.csproj b/test/tools/TestService/TestService.csproj index 3b8ded97a05..7630007f414 100644 --- a/test/tools/TestService/TestService.csproj +++ b/test/tools/TestService/TestService.csproj @@ -9,7 +9,7 @@ Exe true true - win7-x86;win7-x64 + win81-x86;win81-x64 diff --git a/test/xUnit/xUnit.tests.csproj b/test/xUnit/xUnit.tests.csproj index 2fb87c8e29d..609478361e8 100644 --- a/test/xUnit/xUnit.tests.csproj +++ b/test/xUnit/xUnit.tests.csproj @@ -6,7 +6,7 @@ PowerShell xUnit Tests powershell-tests true - win7-x86;win7-x64;osx-x64;linux-x64 + win81-x86;win81-x64;osx-x64;linux-x64 diff --git a/tools/ci.psm1 b/tools/ci.psm1 index e2feca60dd3..a03acea2dc0 100644 --- a/tools/ci.psm1 +++ b/tools/ci.psm1 @@ -467,7 +467,7 @@ function Get-ReleaseTag function Invoke-CIFinish { param( - [string] $Runtime = 'win7-x64', + [string] $Runtime = 'win81-x64', [string] $Channel = 'preview', [Validateset('Build','Package')] [string[]] $Stage = ('Build','Package') diff --git a/tools/findMissingNotices.ps1 b/tools/findMissingNotices.ps1 index c7a6514d723..a6ded1e0d60 100644 --- a/tools/findMissingNotices.ps1 +++ b/tools/findMissingNotices.ps1 @@ -166,8 +166,8 @@ function Get-CGRegistrations { "osx-x64", "win-arm", "win-arm64", - "win7-x64", - "win7-x86", + "win81-x64", + "win81-x86", "modules")] [string]$Runtime, @@ -196,7 +196,7 @@ function Get-CGRegistrations { $folder = $unixProjectName $target = "$dotnetTargetName|$Runtime" } - "win7-.*" { + "win81-.*" { $sdkToUse = $winDesktopSdk $folder = $windowsProjectName $target = "$dotnetTargetNameWin7|$Runtime" @@ -264,7 +264,7 @@ function Get-CGRegistrations { $registrations = [System.Collections.Generic.Dictionary[string, Registration]]::new() $lastCount = 0 $registrationChanged = $false -foreach ($runtime in "win7-x64", "linux-x64", "osx-x64", "alpine-x64", "win-arm", "linux-arm", "linux-arm64", "osx-arm64", "win-arm64", "win7-x86") { +foreach ($runtime in "win81-x64", "linux-x64", "osx-x64", "alpine-x64", "win-arm", "linux-arm", "linux-arm64", "osx-arm64", "win-arm64", "win81-x86") { $registrationChanged = (Get-CGRegistrations -Runtime $runtime -RegistrationTable $registrations) -or $registrationChanged $count = $registrations.Count $newCount = $count - $lastCount @@ -276,7 +276,7 @@ $newRegistrations = $registrations.Keys | Sort-Object | ForEach-Object { $regist $count = $newRegistrations.Count $newJson = @{ - Registrations = $newRegistrations + Registrations = $newRegistrations '$schema' = "https://json.schemastore.org/component-detection-manifest.json" } | ConvertTo-Json -depth 99 diff --git a/tools/packaging/packaging.psm1 b/tools/packaging/packaging.psm1 index d3484793a74..654b48ddfd7 100644 --- a/tools/packaging/packaging.psm1 +++ b/tools/packaging/packaging.psm1 @@ -41,7 +41,7 @@ function Start-PSPackage { [string[]]$Type, # Generate windows downlevel package - [ValidateSet("win7-x86", "win7-x64", "win-arm", "win-arm64")] + [ValidateSet("win81-x86", "win81-x64", "win-arm", "win-arm64")] [ValidateScript({$Environment.IsWindows})] [string] $WindowsRuntime, @@ -102,7 +102,7 @@ function Start-PSPackage { } if ($Environment.IsWindows) { - # Runtime will be one of win7-x64, win7-x86, "win-arm" and "win-arm64" on Windows. + # Runtime will be one of win81-x64, win81-x86, "win-arm" and "win-arm64" on Windows. # Build the name suffix for universal win-plat packages. switch ($Runtime) { "win-arm" { $NameSuffix = "win-arm32" } @@ -3200,7 +3200,7 @@ function New-MSIPatch # This example shows how to produce a Debug-x64 installer for development purposes. cd $RootPathOfPowerShellRepo Import-Module .\build.psm1; Import-Module .\tools\packaging\packaging.psm1 - New-MSIPackage -Verbose -ProductSourcePath '.\src\powershell-win-core\bin\Debug\net7.0\win7-x64\publish' -ProductTargetArchitecture x64 -ProductVersion '1.2.3' + New-MSIPackage -Verbose -ProductSourcePath '.\src\powershell-win-core\bin\Debug\net7.0\win81-x64\publish' -ProductTargetArchitecture x64 -ProductVersion '1.2.3' #> function New-MSIPackage { @@ -3591,7 +3591,7 @@ function Start-MsiBuild { # This example shows how to produce a Debug-x64 installer for development purposes. cd $RootPathOfPowerShellRepo Import-Module .\build.psm1; Import-Module .\tools\packaging\packaging.psm1 - New-MSIXPackage -Verbose -ProductSourcePath '.\src\powershell-win-core\bin\Debug\net7.0\win7-x64\publish' -ProductTargetArchitecture x64 -ProductVersion '1.2.3' + New-MSIXPackage -Verbose -ProductSourcePath '.\src\powershell-win-core\bin\Debug\net7.0\win81-x64\publish' -ProductTargetArchitecture x64 -ProductVersion '1.2.3' #> function New-MSIXPackage { diff --git a/tools/releaseBuild/Images/microsoft_powershell_windowsservercore/PowerShellPackage.ps1 b/tools/releaseBuild/Images/microsoft_powershell_windowsservercore/PowerShellPackage.ps1 index ae0bc4f2b10..443f22bd859 100644 --- a/tools/releaseBuild/Images/microsoft_powershell_windowsservercore/PowerShellPackage.ps1 +++ b/tools/releaseBuild/Images/microsoft_powershell_windowsservercore/PowerShellPackage.ps1 @@ -11,8 +11,8 @@ param ( [string] $destination = "$env:WORKSPACE", - [ValidateSet("win7-x64", "win7-x86", "win-arm", "win-arm64", "fxdependent", "fxdependent-win-desktop")] - [string] $Runtime = 'win7-x64', + [ValidateSet("win81-x64", "win81-x86", "win-arm", "win-arm64", "fxdependent", "fxdependent-win-desktop")] + [string] $Runtime = 'win81-x64', [switch] $ForMinimalSize, diff --git a/tools/releaseBuild/azureDevOps/templates/testartifacts.yml b/tools/releaseBuild/azureDevOps/templates/testartifacts.yml index b75ade828a3..4d7111f94de 100644 --- a/tools/releaseBuild/azureDevOps/templates/testartifacts.yml +++ b/tools/releaseBuild/azureDevOps/templates/testartifacts.yml @@ -35,8 +35,8 @@ jobs: switch ($runtime) { - win7-x64 { $packageName = "TestPackage-win-x64.zip" } - win7-x86 { $packageName = "TestPackage-win-x86.zip" } + win81-x64 { $packageName = "TestPackage-win-x64.zip" } + win81-x86 { $packageName = "TestPackage-win-x86.zip" } win-arm64 { $packageName = "TestPackage-win-arm64.zip" } linux-x64 { $packageName = "TestPackage-linux-x64.zip" } linux-arm { $packageName = "TestPackage-linux-arm.zip" } @@ -49,8 +49,8 @@ jobs: Write-Host "##vso[artifact.upload containerfolder=testArtifacts;artifactname=testArtifacts]$(System.ArtifactsDirectory)/$packageName" } - BuildTestPackage -runtime win7-x64 - BuildTestPackage -runtime win7-x86 + BuildTestPackage -runtime win81-x64 + BuildTestPackage -runtime win81-x86 BuildTestPackage -runtime win-arm64 BuildTestPackage -runtime linux-x64 BuildTestPackage -runtime linux-arm diff --git a/tools/releaseBuild/azureDevOps/templates/windows-hosted-build.yml b/tools/releaseBuild/azureDevOps/templates/windows-hosted-build.yml index 1201edf98b7..f5dfe4b75cf 100644 --- a/tools/releaseBuild/azureDevOps/templates/windows-hosted-build.yml +++ b/tools/releaseBuild/azureDevOps/templates/windows-hosted-build.yml @@ -50,8 +50,8 @@ jobs: $runtime = switch ($env:Architecture) { - "x64" { "win7-x64" } - "x86" { "win7-x86" } + "x64" { "win81-x64" } + "x86" { "win81-x86" } "arm" { "win-arm"} "arm64" { "win-arm64" } "fxdependent" { "fxdependent" } diff --git a/tools/releaseBuild/azureDevOps/templates/windows-packaging.yml b/tools/releaseBuild/azureDevOps/templates/windows-packaging.yml index befcebf3bd3..10870c8521a 100644 --- a/tools/releaseBuild/azureDevOps/templates/windows-packaging.yml +++ b/tools/releaseBuild/azureDevOps/templates/windows-packaging.yml @@ -239,8 +239,8 @@ jobs: - pwsh: | $runtime = switch ($env:Architecture) { - "x64" { "win7-x64" } - "x86" { "win7-x86" } + "x64" { "win81-x64" } + "x86" { "win81-x86" } "arm" { "win-arm"} "arm64" { "win-arm64" } "fxdependent" { "fxdependent" } From 01948aedb679a4bcf04be64e18cec4ad7eacf74f Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Tue, 18 Oct 2022 11:52:06 -0700 Subject: [PATCH 120/779] Remove the `ProcessorArchitecture` portion from the full name as it's obsolete (#18320) --- .../singleshell/config/MshSnapinInfo.cs | 45 ++++++++----------- test/xUnit/csharp/test_MshSnapinInfo.cs | 2 +- 2 files changed, 19 insertions(+), 28 deletions(-) diff --git a/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs b/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs index e3ce3a406d1..05f8991e4a9 100644 --- a/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs +++ b/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs @@ -865,7 +865,7 @@ internal static Version ReadVersionValue(RegistryKey mshsnapinKey, string name, return v; } - internal static void ReadRegistryInfo(out Version assemblyVersion, out string publicKeyToken, out string culture, out string architecture, out string applicationBase, out Version psVersion) + internal static void ReadRegistryInfo(out Version assemblyVersion, out string publicKeyToken, out string culture, out string applicationBase, out Version psVersion) { applicationBase = Utils.DefaultPowerShellAppBase; Dbg.Assert( @@ -885,8 +885,7 @@ internal static void ReadRegistryInfo(out Version assemblyVersion, out string pu // culture, publickeytoken...This will break the scenarios where only one of // the assemblies is patched. ie., all monad assemblies should have the // same version number. - Assembly currentAssembly = typeof(PSSnapInReader).Assembly; - AssemblyName assemblyName = currentAssembly.GetName(); + AssemblyName assemblyName = typeof(PSSnapInReader).Assembly.GetName(); assemblyVersion = assemblyName.Version; byte[] publicTokens = assemblyName.GetPublicKeyToken(); if (publicTokens.Length == 0) @@ -899,11 +898,6 @@ internal static void ReadRegistryInfo(out Version assemblyVersion, out string pu // save some cpu cycles by hardcoding the culture to neutral // assembly should never be targeted to a particular culture culture = "neutral"; - - // Hardcoding the architecture MSIL as PowerShell assemblies are architecture neutral, this should - // be changed if the assumption is broken. Preferred hardcoded string to using (for perf reasons): - // string architecture = currentAssembly.GetName().ProcessorArchitecture.ToString() - architecture = "MSIL"; } /// @@ -931,13 +925,12 @@ internal static string ConvertByteArrayToString(byte[] tokens) /// internal static PSSnapInInfo ReadCoreEngineSnapIn() { - Version assemblyVersion, psVersion; - string publicKeyToken = null; - string culture = null; - string architecture = null; - string applicationBase = null; - - ReadRegistryInfo(out assemblyVersion, out publicKeyToken, out culture, out architecture, out applicationBase, out psVersion); + ReadRegistryInfo( + out Version assemblyVersion, + out string publicKeyToken, + out string culture, + out string applicationBase, + out Version psVersion); // System.Management.Automation formats & types files Collection types = new Collection(new string[] { "types.ps1xml", "typesv3.ps1xml" }); @@ -946,8 +939,8 @@ internal static PSSnapInInfo ReadCoreEngineSnapIn() "Help.format.ps1xml", "HelpV3.format.ps1xml", "PowerShellCore.format.ps1xml", "PowerShellTrace.format.ps1xml", "Registry.format.ps1xml"}); - string strongName = string.Format(CultureInfo.InvariantCulture, "{0}, Version={1}, Culture={2}, PublicKeyToken={3}, ProcessorArchitecture={4}", - s_coreSnapin.AssemblyName, assemblyVersion, culture, publicKeyToken, architecture); + string strongName = string.Format(CultureInfo.InvariantCulture, "{0}, Version={1}, Culture={2}, PublicKeyToken={3}", + s_coreSnapin.AssemblyName, assemblyVersion, culture, publicKeyToken); string moduleName = Path.Combine(applicationBase, s_coreSnapin.AssemblyName + ".dll"); @@ -985,13 +978,12 @@ internal static PSSnapInInfo ReadCoreEngineSnapIn() /// internal static Collection ReadEnginePSSnapIns() { - Version assemblyVersion, psVersion; - string publicKeyToken = null; - string culture = null; - string architecture = null; - string applicationBase = null; - - ReadRegistryInfo(out assemblyVersion, out publicKeyToken, out culture, out architecture, out applicationBase, out psVersion); + ReadRegistryInfo( + out Version assemblyVersion, + out string publicKeyToken, + out string culture, + out string applicationBase, + out Version psVersion); // System.Management.Automation formats & types files Collection smaFormats = new Collection(new string[] @@ -1010,12 +1002,11 @@ internal static Collection ReadEnginePSSnapIns() string strongName = string.Format( CultureInfo.InvariantCulture, - "{0}, Version={1}, Culture={2}, PublicKeyToken={3}, ProcessorArchitecture={4}", + "{0}, Version={1}, Culture={2}, PublicKeyToken={3}", defaultMshSnapinInfo.AssemblyName, assemblyVersionString, culture, - publicKeyToken, - architecture); + publicKeyToken); Collection formats = null; Collection types = null; diff --git a/test/xUnit/csharp/test_MshSnapinInfo.cs b/test/xUnit/csharp/test_MshSnapinInfo.cs index 2742ba71c09..039825025d1 100644 --- a/test/xUnit/csharp/test_MshSnapinInfo.cs +++ b/test/xUnit/csharp/test_MshSnapinInfo.cs @@ -17,7 +17,7 @@ public void TestReadRegistryInfo() Skip.IfNot(Platform.IsWindows); Version someVersion = null; string someString = null; - PSSnapInReader.ReadRegistryInfo(out someVersion, out someString, out someString, out someString, out someString, out someVersion); + PSSnapInReader.ReadRegistryInfo(out someVersion, out someString, out someString, out someString, out someVersion); } // PublicKeyToken is null on Linux From 813d38875dc8bd6df0c52de8d79c4806adcd6dc7 Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Tue, 18 Oct 2022 16:48:07 -0700 Subject: [PATCH 121/779] Revert "Replace win7 runtime with win8 and remove APISets (#18304)" (#18322) --- .../windows/templates/windows-packaging.yml | 2 +- build.psm1 | 22 +++++++++---------- src/ResGen/ResGen.csproj | 2 +- src/TypeCatalogGen/TypeCatalogGen.csproj | 2 +- .../powershell-win-core.csproj | 2 +- test/hosting/hosting.tests.csproj | 1 + test/packaging/windows/exe.tests.ps1 | 10 ++++----- test/packaging/windows/msi.tests.ps1 | 10 ++++----- .../Get-ExperimentalFeature.Tests.ps1 | 4 ++-- test/tools/OpenCover/OpenCover.psm1 | 4 ++-- test/tools/TestExe/TestExe.csproj | 2 +- test/tools/TestService/TestService.csproj | 2 +- test/xUnit/xUnit.tests.csproj | 2 +- tools/ci.psm1 | 2 +- tools/findMissingNotices.ps1 | 10 ++++----- tools/packaging/packaging.psm1 | 8 +++---- .../PowerShellPackage.ps1 | 4 ++-- .../azureDevOps/templates/testartifacts.yml | 8 +++---- .../templates/windows-hosted-build.yml | 4 ++-- .../templates/windows-packaging.yml | 4 ++-- 20 files changed, 53 insertions(+), 52 deletions(-) diff --git a/.vsts-ci/windows/templates/windows-packaging.yml b/.vsts-ci/windows/templates/windows-packaging.yml index 011a7424291..832fe73af5e 100644 --- a/.vsts-ci/windows/templates/windows-packaging.yml +++ b/.vsts-ci/windows/templates/windows-packaging.yml @@ -4,7 +4,7 @@ parameters: - name: jobName default: 'win_packaging' - name: runtimePrefix - default: 'win81' + default: 'win7' - name: architecture default: 'x64' - name: channel diff --git a/build.psm1 b/build.psm1 index 3c4e8e64914..17fb59711a9 100644 --- a/build.psm1 +++ b/build.psm1 @@ -270,7 +270,7 @@ function Test-IsReleaseCandidate return $false } -$optimizedFddRegex = 'fxdependent-(linux|alpine|win|win81|osx)-(x64|x86|arm64|arm)' +$optimizedFddRegex = 'fxdependent-(linux|alpine|win|win7|osx)-(x64|x86|arm64|arm)' function Start-PSBuild { [CmdletBinding(DefaultParameterSetName="Default")] @@ -315,8 +315,8 @@ function Start-PSBuild { "osx-x64", "win-arm", "win-arm64", - "win81-x64", - "win81-x86")] + "win7-x64", + "win7-x86")] [string]$Runtime, [ValidateSet('Debug', 'Release', 'CodeCoverage', 'StaticAnalysis', '')] # We might need "Checked" as well @@ -349,8 +349,8 @@ function Start-PSBuild { } if ($ForMinimalSize) { - if ($Runtime -and "linux-x64", "win81-x64", "osx-x64" -notcontains $Runtime) { - throw "Build for the minimal size is enabled only for following runtimes: 'linux-x64', 'win81-x64', 'osx-x64'" + if ($Runtime -and "linux-x64", "win7-x64", "osx-x64" -notcontains $Runtime) { + throw "Build for the minimal size is enabled only for following runtimes: 'linux-x64', 'win7-x64', 'osx-x64'" } } @@ -528,7 +528,7 @@ Fix steps: if ($Options.Runtime -notlike 'fxdependent*' -or $Options.Runtime -match $optimizedFddRegex) { Write-Verbose "Building without shim" -Verbose $sdkToUse = 'Microsoft.NET.Sdk' - if ($Options.Runtime -like 'win81-*' -and !$ForMinimalSize) { + if ($Options.Runtime -like 'win7-*' -and !$ForMinimalSize) { ## WPF/WinForm and the PowerShell GraphicalHost assemblies are included ## when 'Microsoft.NET.Sdk.WindowsDesktop' is used. $sdkToUse = 'Microsoft.NET.Sdk.WindowsDesktop' @@ -721,7 +721,7 @@ function Restore-PSPackage } else { $sdkToUse = 'Microsoft.NET.Sdk' - if ($Options.Runtime -like 'win81-*' -and !$Options.ForMinimalSize) { + if ($Options.Runtime -like 'win7-*' -and !$Options.ForMinimalSize) { $sdkToUse = 'Microsoft.NET.Sdk.WindowsDesktop' } } @@ -836,8 +836,8 @@ function New-PSOptions { "osx-x64", "win-arm", "win-arm64", - "win81-x64", - "win81-x86")] + "win7-x64", + "win7-x86")] [string]$Runtime, # Accept a path to the output directory @@ -871,9 +871,9 @@ function New-PSOptions { switch ($Platform) { 'Windows' { - # For x86 and x64 architectures, we use win81-x64 and win81-x86 RIDs. + # For x86 and x64 architectures, we use win7-x64 and win7-x86 RIDs. # For arm and arm64 architectures, we use win-arm and win-arm64 RIDs. - $Platform = if ($Architecture[0] -eq 'x') { 'win81' } else { 'win' } + $Platform = if ($Architecture[0] -eq 'x') { 'win7' } else { 'win' } $Runtime = "${Platform}-${Architecture}" } diff --git a/src/ResGen/ResGen.csproj b/src/ResGen/ResGen.csproj index 84bde77f294..f86d5328ba8 100644 --- a/src/ResGen/ResGen.csproj +++ b/src/ResGen/ResGen.csproj @@ -7,7 +7,7 @@ Exe true true - win81-x86;win81-x64;osx-x64;linux-x64 + win7-x86;win7-x64;osx-x64;linux-x64 diff --git a/src/TypeCatalogGen/TypeCatalogGen.csproj b/src/TypeCatalogGen/TypeCatalogGen.csproj index 1258bd28ac8..170819a6bf9 100644 --- a/src/TypeCatalogGen/TypeCatalogGen.csproj +++ b/src/TypeCatalogGen/TypeCatalogGen.csproj @@ -8,7 +8,7 @@ Exe true true - win81-x86;win81-x64;osx-x64;linux-x64 + win7-x86;win7-x64;osx-x64;linux-x64 diff --git a/src/powershell-win-core/powershell-win-core.csproj b/src/powershell-win-core/powershell-win-core.csproj index e44a8a2f42d..9879e8485b4 100644 --- a/src/powershell-win-core/powershell-win-core.csproj +++ b/src/powershell-win-core/powershell-win-core.csproj @@ -8,7 +8,7 @@ true true true - win81-x86;win81-x64 + win7-x86;win7-x64 Microsoft.PowerShell ..\..\assets\pwsh.manifest Windows diff --git a/test/hosting/hosting.tests.csproj b/test/hosting/hosting.tests.csproj index cb72e0a90ef..3a73e139318 100644 --- a/test/hosting/hosting.tests.csproj +++ b/test/hosting/hosting.tests.csproj @@ -5,6 +5,7 @@ PowerShell hosting SDK xUnit Tests powershell-hosting-tests + diff --git a/test/packaging/windows/exe.tests.ps1 b/test/packaging/windows/exe.tests.ps1 index 2e0ffc9e9c1..5a72195900e 100644 --- a/test/packaging/windows/exe.tests.ps1 +++ b/test/packaging/windows/exe.tests.ps1 @@ -63,17 +63,17 @@ Describe -Name "Windows EXE" -Fixture { Context "$Channel-$Runtime" { BeforeAll { Write-Verbose "cr-$channel-$runtime" -Verbose - switch -regex ("$channel-$runtime") { - "preview-win\d*-x64" { + switch ("$channel-$runtime") { + "preview-win7-x64" { $msiUpgradeCode = '39243d76-adaf-42b1-94fb-16ecf83237c8' } - "stable-win\d*-x64" { + "stable-win7-x64" { $msiUpgradeCode = '31ab5147-9a97-4452-8443-d9709f0516e1' } - "preview-win\d*-x86" { + "preview-win7-x86" { $msiUpgradeCode = '86abcfbd-1ccc-4a88-b8b2-0facfde29094' } - "stable-win\d*-x86" { + "stable-win7-x86" { $msiUpgradeCode = '1d00683b-0f84-4db8-a64f-2f98ad42fe06' } default { diff --git a/test/packaging/windows/msi.tests.ps1 b/test/packaging/windows/msi.tests.ps1 index 6e4f9ff2f2f..0ee34ca482c 100644 --- a/test/packaging/windows/msi.tests.ps1 +++ b/test/packaging/windows/msi.tests.ps1 @@ -145,23 +145,23 @@ Describe -Name "Windows MSI" -Fixture { $pwshPath = Join-Path $env:ProgramFiles -ChildPath "PowerShell" $pwshx86Path = Join-Path ${env:ProgramFiles(x86)} -ChildPath "PowerShell" - switch -regex ("$channel-$runtime") { - "preview-win\d*-x64" { + switch ("$channel-$runtime") { + "preview-win7-x64" { $versionPath = Join-Path -Path $pwshPath -ChildPath '7-preview' $revisionRange = 0, 99 $msiUpgradeCode = '39243d76-adaf-42b1-94fb-16ecf83237c8' } - "stable-win\d*-x64" { + "stable-win7-x64" { $versionPath = Join-Path -Path $pwshPath -ChildPath '7' $revisionRange = 500, 500 $msiUpgradeCode = '31ab5147-9a97-4452-8443-d9709f0516e1' } - "preview-win\d*-x86" { + "preview-win7-x86" { $versionPath = Join-Path -Path $pwshx86Path -ChildPath '7-preview' $revisionRange = 0, 99 $msiUpgradeCode = '86abcfbd-1ccc-4a88-b8b2-0facfde29094' } - "stable-win\d*-x86" { + "stable-win7-x86" { $versionPath = Join-Path -Path $pwshx86Path -ChildPath '7' $revisionRange = 500, 500 $msiUpgradeCode = '1d00683b-0f84-4db8-a64f-2f98ad42fe06' diff --git a/test/powershell/engine/ExperimentalFeature/Get-ExperimentalFeature.Tests.ps1 b/test/powershell/engine/ExperimentalFeature/Get-ExperimentalFeature.Tests.ps1 index f561440856f..02c4ad856b7 100644 --- a/test/powershell/engine/ExperimentalFeature/Get-ExperimentalFeature.Tests.ps1 +++ b/test/powershell/engine/ExperimentalFeature/Get-ExperimentalFeature.Tests.ps1 @@ -167,7 +167,7 @@ Describe "Default enablement of Experimental Features" -Tags CI { It "On stable builds, Experimental Features are not enabled" -Skip:($isPreview) { foreach ($expFeature in Get-ExperimentalFeature) { - # In CI, pwsh that is running tests (with $PSHOME like D:\a\1\s\src\powershell-win-core\bin\release\net7.0\win81-x64\publish) + # In CI, pwsh that is running tests (with $PSHOME like D:\a\1\s\src\powershell-win-core\bin\release\net7.0\win7-x64\publish) # is launched from another pwsh (with $PSHOME like C:\program files\powershell\7) # resulting in combined PSModulePath which is used by Get-ExperimentalFeature to enum module-scoped exp.features from both pwsh locations. # So we need to exclude parent's modules' exp.features from verification using filtering on $PSHOME. @@ -184,7 +184,7 @@ Describe "Default enablement of Experimental Features" -Tags CI { foreach ($expFeature in Get-ExperimentalFeature) { - # In CI, pwsh that is running tests (with $PSHOME like D:\a\1\s\src\powershell-win-core\bin\release\net7.0\win81-x64\publish) + # In CI, pwsh that is running tests (with $PSHOME like D:\a\1\s\src\powershell-win-core\bin\release\net7.0\win7-x64\publish) # is launched from another pwsh (with $PSHOME like C:\program files\powershell\7) # resulting in combined PSModulePath which is used by Get-ExperimentalFeature to enum module-scoped exp.features from both pwsh locations. # So we need to exclude parent's modules' exp.features from verification using filtering on $PSHOME. diff --git a/test/tools/OpenCover/OpenCover.psm1 b/test/tools/OpenCover/OpenCover.psm1 index 262c1e075bd..f9130df5ae9 100644 --- a/test/tools/OpenCover/OpenCover.psm1 +++ b/test/tools/OpenCover/OpenCover.psm1 @@ -615,7 +615,7 @@ function Install-OpenCover .Description Invoke-OpenCover runs tests under OpenCover by executing tests on PowerShell located at $PowerShellExeDirectory. .EXAMPLE - Invoke-OpenCover -TestPath $PWD/test/powershell -PowerShellExeDirectory $PWD/src/powershell-win-core/bin/CodeCoverage/7.0/win81-x64 + Invoke-OpenCover -TestPath $PWD/test/powershell -PowerShellExeDirectory $PWD/src/powershell-win-core/bin/CodeCoverage/7.0/win7-x64 #> function Invoke-OpenCover { @@ -624,7 +624,7 @@ function Invoke-OpenCover [parameter()]$OutputLog = "$HOME/Documents/OpenCover.xml", [parameter()]$TestPath = "${script:psRepoPath}/test/powershell", [parameter()]$OpenCoverPath = "$HOME/OpenCover", - [parameter()]$PowerShellExeDirectory = "${script:psRepoPath}/src/powershell-win-core/bin/CodeCoverage/net7.0/win81-x64/publish", + [parameter()]$PowerShellExeDirectory = "${script:psRepoPath}/src/powershell-win-core/bin/CodeCoverage/net7.0/win7-x64/publish", [parameter()]$PesterLogElevated = "$HOME/Documents/TestResultsElevated.xml", [parameter()]$PesterLogUnelevated = "$HOME/Documents/TestResultsUnelevated.xml", [parameter()]$PesterLogFormat = "NUnitXml", diff --git a/test/tools/TestExe/TestExe.csproj b/test/tools/TestExe/TestExe.csproj index 21f10e03c35..8eec2019df3 100644 --- a/test/tools/TestExe/TestExe.csproj +++ b/test/tools/TestExe/TestExe.csproj @@ -8,7 +8,7 @@ Exe true true - win81-x86;win81-x64;osx-x64;linux-x64 + win7-x86;win7-x64;osx-x64;linux-x64 diff --git a/test/tools/TestService/TestService.csproj b/test/tools/TestService/TestService.csproj index 7630007f414..3b8ded97a05 100644 --- a/test/tools/TestService/TestService.csproj +++ b/test/tools/TestService/TestService.csproj @@ -9,7 +9,7 @@ Exe true true - win81-x86;win81-x64 + win7-x86;win7-x64 diff --git a/test/xUnit/xUnit.tests.csproj b/test/xUnit/xUnit.tests.csproj index 609478361e8..2fb87c8e29d 100644 --- a/test/xUnit/xUnit.tests.csproj +++ b/test/xUnit/xUnit.tests.csproj @@ -6,7 +6,7 @@ PowerShell xUnit Tests powershell-tests true - win81-x86;win81-x64;osx-x64;linux-x64 + win7-x86;win7-x64;osx-x64;linux-x64 diff --git a/tools/ci.psm1 b/tools/ci.psm1 index a03acea2dc0..e2feca60dd3 100644 --- a/tools/ci.psm1 +++ b/tools/ci.psm1 @@ -467,7 +467,7 @@ function Get-ReleaseTag function Invoke-CIFinish { param( - [string] $Runtime = 'win81-x64', + [string] $Runtime = 'win7-x64', [string] $Channel = 'preview', [Validateset('Build','Package')] [string[]] $Stage = ('Build','Package') diff --git a/tools/findMissingNotices.ps1 b/tools/findMissingNotices.ps1 index a6ded1e0d60..c7a6514d723 100644 --- a/tools/findMissingNotices.ps1 +++ b/tools/findMissingNotices.ps1 @@ -166,8 +166,8 @@ function Get-CGRegistrations { "osx-x64", "win-arm", "win-arm64", - "win81-x64", - "win81-x86", + "win7-x64", + "win7-x86", "modules")] [string]$Runtime, @@ -196,7 +196,7 @@ function Get-CGRegistrations { $folder = $unixProjectName $target = "$dotnetTargetName|$Runtime" } - "win81-.*" { + "win7-.*" { $sdkToUse = $winDesktopSdk $folder = $windowsProjectName $target = "$dotnetTargetNameWin7|$Runtime" @@ -264,7 +264,7 @@ function Get-CGRegistrations { $registrations = [System.Collections.Generic.Dictionary[string, Registration]]::new() $lastCount = 0 $registrationChanged = $false -foreach ($runtime in "win81-x64", "linux-x64", "osx-x64", "alpine-x64", "win-arm", "linux-arm", "linux-arm64", "osx-arm64", "win-arm64", "win81-x86") { +foreach ($runtime in "win7-x64", "linux-x64", "osx-x64", "alpine-x64", "win-arm", "linux-arm", "linux-arm64", "osx-arm64", "win-arm64", "win7-x86") { $registrationChanged = (Get-CGRegistrations -Runtime $runtime -RegistrationTable $registrations) -or $registrationChanged $count = $registrations.Count $newCount = $count - $lastCount @@ -276,7 +276,7 @@ $newRegistrations = $registrations.Keys | Sort-Object | ForEach-Object { $regist $count = $newRegistrations.Count $newJson = @{ - Registrations = $newRegistrations + Registrations = $newRegistrations '$schema' = "https://json.schemastore.org/component-detection-manifest.json" } | ConvertTo-Json -depth 99 diff --git a/tools/packaging/packaging.psm1 b/tools/packaging/packaging.psm1 index 654b48ddfd7..d3484793a74 100644 --- a/tools/packaging/packaging.psm1 +++ b/tools/packaging/packaging.psm1 @@ -41,7 +41,7 @@ function Start-PSPackage { [string[]]$Type, # Generate windows downlevel package - [ValidateSet("win81-x86", "win81-x64", "win-arm", "win-arm64")] + [ValidateSet("win7-x86", "win7-x64", "win-arm", "win-arm64")] [ValidateScript({$Environment.IsWindows})] [string] $WindowsRuntime, @@ -102,7 +102,7 @@ function Start-PSPackage { } if ($Environment.IsWindows) { - # Runtime will be one of win81-x64, win81-x86, "win-arm" and "win-arm64" on Windows. + # Runtime will be one of win7-x64, win7-x86, "win-arm" and "win-arm64" on Windows. # Build the name suffix for universal win-plat packages. switch ($Runtime) { "win-arm" { $NameSuffix = "win-arm32" } @@ -3200,7 +3200,7 @@ function New-MSIPatch # This example shows how to produce a Debug-x64 installer for development purposes. cd $RootPathOfPowerShellRepo Import-Module .\build.psm1; Import-Module .\tools\packaging\packaging.psm1 - New-MSIPackage -Verbose -ProductSourcePath '.\src\powershell-win-core\bin\Debug\net7.0\win81-x64\publish' -ProductTargetArchitecture x64 -ProductVersion '1.2.3' + New-MSIPackage -Verbose -ProductSourcePath '.\src\powershell-win-core\bin\Debug\net7.0\win7-x64\publish' -ProductTargetArchitecture x64 -ProductVersion '1.2.3' #> function New-MSIPackage { @@ -3591,7 +3591,7 @@ function Start-MsiBuild { # This example shows how to produce a Debug-x64 installer for development purposes. cd $RootPathOfPowerShellRepo Import-Module .\build.psm1; Import-Module .\tools\packaging\packaging.psm1 - New-MSIXPackage -Verbose -ProductSourcePath '.\src\powershell-win-core\bin\Debug\net7.0\win81-x64\publish' -ProductTargetArchitecture x64 -ProductVersion '1.2.3' + New-MSIXPackage -Verbose -ProductSourcePath '.\src\powershell-win-core\bin\Debug\net7.0\win7-x64\publish' -ProductTargetArchitecture x64 -ProductVersion '1.2.3' #> function New-MSIXPackage { diff --git a/tools/releaseBuild/Images/microsoft_powershell_windowsservercore/PowerShellPackage.ps1 b/tools/releaseBuild/Images/microsoft_powershell_windowsservercore/PowerShellPackage.ps1 index 443f22bd859..ae0bc4f2b10 100644 --- a/tools/releaseBuild/Images/microsoft_powershell_windowsservercore/PowerShellPackage.ps1 +++ b/tools/releaseBuild/Images/microsoft_powershell_windowsservercore/PowerShellPackage.ps1 @@ -11,8 +11,8 @@ param ( [string] $destination = "$env:WORKSPACE", - [ValidateSet("win81-x64", "win81-x86", "win-arm", "win-arm64", "fxdependent", "fxdependent-win-desktop")] - [string] $Runtime = 'win81-x64', + [ValidateSet("win7-x64", "win7-x86", "win-arm", "win-arm64", "fxdependent", "fxdependent-win-desktop")] + [string] $Runtime = 'win7-x64', [switch] $ForMinimalSize, diff --git a/tools/releaseBuild/azureDevOps/templates/testartifacts.yml b/tools/releaseBuild/azureDevOps/templates/testartifacts.yml index 4d7111f94de..b75ade828a3 100644 --- a/tools/releaseBuild/azureDevOps/templates/testartifacts.yml +++ b/tools/releaseBuild/azureDevOps/templates/testartifacts.yml @@ -35,8 +35,8 @@ jobs: switch ($runtime) { - win81-x64 { $packageName = "TestPackage-win-x64.zip" } - win81-x86 { $packageName = "TestPackage-win-x86.zip" } + win7-x64 { $packageName = "TestPackage-win-x64.zip" } + win7-x86 { $packageName = "TestPackage-win-x86.zip" } win-arm64 { $packageName = "TestPackage-win-arm64.zip" } linux-x64 { $packageName = "TestPackage-linux-x64.zip" } linux-arm { $packageName = "TestPackage-linux-arm.zip" } @@ -49,8 +49,8 @@ jobs: Write-Host "##vso[artifact.upload containerfolder=testArtifacts;artifactname=testArtifacts]$(System.ArtifactsDirectory)/$packageName" } - BuildTestPackage -runtime win81-x64 - BuildTestPackage -runtime win81-x86 + BuildTestPackage -runtime win7-x64 + BuildTestPackage -runtime win7-x86 BuildTestPackage -runtime win-arm64 BuildTestPackage -runtime linux-x64 BuildTestPackage -runtime linux-arm diff --git a/tools/releaseBuild/azureDevOps/templates/windows-hosted-build.yml b/tools/releaseBuild/azureDevOps/templates/windows-hosted-build.yml index f5dfe4b75cf..1201edf98b7 100644 --- a/tools/releaseBuild/azureDevOps/templates/windows-hosted-build.yml +++ b/tools/releaseBuild/azureDevOps/templates/windows-hosted-build.yml @@ -50,8 +50,8 @@ jobs: $runtime = switch ($env:Architecture) { - "x64" { "win81-x64" } - "x86" { "win81-x86" } + "x64" { "win7-x64" } + "x86" { "win7-x86" } "arm" { "win-arm"} "arm64" { "win-arm64" } "fxdependent" { "fxdependent" } diff --git a/tools/releaseBuild/azureDevOps/templates/windows-packaging.yml b/tools/releaseBuild/azureDevOps/templates/windows-packaging.yml index 10870c8521a..befcebf3bd3 100644 --- a/tools/releaseBuild/azureDevOps/templates/windows-packaging.yml +++ b/tools/releaseBuild/azureDevOps/templates/windows-packaging.yml @@ -239,8 +239,8 @@ jobs: - pwsh: | $runtime = switch ($env:Architecture) { - "x64" { "win81-x64" } - "x86" { "win81-x86" } + "x64" { "win7-x64" } + "x86" { "win7-x86" } "arm" { "win-arm"} "arm64" { "win-arm64" } "fxdependent" { "fxdependent" } From 028eeb045726ce94e81626e86d8063cdf9177d9e Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Tue, 18 Oct 2022 16:49:18 -0700 Subject: [PATCH 122/779] Bump to .NET 7 to version `7.0.100-rc.2.22477.20` (#18286) --- DotnetRuntimeMetadata.json | 8 ++++---- assets/wix/files.wxs | 20 ++++--------------- global.json | 2 +- ...soft.PowerShell.Commands.Management.csproj | 2 +- ...crosoft.PowerShell.Commands.Utility.csproj | 4 ++-- ...crosoft.PowerShell.CoreCLR.Eventing.csproj | 2 +- .../Microsoft.PowerShell.SDK.csproj | 8 ++++---- .../Microsoft.WSMan.Management.csproj | 2 +- .../System.Management.Automation.csproj | 16 +++++++-------- test/tools/TestService/TestService.csproj | 2 +- test/tools/WebListener/WebListener.csproj | 4 ++-- 11 files changed, 29 insertions(+), 41 deletions(-) diff --git a/DotnetRuntimeMetadata.json b/DotnetRuntimeMetadata.json index c13bf52cd59..2f4b4442efc 100644 --- a/DotnetRuntimeMetadata.json +++ b/DotnetRuntimeMetadata.json @@ -1,13 +1,13 @@ { "sdk": { - "channel": "7.0.1xx-rc1", + "channel": "7.0.1xx-rc2", "quality": "daily", "qualityFallback": "preview", - "packageVersionPattern": "7.0.0-rc.1", + "packageVersionPattern": "7.0.0-rc.2", "sdkImageVersion": "7.0.100", - "nextChannel": "7.0.1xx-rc1", + "nextChannel": "7.0.1xx-rc2", "azureFeed": "", - "sdkImageOverride": "7.0.100-rc.1.22431.12" + "sdkImageOverride": "" }, "internalfeed": { "url": "" diff --git a/assets/wix/files.wxs b/assets/wix/files.wxs index ae7d69c9326..d4427021a56 100644 --- a/assets/wix/files.wxs +++ b/assets/wix/files.wxs @@ -1221,15 +1221,6 @@ - - - - - - - - - @@ -2772,12 +2763,12 @@ - - - + + + @@ -3661,11 +3652,8 @@ - - - - + diff --git a/global.json b/global.json index fa6c98cbf9e..0ad5fa427db 100644 --- a/global.json +++ b/global.json @@ -1,5 +1,5 @@ { "sdk": { - "version": "7.0.100-rc.1.22431.12" + "version": "7.0.100-rc.2.22477.20" } } diff --git a/src/Microsoft.PowerShell.Commands.Management/Microsoft.PowerShell.Commands.Management.csproj b/src/Microsoft.PowerShell.Commands.Management/Microsoft.PowerShell.Commands.Management.csproj index 48fcd1861c4..414c338a2c4 100644 --- a/src/Microsoft.PowerShell.Commands.Management/Microsoft.PowerShell.Commands.Management.csproj +++ b/src/Microsoft.PowerShell.Commands.Management/Microsoft.PowerShell.Commands.Management.csproj @@ -47,7 +47,7 @@ - + diff --git a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj index 390a14193ba..d502b7048e3 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj +++ b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj @@ -32,8 +32,8 @@ - - + + diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/Microsoft.PowerShell.CoreCLR.Eventing.csproj b/src/Microsoft.PowerShell.CoreCLR.Eventing/Microsoft.PowerShell.CoreCLR.Eventing.csproj index 36317ba86ee..c33fc10ccd1 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/Microsoft.PowerShell.CoreCLR.Eventing.csproj +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/Microsoft.PowerShell.CoreCLR.Eventing.csproj @@ -8,7 +8,7 @@ - + diff --git a/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj b/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj index 682511ffba9..4159ee8e569 100644 --- a/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj +++ b/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj @@ -18,9 +18,9 @@ - - - + + + @@ -29,7 +29,7 @@ - + diff --git a/src/Microsoft.WSMan.Management/Microsoft.WSMan.Management.csproj b/src/Microsoft.WSMan.Management/Microsoft.WSMan.Management.csproj index 0ac640d196e..3b45803af9d 100644 --- a/src/Microsoft.WSMan.Management/Microsoft.WSMan.Management.csproj +++ b/src/Microsoft.WSMan.Management/Microsoft.WSMan.Management.csproj @@ -10,7 +10,7 @@ - + diff --git a/src/System.Management.Automation/System.Management.Automation.csproj b/src/System.Management.Automation/System.Management.Automation.csproj index 17938e92941..67431292607 100644 --- a/src/System.Management.Automation/System.Management.Automation.csproj +++ b/src/System.Management.Automation/System.Management.Automation.csproj @@ -1,4 +1,4 @@ - + PowerShell's System.Management.Automation project @@ -34,16 +34,16 @@ - - - + + + - + - - - + + + diff --git a/test/tools/TestService/TestService.csproj b/test/tools/TestService/TestService.csproj index 3b8ded97a05..aeb87b00ad1 100644 --- a/test/tools/TestService/TestService.csproj +++ b/test/tools/TestService/TestService.csproj @@ -13,7 +13,7 @@ - + diff --git a/test/tools/WebListener/WebListener.csproj b/test/tools/WebListener/WebListener.csproj index 972638cbba0..a80dcd0d97b 100644 --- a/test/tools/WebListener/WebListener.csproj +++ b/test/tools/WebListener/WebListener.csproj @@ -7,8 +7,8 @@ - - + + From b7f61ca50c7d480283b0d493fc2a4fc89e450bbe Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Wed, 19 Oct 2022 06:07:09 +0100 Subject: [PATCH 123/779] Use `MemoryExtensions.IndexOfAny` in `WildcardPattern` (#18242) --- src/System.Management.Automation/engine/regex.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/System.Management.Automation/engine/regex.cs b/src/System.Management.Automation/engine/regex.cs index dbdbcb41354..a1e7f9ede94 100644 --- a/src/System.Management.Automation/engine/regex.cs +++ b/src/System.Management.Automation/engine/regex.cs @@ -57,12 +57,12 @@ public sealed class WildcardPattern // The size is less than MaxShortPath = 260. private const int StackAllocThreshold = 256; + // chars that are considered special in a wildcard pattern + private const string SpecialChars = "*?[]`"; + // we convert a wildcard pattern to a predicate private Predicate _isMatch; - // chars that are considered special in a wildcard pattern - private static readonly char[] s_specialChars = new[] { '*', '?', '[', ']', '`' }; - // static match-all delegate that is shared by all WildcardPattern instances private static readonly Predicate s_matchAll = _ => true; @@ -173,8 +173,8 @@ StringComparison GetStringComparison() return; } - int index = Pattern.IndexOfAny(s_specialChars); - if (index == -1) + int index = Pattern.AsSpan().IndexOfAny(SpecialChars); + if (index < 0) { // No special characters present in the pattern, so we can just do a string comparison. _isMatch = str => string.Equals(str, Pattern, GetStringComparison()); From 65d3786ceb6548d750d51a1d4ee55812fefef91c Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Wed, 19 Oct 2022 10:17:54 -0700 Subject: [PATCH 124/779] Bump to .NET 7 RC2 official version (#18328) --- assets/wix/files.wxs | 18 +++++++++++++++--- global.json | 2 +- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/assets/wix/files.wxs b/assets/wix/files.wxs index d4427021a56..8da3a423d0a 100644 --- a/assets/wix/files.wxs +++ b/assets/wix/files.wxs @@ -1221,6 +1221,15 @@ + + + + + + + + + @@ -2766,8 +2775,8 @@ - - + + @@ -3653,7 +3662,10 @@ - + + + + diff --git a/global.json b/global.json index 0ad5fa427db..76bca39fb4f 100644 --- a/global.json +++ b/global.json @@ -1,5 +1,5 @@ { "sdk": { - "version": "7.0.100-rc.2.22477.20" + "version": "7.0.100-rc.2.22477.23" } } From 3e15fc512829b2722315ca8dfedac409e601548f Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Wed, 19 Oct 2022 12:22:42 -0700 Subject: [PATCH 125/779] Update to the latest NOTICES file (#18327) Co-authored-by: adityapatwardhan --- ThirdPartyNotices.txt | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/ThirdPartyNotices.txt b/ThirdPartyNotices.txt index eb30daa0025..fadb831d31f 100644 --- a/ThirdPartyNotices.txt +++ b/ThirdPartyNotices.txt @@ -3187,6 +3187,48 @@ SOFTWARE. System.Security.Cryptography.Xml 6.0.1 - MIT +(c) Microsoft Corporation +Copyright (c) Andrew Arnott +Copyright 2019 LLVM Project +Copyright 2018 Daniel Lemire +Copyright (c) .NET Foundation +Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson +Copyright (c) 1998 Microsoft. To +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2005-2020 Rich Felker +Copyright (c) Microsoft Corporation +Copyright (c) 2007 James Newton-King +Copyright (c) 2012-2014, Yann Collet +Copyright (c) 1991-2020 Unicode, Inc. +Copyright (c) 2013-2017, Alfred Klomp +Copyright 2012 the V8 project authors +Copyright (c) 2011-2020 Microsoft Corp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors +Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 +Portions (c) International Organization +Copyright (c) 2004-2006 Intel Corporation +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) +Copyright (c) .NET Foundation Contributors +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2019 Microsoft Corporation, Daan Leijen +Copyright (c) 2011 Novell, Inc (http://www.novell.com) +Copyright (c) 1995-2017 Jean-loup Gailly and Mark Adler +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors +Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass. To The MIT License (MIT) From c1e6b41f98baddee63debc800eca3588db820a25 Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Wed, 19 Oct 2022 22:18:09 +0100 Subject: [PATCH 126/779] Use `MemoryExtensions.IndexOfAny` in `PSv2CompletionCompleter`` (#18245) --- .../engine/CommandCompletion/CommandCompletion.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs b/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs index 409cb902f77..7c700317e87 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs @@ -691,8 +691,9 @@ private static List InvokeLegacyTabExpansion(PowerShell powers /// private static class PSv2CompletionCompleter { + private const string CharsRequiringQuotedString = "`&@'#{}()$,;|<> \t"; + private static readonly Regex s_cmdletTabRegex = new Regex(@"^[\w\*\?]+-[\w\*\?]*"); - private static readonly char[] s_charsRequiringQuotedString = "`&@'#{}()$,;|<> \t".ToCharArray(); #region "Handle Command" @@ -939,7 +940,7 @@ internal static List PSv2GenerateMatchSetOfFiles(PowerShellExe private static string AddQuoteIfNecessary(string completionText, string quote, bool completingAtStartOfLine) { - if (completionText.IndexOfAny(s_charsRequiringQuotedString) != -1) + if (completionText.AsSpan().IndexOfAny(CharsRequiringQuotedString) >= 0) { bool needAmpersand = quote.Length == 0 && completingAtStartOfLine; string quoteInUse = quote.Length == 0 ? "'" : quote; From 152887154edafaa389cda34c5bfd1e8b0bd52a21 Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Wed, 19 Oct 2022 22:18:24 +0100 Subject: [PATCH 127/779] Remove some static initializations in `StringManipulationHelper` (#18243) --- .../FormatAndOutput/common/ComplexWriter.cs | 20 +++++++++---------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/src/System.Management.Automation/FormatAndOutput/common/ComplexWriter.cs b/src/System.Management.Automation/FormatAndOutput/common/ComplexWriter.cs index 0ffc713cb92..099bec43dc6 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/ComplexWriter.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/ComplexWriter.cs @@ -327,9 +327,10 @@ internal struct GetWordsResult /// internal sealed class StringManipulationHelper { - private static readonly char s_softHyphen = '\u00AD'; - private static readonly char s_hardHyphen = '\u2011'; - private static readonly char s_nonBreakingSpace = '\u00A0'; + private const char SoftHyphen = '\u00AD'; + private const char HardHyphen = '\u2011'; + private const char NonBreakingSpace = '\u00A0'; + private static readonly Collection s_cultureCollection = new Collection(); static StringManipulationHelper() @@ -377,13 +378,13 @@ private static IEnumerable GetWords(string s) } string delimiter = null; - if (s[i] == ' ' || s[i] == '\t' || s[i] == s_softHyphen) + if (s[i] is ' ' or '\t' or SoftHyphen) { // Soft hyphen = \u00AD - Should break, and add a hyphen if needed. // If not needed for a break, hyphen should be absent. delimiter = new string(s[i], 1); } - else if (s[i] == s_hardHyphen || s[i] == s_nonBreakingSpace) + else if (s[i] is HardHyphen or NonBreakingSpace) { // Non-breaking space = \u00A0 - ideally shouldn't wrap. // Hard hyphen = \u2011 - Should not break. @@ -596,9 +597,9 @@ private static StringCollection GenerateLinesWithWordWrap(DisplayCells displayCe string suffix = null; // Handle soft hyphen - if (word.Delim.Length == 1 && word.Delim[0] == s_softHyphen) + if (word.Delim.Length == 1 && word.Delim[0] is SoftHyphen) { - int wordWidthWithHyphen = displayCells.Length(wordToAdd) + displayCells.Length(s_softHyphen); + int wordWidthWithHyphen = displayCells.Length(wordToAdd) + displayCells.Length(SoftHyphen); // Add hyphen only if necessary if (wordWidthWithHyphen == spacesLeft) @@ -813,7 +814,7 @@ internal static string TruncateAtNewLine(string s) return string.Empty; } - int lineBreak = s.IndexOfAny(s_lineBreakChars); + int lineBreak = s.AsSpan().IndexOfAny('\n', '\r'); if (lineBreak < 0) { @@ -827,8 +828,5 @@ internal static string PadLeft(string val, int count) { return StringUtil.Padding(count) + val; } - - private static readonly char[] s_newLineChar = new char[] { '\n' }; - private static readonly char[] s_lineBreakChars = new char[] { '\n', '\r' }; } } From 6c0dace9ee4cde134522893c316b527a38bd18fa Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Thu, 20 Oct 2022 17:20:46 -0700 Subject: [PATCH 128/779] Update README and metadata from servicing releases (#18332) --- README.md | 54 ++++++++++++++++++++++----------------------- tools/metadata.json | 8 +++---- 2 files changed, 31 insertions(+), 31 deletions(-) diff --git a/README.md b/README.md index 6b53bd1f781..78205f85cc1 100644 --- a/README.md +++ b/README.md @@ -64,33 +64,33 @@ You can also download the PowerShell binary archives for Windows, macOS and Linu | Windows (Arm) | [64-bit][rl-winarm64] (preview) | [64-bit][pv-winarm64] | [Instructions][in-arm] | | Raspbian (Arm) | [32-bit][rl-arm32]/[64-bit][rl-arm64] | [32-bit][pv-arm32]/[64-bit][pv-arm64] | [Instructions][in-raspbian] | -[lts-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.6/PowerShell-7.2.6-win-x86.msi -[lts-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.6/PowerShell-7.2.6-win-x64.msi -[lts-deb]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.6/powershell-lts_7.2.6-1.deb_amd64.deb -[lts-rh]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.6/powershell-lts-7.2.6-1.rh.x86_64.rpm -[lts-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.6/powershell-lts-7.2.6-osx-x64.pkg -[lts-macos-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.6/powershell-lts-7.2.6-osx-arm64.pkg - -[rl-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.6/PowerShell-7.2.6-win-x64.msi -[rl-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.6/PowerShell-7.2.6-win-x86.msi -[rl-ubuntu20]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.6/powershell_7.2.6-1.deb_amd64.deb -[rl-ubuntu18]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.6/powershell_7.2.6-1.deb_amd64.deb -[rl-ubuntu16]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.6/powershell_7.2.6-1.deb_amd64.deb -[rl-debian9]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.6/powershell_7.2.6-1.deb_amd64.deb -[rl-debian10]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.6/powershell_7.2.6-1.deb_amd64.deb -[rl-debian11]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.6/powershell_7.2.6-1.deb_amd64.deb -[rl-centos]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.6/powershell-7.2.6-1.rh.x86_64.rpm -[rl-centos8]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.6/powershell-7.2.6-1.rh.x86_64.rpm -[rl-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.6/powershell-7.2.6-osx-x64.pkg -[rl-macos-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.6/powershell-7.2.6-osx-arm64.pkg -[rl-winarm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.6/PowerShell-7.2.6-win-arm64.zip -[rl-winx86-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.6/PowerShell-7.2.6-win-x86.zip -[rl-winx64-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.6/PowerShell-7.2.6-win-x64.zip -[rl-macos-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.6/powershell-7.2.6-osx-x64.tar.gz -[rl-macos-tar-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.6/powershell-7.2.6-osx-arm64.tar.gz -[rl-linux-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.6/powershell-7.2.6-linux-x64.tar.gz -[rl-arm32]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.6/powershell-7.2.6-linux-arm32.tar.gz -[rl-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.6/powershell-7.2.6-linux-arm64.tar.gz +[lts-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.7/PowerShell-7.2.7-win-x86.msi +[lts-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.7/PowerShell-7.2.7-win-x64.msi +[lts-deb]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.7/powershell-lts_7.2.7-1.deb_amd64.deb +[lts-rh]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.7/powershell-lts-7.2.7-1.rh.x86_64.rpm +[lts-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.7/powershell-lts-7.2.7-osx-x64.pkg +[lts-macos-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.7/powershell-lts-7.2.7-osx-arm64.pkg + +[rl-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.7/PowerShell-7.2.7-win-x64.msi +[rl-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.7/PowerShell-7.2.7-win-x86.msi +[rl-ubuntu20]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.7/powershell_7.2.7-1.deb_amd64.deb +[rl-ubuntu18]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.7/powershell_7.2.7-1.deb_amd64.deb +[rl-ubuntu16]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.7/powershell_7.2.7-1.deb_amd64.deb +[rl-debian9]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.7/powershell_7.2.7-1.deb_amd64.deb +[rl-debian10]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.7/powershell_7.2.7-1.deb_amd64.deb +[rl-debian11]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.7/powershell_7.2.7-1.deb_amd64.deb +[rl-centos]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.7/powershell-7.2.7-1.rh.x86_64.rpm +[rl-centos8]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.7/powershell-7.2.7-1.rh.x86_64.rpm +[rl-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.7/powershell-7.2.7-osx-x64.pkg +[rl-macos-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.7/powershell-7.2.7-osx-arm64.pkg +[rl-winarm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.7/PowerShell-7.2.7-win-arm64.zip +[rl-winx86-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.7/PowerShell-7.2.7-win-x86.zip +[rl-winx64-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.7/PowerShell-7.2.7-win-x64.zip +[rl-macos-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.7/powershell-7.2.7-osx-x64.tar.gz +[rl-macos-tar-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.7/powershell-7.2.7-osx-arm64.tar.gz +[rl-linux-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.7/powershell-7.2.7-linux-x64.tar.gz +[rl-arm32]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.7/powershell-7.2.7-linux-arm32.tar.gz +[rl-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.7/powershell-7.2.7-linux-arm64.tar.gz [rl-snap]: https://snapcraft.io/powershell [pv-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.8/PowerShell-7.3.0-preview.8-win-x64.msi diff --git a/tools/metadata.json b/tools/metadata.json index 30b54c8433a..4891e611488 100644 --- a/tools/metadata.json +++ b/tools/metadata.json @@ -1,9 +1,9 @@ { - "StableReleaseTag": "v7.2.6", + "StableReleaseTag": "v7.2.7", "PreviewReleaseTag": "v7.3.0-preview.8", - "ServicingReleaseTag": "v7.0.12", - "ReleaseTag": "v7.2.6", - "LTSReleaseTag" : ["v7.2.6", "v7.0.12"], + "ServicingReleaseTag": "v7.0.13", + "ReleaseTag": "v7.2.7", + "LTSReleaseTag" : ["v7.2.7", "v7.0.13"], "NextReleaseTag": "v7.3.0-preview.9", "LTSRelease": { "Latest": false, "Package": false }, "StableRelease": { "Latest": false, "Package": false } From 1d129c9a7d8e82c9e742c5d0e5deeba1d5fb95f5 Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Thu, 20 Oct 2022 17:21:20 -0700 Subject: [PATCH 129/779] Update change logs for `v7.2.7` and `v7.0.13` (#18342) --- .spelling | 6 +++++- CHANGELOG/7.0.md | 31 +++++++++++++++++++++++++++++++ CHANGELOG/7.2.md | 42 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 78 insertions(+), 1 deletion(-) diff --git a/.spelling b/.spelling index 35c76464e8d..3395cf42ad7 100644 --- a/.spelling +++ b/.spelling @@ -114,8 +114,9 @@ cdxml celsius CentOS codeql-action -cgmanifest CGManifest +cgmanifest.json +cgmanifest changelog changelog.md changelogs @@ -325,6 +326,7 @@ functionprovider FunctionTable fxdependent gabrielsroka +GAC_Arm64 gamified gc.regions.xml Generic.SortedList @@ -614,6 +616,7 @@ new-wsmaninstance new-wsmansessionoption NextTurn ngharo +Newtonsoft.Json NJsonSchema NoMoreFood non-22 @@ -1052,6 +1055,7 @@ v7.1.6 v7.1.7 v7.2.2 v7.3.0 +v7.0.13 validatenotnullorempty ValidateSet varunsh-coder diff --git a/CHANGELOG/7.0.md b/CHANGELOG/7.0.md index 3d446b6cf8e..e054b34cfc9 100644 --- a/CHANGELOG/7.0.md +++ b/CHANGELOG/7.0.md @@ -1,5 +1,36 @@ # 7.0 Changelog +## [7.0.13] - 2022-10-20 + +### Engine Updates and Fixes + +- Stop sending telemetry about `ApplicationType` (#18265) + +### Build and Packaging Improvements + +
+ + + +

Bump .NET SDK to 3.1.424 (#18272)

+ +
+ +
    +
  • Update Wix file for new assemblies (Internal 22873)
  • +
  • Update the cgmanifest.json for v7.0.13 (#18318)
  • +
  • Update Newtonsoft.Json version for 7.0.13 release (#18259)
  • +
  • Fix build.psm1 to not specify both version and quality for dotnet-install (#18267)
  • +
  • Update list of PowerShell team members in release tools(#18266)
  • +
  • Move cgmanifest generation to daily (#18268)
  • +
  • Disable static analysis CI on 7.0 (#18269)
  • +
+ +
+ +[7.0.13]: https://github.com/PowerShell/PowerShell/compare/v7.0.12...v7.0.13 + + ## [7.0.12] - 2022-08-11 ### General Cmdlet Updates and Fixes diff --git a/CHANGELOG/7.2.md b/CHANGELOG/7.2.md index a5ac6b7f1ed..fd1ee4af54f 100644 --- a/CHANGELOG/7.2.md +++ b/CHANGELOG/7.2.md @@ -1,5 +1,47 @@ # 7.2 Changelog +## [7.2.7] - 2022-10-20 + +### Engine Updates and Fixes + +- On Unix, explicitly terminate the native process during cleanup only if it's not running in background (#18280) +- Stop sending telemetry about `ApplicationType` (#18168) + +### General Cmdlet Updates and Fixes + +- Remove the 1-second minimum delay in `Invoke-WebRequest` for downloading small files, and prevent file-download-error suppression (#18170) +- Enable searching for assemblies in GAC_Arm64 on Windows (#18169) +- Fix error formatting to use color defined in `$PSStyle.Formatting` (#18287) + +### Tests + +- Use Ubuntu 20.04 for SSH remoting test (#18289) + +### Build and Packaging Improvements + +
+ + + +

Bump .NET to version 6.0.402 (#18188)(#18290)

+ +
+ +
    +
  • Update cgmanifest (#18319)
  • +
  • Fix build.psm1 to find the required .NET SDK version when a higher version is installed (#17299) (#18282)
  • +
  • Update MSI exit message (#18173)
  • +
  • Remove XML files for min-size package (#18274)
  • +
  • Update list of PS team members in release tools (#18171)
  • +
  • Make the link to minimal package blob public during release (#18174)
  • +
  • Add XML reference documents to NuPkg files for SDK (#18172)
  • +
  • Update to use version 2.21.0 of Application Insights (#18271)
  • +
+ +
+ +[7.2.7]: https://github.com/PowerShell/PowerShell/compare/v7.2.6...v7.2.7 + ## [7.2.6] - 2022-08-11 ### Engine Updates and Fixes From 53c3690c2a484c61064abdf0dc3ee95e224c69a2 Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Mon, 24 Oct 2022 11:59:32 -0700 Subject: [PATCH 130/779] Replace command-error suggestion with new implementation based on subsystem plugin (#18252) --- experimental-feature-linux.json | 3 +- experimental-feature-windows.json | 3 +- .../host/msh/ConsoleHost.cs | 84 +++++- .../PowerShellCore_format_ps1xml.cs | 10 +- .../FormatAndOutput/common/PSStyle.cs | 22 ++ .../ExperimentalFeature.cs | 4 + .../FeedbackSubsystem/FeedbackHub.cs | 228 ++++++++++++++ .../FeedbackSubsystem/IFeedbackProvider.cs | 285 ++++++++++++++++++ .../engine/Subsystem/ISubsystem.cs | 9 +- .../CommandPrediction.cs | 0 .../ICommandPredictor.cs | 0 .../engine/Subsystem/SubsystemInfo.cs | 2 + .../engine/Subsystem/SubsystemManager.cs | 17 +- .../engine/Utils.cs | 14 + .../engine/hostifaces/HostUtilities.cs | 96 +----- .../resources/SubsystemStrings.resx | 3 + .../resources/SuggestionStrings.resx | 8 +- test/xUnit/csharp/test_Feedback.cs | 120 ++++++++ test/xUnit/csharp/test_Subsystem.cs | 48 ++- 19 files changed, 835 insertions(+), 121 deletions(-) create mode 100644 src/System.Management.Automation/engine/Subsystem/FeedbackSubsystem/FeedbackHub.cs create mode 100644 src/System.Management.Automation/engine/Subsystem/FeedbackSubsystem/IFeedbackProvider.cs rename src/System.Management.Automation/engine/Subsystem/{CommandPrediction => PredictionSubsystem}/CommandPrediction.cs (100%) rename src/System.Management.Automation/engine/Subsystem/{CommandPrediction => PredictionSubsystem}/ICommandPredictor.cs (100%) create mode 100644 test/xUnit/csharp/test_Feedback.cs diff --git a/experimental-feature-linux.json b/experimental-feature-linux.json index 573cfc1084a..08f398171d4 100644 --- a/experimental-feature-linux.json +++ b/experimental-feature-linux.json @@ -3,5 +3,6 @@ "PSCustomTableHeaderLabelDecoration", "PSLoadAssemblyFromNativeCode", "PSNativeCommandErrorActionPreference", - "PSSubsystemPluginModel" + "PSSubsystemPluginModel", + "PSFeedbackProvider" ] diff --git a/experimental-feature-windows.json b/experimental-feature-windows.json index 573cfc1084a..08f398171d4 100644 --- a/experimental-feature-windows.json +++ b/experimental-feature-windows.json @@ -3,5 +3,6 @@ "PSCustomTableHeaderLabelDecoration", "PSLoadAssemblyFromNativeCode", "PSNativeCommandErrorActionPreference", - "PSSubsystemPluginModel" + "PSSubsystemPluginModel", + "PSFeedbackProvider" ] diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs index 812f42cfd5e..ab2698ab7ec 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -#pragma warning disable 1634, 1691 - using System; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -18,6 +16,7 @@ using System.Management.Automation.Remoting; using System.Management.Automation.Remoting.Server; using System.Management.Automation.Runspaces; +using System.Management.Automation.Subsystem.Feedback; using System.Management.Automation.Tracing; using System.Reflection; using System.Runtime; @@ -2489,7 +2488,6 @@ internal void Run(bool inputLoopIsNested) if (inBlockMode) { // use a special prompt that denotes block mode - prompt = ">> "; } else @@ -2502,7 +2500,14 @@ internal void Run(bool inputLoopIsNested) // Evaluate any suggestions if (previousResponseWasEmpty == false) { - EvaluateSuggestions(ui); + if (ExperimentalFeature.IsEnabled(ExperimentalFeature.PSFeedbackProvider)) + { + EvaluateFeedbacks(ui); + } + else + { + EvaluateSuggestions(ui); + } } // Then output the prompt @@ -2805,6 +2810,77 @@ private static bool IsIncompleteParseException(Exception e) return remoteException.ErrorRecord.CategoryInfo.Reason == nameof(IncompleteParseException); } + private void EvaluateFeedbacks(ConsoleHostUserInterface ui) + { + // Output any training suggestions + try + { + List feedbacks = FeedbackHub.GetFeedback(_parent.Runspace); + if (feedbacks is null || feedbacks.Count == 0) + { + return; + } + + // Feedback section starts with a new line. + ui.WriteLine(); + + const string Indentation = " "; + string nameStyle = PSStyle.Instance.Formatting.FeedbackProvider; + string textStyle = PSStyle.Instance.Formatting.FeedbackText; + string ansiReset = PSStyle.Instance.Reset; + + if (!ui.SupportsVirtualTerminal) + { + nameStyle = string.Empty; + textStyle = string.Empty; + ansiReset = string.Empty; + } + + int count = 0; + var output = new StringBuilder(); + + foreach (FeedbackEntry entry in feedbacks) + { + if (count > 0) + { + output.AppendLine(); + } + + output.Append("Suggestion [") + .Append(nameStyle) + .Append(entry.Name) + .Append(ansiReset) + .AppendLine("]:") + .Append(textStyle); + + string[] lines = entry.Text.Split('\n', StringSplitOptions.RemoveEmptyEntries); + foreach (string line in lines) + { + output.Append(Indentation) + .Append(line.AsSpan().TrimEnd()) + .AppendLine(); + } + + output.Append(ansiReset); + ui.Write(output.ToString()); + + count++; + output.Clear(); + } + + // Feedback section ends with a new line. + ui.WriteLine(); + } + catch (Exception e) + { + // Catch-all OK. This is a third-party call-out. + ui.WriteErrorLine(e.Message); + + LocalRunspace localRunspace = (LocalRunspace)_parent.Runspace; + localRunspace.GetExecutionContext.AppendDollarError(e); + } + } + private void EvaluateSuggestions(ConsoleHostUserInterface ui) { // Output any training suggestions diff --git a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs index 9b2f6596bd5..80aef760ac5 100644 --- a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs +++ b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs @@ -2030,12 +2030,15 @@ private static IEnumerable ViewsOf_System_Management_Autom .AddItemScriptBlock(@"""$($_.Strikethrough)$($_.Strikethrough.Replace(""""`e"""",'`e'))$($_.Reset)""", label: "Strikethrough") .AddItemProperty(@"OutputRendering") .AddItemScriptBlock(@"""$($_.Formatting.FormatAccent)$($_.Formatting.FormatAccent.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Formatting.FormatAccent") - .AddItemScriptBlock(@"""$($_.Formatting.TableHeader)$($_.Formatting.TableHeader.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Formatting.TableHeader") .AddItemScriptBlock(@"""$($_.Formatting.ErrorAccent)$($_.Formatting.ErrorAccent.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Formatting.ErrorAccent") .AddItemScriptBlock(@"""$($_.Formatting.Error)$($_.Formatting.Error.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Formatting.Error") .AddItemScriptBlock(@"""$($_.Formatting.Warning)$($_.Formatting.Warning.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Formatting.Warning") .AddItemScriptBlock(@"""$($_.Formatting.Verbose)$($_.Formatting.Verbose.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Formatting.Verbose") .AddItemScriptBlock(@"""$($_.Formatting.Debug)$($_.Formatting.Debug.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Formatting.Debug") + .AddItemScriptBlock(@"""$($_.Formatting.TableHeader)$($_.Formatting.TableHeader.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Formatting.TableHeader") + .AddItemScriptBlock(@"""$($_.Formatting.CustomTableHeaderLabel)$($_.Formatting.CustomTableHeaderLabel.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Formatting.CustomTableHeaderLabel") + .AddItemScriptBlock(@"""$($_.Formatting.FeedbackProvider)$($_.Formatting.FeedbackProvider.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Formatting.FeedbackProvider") + .AddItemScriptBlock(@"""$($_.Formatting.FeedbackText)$($_.Formatting.FeedbackText.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Formatting.FeedbackText") .AddItemScriptBlock(@"""$($_.Progress.Style)$($_.Progress.Style.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Progress.Style") .AddItemScriptBlock(@"""$($_.Progress.MaxWidth)""", label: "Progress.MaxWidth") .AddItemScriptBlock(@"""$($_.Progress.View)""", label: "Progress.View") @@ -2086,12 +2089,15 @@ private static IEnumerable ViewsOf_System_Management_Autom ListControl.Create() .StartEntry() .AddItemScriptBlock(@"""$($_.FormatAccent)$($_.FormatAccent.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "FormatAccent") - .AddItemScriptBlock(@"""$($_.TableHeader)$($_.TableHeader.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "TableHeader") .AddItemScriptBlock(@"""$($_.ErrorAccent)$($_.ErrorAccent.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "ErrorAccent") .AddItemScriptBlock(@"""$($_.Error)$($_.Error.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Error") .AddItemScriptBlock(@"""$($_.Warning)$($_.Warning.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Warning") .AddItemScriptBlock(@"""$($_.Verbose)$($_.Verbose.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Verbose") .AddItemScriptBlock(@"""$($_.Debug)$($_.Debug.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Debug") + .AddItemScriptBlock(@"""$($_.TableHeader)$($_.TableHeader.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "TableHeader") + .AddItemScriptBlock(@"""$($_.CustomTableHeaderLabel)$($_.CustomTableHeaderLabel.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "CustomTableHeaderLabel") + .AddItemScriptBlock(@"""$($_.FeedbackProvider)$($_.FeedbackProvider.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "FeedbackProvider") + .AddItemScriptBlock(@"""$($_.FeedbackText)$($_.FeedbackText.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "FeedbackText") .EndEntry() .EndList()); } diff --git a/src/System.Management.Automation/FormatAndOutput/common/PSStyle.cs b/src/System.Management.Automation/FormatAndOutput/common/PSStyle.cs index b6e7b9370e1..ec3955c29bc 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/PSStyle.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/PSStyle.cs @@ -431,6 +431,28 @@ public string Debug } private string _debug = "\x1b[33;1m"; + + /// + /// Gets or sets the style for rendering feedback provider names. + /// + public string FeedbackProvider + { + get => _feedbackProvider; + set => _feedbackProvider = ValidateNoContent(value); + } + + private string _feedbackProvider = "\x1b[33m"; + + /// + /// Gets or sets the style for rendering feedback text. + /// + public string FeedbackText + { + get => _feedbackText; + set => _feedbackText = ValidateNoContent(value); + } + + private string _feedbackText = "\x1b[96m"; } /// diff --git a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs index d83bd4bc8f3..5fe456f48d5 100644 --- a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs +++ b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs @@ -23,6 +23,7 @@ public class ExperimentalFeature internal const string EngineSource = "PSEngine"; internal const string PSNativeCommandErrorActionPreferenceFeatureName = "PSNativeCommandErrorActionPreference"; internal const string PSCustomTableHeaderLabelDecoration = "PSCustomTableHeaderLabelDecoration"; + internal const string PSFeedbackProvider = "PSFeedbackProvider"; #endregion @@ -120,6 +121,9 @@ static ExperimentalFeature() new ExperimentalFeature( name: PSCustomTableHeaderLabelDecoration, description: "Formatting differentiation for table header labels that aren't property members"), + new ExperimentalFeature( + name: PSFeedbackProvider, + description: "Replace the hard-coded suggestion framework with the extensible feedback provider"), }; EngineExperimentalFeatures = new ReadOnlyCollection(engineFeatures); diff --git a/src/System.Management.Automation/engine/Subsystem/FeedbackSubsystem/FeedbackHub.cs b/src/System.Management.Automation/engine/Subsystem/FeedbackSubsystem/FeedbackHub.cs new file mode 100644 index 00000000000..5755945dcd0 --- /dev/null +++ b/src/System.Management.Automation/engine/Subsystem/FeedbackSubsystem/FeedbackHub.cs @@ -0,0 +1,228 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Management.Automation.Internal; +using System.Management.Automation.Runspaces; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.PowerShell.Commands; + +namespace System.Management.Automation.Subsystem.Feedback +{ + /// + /// The class represents a result from a feedback provider. + /// + public class FeedbackEntry + { + /// + /// Gets the Id of the feedback provider. + /// + public Guid Id { get; } + + /// + /// Gets the name of the feedback provider. + /// + public string Name { get; } + + /// + /// Gets the text of the feedback. + /// + public string Text { get; } + + internal FeedbackEntry(Guid id, string name, string text) + { + Id = id; + Name = name; + Text = text; + } + } + + /// + /// Provides a set of feedbacks for given input. + /// + public static class FeedbackHub + { + /// + /// Collect the feedback from registered feedback providers using the default timeout. + /// + public static List? GetFeedback(Runspace runspace) + { + return GetFeedback(runspace, millisecondsTimeout: 300); + } + + /// + /// Collect the feedback from registered feedback providers using the specified timeout. + /// + public static List? GetFeedback(Runspace runspace, int millisecondsTimeout) + { + Requires.Condition(millisecondsTimeout > 0, nameof(millisecondsTimeout)); + + var localRunspace = runspace as LocalRunspace; + if (localRunspace is null) + { + return null; + } + + // Get the last value of $? + bool questionMarkValue = localRunspace.ExecutionContext.QuestionMarkVariableValue; + if (questionMarkValue) + { + return null; + } + + // Get the last history item + HistoryInfo[] histories = localRunspace.History.GetEntries(id: 0, count: 1, newest: true); + if (histories.Length == 0) + { + return null; + } + + HistoryInfo lastHistory = histories[0]; + + // Get the last error + ArrayList errorList = (ArrayList)localRunspace.ExecutionContext.DollarErrorVariable; + if (errorList.Count == 0) + { + return null; + } + + var lastError = errorList[0] as ErrorRecord; + if (lastError is null && errorList[0] is RuntimeException rtEx) + { + lastError = rtEx.ErrorRecord; + } + + if (lastError?.InvocationInfo is null || lastError.InvocationInfo.HistoryId != lastHistory.Id) + { + return null; + } + + var providers = SubsystemManager.GetSubsystems(); + int count = providers.Count; + if (count == 0) + { + return null; + } + + IFeedbackProvider? generalFeedback = null; + List>? tasks = null; + CancellationTokenSource? cancellationSource = null; + Func? callBack = null; + + for (int i = 0; i < providers.Count; i++) + { + IFeedbackProvider provider = providers[i]; + if (provider is GeneralCommandErrorFeedback) + { + // This built-in feedback provider needs to run on the target Runspace. + generalFeedback = provider; + continue; + } + + if (tasks is null) + { + tasks = new List>(capacity: count); + cancellationSource = new CancellationTokenSource(); + callBack = GetCallBack(lastHistory.CommandLine, lastError, cancellationSource); + } + + // Other feedback providers will run on background threads in parallel. + tasks.Add(Task.Factory.StartNew( + callBack!, + provider, + cancellationSource!.Token, + TaskCreationOptions.DenyChildAttach, + TaskScheduler.Default)); + } + + Task? waitTask = null; + if (tasks is not null) + { + waitTask = Task.WhenAny( + Task.WhenAll(tasks), + Task.Delay(millisecondsTimeout, cancellationSource!.Token)); + } + + List? resultList = null; + if (generalFeedback is not null) + { + bool changedDefault = false; + Runspace? oldDefault = Runspace.DefaultRunspace; + + try + { + if (oldDefault != localRunspace) + { + changedDefault = true; + Runspace.DefaultRunspace = localRunspace; + } + + string? text = generalFeedback.GetFeedback(lastHistory.CommandLine, lastError, CancellationToken.None); + if (text is not null) + { + resultList ??= new List(count); + resultList.Add(new FeedbackEntry(generalFeedback.Id, generalFeedback.Name, text)); + } + } + finally + { + if (changedDefault) + { + Runspace.DefaultRunspace = oldDefault; + } + + // Restore $? for the target Runspace. + localRunspace.ExecutionContext.QuestionMarkVariableValue = questionMarkValue; + } + } + + if (waitTask is not null) + { + try + { + waitTask.Wait(); + cancellationSource!.Cancel(); + + foreach (Task task in tasks!) + { + if (task.IsCompletedSuccessfully) + { + FeedbackEntry? result = task.Result; + if (result is not null) + { + resultList ??= new List(count); + resultList.Add(result); + } + } + } + } + finally + { + cancellationSource!.Dispose(); + } + } + + return resultList; + } + + // A local helper function to avoid creating an instance of the generated delegate helper class + // when no feedback provider is registered. + private static Func GetCallBack( + string commandLine, + ErrorRecord lastError, + CancellationTokenSource cancellationSource) + { + return state => + { + var provider = (IFeedbackProvider)state!; + var text = provider.GetFeedback(commandLine, lastError, cancellationSource.Token); + return text is null ? null : new FeedbackEntry(provider.Id, provider.Name, text); + }; + } + } +} diff --git a/src/System.Management.Automation/engine/Subsystem/FeedbackSubsystem/IFeedbackProvider.cs b/src/System.Management.Automation/engine/Subsystem/FeedbackSubsystem/IFeedbackProvider.cs new file mode 100644 index 00000000000..a254cd9b013 --- /dev/null +++ b/src/System.Management.Automation/engine/Subsystem/FeedbackSubsystem/IFeedbackProvider.cs @@ -0,0 +1,285 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Management.Automation.Internal; +using System.Management.Automation.Runspaces; +using System.Management.Automation.Subsystem.Prediction; +using System.Threading; + +namespace System.Management.Automation.Subsystem.Feedback +{ + /// + /// Interface for implementing a feedback provider on command failures. + /// + public interface IFeedbackProvider : ISubsystem + { + /// + /// Default implementation. No function is required for a feedback provider. + /// + Dictionary? ISubsystem.FunctionsToDefine => null; + + /// + /// Default implementation for `ISubsystem.Kind`. + /// + SubsystemKind ISubsystem.Kind => SubsystemKind.FeedbackProvider; + + /// + /// Gets feedback based on the given commandline and error record. + /// + /// + string? GetFeedback(string commandLine, ErrorRecord lastError, CancellationToken token); + } + + internal sealed class GeneralCommandErrorFeedback : IFeedbackProvider + { + private readonly Guid _guid; + private readonly object[] _args; + private ScriptBlock? _fuzzySb; + + internal GeneralCommandErrorFeedback() + { + _guid = new Guid("A3C6B07E-4A89-40C9-8BE6-2A9AAD2786A4"); + _args = new object[1]; + } + + public Guid Id => _guid; + + public string Name => "General"; + + public string Description => "The built-in general feedback source for command errors."; + + public string? GetFeedback(string commandLine, ErrorRecord lastError, CancellationToken token) + { + var rsToUse = Runspace.DefaultRunspace; + if (rsToUse is null) + { + return null; + } + + if (lastError.FullyQualifiedErrorId == "CommandNotFoundException") + { + EngineIntrinsics context = rsToUse.ExecutionContext.EngineIntrinsics; + + var target = (string)lastError.TargetObject; + CommandInvocationIntrinsics invocation = context.SessionState.InvokeCommand; + + // See if target is actually an executable file in current directory. + var localTarget = Path.Combine(".", target); + var command = invocation.GetCommand( + localTarget, + CommandTypes.Application | CommandTypes.ExternalScript); + + if (command is not null) + { + return StringUtil.Format( + SuggestionStrings.Suggestion_CommandExistsInCurrentDirectory, + target, + localTarget); + } + + // Check fuzzy matching command names. + if (ExperimentalFeature.IsEnabled("PSCommandNotFoundSuggestion")) + { + _fuzzySb ??= ScriptBlock.CreateDelayParsedScriptBlock(@$" + param([string] $target) + $cmdNames = Get-Command $target -UseFuzzyMatching -FuzzyMinimumDistance 1 | Select-Object -First 5 -Unique -ExpandProperty Name + if ($cmdNames) {{ + [string]::Join(', ', $cmdNames) + }} + ", isProductCode: true); + + _args[0] = target; + var result = _fuzzySb.InvokeReturnAsIs(_args); + + if (result is not null && result != AutomationNull.Value) + { + return StringUtil.Format( + SuggestionStrings.Suggestion_CommandNotFound, + result.ToString()); + } + } + } + + return null; + } + } + + internal sealed class UnixCommandNotFound : IFeedbackProvider, ICommandPredictor + { + private readonly Guid _guid; + private string? _notFoundFeedback; + private List? _candidates; + + internal UnixCommandNotFound() + { + _guid = new Guid("47013747-CB9D-4EBC-9F02-F32B8AB19D48"); + } + + Dictionary? ISubsystem.FunctionsToDefine => null; + + SubsystemKind ISubsystem.Kind => SubsystemKind.FeedbackProvider | SubsystemKind.CommandPredictor; + + public Guid Id => _guid; + + public string Name => "cmd-not-found"; + + public string Description => "The built-in feedback/prediction source for the Unix command utility."; + + #region IFeedbackProvider + + private static string? GetUtilityPath() + { + string cmd_not_found = "/usr/lib/command-not-found"; + bool exist = IsFileExecutable(cmd_not_found); + + if (!exist) + { + cmd_not_found = "/usr/share/command-not-found/command-not-found"; + exist = IsFileExecutable(cmd_not_found); + } + + return exist ? cmd_not_found : null; + + static bool IsFileExecutable(string path) + { + var file = new FileInfo(path); + return file.Exists && file.UnixFileMode.HasFlag(UnixFileMode.OtherExecute); + } + } + + /// + /// Gets feedback based on the given commandline and error record. + /// + public string? GetFeedback(string commandLine, ErrorRecord lastError, CancellationToken token) + { + if (Platform.IsWindows || lastError.FullyQualifiedErrorId != "CommandNotFoundException") + { + return null; + } + + var target = (string)lastError.TargetObject; + if (target is null) + { + return null; + } + + if (target.EndsWith(".ps1", StringComparison.OrdinalIgnoreCase)) + { + return null; + } + + string? cmd_not_found = GetUtilityPath(); + if (cmd_not_found is not null) + { + var startInfo = new ProcessStartInfo(cmd_not_found); + startInfo.ArgumentList.Add(target); + startInfo.RedirectStandardError = true; + startInfo.RedirectStandardOutput = true; + + using var process = Process.Start(startInfo); + var stderr = process?.StandardError.ReadToEnd().Trim(); + + // The feedback contains recommended actions only if the output has multiple lines of text. + if (stderr?.IndexOf('\n') > 0) + { + _notFoundFeedback = stderr; + + var stdout = process?.StandardOutput.ReadToEnd().Trim(); + return string.IsNullOrEmpty(stdout) ? stderr : $"{stderr}\n{stdout}"; + } + } + + return null; + } + + #endregion + + #region ICommandPredictor + + public bool CanAcceptFeedback(PredictionClient client, PredictorFeedbackKind feedback) + { + return feedback switch + { + PredictorFeedbackKind.CommandLineAccepted => true, + _ => false, + }; + } + + public SuggestionPackage GetSuggestion(PredictionClient client, PredictionContext context, CancellationToken cancellationToken) + { + if (_candidates is null && _notFoundFeedback is not null) + { + var text = _notFoundFeedback.AsSpan(); + // Set to null to avoid potential race condition. + _notFoundFeedback = null; + + // This loop searches for candidate results with almost no allocation. + while (true) + { + // The line is a candidate if it starts with "sudo ", such as "sudo apt install python3". + // 'sudo' is a command name that remains the same, so this check should work for all locales. + bool isCandidate = text.StartsWith("sudo ", StringComparison.Ordinal); + int index = text.IndexOf('\n'); + if (isCandidate) + { + var line = index != -1 ? text.Slice(0, index) : text; + _candidates ??= new List(); + _candidates.Add(new string(line.TrimEnd())); + } + + // Break out the loop if we are done with the last line. + if (index == -1 || index == text.Length - 1) + { + break; + } + + // Point to the rest of feedback text. + text = text.Slice(index + 1); + } + } + + if (_candidates is not null) + { + string input = context.InputAst.Extent.Text; + List? result = null; + + foreach (string c in _candidates) + { + if (c.StartsWith(input, StringComparison.OrdinalIgnoreCase)) + { + result ??= new List(_candidates.Count); + result.Add(new PredictiveSuggestion(c)); + } + } + + if (result is not null) + { + return new SuggestionPackage(result); + } + } + + return default; + } + + public void OnCommandLineAccepted(PredictionClient client, IReadOnlyList history) + { + // Reset the candidate state. + _notFoundFeedback = null; + _candidates = null; + } + + public void OnSuggestionDisplayed(PredictionClient client, uint session, int countOrIndex) { } + + public void OnSuggestionAccepted(PredictionClient client, uint session, string acceptedSuggestion) { } + + public void OnCommandLineExecuted(PredictionClient client, string commandLine, bool success) { } + + #endregion; + } +} diff --git a/src/System.Management.Automation/engine/Subsystem/ISubsystem.cs b/src/System.Management.Automation/engine/Subsystem/ISubsystem.cs index db842f435bb..e8937486d41 100644 --- a/src/System.Management.Automation/engine/Subsystem/ISubsystem.cs +++ b/src/System.Management.Automation/engine/Subsystem/ISubsystem.cs @@ -10,8 +10,10 @@ namespace System.Management.Automation.Subsystem { /// /// Define the kinds of subsystems. + /// Allow composite enum values to enable one subsystem implementation to serve as multiple subystems. /// - public enum SubsystemKind + [Flags] + public enum SubsystemKind : uint { /// /// Component that provides predictive suggestions to commandline input. @@ -22,6 +24,11 @@ public enum SubsystemKind /// Cross platform desired state configuration component. /// CrossPlatformDsc = 2, + + /// + /// Component that provides feedback when a command fails interactively. + /// + FeedbackProvider = 4, } /// diff --git a/src/System.Management.Automation/engine/Subsystem/CommandPrediction/CommandPrediction.cs b/src/System.Management.Automation/engine/Subsystem/PredictionSubsystem/CommandPrediction.cs similarity index 100% rename from src/System.Management.Automation/engine/Subsystem/CommandPrediction/CommandPrediction.cs rename to src/System.Management.Automation/engine/Subsystem/PredictionSubsystem/CommandPrediction.cs diff --git a/src/System.Management.Automation/engine/Subsystem/CommandPrediction/ICommandPredictor.cs b/src/System.Management.Automation/engine/Subsystem/PredictionSubsystem/ICommandPredictor.cs similarity index 100% rename from src/System.Management.Automation/engine/Subsystem/CommandPrediction/ICommandPredictor.cs rename to src/System.Management.Automation/engine/Subsystem/PredictionSubsystem/ICommandPredictor.cs diff --git a/src/System.Management.Automation/engine/Subsystem/SubsystemInfo.cs b/src/System.Management.Automation/engine/Subsystem/SubsystemInfo.cs index ae555e8d187..e8d8fe39eae 100644 --- a/src/System.Management.Automation/engine/Subsystem/SubsystemInfo.cs +++ b/src/System.Management.Automation/engine/Subsystem/SubsystemInfo.cs @@ -78,6 +78,8 @@ public abstract class SubsystemInfo private protected SubsystemInfo(SubsystemKind kind, Type subsystemType) { + Requires.OneSpecificSubsystemKind(kind); + _syncObj = new object(); _cachedImplInfos = Utils.EmptyReadOnlyCollection(); diff --git a/src/System.Management.Automation/engine/Subsystem/SubsystemManager.cs b/src/System.Management.Automation/engine/Subsystem/SubsystemManager.cs index d603436790c..501bebcaddc 100644 --- a/src/System.Management.Automation/engine/Subsystem/SubsystemManager.cs +++ b/src/System.Management.Automation/engine/Subsystem/SubsystemManager.cs @@ -6,9 +6,9 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; -using System.Linq; using System.Management.Automation.Internal; using System.Management.Automation.Subsystem.DSC; +using System.Management.Automation.Subsystem.Feedback; using System.Management.Automation.Subsystem.Prediction; namespace System.Management.Automation.Subsystem @@ -35,6 +35,11 @@ static SubsystemManager() SubsystemKind.CrossPlatformDsc, allowUnregistration: true, allowMultipleRegistration: false), + + SubsystemInfo.Create( + SubsystemKind.FeedbackProvider, + allowUnregistration: true, + allowMultipleRegistration: true), }; var subSystemTypeMap = new Dictionary(subsystems.Length); @@ -49,6 +54,9 @@ static SubsystemManager() s_subsystems = new ReadOnlyCollection(subsystems); s_subSystemTypeMap = new ReadOnlyDictionary(subSystemTypeMap); s_subSystemKindMap = new ReadOnlyDictionary(subSystemKindMap); + + // Register built-in suggestion providers. + RegisterSubsystem(SubsystemKind.FeedbackProvider, new GeneralCommandErrorFeedback()); } #region internal - Retrieve subsystem proxy object @@ -143,6 +151,8 @@ public static SubsystemInfo GetSubsystemInfo(Type subsystemType) /// The object that represents the concrete subsystem. public static SubsystemInfo GetSubsystemInfo(SubsystemKind kind) { + Requires.OneSpecificSubsystemKind(kind); + if (s_subSystemKindMap.TryGetValue(kind, out SubsystemInfo? subsystemInfo)) { return subsystemInfo; @@ -181,8 +191,9 @@ public static void RegisterSubsystem(TImple public static void RegisterSubsystem(SubsystemKind kind, ISubsystem proxy) { Requires.NotNull(proxy, nameof(proxy)); + Requires.OneSpecificSubsystemKind(kind); - if (kind != proxy.Kind) + if (!proxy.Kind.HasFlag(kind)) { throw new ArgumentException( StringUtil.Format( @@ -267,6 +278,8 @@ public static void UnregisterSubsystem(Guid id) /// The Id of the implementation to be unregistered. public static void UnregisterSubsystem(SubsystemKind kind, Guid id) { + Requires.OneSpecificSubsystemKind(kind); + UnregisterSubsystem(GetSubsystemInfo(kind), id); } diff --git a/src/System.Management.Automation/engine/Utils.cs b/src/System.Management.Automation/engine/Utils.cs index a3b6b83dc9a..57463a6f330 100644 --- a/src/System.Management.Automation/engine/Utils.cs +++ b/src/System.Management.Automation/engine/Utils.cs @@ -1788,5 +1788,19 @@ internal static void Condition([DoesNotReturnIf(false)] bool precondition, strin throw new ArgumentException(paramName); } } + + internal static void OneSpecificSubsystemKind(Subsystem.SubsystemKind kind) + { + uint value = (uint)kind; + if (value == 0 || (value & (value - 1)) != 0) + { + // The value is either invalid or a composite value because it's not power of 2. + throw new ArgumentException( + StringUtil.Format( + SubsystemStrings.RequireOneSpecificSubsystemKind, + kind.ToString()), + nameof(kind)); + } + } } } diff --git a/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs b/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs index b3e29423a83..c543ad11f13 100644 --- a/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs +++ b/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs @@ -69,7 +69,7 @@ public static class HostUtilities [System.Diagnostics.DebuggerHidden()] param([string] $formatString) - $formatString -f [string]::Join(', ', (Get-Command $lastError.TargetObject -UseFuzzyMatch | Select-Object -First 10 -Unique -ExpandProperty Name)) + $formatString -f [string]::Join(', ', (Get-Command $lastError.TargetObject -UseFuzzyMatching -FuzzyMinimumDistance 1 | Select-Object -First 5 -Unique -ExpandProperty Name)) "; private static readonly List s_suggestions = InitializeSuggestions(); @@ -79,20 +79,6 @@ private static List InitializeSuggestions() var suggestions = new List( new Hashtable[] { - NewSuggestion( - id: 1, - category: "Transactions", - matchType: SuggestionMatchType.Command, - rule: "^Start-Transaction", - suggestion: SuggestionStrings.Suggestion_StartTransaction, - enabled: true), - NewSuggestion( - id: 2, - category: "Transactions", - matchType: SuggestionMatchType.Command, - rule: "^Use-Transaction", - suggestion: SuggestionStrings.Suggestion_UseTransaction, - enabled: true), NewSuggestion( id: 3, category: "General", @@ -138,16 +124,6 @@ internal static PSObject GetDollarProfile(string allUsersAllHosts, string allUse return returnValue; } - /// - /// Gets an array of commands that can be run sequentially to set $profile and run the profile commands. - /// - /// The id identifying the host or shell used in profile file names. - /// - internal static PSCommand[] GetProfileCommands(string shellId) - { - return HostUtilities.GetProfileCommands(shellId, false); - } - /// /// Gets the object that serves as a value to $profile and the paths on it. /// @@ -561,30 +537,6 @@ internal static string RemoveIdentifierInfoFromMessage(string message, out bool return message; } - /// - /// Create suggestion with string rule and suggestion. - /// - /// Identifier for the suggestion. - /// Category for the suggestion. - /// Suggestion match type. - /// Rule to match. - /// Suggestion to return. - /// True if the suggestion is enabled. - /// Hashtable representing the suggestion. - private static Hashtable NewSuggestion(int id, string category, SuggestionMatchType matchType, string rule, string suggestion, bool enabled) - { - Hashtable result = new Hashtable(StringComparer.CurrentCultureIgnoreCase); - - result["Id"] = id; - result["Category"] = category; - result["MatchType"] = matchType; - result["Rule"] = rule; - result["Suggestion"] = suggestion; - result["Enabled"] = enabled; - - return result; - } - /// /// Create suggestion with string rule and scriptblock suggestion. /// @@ -639,15 +591,6 @@ private static Hashtable NewSuggestion(int id, string category, SuggestionMatchT return result; } - /// - /// Get suggestion text from suggestion scriptblock. - /// - [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Need to keep this for legacy reflection based use")] - private static string GetSuggestionText(object suggestion, PSModuleInfo invocationModule) - { - return GetSuggestionText(suggestion, null, invocationModule); - } - /// /// Get suggestion text from suggestion scriptblock with arguments. /// @@ -702,43 +645,6 @@ runspace.ConnectionInfo is VMConnectionInfo || return string.Format(CultureInfo.InvariantCulture, "[{0}]: {1}", runspace.ConnectionInfo.ComputerName, basePrompt); } - internal static bool IsProcessInteractive(InvocationInfo invocationInfo) - { -#if CORECLR - return false; -#else - // CommandOrigin != Runspace means it is in a script - if (invocationInfo.CommandOrigin != CommandOrigin.Runspace) - return false; - - // If we don't own the window handle, we've been invoked - // from another process that just calls "PowerShell -Command" - if (System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle == IntPtr.Zero) - return false; - - // If the window has been idle for less than two seconds, - // they're probably still calling "PowerShell -Command" - // but from Start-Process, or the StartProcess API - try - { - System.Diagnostics.Process currentProcess = System.Diagnostics.Process.GetCurrentProcess(); - TimeSpan timeSinceStart = DateTime.Now - currentProcess.StartTime; - TimeSpan idleTime = timeSinceStart - currentProcess.TotalProcessorTime; - - // Making it 2 seconds because of things like delayed prompt - if (idleTime.TotalSeconds > 2) - return true; - } - catch (System.ComponentModel.Win32Exception) - { - // Don't have access to the properties - return false; - } - - return false; -#endif - } - /// /// Create a configured remote runspace from provided name. /// diff --git a/src/System.Management.Automation/resources/SubsystemStrings.resx b/src/System.Management.Automation/resources/SubsystemStrings.resx index a2819da8682..1ca0453ae31 100644 --- a/src/System.Management.Automation/resources/SubsystemStrings.resx +++ b/src/System.Management.Automation/resources/SubsystemStrings.resx @@ -153,4 +153,7 @@ The 'Description' property of an implementation for the subsystem '{0}' cannot be null or an empty string. + + The subsystem kind here should represent one specific subsystem, but the given value is either invalid or a composite enum value: '{0}'. + diff --git a/src/System.Management.Automation/resources/SuggestionStrings.resx b/src/System.Management.Automation/resources/SuggestionStrings.resx index cd44c33e759..14e9c01b275 100644 --- a/src/System.Management.Automation/resources/SuggestionStrings.resx +++ b/src/System.Management.Automation/resources/SuggestionStrings.resx @@ -117,14 +117,8 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - Once a transaction is started, only commands that get called with the -UseTransaction flag become part of that transaction. - - - The Use-Transaction cmdlet is intended for scripting of transaction-enabled .NET objects. Its ScriptBlock should contain nothing else. - - The command {0} was not found, but does exist in the current location. PowerShell does not load commands from the current location by default. If you trust this command, instead type: "{1}". See "get-help about_Command_Precedence" for more details. + The command "{0}" was not found, but does exist in the current location. PowerShell does not load commands from the current location by default. If you trust this command, instead type: "{1}". See "get-help about_Command_Precedence" for more details. The most similar commands are: {0}. diff --git a/test/xUnit/csharp/test_Feedback.cs b/test/xUnit/csharp/test_Feedback.cs new file mode 100644 index 00000000000..d57d21fa0ec --- /dev/null +++ b/test/xUnit/csharp/test_Feedback.cs @@ -0,0 +1,120 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.IO; +using System.Management.Automation; +using System.Management.Automation.Subsystem; +using System.Management.Automation.Subsystem.Feedback; +using System.Threading; +using Xunit; + +namespace PSTests.Sequential +{ + public class MyFeedback : IFeedbackProvider + { + private readonly Guid _id; + private readonly string _name, _description; + private readonly bool _delay; + + public static readonly MyFeedback SlowFeedback; + + static MyFeedback() + { + SlowFeedback = new MyFeedback( + Guid.NewGuid(), + "Slow", + "Description for #1 feedback provider.", + delay: true); + } + + private MyFeedback(Guid id, string name, string description, bool delay) + { + _id = id; + _name = name; + _description = description; + _delay = delay; + } + + public Guid Id => _id; + + public string Name => _name; + + public string Description => _description; + + public string GetFeedback(string commandLine, ErrorRecord errorRecord, CancellationToken token) + { + if (_delay) + { + // The delay is exaggerated to make the test reliable. + // xUnit must spin up a lot tasks, which makes the test unreliable when the time difference between 'delay' and 'timeout' is small. + Thread.Sleep(2000); + } + + return $"{commandLine}+{errorRecord.FullyQualifiedErrorId}"; + } + } + + public static class FeedbackProviderTests + { + [Fact] + public static void GetFeedback() + { + var pwsh = PowerShell.Create(); + var settings = new PSInvocationSettings() { AddToHistory = true }; + + // Setup the context for the test. + // Change current working directory to the temp path. + pwsh.AddCommand("Set-Location") + .AddParameter("Path", Path.GetTempPath()) + .Invoke(input: null, settings); + pwsh.Commands.Clear(); + + // Create an empty file 'feedbacktest.ps1' under the temp path; + pwsh.AddCommand("New-Item") + .AddParameter("Path", "feedbacktest.ps1") + .Invoke(input: null, settings); + pwsh.Commands.Clear(); + + // Run a command 'feedbacktest', so as to trigger the 'General' feedback. + pwsh.AddScript("feedbacktest").Invoke(input: null, settings); + pwsh.Commands.Clear(); + + try + { + // Register the slow feedback provider. + // The 'General' feedback provider is built-in and registered by default. + SubsystemManager.RegisterSubsystem(SubsystemKind.FeedbackProvider, MyFeedback.SlowFeedback); + + // Expect the result from 'General' only because the 'slow' one cannot finish before the specified timeout. + // The specified timeout is exaggerated to make the test reliable. + // xUnit must spin up a lot tasks, which makes the test unreliable when the time difference between 'delay' and 'timeout' is small. + var feedbacks = FeedbackHub.GetFeedback(pwsh.Runspace, millisecondsTimeout: 1000); + string expectedCmd = Path.Combine(".", "feedbacktest"); + + // Test the result from the 'General' feedback provider. + Assert.Single(feedbacks); + Assert.Equal("General", feedbacks[0].Name); + Assert.Contains(expectedCmd, feedbacks[0].Text); + + // Expect the result from both 'General' and the 'slow' feedback providers. + // Same here -- the specified timeout is exaggerated to make the test reliable. + // xUnit must spin up a lot tasks, which makes the test unreliable when the time difference between 'delay' and 'timeout' is small. + feedbacks = FeedbackHub.GetFeedback(pwsh.Runspace, millisecondsTimeout: 4000); + Assert.Equal(2, feedbacks.Count); + + FeedbackEntry entry1 = feedbacks[0]; + Assert.Equal("General", entry1.Name); + Assert.Contains(expectedCmd, entry1.Text); + + FeedbackEntry entry2 = feedbacks[1]; + Assert.Equal("Slow", entry2.Name); + Assert.Equal("feedbacktest+CommandNotFoundException", entry2.Text); + } + finally + { + SubsystemManager.UnregisterSubsystem(MyFeedback.SlowFeedback.Id); + } + } + } +} diff --git a/test/xUnit/csharp/test_Subsystem.cs b/test/xUnit/csharp/test_Subsystem.cs index d5bc3b9c728..11ac9d55419 100644 --- a/test/xUnit/csharp/test_Subsystem.cs +++ b/test/xUnit/csharp/test_Subsystem.cs @@ -5,6 +5,7 @@ using System.Collections.ObjectModel; using System.Management.Automation.Subsystem; using System.Management.Automation.Subsystem.DSC; +using System.Management.Automation.Subsystem.Feedback; using System.Management.Automation.Subsystem.Prediction; using System.Threading; using Xunit; @@ -41,37 +42,63 @@ private static void VerifyCrossPlatformDscMetadata(SubsystemInfo ssInfo) Assert.Empty(ssInfo.RequiredFunctions); } + private static void VerifyFeedbackProviderMetadata(SubsystemInfo ssInfo) + { + Assert.Equal(SubsystemKind.FeedbackProvider, ssInfo.Kind); + Assert.Equal(typeof(IFeedbackProvider), ssInfo.SubsystemType); + Assert.True(ssInfo.AllowUnregistration); + Assert.True(ssInfo.AllowMultipleRegistration); + Assert.Empty(ssInfo.RequiredCmdlets); + Assert.Empty(ssInfo.RequiredFunctions); + } + [Fact] public static void GetSubsystemInfo() { + #region Predictor SubsystemInfo predictorInfo = SubsystemManager.GetSubsystemInfo(typeof(ICommandPredictor)); + SubsystemInfo predictorInfo2 = SubsystemManager.GetSubsystemInfo(SubsystemKind.CommandPredictor); + Assert.Same(predictorInfo2, predictorInfo); VerifyCommandPredictorMetadata(predictorInfo); Assert.False(predictorInfo.IsRegistered); Assert.Empty(predictorInfo.Implementations); + #endregion - SubsystemInfo predictorInfo2 = SubsystemManager.GetSubsystemInfo(SubsystemKind.CommandPredictor); - Assert.Same(predictorInfo2, predictorInfo); + #region Feedback + SubsystemInfo feedbackProviderInfo = SubsystemManager.GetSubsystemInfo(typeof(IFeedbackProvider)); + SubsystemInfo feedback2 = SubsystemManager.GetSubsystemInfo(SubsystemKind.FeedbackProvider); + Assert.Same(feedback2, feedbackProviderInfo); - SubsystemInfo crossPlatformDscInfo = SubsystemManager.GetSubsystemInfo(typeof(ICrossPlatformDsc)); + VerifyFeedbackProviderMetadata(feedbackProviderInfo); + Assert.True(feedbackProviderInfo.IsRegistered); + Assert.Single(feedbackProviderInfo.Implementations); + #endregion + #region DSC + SubsystemInfo crossPlatformDscInfo = SubsystemManager.GetSubsystemInfo(typeof(ICrossPlatformDsc)); + SubsystemInfo crossPlatformDscInfo2 = SubsystemManager.GetSubsystemInfo(SubsystemKind.CrossPlatformDsc); + Assert.Same(crossPlatformDscInfo2, crossPlatformDscInfo); VerifyCrossPlatformDscMetadata(crossPlatformDscInfo); + Assert.False(crossPlatformDscInfo.IsRegistered); Assert.Empty(crossPlatformDscInfo.Implementations); - - SubsystemInfo crossPlatformDscInfo2 = SubsystemManager.GetSubsystemInfo(SubsystemKind.CrossPlatformDsc); - Assert.Same(crossPlatformDscInfo2, crossPlatformDscInfo); + #endregion ReadOnlyCollection ssInfos = SubsystemManager.GetAllSubsystemInfo(); - Assert.Equal(2, ssInfos.Count); + Assert.Equal(3, ssInfos.Count); Assert.Same(ssInfos[0], predictorInfo); Assert.Same(ssInfos[1], crossPlatformDscInfo); + Assert.Same(ssInfos[2], feedbackProviderInfo); ICommandPredictor predictorImpl = SubsystemManager.GetSubsystem(); Assert.Null(predictorImpl); ReadOnlyCollection predictorImpls = SubsystemManager.GetSubsystems(); Assert.Empty(predictorImpls); + ReadOnlyCollection feedbackImpls = SubsystemManager.GetSubsystems(); + Assert.Single(feedbackImpls); + ICrossPlatformDsc crossPlatformDscImpl = SubsystemManager.GetSubsystem(); Assert.Null(crossPlatformDscImpl); ReadOnlyCollection crossPlatformDscImpls = SubsystemManager.GetSubsystems(); @@ -91,14 +118,19 @@ public static void RegisterSubsystem() () => SubsystemManager.RegisterSubsystem(SubsystemKind.CommandPredictor, null)); Assert.Throws( paramName: "proxy", + () => SubsystemManager.RegisterSubsystem(SubsystemKind.CrossPlatformDsc, predictor1)); + Assert.Throws( + paramName: "kind", () => SubsystemManager.RegisterSubsystem((SubsystemKind)0, predictor1)); + Assert.Throws( + paramName: "kind", + () => SubsystemManager.RegisterSubsystem(SubsystemKind.CommandPredictor | SubsystemKind.FeedbackProvider, predictor1)); // Register 'predictor1' SubsystemManager.RegisterSubsystem(predictor1); // Now validate the SubsystemInfo of the 'ICommandPredictor' subsystem SubsystemInfo ssInfo = SubsystemManager.GetSubsystemInfo(typeof(ICommandPredictor)); - SubsystemInfo crossPlatformDscInfo = SubsystemManager.GetSubsystemInfo(typeof(ICrossPlatformDsc)); VerifyCommandPredictorMetadata(ssInfo); Assert.True(ssInfo.IsRegistered); Assert.Single(ssInfo.Implementations); From effa29aae4c252b5b8de00214eb0da34dae5c893 Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Mon, 24 Oct 2022 20:14:05 +0100 Subject: [PATCH 131/779] Implement `IDisposable` in `NamedPipeClient` (#18341) --- test/tools/NamedPipeConnection/src/code/NamedPipeConnection.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/tools/NamedPipeConnection/src/code/NamedPipeConnection.cs b/test/tools/NamedPipeConnection/src/code/NamedPipeConnection.cs index 02b63999de8..7a9bff15f79 100644 --- a/test/tools/NamedPipeConnection/src/code/NamedPipeConnection.cs +++ b/test/tools/NamedPipeConnection/src/code/NamedPipeConnection.cs @@ -22,7 +22,7 @@ namespace Microsoft.PowerShell.CustomNamedPipeConnection /// a client side named pipe object that can connect to a running PowerShell /// process by its process Id. /// - internal sealed class NamedPipeClient + internal sealed class NamedPipeClient : IDisposable { #region Members From ece26bcf117b8a0583fa9dbde7f367f0b637caba Mon Sep 17 00:00:00 2001 From: Ilya Date: Tue, 25 Oct 2022 00:16:22 +0500 Subject: [PATCH 132/779] Remove `FusionAssemblyIdentity` and `GlobalAssemblyCache` as they are not used (#18334) --- .../engine/parser/Compiler.cs | 6 - .../engine/parser/FusionAssemblyIdentity.cs | 316 ------------------ .../engine/parser/GlobalAssemblyCache.cs | 215 ------------ .../engine/parser/Parser.cs | 7 - 4 files changed, 544 deletions(-) delete mode 100644 src/System.Management.Automation/engine/parser/FusionAssemblyIdentity.cs delete mode 100644 src/System.Management.Automation/engine/parser/GlobalAssemblyCache.cs diff --git a/src/System.Management.Automation/engine/parser/Compiler.cs b/src/System.Management.Automation/engine/parser/Compiler.cs index cf7527069db..676ed06fcd0 100644 --- a/src/System.Management.Automation/engine/parser/Compiler.cs +++ b/src/System.Management.Automation/engine/parser/Compiler.cs @@ -2804,12 +2804,6 @@ private static Assembly LoadAssembly(string assemblyName, string scriptFileName) assemblyFileName = Path.GetDirectoryName(scriptFileName) + "\\" + assemblyFileName; } -#if !CORECLR - if (!File.Exists(assemblyFileName)) - { - Microsoft.CodeAnalysis.GlobalAssemblyCache.ResolvePartialName(assemblyName, out assemblyFileName); - } -#endif if (File.Exists(assemblyFileName)) { assembly = Assembly.LoadFrom(assemblyFileName); diff --git a/src/System.Management.Automation/engine/parser/FusionAssemblyIdentity.cs b/src/System.Management.Automation/engine/parser/FusionAssemblyIdentity.cs deleted file mode 100644 index 79df05d09f4..00000000000 --- a/src/System.Management.Automation/engine/parser/FusionAssemblyIdentity.cs +++ /dev/null @@ -1,316 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -// Code in this file was copied from https://github.com/dotnet/roslyn - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Reflection; -using System.Runtime.InteropServices; - -#if !CORECLR -namespace Microsoft.CodeAnalysis -{ - internal sealed class FusionAssemblyIdentity - { - [Flags] - internal enum ASM_DISPLAYF - { - VERSION = 0x01, - CULTURE = 0x02, - PUBLIC_KEY_TOKEN = 0x04, - PUBLIC_KEY = 0x08, - CUSTOM = 0x10, - PROCESSORARCHITECTURE = 0x20, - LANGUAGEID = 0x40, - RETARGET = 0x80, - CONFIG_MASK = 0x100, - MVID = 0x200, - CONTENT_TYPE = 0x400, - FULL = VERSION | CULTURE | PUBLIC_KEY_TOKEN | RETARGET | PROCESSORARCHITECTURE | CONTENT_TYPE - } - - internal enum PropertyId - { - PUBLIC_KEY = 0, // 0 - PUBLIC_KEY_TOKEN, // 1 - HASH_VALUE, // 2 - NAME, // 3 - MAJOR_VERSION, // 4 - MINOR_VERSION, // 5 - BUILD_NUMBER, // 6 - REVISION_NUMBER, // 7 - CULTURE, // 8 - PROCESSOR_ID_ARRAY, // 9 - OSINFO_ARRAY, // 10 - HASH_ALGID, // 11 - ALIAS, // 12 - CODEBASE_URL, // 13 - CODEBASE_LASTMOD, // 14 - NULL_PUBLIC_KEY, // 15 - NULL_PUBLIC_KEY_TOKEN, // 16 - CUSTOM, // 17 - NULL_CUSTOM, // 18 - MVID, // 19 - FILE_MAJOR_VERSION, // 20 - FILE_MINOR_VERSION, // 21 - FILE_BUILD_NUMBER, // 22 - FILE_REVISION_NUMBER, // 23 - RETARGET, // 24 - SIGNATURE_BLOB, // 25 - CONFIG_MASK, // 26 - ARCHITECTURE, // 27 - CONTENT_TYPE, // 28 - MAX_PARAMS // 29 - } - - private static class CANOF - { - public const uint PARSE_DISPLAY_NAME = 0x1; - public const uint SET_DEFAULT_VALUES = 0x2; - } - - [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("CD193BC0-B4BC-11d2-9833-00C04FC31D2E")] - internal unsafe interface IAssemblyName - { - void SetProperty(PropertyId id, void* data, uint size); - - [PreserveSig] - int GetProperty(PropertyId id, void* data, ref uint size); - - [PreserveSig] - int Finalize(); - - [PreserveSig] - int GetDisplayName(byte* buffer, ref uint characterCount, ASM_DISPLAYF dwDisplayFlags); - - [PreserveSig] - int __BindToObject(/*...*/); - - [PreserveSig] - int __GetName(/*...*/); - - [PreserveSig] - int GetVersion(out uint versionHi, out uint versionLow); - - [PreserveSig] - int IsEqual(IAssemblyName pName, uint dwCmpFlags); - - [PreserveSig] - int Clone(out IAssemblyName pName); - } - - [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("7c23ff90-33af-11d3-95da-00a024a85b51")] - internal interface IApplicationContext - { - } - - // NOTE: The CLR caches assembly identities, but doesn't do so in a threadsafe manner. - // Wrap all calls to this with a lock. - private static object s_assemblyIdentityGate = new object(); - private static int CreateAssemblyNameObject(out IAssemblyName ppEnum, string szAssemblyName, uint dwFlags, IntPtr pvReserved) - { - lock (s_assemblyIdentityGate) - { - return RealCreateAssemblyNameObject(out ppEnum, szAssemblyName, dwFlags, pvReserved); - } - } - - [DllImport("clr", EntryPoint = "CreateAssemblyNameObject", CharSet = CharSet.Unicode, PreserveSig = true)] - private static extern int RealCreateAssemblyNameObject(out IAssemblyName ppEnum, [MarshalAs(UnmanagedType.LPWStr)]string szAssemblyName, uint dwFlags, IntPtr pvReserved); - - private const int ERROR_INSUFFICIENT_BUFFER = unchecked((int)0x8007007A); - private const int FUSION_E_INVALID_NAME = unchecked((int)0x80131047); - - internal static unsafe string GetDisplayName(IAssemblyName nameObject, ASM_DISPLAYF displayFlags) - { - int hr; - uint characterCountIncludingTerminator = 0; - - hr = nameObject.GetDisplayName(null, ref characterCountIncludingTerminator, displayFlags); - if (hr == 0) - { - return string.Empty; - } - - if (hr != ERROR_INSUFFICIENT_BUFFER) - { - Marshal.ThrowExceptionForHR(hr); - } - - byte[] data = new byte[(int)characterCountIncludingTerminator * 2]; - fixed (byte* p = data) - { - hr = nameObject.GetDisplayName(p, ref characterCountIncludingTerminator, displayFlags); - Marshal.ThrowExceptionForHR(hr); - - return Marshal.PtrToStringUni((IntPtr)p, (int)characterCountIncludingTerminator - 1); - } - } - - internal static unsafe byte[] GetPropertyBytes(IAssemblyName nameObject, PropertyId propertyId) - { - int hr; - uint size = 0; - - hr = nameObject.GetProperty(propertyId, null, ref size); - if (hr == 0) - { - return null; - } - - if (hr != ERROR_INSUFFICIENT_BUFFER) - { - Marshal.ThrowExceptionForHR(hr); - } - - byte[] data = new byte[(int)size]; - fixed (byte* p = data) - { - hr = nameObject.GetProperty(propertyId, p, ref size); - Marshal.ThrowExceptionForHR(hr); - } - - return data; - } - - internal static unsafe string GetPropertyString(IAssemblyName nameObject, PropertyId propertyId) - { - byte[] data = GetPropertyBytes(nameObject, propertyId); - if (data == null) - { - return null; - } - - fixed (byte* p = data) - { - return Marshal.PtrToStringUni((IntPtr)p, (data.Length / 2) - 1); - } - } - - internal static unsafe Version GetVersion(IAssemblyName nameObject) - { - uint hi, lo; - int hr = nameObject.GetVersion(out hi, out lo); - if (hr != 0) - { - Debug.Assert(hr == FUSION_E_INVALID_NAME); - return null; - } - - return new Version((int)(hi >> 16), (int)(hi & 0xffff), (int)(lo >> 16), (int)(lo & 0xffff)); - } - - internal static unsafe uint? GetPropertyWord(IAssemblyName nameObject, PropertyId propertyId) - { - uint result; - uint size = sizeof(uint); - int hr = nameObject.GetProperty(propertyId, &result, ref size); - Marshal.ThrowExceptionForHR(hr); - - if (size == 0) - { - return null; - } - - return result; - } - - internal static string GetCulture(IAssemblyName nameObject) - { - return GetPropertyString(nameObject, PropertyId.CULTURE); - } - - internal static ProcessorArchitecture GetProcessorArchitecture(IAssemblyName nameObject) - { - return (ProcessorArchitecture)(GetPropertyWord(nameObject, PropertyId.ARCHITECTURE) ?? 0); - } - - /// - /// Creates object by parsing given display name. - /// - internal static IAssemblyName ToAssemblyNameObject(string displayName) - { - // CLR doesn't handle \0 in the display name well: - if (displayName.IndexOf('\0') >= 0) - { - return null; - } - - Debug.Assert(displayName != null); - IAssemblyName result; - int hr = CreateAssemblyNameObject(out result, displayName, CANOF.PARSE_DISPLAY_NAME, IntPtr.Zero); - if (hr != 0) - { - return null; - } - - Debug.Assert(result != null); - return result; - } - - /// - /// Selects the candidate assembly with the largest version number. Uses culture as a tie-breaker if it is provided. - /// All candidates are assumed to have the same name and must include versions and cultures. - /// - internal static IAssemblyName GetBestMatch(IEnumerable candidates, string preferredCultureOpt) - { - IAssemblyName bestCandidate = null; - Version bestVersion = null; - string bestCulture = null; - foreach (var candidate in candidates) - { - if (bestCandidate != null) - { - Version candidateVersion = GetVersion(candidate); - Debug.Assert(candidateVersion != null); - - if (bestVersion == null) - { - bestVersion = GetVersion(bestCandidate); - Debug.Assert(bestVersion != null); - } - - int cmp = bestVersion.CompareTo(candidateVersion); - if (cmp == 0) - { - if (preferredCultureOpt != null) - { - string candidateCulture = GetCulture(candidate); - Debug.Assert(candidateCulture != null); - - if (bestCulture == null) - { - bestCulture = GetCulture(candidate); - Debug.Assert(bestCulture != null); - } - - // we have exactly the preferred culture or - // we have neutral culture and the best candidate's culture isn't the preferred one: - if (StringComparer.OrdinalIgnoreCase.Equals(candidateCulture, preferredCultureOpt) || - candidateCulture.Length == 0 && !StringComparer.OrdinalIgnoreCase.Equals(bestCulture, preferredCultureOpt)) - { - bestCandidate = candidate; - bestVersion = candidateVersion; - bestCulture = candidateCulture; - } - } - } - else if (cmp < 0) - { - bestCandidate = candidate; - bestVersion = candidateVersion; - } - } - else - { - bestCandidate = candidate; - } - } - - return bestCandidate; - } - } -} -#endif // !CORECLR diff --git a/src/System.Management.Automation/engine/parser/GlobalAssemblyCache.cs b/src/System.Management.Automation/engine/parser/GlobalAssemblyCache.cs deleted file mode 100644 index 3761c55d3dc..00000000000 --- a/src/System.Management.Automation/engine/parser/GlobalAssemblyCache.cs +++ /dev/null @@ -1,215 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -// Code in this file was copied from https://github.com/dotnet/roslyn - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Reflection; -using System.Runtime.InteropServices; - -#if !CORECLR // Only enable/port what is needed by CORE CLR. -namespace Microsoft.CodeAnalysis -{ - /// - /// Provides APIs to enumerate and look up assemblies stored in the Global Assembly Cache. - /// - internal static class GlobalAssemblyCache - { - /// - /// Represents the current Processor architecture. - /// - public static readonly ProcessorArchitecture[] CurrentArchitectures = (IntPtr.Size == 4) - ? new[] { ProcessorArchitecture.None, ProcessorArchitecture.MSIL, ProcessorArchitecture.X86 } - - : new[] { ProcessorArchitecture.None, ProcessorArchitecture.MSIL, ProcessorArchitecture.Amd64 }; - -#region Interop - - private const int MAX_PATH = 260; - - [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("21b8916c-f28e-11d2-a473-00c04f8ef448")] - private interface IAssemblyEnum - { - [PreserveSig] - int GetNextAssembly(out FusionAssemblyIdentity.IApplicationContext ppAppCtx, out FusionAssemblyIdentity.IAssemblyName ppName, uint dwFlags); - - [PreserveSig] - int Reset(); - - [PreserveSig] - int Clone(out IAssemblyEnum ppEnum); - } - - [ComImport, Guid("e707dcde-d1cd-11d2-bab9-00c04f8eceae"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - private interface IAssemblyCache - { - void UninstallAssembly(); - - void QueryAssemblyInfo(uint dwFlags, [MarshalAs(UnmanagedType.LPWStr)] string pszAssemblyName, ref ASSEMBLY_INFO pAsmInfo); - - void CreateAssemblyCacheItem(); - void CreateAssemblyScavenger(); - void InstallAssembly(); - } - - [StructLayout(LayoutKind.Sequential)] - private unsafe struct ASSEMBLY_INFO - { - public uint cbAssemblyInfo; - public uint dwAssemblyFlags; - public ulong uliAssemblySizeInKB; - public char* pszCurrentAssemblyPathBuf; - public uint cchBuf; - } - - private enum ASM_CACHE - { - ZAP = 0x1, - GAC = 0x2, // C:\Windows\Assembly\GAC - DOWNLOAD = 0x4, - ROOT = 0x8, // C:\Windows\Assembly - GAC_MSIL = 0x10, - GAC_32 = 0x20, // C:\Windows\Assembly\GAC_32 - GAC_64 = 0x40, // C:\Windows\Assembly\GAC_64 - ROOT_EX = 0x80, // C:\Windows\Microsoft.NET\assembly - } - - [DllImport("clr", CharSet = CharSet.Auto, PreserveSig = true)] - private static extern int CreateAssemblyEnum(out IAssemblyEnum ppEnum, FusionAssemblyIdentity.IApplicationContext pAppCtx, FusionAssemblyIdentity.IAssemblyName pName, ASM_CACHE dwFlags, IntPtr pvReserved); - - [DllImport("clr", CharSet = CharSet.Auto, PreserveSig = false)] - private static extern void CreateAssemblyCache(out IAssemblyCache ppAsmCache, uint dwReserved); - -#endregion - - private const int S_OK = 0; - private const int S_FALSE = 1; - - // Internal for testing. - internal static IEnumerable GetAssemblyObjects( - FusionAssemblyIdentity.IAssemblyName partialNameFilter, - ProcessorArchitecture[] architectureFilter) - { - IAssemblyEnum enumerator; - - int hr = CreateAssemblyEnum(out enumerator, null, partialNameFilter, ASM_CACHE.GAC, IntPtr.Zero); - if (hr == S_FALSE) - { - // no assembly found - yield break; - } - - if (hr != S_OK) - { - Exception e = Marshal.GetExceptionForHR(hr); - if (e is FileNotFoundException) - { - // invalid assembly name: - yield break; - } - - if (e != null) - { - throw e; - } - // for some reason it might happen that CreateAssemblyEnum returns non-zero HR that doesn't correspond to any exception: - throw new ArgumentException("Invalid assembly name"); - } - - while (true) - { - FusionAssemblyIdentity.IAssemblyName nameObject; - - FusionAssemblyIdentity.IApplicationContext applicationContext; - hr = enumerator.GetNextAssembly(out applicationContext, out nameObject, 0); - if (hr != 0) - { - if (hr < 0) - { - Marshal.ThrowExceptionForHR(hr); - } - - break; - } - - if (architectureFilter != null) - { - var assemblyArchitecture = FusionAssemblyIdentity.GetProcessorArchitecture(nameObject); - if (!architectureFilter.Contains(assemblyArchitecture)) - { - continue; - } - } - - yield return nameObject; - } - } - - /// - /// Looks up specified partial assembly name in the GAC and returns the best matching full assembly name/>. - /// - /// The display name of an assembly. - /// Full path name of the resolved assembly. - /// The optional processor architecture. - /// The optional preferred culture information. - /// An assembly identity or null, if can't be resolved. - /// is null. - public static unsafe string ResolvePartialName( - string displayName, - out string location, - ProcessorArchitecture[] architectureFilter = null, - CultureInfo preferredCulture = null) - { - if (displayName == null) - { - throw new ArgumentNullException("displayName"); - } - - location = null; - FusionAssemblyIdentity.IAssemblyName nameObject = FusionAssemblyIdentity.ToAssemblyNameObject(displayName); - if (nameObject == null) - { - return null; - } - - var candidates = GetAssemblyObjects(nameObject, architectureFilter); - string cultureName = (preferredCulture != null && !preferredCulture.IsNeutralCulture) ? preferredCulture.Name : null; - - var bestMatch = FusionAssemblyIdentity.GetBestMatch(candidates, cultureName); - if (bestMatch == null) - { - return null; - } - - string fullName = FusionAssemblyIdentity.GetDisplayName(bestMatch, FusionAssemblyIdentity.ASM_DISPLAYF.FULL); - - fixed (char* p = new char[MAX_PATH]) - { - ASSEMBLY_INFO info = new ASSEMBLY_INFO - { - cbAssemblyInfo = (uint)Marshal.SizeOf(typeof(ASSEMBLY_INFO)), - pszCurrentAssemblyPathBuf = p, - cchBuf = (uint)MAX_PATH - }; - - IAssemblyCache assemblyCacheObject; - CreateAssemblyCache(out assemblyCacheObject, 0); - assemblyCacheObject.QueryAssemblyInfo(0, fullName, ref info); - Debug.Assert(info.pszCurrentAssemblyPathBuf != null); - Debug.Assert(info.pszCurrentAssemblyPathBuf[info.cchBuf - 1] == '\0'); - - var result = Marshal.PtrToStringUni((IntPtr)info.pszCurrentAssemblyPathBuf, (int)info.cchBuf - 1); - Debug.Assert(result.IndexOf('\0') == -1); - location = result; - } - - return fullName; - } - } -} -#endif // !CORECLR diff --git a/src/System.Management.Automation/engine/parser/Parser.cs b/src/System.Management.Automation/engine/parser/Parser.cs index 31e7618a32f..9d80edf6500 100644 --- a/src/System.Management.Automation/engine/parser/Parser.cs +++ b/src/System.Management.Automation/engine/parser/Parser.cs @@ -5115,13 +5115,6 @@ private StringConstantExpressionAst ResolveUsingAssembly(StringConstantExpressio assemblyFileName = workingDirectory + @"\" + assemblyFileName; } - -#if !CORECLR - if (!File.Exists(assemblyFileName)) - { - GlobalAssemblyCache.ResolvePartialName(assemblyName, out assemblyFileName); - } -#endif } catch { From 9fa4a113808122ab050b7582a8f0c82ece8b7847 Mon Sep 17 00:00:00 2001 From: Olivia Date: Tue, 25 Oct 2022 08:22:36 +1300 Subject: [PATCH 133/779] Fix the exception reporting in `ConvertFrom-StringData` (#18336) --- .../commands/utility/ConvertFrom-StringData.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-StringData.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-StringData.cs index 16bb4be012d..284c344f7cc 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-StringData.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-StringData.cs @@ -69,7 +69,7 @@ protected override void ProcessRecord() { throw PSTraceSource.NewInvalidOperationException( ConvertFromStringData.InvalidDataLine, - line); + s); } string name = s.Substring(0, index); @@ -79,7 +79,7 @@ protected override void ProcessRecord() { throw PSTraceSource.NewInvalidOperationException( ConvertFromStringData.DataItemAlreadyDefined, - line, + s, name); } From f12a4f86792535f3155e29e84dd1bbfc1ce9b0f6 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 24 Oct 2022 14:26:24 -0700 Subject: [PATCH 134/779] Bump `Microsoft.CodeAnalysis.NetAnalyzers` (#18363) --- Analyzers.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Analyzers.props b/Analyzers.props index 8dd63903e97..4117ed85883 100644 --- a/Analyzers.props +++ b/Analyzers.props @@ -1,7 +1,7 @@ - + From ab7f2062717bfc3063c64e409706cb80ad8782f9 Mon Sep 17 00:00:00 2001 From: MartinGC94 <42123497+MartinGC94@users.noreply.github.com> Date: Mon, 24 Oct 2022 23:39:34 +0200 Subject: [PATCH 135/779] Fix type inference error for empty return statements (#18351) --- .../engine/parser/TypeInferenceVisitor.cs | 5 +++++ test/powershell/engine/Api/TypeInference.Tests.ps1 | 5 +++++ 2 files changed, 10 insertions(+) diff --git a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs index a1e761c1cce..b48a35e7502 100644 --- a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs +++ b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs @@ -936,6 +936,11 @@ object ICustomAstVisitor.VisitContinueStatement(ContinueStatementAst continueSta object ICustomAstVisitor.VisitReturnStatement(ReturnStatementAst returnStatementAst) { + if (returnStatementAst.Pipeline is null) + { + return TypeInferenceContext.EmptyPSTypeNameArray; + } + return returnStatementAst.Pipeline.Accept(this); } diff --git a/test/powershell/engine/Api/TypeInference.Tests.ps1 b/test/powershell/engine/Api/TypeInference.Tests.ps1 index 1c41ef72e84..5eca91ca0c0 100644 --- a/test/powershell/engine/Api/TypeInference.Tests.ps1 +++ b/test/powershell/engine/Api/TypeInference.Tests.ps1 @@ -796,6 +796,11 @@ Describe "Type inference Tests" -tags "CI" { $res.Name | Should -Be 'System.Int32' } + It 'Infers type from empty Return statement' { + $res = [AstTypeInference]::InferTypeOf( { return }.Ast) + $res.Count | Should -Be 0 + } + It 'Infers type from New-Object statement' { $res = [AstTypeInference]::InferTypeOf( { New-Object -TypeName 'System.Diagnostics.Stopwatch' From 215ac2f0f41789e6ee71d9ff1e3000b19c155b52 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Mon, 24 Oct 2022 23:52:09 +0200 Subject: [PATCH 136/779] Code cleanup in `ContentHelper.Common.cs` (#18288) --- .../WebCmdlet/Common/ContentHelper.Common.cs | 46 ++----------------- .../Common/InvokeRestMethodCommand.Common.cs | 2 - 2 files changed, 4 insertions(+), 44 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs index f16ad99d2a1..c7b8c878ca0 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs @@ -13,20 +13,6 @@ namespace Microsoft.PowerShell.Commands { internal static class ContentHelper { - #region Constants - - // default codepage encoding for web content. See RFC 2616. - private const string _defaultCodePage = "ISO-8859-1"; - - #endregion Constants - - #region Fields - - // used to split contentType arguments - private static readonly char[] s_contentTypeParamSeparator = { ';' }; - - #endregion Fields - #region Internal Methods internal static string GetContentType(HttpResponseMessage response) @@ -37,33 +23,9 @@ internal static string GetContentType(HttpResponseMessage response) internal static Encoding GetDefaultEncoding() { - return GetEncodingOrDefault((string)null); - } - - internal static Encoding GetEncoding(HttpResponseMessage response) - { - // ContentType may not exist in response header. - string charSet = response.Content.Headers.ContentType?.CharSet; - return GetEncodingOrDefault(charSet); - } - - internal static Encoding GetEncodingOrDefault(string characterSet) - { - // get the name of the codepage to use for response content - string codepage = (string.IsNullOrEmpty(characterSet) ? _defaultCodePage : characterSet); - Encoding encoding = null; - - try - { - encoding = Encoding.GetEncoding(codepage); - } - catch (ArgumentException) - { - // 0, default code page - encoding = Encoding.GetEncoding(0); - } - - return encoding; + // default codepage encoding for web content. See RFC 2616. + Encoding encoding = Encoding.GetEncoding("ISO-8859-1"); + return encoding; } internal static StringBuilder GetRawContentHeader(HttpResponseMessage response) @@ -206,7 +168,7 @@ private static string GetContentTypeSignature(string contentType) if (string.IsNullOrEmpty(contentType)) return null; - string sig = contentType.Split(s_contentTypeParamSeparator, 2)[0].ToUpperInvariant(); + string sig = contentType.Split(';', 2)[0].ToUpperInvariant(); return (sig); } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs index 0970ae46e8f..72844df44fc 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs @@ -404,8 +404,6 @@ internal override void ProcessResponse(HttpResponseMessage response) string charSet = response.Content.Headers.ContentType?.CharSet; if (!string.IsNullOrEmpty(charSet)) { - // NOTE: Don't use ContentHelper.GetEncoding; it returns a - // default which bypasses checking for a meta charset value. StreamHelper.TryGetEncoding(charSet, out encoding); } From 7cae30de39de37276b0e9cd1ce24ead1374d67bf Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Mon, 24 Oct 2022 14:58:51 -0700 Subject: [PATCH 137/779] Remove unused strings from `ConsoleInfoErrorStrings.resx` (#18367) --- .../resources/ConsoleInfoErrorStrings.resx | 90 ------------------- 1 file changed, 90 deletions(-) diff --git a/src/System.Management.Automation/resources/ConsoleInfoErrorStrings.resx b/src/System.Management.Automation/resources/ConsoleInfoErrorStrings.resx index ba0809e9010..c795fe2b8f7 100644 --- a/src/System.Management.Automation/resources/ConsoleInfoErrorStrings.resx +++ b/src/System.Management.Automation/resources/ConsoleInfoErrorStrings.resx @@ -117,63 +117,9 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - Required element "PSConsoleFile" in {0} is missing or incorrect. - - - Required element "PSVersion" in {0} is missing or incorrect. - - - Required element "ConsoleSchemaVersion" in {0} is missing or incorrect. - - - The console file is not valid. Multiple entries were found for the element PSConsoleFile. Only one entry is supported for this version. - - - The console file is not valid because the element {0} is not valid. - - - The console file is not valid because the PowerShell snap-in name is missing. - - - Attempting to save a console file with no name. Use Export-Console with the Path parameter to save the console file. - - - Unknown element {0} found. "{1}" should have "{2}" and "{3}" elements only. - - - The console file is not valid. Only one occurrence of the element "{0}" is allowed. - - - The path {0} is not an absolute path. - - - The console file name extension is not valid. A console file name extension must be psc1. - Incorrect PowerShell version {0}. PowerShell version {1} is supported on this computer. - - Cannot find any PowerShell snap-in information for {0}. - - - This is a system PowerShell snap-in that is loaded by PowerShell. - - - Cannot add PowerShell snap-in {0} because it is already added. Verify the name of the snap-in, and then try again. - - - Cannot remove the PowerShell snap-in {0} because it is not loaded. Verify the name of the snap-in that you want to remove, and then try again. - - - Cannot remove the PowerShell snap-in {0} because it is a system snap-in. Verify the name of the snap-in that you want to remove, and then try again. - - - Cannot load the PowerShell snap-in because an error occurred while reading the registry information for the snap-in. - - - An error occurred while attempting to load the system PowerShell snap-ins. Please contact Microsoft Customer Support Services. - The following errors occurred when loading console {0}: {1} @@ -195,45 +141,9 @@ PowerShell {0} is not supported in the current console. PowerShell {1} is supported in the current console. - - The cmdlet is not supported by the custom shell. - - - Cannot export to this file because file {0} is read-only. Change the read-only attribute of the file to read-write, or export to a different file. - File {0} already exists and {1} was specified. - - Cannot export to a console because no console is loaded or no name is specified. - - - Cmdlet {0} - - - Supply values for the following parameters: - - - Cannot export a console file because no console file has been specified. Do you want to continue with the export operation? - - - Cannot save the file because the file name format is not valid. Specify a file name using the command: export-console -path. - - - Cannot save the specified file. The Save operation was canceled. - - - Cannot save the console file because wildcard characters were used. Specify a console file without wildcard characters. - - - You can only save a file when you are working in a file provider. The current provider '{0}' is not a file provider. - - - Cannot set the ConsoleFileName variable to {0}. File {0} was saved. - - - The Save operation failed. Cannot remove the file {0}. - The provided configuration file '{0}' does not exist. From eef7c4526e2ac8fcab7e92d824fc0675e7acd7d9 Mon Sep 17 00:00:00 2001 From: Olivia Date: Tue, 25 Oct 2022 17:58:54 +1300 Subject: [PATCH 138/779] Add the function `cd~` (#18308) --- .../engine/InitialSessionState.cs | 1 + .../Set-Location.Tests.ps1 | 32 +++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/src/System.Management.Automation/engine/InitialSessionState.cs b/src/System.Management.Automation/engine/InitialSessionState.cs index 6fa242ce521..34e5c6d7abb 100644 --- a/src/System.Management.Automation/engine/InitialSessionState.cs +++ b/src/System.Management.Automation/engine/InitialSessionState.cs @@ -4709,6 +4709,7 @@ internal static SessionStateAliasEntry[] BuiltInAliases // Functions that don't require full language mode SessionStateFunctionEntry.GetDelayParsedFunctionEntry("cd..", "Set-Location ..", isProductCode: true, languageMode: systemLanguageMode), SessionStateFunctionEntry.GetDelayParsedFunctionEntry("cd\\", "Set-Location \\", isProductCode: true, languageMode: systemLanguageMode), + SessionStateFunctionEntry.GetDelayParsedFunctionEntry("cd~", "Set-Location ~", isProductCode: true, languageMode: systemLanguageMode), // Win8: 320909. Retaining the original definition to ensure backward compatability. SessionStateFunctionEntry.GetDelayParsedFunctionEntry("Pause", string.Concat("$null = Read-Host '", CodeGeneration.EscapeSingleQuotedStringContent(RunspaceInit.PauseDefinitionString), "'"), isProductCode: true, languageMode: systemLanguageMode), diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Set-Location.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Set-Location.Tests.ps1 index 2fb8177ec1a..f8a15d389e3 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Set-Location.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Set-Location.Tests.ps1 @@ -230,4 +230,36 @@ Describe "Set-Location" -Tags "CI" { $PWD.Path | Should -Be $location.Path } } + + Context 'Parsing of Set-Location to cd' { + It 'Should go to Filesystem home on cd~ run' { + Set-Location 'TestDrive:\' + cd~ + (Get-Location).Path | Should -BeExactly (Get-PSProvider FileSystem).Home + } + It 'Should go to the parent folder on cd.. run' { + Set-Location 'TestDrive:\' + $ParentDir = (Get-Location).path + New-Item -Path 'TestDrive:\' -Name 'Directory1' -ItemType Directory + Set-Location 'TestDrive:\Directory1' + cd.. + (Get-Location).Path | Should -BeExactly $ParentDir + } + It 'Should go to root of current drive on cd\ run (Windows)' -Skip:(!$IsWindows){ + #root is / on linux and Mac, so it's not happy with this check. + Set-Location 'TestDrive:\' + $DriveRoot = (Get-Location).path + New-Item -Path 'TestDrive:\Directory1' -Name 'Directory2' -ItemType Directory + Set-Location 'TestDrive:\Directory1\Directory2' + cd\ + (Get-Location).Path | Should -BeExactly $DriveRoot + } + It 'Should go to root of current drive on cd\ run (Linux/Mac)' -Skip:($IsWindows){ + Set-Location 'TestDrive:\' + New-Item -Path 'TestDrive:\Directory1' -Name 'Directory2' -ItemType Directory + Set-Location 'TestDrive:\Directory1\Directory2' + cd\ + (Get-Location).Path | Should -BeExactly "/" + } + } } From d0b2304b28d2a9a40c6ecdd1ec6d2e1025934564 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Mon, 24 Oct 2022 21:59:43 -0700 Subject: [PATCH 139/779] Remove unused console strings (#18369) --- .../resources/ConsoleControlStrings.resx | 12 ------------ .../resources/ConsoleHostStrings.resx | 9 --------- 2 files changed, 21 deletions(-) diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/ConsoleControlStrings.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/ConsoleControlStrings.resx index f5fc6e4427a..bf1a8f84bfd 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/resources/ConsoleControlStrings.resx +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/ConsoleControlStrings.resx @@ -123,12 +123,6 @@ The Win32 internal error "{0}" 0x{1:X} occurred while trying to remove a break handler. Contact Microsoft Customer Support Services. - - The Win32 internal error "{0}" 0x{1:X} occurred while attaching to parent console. Contact Microsoft Customer Support Services. - - - The Win32 internal error "{0}" 0x{1:X} occurred while detaching from the console. Contact Microsoft Customer Support Services. - The Win32 internal error "{0}" 0x{1:X} occurred while getting input about the console handle. Contact Microsoft Customer Support Services. @@ -192,9 +186,6 @@ The Win32 internal error "{0}" 0x{1:X} occurred while setting character attributes for the console output buffer. Contact Microsoft Customer Support Services. - - The Win32 internal error "{0}" 0x{1:X} occurred while trying to set the cursor position. Contact Microsoft Customer Support Services. - The Win32 internal error "{0}" 0x{1:X} occurred while getting cursor information. Contact Microsoft Customer Support Services. @@ -207,7 +198,4 @@ The Win32 internal error "{0}" 0x{1:X} occurred while sending keyboard input. Contact Microsoft Customer Support Services. - - The Win32 internal error "{0}" 0x{1:X} occurred while setting console font information. Contact Microsoft Customer Support Services. - diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/ConsoleHostStrings.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/ConsoleHostStrings.resx index 49c22783c1f..e8dcccb3dee 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/resources/ConsoleHostStrings.resx +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/ConsoleHostStrings.resx @@ -123,15 +123,9 @@ Cannot process input loop. ExitCurrentLoop was called when no InputLoops were running. - - A nested prompt cannot be entered until the host is running at least one prompt loop. - PS> - - Execution of initialization script has failed. The shell cannot be started. - The shell cannot be started. A failure occurred during initialization: @@ -155,9 +149,6 @@ PowerShell transcript end End time: {0:yyyyMMddHHmmss} ********************** - - An instance of the ConsoleHost class has already been created for this process. - Command '{0}' could not be run because some PowerShell Snap-Ins did not load. From f3f56d4d1d27081312e7cd52b04195a8400bfbf2 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Mon, 24 Oct 2022 22:00:01 -0700 Subject: [PATCH 140/779] Remove unused strings from Utility module (#18370) --- .../resources/AliasCommandStrings.resx | 6 ----- .../resources/HostStrings.resx | 3 --- .../resources/ImmutableStrings.resx | 24 ------------------- .../resources/ImplicitRemotingStrings.resx | 15 ------------ .../resources/NewObjectStrings.resx | 3 --- .../resources/TraceCommandStrings.resx | 3 --- .../resources/UpdateDataStrings.resx | 3 --- .../resources/WebCmdletStrings.resx | 21 ---------------- 8 files changed, 78 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/AliasCommandStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/AliasCommandStrings.resx index 1c3b0e52953..f10c2e64236 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/AliasCommandStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/AliasCommandStrings.resx @@ -135,12 +135,6 @@ Name: {0} Value: {1} - - Cannot export the aliases because path '{0}' referred to a '{1}' provider path. Change the Path parameter to a file system path. - - - Cannot export the aliases because path '{0}' contains wildcard characters that resolved to multiple paths. Aliases can be exported to only one file. Change the value of the Path parameter to a path that resolves to a single file. - Cannot open file {0} to export the alias. {1} diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/HostStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/HostStrings.resx index 6172bb81951..c01248ed5d7 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/HostStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/HostStrings.resx @@ -120,7 +120,4 @@ Cannot process the color because {0} is not a valid color. - - Cannot evaluate the error because a string is not specified. - diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ImmutableStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ImmutableStrings.resx index 9ba7fddb0b5..71e978c89b4 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/ImmutableStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ImmutableStrings.resx @@ -117,31 +117,7 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - Object is not a array with the same initialization state as the array to compare it to. - - - Object is not a array with the same number of elements as the array to compare it to. - - - Cannot find the old value - - - Capacity was less than the current Count of elements. - - - MoveToImmutable can only be performed when Count equals Capacity. - - - Collection was modified; enumeration operation may not execute. - An element with the same key but a different value already exists. Key: {0} - - This operation does not apply to an empty instance. - - - This operation cannot be performed on a default instance of ImmutableArray<T>. Consider initializing the array, or checking the ImmutableArray<T>.IsDefault property. - diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ImplicitRemotingStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ImplicitRemotingStrings.resx index 48d1fea7c34..3ee0ae73220 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/ImplicitRemotingStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ImplicitRemotingStrings.resx @@ -129,9 +129,6 @@ Running the {0} command in a remote session returned no results. - - Cannot create temporary file for implicit remoting module. - No session has been associated with this implicit remoting module. @@ -147,15 +144,6 @@ Proxy creation has been skipped for the '{0}' command, because PowerShell could not verify the safety of the command name. - - Proxy creation has been skipped for the '{0}' command, because PowerShell could not verify the safety of a parameter name: '{1}'. - - - Proxy creation has been skipped for the '{0}' command, because PowerShell could not verify the safety of a parameter set name: '{1}'. - - - Proxy creation has been skipped for the '{0}' command, because PowerShell could not verify the safety of a parameter alias name: '{1}'. - Proxy creation has been skipped for the following command: '{0}', because it would shadow an existing local command. Use the AllowClobber parameter if you want to shadow existing local commands. @@ -204,9 +192,6 @@ Getting formatting and output information from remote session ... {0} objects received - - Generating a proxy command for '{0}' ... - Completed. diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/NewObjectStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/NewObjectStrings.resx index 07c2a6d8c9e..92437a76646 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/NewObjectStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/NewObjectStrings.resx @@ -147,7 +147,4 @@ Cannot create type. Only core types are supported in {0} language mode on a policy locked down machine. - - {0} Please note that Single-Threaded Apartment is not supported in PowerShell. - diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/TraceCommandStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/TraceCommandStrings.resx index 0eb1e1e9466..c09ba1ea796 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/TraceCommandStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/TraceCommandStrings.resx @@ -117,9 +117,6 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - A file listener with name '{0}' was not found. - Trace output can only be written to the file system. The path '{0}' referred to a '{1}' provider path. diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/UpdateDataStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/UpdateDataStrings.resx index 9d2ccaced94..ba1bdfd6174 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/UpdateDataStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/UpdateDataStrings.resx @@ -135,9 +135,6 @@ Cannot update a member with type "{0}". Specify a different type for the MemberType parameter. - - The value of the SerializationDepth property should not be negative. - The {0} parameter is required for the type "{1}". Please specify the {0} parameter. diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/WebCmdletStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/WebCmdletStrings.resx index e4f34c17ea2..bea0ae7d28a 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/WebCmdletStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/WebCmdletStrings.resx @@ -162,15 +162,9 @@ Cannot convert the JSON string because it contains keys with different casing. Please use the -AsHashTable switch instead. The key that was attempted to be added to the existing key '{0}' was '{1}'. - - The ConvertTo-Json and ConvertFrom-Json cmdlets require the installation of the .NET Client Profile, sometimes called the .NET extended profile. - The response content cannot be parsed because the Internet Explorer engine is not available, or Internet Explorer's first-launch configuration is not complete. Specify the UseBasicParsing parameter and try again. - - The converted JSON string is in bad format. - The maximum redirection count has been exceeded. To increase the number of redirections allowed, supply a higher value to the -MaximumRedirection parameter. @@ -207,9 +201,6 @@ Downloaded: {0} of {1} - - The operation has timed out. - The cmdlet cannot run because the following conflicting parameters are specified: Session and SessionVariable. Specify either Session or SessionVariable, then retry. @@ -228,18 +219,6 @@ Downloaded: {0} of {1} - - The ConvertTo-Json and ConvertFrom-Json cmdlets require the 'Json.Net' module. {0} - - - The cmdlet cannot run because the 'Json.Net' module cannot be loaded. Import the module manually or set the $PSModuleAutoLoadingPreference variable to enable module auto loading. For more information, see 'get-help about_Preference_Variables'. - - - However, the 'Json.Net' module could not be loaded. For more information, run 'Import-Module Json.Net'. - - - Ensure 'Json.Net.psd1' and 'Newtonsoft.Json.dll' are available in a versioned subdirectory of '{0}'. - Conversion from JSON failed with error: {0} From 4936a566b04a8a0536145caf03950423cf27d1f9 Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Tue, 25 Oct 2022 16:01:30 -0700 Subject: [PATCH 141/779] Increase timeout to make subsystem tests more reliable (#18380) --- test/xUnit/csharp/test_Feedback.cs | 2 +- test/xUnit/csharp/test_Prediction.cs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/test/xUnit/csharp/test_Feedback.cs b/test/xUnit/csharp/test_Feedback.cs index d57d21fa0ec..9d7588a880d 100644 --- a/test/xUnit/csharp/test_Feedback.cs +++ b/test/xUnit/csharp/test_Feedback.cs @@ -89,7 +89,7 @@ public static void GetFeedback() // Expect the result from 'General' only because the 'slow' one cannot finish before the specified timeout. // The specified timeout is exaggerated to make the test reliable. // xUnit must spin up a lot tasks, which makes the test unreliable when the time difference between 'delay' and 'timeout' is small. - var feedbacks = FeedbackHub.GetFeedback(pwsh.Runspace, millisecondsTimeout: 1000); + var feedbacks = FeedbackHub.GetFeedback(pwsh.Runspace, millisecondsTimeout: 1500); string expectedCmd = Path.Combine(".", "feedbacktest"); // Test the result from the 'General' feedback provider. diff --git a/test/xUnit/csharp/test_Prediction.cs b/test/xUnit/csharp/test_Prediction.cs index a2c38db1359..e69f5b21a9d 100644 --- a/test/xUnit/csharp/test_Prediction.cs +++ b/test/xUnit/csharp/test_Prediction.cs @@ -147,7 +147,7 @@ public static void PredictInput() // cannot finish before the specified timeout. // The specified timeout is exaggerated to make the test reliable. // xUnit must spin up a lot tasks, which makes the test unreliable when the time difference between 'delay' and 'timeout' is small. - results = CommandPrediction.PredictInputAsync(predClient, ast, tokens, millisecondsTimeout: 1000).Result; + results = CommandPrediction.PredictInputAsync(predClient, ast, tokens, millisecondsTimeout: 1500).Result; Assert.Single(results); PredictionResult res = results[0]; @@ -214,7 +214,7 @@ public static void Feedback() slow.DisplayedSuggestions.Count == 0 || fast.DisplayedSuggestions.Count == 0 || slow.AcceptedSuggestions.Count == 0) { - Thread.Sleep(100); + Thread.Sleep(300); } Assert.Equal(2, slow.History.Count); From 70a0a27f555df34743898b47a106843d71d4898c Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Tue, 25 Oct 2022 20:01:33 -0700 Subject: [PATCH 142/779] Remove unused strings from parser (#18383) --- .../resources/ParserStrings.resx | 160 ------------------ 1 file changed, 160 deletions(-) diff --git a/src/System.Management.Automation/resources/ParserStrings.resx b/src/System.Management.Automation/resources/ParserStrings.resx index c1ae5c6ada4..75618a7dec7 100644 --- a/src/System.Management.Automation/resources/ParserStrings.resx +++ b/src/System.Management.Automation/resources/ParserStrings.resx @@ -123,9 +123,6 @@ Unable to find type [{0}]. Details: {1} - - Incomplete variable reference token. - Incomplete string token. @@ -141,9 +138,6 @@ The Unicode escape sequence contains more than the maximum of six hex digits between braces. - - A number cannot be both a long and floating point. - Cannot use [ref] with other types in a type constraint. @@ -183,14 +177,6 @@ Parameter '{0}' is not valid - - Ambiguous parameter '-{0}' -Possible matches are - - - - {0} ({1}) - Missing expression after '{0}' in pipeline element. @@ -227,15 +213,9 @@ Possible matches are An empty pipe element is not allowed. - - Unknown assignment operator '{0}'. - The assignment expression is not valid. The input to an assignment operator must be an object that is able to accept assignments, such as a variable or a property. - - Cannot expand the splatted variable '@{0}'. Splatted variables cannot be used as part of a property or array expression. Assign the result of the expression to a temporary variable then splat the temporary variable instead. - A hash table can only be added to another hash table. @@ -260,9 +240,6 @@ Possible matches are You must provide a value expression following the '{0}' operator. - - A regular expression that was provided to '{0}' is not valid: {1}. - The '{0}' operator works only on variables or on properties. @@ -275,9 +252,6 @@ Possible matches are Missing property name after reference operator. - - Property reference or expression is missing or not valid. - The property '{0}' cannot be found on this object. Verify that the property exists and can be set. @@ -299,27 +273,15 @@ Possible matches are The array has too many dimensions: {0}. The number of dimensions for an array must be less than or equal to 32. - - Array assignment to [{0}] failed: {1}. - Array assignment to [{0}] failed because assignment to slices is not supported. You cannot index into a {0} dimensional array with index [{1}]. - - Unable to assign to a dictionary of type {0} when the key is of type {1}. - - - Unable to assign to an index into an object of type {0}. - Array assignment failed because index '{0}' was out of range. - - Assigning to array element at index [{0}] failed: {1}. - Missing expression after '{0}'. @@ -350,15 +312,9 @@ Possible matches are An expression was expected after '('. - - Missing key before '=' in hash literal. - Missing '=' operator after key in hash literal. - - The "=" operator is missing after a named argument. - Missing statement after '=' in hash literal. @@ -392,9 +348,6 @@ Possible matches are The path cannot be processed because it resolved to more than one file; only one file at a time can be processed. - - The switch statement was incomplete. - The {0} '-{1}' parameter is reserved for future use. @@ -413,9 +366,6 @@ Possible matches are A switch statement must have one of the following: '-file file_name' or '( expression )'. - - Missing expression after '(' in switch statement. - Missing condition in switch statement clause. @@ -460,15 +410,9 @@ The correct form is: foreach ($a in $b) {...} Options are not allowed on the -split operator with a predicate. - - The terminator '{0}' is missing from the multiline comment. - The token '{0}' is not a valid statement separator in this version. - - The 'from' keyword is not supported in this version of the language. - The '{0}' keyword is not supported in this version of the language. @@ -484,18 +428,12 @@ The correct form is: foreach ($a in $b) {...} Incomplete 'try' statement. A try statement requires a body. - - The character '{0}' is not valid. Labels can contain only alphanumeric characters, numbers, and underscores ('_'). - Parameter declarations are a comma-separated list of variable names with optional initializer expressions. Missing function body in function declaration. - - Could not process combined Begin/Process/End clauses with command text. A script or function can either have begin/process/end clauses or command text but not both. - Script command clause '{0}' has already been defined. @@ -614,45 +552,18 @@ The correct form is: foreach ($a in $b) {...} At {0}:{1} char:{2} + {3} - - At char:{0} - {0,4}+ {1} - - ! Trap or Catch on matching exception [{0}] - - - ! Trap or Catch on [{0}]; subclass of exception [{1}] - - - ! Trap or Catch generic; caught [{0}] - - - ! SET-MULTIPLE ${0} assigned remaining {1} values. - - - ! SET-MULTIPLE ${0} = '{1}'. - ! SET ${0} = '{1}'. - - ! CALL scriptblock. - - - ! CALL script '{0}' - ! CALL function '{0}' ! CALL function '{0}' (defined in file '{1}') - - ! Setting parameterized property '{0}' - ! CALL method '{0}' @@ -665,42 +576,15 @@ The correct form is: foreach ($a in $b) {...} Missing ] at end of type token. - - Missing ) at end of subexpression. - Use `{ instead of { in variable names. - - Missing } at end of variable name. - - - Braced variable name cannot be empty. - The Data section is missing its statement block. - - Missing the opening brace "{" in the Data section. - - - Missing closing brace in the data section statement. - - - The body of the Data section is not valid. The Data section body can be only a convert-* command invocation optionally enclosed by an If statement. - The "{0}" parameter of the Data section is not valid. The valid Data section parameter is SupportedCommand. - - Expandable strings are not allowed in the list of supported commands for the Data section. - - - A token that is not valid was found in the list of supported commands for the Data section. - - - The Data section variable "{0}" has already been used for an existing variable or another Data section. - Array references are not allowed in restricted language mode or a Data section. @@ -710,9 +594,6 @@ The correct form is: foreach ($a in $b) {...} Redirection is not allowed in restricted language mode or a Data section. - - A command is referenced that is not allowed. Only convertfrom-* commands are supported in restricted language mode or a Data section. - The Do and While statements are not allowed in restricted language mode or a Data section. @@ -785,21 +666,12 @@ The correct form is: foreach ($a in $b) {...} Cannot find the type for custom attribute '{0}'. Make sure that the assembly that contains this type is loaded. - - Cannot find an appropriate constructor to instantiate the custom attribute object for type '{0}'. - - - The custom attribute type '{0}' is not derived from System.Attribute. - Property '{0}' cannot be found for type '{1}'. Unexpected attribute '{0}'. - - Operator '{0}' is not supported for type '{1}'. - Missing ] at end of attribute or type literal. @@ -896,9 +768,6 @@ The correct form is: foreach ($a in $b) {...} error stream - - host stream - output stream @@ -959,12 +828,6 @@ The correct form is: foreach ($a in $b) {...} An attribute name for resource '{0}' was found that is not valid. An attribute name must be a simple string, and cannot contain variables or expressions. Replace '{1}' with a simple string. - - The configuration name is missing or '{' was not found for a default definition. - - - The parameter {0} is not valid for the configuration statement. - The member '{0}' is not valid. Valid members are '{1}'. @@ -972,9 +835,6 @@ The correct form is: foreach ($a in $b) {...} Missing '{' in object definition. - - Parameter {0} can only be specified once for a configuration. - A required name or expression was missing. @@ -993,14 +853,6 @@ The correct form is: foreach ($a in $b) {...} The name for the configuration is missing. Provide the missing name as a simple name, string, or string-valued expression. - - Missing argument to -Resources. The argument to the -Resource parameter must be a comma-separated list of names or constant strings naming modules to reference for resource type definitions. - -Required Resources should not be localized - - - Unexpected token '{0}'. The argument to the -Resource parameter must be a comma-separated list of names or constant strings naming modules to reference for resource type definitions. - -Resource parameter should not be localized - Could not find the module '{0}'. @@ -1156,15 +1008,9 @@ ModuleVersion : Version of module to import. If used, ModuleName must represent Missing using directive - - Missing property name - Missing namespace alias - - Missing type alias - Missing '=' operator @@ -1458,12 +1304,6 @@ ModuleVersion : Version of module to import. If used, ModuleName must represent Conflict in using PsDscRunAsCredential for Resource {0} because it already specifies PsDscRunAsCredential value. We can only use one PsDscRunAsCredential for the composite resource. - - Unable to find DSC schema store at "{0}". Please ensure PSDesiredStateConfiguration v3 module is installed. - - - PS7DscSupport experimental feature is disabled; use Enable-ExperimentalFeature or update powershell.config.json to enable this feature. - {0} From e2d13c8efa2b094ba3305abb1c1cbcbb01f73510 Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Wed, 26 Oct 2022 16:46:00 +0100 Subject: [PATCH 143/779] Use `Enum.HasFlags` part 1 (#18386) --- .../utils/StructuredTraceSource.cs | 42 +++++++++---------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/src/System.Management.Automation/utils/StructuredTraceSource.cs b/src/System.Management.Automation/utils/StructuredTraceSource.cs index 287ad5bdd6d..e940bc57b9f 100644 --- a/src/System.Management.Automation/utils/StructuredTraceSource.cs +++ b/src/System.Management.Automation/utils/StructuredTraceSource.cs @@ -448,7 +448,7 @@ internal void TracerObjectHeader( internal IDisposable TraceScope(string msg) { - if ((_flags & PSTraceSourceOptions.Scope) != PSTraceSourceOptions.None) + if (_flags.HasFlag(PSTraceSourceOptions.Scope)) { try { @@ -462,7 +462,7 @@ internal IDisposable TraceScope(string msg) internal IDisposable TraceScope(string format, object arg1) { - if ((_flags & PSTraceSourceOptions.Scope) != PSTraceSourceOptions.None) + if (_flags.HasFlag(PSTraceSourceOptions.Scope)) { try { @@ -476,7 +476,7 @@ internal IDisposable TraceScope(string format, object arg1) internal IDisposable TraceScope(string format, object arg1, object arg2) { - if ((_flags & PSTraceSourceOptions.Scope) != PSTraceSourceOptions.None) + if (_flags.HasFlag(PSTraceSourceOptions.Scope)) { try { @@ -531,7 +531,7 @@ internal IDisposable TraceMethod( string format, params object[] args) { - if ((_flags & PSTraceSourceOptions.Method) != PSTraceSourceOptions.None) + if (_flags.HasFlag(PSTraceSourceOptions.Method)) { try { @@ -578,7 +578,7 @@ internal IDisposable TraceMethod( /// internal IDisposable TraceEventHandlers() { - if ((_flags & PSTraceSourceOptions.Events) != PSTraceSourceOptions.None) + if (_flags.HasFlag(PSTraceSourceOptions.Events)) { try { @@ -628,7 +628,7 @@ internal IDisposable TraceEventHandlers( string format, params object[] args) { - if ((_flags & PSTraceSourceOptions.Events) != PSTraceSourceOptions.None) + if (_flags.HasFlag(PSTraceSourceOptions.Events)) { try { @@ -697,7 +697,7 @@ internal IDisposable TraceEventHandlers( /// internal IDisposable TraceLock(string lockName) { - if ((_flags & PSTraceSourceOptions.Lock) != PSTraceSourceOptions.None) + if (_flags.HasFlag(PSTraceSourceOptions.Lock)) { try { @@ -729,7 +729,7 @@ internal IDisposable TraceLock(string lockName) /// internal void TraceLockAcquiring(string lockName) { - if ((_flags & PSTraceSourceOptions.Lock) != PSTraceSourceOptions.None) + if (_flags.HasFlag(PSTraceSourceOptions.Lock)) { TraceLockHelper( lockAcquiringFormatter, @@ -751,7 +751,7 @@ internal void TraceLockAcquiring(string lockName) /// internal void TraceLockAcquired(string lockName) { - if ((_flags & PSTraceSourceOptions.Lock) != PSTraceSourceOptions.None) + if (_flags.HasFlag(PSTraceSourceOptions.Lock)) { TraceLockHelper( lockEnterFormatter, @@ -769,7 +769,7 @@ internal void TraceLockAcquired(string lockName) /// internal void TraceLockReleased(string lockName) { - if ((_flags & PSTraceSourceOptions.Lock) != PSTraceSourceOptions.None) + if (_flags.HasFlag(PSTraceSourceOptions.Lock)) { TraceLockHelper( lockLeavingFormatter, @@ -823,7 +823,7 @@ internal void TraceError( string errorMessageFormat, params object[] args) { - if ((_flags & PSTraceSourceOptions.Error) != PSTraceSourceOptions.None) + if (_flags.HasFlag(PSTraceSourceOptions.Error)) { FormatOutputLine( PSTraceSourceOptions.Error, @@ -847,7 +847,7 @@ internal void TraceWarning( string warningMessageFormat, params object[] args) { - if ((_flags & PSTraceSourceOptions.Warning) != PSTraceSourceOptions.None) + if (_flags.HasFlag(PSTraceSourceOptions.Warning)) { FormatOutputLine( PSTraceSourceOptions.Warning, @@ -871,7 +871,7 @@ internal void TraceVerbose( string verboseMessageFormat, params object[] args) { - if ((_flags & PSTraceSourceOptions.Verbose) != PSTraceSourceOptions.None) + if (_flags.HasFlag(PSTraceSourceOptions.Verbose)) { FormatOutputLine( PSTraceSourceOptions.Verbose, @@ -889,7 +889,7 @@ internal void TraceVerbose( /// internal void WriteLine(string format) { - if ((_flags & PSTraceSourceOptions.WriteLine) != PSTraceSourceOptions.None) + if (_flags.HasFlag(PSTraceSourceOptions.WriteLine)) { FormatOutputLine( PSTraceSourceOptions.WriteLine, @@ -906,7 +906,7 @@ internal void WriteLine(string format) /// internal void WriteLine(string format, object arg1) { - if ((_flags & PSTraceSourceOptions.WriteLine) != PSTraceSourceOptions.None) + if (_flags.HasFlag(PSTraceSourceOptions.WriteLine)) { FormatOutputLine( PSTraceSourceOptions.WriteLine, @@ -974,7 +974,7 @@ internal void WriteLine(string format, ulong arg1) /// internal void WriteLine(string format, object arg1, object arg2) { - if ((_flags & PSTraceSourceOptions.WriteLine) != PSTraceSourceOptions.None) + if (_flags.HasFlag(PSTraceSourceOptions.WriteLine)) { FormatOutputLine( PSTraceSourceOptions.WriteLine, @@ -993,7 +993,7 @@ internal void WriteLine(string format, object arg1, object arg2) /// internal void WriteLine(string format, object arg1, object arg2, object arg3) { - if ((_flags & PSTraceSourceOptions.WriteLine) != PSTraceSourceOptions.None) + if (_flags.HasFlag(PSTraceSourceOptions.WriteLine)) { FormatOutputLine( PSTraceSourceOptions.WriteLine, @@ -1013,7 +1013,7 @@ internal void WriteLine(string format, object arg1, object arg2, object arg3) /// internal void WriteLine(string format, object arg1, object arg2, object arg3, object arg4) { - if ((_flags & PSTraceSourceOptions.WriteLine) != PSTraceSourceOptions.None) + if (_flags.HasFlag(PSTraceSourceOptions.WriteLine)) { FormatOutputLine( PSTraceSourceOptions.WriteLine, @@ -1034,7 +1034,7 @@ internal void WriteLine(string format, object arg1, object arg2, object arg3, ob /// internal void WriteLine(string format, object arg1, object arg2, object arg3, object arg4, object arg5) { - if ((_flags & PSTraceSourceOptions.WriteLine) != PSTraceSourceOptions.None) + if (_flags.HasFlag(PSTraceSourceOptions.WriteLine)) { FormatOutputLine( PSTraceSourceOptions.WriteLine, @@ -1056,7 +1056,7 @@ internal void WriteLine(string format, object arg1, object arg2, object arg3, ob /// internal void WriteLine(string format, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6) { - if ((_flags & PSTraceSourceOptions.WriteLine) != PSTraceSourceOptions.None) + if (_flags.HasFlag(PSTraceSourceOptions.WriteLine)) { FormatOutputLine( PSTraceSourceOptions.WriteLine, @@ -1074,7 +1074,7 @@ internal void WriteLine(string format, object arg1, object arg2, object arg3, ob /// internal void WriteLine(object arg) { - if ((_flags & PSTraceSourceOptions.WriteLine) != PSTraceSourceOptions.None) + if (_flags.HasFlag(PSTraceSourceOptions.WriteLine)) { WriteLine("{0}", arg == null ? "null" : arg.ToString()); } From a06d9085873a48de5d5bd5eca3ebe5605e0f8e45 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicklas=20Bj=C3=A4lemark?= <65188814+urizen-source@users.noreply.github.com> Date: Wed, 26 Oct 2022 19:27:36 +0300 Subject: [PATCH 144/779] Fix incorrect cmdlet name in the script used by `Restart-Computer` (#18374) --- .../commands/management/Computer.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs index e7e185ff8fb..e1b06c0bc94 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs @@ -306,7 +306,7 @@ public short Delay ComputerName = $computerName ScriptBlock = { $true } - SessionOption = NewPSSessionOption -NoMachineProfile + SessionOption = New-PSSessionOption -NoMachineProfile ErrorAction = 'SilentlyContinue' } From 8b82fa3597bc5d207f1745199f3d4a0d302adf39 Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Wed, 26 Oct 2022 09:50:26 -0700 Subject: [PATCH 145/779] Avoid using regex when unnecessary in `ScriptWriter` (#18348) --- .../cimSupport/cmdletization/ScriptWriter.cs | 54 ++++++++++++++++--- 1 file changed, 47 insertions(+), 7 deletions(-) diff --git a/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs b/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs index 5aa1b201fc9..46484a35d06 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs @@ -517,13 +517,53 @@ private Type GetDotNetType(TypeMetadata typeMetadata) Dbg.Assert(typeMetadata != null, "Caller should verify typeMetadata != null"); string psTypeText; - List matchingEnums = (_cmdletizationMetadata.Enums ?? Enumerable.Empty()) - .Where(e => Regex.IsMatch( - typeMetadata.PSType, - string.Format(CultureInfo.InvariantCulture, @"\b{0}\b", Regex.Escape(e.EnumName)), - RegexOptions.CultureInvariant)) - .ToList(); - EnumMetadataEnum matchingEnum = matchingEnums.Count == 1 ? matchingEnums[0] : null; + EnumMetadataEnum matchingEnum = null; + + if (_cmdletizationMetadata.Enums is not null) + { + string psType = typeMetadata.PSType; + foreach (EnumMetadataEnum e in _cmdletizationMetadata.Enums) + { + int index = psType.IndexOf(e.EnumName, StringComparison.Ordinal); + if (index == -1) + { + // Fast return if 'PSType' doesn't contain the enum name at all. + continue; + } + + bool matchFound = false; + if (index == 0) + { + // Handle 2 common cases here (cover over 99% of how enum name is used in 'PSType'): + // - 'PSType' is exactly the enum name. + // - 'PSType' is the array format of the enum. + ReadOnlySpan remains = psType.AsSpan(e.EnumName.Length); + matchFound = remains.Length is 0 || remains.Equals("[]", StringComparison.Ordinal); + } + + if (!matchFound) + { + // Now we have to fall back to the expensive regular expression matching, because 'PSType' + // could be a composite type like 'Nullable' or 'Dictionary', + // but we don't want the case where the enum name is part of another type's name. + matchFound = Regex.IsMatch(psType, $@"\b{Regex.Escape(e.EnumName)}\b"); + } + + if (matchFound) + { + if (matchingEnum is null) + { + matchingEnum = e; + continue; + } + + // If more than one matching enum names were found, we treat it as no match found. + matchingEnum = null; + break; + } + } + } + if (matchingEnum != null) { psTypeText = typeMetadata.PSType.Replace(matchingEnum.EnumName, EnumWriter.GetEnumFullName(matchingEnum)); From 0ede37731123ac6bdb3a765078bff1c0e075149d Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Wed, 26 Oct 2022 11:04:44 -0700 Subject: [PATCH 146/779] Remove unused resource strings in `System.Management.Automation` (#18388) --- .../resources/PowerShellStrings.resx | 28 ------------------- .../resources/RunspaceStrings.resx | 6 ---- .../resources/TypesXmlStrings.resx | 24 ---------------- 3 files changed, 58 deletions(-) diff --git a/src/System.Management.Automation/resources/PowerShellStrings.resx b/src/System.Management.Automation/resources/PowerShellStrings.resx index 230ac1b2685..563479c2d62 100644 --- a/src/System.Management.Automation/resources/PowerShellStrings.resx +++ b/src/System.Management.Automation/resources/PowerShellStrings.resx @@ -132,12 +132,6 @@ Cannot perform operation because the runspace is not in the '{0}' state. Current state of runspace is '{1}'. - - The runspace pool specified is not in an opened state. - - - This operation is currently not supported in the remoting scenario. - Nested PowerShell instances cannot be invoked asynchronously. Use the Invoke method. @@ -159,24 +153,6 @@ There is no Runspace available to run commands in this thread. You can provide one in the DefaultRunspace property of the System.Management.Automation.Runspaces.Runspace type. The command you attempted to invoke was: {0} - - GetJobForCommand is not supported when there is more than one command in the PowerShell instance. - - - The Command property of a PowerShell object cannot be empty. - - - A job cannot be started when it is already running. - - - Support for interactive jobs is not available - - - A job object can be used only once. - - - A job object cannot be reused. - This PowerShell object cannot be connected because it is not associated with a remote runspace or runspace pool. @@ -192,10 +168,6 @@ The connection attempt to the remote command failed. - - PSChildJobProxy does not support control methods. - PSChildJobProxy is the name of a class and should not be localized - The operation cannot be performed because a command is currently stopping. Wait for the command to complete stopping, and then try the operation again. diff --git a/src/System.Management.Automation/resources/RunspaceStrings.resx b/src/System.Management.Automation/resources/RunspaceStrings.resx index fa98177bc95..e3a0f93bd7e 100644 --- a/src/System.Management.Automation/resources/RunspaceStrings.resx +++ b/src/System.Management.Automation/resources/RunspaceStrings.resx @@ -162,9 +162,6 @@ A pipeline is already running. Concurrent SessionStateProxy method calls are not allowed. - - Parameter name or value must be specified. - This property cannot be changed after the runspace has been opened. @@ -207,9 +204,6 @@ Cannot connect the PSSession because the session is not in the Disconnected state, or is not available for connection. - - One or more errors occurred while processing the module '{0}' that is specified in the InitialSessionState object used to create this runspace. For a complete list of errors, see the ErrorRecords property. - Value for parameter cannot be PipelineResultTypes.None or PipelineResultTypes.Output. diff --git a/src/System.Management.Automation/resources/TypesXmlStrings.resx b/src/System.Management.Automation/resources/TypesXmlStrings.resx index 02c77e45424..10eb08a7351 100644 --- a/src/System.Management.Automation/resources/TypesXmlStrings.resx +++ b/src/System.Management.Automation/resources/TypesXmlStrings.resx @@ -126,9 +126,6 @@ Node "{0}" must occur only once under "{1}". The parent node, "{1}", will be ignored. - - Node "{0}" must have a maximum of one occurrence under "{1}". The parent node, "{1}", will be ignored. - The node {0} is not allowed. The following nodes are allowed: {1}. @@ -141,18 +138,6 @@ Node "{0}" was not found. It should occur only once under "{1}". The parent node, "{1}", will be ignored. - - Node "{0}" was not found. It should occur at least once under "{1}". The parent node, "{1}", will be ignored. - - - Expected XML tag "{0}" instead of node of type "{1}". - - - Node of type "{0}" was not expected. - - - Expected XML tag "{0}" instead of "{1}". - The "Type" node must have "Members", "TypeConverters", or "TypeAdapters". @@ -201,9 +186,6 @@ Node "{0}" should not have "{1}" attribute. - - Value should be "true" or "false" instead of "{0}" for "{1}" attribute. - {0}, {1}: The file was not found. @@ -261,12 +243,6 @@ "{0}" should not have null or an empty string in its property "{1}". - - More than one member with the name "{0}" is defined in the type file. - - - {0}: The file was skipped because it already occurred. - The type "{0}" was not found. The type name value must be the full name of the type. Verify the type name and run the command again. From ea8f2459d806a1dafa798d6759fdc6c58e30f577 Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Wed, 26 Oct 2022 15:54:15 -0700 Subject: [PATCH 147/779] Update `README.json` and `metadata.json` for `v7.3.0-rc.1` (#18393) --- README.md | 28 ++++++++++++++-------------- tools/metadata.json | 2 +- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index 78205f85cc1..8f411870852 100644 --- a/README.md +++ b/README.md @@ -93,20 +93,20 @@ You can also download the PowerShell binary archives for Windows, macOS and Linu [rl-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.7/powershell-7.2.7-linux-arm64.tar.gz [rl-snap]: https://snapcraft.io/powershell -[pv-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.8/PowerShell-7.3.0-preview.8-win-x64.msi -[pv-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.8/PowerShell-7.3.0-preview.8-win-x86.msi -[pv-deb]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.8/powershell-preview_7.3.0-preview.8-1.deb_amd64.deb -[pv-rpm]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.8/powershell-preview-7.3.0_preview.8-1.rh.x86_64.rpm -[pv-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.8/powershell-7.3.0-preview.8-osx-x64.pkg -[pv-macos-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.8/powershell-7.3.0-preview.8-osx-arm64.pkg -[pv-winarm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.8/PowerShell-7.3.0-preview.8-win-arm64.zip -[pv-winx86-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.8/PowerShell-7.3.0-preview.8-win-x86.zip -[pv-winx64-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.8/PowerShell-7.3.0-preview.8-win-x64.zip -[pv-macos-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.8/powershell-7.3.0-preview.8-osx-x64.tar.gz -[pv-macos-tar-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.8/powershell-7.3.0-preview.8-osx-arm64.tar.gz -[pv-linux-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.8/powershell-7.3.0-preview.8-linux-x64.tar.gz -[pv-arm32]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.8/powershell-7.3.0-preview.8-linux-arm32.tar.gz -[pv-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-preview.8/powershell-7.3.0-preview.8-linux-arm64.tar.gz +[pv-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-rc.1/PowerShell-7.3.0-rc.1-win-x64.msi +[pv-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-rc.1/PowerShell-7.3.0-rc.1-win-x86.msi +[pv-deb]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-rc.1/powershell-preview_7.3.0-rc.1-1.deb_amd64.deb +[pv-rpm]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-rc.1/powershell-preview-7.3.0_rc.1-1.rh.x86_64.rpm +[pv-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-rc.1/powershell-7.3.0-rc.1-osx-x64.pkg +[pv-macos-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-rc.1/powershell-7.3.0-rc.1-osx-arm64.pkg +[pv-winarm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-rc.1/PowerShell-7.3.0-rc.1-win-arm64.zip +[pv-winx86-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-rc.1/PowerShell-7.3.0-rc.1-win-x86.zip +[pv-winx64-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-rc.1/PowerShell-7.3.0-rc.1-win-x64.zip +[pv-macos-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-rc.1/powershell-7.3.0-rc.1-osx-x64.tar.gz +[pv-macos-tar-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-rc.1/powershell-7.3.0-rc.1-osx-arm64.tar.gz +[pv-linux-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-rc.1/powershell-7.3.0-rc.1-linux-x64.tar.gz +[pv-arm32]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-rc.1/powershell-7.3.0-rc.1-linux-arm32.tar.gz +[pv-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-rc.1/powershell-7.3.0-rc.1-linux-arm64.tar.gz [pv-snap]: https://snapcraft.io/powershell-preview [in-windows]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-windows diff --git a/tools/metadata.json b/tools/metadata.json index 4891e611488..30945bacb99 100644 --- a/tools/metadata.json +++ b/tools/metadata.json @@ -1,6 +1,6 @@ { "StableReleaseTag": "v7.2.7", - "PreviewReleaseTag": "v7.3.0-preview.8", + "PreviewReleaseTag": "v7.3.0-rc.1", "ServicingReleaseTag": "v7.0.13", "ReleaseTag": "v7.2.7", "LTSReleaseTag" : ["v7.2.7", "v7.0.13"], From 6c4f27eec137c7fd98e5dbd07cc920bd24024035 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Thu, 27 Oct 2022 09:36:11 -0700 Subject: [PATCH 148/779] Remove unused resource strings from `SessionStateStrings` (#18394) --- .../resources/SessionStateStrings.resx | 90 ------------------- 1 file changed, 90 deletions(-) diff --git a/src/System.Management.Automation/resources/SessionStateStrings.resx b/src/System.Management.Automation/resources/SessionStateStrings.resx index f5d817ccd02..72af3dfea4c 100644 --- a/src/System.Management.Automation/resources/SessionStateStrings.resx +++ b/src/System.Management.Automation/resources/SessionStateStrings.resx @@ -138,9 +138,6 @@ Attempting to perform the ClearItem operation on the '{0}' provider failed for path '{1}'. {2} - - The dynamic parameters for the ClearItem operation cannot be retrieved from the '{0}' provider for path '{1}'. {2} - Attempting to perform the InvokeDefaultAction operation on the '{0}' provider failed for path '{1}'. {2} @@ -159,15 +156,9 @@ Attempting to perform the IsItemContainer operation on the '{0}' provider failed for path '{1}'. {2} - - The dynamic parameters for the IsItemContainer cannot be retrieved from the '{0}' provider for path '{1}'. {2} - Attempting to perform the RemoveItem operation on the '{0}' provider failed for path '{1}'. {2} - - The dynamic parameters for the RemoveItem operation cannot be retrieved from the '{0}' provider for path '{1}'. {2} - Attempting to perform the GetChildItems operation on the '{0}' provider failed for path '{1}'. {2} @@ -309,15 +300,9 @@ Attempting to perform the SetSecurityDescriptor operation on the '{0}' provider failed for path '{1}'. {2} - - This provider does not support security descriptor related operations. - Attempting to perform the Start operation on the '{0}' provider failed. {1} - - Attempting to perform the StartDynamicParameters operation on the '{0}' provider failed for the path '{1}'. {2} - Attempting to perform the InitializeDefaultDrives operation on the '{0}' provider failed. @@ -333,9 +318,6 @@ Drive '{0}' cannot be removed because the provider '{1}' prevented it. - - The path '{0}' is shorter than the base path '{1}'. - The path '{0}' referred to an item that was outside the base '{1}'. @@ -393,27 +375,15 @@ Alias {0} cannot be modified because it is read-only. - - Filter {0} cannot be modified because it is constant. - - - Filter {0} cannot be modified because it is read-only. - Cannot modify function {0} because it is constant. Cannot modify function {0} because it is read-only. - - Cannot modify variable {0} because it is a constant. - Alias {0} cannot be made constant after it has been created. Aliases can only be made constant at creation time. - - Existing filter {0} cannot be made constant. Filters can be made constant only at creation time. - Existing function {0} cannot be made constant. Functions can be made constant only at creation time. @@ -423,9 +393,6 @@ The AllScope option cannot be removed from the alias '{0}'. - - The AllScope option cannot be removed from the filter '{0}'. - The AllScope option cannot be removed from the function '{0}'. @@ -507,9 +474,6 @@ Global scope cannot be removed. - - Too many scopes have been created. - The scope number '{0}' exceeds the number of active scopes. @@ -627,72 +591,18 @@ Drive that maps to the temporary directory path for the current user - - The path is not in the correct format. Paths can contain only provider and drive names separated by slashes or backslashes. - - - Cannot remove provider because removal of providers is not supported. - - - Cannot create provider because creation of new providers is not supported. - - - Drive that contains the list of loaded providers and their drives - - - The root of the drive '{0}' cannot be modified. - - - Cannot create a new provider because type '{0}' is not of type "provider". - - - Cannot set the new item value because the parameter "value" must be of the type ProviderInfo when "type" is specified as "provider". - - - Cannot create a new drive because type '{0}' is not of type "drive". - - - Cannot set new item value because the parameter "value" must be of type PSDriveInfo when "type" is specified as "drive". - - - Cannot create new drive because the name specified in the PSDriveInfo '{0}' does not match the drive name specified in the path '{1}'. - - - The provider name specified in the PSDriveInfo '{0}' does not match the provider name specified in the path '{1}'. - - - Cannot remove the drive root in this way. Use "Remove-PSDrive" to remove this drive. - Link '{0}' cannot be created because Target was not specified. References to the null variable always return the null value. Assignments have no effect. - - Maximum number of errors to retain in a session - - - Maximum number of drives allowed in a session - - - Maximum number of aliases allowed in a session - - - Maximum number of functions allowed in a session - - - Maximum number of variables allowed in a session - Maximum number of history objects to retain in a session Cannot rename function because function {0} is read-only or constant. - - Cannot rename filter because filter {0} is read-only or constant. - Cannot rename alias because alias {0} is read-only or constant. From dd477bb15f5682ef99ad7c4c4c3c82003db6d24f Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Thu, 27 Oct 2022 09:40:10 -0700 Subject: [PATCH 149/779] Allow two-digit revisions in `vPack` package validation pattern (#18392) --- tools/releaseBuild/azureDevOps/templates/vpackReleaseJob.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/releaseBuild/azureDevOps/templates/vpackReleaseJob.yml b/tools/releaseBuild/azureDevOps/templates/vpackReleaseJob.yml index c8988b90106..a51818e4acb 100644 --- a/tools/releaseBuild/azureDevOps/templates/vpackReleaseJob.yml +++ b/tools/releaseBuild/azureDevOps/templates/vpackReleaseJob.yml @@ -59,7 +59,7 @@ jobs: - pwsh: | Get-ChildItem $(System.ArtifactsDirectory)\* -recurse -include *.zip, *.msi | ForEach-Object { - if($_.Name -match 'PowerShell-\d\.\d\.\d\-([a-z]*.\d+\-)?win\-(${{ parameters.architecture }})\.(zip){1}') + if($_.Name -match 'PowerShell-\d+\.\d+\.\d+\-([a-z]*.\d+\-)?win\-(${{ parameters.architecture }})\.(zip){1}') { $destDir = "$(System.ArtifactsDirectory)\vpack${{ parameters.architecture }}" $null = new-item -ItemType Directory -Path $destDir From dd884459c1ccafc3fe7615d53a0ffa7b9646c571 Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Thu, 27 Oct 2022 17:42:33 +0100 Subject: [PATCH 150/779] Use generic `GetValues`, `GetNames` enum methods (#18391) --- .../commands/management/GetComputerInfoCommand.cs | 2 +- .../commands/utility/ConvertFrom-SddlString.cs | 2 +- .../host/msh/CommandLineParameterParser.cs | 2 +- src/System.Management.Automation/engine/CommandMetadata.cs | 2 +- src/System.Management.Automation/engine/TypeMetadata.cs | 2 +- .../engine/remoting/fanin/PriorityCollection.cs | 4 ++-- 6 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs index a57756bbf75..9c1c2c5362f 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs @@ -1890,7 +1890,7 @@ private static OSProductSuite[] MakeProductSuites(uint? suiteMask) var mask = suiteMask.Value; var list = new List(); - foreach (OSProductSuite suite in Enum.GetValues(typeof(OSProductSuite))) + foreach (OSProductSuite suite in Enum.GetValues()) if ((mask & (uint)suite) != 0) list.Add(suite); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-SddlString.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-SddlString.cs index 22c1e5ef46b..f4cddb37bec 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-SddlString.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-SddlString.cs @@ -70,7 +70,7 @@ private static List GetApplicableAccessRights(int accessMask, AccessRigh } else { - foreach (AccessRightTypeNames member in Enum.GetValues(typeof(AccessRightTypeNames))) + foreach (AccessRightTypeNames member in Enum.GetValues()) { typesToExamine.Add(GetRealAccessRightType(member)); } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs index a946051995f..c3e2e196cbb 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs @@ -1200,7 +1200,7 @@ private void SetCommandLineError(string msg, bool showHelp = false, bool showBan private void ParseFormat(string[] args, ref int i, ref Serialization.DataFormat format, string resourceStr) { StringBuilder sb = new StringBuilder(); - foreach (string s in Enum.GetNames(typeof(Serialization.DataFormat))) + foreach (string s in Enum.GetNames()) { sb.Append(s); sb.Append(Environment.NewLine); diff --git a/src/System.Management.Automation/engine/CommandMetadata.cs b/src/System.Management.Automation/engine/CommandMetadata.cs index a9094f54b36..f7e74f00cb8 100644 --- a/src/System.Management.Automation/engine/CommandMetadata.cs +++ b/src/System.Management.Automation/engine/CommandMetadata.cs @@ -1249,7 +1249,7 @@ private static CommandMetadata GetRestrictedGetHelp() // This should only be called with 1 valid category ParameterMetadata categoryParameter = new ParameterMetadata("Category", typeof(string[])); - categoryParameter.Attributes.Add(new ValidateSetAttribute(Enum.GetNames(typeof(HelpCategory)))); + categoryParameter.Attributes.Add(new ValidateSetAttribute(Enum.GetNames())); categoryParameter.Attributes.Add(new ValidateCountAttribute(0, 1)); return GetRestrictedCmdlet("Get-Help", null, "https://go.microsoft.com/fwlink/?LinkID=113316", nameParameter, categoryParameter); diff --git a/src/System.Management.Automation/engine/TypeMetadata.cs b/src/System.Management.Automation/engine/TypeMetadata.cs index 3c2515183f1..926b07fb15a 100644 --- a/src/System.Management.Automation/engine/TypeMetadata.cs +++ b/src/System.Management.Automation/engine/TypeMetadata.cs @@ -983,7 +983,7 @@ private static string GetProxyAttributeData(Attribute attrib, string prefix) /* TODO: Validate Pattern dont support Options in ScriptCmdletText. StringBuilder regexOps = new System.Text.StringBuilder(); string or = string.Empty; - string[] regexOptionEnumValues = Enum.GetNames(typeof(System.Text.RegularExpressions.RegexOptions)); + string[] regexOptionEnumValues = Enum.GetNames(); foreach (string regexOption in regexOptionEnumValues) { diff --git a/src/System.Management.Automation/engine/remoting/fanin/PriorityCollection.cs b/src/System.Management.Automation/engine/remoting/fanin/PriorityCollection.cs index ce9b2fe09cb..f13970274b6 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/PriorityCollection.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/PriorityCollection.cs @@ -98,7 +98,7 @@ internal Fragmentor Fragmentor Dbg.Assert(value != null, "Fragmentor cannot be null."); _fragmentor = value; // create serialized streams using fragment size. - string[] names = Enum.GetNames(typeof(DataPriorityType)); + string[] names = Enum.GetNames(); _dataToBeSent = new SerializedDataStream[names.Length]; _dataSyncObjects = new object[names.Length]; for (int i = 0; i < names.Length; i++) @@ -765,7 +765,7 @@ internal class PriorityReceiveDataCollection : IDisposable internal PriorityReceiveDataCollection(Fragmentor defragmentor, bool createdByClientTM) { _defragmentor = defragmentor; - string[] names = Enum.GetNames(typeof(DataPriorityType)); + string[] names = Enum.GetNames(); _recvdData = new ReceiveDataCollection[names.Length]; for (int index = 0; index < names.Length; index++) { From 8965af3d5201b103971b00f040c13e90ca7b6de6 Mon Sep 17 00:00:00 2001 From: Ilya Date: Fri, 28 Oct 2022 03:25:41 +0500 Subject: [PATCH 151/779] Remove some static constants from `Utils.Separators` (#18154) --- .../security/SecureStringCommands.cs | 2 +- .../DscSupport/CimDSCParser.cs | 6 +++--- .../common/FormatViewGenerator_Complex.cs | 2 +- .../CommandCompletion/CommandCompletion.cs | 2 +- .../CommandCompletion/CompletionAnalysis.cs | 18 ++++++++-------- .../CommandCompletion/CompletionCompleters.cs | 10 ++++----- .../engine/CommandDiscovery.cs | 10 ++++----- .../engine/CommandSearcher.cs | 2 +- .../engine/LanguagePrimitives.cs | 2 +- .../engine/Modules/ModuleCmdletBase.cs | 4 ++-- .../engine/Modules/ModuleIntrinsics.cs | 6 +++--- .../engine/MshSnapinQualifiedName.cs | 2 +- .../engine/NativeCommandProcessor.cs | 2 +- .../engine/PSVersionInfo.cs | 2 +- .../engine/ParameterSetInfo.cs | 2 +- .../engine/Utils.cs | 21 +++---------------- .../remoting/commands/CustomShellCommands.cs | 4 ++-- .../remoting/common/RunspaceConnectionInfo.cs | 8 +++---- .../engine/remoting/common/psstreamobject.cs | 2 +- .../fanin/InitialSessionStateProvider.cs | 8 +++---- .../engine/serialization.cs | 4 ++-- .../help/BaseCommandHelpInfo.cs | 4 ++-- .../help/DscResourceHelpProvider.cs | 2 +- .../help/HelpFileHelpProvider.cs | 3 +-- .../help/MamlNode.cs | 4 ++-- .../namespaces/FileSystemProvider.cs | 2 +- .../namespaces/ProviderBase.cs | 2 +- 27 files changed, 60 insertions(+), 76 deletions(-) diff --git a/src/Microsoft.PowerShell.Security/security/SecureStringCommands.cs b/src/Microsoft.PowerShell.Security/security/SecureStringCommands.cs index 821fe608efa..c727476c0a3 100644 --- a/src/Microsoft.PowerShell.Security/security/SecureStringCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/SecureStringCommands.cs @@ -326,7 +326,7 @@ protected override void ProcessRecord() // representation, then parse it into its components. byte[] inputBytes = Convert.FromBase64String(remainingData); string dataPackage = System.Text.Encoding.Unicode.GetString(inputBytes); - string[] dataElements = dataPackage.Split(Utils.Separators.Pipe); + string[] dataElements = dataPackage.Split('|'); if (dataElements.Length == 3) { diff --git a/src/System.Management.Automation/DscSupport/CimDSCParser.cs b/src/System.Management.Automation/DscSupport/CimDSCParser.cs index a91691535d4..2fd205cd415 100644 --- a/src/System.Management.Automation/DscSupport/CimDSCParser.cs +++ b/src/System.Management.Automation/DscSupport/CimDSCParser.cs @@ -918,7 +918,7 @@ private static CimClass MyClassCallback(string serverName, string namespaceName, { foreach (KeyValuePair cimClass in ClassCache) { - string cachedClassName = cimClass.Key.Split(Utils.Separators.Backslash)[IndexClassName]; + string cachedClassName = cimClass.Key.Split('\\')[IndexClassName]; if (string.Equals(cachedClassName, className, StringComparison.OrdinalIgnoreCase)) { return cimClass.Value.CimClassInstance; @@ -1099,7 +1099,7 @@ private static string GetModuleQualifiedResourceName(string moduleName, string m private static List> FindResourceInCache(string moduleName, string className, string resourceName) { return (from cacheEntry in ClassCache - let splittedName = cacheEntry.Key.Split(Utils.Separators.Backslash) + let splittedName = cacheEntry.Key.Split('\\') let cachedClassName = splittedName[IndexClassName] let cachedModuleName = splittedName[IndexModuleName] let cachedResourceName = splittedName[IndexFriendlyName] @@ -1295,7 +1295,7 @@ public static Collection GetCachedKeywords() foreach (KeyValuePair cachedClass in ClassCache) { - string[] splittedName = cachedClass.Key.Split(Utils.Separators.Backslash); + string[] splittedName = cachedClass.Key.Split('\\'); string moduleName = splittedName[IndexModuleName]; string moduleVersion = splittedName[IndexModuleVersion]; diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Complex.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Complex.cs index 77aa2da6e4d..cae35b7b28c 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Complex.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Complex.cs @@ -714,7 +714,7 @@ private string GetObjectDisplayName(PSObject so) if (_complexSpecificParameters.classDisplay == ComplexSpecificParameters.ClassInfoDisplay.shortName) { // get the last token in the full name - string[] arr = typeNames[0].Split(Utils.Separators.Dot); + string[] arr = typeNames[0].Split('.'); if (arr.Length > 0) return arr[arr.Length - 1]; } diff --git a/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs b/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs index 7c700317e87..d0d248fa50a 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs @@ -707,7 +707,7 @@ private static bool PSv2IsCommandLikeCmdlet(string lastWord, out bool isSnapinSp { isSnapinSpecified = false; - string[] cmdletParts = lastWord.Split(Utils.Separators.Backslash); + string[] cmdletParts = lastWord.Split('\\'); if (cmdletParts.Length == 1) { return s_cmdletTabRegex.IsMatch(lastWord); diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs index 24e6873966f..a11d6ca6763 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs @@ -156,7 +156,7 @@ internal static AstAnalysisContext ExtractAstContext(Ast inputAst, Token[] input searchNestedScriptBlocks: true).ToList(); // If the last ast is an unnamed block that starts with "param" the cursor is inside a param block. - // To avoid adding special handling to all the completers that look at the last ast, we remove it here because it's not useful for completion. + // To avoid adding special handling to all the completers that look at the last ast, we remove it here because it's not useful for completion. if (relatedAsts[^1].Extent.Text.StartsWith("param", StringComparison.OrdinalIgnoreCase) && relatedAsts[^1] is NamedBlockAst namedBlock && namedBlock.Unnamed) { @@ -905,7 +905,7 @@ internal List GetResultHelper(CompletionContext completionCont { switch (completionContext.TokenBeforeCursor.Kind) { - + case TokenKind.Dot: case TokenKind.ColonColon: case TokenKind.QuestionDot: @@ -940,7 +940,7 @@ internal List GetResultHelper(CompletionContext completionCont result = CompletionCompleters.CompleteComparisonOperatorValues(completionContext, binaryExpression.Left); } break; - + case TokenKind.LBracket: if (lastAst.Parent is IndexExpressionAst indexExpression) { @@ -949,7 +949,7 @@ internal List GetResultHelper(CompletionContext completionCont result = CompletionCompleters.CompleteIndexExpression(completionContext, indexExpression.Target); } break; - + default: break; } @@ -1102,7 +1102,7 @@ internal List GetResultHelper(CompletionContext completionCont typeNameToComplete = FindTypeNameToComplete(typeConstraintAst.TypeName, _cursorPosition); } } - + if (typeNameToComplete is null && tokenAtCursor?.TokenFlags.HasFlag(TokenFlags.TypeName) == true) { typeNameToComplete = new TypeName(tokenAtCursor.Extent, tokenAtCursor.Text); @@ -1263,7 +1263,7 @@ private static string GetFirstLineSubString(string stringToComplete, out bool ha hasNewLine = false; if (!string.IsNullOrEmpty(stringToComplete)) { - var index = stringToComplete.IndexOfAny(Utils.Separators.CrLf); + var index = stringToComplete.AsSpan().IndexOfAny('\r', '\n'); if (index >= 0) { stringToComplete = stringToComplete.Substring(0, index); @@ -2042,7 +2042,7 @@ private static List GetResultForIdentifier(CompletionContext c { if (cursorAst.Extent.EndOffset == tokenAtCursor.Extent.StartOffset) { - if (tokenAtCursorText.IndexOfAny(Utils.Separators.Directory) == 0) + if (tokenAtCursorText.AsSpan().IndexOfAny('\\', '/') == 0) { string wordToComplete = CompletionCompleters.ConcatenateStringPathArguments(cursorAst as CommandElementAst, tokenAtCursorText, completionContext); @@ -2292,7 +2292,7 @@ private static List GetResultForIdentifier(CompletionContext c completionContext.WordToComplete = wordToComplete; } } - else if (tokenAtCursorText.IndexOfAny(Utils.Separators.Directory) == 0) + else if (tokenAtCursorText.AsSpan().IndexOfAny('\\', '/') == 0) { var command = lastAst.Parent as CommandBaseAst; if (command != null && command.Redirections.Count > 0) @@ -2384,7 +2384,7 @@ private static List GetResultForAttributeArgument(CompletionCo // Ignore getter-only properties and properties that have already been set. if (!property.CanWrite || existingArguments.Contains(property.Name)) { - continue; + continue; } if (property.Name.StartsWith(argName, StringComparison.OrdinalIgnoreCase)) diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs index 3fbbf928ca8..14b662aa419 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs @@ -890,7 +890,7 @@ internal static List CompleteCommandArgument(CompletionContext partialPathAst.StringConstantType == StringConstantType.BareWord && secondToLastAst.Extent.EndLineNumber == partialPathAst.Extent.StartLineNumber && secondToLastAst.Extent.EndColumnNumber == partialPathAst.Extent.StartColumnNumber && - partialPathAst.Value.IndexOfAny(Utils.Separators.Directory) == 0) + partialPathAst.Value.AsSpan().IndexOfAny('\\', '/') == 0) { var secondToLastStringConstantAst = secondToLastAst as StringConstantExpressionAst; var secondToLastExpandableStringAst = secondToLastAst as ExpandableStringExpressionAst; @@ -1270,7 +1270,7 @@ internal static List CompleteCommandArgument(CompletionContext // Treat it as the file name completion // Handle this scenario: & 'c:\a b'\ string fileName = pathAst.Value; - if (commandAst.InvocationOperator != TokenKind.Unknown && fileName.IndexOfAny(Utils.Separators.Directory) == 0 && + if (commandAst.InvocationOperator != TokenKind.Unknown && fileName.AsSpan().IndexOfAny('\\', '/') == 0 && commandAst.CommandElements.Count == 2 && commandAst.CommandElements[0] is StringConstantExpressionAst && commandAst.CommandElements[0].Extent.EndLineNumber == expressionAst.Extent.StartLineNumber && commandAst.CommandElements[0].Extent.EndColumnNumber == expressionAst.Extent.StartColumnNumber) @@ -2924,7 +2924,7 @@ private static void NativeCompletionCimNamespace( string prefixOfChildNamespace = string.Empty; if (!string.IsNullOrEmpty(context.WordToComplete)) { - int lastSlashOrBackslash = context.WordToComplete.LastIndexOfAny(Utils.Separators.Directory); + int lastSlashOrBackslash = context.WordToComplete.AsSpan().LastIndexOfAny('\\', '/'); if (lastSlashOrBackslash != (-1)) { containerNamespace = context.WordToComplete.Substring(0, lastSlashOrBackslash); @@ -4395,7 +4395,7 @@ internal static IEnumerable CompleteFilename(CompletionContext // specified a drive or portion of the path. var executionContext = context.ExecutionContext; var defaultRelative = string.IsNullOrWhiteSpace(wordToComplete) - || (wordToComplete.IndexOfAny(Utils.Separators.Directory) != 0 && + || (wordToComplete.AsSpan().IndexOfAny('\\', '/') != 0 && !Regex.Match(wordToComplete, @"^~[\\/]+.*").Success && !executionContext.LocationGlobber.IsAbsolutePath(wordToComplete, out _)); var relativePaths = context.GetOption("RelativePaths", @default: defaultRelative); @@ -6137,7 +6137,7 @@ internal static void CompleteMemberByInferredType( string memberName, Func filter, bool isStatic, - HashSet excludedMembers = null, + HashSet excludedMembers = null, bool addMethodParenthesis = true) { bool extensionMethodsAdded = false; diff --git a/src/System.Management.Automation/engine/CommandDiscovery.cs b/src/System.Management.Automation/engine/CommandDiscovery.cs index 9ce60e56c04..0dca804e648 100644 --- a/src/System.Management.Automation/engine/CommandDiscovery.cs +++ b/src/System.Management.Automation/engine/CommandDiscovery.cs @@ -1045,7 +1045,7 @@ private static CommandInfo TryModuleAutoDiscovery(string commandName, // If commandName had a slash, it was module-qualified or path-qualified. // In that case, we should not return anything (module-qualified is handled // by the previous call to TryModuleAutoLoading(). - int colonOrBackslash = commandName.IndexOfAny(Utils.Separators.ColonOrBackslash); + int colonOrBackslash = commandName.AsSpan().IndexOfAny('\\', ':'); if (colonOrBackslash != -1) return null; @@ -1139,7 +1139,7 @@ private static CommandInfo TryModuleAutoLoading(string commandName, ExecutionCon CommandInfo result = null; // If commandName was module-qualified. In that case, we should load the module. - var colonOrBackslash = commandName.IndexOfAny(Utils.Separators.ColonOrBackslash); + var colonOrBackslash = commandName.AsSpan().IndexOfAny('\\', ':'); // If we don't see '\', there is no module specified, so no module to load. // If we see ':' before '\', then we probably have a drive qualified path, not a module name @@ -1150,7 +1150,7 @@ private static CommandInfo TryModuleAutoLoading(string commandName, ExecutionCon string moduleName; // Now we check if there exists the second '\' - var secondBackslash = moduleCommandName.IndexOfAny(Utils.Separators.Backslash); + var secondBackslash = moduleCommandName.IndexOf('\\'); if (secondBackslash == -1) { moduleName = commandName.Substring(0, colonOrBackslash); @@ -1306,7 +1306,7 @@ internal LookupPathCollection GetLookupDirectoryPaths() if (_pathCacheKey != null) { - string[] tokenizedPath = _pathCacheKey.Split(Utils.Separators.PathSeparator, StringSplitOptions.RemoveEmptyEntries); + string[] tokenizedPath = _pathCacheKey.Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries); _cachedPath = new Collection(); foreach (string directory in tokenizedPath) @@ -1398,7 +1398,7 @@ private static void InitPathExtCache(string pathExt) lock (s_lockObject) { s_cachedPathExtCollection = pathExt != null - ? pathExt.ToLower().Split(Utils.Separators.PathSeparator, StringSplitOptions.RemoveEmptyEntries) + ? pathExt.ToLower().Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries) : Array.Empty(); s_cachedPathExtCollectionWithPs1 = new string[s_cachedPathExtCollection.Length + 1]; s_cachedPathExtCollectionWithPs1[0] = StringLiterals.PowerShellScriptFileExtension; diff --git a/src/System.Management.Automation/engine/CommandSearcher.cs b/src/System.Management.Automation/engine/CommandSearcher.cs index 3b1490cb3ab..63bc666e123 100644 --- a/src/System.Management.Automation/engine/CommandSearcher.cs +++ b/src/System.Management.Automation/engine/CommandSearcher.cs @@ -1439,7 +1439,7 @@ private static CanDoPathLookupResult CanDoPathLookup(string possiblePath) // If the command contains any path separators, we can't // do the path lookup - if (possiblePath.IndexOfAny(Utils.Separators.Directory) != -1) + if (possiblePath.AsSpan().IndexOfAny('\\', '/') != -1) { result = CanDoPathLookupResult.DirectorySeparator; break; diff --git a/src/System.Management.Automation/engine/LanguagePrimitives.cs b/src/System.Management.Automation/engine/LanguagePrimitives.cs index 283ea28dd96..028bfda42a8 100644 --- a/src/System.Management.Automation/engine/LanguagePrimitives.cs +++ b/src/System.Management.Automation/engine/LanguagePrimitives.cs @@ -2146,7 +2146,7 @@ protected static object BaseConvertFrom(object sourceValue, Type destinationType } else { - sourceValueEntries = sourceValueString.Split(Utils.Separators.Comma); + sourceValueEntries = sourceValueString.Split(','); fromValuePatterns = new WildcardPattern[sourceValueEntries.Length]; for (int i = 0; i < sourceValueEntries.Length; i++) { diff --git a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs index dc5f500f59b..e95c9cc0984 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs @@ -381,7 +381,7 @@ internal bool LoadUsingModulePath( module = LoadUsingMultiVersionModuleBase(qualifiedPath, manifestProcessingFlags, options, out found); if (!found) { - if (name.IndexOfAny(Utils.Separators.Directory) == -1) + if (name.AsSpan().IndexOfAny('\\', '/') == -1) { qualifiedPath = Path.Combine(qualifiedPath, fileBaseName); } @@ -1014,7 +1014,7 @@ private IEnumerable GetModuleForRootedPaths(List modulePat { bool containsWildCards = false; - string modulePath = mp.TrimEnd(Utils.Separators.Backslash); + string modulePath = mp.TrimEnd('\\'); // If the given path contains wildcards, we won't throw error if no match module path is found. if (WildcardPattern.ContainsWildcardCharacters(modulePath)) diff --git a/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs b/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs index 6c5eae34968..10b5ffa34e3 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs @@ -1092,7 +1092,7 @@ private static int PathContainsSubstring(string pathToScan, string pathToLookFor Diagnostics.Assert(pathToLookFor != null, "pathToLookFor should not be null according to contract of the function"); int pos = 0; // position of the current substring in pathToScan - string[] substrings = pathToScan.Split(Utils.Separators.PathSeparator, StringSplitOptions.None); // we want to process empty entries + string[] substrings = pathToScan.Split(Path.PathSeparator, StringSplitOptions.None); // we want to process empty entries string goodPathToLookFor = pathToLookFor.Trim().TrimEnd(Path.DirectorySeparatorChar); // trailing backslashes and white-spaces will mess up equality comparison foreach (string substring in substrings) { @@ -1131,7 +1131,7 @@ private static string AddToPath(string basePath, string pathToAdd, int insertPos if (!string.IsNullOrEmpty(pathToAdd)) // we don't want to append empty paths { - foreach (string subPathToAdd in pathToAdd.Split(Utils.Separators.PathSeparator, StringSplitOptions.RemoveEmptyEntries)) // in case pathToAdd is a 'combined path' (semicolon-separated) + foreach (string subPathToAdd in pathToAdd.Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries)) // in case pathToAdd is a 'combined path' (semicolon-separated) { int position = PathContainsSubstring(result.ToString(), subPathToAdd); // searching in effective 'result' value ensures that possible duplicates in pathsToAdd are handled correctly if (position == -1) // subPathToAdd not found - add it @@ -1351,7 +1351,7 @@ internal static IEnumerable GetModulePath(bool includeSystemModulePath, if (!string.IsNullOrWhiteSpace(modulePathString)) { - foreach (string envPath in modulePathString.Split(Utils.Separators.PathSeparator, StringSplitOptions.RemoveEmptyEntries)) + foreach (string envPath in modulePathString.Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries)) { var processedPath = ProcessOneModulePath(context, envPath, processedPathSet); if (processedPath != null) diff --git a/src/System.Management.Automation/engine/MshSnapinQualifiedName.cs b/src/System.Management.Automation/engine/MshSnapinQualifiedName.cs index 08115648527..b4cf7c16eef 100644 --- a/src/System.Management.Automation/engine/MshSnapinQualifiedName.cs +++ b/src/System.Management.Automation/engine/MshSnapinQualifiedName.cs @@ -68,7 +68,7 @@ private PSSnapinQualifiedName(string[] splitName) { if (name == null) return null; - string[] splitName = name.Split(Utils.Separators.Backslash); + string[] splitName = name.Split('\\'); if (splitName.Length == 0 || splitName.Length > 2) return null; var result = new PSSnapinQualifiedName(splitName); diff --git a/src/System.Management.Automation/engine/NativeCommandProcessor.cs b/src/System.Management.Automation/engine/NativeCommandProcessor.cs index 65903305efb..e89faac4b05 100644 --- a/src/System.Management.Automation/engine/NativeCommandProcessor.cs +++ b/src/System.Management.Automation/engine/NativeCommandProcessor.cs @@ -1576,7 +1576,7 @@ private bool IsExecutable(string path) } else { - extensionList = pathext.Split(Utils.Separators.Semicolon); + extensionList = pathext.Split(';'); } foreach (string extension in extensionList) diff --git a/src/System.Management.Automation/engine/PSVersionInfo.cs b/src/System.Management.Automation/engine/PSVersionInfo.cs index 620577d8d43..009f6704fad 100644 --- a/src/System.Management.Automation/engine/PSVersionInfo.cs +++ b/src/System.Management.Automation/engine/PSVersionInfo.cs @@ -718,7 +718,7 @@ public override string ToString() { StringBuilder result = new StringBuilder(); - result.Append(Major).Append(Utils.Separators.Dot).Append(Minor).Append(Utils.Separators.Dot).Append(Patch); + result.Append(Major).Append('.').Append(Minor).Append('.').Append(Patch); if (!string.IsNullOrEmpty(PreReleaseLabel)) { diff --git a/src/System.Management.Automation/engine/ParameterSetInfo.cs b/src/System.Management.Automation/engine/ParameterSetInfo.cs index 74745fca6da..a2bbd69b7d1 100644 --- a/src/System.Management.Automation/engine/ParameterSetInfo.cs +++ b/src/System.Management.Automation/engine/ParameterSetInfo.cs @@ -284,7 +284,7 @@ internal static string GetParameterTypeString(Type type, IEnumerable parameterTypeString = typeName.PSTypeName; // Drop the namespace from the typename, if any. - var lastDotIndex = parameterTypeString.LastIndexOfAny(Utils.Separators.Dot); + var lastDotIndex = parameterTypeString.LastIndexOf('.'); if (lastDotIndex != -1 && lastDotIndex + 1 < parameterTypeString.Length) { parameterTypeString = parameterTypeString.Substring(lastDotIndex + 1); diff --git a/src/System.Management.Automation/engine/Utils.cs b/src/System.Management.Automation/engine/Utils.cs index 57463a6f330..6512093c5f5 100644 --- a/src/System.Management.Automation/engine/Utils.cs +++ b/src/System.Management.Automation/engine/Utils.cs @@ -1392,7 +1392,7 @@ private static void WorkItemCallback(object callBackArgs) /// Command name and as appropriate Module name in out parameter. internal static string ParseCommandName(string commandName, out string moduleName) { - var names = commandName.Split(Separators.Backslash, 2); + var names = commandName.Split('\\', 2); if (names.Length == 2) { moduleName = names[0]; @@ -1416,25 +1416,10 @@ private static class EmptyReadOnlyCollectionHolder internal static class Separators { - internal static readonly char[] Backslash = new char[] { '\\' }; internal static readonly char[] Directory = new char[] { '\\', '/' }; internal static readonly char[] DirectoryOrDrive = new char[] { '\\', '/', ':' }; - - internal static readonly char[] Colon = new char[] { ':' }; - internal static readonly char[] Dot = new char[] { '.' }; - internal static readonly char[] Pipe = new char[] { '|' }; - internal static readonly char[] Comma = new char[] { ',' }; - internal static readonly char[] Semicolon = new char[] { ';' }; - internal static readonly char[] StarOrQuestion = new char[] { '*', '?' }; - internal static readonly char[] ColonOrBackslash = new char[] { '\\', ':' }; - internal static readonly char[] PathSeparator = new char[] { Path.PathSeparator }; - - internal static readonly char[] QuoteChars = new char[] { '\'', '"' }; - internal static readonly char[] Space = new char[] { ' ' }; - internal static readonly char[] QuotesSpaceOrTab = new char[] { ' ', '\t', '\'', '"' }; internal static readonly char[] SpaceOrTab = new char[] { ' ', '\t' }; - internal static readonly char[] Newline = new char[] { '\n' }; - internal static readonly char[] CrLf = new char[] { '\r', '\n' }; + internal static readonly char[] StarOrQuestion = new char[] { '*', '?' }; // (Copied from System.IO.Path so we can call TrimEnd in the same way that Directory.EnumerateFiles would on the search patterns). // Trim trailing white spaces, tabs etc but don't be aggressive in removing everything that has UnicodeCategory of trailing space. @@ -1506,7 +1491,7 @@ internal static bool IsComObject(object obj) return oldMode; } - + internal static string DisplayHumanReadableFileSize(long bytes) { return bytes switch diff --git a/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs b/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs index 76601ff6dfb..557073ae699 100644 --- a/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs +++ b/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs @@ -1373,7 +1373,7 @@ internal static PSCredential CreateGMSAAccountCredentials(string gmsaAccount) Dbg.Assert(!string.IsNullOrEmpty(gmsaAccount), "Should not be null or empty string."); // Validate account name form (must be DomainName\UserName) - var parts = gmsaAccount.Split(Utils.Separators.Backslash); + var parts = gmsaAccount.Split('\\'); if ((parts.Length != 2) || (string.IsNullOrEmpty(parts[0])) || (string.IsNullOrEmpty(parts[1])) @@ -5273,7 +5273,7 @@ protected override void BeginProcessing() validator = null; // Convert DOMAIN\user to the upn (user@DOMAIN) - string[] upnComponents = this.Username.Split(Utils.Separators.Backslash); + string[] upnComponents = this.Username.Split('\\'); if (upnComponents.Length == 2) { this.Username = upnComponents[1] + "@" + upnComponents[0]; diff --git a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs index 50853d86e7a..c4244c2864a 100644 --- a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs +++ b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs @@ -1944,7 +1944,7 @@ public sealed class SSHConnectionInfo : RunspaceConnectionInfo /// Default value for subsystem. /// private const string DefaultSubsystem = "powershell"; - + /// /// Default value is infinite timeout. /// @@ -2257,7 +2257,7 @@ internal int StartSSHProcess( // if UserName is not set, then ssh will use User from ssh_config if defined else the environment user by default if (!string.IsNullOrEmpty(this.UserName)) { - var parts = this.UserName.Split(Utils.Separators.Backslash); + var parts = this.UserName.Split('\\'); if (parts.Length == 2) { // convert DOMAIN\user to user@DOMAIN @@ -2279,9 +2279,9 @@ internal int StartSSHProcess( } // pass "-o option=value" command line argument to ssh if options are provided - if (this.Options != null) + if (this.Options != null) { - foreach (DictionaryEntry pair in this.Options) + foreach (DictionaryEntry pair in this.Options) { startInfo.ArgumentList.Add(string.Format(CultureInfo.InvariantCulture, @"-o {0}={1}", pair.Key, pair.Value)); } diff --git a/src/System.Management.Automation/engine/remoting/common/psstreamobject.cs b/src/System.Management.Automation/engine/remoting/common/psstreamobject.cs index c0052b3df29..6a39d8ed268 100644 --- a/src/System.Management.Automation/engine/remoting/common/psstreamobject.cs +++ b/src/System.Management.Automation/engine/remoting/common/psstreamobject.cs @@ -226,7 +226,7 @@ private static void GetIdentifierInfo(string message, out Guid jobInstanceId, ou computerName = string.Empty; if (message == null) return; - string[] parts = message.Split(Utils.Separators.Colon, 3); + string[] parts = message.Split(':', 3); if (parts.Length != 3) return; diff --git a/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs b/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs index 088685c28e0..8596e87e834 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs @@ -1929,13 +1929,13 @@ private static string GetRoleCapabilityPath(string roleCapability) string moduleName = "*"; if (roleCapability.Contains('\\')) { - string[] components = roleCapability.Split(Utils.Separators.Backslash, 2); + string[] components = roleCapability.Split('\\', 2); moduleName = components[0]; roleCapability = components[1]; } // Go through each directory in the module path - string[] modulePaths = ModuleIntrinsics.GetModulePath().Split(Utils.Separators.PathSeparator); + string[] modulePaths = ModuleIntrinsics.GetModulePath().Split(Path.PathSeparator); foreach (string path in modulePaths) { try @@ -2985,7 +2985,7 @@ internal static class DISCFileValidation }; #endif - // These are configuration options for WSMan (WinRM) endpoint configurations, that + // These are configuration options for WSMan (WinRM) endpoint configurations, that // appearand in .pssc files, but are not part of PowerShell InitialSessionState. private static readonly HashSet UnsupportedConfigOptions = new HashSet(StringComparer.OrdinalIgnoreCase) { @@ -3022,6 +3022,6 @@ internal static void ValidateContents(Hashtable configHash) } #endregion - + #endregion } diff --git a/src/System.Management.Automation/engine/serialization.cs b/src/System.Management.Automation/engine/serialization.cs index 76b7c38b7b3..d3405df91c0 100644 --- a/src/System.Management.Automation/engine/serialization.cs +++ b/src/System.Management.Automation/engine/serialization.cs @@ -3457,7 +3457,7 @@ private PSObject RehydrateCimInstance(PSObject deserializedObject) if ((modifiedPropertiesProperty != null) && (modifiedPropertiesProperty.Value != null)) { string modifiedPropertiesString = modifiedPropertiesProperty.Value.ToString(); - foreach (string nameOfModifiedProperty in modifiedPropertiesString.Split(Utils.Separators.Space)) + foreach (string nameOfModifiedProperty in modifiedPropertiesString.Split(' ')) { namesOfModifiedProperties.Add(nameOfModifiedProperty); } @@ -4055,7 +4055,7 @@ private object ReadDictionary(ContainerType ct, ConsolidatedString InternalTypeN // We assume the hash table is a PowerShell hash table and hence uses // a case insensitive string comparer. If we discover a key collision, // we'll revert back to the default comparer. - + // Find whether original directory was ordered bool isOrdered = InternalTypeNames.Count > 0 && (Deserializer.MaskDeserializationPrefix(InternalTypeNames[0]) == typeof(OrderedDictionary).FullName); diff --git a/src/System.Management.Automation/help/BaseCommandHelpInfo.cs b/src/System.Management.Automation/help/BaseCommandHelpInfo.cs index 5c50094abf3..8a5969e7b35 100644 --- a/src/System.Management.Automation/help/BaseCommandHelpInfo.cs +++ b/src/System.Management.Automation/help/BaseCommandHelpInfo.cs @@ -252,7 +252,7 @@ internal Uri LookupUriFromCommandInfo() // Split the string based on (space). We decided to go with this approach as // UX localization authors use spaces. Correctly extracting only the wellformed URI // is out-of-scope for this fix. - string[] tempUriSplitArray = uriString.Split(Utils.Separators.Space); + string[] tempUriSplitArray = uriString.Split(' '); uriString = tempUriSplitArray[0]; } @@ -319,7 +319,7 @@ internal static Uri GetUriFromCommandPSObject(PSObject commandFullHelp) // Split the string based on (space). We decided to go with this approach as // UX localization authors use spaces. Correctly extracting only the wellformed URI // is out-of-scope for this fix. - string[] tempUriSplitArray = uriString.Split(Utils.Separators.Space); + string[] tempUriSplitArray = uriString.Split(' '); uriString = tempUriSplitArray[0]; } diff --git a/src/System.Management.Automation/help/DscResourceHelpProvider.cs b/src/System.Management.Automation/help/DscResourceHelpProvider.cs index 42412926a47..c33a03dc899 100644 --- a/src/System.Management.Automation/help/DscResourceHelpProvider.cs +++ b/src/System.Management.Automation/help/DscResourceHelpProvider.cs @@ -141,7 +141,7 @@ private IEnumerable GetHelpInfo(DscResourceSearcher searcher) } else if (!string.IsNullOrEmpty(moduleDir)) { - string[] splitPath = moduleDir.Split(Utils.Separators.Backslash); + string[] splitPath = moduleDir.Split('\\'); moduleName = splitPath[splitPath.Length - 1]; } diff --git a/src/System.Management.Automation/help/HelpFileHelpProvider.cs b/src/System.Management.Automation/help/HelpFileHelpProvider.cs index 4591ddbf863..71680c13866 100644 --- a/src/System.Management.Automation/help/HelpFileHelpProvider.cs +++ b/src/System.Management.Automation/help/HelpFileHelpProvider.cs @@ -275,9 +275,8 @@ private static void GetModuleNameAndVersion(string psmodulePathRoot, string file if (filePath.StartsWith(psmodulePathRoot, StringComparison.OrdinalIgnoreCase)) { - var moduleRootSubPath = filePath.Remove(0, psmodulePathRoot.Length).TrimStart(Utils.Separators.Directory); + var moduleRootSubPath = filePath.Remove(0, psmodulePathRoot.Length); var pathParts = moduleRootSubPath.Split(Utils.Separators.Directory, StringSplitOptions.RemoveEmptyEntries); - moduleName = pathParts[0]; var potentialVersion = pathParts[1]; Version result; diff --git a/src/System.Management.Automation/help/MamlNode.cs b/src/System.Management.Automation/help/MamlNode.cs index fa175391501..4abb80b1397 100644 --- a/src/System.Management.Automation/help/MamlNode.cs +++ b/src/System.Management.Automation/help/MamlNode.cs @@ -1109,7 +1109,7 @@ private static string GetPreformattedText(string text) // It is discouraged to use tab in preformatted text. string noTabText = text.Replace("\t", " "); - string[] lines = noTabText.Split(Utils.Separators.Newline); + string[] lines = noTabText.Split('\n'); string[] trimedLines = TrimLines(lines); if (trimedLines == null || trimedLines.Length == 0) @@ -1212,7 +1212,7 @@ private static int GetIndentation(string line) if (IsEmptyLine(line)) return 0; - string leftTrimedLine = line.TrimStart(Utils.Separators.Space); + string leftTrimedLine = line.TrimStart(' '); return line.Length - leftTrimedLine.Length; } diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index 07625fc2ab0..1d434a06e49 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -8592,7 +8592,7 @@ internal static List GetStreams(string path) data.Stream = findStreamData.Name; data.Length = findStreamData.Length; data.FileName = path.Replace(data.Stream, string.Empty); - data.FileName = data.FileName.Trim(Utils.Separators.Colon); + data.FileName = data.FileName.Trim(':'); alternateStreams.Add(data); findStreamData = new AlternateStreamNativeData(); diff --git a/src/System.Management.Automation/namespaces/ProviderBase.cs b/src/System.Management.Automation/namespaces/ProviderBase.cs index d3fad54bdd7..2eebb56e750 100644 --- a/src/System.Management.Automation/namespaces/ProviderBase.cs +++ b/src/System.Management.Automation/namespaces/ProviderBase.cs @@ -1352,7 +1352,7 @@ public PSHost Host ///
public virtual char AltItemSeparator => #if UNIX - Utils.Separators.Backslash[0]; + '\\'; #else Path.AltDirectorySeparatorChar; #endif From ae3f5f0f647ab3ac399edc91d870026169e8e87a Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Thu, 27 Oct 2022 20:18:36 -0700 Subject: [PATCH 152/779] Remove unused strings from FileSystem and Registry providers (#18403) --- .../resources/FileSystemProviderStrings.resx | 9 --- .../resources/RegistryProviderStrings.resx | 69 ------------------- 2 files changed, 78 deletions(-) diff --git a/src/System.Management.Automation/resources/FileSystemProviderStrings.resx b/src/System.Management.Automation/resources/FileSystemProviderStrings.resx index 9c232ae836e..7f9035b1e99 100644 --- a/src/System.Management.Automation/resources/FileSystemProviderStrings.resx +++ b/src/System.Management.Automation/resources/FileSystemProviderStrings.resx @@ -216,9 +216,6 @@ An item with the specified name {0} already exists. - - The path length is too short. The character length of a path cannot be less than the character length of the basePath. - A delimiter cannot be specified when reading the stream one byte at a time. @@ -324,15 +321,9 @@ Failed to read remote file '{0}'. - - Failed to validate remote destination '{0}'. - Cannot validate if remote destination {0} is a file. - - Remote copy with {0} is not supported. - Failed to create directory '{0}' on remote destination. diff --git a/src/System.Management.Automation/resources/RegistryProviderStrings.resx b/src/System.Management.Automation/resources/RegistryProviderStrings.resx index 046d28b3c10..901c944fd77 100644 --- a/src/System.Management.Automation/resources/RegistryProviderStrings.resx +++ b/src/System.Management.Automation/resources/RegistryProviderStrings.resx @@ -132,9 +132,6 @@ New Item - - Item: {0} Type: {1} - Item: {0} @@ -174,24 +171,6 @@ Item: {0} Property: {1} - - Set Property Value At - - - Item: {0} Property: {1} At: {2} - - - Add Property Value At - - - Item: {0} Property: {1} At: {2} - - - Remove Property Value At - - - Item: {0} Property: {1} At: {2} - New Property @@ -222,9 +201,6 @@ Item: {0} SourceProperty: {1} DestinationItem: {2} DestinationProperty: {3} - - (default) - The operation was not processed. The location that was provided does not allow this operation. @@ -246,15 +222,6 @@ The operation cannot be performed because the destination path is subordinate to the source path. - - The at parameter must be an integer to index a specific property value. - - - The property is not a multi-valued property. To remove this property, use Remove-ItemProperty. - - - The property is not a multi-valued property and values cannot be added to it. To change the value use Set-ItemProperty. - The property already exists. @@ -330,24 +297,12 @@ The specified RegistryKeyPermissionCheck value is not valid. - - A transaction argument must be specified. - - - The specified SafeHandle value is not valid. - The registry key has subkeys; recursive removals are not supported by this method. - - Remote registry operations are not allowed with transactions. - Cannot create a KTM handle without a Transaction.Current or specified transaction. - - The object does not contain a security descriptor. - The specified transaction or Transaction.Current must match the transaction used to create or open this TransactedRegistryKey. @@ -357,21 +312,6 @@ Requested registry access is not allowed. - - The security identifier is not allowed to be the owner of this object. - - - The security identifier is not allowed to be the primary group of this object. - - - Method failed with unexpected error code {0}. - - - Unable to perform a security operation on an object that has no associated security. This can happen when trying to get an ACL of an anonymous kernel object. - - - Transaction related error {0} occurred. - Access to the registry key '{0}' is denied. @@ -387,15 +327,6 @@ Registry transactions are not supported on this platform. - - The specified permission name is not valid. - - - Incorrect thread for enabling or disabling a privilege. - - - The permission must be reverted before changing its state again. - The specified handle is not valid. From 4014154b3ba1b9c230b6f618ebf7a80d5d4916d4 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Fri, 28 Oct 2022 09:19:10 -0700 Subject: [PATCH 153/779] Update the cgmanifest (#18408) --- tools/cgmanifest.json | 32 +------------------------------- 1 file changed, 1 insertion(+), 31 deletions(-) diff --git a/tools/cgmanifest.json b/tools/cgmanifest.json index 0a335fdfbe1..30a149dfd26 100644 --- a/tools/cgmanifest.json +++ b/tools/cgmanifest.json @@ -160,16 +160,6 @@ }, "DevelopmentDependency": false }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "Microsoft.NETCore.Windows.ApiSets", - "Version": "1.0.1" - } - }, - "DevelopmentDependency": false - }, { "Component": { "Type": "nuget", @@ -235,7 +225,7 @@ "Type": "nuget", "Nuget": { "Name": "Microsoft.Windows.Compatibility", - "Version": "6.0.0" + "Version": "6.0.1" } }, "DevelopmentDependency": false @@ -660,26 +650,6 @@ }, "DevelopmentDependency": false }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "runtime.win7-x64.Microsoft.NETCore.Windows.ApiSets", - "Version": "1.0.1" - } - }, - "DevelopmentDependency": false - }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "runtime.win7-x86.Microsoft.NETCore.Windows.ApiSets", - "Version": "1.0.1" - } - }, - "DevelopmentDependency": false - }, { "Component": { "Type": "nuget", From 8b957f86731c92dd3c0b51ae51758e81c5019f91 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 28 Oct 2022 09:19:32 -0700 Subject: [PATCH 154/779] Bump `Microsoft.PowerShell.Native` from 7.3.0-rc.1 to 7.3.0 (#18405) --- .../System.Management.Automation.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/System.Management.Automation/System.Management.Automation.csproj b/src/System.Management.Automation/System.Management.Automation.csproj index 67431292607..9cde2d2494d 100644 --- a/src/System.Management.Automation/System.Management.Automation.csproj +++ b/src/System.Management.Automation/System.Management.Automation.csproj @@ -46,7 +46,7 @@ - + From 4780225ee333152304caf2c073e71c21b5eb4e66 Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Fri, 28 Oct 2022 13:53:20 -0700 Subject: [PATCH 155/779] Change log for `v7.3.0-rc.1` (#18400) --- .spelling | 4 ++++ CHANGELOG/preview.md | 44 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/.spelling b/.spelling index 3395cf42ad7..f8f6d445b59 100644 --- a/.spelling +++ b/.spelling @@ -734,6 +734,7 @@ preview.8 preview1-24530-04 preview1.22217.1 preview7 +ProcessorArchitecture productversion program.cs prototyyppi @@ -768,6 +769,7 @@ pvs-studio pwd pwrshplughin.dll pwsh +pwsh.deps.json qmfrederik raghav710 RandomNoun7 @@ -777,6 +779,7 @@ rc.1 rc.1.21455.2 rc.1.21458.32 rc.2 +rc.2.22477.20 rc.3 rc2-24027 rc3-24011 @@ -1084,6 +1087,7 @@ wildcards win32 win32-openssh win7 +win8 windos windowspsmodulepath windowsversion diff --git a/CHANGELOG/preview.md b/CHANGELOG/preview.md index 41a27232a2b..96163085408 100644 --- a/CHANGELOG/preview.md +++ b/CHANGELOG/preview.md @@ -1,5 +1,49 @@ # Current preview release +## [7.3.0-rc.1] - 2022-10-26 + +### Breaking Change + +- Update to use `ComputeCore.dll` for PowerShell Direct (#18194) + +### Engine Updates and Fixes + +- On Unix, explicitly terminate the native process during cleanup only if it's not running in background (#18215) + +### General Cmdlet Updates and Fixes + +- Remove the `ProcessorArchitecture` portion from the full name as it's obsolete (#18320) + +### Tests + +- Add missing `-Tag 'CI'` to describe blocks. (#18317) + +### Build and Packaging Improvements + +
+ + +

Bump to .NET 7 to 7.0.100-rc.2.22477.20 (#18328)(#18286)

+
+ +
    +
  • Update ThirdPartyNotices (Internal 22987)
  • +
  • Remove API sets (#18304) (#18376)
  • +
  • Do not cleanup pwsh.deps.json for framework dependent packages (#18300)
  • +
  • Bump Microsoft.PowerShell.Native from 7.3.0-preview.1 to 7.3.0-rc.1 (#18217)
  • +
  • Remove unnecessary native dependencies from the package (#18213)
  • +
  • Make the link to minimal package blob public during release (#18158)
  • +
  • Create tasks to collect and publish hashes for build files. (#18276)(#18277)
  • +
  • Add branch counter to compliance build (#18214)
  • +
  • Move APIScan to compliance build (#18191)
  • +
  • Update MSI exit message (#18137)
  • +
  • Remove XML files for min-size package (#18189)
  • +
+ +
+ +[7.3.0-rc.1]: https://github.com/PowerShell/PowerShell/compare/v7.3.0-preview.8...v7.3.0-rc.1 + ## [7.3.0-preview.8] - 2022-09-20 ### General Cmdlet Updates and Fixes From f4e68ad8758d43f3b0bf8a4b8d24ac5f50b025bc Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Sat, 29 Oct 2022 09:10:03 -0700 Subject: [PATCH 156/779] Skip output rendering tests on Windows Server 2012 R2 (#18382) --- .../engine/Formatting/OutputRendering.Tests.ps1 | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/test/powershell/engine/Formatting/OutputRendering.Tests.ps1 b/test/powershell/engine/Formatting/OutputRendering.Tests.ps1 index a1c721e7646..0784c7a1f29 100644 --- a/test/powershell/engine/Formatting/OutputRendering.Tests.ps1 +++ b/test/powershell/engine/Formatting/OutputRendering.Tests.ps1 @@ -2,6 +2,14 @@ # Licensed under the MIT License. Describe 'OutputRendering tests' -Tag 'CI' { + BeforeAll { + $originalDefaultParameterValues = $PSDefaultParameterValues.Clone() + # Console host does not support VT100 escape sequences on Windows 2012R2 or earlier + if ($IsWindows -and [System.Environment]::OSVersion.Version -le [version]::new(6, 3)) { + $PSDefaultParameterValues["it:skip"] = $true + } + } + BeforeEach { if ($null -ne $PSStyle) { $oldOutputRendering = $PSStyle.OutputRendering @@ -14,6 +22,10 @@ Describe 'OutputRendering tests' -Tag 'CI' { } } + AfterAll { + $global:PSDefaultParameterValues = $originalDefaultParameterValues + } + It 'OutputRendering works for "" to the host' -TestCases @( @{ outputRendering = 'host' ; ansi = $true } @{ outputRendering = 'ansi' ; ansi = $true } From 9016adf1c22fcaf97d026762bf4b0c8da9e3d6c4 Mon Sep 17 00:00:00 2001 From: Berkan Diler Date: Mon, 31 Oct 2022 17:56:15 +0100 Subject: [PATCH 157/779] Replace some `string.Join(string)` calls with `string.Join(char)` (#18411) --- .../commands/utility/AddType.cs | 2 +- .../engine/CommandCompletion/CompletionCompleters.cs | 2 +- src/System.Management.Automation/engine/InitialSessionState.cs | 2 +- .../engine/Modules/NewModuleManifestCommand.cs | 2 +- .../engine/Modules/SwitchProcessCommand.cs | 2 +- src/System.Management.Automation/engine/parser/PSType.cs | 2 +- .../engine/remoting/commands/CustomShellCommands.cs | 2 +- .../engine/remoting/common/RunspaceConnectionInfo.cs | 2 +- src/System.Management.Automation/engine/serialization.cs | 2 +- src/System.Management.Automation/logging/MshLog.cs | 2 +- 10 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs index 00d6b11efcf..bc1d6b0ba4e 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs @@ -110,7 +110,7 @@ public string[] MemberDefinition if (value != null) { - _sourceCode = string.Join("\n", value); + _sourceCode = string.Join('\n', value); } } } diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs index 14b662aa419..6e8da81febf 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs @@ -6206,7 +6206,7 @@ private static void AddInferredMember(object member, WildcardPattern memberNameP { memberName = methodCacheEntry[0].method.Name; isMethod = true; - getToolTip = () => string.Join("\n", methodCacheEntry.methodInformationStructures.Select(static m => m.methodDefinition)); + getToolTip = () => string.Join('\n', methodCacheEntry.methodInformationStructures.Select(static m => m.methodDefinition)); } var psMemberInfo = member as PSMemberInfo; diff --git a/src/System.Management.Automation/engine/InitialSessionState.cs b/src/System.Management.Automation/engine/InitialSessionState.cs index 34e5c6d7abb..751c9655e0d 100644 --- a/src/System.Management.Automation/engine/InitialSessionState.cs +++ b/src/System.Management.Automation/engine/InitialSessionState.cs @@ -2781,7 +2781,7 @@ private static void ProcessCommandModification(Hashtable commandModification, Co break; case "ValidatePattern": - string pattern = "^(" + string.Join("|", parameterValidationValues) + ")$"; + string pattern = "^(" + string.Join('|', parameterValidationValues) + ")$"; ValidatePatternAttribute validatePattern = new ValidatePatternAttribute(pattern); metadata.Parameters[parameterName].Attributes.Add(validatePattern); break; diff --git a/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs b/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs index 1035b36e0e6..65739b03c8c 100644 --- a/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs +++ b/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs @@ -963,7 +963,7 @@ protected override void EndProcessing() if (CompatiblePSEditions != null && (CompatiblePSEditions.Distinct(StringComparer.OrdinalIgnoreCase).Count() != CompatiblePSEditions.Length)) { - string message = StringUtil.Format(Modules.DuplicateEntriesInCompatiblePSEditions, string.Join(",", CompatiblePSEditions)); + string message = StringUtil.Format(Modules.DuplicateEntriesInCompatiblePSEditions, string.Join(',', CompatiblePSEditions)); var ioe = new InvalidOperationException(message); var er = new ErrorRecord(ioe, "Modules_DuplicateEntriesInCompatiblePSEditions", ErrorCategory.InvalidArgument, CompatiblePSEditions); ThrowTerminatingError(er); diff --git a/src/System.Management.Automation/engine/Modules/SwitchProcessCommand.cs b/src/System.Management.Automation/engine/Modules/SwitchProcessCommand.cs index 1bad35bfd31..4700c425dbc 100644 --- a/src/System.Management.Automation/engine/Modules/SwitchProcessCommand.cs +++ b/src/System.Management.Automation/engine/Modules/SwitchProcessCommand.cs @@ -80,7 +80,7 @@ protected override void EndProcessing() System.Globalization.CultureInfo.InvariantCulture, CommandBaseStrings.ExecFailed, Marshal.GetLastPInvokeError(), - string.Join(" ", WithCommand) + string.Join(' ', WithCommand) ) ), "ExecutionFailed", diff --git a/src/System.Management.Automation/engine/parser/PSType.cs b/src/System.Management.Automation/engine/parser/PSType.cs index 7f35927af26..f7dcdfb4265 100644 --- a/src/System.Management.Automation/engine/parser/PSType.cs +++ b/src/System.Management.Automation/engine/parser/PSType.cs @@ -1434,7 +1434,7 @@ private static string GetClassNameInAssembly(TypeDefinitionAst typeDefinitionAst nameParts.Reverse(); nameParts.Add(typeDefinitionAst.Name); - return string.Join(".", nameParts); + return string.Join('.', nameParts); } private static readonly OpCode[] s_ldc = diff --git a/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs b/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs index 557073ae699..d08f8662b06 100644 --- a/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs +++ b/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs @@ -1462,7 +1462,7 @@ internal static string GetRunAsVirtualAccountGroupsString(string[] groups) { if (groups == null) { return string.Empty; } - return string.Join(";", groups); + return string.Join(';', groups); } /// diff --git a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs index c4244c2864a..f2ea47228cb 100644 --- a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs +++ b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs @@ -2470,7 +2470,7 @@ private static string[] ParseArgv(ProcessStartInfo psi) var argvList = new List(); argvList.Add(psi.FileName); - var argsToParse = String.Join(" ", psi.ArgumentList).Trim(); + var argsToParse = String.Join(' ', psi.ArgumentList).Trim(); var argsLength = argsToParse.Length; for (int i = 0; i < argsLength; ) { diff --git a/src/System.Management.Automation/engine/serialization.cs b/src/System.Management.Automation/engine/serialization.cs index d3405df91c0..a5ad0091db3 100644 --- a/src/System.Management.Automation/engine/serialization.cs +++ b/src/System.Management.Automation/engine/serialization.cs @@ -1632,7 +1632,7 @@ private void PrepareCimInstanceForSerialization(PSObject psObject, CimInstance c instanceMetadata.Properties.Add( new PSNoteProperty( InternalDeserializer.CimModifiedProperties, - string.Join(" ", namesOfModifiedProperties))); + string.Join(' ', namesOfModifiedProperties))); } } diff --git a/src/System.Management.Automation/logging/MshLog.cs b/src/System.Management.Automation/logging/MshLog.cs index 9d98ea8d0ab..da48dc816aa 100644 --- a/src/System.Management.Automation/logging/MshLog.cs +++ b/src/System.Management.Automation/logging/MshLog.cs @@ -771,7 +771,7 @@ private static LogContext GetLogContext(ExecutionContext executionContext, Invoc logContext.HostId = (string)executionContext.EngineHostInterface.InstanceId.ToString(); } - logContext.HostApplication = string.Join(" ", Environment.GetCommandLineArgs()); + logContext.HostApplication = string.Join(' ', Environment.GetCommandLineArgs()); if (executionContext.CurrentRunspace != null) { From 8619d8432fc5ea05cd207342ca8db2989f357290 Mon Sep 17 00:00:00 2001 From: Berkan Diler Date: Mon, 31 Oct 2022 18:20:22 +0100 Subject: [PATCH 158/779] Make use of StringSplitOptions.TrimEntries when possible (#18412) --- .../commands/utility/ConvertFrom-StringData.cs | 15 +++++++-------- .../engine/Modules/ModuleIntrinsics.cs | 11 +++++------ 2 files changed, 12 insertions(+), 14 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-StringData.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-StringData.cs index 284c344f7cc..14cc2eecb63 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-StringData.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-StringData.cs @@ -55,35 +55,34 @@ protected override void ProcessRecord() return; } - string[] lines = _stringData.Split('\n'); + string[] lines = _stringData.Split('\n', StringSplitOptions.TrimEntries); foreach (string line in lines) { - string s = line.Trim(); - if (string.IsNullOrEmpty(s) || s[0] == '#') + if (string.IsNullOrEmpty(line) || line[0] == '#') continue; - int index = s.IndexOf(Delimiter); + int index = line.IndexOf(Delimiter); if (index <= 0) { throw PSTraceSource.NewInvalidOperationException( ConvertFromStringData.InvalidDataLine, - s); + line); } - string name = s.Substring(0, index); + string name = line.Substring(0, index); name = name.Trim(); if (result.ContainsKey(name)) { throw PSTraceSource.NewInvalidOperationException( ConvertFromStringData.DataItemAlreadyDefined, - s, + line, name); } - string value = s.Substring(index + 1); + string value = line.Substring(index + 1); value = value.Trim(); value = Regex.Unescape(value); diff --git a/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs b/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs index 10b5ffa34e3..796ce35943d 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs @@ -1273,24 +1273,23 @@ internal static string GetWindowsPowerShellModulePath() }; var modulePathList = new List(); - foreach (var path in currentModulePath.Split(';')) + foreach (var path in currentModulePath.Split(';', StringSplitOptions.TrimEntries)) { - var trimmedPath = path.Trim(); - if (!excludeModulePaths.Contains(trimmedPath)) + if (!excludeModulePaths.Contains(path)) { // make sure this module path is Not part of other PS Core installation - var possiblePwshDir = Path.GetDirectoryName(trimmedPath); + var possiblePwshDir = Path.GetDirectoryName(path); if (string.IsNullOrEmpty(possiblePwshDir)) { // i.e. module dir is in the drive root - modulePathList.Add(trimmedPath); + modulePathList.Add(path); } else { if (!File.Exists(Path.Combine(possiblePwshDir, "pwsh.dll"))) { - modulePathList.Add(trimmedPath); + modulePathList.Add(path); } } } From c16521ac87e11b911d38d872b469424a7c03d75c Mon Sep 17 00:00:00 2001 From: Berkan Diler Date: Tue, 1 Nov 2022 09:31:58 +0100 Subject: [PATCH 159/779] Use new LINQ Order() methods instead of OrderBy(static x => x) (#18395) Less code, a bit faster, less allocations --- .../commands/utility/Group-Object.cs | 2 +- .../CoreCLR/CorePsAssemblyLoadContext.cs | 2 +- src/System.Management.Automation/DscSupport/CimDSCParser.cs | 2 +- .../engine/CommandCompletion/CompletionAnalysis.cs | 2 +- .../engine/CommandCompletion/CompletionCompleters.cs | 4 ++-- .../EnableDisableExperimentalFeatureCommand.cs | 2 +- src/System.Management.Automation/engine/GetCommandCommand.cs | 4 ++-- .../engine/parser/SemanticChecks.cs | 2 +- .../engine/remoting/commands/NewPSSessionConfigurationFile.cs | 2 +- 9 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Group-Object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Group-Object.cs index a15c3f87f01..379865e850e 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Group-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Group-Object.cs @@ -488,7 +488,7 @@ protected override void EndProcessing() { // using OrderBy to get stable sort. // fast path when we only have the same object types to group - foreach (var entry in _entriesToOrder.OrderBy(static e => e, _orderByPropertyComparer)) + foreach (var entry in _entriesToOrder.Order(_orderByPropertyComparer)) { DoOrderedGrouping(entry, NoElement, _groups, _tupleToGroupInfoMappingDictionary, _orderByPropertyComparer); if (Stopping) diff --git a/src/System.Management.Automation/CoreCLR/CorePsAssemblyLoadContext.cs b/src/System.Management.Automation/CoreCLR/CorePsAssemblyLoadContext.cs index 0e547138220..2e4e7fe0f9b 100644 --- a/src/System.Management.Automation/CoreCLR/CorePsAssemblyLoadContext.cs +++ b/src/System.Management.Automation/CoreCLR/CorePsAssemblyLoadContext.cs @@ -401,7 +401,7 @@ private static bool FindInGac(string gacRoot, AssemblyName assemblyName, out str if (Directory.Exists(tempAssemblyDirPath)) { // Enumerate all directories, sort by name and select the last. This selects the latest version. - var chosenVersionDirectory = Directory.EnumerateDirectories(tempAssemblyDirPath).OrderBy(static d => d).LastOrDefault(); + var chosenVersionDirectory = Directory.EnumerateDirectories(tempAssemblyDirPath).Order().LastOrDefault(); if (!string.IsNullOrEmpty(chosenVersionDirectory)) { diff --git a/src/System.Management.Automation/DscSupport/CimDSCParser.cs b/src/System.Management.Automation/DscSupport/CimDSCParser.cs index 2fd205cd415..d94e41998ac 100644 --- a/src/System.Management.Automation/DscSupport/CimDSCParser.cs +++ b/src/System.Management.Automation/DscSupport/CimDSCParser.cs @@ -3677,7 +3677,7 @@ private static StringBuilder FormatCimPropertyType(DynamicKeywordProperty prop, // Do the property values map if (prop.ValueMap != null && prop.ValueMap.Count > 0) { - formattedTypeString.Append(" { " + string.Join(" | ", prop.ValueMap.Keys.OrderBy(static x => x)) + " }"); + formattedTypeString.Append(" { " + string.Join(" | ", prop.ValueMap.Keys.Order()) + " }"); } // We prepend optional property with "[" so close out it here. This way it is shown with [ ] to indication optional diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs index a11d6ca6763..1db575028cc 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs @@ -1650,7 +1650,7 @@ private static List GetResultForEnumPropertyValueOfDSCResource Diagnostics.Assert(isCursorInString || (!hasNewLine), "hasNoQuote and hasNewLine cannot be true at the same time"); if (property.ValueMap != null && property.ValueMap.Count > 0) { - IEnumerable orderedValues = property.ValueMap.Keys.OrderBy(static x => x).Where(v => !existingValues.Contains(v, StringComparer.OrdinalIgnoreCase)); + IEnumerable orderedValues = property.ValueMap.Keys.Order().Where(v => !existingValues.Contains(v, StringComparer.OrdinalIgnoreCase)); var matchedResults = orderedValues.Where(v => wildcardPattern.IsMatch(v)); if (matchedResults == null || !matchedResults.Any()) { diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs index 6e8da81febf..3e9f16bc4bd 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs @@ -195,7 +195,7 @@ List ExecuteGetCommandCommand(bool useModulePrefix) if (commandInfos != null && commandInfos.Count > 1) { // OrderBy is using stable sorting - var sortedCommandInfos = commandInfos.OrderBy(static a => a, new CommandNameComparer()); + var sortedCommandInfos = commandInfos.Order(new CommandNameComparer()); completionResults = MakeCommandsUnique(sortedCommandInfos, useModulePrefix, addAmpersandIfNecessary, quote); } else @@ -4563,7 +4563,7 @@ internal static IEnumerable CompleteFilename(CompletionContext } // Sorting the results by the path - var sortedPsobjs = psobjs.OrderBy(static a => a, new ItemPathComparer()); + var sortedPsobjs = psobjs.Order(new ItemPathComparer()); foreach (PSObject psobj in sortedPsobjs) { diff --git a/src/System.Management.Automation/engine/ExperimentalFeature/EnableDisableExperimentalFeatureCommand.cs b/src/System.Management.Automation/engine/ExperimentalFeature/EnableDisableExperimentalFeatureCommand.cs index f68a45cd0f2..2cdb266571d 100644 --- a/src/System.Management.Automation/engine/ExperimentalFeature/EnableDisableExperimentalFeatureCommand.cs +++ b/src/System.Management.Automation/engine/ExperimentalFeature/EnableDisableExperimentalFeatureCommand.cs @@ -131,7 +131,7 @@ public IEnumerable CompleteArgument(string commandName, string names.Add(result.Name); } - return names.OrderBy(static name => name).Select(static name => new CompletionResult(name, name, CompletionResultType.Text, name)); + return names.Order().Select(static name => new CompletionResult(name, name, CompletionResultType.Text, name)); } } } diff --git a/src/System.Management.Automation/engine/GetCommandCommand.cs b/src/System.Management.Automation/engine/GetCommandCommand.cs index b211744965a..3c253504f01 100644 --- a/src/System.Management.Automation/engine/GetCommandCommand.cs +++ b/src/System.Management.Automation/engine/GetCommandCommand.cs @@ -481,7 +481,7 @@ protected override void EndProcessing() if ((_names == null) || (_nameContainsWildcard)) { // Use the stable sorting to sort the result list - _accumulatedResults = _accumulatedResults.OrderBy(static a => a, new CommandInfoComparer()).ToList(); + _accumulatedResults = _accumulatedResults.Order(new CommandInfoComparer()).ToList(); } OutputResultsHelper(_accumulatedResults); @@ -1688,7 +1688,7 @@ public IEnumerable CompleteArgument(string commandName, string } } - return nouns.OrderBy(static noun => noun).Select(static noun => new CompletionResult(noun, noun, CompletionResultType.Text, noun)); + return nouns.Order().Select(static noun => new CompletionResult(noun, noun, CompletionResultType.Text, noun)); } } } diff --git a/src/System.Management.Automation/engine/parser/SemanticChecks.cs b/src/System.Management.Automation/engine/parser/SemanticChecks.cs index 2e2dcadd645..a7be00b2e13 100644 --- a/src/System.Management.Automation/engine/parser/SemanticChecks.cs +++ b/src/System.Management.Automation/engine/parser/SemanticChecks.cs @@ -1396,7 +1396,7 @@ public override AstVisitAction VisitDynamicKeywordStatement(DynamicKeywordStatem else if (!keyword.Properties.ContainsKey(propName.Value)) { IOrderedEnumerable tableKeys = keyword.Properties.Keys - .OrderBy(static key => key, StringComparer.OrdinalIgnoreCase); + .Order(StringComparer.OrdinalIgnoreCase); _parser.ReportError(propName.Extent, nameof(ParserStrings.InvalidInstanceProperty), diff --git a/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationFile.cs b/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationFile.cs index e5aa6bef798..d6b6c261d6d 100644 --- a/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationFile.cs +++ b/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationFile.cs @@ -1942,7 +1942,7 @@ internal static string CombineHashtable(IDictionary table, StreamWriter writer, sb.Append("@{"); - var keys = table.Keys.Cast().OrderBy(static x => x); + var keys = table.Keys.Cast().Order(); foreach (var key in keys) { sb.Append(writer.NewLine); From f9b6d12dde595af3b902e11496f76755d3ce9da6 Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Tue, 1 Nov 2022 17:27:09 -0700 Subject: [PATCH 160/779] Do not remove `penimc_cor3.dll` from build (#18438) --- assets/wix/files.wxs | 4 ++++ build.psm1 | 3 ++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/assets/wix/files.wxs b/assets/wix/files.wxs index 8da3a423d0a..47501d9303e 100644 --- a/assets/wix/files.wxs +++ b/assets/wix/files.wxs @@ -2778,6 +2778,9 @@ + + + @@ -3666,6 +3669,7 @@ + diff --git a/build.psm1 b/build.psm1 index 17fb59711a9..713ce06f364 100644 --- a/build.psm1 +++ b/build.psm1 @@ -3392,7 +3392,8 @@ function Clear-NativeDependencies $filesToDeleteCore = @($diasymFileName) - $filesToDeleteWinDesktop = @('penimc_cor3.dll') + ## Currently we do not need to remove any files from WinDesktop runtime. + $filesToDeleteWinDesktop = @() $deps = Get-Content "$PublishFolder/pwsh.deps.json" -Raw | ConvertFrom-Json -Depth 20 $targetRuntime = ".NETCoreApp,Version=v7.0/$($script:Options.Runtime)" From 489e316151871e180c3db34a84f0a0747a437ce1 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Wed, 2 Nov 2022 18:34:09 +0100 Subject: [PATCH 161/779] Webcmdlets set default charset encoding to UTF8 (#18219) --- .../WebCmdlet/Common/ContentHelper.Common.cs | 3 +- .../Common/InvokeRestMethodCommand.Common.cs | 5 --- .../WebCmdlets.Tests.ps1 | 43 +++---------------- 3 files changed, 7 insertions(+), 44 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs index c7b8c878ca0..657f527ab0b 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs @@ -23,8 +23,7 @@ internal static string GetContentType(HttpResponseMessage response) internal static Encoding GetDefaultEncoding() { - // default codepage encoding for web content. See RFC 2616. - Encoding encoding = Encoding.GetEncoding("ISO-8859-1"); + Encoding encoding = Encoding.UTF8; return encoding; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs index 72844df44fc..3847fd9bab8 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs @@ -407,11 +407,6 @@ internal override void ProcessResponse(HttpResponseMessage response) StreamHelper.TryGetEncoding(charSet, out encoding); } - if (string.IsNullOrEmpty(charSet) && returnType == RestReturnType.Json) - { - encoding = Encoding.UTF8; - } - object obj = null; Exception ex = null; diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 index c7d75bc75ed..2e7c9f00cb4 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 @@ -1193,13 +1193,13 @@ Describe "Invoke-WebRequest tests" -Tags "Feature", "RequireAdminOnWindows" { $response.Output | Should -BeOfType Microsoft.PowerShell.Commands.BasicHtmlWebResponseObject } - It "Verifies Invoke-WebRequest defaults to iso-8859-1 when an unsupported/invalid charset is declared" { + It "Verifies Invoke-WebRequest defaults to iso-UTF-8 when an unsupported/invalid charset is declared" { $query = @{ contenttype = 'text/html' body = '' } $uri = Get-WebListenerUrl -Test 'Response' -Query $query - $expectedEncoding = [System.Text.Encoding]::GetEncoding('iso-8859-1') + $expectedEncoding = [System.Text.Encoding]::UTF8 $response = ExecuteWebRequest -Uri $uri -UseBasicParsing $response.Error | Should -BeNullOrEmpty @@ -1207,34 +1207,18 @@ Describe "Invoke-WebRequest tests" -Tags "Feature", "RequireAdminOnWindows" { $response.Output | Should -BeOfType Microsoft.PowerShell.Commands.BasicHtmlWebResponseObject } - It "Verifies Invoke-WebRequest defaults to iso-8859-1 when an unsupported/invalid charset is declared using http-equiv" { + It "Verifies Invoke-WebRequest defaults to UTF-8 when an unsupported/invalid charset is declared using http-equiv" { $query = @{ contenttype = 'text/html' body = "`n`n`n" } $uri = Get-WebListenerUrl -Test 'Response' -Query $query - $expectedEncoding = [System.Text.Encoding]::GetEncoding('iso-8859-1') - $response = ExecuteWebRequest -Uri $uri -UseBasicParsing - - $response.Error | Should -BeNullOrEmpty - $response.Output.Encoding.EncodingName | Should -Be $expectedEncoding.EncodingName - $response.Output | Should -BeOfType Microsoft.PowerShell.Commands.BasicHtmlWebResponseObject - } - - It "Verifies Invoke-WebRequest defaults to UTF8 on application/json when no charset is present" { - # when contenttype is set, WebListener suppresses charset unless it is included in the query - $query = @{ - contenttype = 'application/json' - body = '{"Test": "Test"}' - } - $uri = Get-WebListenerUrl -Test 'Response' -Query $query $expectedEncoding = [System.Text.Encoding]::UTF8 $response = ExecuteWebRequest -Uri $uri -UseBasicParsing $response.Error | Should -BeNullOrEmpty $response.Output.Encoding.EncodingName | Should -Be $expectedEncoding.EncodingName $response.Output | Should -BeOfType Microsoft.PowerShell.Commands.BasicHtmlWebResponseObject - $response.Output.Content | Should -BeExactly $query.body } } @@ -3056,45 +3040,30 @@ Describe "Invoke-RestMethod tests" -Tags "Feature", "RequireAdminOnWindows" { $response.Encoding.EncodingName | Should -Be $expectedEncoding.EncodingName } - It "Verifies Invoke-RestMethod defaults to iso-8859-1 when an unsupported/invalid charset is declared" { + It "Verifies Invoke-RestMethod defaults to UTF-8 when an unsupported/invalid charset is declared" { $query = @{ contenttype = 'text/html' body = '' } $uri = Get-WebListenerUrl -Test 'Response' -Query $query - $expectedEncoding = [System.Text.Encoding]::GetEncoding('iso-8859-1') + $expectedEncoding = [System.Text.Encoding]::UTF8 $response = ExecuteRestMethod -Uri $uri -UseBasicParsing $response.Error | Should -BeNullOrEmpty $response.Encoding.EncodingName | Should -Be $expectedEncoding.EncodingName } - It "Verifies Invoke-RestMethod defaults to iso-8859-1 when an unsupported/invalid charset is declared using http-equiv" { + It "Verifies Invoke-RestMethod defaults to UTF-8 when an unsupported/invalid charset is declared using http-equiv" { $query = @{ contenttype = 'text/html' body = "`n`n`n" } $uri = Get-WebListenerUrl -Test 'Response' -Query $query - $expectedEncoding = [System.Text.Encoding]::GetEncoding('iso-8859-1') - $response = ExecuteRestMethod -Uri $uri -UseBasicParsing - - $response.Error | Should -BeNullOrEmpty - $response.Encoding.EncodingName | Should -Be $expectedEncoding.EncodingName - } - - It "Verifies Invoke-RestMethod defaults to UTF8 on application/json when no charset is present" { - # when contenttype is set, WebListener suppresses charset unless it is included in the query - $query = @{ - contenttype = 'application/json' - body = '{"Test": "Test"}' - } - $uri = Get-WebListenerUrl -Test 'Response' -Query $query $expectedEncoding = [System.Text.Encoding]::UTF8 $response = ExecuteRestMethod -Uri $uri -UseBasicParsing $response.Error | Should -BeNullOrEmpty $response.Encoding.EncodingName | Should -Be $expectedEncoding.EncodingName - $response.output.Test | Should -BeExactly 'Test' } } From f2e0640dd7bf2e1f217373d628ea6a9ec45da3fa Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Wed, 2 Nov 2022 15:42:45 -0700 Subject: [PATCH 162/779] Update `Out-Printer` to remove all decorating ANSI escape sequences from PowerShell formatting (#18425) --- .../out-printer/PrinterLineOutput.cs | 24 +++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/PrinterLineOutput.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/PrinterLineOutput.cs index cbd19a17f4f..94f3fe6a50e 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/PrinterLineOutput.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/PrinterLineOutput.cs @@ -5,6 +5,8 @@ using System.Collections.Generic; using System.Drawing; using System.Drawing.Printing; +using System.Management.Automation; +using System.Management.Automation.Internal; namespace Microsoft.PowerShell.Commands.Internal.Format { @@ -62,11 +64,25 @@ internal override int RowNumber internal override void WriteLine(string s) { CheckStopProcessing(); - // delegate the action to the helper, - // that will properly break the string into - // screen lines - _writeLineHelper.WriteLine(s, this.ColumnNumber); + + // Remove all ANSI escape sequences before sending out to the printer. + s = new ValueStringDecorated(s).ToString(OutputRendering.PlainText); + WriteRawText(s); } + + /// + /// Write a raw text by delegating to the writer underneath, with no change to the text. + /// For example, keeping VT escape sequences intact in it. + /// + /// The raw text to be written to the device. + internal override void WriteRawText(string s) + { + CheckStopProcessing(); + + // Delegate the action to the helper, that will properly break the string into screen lines. + _writeLineHelper.WriteLine(s, ColumnNumber); + } + #endregion /// From 38531558acd9e52d4384d20ef9e8cf334c5ff52e Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Wed, 2 Nov 2022 15:52:05 -0700 Subject: [PATCH 163/779] Add authenticode signing for assemblies on linux builds (#18440) --- .../releaseBuild/azureDevOps/releaseBuild.yml | 25 +- .../templates/linux-authenticode-sign.yml | 127 ++++++ .../azureDevOps/templates/linux-packaging.yml | 391 ++++++++++++++++++ .../azureDevOps/templates/linux.yml | 281 ++++--------- .../azureDevOps/templates/signBuildFiles.yml | 171 ++++++++ 5 files changed, 782 insertions(+), 213 deletions(-) create mode 100644 tools/releaseBuild/azureDevOps/templates/linux-authenticode-sign.yml create mode 100644 tools/releaseBuild/azureDevOps/templates/linux-packaging.yml create mode 100644 tools/releaseBuild/azureDevOps/templates/signBuildFiles.yml diff --git a/tools/releaseBuild/azureDevOps/releaseBuild.yml b/tools/releaseBuild/azureDevOps/releaseBuild.yml index 9eb2d62bbdc..e21b4fe0c4e 100644 --- a/tools/releaseBuild/azureDevOps/releaseBuild.yml +++ b/tools/releaseBuild/azureDevOps/releaseBuild.yml @@ -100,7 +100,7 @@ stages: - template: templates/linux.yml parameters: buildName: rpm - uploadDisplayName: Upload and Sign + parentJob: build_deb - template: templates/linux.yml parameters: @@ -111,6 +111,29 @@ stages: parameters: buildName: alpine + - template: templates/linux-authenticode-sign.yml + + - template: templates/linux-packaging.yml + parameters: + buildName: deb + parentJob: sign_linux_builds + + - template: templates/linux-packaging.yml + parameters: + buildName: rpm + uploadDisplayName: Upload and Sign + parentJob: sign_linux_builds + + - template: templates/linux-packaging.yml + parameters: + buildName: alpine + parentJob: sign_linux_builds + + - template: templates/linux-packaging.yml + parameters: + buildName: fxdependent + parentJob: sign_linux_builds + - stage: windows dependsOn: ['prep'] jobs: diff --git a/tools/releaseBuild/azureDevOps/templates/linux-authenticode-sign.yml b/tools/releaseBuild/azureDevOps/templates/linux-authenticode-sign.yml new file mode 100644 index 00000000000..d014cf74320 --- /dev/null +++ b/tools/releaseBuild/azureDevOps/templates/linux-authenticode-sign.yml @@ -0,0 +1,127 @@ +jobs: +- job: sign_linux_builds + displayName: Sign all linux builds + condition: succeeded() + pool: + name: PowerShell1ES + demands: + - ImageOverride -equals PSMMS2019-Secure + dependsOn: ['build_fxdependent', 'build_rpm'] + variables: + - name: runCodesignValidationInjection + value: false + - name: NugetSecurityAnalysisWarningLevel + value: none + - group: ESRP + + steps: + - checkout: self + clean: true + + - task: DownloadPipelineArtifact@2 + inputs: + artifact: pwshLinuxBuild + path: $(Build.ArtifactStagingDirectory)/pwshLinuxBuild + displayName: Download deb build + + - task: DownloadPipelineArtifact@2 + inputs: + artifact: pwshLinuxBuildMinSize + path: $(Build.ArtifactStagingDirectory)/pwshLinuxBuildMinSize + displayName: Download min-size build + + - task: DownloadPipelineArtifact@2 + inputs: + artifact: pwshLinuxBuildArm32 + path: $(Build.ArtifactStagingDirectory)/pwshLinuxBuildArm32 + displayName: Download arm32 build + + - task: DownloadPipelineArtifact@2 + inputs: + artifact: pwshLinuxBuildArm64 + path: $(Build.ArtifactStagingDirectory)/pwshLinuxBuildArm64 + displayName: Download arm64 build + + - task: DownloadPipelineArtifact@2 + inputs: + artifact: pwshMarinerBuildAmd64 + path: $(Build.ArtifactStagingDirectory)/pwshMarinerBuildAmd64 + displayName: Download mariner build + + - task: DownloadPipelineArtifact@2 + inputs: + artifact: pwshLinuxBuildAlpine + path: $(Build.ArtifactStagingDirectory)/pwshLinuxBuildAlpine + displayName: Download alpine build + + - task: DownloadPipelineArtifact@2 + inputs: + artifact: pwshLinuxBuildFxdependent + path: $(Build.ArtifactStagingDirectory)/pwshLinuxBuildFxdependent + displayName: Download fxdependent build + + - template: SetVersionVariables.yml + parameters: + ReleaseTagVar: $(ReleaseTagVar) + + - template: cloneToOfficialPath.yml + + - template: insert-nuget-config-azfeed.yml + parameters: + repoRoot: $(PowerShellRoot) + + - powershell: | + Set-Location $env:POWERSHELLROOT + import-module "$env:POWERSHELLROOT/build.psm1" + Sync-PSTags -AddRemoteIfMissing + displayName: SyncTags + condition: and(succeeded(), ne(variables['SkipBuild'], 'true')) + + - checkout: ComplianceRepo + clean: true + + - template: shouldSign.yml + + - template: signBuildFiles.yml + parameters: + binLocation: pwshLinuxBuild + buildPrefixName: 'PowerShell Linux' + + - template: signBuildFiles.yml + parameters: + binLocation: pwshLinuxBuildMinSize + buildPrefixName: 'PowerShell Linux Minimum Size' + + - template: signBuildFiles.yml + parameters: + binLocation: pwshLinuxBuildArm32 + buildPrefixName: 'PowerShell Linux Arm32' + + - template: signBuildFiles.yml + parameters: + binLocation: pwshLinuxBuildArm64 + buildPrefixName: 'PowerShell Linux Arm64' + + - template: signBuildFiles.yml + parameters: + binLocation: pwshMarinerBuildAmd64 + buildPrefixName: 'PowerShell Linux x64 Framework Dependent' + + - template: signBuildFiles.yml + parameters: + binLocation: pwshLinuxBuildAlpine + buildPrefixName: 'PowerShell Linux Alpine x64' + + - template: signBuildFiles.yml + parameters: + binLocation: pwshLinuxBuildFxdependent + buildPrefixName: 'PowerShell Linux Framework Dependent' + + #- template: Sbom.yml@ComplianceRepo + # parameters: + # BuildDropPath: '$(System.ArtifactsDirectory)/$(BIN_LOCATION)' + # Build_Repository_Uri: $(Github_Build_Repository_Uri) + # displayName: ${{ parameters.buildName }} SBOM + # PackageName: $(PACKAGE_NAME) + # PackageVersion: $(Version) + # sourceScanPath: '$(PowerShellRoot)/tools' diff --git a/tools/releaseBuild/azureDevOps/templates/linux-packaging.yml b/tools/releaseBuild/azureDevOps/templates/linux-packaging.yml new file mode 100644 index 00000000000..f5e298f7139 --- /dev/null +++ b/tools/releaseBuild/azureDevOps/templates/linux-packaging.yml @@ -0,0 +1,391 @@ +parameters: + buildName: '' + uploadDisplayName: 'Upload' + parentJob: '' + +jobs: +- job: pkg_${{ parameters.buildName }} + displayName: Package ${{ parameters.buildName }} + condition: succeeded() + pool: + name: PowerShell1ES + demands: + - ImageOverride -equals PSMMSUbuntu20.04-Secure + dependsOn: sign_linux_builds + variables: + - name: runCodesignValidationInjection + value: false + - name: build + value: ${{ parameters.buildName }} + - name: NugetSecurityAnalysisWarningLevel + value: none + - group: ESRP + + steps: + - ${{ if or(eq(variables.build,'deb'), eq(variables.build,'rpm')) }} : + - task: DownloadPipelineArtifact@2 + inputs: + artifact: pwshLinuxBuild-signed + path: $(Build.ArtifactStagingDirectory)/pwshLinuxBuild + displayName: Download deb build + + - ${{ if eq(variables.build,'deb') }} : + - task: DownloadPipelineArtifact@2 + inputs: + artifact: pwshLinuxBuildMinSize-signed + path: $(Build.ArtifactStagingDirectory)/pwshLinuxBuildMinSize + displayName: Download min-size build + + - ${{ if eq(variables.build,'deb') }} : + - task: DownloadPipelineArtifact@2 + inputs: + artifact: pwshLinuxBuildArm32-signed + path: $(Build.ArtifactStagingDirectory)/pwshLinuxBuildArm32 + displayName: Download arm32 build + + - ${{ if eq(variables.build,'deb') }} : + - task: DownloadPipelineArtifact@2 + inputs: + artifact: pwshLinuxBuildArm64-signed + path: $(Build.ArtifactStagingDirectory)/pwshLinuxBuildArm64 + displayName: Download arm64 build + + - ${{ if eq(variables.build,'rpm') }} : + - task: DownloadPipelineArtifact@2 + inputs: + artifact: pwshMarinerBuildAmd64-signed + path: $(Build.ArtifactStagingDirectory)/pwshMarinerBuildAmd64 + displayName: Download mariner build + + - ${{ if eq(variables.build,'alpine') }} : + - task: DownloadPipelineArtifact@2 + inputs: + artifact: pwshLinuxBuildAlpine-signed + path: $(Build.ArtifactStagingDirectory)/pwshLinuxBuild + displayName: Download alpine build + + - ${{ if eq(variables.build,'fxdependent') }} : + - task: DownloadPipelineArtifact@2 + inputs: + artifact: pwshLinuxBuildFxdependent-signed + path: $(Build.ArtifactStagingDirectory)/pwshLinuxBuild + displayName: Download fxdependent build + + - ${{ if or(eq(variables.build,'deb'), eq(variables.build,'rpm')) }} : + - task: DownloadPipelineArtifact@2 + inputs: + artifact: pwshLinuxBuild-meta + path: $(Build.ArtifactStagingDirectory)/pwshLinuxBuild-meta + displayName: Download deb build meta + + - ${{ if eq(variables.build,'deb') }} : + - task: DownloadPipelineArtifact@2 + inputs: + artifact: pwshLinuxBuildMinSize-meta + path: $(Build.ArtifactStagingDirectory)/pwshLinuxBuildMinSize-meta + displayName: Download min-size build meta + + - ${{ if eq(variables.build,'deb') }} : + - task: DownloadPipelineArtifact@2 + inputs: + artifact: pwshLinuxBuildArm32-meta + path: $(Build.ArtifactStagingDirectory)/pwshLinuxBuildArm32-meta + displayName: Download arm32 build meta + + - ${{ if eq(variables.build,'deb') }} : + - task: DownloadPipelineArtifact@2 + inputs: + artifact: pwshLinuxBuildArm64-meta + path: $(Build.ArtifactStagingDirectory)/pwshLinuxBuildArm64-meta + displayName: Download arm64 build meta + + - ${{ if eq(variables.build,'rpm') }} : + - task: DownloadPipelineArtifact@2 + inputs: + artifact: pwshMarinerBuildAmd64-meta + path: $(Build.ArtifactStagingDirectory)/pwshMarinerBuildAmd64-meta + displayName: Download mariner build meta + + - ${{ if eq(variables.build,'alpine') }} : + - task: DownloadPipelineArtifact@2 + inputs: + artifact: pwshLinuxBuildAlpine-meta + path: $(Build.ArtifactStagingDirectory)/pwshLinuxBuild-meta + displayName: Download alpine build meta + + - ${{ if eq(variables.build,'fxdependent') }} : + - task: DownloadPipelineArtifact@2 + inputs: + artifact: pwshLinuxBuildFxdependent-meta + path: $(Build.ArtifactStagingDirectory)/pwshLinuxBuild-meta + displayName: Download fxdependent build meta + + - pwsh: | + Get-ChildItem '$(Build.ArtifactStagingDirectory)' | Select-Object -Property 'unixmode', 'size', 'name' + displayName: Capture downloads + + - checkout: self + clean: true + + - checkout: ComplianceRepo + clean: true + + - template: SetVersionVariables.yml + parameters: + ReleaseTagVar: $(ReleaseTagVar) + + - pwsh: | + # create folder + sudo mkdir /PowerShell + + # make the current user the owner + sudo chown $env:USER /PowerShell + displayName: 'Create /PowerShell' + + - template: cloneToOfficialPath.yml + + - template: insert-nuget-config-azfeed.yml + parameters: + repoRoot: $(PowerShellRoot) + + - powershell: | + import-module "$env:POWERSHELLROOT/build.psm1" + Sync-PSTags -AddRemoteIfMissing + displayName: SyncTags + condition: and(succeeded(), ne(variables['SkipBuild'], 'true')) + workingDirectory: $(PowerShellRoot) + + - powershell: | + Import-Module "$env:POWERSHELLROOT/build.psm1" + + Start-PSBootstrap -Package + displayName: 'Bootstrap' + condition: and(succeeded(), ne(variables['SkipBuild'], 'true')) + workingDirectory: $(PowerShellRoot) + + - powershell: | + try { + Import-Module "$env:POWERSHELLROOT/build.psm1" + Import-Module "$env:POWERSHELLROOT/tools/packaging" + + $metadata = Get-Content "$env:POWERSHELLROOT/tools/metadata.json" -Raw | ConvertFrom-Json + + # LTSRelease.Package indicates that the release should be packaged as an LTS + $LTS = $metadata.LTSRelease.Package + Write-Verbose -Verbose -Message "LTS is set to: $LTS" + + Invoke-AzDevOpsLinuxPackageCreation -ReleaseTag '$(ReleaseTagVar)' -BuildType '$(build)' + + if ($LTS) { + Write-Verbose -Verbose "Packaging LTS" + Invoke-AzDevOpsLinuxPackageCreation -LTS -ReleaseTag '$(ReleaseTagVar)' -BuildType '$(build)' + } + } catch { + Get-Error + throw + } + displayName: 'Package' + condition: and(succeeded(), ne(variables['SkipBuild'], 'true')) + workingDirectory: $(PowerShellRoot) + + - powershell: | + $linuxPackages = Get-ChildItem "$env:POWERSHELLROOT/powershell*" -Include *.deb,*.rpm,*.tar.gz + + $bucket = 'release' + foreach ($linuxPackage in $linuxPackages) + { + $filePath = $linuxPackage.FullName + Write-Verbose "Publishing $filePath to $bucket" -Verbose + Write-Host "##vso[artifact.upload containerfolder=$bucket;artifactname=$bucket]$filePath" + } + displayName: Publish artifacts + condition: and(succeeded(), ne(variables['SkipBuild'], 'true')) + workingDirectory: $(PowerShellRoot) + + - template: /tools/releaseBuild/azureDevOps/templates/step/finalize.yml + +- job: upload_${{ parameters.buildName }} + displayName: ${{ parameters.uploadDisplayName }} ${{ parameters.buildName }} + dependsOn: pkg_${{ parameters.buildName }} + condition: succeeded() + pool: + name: PowerShell1ES + demands: + - ImageOverride -equals PSMMS2019-Secure + variables: + - name: buildName + value: ${{ parameters.buildName }} + - group: ESRP + - name: runCodesignValidationInjection + value: false + - name: NugetSecurityAnalysisWarningLevel + value: none + - name: skipComponentGovernanceDetection + value: true + + steps: + - checkout: self + clean: true + + - checkout: ComplianceRepo + clean: true + + - template: SetVersionVariables.yml + parameters: + ReleaseTagVar: $(ReleaseTagVar) + - template: shouldSign.yml + + - task: DownloadBuildArtifacts@0 + displayName: 'Download Deb Artifacts' + inputs: + downloadType: specific + itemPattern: '**/*.deb' + downloadPath: '$(System.ArtifactsDirectory)\finished' + condition: and(eq(variables['buildName'], 'DEB'), succeeded()) + + - task: DownloadBuildArtifacts@0 + displayName: 'Download tar.gz Artifacts copy' + inputs: + downloadType: specific + itemPattern: '**/*.tar.gz' + downloadPath: '$(System.ArtifactsDirectory)\finished' + + - powershell: | + Write-Host 'We handle the min-size package only when uploading for deb build.' + Write-Host '- For deb build, the min-size package is moved to a separate folder "finished\minSize",' + Write-Host ' so that the min-size package can be uploaded to a different Az Blob container.' + Write-Host '- For other builds, the min-size package is removed after being downloaded, so that it' + Write-Host ' does not get accidentally uploaded to the wrong Az Blob container.' + + $minSizePkg = '$(System.ArtifactsDirectory)\finished\release\*-gc.tar.gz' + if (Test-Path -Path $minSizePkg) + { + if ('$(buildName)' -eq 'DEB') + { + $minSizeDir = '$(System.ArtifactsDirectory)\finished\minSize' + New-Item -Path $minSizeDir -Type Directory -Force > $null + Move-Item -Path $minSizePkg -Destination $minSizeDir + + Write-Host "`nCapture the min-size package moved to the target folder." + Get-ChildItem -Path $minSizeDir + } + else + { + Write-Host '$(buildName): Remove the min-size package.' + Remove-Item -Path $minSizePkg -Force + } + } + else + { + Write-Host 'min-size package not found, so skip this step.' + } + displayName: 'Move minSize package to separate folder' + + - task: DownloadBuildArtifacts@0 + displayName: 'Download rpm Artifacts copy' + inputs: + downloadType: specific + itemPattern: '**/*.rpm' + downloadPath: '$(System.ArtifactsDirectory)\rpm' + condition: and(eq(variables['buildName'], 'RPM'), succeeded()) + + - template: EsrpScan.yml@ComplianceRepo + parameters: + scanPath: $(System.ArtifactsDirectory) + pattern: | + **\*.rpm + **\*.deb + **\*.tar.gz + + - ${{ if eq(variables['buildName'], 'RPM') }}: + - template: EsrpSign.yml@ComplianceRepo + parameters: + buildOutputPath: $(System.ArtifactsDirectory)\rpm + signOutputPath: $(Build.StagingDirectory)\signedPackages + certificateId: "CP-450779-Pgp" + pattern: | + **\*.rh.*.rpm + useMinimatch: true + shouldSign: $(SHOULD_SIGN) + displayName: Sign RedHat RPM + OutputMode: AlwaysCopy + + - ${{ if eq(variables['buildName'], 'RPM') }}: + - template: EsrpSign.yml@ComplianceRepo + parameters: + # Sign in-place, previous task copied the files to this folder + buildOutputPath: $(Build.StagingDirectory)\signedPackages + signOutputPath: $(Build.StagingDirectory)\signedPackages + certificateId: "CP-459159-Pgp" + pattern: | + **\*.cm.*.rpm + **\*.cm?.*.rpm + useMinimatch: true + shouldSign: $(SHOULD_SIGN) + displayName: Sign Mariner RPM + OutputMode: NeverCopy + + # requires windows + - ${{ if ne(variables['buildName'], 'RPM') }}: + - task: AzureFileCopy@4 + displayName: 'Upload to Azure - DEB and tar.gz' + inputs: + SourcePath: '$(System.ArtifactsDirectory)\finished\release\*' + azureSubscription: '$(AzureFileCopySubscription)' + Destination: AzureBlob + storage: '$(StorageAccount)' + ContainerName: '$(AzureVersion)' + + - template: upload-final-results.yml + parameters: + artifactPath: $(System.ArtifactsDirectory)\finished\release + + # requires windows + - task: AzureFileCopy@4 + displayName: 'Upload to Azure - min-size package for Guest Config' + inputs: + SourcePath: '$(System.ArtifactsDirectory)\finished\minSize\*' + azureSubscription: '$(AzureFileCopySubscription)' + Destination: AzureBlob + storage: '$(StorageAccount)' + ContainerName: '$(AzureVersion)-gc' + condition: and(eq(variables['buildName'], 'DEB'), succeeded()) + + - template: upload-final-results.yml + parameters: + artifactPath: $(System.ArtifactsDirectory)\finished\minSize + condition: and(eq(variables['buildName'], 'DEB'), succeeded()) + + # requires windows + - task: AzureFileCopy@4 + displayName: 'Upload to Azure - RPM - Unsigned' + inputs: + SourcePath: '$(System.ArtifactsDirectory)\rpm\release\*' + azureSubscription: '$(AzureFileCopySubscription)' + Destination: AzureBlob + storage: '$(StorageAccount)' + ContainerName: '$(AzureVersion)' + condition: and(and(succeeded(), ne(variables['SHOULD_SIGN'], 'true')),eq(variables['buildName'], 'RPM')) + + # requires windows + - task: AzureFileCopy@4 + displayName: 'Upload to Azure - RPM - Signed' + inputs: + SourcePath: '$(Build.StagingDirectory)\signedPackages\release\*' + azureSubscription: '$(AzureFileCopySubscription)' + Destination: AzureBlob + storage: '$(StorageAccount)' + ContainerName: '$(AzureVersion)' + condition: and(and(succeeded(), eq(variables['SHOULD_SIGN'], 'true')),eq(variables['buildName'], 'RPM')) + + - template: upload-final-results.yml + parameters: + artifactPath: $(System.ArtifactsDirectory)\rpm\release + condition: and(and(succeeded(), ne(variables['SHOULD_SIGN'], 'true')),eq(variables['buildName'], 'RPM')) + + - template: upload-final-results.yml + parameters: + artifactPath: '$(Build.StagingDirectory)\signedPackages\release' + condition: and(and(succeeded(), eq(variables['SHOULD_SIGN'], 'true')),eq(variables['buildName'], 'RPM')) + + - template: /tools/releaseBuild/azureDevOps/templates/step/finalize.yml diff --git a/tools/releaseBuild/azureDevOps/templates/linux.yml b/tools/releaseBuild/azureDevOps/templates/linux.yml index 53057fec716..e7caa41bc30 100644 --- a/tools/releaseBuild/azureDevOps/templates/linux.yml +++ b/tools/releaseBuild/azureDevOps/templates/linux.yml @@ -124,229 +124,86 @@ jobs: PackageVersion: $(Version) sourceScanPath: '$(PowerShellRoot)/tools' - - powershell: | - try { - Import-Module "$env:POWERSHELLROOT/build.psm1" - Import-Module "$env:POWERSHELLROOT/tools/packaging" - - $metadata = Get-Content "$env:POWERSHELLROOT/tools/metadata.json" -Raw | ConvertFrom-Json - - # LTSRelease.Package indicates that the release should be packaged as an LTS - $LTS = $metadata.LTSRelease.Package - Write-Verbose -Verbose -Message "LTS is set to: $LTS" - - Invoke-AzDevOpsLinuxPackageCreation -ReleaseTag '$(ReleaseTagVar)' -BuildType '$(build)' + - ${{ if eq(variables.build,'deb') }} : + - task: PublishPipelineArtifact@1 + inputs: + path: '$(System.ArtifactsDirectory)/pwshLinuxBuild' + artifactName: pwshLinuxBuild - if ($LTS) { - Write-Verbose -Verbose "Packaging LTS" - Invoke-AzDevOpsLinuxPackageCreation -LTS -ReleaseTag '$(ReleaseTagVar)' -BuildType '$(build)' - } - } catch { - Get-Error - throw - } - displayName: 'Package' - condition: and(succeeded(), ne(variables['SkipBuild'], 'true')) - workingDirectory: $(PowerShellRoot) + - ${{ if eq(variables.build,'deb') }} : + - task: PublishPipelineArtifact@1 + inputs: + path: '$(System.ArtifactsDirectory)/pwshLinuxBuild-meta' + artifactName: pwshLinuxBuild-meta - - powershell: | - $linuxPackages = Get-ChildItem "$env:POWERSHELLROOT/powershell*" -Include *.deb,*.rpm,*.tar.gz - - $bucket = 'release' - foreach ($linuxPackage in $linuxPackages) - { - $filePath = $linuxPackage.FullName - Write-Verbose "Publishing $filePath to $bucket" -Verbose - Write-Host "##vso[artifact.upload containerfolder=$bucket;artifactname=$bucket]$filePath" - } - displayName: Publish artifacts - condition: and(succeeded(), ne(variables['SkipBuild'], 'true')) - workingDirectory: $(PowerShellRoot) + - ${{ if eq(variables.build,'deb') }} : + - task: PublishPipelineArtifact@1 + inputs: + path: '$(System.ArtifactsDirectory)/pwshLinuxBuildMinSize' + artifactName: pwshLinuxBuildMinSize - - template: /tools/releaseBuild/azureDevOps/templates/step/finalize.yml + - ${{ if eq(variables.build,'deb') }} : + - task: PublishPipelineArtifact@1 + inputs: + path: '$(System.ArtifactsDirectory)/pwshLinuxBuildMinSize-meta' + artifactName: pwshLinuxBuildMinSize-meta -- job: upload_${{ parameters.buildName }} - displayName: ${{ parameters.uploadDisplayName }} ${{ parameters.buildName }} - dependsOn: build_${{ parameters.buildName }} - condition: succeeded() - pool: - name: PowerShell1ES - demands: - - ImageOverride -equals PSMMS2019-Secure - variables: - - name: buildName - value: ${{ parameters.buildName }} - - group: ESRP - - name: runCodesignValidationInjection - value: false - - name: NugetSecurityAnalysisWarningLevel - value: none - - name: skipComponentGovernanceDetection - value: true + - ${{ if eq(variables.build,'deb') }} : + - task: PublishPipelineArtifact@1 + inputs: + path: '$(System.ArtifactsDirectory)/pwshLinuxBuildArm32' + artifactName: pwshLinuxBuildArm32 - steps: - - checkout: self - clean: true + - ${{ if eq(variables.build,'deb') }} : + - task: PublishPipelineArtifact@1 + inputs: + path: '$(System.ArtifactsDirectory)/pwshLinuxBuildArm32-meta' + artifactName: pwshLinuxBuildArm32-meta - - checkout: ComplianceRepo - clean: true + - ${{ if eq(variables.build,'deb') }} : + - task: PublishPipelineArtifact@1 + inputs: + path: '$(System.ArtifactsDirectory)/pwshLinuxBuildArm64' + artifactName: pwshLinuxBuildArm64 - - template: SetVersionVariables.yml - parameters: - ReleaseTagVar: $(ReleaseTagVar) - - template: shouldSign.yml - - - task: DownloadBuildArtifacts@0 - displayName: 'Download Deb Artifacts' - inputs: - downloadType: specific - itemPattern: '**/*.deb' - downloadPath: '$(System.ArtifactsDirectory)\finished' - condition: and(eq(variables['buildName'], 'DEB'), succeeded()) - - - task: DownloadBuildArtifacts@0 - displayName: 'Download tar.gz Artifacts copy' - inputs: - downloadType: specific - itemPattern: '**/*.tar.gz' - downloadPath: '$(System.ArtifactsDirectory)\finished' + - ${{ if eq(variables.build,'deb') }} : + - task: PublishPipelineArtifact@1 + inputs: + path: '$(System.ArtifactsDirectory)/pwshLinuxBuildArm64-meta' + artifactName: pwshLinuxBuildArm64-meta - - powershell: | - Write-Host 'We handle the min-size package only when uploading for deb build.' - Write-Host '- For deb build, the min-size package is moved to a separate folder "finished\minSize",' - Write-Host ' so that the min-size package can be uploaded to a different Az Blob container.' - Write-Host '- For other builds, the min-size package is removed after being downloaded, so that it' - Write-Host ' does not get accidentally uploaded to the wrong Az Blob container.' - - $minSizePkg = '$(System.ArtifactsDirectory)\finished\release\*-gc.tar.gz' - if (Test-Path -Path $minSizePkg) - { - if ('$(buildName)' -eq 'DEB') - { - $minSizeDir = '$(System.ArtifactsDirectory)\finished\minSize' - New-Item -Path $minSizeDir -Type Directory -Force > $null - Move-Item -Path $minSizePkg -Destination $minSizeDir - - Write-Host "`nCapture the min-size package moved to the target folder." - Get-ChildItem -Path $minSizeDir - } - else - { - Write-Host '$(buildName): Remove the min-size package.' - Remove-Item -Path $minSizePkg -Force - } - } - else - { - Write-Host 'min-size package not found, so skip this step.' - } - displayName: 'Move minSize package to separate folder' + - ${{ if eq(variables.build,'rpm') }} : + - task: PublishPipelineArtifact@1 + inputs: + path: '$(System.ArtifactsDirectory)/pwshMarinerBuildAmd64' + artifactName: pwshMarinerBuildAmd64 - - task: DownloadBuildArtifacts@0 - displayName: 'Download rpm Artifacts copy' - inputs: - downloadType: specific - itemPattern: '**/*.rpm' - downloadPath: '$(System.ArtifactsDirectory)\rpm' - condition: and(eq(variables['buildName'], 'RPM'), succeeded()) + - ${{ if eq(variables.build,'rpm') }} : + - task: PublishPipelineArtifact@1 + inputs: + path: '$(System.ArtifactsDirectory)/pwshMarinerBuildAmd64-meta' + artifactName: pwshMarinerBuildAmd64-meta - - template: EsrpScan.yml@ComplianceRepo - parameters: - scanPath: $(System.ArtifactsDirectory) - pattern: | - **\*.rpm - **\*.deb - **\*.tar.gz - - - ${{ if eq(variables['buildName'], 'RPM') }}: - - template: EsrpSign.yml@ComplianceRepo - parameters: - buildOutputPath: $(System.ArtifactsDirectory)\rpm - signOutputPath: $(Build.StagingDirectory)\signedPackages - certificateId: "CP-450779-Pgp" - pattern: | - **\*.rh.*.rpm - useMinimatch: true - shouldSign: $(SHOULD_SIGN) - displayName: Sign RedHat RPM - OutputMode: AlwaysCopy - - - ${{ if eq(variables['buildName'], 'RPM') }}: - - template: EsrpSign.yml@ComplianceRepo - parameters: - # Sign in-place, previous task copied the files to this folder - buildOutputPath: $(Build.StagingDirectory)\signedPackages - signOutputPath: $(Build.StagingDirectory)\signedPackages - certificateId: "CP-459159-Pgp" - pattern: | - **\*.cm.*.rpm - **\*.cm?.*.rpm - useMinimatch: true - shouldSign: $(SHOULD_SIGN) - displayName: Sign Mariner RPM - OutputMode: NeverCopy - - # requires windows - - ${{ if ne(variables['buildName'], 'RPM') }}: - - task: AzureFileCopy@4 - displayName: 'Upload to Azure - DEB and tar.gz' + - ${{ if eq(variables.build,'alpine') }} : + - task: PublishPipelineArtifact@1 inputs: - SourcePath: '$(System.ArtifactsDirectory)\finished\release\*' - azureSubscription: '$(AzureFileCopySubscription)' - Destination: AzureBlob - storage: '$(StorageAccount)' - ContainerName: '$(AzureVersion)' + path: '$(System.ArtifactsDirectory)/pwshLinuxBuild' + artifactName: pwshLinuxBuildAlpine - - template: upload-final-results.yml - parameters: - artifactPath: $(System.ArtifactsDirectory)\finished\release - - # requires windows - - task: AzureFileCopy@4 - displayName: 'Upload to Azure - min-size package for Guest Config' - inputs: - SourcePath: '$(System.ArtifactsDirectory)\finished\minSize\*' - azureSubscription: '$(AzureFileCopySubscription)' - Destination: AzureBlob - storage: '$(StorageAccount)' - ContainerName: '$(AzureVersion)-gc' - condition: and(eq(variables['buildName'], 'DEB'), succeeded()) - - - template: upload-final-results.yml - parameters: - artifactPath: $(System.ArtifactsDirectory)\finished\minSize - condition: and(eq(variables['buildName'], 'DEB'), succeeded()) - - # requires windows - - task: AzureFileCopy@4 - displayName: 'Upload to Azure - RPM - Unsigned' - inputs: - SourcePath: '$(System.ArtifactsDirectory)\rpm\release\*' - azureSubscription: '$(AzureFileCopySubscription)' - Destination: AzureBlob - storage: '$(StorageAccount)' - ContainerName: '$(AzureVersion)' - condition: and(and(succeeded(), ne(variables['SHOULD_SIGN'], 'true')),eq(variables['buildName'], 'RPM')) - - # requires windows - - task: AzureFileCopy@4 - displayName: 'Upload to Azure - RPM - Signed' - inputs: - SourcePath: '$(Build.StagingDirectory)\signedPackages\release\*' - azureSubscription: '$(AzureFileCopySubscription)' - Destination: AzureBlob - storage: '$(StorageAccount)' - ContainerName: '$(AzureVersion)' - condition: and(and(succeeded(), eq(variables['SHOULD_SIGN'], 'true')),eq(variables['buildName'], 'RPM')) - - - template: upload-final-results.yml - parameters: - artifactPath: $(System.ArtifactsDirectory)\rpm\release - condition: and(and(succeeded(), ne(variables['SHOULD_SIGN'], 'true')),eq(variables['buildName'], 'RPM')) + - ${{ if eq(variables.build,'alpine') }} : + - task: PublishPipelineArtifact@1 + inputs: + path: '$(System.ArtifactsDirectory)/pwshLinuxBuild-meta' + artifactName: pwshLinuxBuildAlpine-meta - - template: upload-final-results.yml - parameters: - artifactPath: '$(Build.StagingDirectory)\signedPackages\release' - condition: and(and(succeeded(), eq(variables['SHOULD_SIGN'], 'true')),eq(variables['buildName'], 'RPM')) + - ${{ if eq(variables.build,'fxdependent') }} : + - task: PublishPipelineArtifact@1 + inputs: + path: '$(System.ArtifactsDirectory)/pwshLinuxBuild' + artifactName: pwshLinuxBuildFxdependent - - template: /tools/releaseBuild/azureDevOps/templates/step/finalize.yml + - ${{ if eq(variables.build,'fxdependent') }} : + - task: PublishPipelineArtifact@1 + inputs: + path: '$(System.ArtifactsDirectory)/pwshLinuxBuild-meta' + artifactName: pwshLinuxBuildFxdependent-meta diff --git a/tools/releaseBuild/azureDevOps/templates/signBuildFiles.yml b/tools/releaseBuild/azureDevOps/templates/signBuildFiles.yml new file mode 100644 index 00000000000..e628f2ca81d --- /dev/null +++ b/tools/releaseBuild/azureDevOps/templates/signBuildFiles.yml @@ -0,0 +1,171 @@ +parameters: + binLocation: '' + buildPrefixName: '' + addWindowsModules: 'false' + +steps: +- pwsh: | + $fullSymbolsFolder = Join-Path $(System.ArtifactsDirectory) "${{ parameters.binLocation }}" + + Write-Verbose -Verbose "fullSymbolsFolder == $fullSymbolsFolder" + + Get-ChildItem -Recurse $fullSymbolsFolder | out-string | Write-Verbose -Verbose + + $filesToSignDirectory = "$(System.ArtifactsDirectory)\toBeSigned" + + if ((Test-Path -Path $filesToSignDirectory)) { + Remove-Item -Path $filesToSignDirectory -Recurse -Force + } + + $null = New-Item -ItemType Directory -Path $filesToSignDirectory -Force + + $signedFilesDirectory = "$(System.ArtifactsDirectory)\signed" + + if ((Test-Path -Path $signedFilesDirectory)) { + Remove-Item -Path $signedFilesDirectory -Recurse -Force + } + + $null = New-Item -ItemType Directory -Path $signedFilesDirectory -Force + + $itemsToCopyWithRecurse = @( + "$($fullSymbolsFolder)\*.ps1" + "$($fullSymbolsFolder)\Microsoft.PowerShell*.dll" + ) + + $itemsToCopy = @{ + "$($fullSymbolsFolder)\*.ps1" = "" + "$($fullSymbolsFolder)\Modules\Microsoft.PowerShell.Host\Microsoft.PowerShell.Host.psd1" = "Modules\Microsoft.PowerShell.Host" + "$($fullSymbolsFolder)\Modules\Microsoft.PowerShell.Management\Microsoft.PowerShell.Management.psd1" = "Modules\Microsoft.PowerShell.Management" + "$($fullSymbolsFolder)\Modules\Microsoft.PowerShell.Security\Microsoft.PowerShell.Security.psd1" = "Modules\Microsoft.PowerShell.Security" + "$($fullSymbolsFolder)\Modules\Microsoft.PowerShell.Utility\Microsoft.PowerShell.Utility.psd1" = "Modules\Microsoft.PowerShell.Utility" + "$($fullSymbolsFolder)\pwsh.dll" = "" + "$($fullSymbolsFolder)\System.Management.Automation.dll" = "" + } + + ## Windows only modules + + if('${{ parameters.addWindowsModules }}' -ne 'false') { + $itemsToCopy += @{ + "$($fullSymbolsFolder)\pwsh.exe" = "" + "$($fullSymbolsFolder)\Microsoft.Management.Infrastructure.CimCmdlets.dll" = "" + "$($fullSymbolsFolder)\Microsoft.WSMan.*.dll" = "" + "$($fullSymbolsFolder)\Modules\CimCmdlets\CimCmdlets.psd1" = "Modules\CimCmdlets" + "$($fullSymbolsFolder)\Modules\Microsoft.PowerShell.Diagnostics\Diagnostics.format.ps1xml" = "Modules\Microsoft.PowerShell.Diagnostics" + "$($fullSymbolsFolder)\Modules\Microsoft.PowerShell.Diagnostics\Event.format.ps1xml" = "Modules\Microsoft.PowerShell.Diagnostics" + "$($fullSymbolsFolder)\Modules\Microsoft.PowerShell.Diagnostics\GetEvent.types.ps1xml" = "Modules\Microsoft.PowerShell.Diagnostics" + "$($fullSymbolsFolder)\Modules\Microsoft.PowerShell.Security\Security.types.ps1xml" = "Modules\Microsoft.PowerShell.Security" + "$($fullSymbolsFolder)\Modules\Microsoft.PowerShell.Diagnostics\Microsoft.PowerShell.Diagnostics.psd1" = "Modules\Microsoft.PowerShell.Diagnostics" + "$($fullSymbolsFolder)\Modules\Microsoft.WSMan.Management\Microsoft.WSMan.Management.psd1" = "Modules\Microsoft.WSMan.Management" + "$($fullSymbolsFolder)\Modules\Microsoft.WSMan.Management\WSMan.format.ps1xml" = "Modules\Microsoft.WSMan.Management" + "$($fullSymbolsFolder)\Modules\PSDiagnostics\PSDiagnostics.ps?1" = "Modules\PSDiagnostics" + } + } + else { + $itemsToCopy += @{ + "$($fullSymbolsFolder)\pwsh" = "" + } + } + + $itemsToExclude = @( + # This package is retrieved from https://www.github.com/powershell/MarkdownRender + "$($fullSymbolsFolder)\Microsoft.PowerShell.MarkdownRender.dll" + ) + + Write-Verbose -verbose "recusively copying $($itemsToCopyWithRecurse | out-string) to $filesToSignDirectory" + Copy-Item -Path $itemsToCopyWithRecurse -Destination $filesToSignDirectory -Recurse -verbose -exclude $itemsToExclude + + foreach($pattern in $itemsToCopy.Keys) { + $destinationFolder = Join-Path $filesToSignDirectory -ChildPath $itemsToCopy.$pattern + $null = New-Item -ItemType Directory -Path $destinationFolder -Force + Write-Verbose -verbose "copying $pattern to $destinationFolder" + Copy-Item -Path $pattern -Destination $destinationFolder -Recurse -verbose + } + displayName: '${{ parameters.buildPrefixName }} - Prepare files to be signed' + +- template: EsrpSign.yml@ComplianceRepo + parameters: + buildOutputPath: $(System.ArtifactsDirectory)\toBeSigned + signOutputPath: $(System.ArtifactsDirectory)\signed + certificateId: "$(AUTHENTICODE_CERT)" + pattern: | + **\*.dll + **\*.psd1 + **\*.psm1 + **\*.ps1xml + **\*.ps1 + **\*.exe + useMinimatch: true + shouldSign: $(SHOULD_SIGN) + displayName: ${{ parameters.buildPrefixName }} - Authenticode + +- pwsh: | + Import-Module $(PowerShellRoot)/build.psm1 -Force + Import-Module $(PowerShellRoot)/tools/packaging -Force + $signedFilesPath = '$(System.ArtifactsDirectory)\signed\' + $BuildPath = Join-Path $(System.ArtifactsDirectory) '${{ parameters.binLocation }}' + Write-Verbose -Verbose -Message "BuildPath: $BuildPath" + + Update-PSSignedBuildFolder -BuildPath $BuildPath -SignedFilesPath $SignedFilesPath + $dlls = Get-ChildItem $BuildPath\*.dll, $BuildPath\*.exe -Recurse + $signatures = $dlls | Get-AuthenticodeSignature + $missingSignatures = $signatures | Where-Object { $_.status -eq 'notsigned' -or $_.SignerCertificate.Issuer -notmatch '^CN=Microsoft.*'}| select-object -ExpandProperty Path + + Write-Verbose -verbose "to be signed:`r`n $($missingSignatures | Out-String)" + + $filesToSignDirectory = "$(System.ArtifactsDirectory)\thirdPartyToBeSigned" + $null = New-Item -ItemType Directory -Path $filesToSignDirectory -Force -Verbose + + $signedFilesDirectory = "$(System.ArtifactsDirectory)\thirdPartySigned" + $null = New-Item -ItemType Directory -Path $signedFilesDirectory -Force -Verbose + + $missingSignatures | ForEach-Object { + $pathWithoutLeaf = Split-Path $_ + $relativePath = $pathWithoutLeaf.replace($BuildPath,'') + Write-Verbose -Verbose -Message "relativePath: $relativePath" + $targetDirectory = Join-Path -Path $filesToSignDirectory -ChildPath $relativePath + Write-Verbose -Verbose -Message "targetDirectory: $targetDirectory" + if(!(Test-Path $targetDirectory)) + { + $null = New-Item -ItemType Directory -Path $targetDirectory -Force -Verbose + } + Copy-Item -Path $_ -Destination $targetDirectory + } + + displayName: ${{ parameters.buildPrefixName }} - Create ThirdParty Signing Folder + condition: and(succeeded(), eq(variables['SHOULD_SIGN'], 'true')) + +- template: EsrpSign.yml@ComplianceRepo + parameters: + buildOutputPath: $(System.ArtifactsDirectory)\thirdPartyToBeSigned + signOutputPath: $(System.ArtifactsDirectory)\thirdPartySigned + certificateId: "CP-231522" + pattern: | + **\*.dll + useMinimatch: true + shouldSign: $(SHOULD_SIGN) + displayName: Sign ThirdParty binaries + +- pwsh: | + Get-ChildItem '$(System.ArtifactsDirectory)\thirdPartySigned\*' + displayName: ${{ parameters.buildPrefixName }} - Capture ThirdParty Signed files + condition: and(succeeded(), eq(variables['SHOULD_SIGN'], 'true')) + +- pwsh: | + Import-Module $(PowerShellRoot)/build.psm1 -Force + Import-Module $(PowerShellRoot)/tools/packaging -Force + $signedFilesPath = '$(System.ArtifactsDirectory)\thirdPartySigned' + $BuildPath = Join-Path $(System.ArtifactsDirectory) '${{ parameters.binLocation }}' + + Update-PSSignedBuildFolder -BuildPath $BuildPath -SignedFilesPath $SignedFilesPath + if ($env:BuildConfiguration -eq 'minSize') { + ## Remove XML files when making a min-size package. + Remove-Item "$BuildPath/*.xml" -Force + } + displayName: ${{ parameters.buildPrefixName }} - Merge ThirdParty signed files with Build + condition: and(succeeded(), eq(variables['SHOULD_SIGN'], 'true')) + +- pwsh: | + $uploadFolder = '$(System.ArtifactsDirectory)/${{ parameters.binLocation }}' + $containerName = '${{ parameters.binLocation }}-signed' + Write-Host "##vso[artifact.upload containerfolder=$containerName;artifactname=$containerName]$uploadFolder" + displayName: ${{ parameters.buildPrefixName }} - Upload signed files to artifacts From 753a2523633e61ac7658a1dfbf4d7f19d2d6fff8 Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Wed, 2 Nov 2022 15:58:18 -0700 Subject: [PATCH 164/779] Add TSAUpload for APIScan (#18446) --- tools/guardian/tsaconfig-apiscan.json | 6 ++++++ tools/guardian/tsaconfig-others.json | 7 +++++++ .../templates/compliance/apiscan.yml | 6 ++++++ .../templates/compliance/compliance.yml | 21 ++++++------------- 4 files changed, 25 insertions(+), 15 deletions(-) create mode 100644 tools/guardian/tsaconfig-apiscan.json create mode 100644 tools/guardian/tsaconfig-others.json diff --git a/tools/guardian/tsaconfig-apiscan.json b/tools/guardian/tsaconfig-apiscan.json new file mode 100644 index 00000000000..3cadeccff3f --- /dev/null +++ b/tools/guardian/tsaconfig-apiscan.json @@ -0,0 +1,6 @@ +{ + "codebaseName": "PowerShellCore_201906", + "tools": [ + "APIScan" + ] +} diff --git a/tools/guardian/tsaconfig-others.json b/tools/guardian/tsaconfig-others.json new file mode 100644 index 00000000000..1f44978032e --- /dev/null +++ b/tools/guardian/tsaconfig-others.json @@ -0,0 +1,7 @@ +{ + "codebaseName": "PowerShellCore_201906", + "tools": [ + "CredScan", + "PoliCheck" + ] +} diff --git a/tools/releaseBuild/azureDevOps/templates/compliance/apiscan.yml b/tools/releaseBuild/azureDevOps/templates/compliance/apiscan.yml index c972106195d..aa81407e3e8 100644 --- a/tools/releaseBuild/azureDevOps/templates/compliance/apiscan.yml +++ b/tools/releaseBuild/azureDevOps/templates/compliance/apiscan.yml @@ -121,6 +121,12 @@ jobs: GdnExportGdnToolApiScan: true #this didn't do anything GdnExportCustomLogsFolder: '$(Build.ArtifactStagingDirectory)/Guardian' + - task: TSAUpload@2 + displayName: 'TSA upload' + inputs: + GdnPublishTsaOnboard: false + GdnPublishTsaConfigFile: '$(Build.SourcesDirectory)\tools\guardian\tsaconfig-APIScan.json' + - pwsh: | Get-ChildItem -Path env: displayName: Capture Environment diff --git a/tools/releaseBuild/azureDevOps/templates/compliance/compliance.yml b/tools/releaseBuild/azureDevOps/templates/compliance/compliance.yml index eb0400bc3fe..13603a0c808 100644 --- a/tools/releaseBuild/azureDevOps/templates/compliance/compliance.yml +++ b/tools/releaseBuild/azureDevOps/templates/compliance/compliance.yml @@ -35,7 +35,7 @@ jobs: debugMode: false continueOnError: true - - task: securedevelopmentteam.vss-secure-development-tools.build-task-policheck.PoliCheck@1 + - task: securedevelopmentteam.vss-secure-development-tools.build-task-policheck.PoliCheck@2 displayName: 'Run PoliCheck' inputs: # targetType F means file or folder and is the only applicable value and the default @@ -54,24 +54,15 @@ jobs: optionsUEPath: $(Build.SourcesDirectory)\tools\terms\TermsExclusion.xml continueOnError: true - - task: securedevelopmentteam.vss-secure-development-tools.build-task-publishsecurityanalysislogs.PublishSecurityAnalysisLogs@2 + - task: securedevelopmentteam.vss-secure-development-tools.build-task-publishsecurityanalysislogs.PublishSecurityAnalysisLogs@3 displayName: 'Publish Security Analysis Logs to Build Artifacts' continueOnError: true - - task: securedevelopmentteam.vss-secure-development-tools.build-task-uploadtotsa.TSAUpload@1 - displayName: 'TSA upload to Codebase: PowerShellCore_201906' + - task: TSAUpload@2 + displayName: 'TSA upload' inputs: - tsaVersion: TsaV2 - codeBaseName: 'PowerShellCore_201906' - uploadFortifySCA: false - uploadFxCop: false - uploadModernCop: false - uploadPREfast: false - uploadRoslyn: false - uploadTSLint: false - uploadCredScan: true - uploadPoliCheck: true - uploadBinSkim: false + GdnPublishTsaOnboard: false + GdnPublishTsaConfigFile: '$(Build.SourcesDirectory)\tools\guardian\tsaconfig-others.json' - task: securedevelopmentteam.vss-secure-development-tools.build-task-report.SdtReport@1 displayName: 'Create Security Analysis Report' From 3e1a4d5679e19e6a16a1b57c45492c600f78cb9c Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Wed, 2 Nov 2022 19:52:46 -0700 Subject: [PATCH 165/779] Remove remaining unused strings from resx files (#18448) --- .../resources/AddTypeStrings.resx | 18 ------------------ .../resources/ConvertMarkdownStrings.resx | 3 --- .../resources/HttpCommandStrings.resx | 3 --- .../resources/MeasureObjectStrings.resx | 3 --- .../resources/UtilityCommonStrings.resx | 3 --- .../resources/VariableCommandStrings.resx | 6 ------ .../CommandLineParameterParserStrings.resx | 3 --- .../resources/TranscriptStrings.resx | 3 --- .../resources/CertificateProviderStrings.resx | 3 --- .../resources/HelpDisplayStrings.resx | 9 --------- .../resources/HistoryStrings.resx | 6 ------ .../resources/InternalHostStrings.resx | 3 --- .../resources/ParameterBinderStrings.resx | 6 ------ .../resources/RunspacePoolStrings.resx | 6 ------ 14 files changed, 75 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/AddTypeStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/AddTypeStrings.resx index 75ba47072d2..ae80d7ded59 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/AddTypeStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/AddTypeStrings.resx @@ -120,27 +120,12 @@ The source code was already compiled and loaded. - - The generated type defines no public methods or properties. - - - The generated type is not public. - - - Cannot add type. The -MemberDefinition parameter is not supported for this language. - Cannot add type. The "{0}" extension is not supported. Cannot add type. Input files must all have the same file extension. - - Cannot add type. Specify only the Language or CodeDomProvider parameters. - - - Cannot add type. The assembly name {0} matches both {1} and {2}. - Cannot add type. The assembly '{0}' could not be found. @@ -153,9 +138,6 @@ Cannot add type. Compilation errors occurred. - - Cannot add type. One or more required assemblies are missing. - Cannot add type. The OutputType parameter requires that the OutputAssembly parameter be specified. diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ConvertMarkdownStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ConvertMarkdownStrings.resx index d37509d0f50..d77c7422abe 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/ConvertMarkdownStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ConvertMarkdownStrings.resx @@ -120,9 +120,6 @@ The type of the input object '{0}' is invalid. - - The file is not found: '{0}'. - Only FileSystem Provider paths are supported. The file path is not supported: '{0}'. diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/HttpCommandStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/HttpCommandStrings.resx index 78ccfb68dc1..a5f3e822ce3 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/HttpCommandStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/HttpCommandStrings.resx @@ -117,9 +117,6 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - The command cannot run because "{0}" is empty or blank. Specify a value, and then run the command again. - This command cannot be completed due to the following error: '{0}'. diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/MeasureObjectStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/MeasureObjectStrings.resx index 8211114c335..e27aa35e747 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/MeasureObjectStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/MeasureObjectStrings.resx @@ -120,9 +120,6 @@ The property "{0}" cannot be found in the input for any objects. - - Property "{0}" is not numeric. - Input object "{0}" is not numeric. diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/UtilityCommonStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/UtilityCommonStrings.resx index 551f0d1fcb8..f75c74920c7 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/UtilityCommonStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/UtilityCommonStrings.resx @@ -117,9 +117,6 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - There are no matching results found for {2}. - {2} has one or more exceptions that are not valid. diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/VariableCommandStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/VariableCommandStrings.resx index bff7eee52af..be5d3bbe47d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/VariableCommandStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/VariableCommandStrings.resx @@ -129,12 +129,6 @@ Name: {0} Value: {1} - - Add variable - - - Name: {0} - Remove variable diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/CommandLineParameterParserStrings.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/CommandLineParameterParserStrings.resx index e346331b414..92f0cf0f1e7 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/resources/CommandLineParameterParserStrings.resx +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/CommandLineParameterParserStrings.resx @@ -120,9 +120,6 @@ Cannot process command because a command is already specified with -Command or -EncodedCommand. - - Unable to read from file '{0}'. - Cannot process the command because of a missing parameter. A command must follow -Command. diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/TranscriptStrings.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/TranscriptStrings.resx index c2a2826955c..9fe6f988e58 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/resources/TranscriptStrings.resx +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/TranscriptStrings.resx @@ -117,9 +117,6 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - This host does not support transcription. - Transcript started, output file is {0} diff --git a/src/Microsoft.PowerShell.Security/resources/CertificateProviderStrings.resx b/src/Microsoft.PowerShell.Security/resources/CertificateProviderStrings.resx index ded11aab0a2..c45c640bbb0 100644 --- a/src/Microsoft.PowerShell.Security/resources/CertificateProviderStrings.resx +++ b/src/Microsoft.PowerShell.Security/resources/CertificateProviderStrings.resx @@ -144,9 +144,6 @@ Invoke Certificate Manager - - {0} is not supported in the current operating system. - Item: {0} Destination: {1} diff --git a/src/System.Management.Automation/resources/HelpDisplayStrings.resx b/src/System.Management.Automation/resources/HelpDisplayStrings.resx index 222c57e3300..8656518d531 100644 --- a/src/System.Management.Automation/resources/HelpDisplayStrings.resx +++ b/src/System.Management.Automation/resources/HelpDisplayStrings.resx @@ -183,9 +183,6 @@ Content: - - Output: - PROVIDER NAME @@ -267,9 +264,6 @@ Cmdlets Supported: - - CMDLETS SUPPORTED - ALIASES @@ -361,9 +355,6 @@ Error extracting Help content. - - Error installing help content. - Unable to connect to Help content. The server on which Help content is stored might not be available. Verify that the server is available, or wait until the server is back online, and then try the command again. diff --git a/src/System.Management.Automation/resources/HistoryStrings.resx b/src/System.Management.Automation/resources/HistoryStrings.resx index c20b5bc6855..7bc4c076521 100644 --- a/src/System.Management.Automation/resources/HistoryStrings.resx +++ b/src/System.Management.Automation/resources/HistoryStrings.resx @@ -117,9 +117,6 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - Cannot locate history. - The identifier {0} is not a valid value for a History identifier. Specify a positive number, and then try again. @@ -147,9 +144,6 @@ The identifier {0} is not valid. Specify a positive number, and then try again. - - Note: {0} entries were cleared from the session history. - This command will clear all the entries from the session history. diff --git a/src/System.Management.Automation/resources/InternalHostStrings.resx b/src/System.Management.Automation/resources/InternalHostStrings.resx index 861c7609d05..cf0a17e16e8 100644 --- a/src/System.Management.Automation/resources/InternalHostStrings.resx +++ b/src/System.Management.Automation/resources/InternalHostStrings.resx @@ -117,9 +117,6 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - Cannot exit a nested prompt because no nested prompts exist. - EnterNestedPrompt has not been called as many times as ExitNestedPrompt. diff --git a/src/System.Management.Automation/resources/ParameterBinderStrings.resx b/src/System.Management.Automation/resources/ParameterBinderStrings.resx index 8c49becc278..88cb8cade8d 100644 --- a/src/System.Management.Automation/resources/ParameterBinderStrings.resx +++ b/src/System.Management.Automation/resources/ParameterBinderStrings.resx @@ -174,9 +174,6 @@ Cannot retrieve the dynamic parameters for the cmdlet. {6} - - Cannot retrieve dynamic parameters for the cmdlet. Dynamic parameter '{1}' specified parameter set '{6}' which was not statically defined for this cmdlet. New parameter sets may not be defined as dynamic parameters, although dynamic parameters may join parameter sets which were statically defined. - Supply values for the following parameters: @@ -222,9 +219,6 @@ Multiple different default values are defined in $PSDefaultParameterValues for the parameter matching the following name or alias: {0}. These defaults have been ignored. - - The automatic variable $PSDefaultParameterValues was ignored because it is not a valid hashtable object. It must be of the type IDictionary. - The following name or alias defined in $PSDefaultParameterValues for this cmdlet resolves to multiple parameters: {0}. The default has been ignored. diff --git a/src/System.Management.Automation/resources/RunspacePoolStrings.resx b/src/System.Management.Automation/resources/RunspacePoolStrings.resx index 515bcece698..1b44e1ea3b0 100644 --- a/src/System.Management.Automation/resources/RunspacePoolStrings.resx +++ b/src/System.Management.Automation/resources/RunspacePoolStrings.resx @@ -117,9 +117,6 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - The runspace pool is closed. - The maximum pool size cannot be less than 1. @@ -150,9 +147,6 @@ This runspace does not support disconnect and connect operations. - - Cannot set the TypeTable data unless the runspace pool is in either the Disconnected or BeforeOpen states. Current state is {0}. - Cannot perform the operation because the runspace pool is in the Disconnected state. From 52a62e9ef2329ab5642bd5c9b20088d104b1fd01 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Wed, 2 Nov 2022 19:54:11 -0700 Subject: [PATCH 166/779] Fix `Switch-Process` error to include the command that is not found (#18443) --- .../engine/Modules/SwitchProcessCommand.cs | 4 ++-- .../Modules/Microsoft.PowerShell.Core/Exec.Tests.ps1 | 7 +++++++ test/xUnit/csharp/test_Feedback.cs | 2 +- 3 files changed, 10 insertions(+), 3 deletions(-) diff --git a/src/System.Management.Automation/engine/Modules/SwitchProcessCommand.cs b/src/System.Management.Automation/engine/Modules/SwitchProcessCommand.cs index 4700c425dbc..5e0cee66847 100644 --- a/src/System.Management.Automation/engine/Modules/SwitchProcessCommand.cs +++ b/src/System.Management.Automation/engine/Modules/SwitchProcessCommand.cs @@ -46,12 +46,12 @@ protected override void EndProcessing() string.Format( System.Globalization.CultureInfo.InvariantCulture, CommandBaseStrings.NativeCommandNotFound, - command + WithCommand[0] ) ), "CommandNotFound", ErrorCategory.InvalidArgument, - WithCommand + WithCommand[0] ) ); } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Core/Exec.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Core/Exec.Tests.ps1 index 858a04fb4e8..21813a02a3b 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Core/Exec.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Core/Exec.Tests.ps1 @@ -48,6 +48,13 @@ Describe 'Switch-Process tests for Unix' -Tags 'CI' { ($p | Get-Process).Name -eq 'sleep' } -timeout 60000 -interval 100 | Should -BeTrue } + + It 'Error is returned if target command is not found' { + $invalidCommand = 'doesNotExist' + $e = { Switch-Process $invalidCommand } | Should -Throw -ErrorId 'CommandNotFound,Microsoft.PowerShell.Commands.SwitchProcessCommand' -PassThru + $e.Exception.Message | Should -BeLike "*'$invalidCommand'*" + $e.TargetObject | Should -BeExactly $invalidCommand + } } Describe 'Switch-Process for Windows' -Tag 'CI' { diff --git a/test/xUnit/csharp/test_Feedback.cs b/test/xUnit/csharp/test_Feedback.cs index 9d7588a880d..372c9ec8cc4 100644 --- a/test/xUnit/csharp/test_Feedback.cs +++ b/test/xUnit/csharp/test_Feedback.cs @@ -48,7 +48,7 @@ public string GetFeedback(string commandLine, ErrorRecord errorRecord, Cancellat { // The delay is exaggerated to make the test reliable. // xUnit must spin up a lot tasks, which makes the test unreliable when the time difference between 'delay' and 'timeout' is small. - Thread.Sleep(2000); + Thread.Sleep(2500); } return $"{commandLine}+{errorRecord.FullyQualifiedErrorId}"; From 455d29471c062f5d1230da589ec3d37de9a4dee0 Mon Sep 17 00:00:00 2001 From: Ikko Ashimine Date: Thu, 3 Nov 2022 15:01:13 +0900 Subject: [PATCH 167/779] Fix typo in InitialSessionState.cs (#18435) controling -> controlling --- .../engine/InitialSessionState.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/System.Management.Automation/engine/InitialSessionState.cs b/src/System.Management.Automation/engine/InitialSessionState.cs index 751c9655e0d..6d8ede14ddb 100644 --- a/src/System.Management.Automation/engine/InitialSessionState.cs +++ b/src/System.Management.Automation/engine/InitialSessionState.cs @@ -652,7 +652,7 @@ public override InitialSessionStateEntry Clone() public string Description { get; } = string.Empty; /// - /// Options controling scope visibility and setability for this entry. + /// Options controlling scope visibility and setability for this entry. /// public ScopedItemOptions Options { get; } = ScopedItemOptions.None; } @@ -809,7 +809,7 @@ internal void SetHelpFile(string help) internal ScriptBlock ScriptBlock { get; set; } /// - /// Options controling scope visibility and setability for this entry. + /// Options controlling scope visibility and setability for this entry. /// public ScopedItemOptions Options { get; } = ScopedItemOptions.None; From db21524d2385b33483276fd8ac2f0e04bd80a61e Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Thu, 3 Nov 2022 11:44:46 -0700 Subject: [PATCH 168/779] Add missing XML doc elements for methods in `RunspaceFactory` (#18450) --- .../engine/hostifaces/ConnectionFactory.cs | 68 +++++++++++++------ .../hostifaces/PowerShellProcessInstance.cs | 18 ++--- 2 files changed, 58 insertions(+), 28 deletions(-) diff --git a/src/System.Management.Automation/engine/hostifaces/ConnectionFactory.cs b/src/System.Management.Automation/engine/hostifaces/ConnectionFactory.cs index 014eed0f548..45591ee2906 100644 --- a/src/System.Management.Automation/engine/hostifaces/ConnectionFactory.cs +++ b/src/System.Management.Automation/engine/hostifaces/ConnectionFactory.cs @@ -476,58 +476,64 @@ connectionInfo is not VMConnectionInfo && #region Runspace - Remote Factory /// + /// Creates a remote Runspace. /// + /// It defines connection path to a remote runspace that needs to be created. + /// The explicit PSHost implementation. /// /// The TypeTable to use while deserializing/serializing remote objects. /// TypeTable has the following information used by serializer: /// 1. SerializationMethod /// 2. SerializationDepth /// 3. SpecificSerializationProperties + /// /// TypeTable has the following information used by deserializer: /// 1. TargetTypeForDeserialization /// 2. TypeConverter /// - /// - /// - /// + /// A remote Runspace. public static Runspace CreateRunspace(RunspaceConnectionInfo connectionInfo, PSHost host, TypeTable typeTable) { return CreateRunspace(connectionInfo, host, typeTable, null, null); } /// + /// Creates a remote Runspace. /// + /// It defines connection path to a remote runspace that needs to be created. + /// The explicit PSHost implementation. /// /// The TypeTable to use while deserializing/serializing remote objects. /// TypeTable has the following information used by serializer: /// 1. SerializationMethod /// 2. SerializationDepth /// 3. SpecificSerializationProperties + /// /// TypeTable has the following information used by deserializer: /// 1. TargetTypeForDeserialization /// 2. TypeConverter /// - /// - /// /// /// Application arguments the server can see in /// - /// + /// A remote Runspace. public static Runspace CreateRunspace(RunspaceConnectionInfo connectionInfo, PSHost host, TypeTable typeTable, PSPrimitiveDictionary applicationArguments) { return CreateRunspace(connectionInfo, host, typeTable, applicationArguments, null); } /// + /// Creates a remote Runspace. /// - /// - /// + /// It defines connection path to a remote runspace that needs to be created. + /// The explicit PSHost implementation. /// /// The TypeTable to use while deserializing/serializing remote objects. /// TypeTable has the following information used by serializer: /// 1. SerializationMethod /// 2. SerializationDepth /// 3. SpecificSerializationProperties + /// /// TypeTable has the following information used by deserializer: /// 1. TargetTypeForDeserialization /// 2. TypeConverter @@ -536,7 +542,7 @@ public static Runspace CreateRunspace(RunspaceConnectionInfo connectionInfo, PSH /// Application arguments the server can see in /// /// Name for remote runspace. - /// + /// A remote Runspace. public static Runspace CreateRunspace(RunspaceConnectionInfo connectionInfo, PSHost host, TypeTable typeTable, PSPrimitiveDictionary applicationArguments, string name) { if (connectionInfo is WSManConnectionInfo) @@ -548,19 +554,21 @@ public static Runspace CreateRunspace(RunspaceConnectionInfo connectionInfo, PSH } /// + /// Creates a remote Runspace. /// - /// - /// - /// + /// The explicit PSHost implementation. + /// It defines connection path to a remote runspace that needs to be created. + /// A remote Runspace. public static Runspace CreateRunspace(PSHost host, RunspaceConnectionInfo connectionInfo) { return CreateRunspace(connectionInfo, host, null); } /// + /// Creates a remote Runspace. /// - /// - /// + /// It defines connection path to a remote runspace that needs to be created. + /// A remote Runspace. public static Runspace CreateRunspace(RunspaceConnectionInfo connectionInfo) { return CreateRunspace(null, connectionInfo); @@ -571,9 +579,20 @@ public static Runspace CreateRunspace(RunspaceConnectionInfo connectionInfo) #region V3 Extensions /// + /// Creates an out-of-process remote Runspace. /// - /// - /// + /// + /// The TypeTable to use while deserializing/serializing remote objects. + /// TypeTable has the following information used by serializer: + /// 1. SerializationMethod + /// 2. SerializationDepth + /// 3. SpecificSerializationProperties + /// + /// TypeTable has the following information used by deserializer: + /// 1. TargetTypeForDeserialization + /// 2. TypeConverter + /// + /// An out-of-process remote Runspace. public static Runspace CreateOutOfProcessRunspace(TypeTable typeTable) { NewProcessConnectionInfo connectionInfo = new NewProcessConnectionInfo(null); @@ -582,10 +601,21 @@ public static Runspace CreateOutOfProcessRunspace(TypeTable typeTable) } /// + /// Creates an out-of-process remote Runspace. /// - /// - /// - /// + /// + /// The TypeTable to use while deserializing/serializing remote objects. + /// TypeTable has the following information used by serializer: + /// 1. SerializationMethod + /// 2. SerializationDepth + /// 3. SpecificSerializationProperties + /// + /// TypeTable has the following information used by deserializer: + /// 1. TargetTypeForDeserialization + /// 2. TypeConverter + /// + /// It represents a PowerShell process that is used for an out-of-process remote Runspace + /// An out-of-process remote Runspace. public static Runspace CreateOutOfProcessRunspace(TypeTable typeTable, PowerShellProcessInstance processInstance) { NewProcessConnectionInfo connectionInfo = new NewProcessConnectionInfo(null) { Process = processInstance }; diff --git a/src/System.Management.Automation/engine/hostifaces/PowerShellProcessInstance.cs b/src/System.Management.Automation/engine/hostifaces/PowerShellProcessInstance.cs index 3f4dcf40744..076aee75ae6 100644 --- a/src/System.Management.Automation/engine/hostifaces/PowerShellProcessInstance.cs +++ b/src/System.Management.Automation/engine/hostifaces/PowerShellProcessInstance.cs @@ -11,6 +11,7 @@ namespace System.Management.Automation.Runspaces { /// + /// This class represents a PowerShell process that is used for an out-of-process remote Runspace. /// public sealed class PowerShellProcessInstance : IDisposable { @@ -30,8 +31,6 @@ public sealed class PowerShellProcessInstance : IDisposable #region Constructors - /// - /// static PowerShellProcessInstance() { #if UNIX @@ -145,10 +144,10 @@ public PowerShellProcessInstance(Version powerShellVersion, PSCredential credent /// /// Initializes a new instance of the class. Initializes the underlying dotnet process class. /// - /// - /// - /// - /// + /// Specifies the version of powershell. + /// Specifies a user account credentials. + /// Specifies a script that will be executed when the powershell process is initialized. + /// Specifies if the powershell process will be 32-bit. public PowerShellProcessInstance(Version powerShellVersion, PSCredential credential, ScriptBlock initializationScript, bool useWow64) : this(powerShellVersion, credential, initializationScript, useWow64, workingDirectory: null) { } @@ -178,7 +177,9 @@ public bool HasExited #endregion Constructors #region Dispose + /// + /// Implementing the interface. /// public void Dispose() { @@ -186,9 +187,6 @@ public void Dispose() GC.SuppressFinalize(this); } - /// - /// - /// private void Dispose(bool disposing) { if (_isDisposed) return; @@ -220,7 +218,9 @@ private void Dispose(bool disposing) #endregion Dispose #region Public Properties + /// + /// Gets the process object of the remote target. /// public Process Process { get; } From 39756d5602546d5956d4e8d87922efa1e35f0d83 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Thu, 3 Nov 2022 12:27:08 -0700 Subject: [PATCH 169/779] Update .gitignore to ignore some test generated files (#18447) --- .gitignore | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.gitignore b/.gitignore index cbf0016dd16..61ad9efb407 100644 --- a/.gitignore +++ b/.gitignore @@ -92,3 +92,9 @@ test/tools/Modules/SelfSignedCertificate/ # BenchmarkDotNet artifacts test/perf/BenchmarkDotNet.Artifacts/ + +# Test generated module +test/tools/Modules/Microsoft.PowerShell.NamedPipeConnection/ + +# Test generated startup profile +StartupProfileData-NonInteractive From a2ee05400f8cb4a44cd87742f95ebc2c3472e649 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Fri, 4 Nov 2022 15:12:09 -0700 Subject: [PATCH 170/779] Fix `Switch-Process` to set termios appropriate for child process (#18467) --- .../engine/Modules/SwitchProcessCommand.cs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/System.Management.Automation/engine/Modules/SwitchProcessCommand.cs b/src/System.Management.Automation/engine/Modules/SwitchProcessCommand.cs index 5e0cee66847..57345182310 100644 --- a/src/System.Management.Automation/engine/Modules/SwitchProcessCommand.cs +++ b/src/System.Management.Automation/engine/Modules/SwitchProcessCommand.cs @@ -69,10 +69,12 @@ protected override void EndProcessing() // need null terminator at end execArgs[execArgs.Length - 1] = null; + // setup termios for a child process as .NET modifies termios dynamically for use with ReadKey() + ConfigureTerminalForChildProcess(true); int exitCode = Exec(command.Source, execArgs); - if (exitCode < 0) { + ConfigureTerminalForChildProcess(false); ThrowTerminatingError( new ErrorRecord( new Exception( @@ -108,6 +110,10 @@ protected override void EndProcessing() CharSet = CharSet.Ansi, SetLastError = true)] private static extern int Exec(string path, string?[] args); + + // leverage .NET runtime's native library which abstracts the need to handle different OS and architectures for termios api + [DllImport("libSystem.Native", EntryPoint = "SystemNative_ConfigureTerminalForChildProcess")] + private static extern void ConfigureTerminalForChildProcess([MarshalAs(UnmanagedType.Bool)] bool childUsesTerminal); } } From 1688b0fc356af9f2f9f8bae1e8304bc0929d51a5 Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Mon, 7 Nov 2022 18:07:36 +0000 Subject: [PATCH 171/779] Replace `UTF8Encoding(false)` with `Encoding.Default` (#18356) --- .../commands/utility/CsvCommands.cs | 4 ++-- .../FormatAndOutput/format-hex/Format-Hex.cs | 2 +- .../FormatAndOutput/out-file/Out-File.cs | 2 +- .../utility/ImplicitRemotingCommands.cs | 2 +- .../commands/utility/MatchString.cs | 2 +- .../commands/utility/Tee-Object.cs | 2 +- .../commands/utility/XmlCommands.cs | 2 +- .../engine/ExternalScriptInfo.cs | 4 +--- .../engine/Modules/ScriptAnalysis.cs | 3 +-- .../namespaces/FileSystemContentStream.cs | 2 +- .../namespaces/FileSystemProvider.cs | 6 +++--- .../utils/ClrFacade.cs | 21 ++----------------- .../utils/EncodingUtils.cs | 8 +++---- 13 files changed, 20 insertions(+), 40 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs index eb3ebacff4a..c42977996ae 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs @@ -229,7 +229,7 @@ public Encoding Encoding } } - private Encoding _encoding = ClrFacade.GetDefaultEncoding(); + private Encoding _encoding = Encoding.Default; /// /// Gets or sets property that sets append parameter. @@ -615,7 +615,7 @@ public Encoding Encoding } } - private Encoding _encoding = ClrFacade.GetDefaultEncoding(); + private Encoding _encoding = Encoding.Default; /// /// Avoid writing out duplicate warning messages when there are one or more unspecified names. diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-hex/Format-Hex.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-hex/Format-Hex.cs index 90d007adb2a..de73b2155a6 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-hex/Format-Hex.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-hex/Format-Hex.cs @@ -85,7 +85,7 @@ public Encoding Encoding } } - private Encoding _encoding = ClrFacade.GetDefaultEncoding(); + private Encoding _encoding = Encoding.Default; /// /// Gets or sets count of bytes to read from the input stream. diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-file/Out-File.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-file/Out-File.cs index 2fbdb73dc9c..50025b12f97 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-file/Out-File.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-file/Out-File.cs @@ -91,7 +91,7 @@ public Encoding Encoding } } - private Encoding _encoding = ClrFacade.GetDefaultEncoding(); + private Encoding _encoding = Encoding.Default; /// /// Property that sets append parameter. diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs index f0044dd1885..8c378c41658 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs @@ -90,7 +90,7 @@ public Encoding Encoding } } - private Encoding _encoding = ClrFacade.GetDefaultEncoding(); + private Encoding _encoding = Encoding.Default; #endregion Parameters diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs index b9964d92bcb..d6e0b004bdf 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs @@ -1363,7 +1363,7 @@ public Encoding Encoding } } - private Encoding _encoding = ClrFacade.GetDefaultEncoding(); + private Encoding _encoding = Encoding.Default; /// /// Gets or sets the number of context lines to collect. If set to a diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Tee-Object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Tee-Object.cs index a23b0be61dc..d8b3261c118 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Tee-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Tee-Object.cs @@ -81,7 +81,7 @@ public SwitchParameter Append [ArgumentToEncodingTransformationAttribute] [ArgumentEncodingCompletionsAttribute] [ValidateNotNullOrEmpty] - public Encoding Encoding { get; set; } = ClrFacade.GetDefaultEncoding(); + public Encoding Encoding { get; set; } = Encoding.Default; /// /// Variable parameter. diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs index 74a8ee1b7c9..1ce259b726e 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs @@ -128,7 +128,7 @@ public Encoding Encoding } } - private Encoding _encoding = ClrFacade.GetDefaultEncoding(); + private Encoding _encoding = Encoding.Default; #endregion Command Line Parameters diff --git a/src/System.Management.Automation/engine/ExternalScriptInfo.cs b/src/System.Management.Automation/engine/ExternalScriptInfo.cs index bcd75bf85f3..a44e514c785 100644 --- a/src/System.Management.Automation/engine/ExternalScriptInfo.cs +++ b/src/System.Management.Automation/engine/ExternalScriptInfo.cs @@ -515,9 +515,7 @@ private void ReadScriptContents() { using (FileStream readerStream = new FileStream(_path, FileMode.Open, FileAccess.Read)) { - Encoding defaultEncoding = ClrFacade.GetDefaultEncoding(); - - using (StreamReader scriptReader = new StreamReader(readerStream, defaultEncoding)) + using (StreamReader scriptReader = new StreamReader(readerStream, Encoding.Default)) { _scriptContents = scriptReader.ReadToEnd(); _originalEncoding = scriptReader.CurrentEncoding; diff --git a/src/System.Management.Automation/engine/Modules/ScriptAnalysis.cs b/src/System.Management.Automation/engine/Modules/ScriptAnalysis.cs index 8720fc1f161..f8b188f47b5 100644 --- a/src/System.Management.Automation/engine/Modules/ScriptAnalysis.cs +++ b/src/System.Management.Automation/engine/Modules/ScriptAnalysis.cs @@ -94,10 +94,9 @@ internal static string ReadScript(string path) { using (FileStream readerStream = new FileStream(path, FileMode.Open, FileAccess.Read)) { - Encoding defaultEncoding = ClrFacade.GetDefaultEncoding(); Microsoft.Win32.SafeHandles.SafeFileHandle safeFileHandle = readerStream.SafeFileHandle; - using (StreamReader scriptReader = new StreamReader(readerStream, defaultEncoding)) + using (StreamReader scriptReader = new StreamReader(readerStream, Encoding.Default)) { return scriptReader.ReadToEnd(); } diff --git a/src/System.Management.Automation/namespaces/FileSystemContentStream.cs b/src/System.Management.Automation/namespaces/FileSystemContentStream.cs index 352298107d5..4d3a01543b7 100644 --- a/src/System.Management.Automation/namespaces/FileSystemContentStream.cs +++ b/src/System.Management.Automation/namespaces/FileSystemContentStream.cs @@ -794,7 +794,7 @@ private bool ReadByteEncoded(bool waitChanges, List blocks, bool readBac // the changes if (waitChanges) { - WaitForChanges(_path, _mode, _access, _share, ClrFacade.GetDefaultEncoding()); + WaitForChanges(_path, _mode, _access, _share, Encoding.Default); byteRead = _stream.ReadByte(); } } diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index 1d434a06e49..79ed698f45e 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -6610,7 +6610,7 @@ public IContentReader GetContentReader(string path) // Defaults for the file read operation string delimiter = "\n"; - Encoding encoding = ClrFacade.GetDefaultEncoding(); + Encoding encoding = Encoding.Default; bool waitForChanges = false; bool streamTypeSpecified = false; @@ -6792,7 +6792,7 @@ public IContentWriter GetContentWriter(string path) // If this is true, then the content will be read as bytes bool usingByteEncoding = false; bool streamTypeSpecified = false; - Encoding encoding = ClrFacade.GetDefaultEncoding(); + Encoding encoding = Encoding.Default; const FileMode filemode = FileMode.OpenOrCreate; string streamName = null; bool suppressNewline = false; @@ -7668,7 +7668,7 @@ public Encoding Encoding } } - private Encoding _encoding = ClrFacade.GetDefaultEncoding(); + private Encoding _encoding = Encoding.Default; /// /// Return file contents as a byte stream or create file from a series of bytes. diff --git a/src/System.Management.Automation/utils/ClrFacade.cs b/src/System.Management.Automation/utils/ClrFacade.cs index cabac1bd335..2331eb15ce9 100644 --- a/src/System.Management.Automation/utils/ClrFacade.cs +++ b/src/System.Management.Automation/utils/ClrFacade.cs @@ -100,23 +100,6 @@ private static IEnumerable GetPSVisibleAssemblies() #region Encoding - /// - /// Facade for getting default encoding. - /// - internal static Encoding GetDefaultEncoding() - { - if (s_defaultEncoding == null) - { - // load all available encodings - EncodingRegisterProvider(); - s_defaultEncoding = new UTF8Encoding(false); - } - - return s_defaultEncoding; - } - - private static volatile Encoding s_defaultEncoding; - /// /// Facade for getting OEM encoding /// OEM encodings work on all platforms, or rather codepage 437 is available on both Windows and Non-Windows. @@ -142,7 +125,7 @@ internal static Encoding GetOEMEncoding() private static void EncodingRegisterProvider() { - if (s_defaultEncoding == null && s_oemEncoding == null) + if (s_oemEncoding == null) { Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); } @@ -263,7 +246,7 @@ private static SecurityZone ReadFromZoneIdentifierDataStream(string filePath) } // If we successfully get the zone data stream, try to read the ZoneId information - using (StreamReader zoneDataReader = new StreamReader(zoneDataStream, GetDefaultEncoding())) + using (StreamReader zoneDataReader = new StreamReader(zoneDataStream, Encoding.Default)) { string line = null; bool zoneTransferMatched = false; diff --git a/src/System.Management.Automation/utils/EncodingUtils.cs b/src/System.Management.Automation/utils/EncodingUtils.cs index e9802488006..b2ee2d8c877 100644 --- a/src/System.Management.Automation/utils/EncodingUtils.cs +++ b/src/System.Management.Automation/utils/EncodingUtils.cs @@ -33,15 +33,15 @@ internal static class EncodingConversion { Ascii, System.Text.Encoding.ASCII }, { BigEndianUnicode, System.Text.Encoding.BigEndianUnicode }, { BigEndianUtf32, new UTF32Encoding(bigEndian: true, byteOrderMark: true) }, - { Default, ClrFacade.GetDefaultEncoding() }, + { Default, Encoding.Default }, { OEM, ClrFacade.GetOEMEncoding() }, { Unicode, System.Text.Encoding.Unicode }, #pragma warning disable SYSLIB0001 { Utf7, System.Text.Encoding.UTF7 }, #pragma warning restore SYSLIB0001 - { Utf8, ClrFacade.GetDefaultEncoding() }, + { Utf8, Encoding.Default }, { Utf8Bom, System.Text.Encoding.UTF8 }, - { Utf8NoBom, ClrFacade.GetDefaultEncoding() }, + { Utf8NoBom, Encoding.Default }, { Utf32, System.Text.Encoding.UTF32 }, { String, System.Text.Encoding.Unicode }, { Unknown, System.Text.Encoding.Unicode }, @@ -57,7 +57,7 @@ internal static Encoding Convert(Cmdlet cmdlet, string encoding) if (string.IsNullOrEmpty(encoding)) { // no parameter passed, default to UTF8 - return ClrFacade.GetDefaultEncoding(); + return Encoding.Default; } Encoding foundEncoding; From 0ddf89e5a8a9fc45f677efb1ace90d41dd9d081c Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Mon, 7 Nov 2022 11:03:37 -0800 Subject: [PATCH 172/779] Fix `Switch-Process` to copy the current env to the new process (#18452) --- .../engine/Modules/SwitchProcessCommand.cs | 20 ++++++++++++++++--- .../Microsoft.PowerShell.Core/Exec.Tests.ps1 | 5 +++++ 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/src/System.Management.Automation/engine/Modules/SwitchProcessCommand.cs b/src/System.Management.Automation/engine/Modules/SwitchProcessCommand.cs index 57345182310..84d14939356 100644 --- a/src/System.Management.Automation/engine/Modules/SwitchProcessCommand.cs +++ b/src/System.Management.Automation/engine/Modules/SwitchProcessCommand.cs @@ -4,6 +4,7 @@ #nullable enable using System; +using System.Collections; using System.Collections.Generic; using System.Management.Automation; using System.Runtime.InteropServices; @@ -69,9 +70,19 @@ protected override void EndProcessing() // need null terminator at end execArgs[execArgs.Length - 1] = null; + var env = Environment.GetEnvironmentVariables(); + var envBlock = new string?[env.Count + 1]; + int j = 0; + foreach (DictionaryEntry entry in env) + { + envBlock[j++] = entry.Key + "=" + entry.Value; + } + + envBlock[envBlock.Length - 1] = null; + // setup termios for a child process as .NET modifies termios dynamically for use with ReadKey() ConfigureTerminalForChildProcess(true); - int exitCode = Exec(command.Source, execArgs); + int exitCode = Exec(command.Source, execArgs, envBlock); if (exitCode < 0) { ConfigureTerminalForChildProcess(false); @@ -101,15 +112,18 @@ protected override void EndProcessing() /// The arguments to send through to the executable. /// Array must have its final element be null. /// + /// + /// The environment variables to send through to the executable in the form of "key=value". + /// Array must have its final element be null. /// /// An exit code if exec failed, but if successful the calling process will be overwritten. /// [DllImport("libc", - EntryPoint = "execv", + EntryPoint = "execve", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, SetLastError = true)] - private static extern int Exec(string path, string?[] args); + private static extern int Exec(string path, string?[] args, string?[] env); // leverage .NET runtime's native library which abstracts the need to handle different OS and architectures for termios api [DllImport("libSystem.Native", EntryPoint = "SystemNative_ConfigureTerminalForChildProcess")] diff --git a/test/powershell/Modules/Microsoft.PowerShell.Core/Exec.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Core/Exec.Tests.ps1 index 21813a02a3b..c4b4ce0e595 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Core/Exec.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Core/Exec.Tests.ps1 @@ -55,6 +55,11 @@ Describe 'Switch-Process tests for Unix' -Tags 'CI' { $e.Exception.Message | Should -BeLike "*'$invalidCommand'*" $e.TargetObject | Should -BeExactly $invalidCommand } + + It 'The environment will be copied to the child process' { + $env = pwsh -noprofile -outputformat text -command { $env:TEST_FOO='my test = value'; Switch-Process bash -c 'echo $TEST_FOO' } + $env | Should -BeExactly 'my test = value' + } } Describe 'Switch-Process for Windows' -Tag 'CI' { From 134149e917b9faa3f178fb5dcc299c619cd4e620 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 7 Nov 2022 17:07:57 -0800 Subject: [PATCH 173/779] Bump Microsoft.CodeAnalysis.NetAnalyzers (#18442) --- Analyzers.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Analyzers.props b/Analyzers.props index 4117ed85883..f2d6a44ec1c 100644 --- a/Analyzers.props +++ b/Analyzers.props @@ -1,7 +1,7 @@ - + From b5ffd043c5421284cedf199d897b8e4112d53e48 Mon Sep 17 00:00:00 2001 From: MartinGC94 <42123497+MartinGC94@users.noreply.github.com> Date: Tue, 8 Nov 2022 02:10:03 +0100 Subject: [PATCH 174/779] Improve type inference of hashtable keys (#17907) --- .../engine/parser/TypeInferenceVisitor.cs | 61 +++++++++++++------ .../engine/Api/TypeInference.Tests.ps1 | 13 ++++ 2 files changed, 55 insertions(+), 19 deletions(-) diff --git a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs index b48a35e7502..f21fb0f4f6d 100644 --- a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs +++ b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs @@ -540,7 +540,6 @@ object ICustomAstVisitor.VisitHashtable(HashtableAst hashtableAst) foreach (var kv in hashtableAst.KeyValuePairs) { string name = null; - string typeName = null; if (kv.Item1 is StringConstantExpressionAst stringConstantExpressionAst) { name = stringConstantExpressionAst.Value; @@ -554,32 +553,46 @@ object ICustomAstVisitor.VisitHashtable(HashtableAst hashtableAst) name = nameValue.ToString(); } - if (name != null) + if (name is not null) { - object value = null; if (kv.Item2 is PipelineAst pipelineAst && pipelineAst.GetPureExpression() is ExpressionAst expression) { - switch (expression) + object value; + if (expression is ConstantExpressionAst constant) { - case ConstantExpressionAst constantExpression: - value = constantExpression.Value; - break; - default: - typeName = InferTypes(kv.Item2).FirstOrDefault()?.Name; - if (typeName == null) - { - if (SafeExprEvaluator.TrySafeEval(expression, _context.ExecutionContext, out object safeValue)) - { - value = safeValue; - } - } + value = constant.Value; + } + else + { + _ = SafeExprEvaluator.TrySafeEval(expression, _context.ExecutionContext, out value); + } - break; + PSTypeName valueType; + if (value is null) + { + valueType = new PSTypeName("System.Object"); } + else + { + valueType = new PSTypeName(value.GetType()); + } + + properties.Add(new PSMemberNameAndType(name, valueType, value)); } + else + { + bool foundAnyTypes = false; + foreach (var item in InferTypes(kv.Item2)) + { + foundAnyTypes = true; + properties.Add(new PSMemberNameAndType(name, item)); + } - var pstypeName = value != null ? new PSTypeName(value.GetType()) : new PSTypeName(typeName ?? "System.Object"); - properties.Add(new PSMemberNameAndType(name, pstypeName, value)); + if (!foundAnyTypes) + { + properties.Add(new PSMemberNameAndType(name, new PSTypeName("System.Object"))); + } + } } } @@ -2257,6 +2270,16 @@ private IEnumerable InferTypeFrom(IndexExpressionAst indexExpression bool foundAny = false; foreach (var psType in targetTypes) { + if (psType is PSSyntheticTypeName syntheticType) + { + foreach (var member in syntheticType.Members) + { + yield return member.PSTypeName; + } + + continue; + } + var type = psType.Type; if (type != null) { diff --git a/test/powershell/engine/Api/TypeInference.Tests.ps1 b/test/powershell/engine/Api/TypeInference.Tests.ps1 index 5eca91ca0c0..8a77945d03b 100644 --- a/test/powershell/engine/Api/TypeInference.Tests.ps1 +++ b/test/powershell/engine/Api/TypeInference.Tests.ps1 @@ -1091,6 +1091,7 @@ Describe "Type inference Tests" -tags "CI" { $res | Should -HaveCount 1 $res.Name | Should -Be System.Guid } + It 'Infers type of variable $_ in array of calculated properties' { $variableAst = { New-TimeSpan | Select-Object -Property Day,@{n="min";e={$_}} }.Ast.Find({ param($a) $a -is [System.Management.Automation.Language.VariableExpressionAst] }, $true) $res = [AstTypeInference]::InferTypeOf($variableAst) @@ -1353,6 +1354,18 @@ Describe "Type inference Tests" -tags "CI" { $res.Count | Should -Be 1 $res.Name | Should -Be 'System.Management.Automation.Language.Ast' } + + It 'Infers type of hashtable key with multiple types' { + $res = [AstTypeInference]::InferTypeOf( { (@{RandomKey = Get-ChildItem $HOME}).RandomKey }.Ast) + $res.Count | Should -Be 2 + $res.Name -join ' ' | Should -Be "System.IO.FileInfo System.IO.DirectoryInfo" + } + + It 'Infers type of index expression on hashtable with synthetic type' { + $res = [AstTypeInference]::InferTypeOf( { (@{RandomKey = Get-ChildItem $HOME})['RandomKey'] }.Ast) + $res.Count | Should -Be 2 + $res.Name -join ' ' | Should -Be "System.IO.FileInfo System.IO.DirectoryInfo" + } } Describe "AstTypeInference tests" -Tags CI { From 0a6de4672a8c31d2142371b01a199c7759a19866 Mon Sep 17 00:00:00 2001 From: MartinGC94 <42123497+MartinGC94@users.noreply.github.com> Date: Tue, 8 Nov 2022 02:14:49 +0100 Subject: [PATCH 175/779] Fix issue when completing the first command in a script with an empty array expression (#18355) --- .../engine/CommandCompletion/CompletionAnalysis.cs | 5 ++++- test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 | 5 +++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs index 1db575028cc..c73f6e64106 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs @@ -2036,7 +2036,10 @@ private static List GetResultForIdentifier(CompletionContext c // Handle completion for a path with variable, such as: $PSHOME\ty if (completionContext.RelatedAsts.Count > 0 && completionContext.RelatedAsts[0] is ScriptBlockAst) { - Ast cursorAst = completionContext.RelatedAsts[0].FindAll(ast => ast.Extent.EndOffset <= tokenAtCursor.Extent.StartOffset, true).LastOrDefault(); + Ast cursorAst = completionContext.RelatedAsts[0].FindAll( + ast => ast.Extent.EndOffset <= tokenAtCursor.Extent.StartOffset + && ast.Extent is not EmptyScriptExtent, + searchNestedScriptBlocks: true).LastOrDefault(); if (cursorAst is not null) { diff --git a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 index 5a93d1307ad..528b81c23ac 100644 --- a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 +++ b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 @@ -818,6 +818,11 @@ Verb-Noun -Param1 Hello ^ $res.CompletionMatches[0].CompletionText | Should -Be "Break" } + it 'Should complete command with an empty arrayexpression element' { + $res = TabExpansion2 -inputScript 'Get-ChildItem @()' -cursorColumn 1 + $res.CompletionMatches[0].CompletionText | Should -Be "Get-ChildItem" + } + Context "Script name completion" { BeforeAll { Setup -f 'install-powershell.ps1' -Content "" From 837482376e1826d483d4f1560afa92b04dfeb266 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Mon, 7 Nov 2022 19:27:52 -0800 Subject: [PATCH 176/779] Replace `msh` in public API comment based documentation with PowerShell equivalent (#18483) --- .../GetEventSnapin.cs | 4 ++-- .../commands/management/ParsePathCommand.cs | 8 ++++---- .../commands/management/ResolvePathCommand.cs | 6 +++--- .../installer/MshManagementMshSnapin.cs | 10 +++++----- .../commands/utility/ExportAliasCommand.cs | 2 +- .../commands/utility/trace/SetTracerCommand.cs | 2 +- .../installer/MshUtilityMshSnapin.cs | 10 +++++----- .../host/msh/ConsoleShell.cs | 4 ++-- .../host/msh/ManagedEntrance.cs | 12 ++++++------ .../singleshell/installer/MshHostMshSnapin.cs | 10 +++++----- .../security/CredentialCommands.cs | 2 +- .../installer/MshSecurityMshSnapin.cs | 10 +++++----- .../cimSupport/other/ciminstancetypeadapter.cs | 2 -- .../engine/AutomationNull.cs | 2 +- .../engine/CmdletInfo.cs | 2 +- .../engine/CommandBase.cs | 4 ++-- .../engine/CommandInfo.cs | 4 ++-- .../engine/Credential.cs | 2 +- .../engine/DataStoreAdapter.cs | 6 +++--- .../engine/DataStoreAdapterProvider.cs | 4 ++-- .../engine/DriveInterfaces.cs | 2 +- .../engine/ErrorPackage.cs | 4 ++-- .../engine/ExternalScriptInfo.cs | 2 +- .../engine/MshCmdlet.cs | 4 ++-- .../engine/MshCommandRuntime.cs | 12 ++++++------ .../engine/NativeCommandProcessor.cs | 8 ++++---- .../engine/PathInterfaces.cs | 14 +++++++------- .../engine/ScriptInfo.cs | 2 +- .../engine/SecurityManagerBase.cs | 2 +- .../engine/cmdlet.cs | 18 +++++++++--------- .../engine/hostifaces/ChoiceDescription.cs | 2 +- .../engine/hostifaces/Connection.cs | 2 +- .../engine/hostifaces/FieldDescription.cs | 4 ++-- .../engine/hostifaces/MshHost.cs | 8 ++++---- .../hostifaces/MshHostRawUserInterface.cs | 12 ++++++------ .../engine/hostifaces/RunspaceInvoke.cs | 6 +++--- .../engine/lang/parserutils.cs | 4 ++-- .../namespaces/DriveProviderBase.cs | 2 +- .../namespaces/ItemProviderBase.cs | 2 +- .../namespaces/PathInfo.cs | 6 +++--- .../namespaces/ProviderBaseSecurity.cs | 2 +- .../namespaces/RegistryProvider.cs | 2 +- .../security/SecuritySupport.cs | 6 +++--- .../singleshell/config/MshSnapinInfo.cs | 18 +++++++++--------- .../utils/ParserException.cs | 4 ++-- src/powershell/Program.cs | 4 ++-- 46 files changed, 128 insertions(+), 130 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventSnapin.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventSnapin.cs index df3835d9e18..a4693c454c0 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventSnapin.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventSnapin.cs @@ -81,7 +81,7 @@ public override string DescriptionResource } /// - /// Get type files to be used for this mshsnapin. + /// Get type files to be used for this PSSnapin. /// public override string[] Types { @@ -94,7 +94,7 @@ public override string[] Types private string[] _types = new string[] { "getevent.types.ps1xml" }; /// - /// Get format files to be used for this mshsnapin. + /// Get format files to be used for this PSSnapin. /// public override string[] Formats { diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/ParsePathCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ParsePathCommand.cs index d56a20faba0..b6609f8b692 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ParsePathCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/ParsePathCommand.cs @@ -12,8 +12,8 @@ namespace Microsoft.PowerShell.Commands { /// - /// A command to resolve MSH paths containing glob characters to - /// MSH paths that match the glob strings. + /// A command to resolve PowerShell paths containing glob characters to + /// PowerShell paths that match the glob strings. /// [Cmdlet(VerbsCommon.Split, "Path", DefaultParameterSetName = "ParentSet", SupportsTransactions = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097149")] [OutputType(typeof(string), ParameterSetName = new[] { leafSet, @@ -105,7 +105,7 @@ public string[] LiteralPath /// /// If true the qualifier of the path will be returned. /// The qualifier is the drive or provider that is qualifying - /// the MSH path. + /// the PowerShell path. /// [Parameter(ParameterSetName = qualifierSet, Mandatory = true, ValueFromPipelineByPropertyName = true)] public SwitchParameter Qualifier { get; set; } @@ -116,7 +116,7 @@ public string[] LiteralPath /// /// If true the qualifier of the path will be returned. /// The qualifier is the drive or provider that is qualifying - /// the MSH path. + /// the PowerShell path. /// [Parameter(ParameterSetName = noQualifierSet, Mandatory = true, ValueFromPipelineByPropertyName = true)] public SwitchParameter NoQualifier { get; set; } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/ResolvePathCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ResolvePathCommand.cs index fcc9aef195f..6bae1a6c878 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ResolvePathCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/ResolvePathCommand.cs @@ -8,8 +8,8 @@ namespace Microsoft.PowerShell.Commands { /// - /// A command to resolve MSH paths containing glob characters to - /// MSH paths that match the glob strings. + /// A command to resolve PowerShell paths containing glob characters to + /// PowerShell paths that match the glob strings. /// [Cmdlet(VerbsDiagnostic.Resolve, "Path", DefaultParameterSetName = "Path", SupportsTransactions = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097143")] @@ -89,7 +89,7 @@ public SwitchParameter Relative #region Command code /// - /// Resolves the path containing glob characters to the MSH paths that it + /// Resolves the path containing glob characters to the PowerShell paths that it /// represents. /// protected override void ProcessRecord() diff --git a/src/Microsoft.PowerShell.Commands.Management/singleshell/installer/MshManagementMshSnapin.cs b/src/Microsoft.PowerShell.Commands.Management/singleshell/installer/MshManagementMshSnapin.cs index 0b0239053ea..ed3495dd334 100644 --- a/src/Microsoft.PowerShell.Commands.Management/singleshell/installer/MshManagementMshSnapin.cs +++ b/src/Microsoft.PowerShell.Commands.Management/singleshell/installer/MshManagementMshSnapin.cs @@ -7,8 +7,8 @@ namespace Microsoft.PowerShell { /// - /// MshManagementMshSnapin (or MshManagementMshSnapinInstaller) is a class for facilitating registry - /// of necessary information for monad management mshsnapin. + /// PSManagementPSSnapIn is a class for facilitating registry + /// of necessary information for PowerShell management PSSnapin. /// /// This class will be built with monad management dll. /// @@ -24,7 +24,7 @@ public PSManagementPSSnapIn() } /// - /// Get name of this mshsnapin. + /// Get name of this PSSnapin. /// public override string Name { @@ -35,7 +35,7 @@ public override string Name } /// - /// Get the default vendor string for this mshsnapin. + /// Get the default vendor string for this PSSnapin. /// public override string Vendor { @@ -57,7 +57,7 @@ public override string VendorResource } /// - /// Get the default description string for this mshsnapin. + /// Get the default description string for this PSSnapin. /// public override string Description { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ExportAliasCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ExportAliasCommand.cs index fcf282d09c8..641d4436daf 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ExportAliasCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ExportAliasCommand.cs @@ -21,7 +21,7 @@ public enum ExportAliasFormat Csv, /// - /// Aliases will be exported as an MSH script. + /// Aliases will be exported as a script. /// Script } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/SetTracerCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/SetTracerCommand.cs index a17ee0fdbef..9f8694ebd20 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/SetTracerCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/SetTracerCommand.cs @@ -99,7 +99,7 @@ public SwitchParameter Debugger } /// - /// If this parameter is specified the Msh Host trace listener will be added. + /// If this parameter is specified the PSHost trace listener will be added. /// /// [Parameter(ParameterSetName = "optionsSet")] diff --git a/src/Microsoft.PowerShell.Commands.Utility/singleshell/installer/MshUtilityMshSnapin.cs b/src/Microsoft.PowerShell.Commands.Utility/singleshell/installer/MshUtilityMshSnapin.cs index 1c29b44c603..038db11916b 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/singleshell/installer/MshUtilityMshSnapin.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/singleshell/installer/MshUtilityMshSnapin.cs @@ -7,8 +7,8 @@ namespace Microsoft.PowerShell { /// - /// MshUtilityMshSnapin (or MshUtilityMshSnapinInstaller) is a class for facilitating registry - /// of necessary information for monad utility mshsnapin. + /// PSUtilityPSSnapIn is a class for facilitating registry + /// of necessary information for monad utility PSSnapin. /// /// This class will be built with monad utility dll. /// @@ -24,7 +24,7 @@ public PSUtilityPSSnapIn() } /// - /// Get name of this mshsnapin. + /// Get name of this PSSnapin. /// public override string Name { @@ -35,7 +35,7 @@ public override string Name } /// - /// Get the default vendor string for this mshsnapin. + /// Get the default vendor string for this PSSnapin. /// public override string Vendor { @@ -57,7 +57,7 @@ public override string VendorResource } /// - /// Get the default description string for this mshsnapin. + /// Get the default description string for this PSSnapin. /// public override string Description { diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleShell.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleShell.cs index 44f29311622..ce5d5ecaef4 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleShell.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleShell.cs @@ -9,8 +9,8 @@ namespace Microsoft.PowerShell { /// - /// This class provides an entry point which is called by minishell's main - /// to transfer control to Msh console host implementation. + /// This class provides an entry point which is called + /// to transfer control to console host implementation. /// public static class ConsoleShell { diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ManagedEntrance.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ManagedEntrance.cs index 18df48d3600..345a6dd0154 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ManagedEntrance.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ManagedEntrance.cs @@ -16,18 +16,18 @@ namespace Microsoft.PowerShell { /// - /// Defines an entry point from unmanaged code to managed Msh. + /// Defines an entry point from unmanaged code to PowerShell. /// public sealed class UnmanagedPSEntry { /// - /// Starts managed MSH. + /// Starts PowerShell. /// /// - /// Deprecated: Console file used to create a runspace configuration to start MSH + /// Deprecated: Console file used to create a runspace configuration to start PowerShell /// /// - /// Command line arguments to the managed MSH + /// Command line arguments to the PowerShell /// /// /// Length of the passed in argument array. @@ -39,10 +39,10 @@ public static int Start(string consoleFilePath, [MarshalAs(UnmanagedType.LPArray } /// - /// Starts managed MSH. + /// Starts PowerShell. /// /// - /// Command line arguments to the managed MSH + /// Command line arguments to PowerShell /// /// /// Length of the passed in argument array. diff --git a/src/Microsoft.PowerShell.ConsoleHost/singleshell/installer/MshHostMshSnapin.cs b/src/Microsoft.PowerShell.ConsoleHost/singleshell/installer/MshHostMshSnapin.cs index c532aeb190d..ce2fd7b3967 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/singleshell/installer/MshHostMshSnapin.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/singleshell/installer/MshHostMshSnapin.cs @@ -7,8 +7,8 @@ namespace Microsoft.PowerShell { /// - /// PSHostMshSnapin (or PSHostMshSnapinInstaller) is a class for facilitating registry - /// of necessary information for monad host mshsnapin. + /// PSHostPSSnapIn is a class for facilitating registry + /// of necessary information for monad host PSSnapin. /// /// This class will be built with monad host engine dll /// (Microsoft.PowerShell.ConsoleHost.dll). @@ -25,7 +25,7 @@ public PSHostPSSnapIn() } /// - /// Get name of this mshsnapin. + /// Get name of this PSSnapin. /// public override string Name { @@ -36,7 +36,7 @@ public override string Name } /// - /// Get the default vendor string for this mshsnapin. + /// Get the default vendor string for this PSSnapin. /// public override string Vendor { @@ -58,7 +58,7 @@ public override string VendorResource } /// - /// Get the default description string for this mshsnapin. + /// Get the default description string for this PSSnapin. /// public override string Description { diff --git a/src/Microsoft.PowerShell.Security/security/CredentialCommands.cs b/src/Microsoft.PowerShell.Security/security/CredentialCommands.cs index 33238c0ca6c..e056f134682 100644 --- a/src/Microsoft.PowerShell.Security/security/CredentialCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/CredentialCommands.cs @@ -9,7 +9,7 @@ namespace Microsoft.PowerShell.Commands /// /// Defines the implementation of the 'get-credential' cmdlet. /// The get-credential Cmdlet establishes a credential object called a - /// Msh credential, by pairing a given username with + /// PSCredential, by pairing a given username with /// a prompted password. That credential object can then be used for other /// operations involving security. /// diff --git a/src/Microsoft.PowerShell.Security/singleshell/installer/MshSecurityMshSnapin.cs b/src/Microsoft.PowerShell.Security/singleshell/installer/MshSecurityMshSnapin.cs index efc4ec63daa..56690e45953 100644 --- a/src/Microsoft.PowerShell.Security/singleshell/installer/MshSecurityMshSnapin.cs +++ b/src/Microsoft.PowerShell.Security/singleshell/installer/MshSecurityMshSnapin.cs @@ -16,8 +16,8 @@ namespace Microsoft.PowerShell { /// - /// MshSecurityMshSnapin (or MshSecurityMshSnapinInstaller) is a class for facilitating registry - /// of necessary information for monad security mshsnapin. + /// PSSecurityPSSnapIn is a class for facilitating registry + /// of necessary information for monad security PSSnapin. /// /// This class will be built with monad security dll. /// @@ -33,7 +33,7 @@ public PSSecurityPSSnapIn() } /// - /// Get name of this mshsnapin. + /// Get name of this PSSnapin. /// public override string Name { @@ -44,7 +44,7 @@ public override string Name } /// - /// Get the default vendor string for this mshsnapin. + /// Get the default vendor string for this PSSnapin. /// public override string Vendor { @@ -66,7 +66,7 @@ public override string VendorResource } /// - /// Get the default description string for this mshsnapin. + /// Get the default description string for this PSSnapin. /// public override string Description { diff --git a/src/System.Management.Automation/cimSupport/other/ciminstancetypeadapter.cs b/src/System.Management.Automation/cimSupport/other/ciminstancetypeadapter.cs index f9aa9f9b73c..ad98e0c50a1 100644 --- a/src/System.Management.Automation/cimSupport/other/ciminstancetypeadapter.cs +++ b/src/System.Management.Automation/cimSupport/other/ciminstancetypeadapter.cs @@ -21,8 +21,6 @@ namespace Microsoft.PowerShell.Cim /// Implementing the PropertyOnlyAdapter for the time being as CimInstanceTypeAdapter currently /// supports only properties. If method support is needed in future, this should derive from /// Adapter class. - /// - /// The Adapter registration is done in monad\src\singleshell\installer\MshManagementMshSnapin.cs /// public sealed class CimInstanceAdapter : PSPropertyAdapter { diff --git a/src/System.Management.Automation/engine/AutomationNull.cs b/src/System.Management.Automation/engine/AutomationNull.cs index 38016c3c513..7cf4742b7b4 100644 --- a/src/System.Management.Automation/engine/AutomationNull.cs +++ b/src/System.Management.Automation/engine/AutomationNull.cs @@ -9,7 +9,7 @@ namespace System.Management.Automation.Internal /// /// It's a singleton class. Sealed to prevent subclassing. Any operation that /// returns no actual value should return this object AutomationNull.Value. - /// Anything that evaluates an MSH expression should be prepared to deal + /// Anything that evaluates a PowerShell expression should be prepared to deal /// with receiving this result and discarding it. When received in an /// evaluation where a value is required, it should be replaced with null. /// diff --git a/src/System.Management.Automation/engine/CmdletInfo.cs b/src/System.Management.Automation/engine/CmdletInfo.cs index 659ed59978a..cf3ba1cab13 100644 --- a/src/System.Management.Automation/engine/CmdletInfo.cs +++ b/src/System.Management.Automation/engine/CmdletInfo.cs @@ -9,7 +9,7 @@ namespace System.Management.Automation { /// - /// The command information for MSH cmdlets that are directly executable by MSH. + /// The command information for cmdlets that are directly executable by PowerShell. /// public class CmdletInfo : CommandInfo { diff --git a/src/System.Management.Automation/engine/CommandBase.cs b/src/System.Management.Automation/engine/CommandBase.cs index bb7aec959f6..4d90a7c2490 100644 --- a/src/System.Management.Automation/engine/CommandBase.cs +++ b/src/System.Management.Automation/engine/CommandBase.cs @@ -397,11 +397,11 @@ public enum ConfirmImpact /// deriving from the PSCmdlet base class. The Cmdlet base class is the primary means by /// which users create their own Cmdlets. Extending this class provides support for the most /// common functionality, including object output and record processing. - /// If your Cmdlet requires access to the MSH Runtime (for example, variables in the session state, + /// If your Cmdlet requires access to the PowerShell Runtime (for example, variables in the session state, /// access to the host, or information about the current Cmdlet Providers,) then you should instead /// derive from the PSCmdlet base class. /// The public members defined by the PSCmdlet class are not designed to be overridden; instead, they - /// provided access to different aspects of the MSH runtime. + /// provided access to different aspects of the PowerShell runtime. /// In both cases, users should first develop and implement an object model to accomplish their /// task, extending the Cmdlet or PSCmdlet classes only as a thin management layer. /// diff --git a/src/System.Management.Automation/engine/CommandInfo.cs b/src/System.Management.Automation/engine/CommandInfo.cs index eb2e7163469..d0e6dd7effa 100644 --- a/src/System.Management.Automation/engine/CommandInfo.cs +++ b/src/System.Management.Automation/engine/CommandInfo.cs @@ -17,7 +17,7 @@ namespace System.Management.Automation { /// - /// Defines the types of commands that MSH can execute. + /// Defines the types of commands that PowerShell can execute. /// [Flags] public enum CommandTypes @@ -52,7 +52,7 @@ public enum CommandTypes Cmdlet = 0x0008, /// - /// An MSH script (*.ps1 file) + /// An PowerShell script (*.ps1 file) /// ExternalScript = 0x0010, diff --git a/src/System.Management.Automation/engine/Credential.cs b/src/System.Management.Automation/engine/Credential.cs index 86557c922c6..5797a8dfcd1 100644 --- a/src/System.Management.Automation/engine/Credential.cs +++ b/src/System.Management.Automation/engine/Credential.cs @@ -16,7 +16,7 @@ namespace System.Management.Automation { /// - /// Defines the valid types of MSH credentials. Used by PromptForCredential calls. + /// Defines the valid types of PSCredentials. Used by PromptForCredential calls. /// [Flags] public enum PSCredentialTypes diff --git a/src/System.Management.Automation/engine/DataStoreAdapter.cs b/src/System.Management.Automation/engine/DataStoreAdapter.cs index 9bf7611d7ff..4cbe6f15f5a 100644 --- a/src/System.Management.Automation/engine/DataStoreAdapter.cs +++ b/src/System.Management.Automation/engine/DataStoreAdapter.cs @@ -289,7 +289,7 @@ protected PSDriveInfo(PSDriveInfo driveInfo) } /// - /// Constructs a drive that maps an MSH Path in + /// Constructs a drive that maps a PowerShell Path in /// the shell to a Cmdlet Provider. /// /// @@ -366,7 +366,7 @@ public PSDriveInfo( } /// - /// Constructs a drive that maps an MSH Path in + /// Constructs a drive that maps a PowerShell Path in /// the shell to a Cmdlet Provider. /// /// @@ -408,7 +408,7 @@ public PSDriveInfo( } /// - /// Constructs a drive that maps an MSH Path in + /// Constructs a drive that maps a PowerShell Path in /// the shell to a Cmdlet Provider. /// /// diff --git a/src/System.Management.Automation/engine/DataStoreAdapterProvider.cs b/src/System.Management.Automation/engine/DataStoreAdapterProvider.cs index 69202e6d20e..3ea2fd00fff 100644 --- a/src/System.Management.Automation/engine/DataStoreAdapterProvider.cs +++ b/src/System.Management.Automation/engine/DataStoreAdapterProvider.cs @@ -201,7 +201,7 @@ public Provider.ProviderCapabilities Capabilities /// /// /// The location can be either a fully qualified provider path - /// or an Msh path. This is the location that is substituted for the ~. + /// or a PowerShell path. This is the location that is substituted for the ~. /// public string Home { get; set; } @@ -368,7 +368,7 @@ internal ProviderInfo( /// The description of the provider. /// /// - /// The home path for the provider. This must be an MSH path. + /// The home path for the provider. This must be a PowerShell path. /// /// /// The help file for the provider. diff --git a/src/System.Management.Automation/engine/DriveInterfaces.cs b/src/System.Management.Automation/engine/DriveInterfaces.cs index 299faa8b76e..c93e47d8c1c 100644 --- a/src/System.Management.Automation/engine/DriveInterfaces.cs +++ b/src/System.Management.Automation/engine/DriveInterfaces.cs @@ -70,7 +70,7 @@ public PSDriveInfo Current #region New /// - /// Creates a new MSH drive in session state. + /// Creates a new PSDrive in session state. /// /// /// The drive to be created. diff --git a/src/System.Management.Automation/engine/ErrorPackage.cs b/src/System.Management.Automation/engine/ErrorPackage.cs index 5ad138079f0..8cdc0ee8d4c 100644 --- a/src/System.Management.Automation/engine/ErrorPackage.cs +++ b/src/System.Management.Automation/engine/ErrorPackage.cs @@ -1723,10 +1723,10 @@ public ErrorRecord(Exception exception, string errorId, ErrorCategory errorCateg /// information. /// /// - /// MSH defines certain exception classes which implement this interface. + /// PowerShell defines certain exception classes which implement this interface. /// This includes wrapper exceptions such as /// , - /// and also MSH engine errors such as + /// and also PowerShell engine errors such as /// . /// Cmdlets and providers should not define this interface; /// instead, they should use the diff --git a/src/System.Management.Automation/engine/ExternalScriptInfo.cs b/src/System.Management.Automation/engine/ExternalScriptInfo.cs index a44e514c785..52713edb874 100644 --- a/src/System.Management.Automation/engine/ExternalScriptInfo.cs +++ b/src/System.Management.Automation/engine/ExternalScriptInfo.cs @@ -14,7 +14,7 @@ namespace System.Management.Automation { /// - /// Provides information for MSH scripts that are directly executable by MSH + /// Provides information for scripts that are directly executable by PowerShell /// but are not built into the runspace configuration. /// public class ExternalScriptInfo : CommandInfo, IScriptCommandInfo diff --git a/src/System.Management.Automation/engine/MshCmdlet.cs b/src/System.Management.Automation/engine/MshCmdlet.cs index 232140d57c5..ebc2f164c6e 100644 --- a/src/System.Management.Automation/engine/MshCmdlet.cs +++ b/src/System.Management.Automation/engine/MshCmdlet.cs @@ -677,7 +677,7 @@ internal IEnumerable GetCommands(string name, CommandTypes commandT /// The given text will be executed in a child scope rather than dot-sourced. /// /// The script text to evaluate. - /// A collection of MshCobjects generated by the script. Never null, but may be empty. + /// A collection of PSObjects generated by the script. Never null, but may be empty. /// Thrown if there was a parsing error in the script. /// Represents a script-level exception. /// @@ -692,7 +692,7 @@ public Collection InvokeScript(string script) /// /// The script text to evaluate. /// The arguments to the script, available as $args. - /// A collection of MshCobjects generated by the script. Never null, but may be empty. + /// A collection of PSObjects generated by the script. Never null, but may be empty. /// Thrown if there was a parsing error in the script. /// Represents a script-level exception. /// diff --git a/src/System.Management.Automation/engine/MshCommandRuntime.cs b/src/System.Management.Automation/engine/MshCommandRuntime.cs index 64202018904..738c3d13981 100644 --- a/src/System.Management.Automation/engine/MshCommandRuntime.cs +++ b/src/System.Management.Automation/engine/MshCommandRuntime.cs @@ -1082,7 +1082,7 @@ internal int OutBuffer /// /// /// - /// namespace Microsoft.Samples.MSH.Cmdlet + /// namespace Microsoft.Samples.Cmdlet /// { /// [Cmdlet(VerbsCommon.Remove,"myobjecttype1")] /// public class RemoveMyObjectType1 : PSCmdlet @@ -1176,7 +1176,7 @@ public bool ShouldProcess(string target) /// /// /// - /// namespace Microsoft.Samples.MSH.Cmdlet + /// namespace Microsoft.Samples.Cmdlet /// { /// [Cmdlet(VerbsCommon.Remove,"myobjecttype2")] /// public class RemoveMyObjectType2 : PSCmdlet @@ -1279,7 +1279,7 @@ public bool ShouldProcess(string target, string action) /// /// /// - /// namespace Microsoft.Samples.MSH.Cmdlet + /// namespace Microsoft.Samples.Cmdlet /// { /// [Cmdlet(VerbsCommon.Remove,"myobjecttype3")] /// public class RemoveMyObjectType3 : PSCmdlet @@ -1394,7 +1394,7 @@ public bool ShouldProcess( /// /// /// - /// namespace Microsoft.Samples.MSH.Cmdlet + /// namespace Microsoft.Samples.Cmdlet /// { /// [Cmdlet(VerbsCommon.Remove,"myobjecttype3")] /// public class RemoveMyObjectType3 : PSCmdlet @@ -1700,7 +1700,7 @@ internal ShouldProcessPossibleOptimization CalculatePossibleShouldProcessOptimiz /// /// /// - /// namespace Microsoft.Samples.MSH.Cmdlet + /// namespace Microsoft.Samples.Cmdlet /// { /// [Cmdlet(VerbsCommon.Remove,"myobjecttype4")] /// public class RemoveMyObjectType4 : PSCmdlet @@ -1882,7 +1882,7 @@ public bool ShouldContinue( /// /// /// - /// namespace Microsoft.Samples.MSH.Cmdlet + /// namespace Microsoft.Samples.Cmdlet /// { /// [Cmdlet(VerbsCommon.Remove,"myobjecttype4")] /// public class RemoveMyObjectType5 : PSCmdlet diff --git a/src/System.Management.Automation/engine/NativeCommandProcessor.cs b/src/System.Management.Automation/engine/NativeCommandProcessor.cs index e89faac4b05..e9a1a13e231 100644 --- a/src/System.Management.Automation/engine/NativeCommandProcessor.cs +++ b/src/System.Management.Automation/engine/NativeCommandProcessor.cs @@ -2297,10 +2297,10 @@ public static void Hide() /// /// Exception used to wrap the error coming from - /// remote instance of Msh. + /// remote instance of PowerShell. /// /// - /// This remote instance of Msh can be in a separate process, + /// This remote instance of PowerShell can be in a separate process, /// appdomain or machine. /// [Serializable] @@ -2394,7 +2394,7 @@ protected RemoteException(SerializationInfo info, StreamingContext context) private readonly PSObject _serializedRemoteInvocationInfo; /// - /// Original Serialized Exception from remote msh. + /// Original Serialized Exception from remote PowerShell. /// /// This is the exception which was thrown in remote. /// @@ -2410,7 +2410,7 @@ public PSObject SerializedRemoteException /// InvocationInfo, if any, associated with the SerializedRemoteException. /// /// - /// This is the serialized InvocationInfo from the remote msh. + /// This is the serialized InvocationInfo from the remote PowerShell. /// public PSObject SerializedRemoteInvocationInfo { diff --git a/src/System.Management.Automation/engine/PathInterfaces.cs b/src/System.Management.Automation/engine/PathInterfaces.cs index 9a604829295..1cc9c6c173c 100644 --- a/src/System.Management.Automation/engine/PathInterfaces.cs +++ b/src/System.Management.Automation/engine/PathInterfaces.cs @@ -379,7 +379,7 @@ public PathInfoStack SetDefaultLocationStack(string stackName) /// characters which will get resolved. /// /// - /// An array of Msh paths that resolved from the given path. + /// An array of PowerShell paths that resolved from the given path. /// /// /// If is null. @@ -728,7 +728,7 @@ public string GetUnresolvedProviderPathFromPSPath(string path) /// The information for the provider for which the returned path should be used. /// /// - /// The drive of the Msh path that was used to convert the path. Note, this may be null + /// The drive of the PowerShell path that was used to convert the path. Note, this may be null /// if the was a provider-qualified path. /// /// @@ -834,7 +834,7 @@ internal string GetUnresolvedProviderPathFromPSPath( } /// - /// Determines if the give path is an Msh provider-qualified path. + /// Determines if the give path is a PowerShell provider-qualified path. /// /// /// The path to check. @@ -863,11 +863,11 @@ public bool IsProviderQualified(string path) /// The path to check. /// /// - /// If the path is an Msh absolute path then the returned value is + /// If the path is an absolute path then the returned value is /// the name of the drive that the path is absolute to. /// /// - /// True if the specified path is an Msh absolute drive-qualified path. + /// True if the specified path is an absolute drive-qualified path. /// False otherwise. /// /// @@ -1232,7 +1232,7 @@ internal string ParseChildName( /// as a relative path to the basePath that was passed. /// /// - /// An MSH path to an item. The item should exist + /// A PowerShell path to an item. The item should exist /// or the provider should write out an error. /// /// @@ -1312,7 +1312,7 @@ internal string NormalizeRelativePath( #region IsValid /// - /// Determines if the MSH path is a syntactically and semantically valid path for the provider. + /// Determines if the path is a syntactically and semantically valid path for the provider. /// /// /// The path to validate. diff --git a/src/System.Management.Automation/engine/ScriptInfo.cs b/src/System.Management.Automation/engine/ScriptInfo.cs index af91867c452..1abdc1424bf 100644 --- a/src/System.Management.Automation/engine/ScriptInfo.cs +++ b/src/System.Management.Automation/engine/ScriptInfo.cs @@ -7,7 +7,7 @@ namespace System.Management.Automation { /// - /// The command information for MSH scripts that are directly executable by MSH. + /// The command information for scripts that are directly executable by PowerShell. /// public class ScriptInfo : CommandInfo, IScriptCommandInfo { diff --git a/src/System.Management.Automation/engine/SecurityManagerBase.cs b/src/System.Management.Automation/engine/SecurityManagerBase.cs index 31712949cf7..0e4f3359704 100644 --- a/src/System.Management.Automation/engine/SecurityManagerBase.cs +++ b/src/System.Management.Automation/engine/SecurityManagerBase.cs @@ -18,7 +18,7 @@ public enum CommandOrigin Runspace, /// - /// The command was dispatched by the msh engine as a result of + /// The command was dispatched by the engine as a result of /// a dispatch request from an already running command. /// Internal diff --git a/src/System.Management.Automation/engine/cmdlet.cs b/src/System.Management.Automation/engine/cmdlet.cs index 953156873fa..20e04a7bd21 100644 --- a/src/System.Management.Automation/engine/cmdlet.cs +++ b/src/System.Management.Automation/engine/cmdlet.cs @@ -23,7 +23,7 @@ namespace System.Management.Automation /// deriving from the PSCmdlet base class. The Cmdlet base class is the primary means by /// which users create their own Cmdlets. Extending this class provides support for the most /// common functionality, including object output and record processing. - /// If your Cmdlet requires access to the MSH Runtime (for example, variables in the session state, + /// If your Cmdlet requires access to the PowerShell Runtime (for example, variables in the session state, /// access to the host, or information about the current Cmdlet Providers,) then you should instead /// derive from the PSCmdlet base class. /// In both cases, users should first develop and implement an object model to accomplish their @@ -802,7 +802,7 @@ public void WriteInformation(InformationRecord informationRecord) /// /// /// - /// namespace Microsoft.Samples.MSH.Cmdlet + /// namespace Microsoft.Samples.Cmdlet /// { /// [Cmdlet(VerbsCommon.Remove,"myobjecttype1")] /// public class RemoveMyObjectType1 : Cmdlet @@ -898,7 +898,7 @@ public bool ShouldProcess(string target) /// /// /// - /// namespace Microsoft.Samples.MSH.Cmdlet + /// namespace Microsoft.Samples.Cmdlet /// { /// [Cmdlet(VerbsCommon.Remove,"myobjecttype2")] /// public class RemoveMyObjectType2 : Cmdlet @@ -1002,7 +1002,7 @@ public bool ShouldProcess(string target, string action) /// /// /// - /// namespace Microsoft.Samples.MSH.Cmdlet + /// namespace Microsoft.Samples.Cmdlet /// { /// [Cmdlet(VerbsCommon.Remove,"myobjecttype3")] /// public class RemoveMyObjectType3 : Cmdlet @@ -1118,7 +1118,7 @@ public bool ShouldProcess( /// /// /// - /// namespace Microsoft.Samples.MSH.Cmdlet + /// namespace Microsoft.Samples.Cmdlet /// { /// [Cmdlet(VerbsCommon.Remove,"myobjecttype3")] /// public class RemoveMyObjectType3 : Cmdlet @@ -1234,7 +1234,7 @@ public bool ShouldProcess( /// /// /// - /// namespace Microsoft.Samples.MSH.Cmdlet + /// namespace Microsoft.Samples.Cmdlet /// { /// [Cmdlet(VerbsCommon.Remove,"myobjecttype4")] /// public class RemoveMyObjectType4 : Cmdlet @@ -1363,7 +1363,7 @@ public bool ShouldContinue(string query, string caption) /// /// /// - /// namespace Microsoft.Samples.MSH.Cmdlet + /// namespace Microsoft.Samples.Cmdlet /// { /// [Cmdlet(VerbsCommon.Remove,"myobjecttype4")] /// public class RemoveMyObjectType5 : Cmdlet @@ -1503,7 +1503,7 @@ public bool ShouldContinue( /// /// /// - /// namespace Microsoft.Samples.MSH.Cmdlet + /// namespace Microsoft.Samples.Cmdlet /// { /// [Cmdlet(VerbsCommon.Remove,"myobjecttype4")] /// public class RemoveMyObjectType5 : Cmdlet @@ -1824,7 +1824,7 @@ public enum ShouldProcessReason /// WhatIf behavior was requested. /// /// - /// In the MSH host, WhatIf behavior can be requested explicitly + /// In the host, WhatIf behavior can be requested explicitly /// for one cmdlet instance using the -WhatIf commandline parameter, /// or implicitly for all SupportsShouldProcess cmdlets with $WhatIfPreference. /// Other hosts may have other ways to request WhatIf behavior. diff --git a/src/System.Management.Automation/engine/hostifaces/ChoiceDescription.cs b/src/System.Management.Automation/engine/hostifaces/ChoiceDescription.cs index 1b55485afdc..4c7c3e65b2b 100644 --- a/src/System.Management.Automation/engine/hostifaces/ChoiceDescription.cs +++ b/src/System.Management.Automation/engine/hostifaces/ChoiceDescription.cs @@ -7,7 +7,7 @@ namespace System.Management.Automation.Host { /// /// Provides a description of a choice for use by . - /// + /// /// public sealed class ChoiceDescription diff --git a/src/System.Management.Automation/engine/hostifaces/Connection.cs b/src/System.Management.Automation/engine/hostifaces/Connection.cs index e892631d0d1..ca212c34666 100644 --- a/src/System.Management.Automation/engine/hostifaces/Connection.cs +++ b/src/System.Management.Automation/engine/hostifaces/Connection.cs @@ -447,7 +447,7 @@ public enum RunspaceCapability #endregion /// - /// Public interface to Msh Runtime. Provides APIs for creating pipelines, + /// Public interface to PowerShell Runtime. Provides APIs for creating pipelines, /// access session state etc. /// public abstract class Runspace : IDisposable diff --git a/src/System.Management.Automation/engine/hostifaces/FieldDescription.cs b/src/System.Management.Automation/engine/hostifaces/FieldDescription.cs index 75987cc463a..45f46d65f5f 100644 --- a/src/System.Management.Automation/engine/hostifaces/FieldDescription.cs +++ b/src/System.Management.Automation/engine/hostifaces/FieldDescription.cs @@ -16,7 +16,7 @@ namespace System.Management.Automation.Host { /// /// Provides a description of a field for use by . - /// + /// /// /// /// It is permitted to subclass @@ -284,7 +284,7 @@ public string Name /// /// Gets the Attribute classes that apply to the field. In the case that - /// is being called from the MSH engine, this will contain the set of prompting attributes that are attached to a + /// is being called from the engine, this will contain the set of prompting attributes that are attached to a /// cmdlet parameter declaration. /// public diff --git a/src/System.Management.Automation/engine/hostifaces/MshHost.cs b/src/System.Management.Automation/engine/hostifaces/MshHost.cs index 7ee89d14b12..7e9a5a81877 100644 --- a/src/System.Management.Automation/engine/hostifaces/MshHost.cs +++ b/src/System.Management.Automation/engine/hostifaces/MshHost.cs @@ -7,7 +7,7 @@ namespace System.Management.Automation.Host { /// - /// Defines the properties and facilities providing by an application hosting an MSH . /// /// @@ -15,7 +15,7 @@ namespace System.Management.Automation.Host /// overrides the abstract methods and properties. The hosting application creates an instance of its derived class and /// passes it to the CreateRunspace method. /// - /// From the moment that the instance of the derived class (the "host class") is passed to CreateRunspace, the MSH runtime + /// From the moment that the instance of the derived class (the "host class") is passed to CreateRunspace, the PowerShell runtime /// can call any of the methods of that class. The instance must not be destroyed until after the Runspace is closed. /// /// There is a 1:1 relationship between the instance of the host class and the Runspace instance to which it is passed. In @@ -64,9 +64,9 @@ protected PSHost() /// The name identifier of the hosting application. /// /// - /// + /// /// if ($Host.Name -ieq "ConsoleHost") { write-host "I'm running in the Console Host" } - /// + /// /// public abstract string Name { diff --git a/src/System.Management.Automation/engine/hostifaces/MshHostRawUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/MshHostRawUserInterface.cs index 09d58ea7357..ce1fe982ba7 100644 --- a/src/System.Management.Automation/engine/hostifaces/MshHostRawUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/MshHostRawUserInterface.cs @@ -1150,7 +1150,7 @@ public enum #endregion Ancillary types /// - /// Defines the lowest-level user interface functions that an interactive application hosting an MSH + /// Defines the lowest-level user interface functions that an interactive application hosting PowerShell /// can choose to implement if it wants to /// support any cmdlet that does character-mode interaction with the user. /// @@ -1340,9 +1340,9 @@ public abstract /// Key stroke when a key is pressed. /// /// - /// + /// /// $Host.UI.RawUI.ReadKey() - /// + /// /// /// /// @@ -1370,10 +1370,10 @@ public abstract /// Neither ReadKeyOptions.IncludeKeyDown nor ReadKeyOptions.IncludeKeyUp is specified. /// /// - /// + /// /// $option = [System.Management.Automation.Host.ReadKeyOptions]"IncludeKeyDown"; /// $host.UI.RawUI.ReadKey($option) - /// + /// /// /// /// @@ -1462,7 +1462,7 @@ public abstract /// using System; /// using System.Management.Automation; /// using System.Management.Automation.Host; - /// namespace Microsoft.Samples.MSH.Cmdlet + /// namespace Microsoft.Samples.Cmdlet /// { /// [Cmdlet("Clear","Screen")] /// public class ClearScreen : PSCmdlet diff --git a/src/System.Management.Automation/engine/hostifaces/RunspaceInvoke.cs b/src/System.Management.Automation/engine/hostifaces/RunspaceInvoke.cs index 25c611eba0e..5fa8370bcea 100644 --- a/src/System.Management.Automation/engine/hostifaces/RunspaceInvoke.cs +++ b/src/System.Management.Automation/engine/hostifaces/RunspaceInvoke.cs @@ -61,7 +61,7 @@ public RunspaceInvoke(Runspace runspace) /// /// Invoke the specified script. /// - /// Msh script to invoke. + /// PowerShell script to invoke. /// Output of invocation. public Collection Invoke(string script) { @@ -71,7 +71,7 @@ public Collection Invoke(string script) /// /// Invoke the specified script and passes specified input to the script. /// - /// Msh script to invoke. + /// PowerShell script to invoke. /// Input to script. /// Output of invocation. public Collection Invoke(string script, IEnumerable input) @@ -93,7 +93,7 @@ public Collection Invoke(string script, IEnumerable input) /// /// Invoke the specified script and passes specified input to the script. /// - /// Msh script to invoke. + /// PowerShell script to invoke. /// Input to script. /// This gets errors from script. /// Output of invocation. diff --git a/src/System.Management.Automation/engine/lang/parserutils.cs b/src/System.Management.Automation/engine/lang/parserutils.cs index 865f3530d71..f159e72be43 100644 --- a/src/System.Management.Automation/engine/lang/parserutils.cs +++ b/src/System.Management.Automation/engine/lang/parserutils.cs @@ -251,7 +251,7 @@ public enum SplitOptions internal delegate object PowerShellBinaryOperator(ExecutionContext context, IScriptExtent errorPosition, object lval, object rval); /// - /// A static class holding various operations specific to the msh interpreter such as + /// A static class holding various operations specific to the PowerShell interpreter such as /// various math operations, ToString() and a routine to extract the base object from an /// PSObject in a canonical fashion. /// @@ -1510,7 +1510,7 @@ internal static string GetTypeFullName(object obj) /// methods and ScriptBlock notes. Native methods currently take precedence over notes... /// /// The position to use for error reporting. - /// The object to call the method on. It shouldn't be an msh object. + /// The object to call the method on. It shouldn't be a PSObject. /// The name of the method to call. /// Invocation constraints. /// The arguments to pass to the method. diff --git a/src/System.Management.Automation/namespaces/DriveProviderBase.cs b/src/System.Management.Automation/namespaces/DriveProviderBase.cs index 91b47619be7..2fc44e50bdc 100644 --- a/src/System.Management.Automation/namespaces/DriveProviderBase.cs +++ b/src/System.Management.Automation/namespaces/DriveProviderBase.cs @@ -9,7 +9,7 @@ namespace System.Management.Automation.Provider #region DriveCmdletProvider /// - /// The base class for Cmdlet providers that can be exposed through MSH drives. + /// The base class for Cmdlet providers that can be exposed through PSDrives. /// /// /// Although it is possible to derive from this base class to implement a Cmdlet Provider, in most diff --git a/src/System.Management.Automation/namespaces/ItemProviderBase.cs b/src/System.Management.Automation/namespaces/ItemProviderBase.cs index eff6782f713..57754273db7 100644 --- a/src/System.Management.Automation/namespaces/ItemProviderBase.cs +++ b/src/System.Management.Automation/namespaces/ItemProviderBase.cs @@ -8,7 +8,7 @@ namespace System.Management.Automation.Provider #region ItemCmdletProvider /// - /// The base class for Cmdlet providers that expose an item as an MSH path. + /// The base class for Cmdlet providers that expose an item as a PowerShell path. /// /// /// The ItemCmdletProvider class is a base class that a provider derives from to diff --git a/src/System.Management.Automation/namespaces/PathInfo.cs b/src/System.Management.Automation/namespaces/PathInfo.cs index f49d478c5e1..0c5483ceffa 100644 --- a/src/System.Management.Automation/namespaces/PathInfo.cs +++ b/src/System.Management.Automation/namespaces/PathInfo.cs @@ -79,7 +79,7 @@ public string ProviderPath private readonly SessionState _sessionState; /// - /// Gets the MSH path that this object represents. + /// Gets the PowerShell path that this object represents. /// public string Path { @@ -94,10 +94,10 @@ public string Path private readonly string _path = string.Empty; /// - /// Gets a string representing the MSH path. + /// Gets a string representing the PowerShell path. /// /// - /// A string representing the MSH path. + /// A string representing the PowerShell path. /// public override string ToString() { diff --git a/src/System.Management.Automation/namespaces/ProviderBaseSecurity.cs b/src/System.Management.Automation/namespaces/ProviderBaseSecurity.cs index c232b769fb3..7bc738c4e49 100644 --- a/src/System.Management.Automation/namespaces/ProviderBaseSecurity.cs +++ b/src/System.Management.Automation/namespaces/ProviderBaseSecurity.cs @@ -7,7 +7,7 @@ namespace System.Management.Automation.Provider { /// /// Defines the base class for all of the classes the provide implementations for a particular - /// data store or item for the MSH core commands. + /// data store or item for the PowerShell core commands. /// public abstract partial class CmdletProvider { diff --git a/src/System.Management.Automation/namespaces/RegistryProvider.cs b/src/System.Management.Automation/namespaces/RegistryProvider.cs index 59a398ef1f6..e324c32234c 100644 --- a/src/System.Management.Automation/namespaces/RegistryProvider.cs +++ b/src/System.Management.Automation/namespaces/RegistryProvider.cs @@ -28,7 +28,7 @@ namespace Microsoft.PowerShell.Commands /// /// INSTALLATION: /// - /// Type the following at an msh prompt: + /// Type the following at a PowerShell prompt: /// /// new-PSProvider -Path "REG.cmdletprovider" -description "My registry navigation provider" /// diff --git a/src/System.Management.Automation/security/SecuritySupport.cs b/src/System.Management.Automation/security/SecuritySupport.cs index 03cf24d80f3..74fb58350d3 100644 --- a/src/System.Management.Automation/security/SecuritySupport.cs +++ b/src/System.Management.Automation/security/SecuritySupport.cs @@ -37,18 +37,18 @@ public enum ExecutionPolicy /// select "Properties," and then "Unblock." Unrestricted = 0, - /// RemoteSigned - Only .msh and .mshxml files originating from the internet + /// RemoteSigned - Only .ps1 and .ps1xml files originating from the internet /// must be digitally signed. If remote, signed, and executed, Monad /// prompts to determine if files from the signing publisher should be /// run or not. This is the default setting. RemoteSigned = 1, - /// AllSigned - All .msh and .mshxml files must be digitally signed. If + /// AllSigned - All .ps1 and .ps1xml files must be digitally signed. If /// signed and executed, Monad prompts to determine if files from the /// signing publisher should be run or not. AllSigned = 2, - /// Restricted - All .msh files are blocked. Mshxml files must be digitally + /// Restricted - All .ps1 files are blocked. Ps1xml files must be digitally /// signed, and by a trusted publisher. If you haven't made a trust decision /// on the publisher yet, prompting is done as in AllSigned mode. Restricted = 3, diff --git a/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs b/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs index 05f8991e4a9..932271fce20 100644 --- a/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs +++ b/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs @@ -69,7 +69,7 @@ internal static class RegistryStrings } /// - /// Contains information about a mshsnapin. + /// Contains information about a PSSnapin. /// public class PSSnapInInfo { @@ -189,22 +189,22 @@ string vendorIndirect } /// - /// Unique Name of the mshsnapin. + /// Unique Name of the PSSnapin. /// public string Name { get; } /// - /// Is this mshsnapin default mshsnapin. + /// Is this PSSnapin default PSSnapin. /// public bool IsDefault { get; } /// - /// Returns applicationbase for mshsnapin. + /// Returns applicationbase for PSSnapin. /// public string ApplicationBase { get; } /// - /// Strong name of mshSnapIn assembly. + /// Strong name of PSSnapin assembly. /// public string AssemblyName { get; } @@ -231,12 +231,12 @@ internal string AbsoluteModulePath } /// - /// Monad version used by mshsnapin. + /// Monad version used by PSSnapin. /// public Version PSVersion { get; } /// - /// Version of mshsnapin. + /// Version of PSSnapin. /// public Version Version { get; } @@ -254,7 +254,7 @@ internal string AbsoluteModulePath private readonly string _descriptionFallback = string.Empty; private string _description; /// - /// Description of mshsnapin. + /// Description of PSSnapin. /// public string Description { @@ -273,7 +273,7 @@ public string Description private readonly string _vendorFallback = string.Empty; private string _vendor; /// - /// Vendor of mshsnapin. + /// Vendor of PSSnapin. /// public string Vendor { diff --git a/src/System.Management.Automation/utils/ParserException.cs b/src/System.Management.Automation/utils/ParserException.cs index 5e36704ff8f..4c953be0276 100644 --- a/src/System.Management.Automation/utils/ParserException.cs +++ b/src/System.Management.Automation/utils/ParserException.cs @@ -9,7 +9,7 @@ namespace System.Management.Automation { /// - /// Defines the exception thrown when a syntax error occurs while parsing msh script text. + /// Defines the exception thrown when a syntax error occurs while parsing PowerShell script text. /// [Serializable] public class ParseException : RuntimeException @@ -170,7 +170,7 @@ public override string Message } /// - /// Defines the exception thrown when a incomplete parse error occurs while parsing msh script text. + /// Defines the exception thrown when a incomplete parse error occurs while parsing PowerShell script text. /// /// /// This is a variation on a parsing error that indicates that the parse was incomplete diff --git a/src/powershell/Program.cs b/src/powershell/Program.cs index d085db22b98..f5c109a1a76 100644 --- a/src/powershell/Program.cs +++ b/src/powershell/Program.cs @@ -59,10 +59,10 @@ public StartupException(string callName, int exitCode) #endif /// - /// Starts the managed MSH. + /// Starts PowerShell. /// /// - /// Command line arguments to the managed MSH + /// Command line arguments to PowerShell /// public static int Main(string[] args) { From 74aa25783986b92b0782cf693765517ab0afc321 Mon Sep 17 00:00:00 2001 From: Patrick Meinecke Date: Tue, 8 Nov 2022 17:37:29 -0500 Subject: [PATCH 177/779] Skip cloud files marked as "not on disk" during command discovery (#18152) --- experimental-feature-linux.json | 1 + experimental-feature-windows.json | 1 + .../ExperimentalFeature.cs | 4 ++ .../engine/Modules/ModuleUtils.cs | 57 ++++++++++++++++++- 4 files changed, 61 insertions(+), 2 deletions(-) diff --git a/experimental-feature-linux.json b/experimental-feature-linux.json index 08f398171d4..0e3bfc3d528 100644 --- a/experimental-feature-linux.json +++ b/experimental-feature-linux.json @@ -4,5 +4,6 @@ "PSLoadAssemblyFromNativeCode", "PSNativeCommandErrorActionPreference", "PSSubsystemPluginModel", + "PSModuleAutoLoadSkipOfflineFiles", "PSFeedbackProvider" ] diff --git a/experimental-feature-windows.json b/experimental-feature-windows.json index 08f398171d4..0e3bfc3d528 100644 --- a/experimental-feature-windows.json +++ b/experimental-feature-windows.json @@ -4,5 +4,6 @@ "PSLoadAssemblyFromNativeCode", "PSNativeCommandErrorActionPreference", "PSSubsystemPluginModel", + "PSModuleAutoLoadSkipOfflineFiles", "PSFeedbackProvider" ] diff --git a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs index 5fe456f48d5..55036d87fce 100644 --- a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs +++ b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs @@ -22,6 +22,7 @@ public class ExperimentalFeature internal const string EngineSource = "PSEngine"; internal const string PSNativeCommandErrorActionPreferenceFeatureName = "PSNativeCommandErrorActionPreference"; + internal const string PSModuleAutoLoadSkipOfflineFilesFeatureName = "PSModuleAutoLoadSkipOfflineFiles"; internal const string PSCustomTableHeaderLabelDecoration = "PSCustomTableHeaderLabelDecoration"; internal const string PSFeedbackProvider = "PSFeedbackProvider"; @@ -118,6 +119,9 @@ static ExperimentalFeature() new ExperimentalFeature( name: PSNativeCommandErrorActionPreferenceFeatureName, description: "Native commands with non-zero exit codes issue errors according to $ErrorActionPreference when $PSNativeCommandUseErrorActionPreference is $true"), + new ExperimentalFeature( + name: PSModuleAutoLoadSkipOfflineFilesFeatureName, + description: "Module discovery will skip over files that are marked by cloud providers as not fully on disk."), new ExperimentalFeature( name: PSCustomTableHeaderLabelDecoration, description: "Formatting differentiation for table header labels that aren't property members"), diff --git a/src/System.Management.Automation/engine/Modules/ModuleUtils.cs b/src/System.Management.Automation/engine/Modules/ModuleUtils.cs index a69b89744a0..d8e2b24e016 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleUtils.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleUtils.cs @@ -13,22 +13,46 @@ namespace System.Management.Automation.Internal { internal static class ModuleUtils { + // These are documented members FILE_ATTRIBUTE, they just have not yet been + // added to System.IO.FileAttributes yet. + private const int FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS = 0x400000; + + private const int FILE_ATTRIBUTE_RECALL_ON_OPEN = 0x40000; + // Default option for local file system enumeration: // - Ignore files/directories when access is denied; // - Search top directory only. private static readonly System.IO.EnumerationOptions s_defaultEnumerationOptions = - new System.IO.EnumerationOptions() { AttributesToSkip = FileAttributes.Hidden }; + new System.IO.EnumerationOptions() { AttributesToSkip = FileAttributesToSkip }; + + private static readonly FileAttributes FileAttributesToSkip; // Default option for UNC path enumeration. Same as above plus a large buffer size. // For network shares, a large buffer may result in better performance as more results can be batched over the wire. // The buffer size 16K is recommended in the comment of the 'BufferSize' property: // "A "large" buffer, for example, would be 16K. Typical is 4K." private static readonly System.IO.EnumerationOptions s_uncPathEnumerationOptions = - new System.IO.EnumerationOptions() { AttributesToSkip = FileAttributes.Hidden, BufferSize = 16384 }; + new System.IO.EnumerationOptions() { AttributesToSkip = FileAttributesToSkip, BufferSize = 16384 }; private static readonly string EnCulturePath = Path.DirectorySeparatorChar + "en"; private static readonly string EnUsCulturePath = Path.DirectorySeparatorChar + "en-us"; + static ModuleUtils() + { + if (ExperimentalFeature.IsEnabled(ExperimentalFeature.PSModuleAutoLoadSkipOfflineFilesFeatureName)) + { + FileAttributesToSkip = FileAttributes.Hidden + // Skip OneDrive files/directories that are not fully on disk. + | FileAttributes.Offline + | (FileAttributes)FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS + | (FileAttributes)FILE_ATTRIBUTE_RECALL_ON_OPEN; + + return; + } + + FileAttributesToSkip = FileAttributes.Hidden; + } + /// /// Check if a directory is likely a localized resources folder. /// @@ -276,6 +300,11 @@ internal static IEnumerable GetDefaultAvailableModuleFiles(string topDir manifestPath += StringLiterals.PowerShellDataFileExtension; if (File.Exists(manifestPath)) { + if (HasSkippedFileAttribute(manifestPath)) + { + continue; + } + isModuleDirectory = true; yield return manifestPath; } @@ -288,6 +317,11 @@ internal static IEnumerable GetDefaultAvailableModuleFiles(string topDir string moduleFile = Path.Combine(directoryToCheck, proposedModuleName) + ext; if (File.Exists(moduleFile)) { + if (HasSkippedFileAttribute(moduleFile)) + { + continue; + } + isModuleDirectory = true; yield return moduleFile; @@ -337,6 +371,25 @@ internal static List GetModuleVersionSubfolders(string moduleBase) return versionFolders; } + private static bool HasSkippedFileAttribute(string path) + { + try + { + FileAttributes attributes = File.GetAttributes(path); + if ((attributes & FileAttributesToSkip) is not 0) + { + return true; + } + } + catch + { + // Ignore failures so that we keep the current behavior of failing + // later in the search. + } + + return false; + } + private static void ProcessPossibleVersionSubdirectories(IEnumerable subdirectories, List versionFolders) { foreach (string subdir in subdirectories) From 84a1a2c2fe55e281f0c543d7d4099da55c4de198 Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Wed, 9 Nov 2022 09:56:44 -0800 Subject: [PATCH 178/779] Update `README.md` and `metadata.json` for `v7.3.0` (#18493) --- README.md | 40 ++++++++++++++++++++-------------------- tools/metadata.json | 4 ++-- 2 files changed, 22 insertions(+), 22 deletions(-) diff --git a/README.md b/README.md index 8f411870852..1489bcafb6a 100644 --- a/README.md +++ b/README.md @@ -71,26 +71,26 @@ You can also download the PowerShell binary archives for Windows, macOS and Linu [lts-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.7/powershell-lts-7.2.7-osx-x64.pkg [lts-macos-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.7/powershell-lts-7.2.7-osx-arm64.pkg -[rl-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.7/PowerShell-7.2.7-win-x64.msi -[rl-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.7/PowerShell-7.2.7-win-x86.msi -[rl-ubuntu20]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.7/powershell_7.2.7-1.deb_amd64.deb -[rl-ubuntu18]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.7/powershell_7.2.7-1.deb_amd64.deb -[rl-ubuntu16]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.7/powershell_7.2.7-1.deb_amd64.deb -[rl-debian9]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.7/powershell_7.2.7-1.deb_amd64.deb -[rl-debian10]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.7/powershell_7.2.7-1.deb_amd64.deb -[rl-debian11]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.7/powershell_7.2.7-1.deb_amd64.deb -[rl-centos]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.7/powershell-7.2.7-1.rh.x86_64.rpm -[rl-centos8]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.7/powershell-7.2.7-1.rh.x86_64.rpm -[rl-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.7/powershell-7.2.7-osx-x64.pkg -[rl-macos-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.7/powershell-7.2.7-osx-arm64.pkg -[rl-winarm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.7/PowerShell-7.2.7-win-arm64.zip -[rl-winx86-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.7/PowerShell-7.2.7-win-x86.zip -[rl-winx64-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.7/PowerShell-7.2.7-win-x64.zip -[rl-macos-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.7/powershell-7.2.7-osx-x64.tar.gz -[rl-macos-tar-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.7/powershell-7.2.7-osx-arm64.tar.gz -[rl-linux-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.7/powershell-7.2.7-linux-x64.tar.gz -[rl-arm32]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.7/powershell-7.2.7-linux-arm32.tar.gz -[rl-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.7/powershell-7.2.7-linux-arm64.tar.gz +[rl-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0/PowerShell-7.3.0-win-x64.msi +[rl-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0/PowerShell-7.3.0-win-x86.msi +[rl-ubuntu20]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0/powershell_7.3.0-1.deb_amd64.deb +[rl-ubuntu18]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0/powershell_7.3.0-1.deb_amd64.deb +[rl-ubuntu16]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0/powershell_7.3.0-1.deb_amd64.deb +[rl-debian9]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0/powershell_7.3.0-1.deb_amd64.deb +[rl-debian10]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0/powershell_7.3.0-1.deb_amd64.deb +[rl-debian11]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0/powershell_7.3.0-1.deb_amd64.deb +[rl-centos]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0/powershell-7.3.0-1.rh.x86_64.rpm +[rl-centos8]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0/powershell-7.3.0-1.rh.x86_64.rpm +[rl-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0/powershell-7.3.0-osx-x64.pkg +[rl-macos-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0/powershell-7.3.0-osx-arm64.pkg +[rl-winarm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0/PowerShell-7.3.0-win-arm64.zip +[rl-winx86-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0/PowerShell-7.3.0-win-x86.zip +[rl-winx64-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0/PowerShell-7.3.0-win-x64.zip +[rl-macos-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0/powershell-7.3.0-osx-x64.tar.gz +[rl-macos-tar-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0/powershell-7.3.0-osx-arm64.tar.gz +[rl-linux-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0/powershell-7.3.0-linux-x64.tar.gz +[rl-arm32]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0/powershell-7.3.0-linux-arm32.tar.gz +[rl-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0/powershell-7.3.0-linux-arm64.tar.gz [rl-snap]: https://snapcraft.io/powershell [pv-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-rc.1/PowerShell-7.3.0-rc.1-win-x64.msi diff --git a/tools/metadata.json b/tools/metadata.json index 30945bacb99..9b834950bef 100644 --- a/tools/metadata.json +++ b/tools/metadata.json @@ -1,8 +1,8 @@ { - "StableReleaseTag": "v7.2.7", + "StableReleaseTag": "v7.3.0", "PreviewReleaseTag": "v7.3.0-rc.1", "ServicingReleaseTag": "v7.0.13", - "ReleaseTag": "v7.2.7", + "ReleaseTag": "v7.3.0", "LTSReleaseTag" : ["v7.2.7", "v7.0.13"], "NextReleaseTag": "v7.3.0-preview.9", "LTSRelease": { "Latest": false, "Package": false }, From cf9e8228e74b738d753ac3574320345b0331f0de Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Wed, 9 Nov 2022 11:41:21 -0800 Subject: [PATCH 179/779] Fix issues with uploading changelog to GitHub release draft (#18504) --- .../azureDevOps/templates/release-CreateGitHubDraft.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/releaseBuild/azureDevOps/templates/release-CreateGitHubDraft.yml b/tools/releaseBuild/azureDevOps/templates/release-CreateGitHubDraft.yml index 9e439db7366..6eed7fbfd9c 100644 --- a/tools/releaseBuild/azureDevOps/templates/release-CreateGitHubDraft.yml +++ b/tools/releaseBuild/azureDevOps/templates/release-CreateGitHubDraft.yml @@ -54,7 +54,7 @@ steps: "preview.md" } else { - $semanticVersion.Major + "." + $semanticVersion.Minor + ".md" + $semanticVersion.Major.ToString() + "." + $semanticVersion.Minor.ToString() + ".md" } $filePath = "$env:BUILD_SOURCESDIRECTORY/CHANGELOG/$fileName" From 6fd7d2fd151a251522461078e8c5ba19f56fed98 Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Wed, 9 Nov 2022 12:16:42 -0800 Subject: [PATCH 180/779] Merged PR 23161: Change log for v7.3.0 (#18505) --- .spelling | 4 +- CHANGELOG/7.3.md | 932 +++++++++++++++++++++++++++++++++++++++++++ CHANGELOG/preview.md | 896 ----------------------------------------- 3 files changed, 935 insertions(+), 897 deletions(-) create mode 100644 CHANGELOG/7.3.md diff --git a/.spelling b/.spelling index f8f6d445b59..b776bf0f562 100644 --- a/.spelling +++ b/.spelling @@ -1549,8 +1549,9 @@ kilasuit michaeltlombardi SeeminglyScience TobiasPSP - - CHANGELOG/preview.md + - CHANGELOG/7.3.md ayousuf23 +AzCopy.exe hammy3502 PowerShellExecutionHelper.cs ClientRemotePowerShell @@ -1568,6 +1569,7 @@ vmImage NoLanguage GetValueOrDefault kondratyev-nv +penimc_cor3.dll PkgES v7.2.0 preview.9 diff --git a/CHANGELOG/7.3.md b/CHANGELOG/7.3.md new file mode 100644 index 00000000000..66516873ae3 --- /dev/null +++ b/CHANGELOG/7.3.md @@ -0,0 +1,932 @@ +# 7.3 Changelog + +## [7.3.0] - 2022-11-08 + +### General Cmdlet Updates and Fixes + +- Correct calling cmdlet `New-PSSessionOption` in script for `Restart-Computer` (#18374) + +### Tests + +- Add test for framework dependent package in release pipeline (Internal 23139) + +### Build and Packaging Improvements + +
+ + + +

Bump to use internal .NET 7 GA build (Internal 23096)

+ +
+ +
    +
  • Fix issues with building test artifacts (Internal 23116)
  • +
  • Use AzFileCopy task instead of AzCopy.exe
  • +
  • Remove AzCopy installation from msixbundle step
  • +
  • Add TSAUpload for APIScan (#18446)
  • +
  • Add authenticode signing for assemblies on Linux builds (#18440)
  • +
  • Do not remove penimc_cor3.dll from build (#18438)
  • +
  • Allow two-digit revisions in vPack package validation pattern (#18392)
  • +
  • Bump Microsoft.PowerShell.Native from 7.3.0-rc.1 to 7.3.0 (#18413)
  • +
+ +
+ +[7.3.0]: https://github.com/PowerShell/PowerShell/compare/v7.3.0-rc.1...v7.3.0 + +## [7.3.0-rc.1] - 2022-10-26 + +### Breaking Change + +- Update to use `ComputeCore.dll` for PowerShell Direct (#18194) + +### Engine Updates and Fixes + +- On Unix, explicitly terminate the native process during cleanup only if it's not running in background (#18215) + +### General Cmdlet Updates and Fixes + +- Remove the `ProcessorArchitecture` portion from the full name as it's obsolete (#18320) + +### Tests + +- Add missing `-Tag 'CI'` to describe blocks. (#18317) + +### Build and Packaging Improvements + +
+ + +

Bump to .NET 7 to 7.0.100-rc.2.22477.20 (#18328)(#18286)

+
+ +
    +
  • Update ThirdPartyNotices (Internal 22987)
  • +
  • Remove API sets (#18304) (#18376)
  • +
  • Do not cleanup pwsh.deps.json for framework dependent packages (#18300)
  • +
  • Bump Microsoft.PowerShell.Native from 7.3.0-preview.1 to 7.3.0-rc.1 (#18217)
  • +
  • Remove unnecessary native dependencies from the package (#18213)
  • +
  • Make the link to minimal package blob public during release (#18158)
  • +
  • Create tasks to collect and publish hashes for build files. (#18276)(#18277)
  • +
  • Add branch counter to compliance build (#18214)
  • +
  • Move APIScan to compliance build (#18191)
  • +
  • Update MSI exit message (#18137)
  • +
  • Remove XML files for min-size package (#18189)
  • +
+ +
+ +[7.3.0-rc.1]: https://github.com/PowerShell/PowerShell/compare/v7.3.0-preview.8...v7.3.0-rc.1 + +## [7.3.0-preview.8] - 2022-09-20 + +### General Cmdlet Updates and Fixes + +- Filter out compiler generated types for `Add-Type -PassThru` (#18095) +- Fix error formatting to use color defined in `$PSStyle.Formatting` (#17987) +- Handle `PSObject` argument specially in method invocation logging (#18060) +- Revert the experimental feature `PSStrictModeAssignment` (#18040) +- Make experimental feature `PSAMSIMethodInvocationLogging` stable (#18041) +- Make experimental feature `PSAnsiRenderingFileInfo` stable (#18042) +- Make experimental feature `PSCleanBlock` stable (#18043) +- Make experimental feature `PSNativeCommandArgumentPassing` stable (#18044) +- Make experimental feature `PSExec` stable (#18045) +- Make experimental feature `PSRemotingSSHTransportErrorHandling` stable (#18046) +- Add the `ConfigurationFile` option to the PowerShell help content (#18093) + +### Build and Packaging Improvements + + +

Bump .NET SDK to version `7.0.100-rc.1`

+
+ +
+
    +
  • Update ThirdPartyNotices.txt for 7.3.0-preview.8 (Internal 22553)
  • +
  • Update cgmanifest.json for 7.3.0-preview.8 (Internal 22551)
  • +
  • Re-enable building with Ready-to-Run (#18107)
  • +
  • Make sure Security.types.ps1xml gets signed in release build (#17930)
  • +
  • Update DotnetRuntimeMetadata.json for .NET 7 RC1 build (#18106)
  • +
  • Add XML reference documents to NuPkg files for SDK (#18017)
  • +
  • Make Register MU timeout (#17995)
  • +
  • Bump Microsoft.NET.Test.Sdk from 17.2.0 to 17.3.0 (#17924)
  • +
  • Update list of PS team members in release tools (#17928)
  • +
  • Update to use version 2.21.0 of Application Insights (#17927)
  • +
  • Complete ongoing Write-Progress in test (#17922)
  • +
+
+ +[7.3.0-preview.8]: https://github.com/PowerShell/PowerShell/compare/v7.3.0-preview.7...v7.3.0-preview.8 + +## [7.3.0-preview.7] - 2022-08-09 + +### Breaking Changes + +- Move the type data definition of `System.Security.AccessControl.ObjectSecurity` to the `Microsoft.PowerShell.Security` module (#16355) (Thanks @iSazonov!) + +### Engine Updates and Fixes + +- Enable searching for assemblies in `GAC_Arm64` on Windows (#17816) +- Fix parser exception in using statements with empty aliases (#16745) (Thanks @MartinGC94!) +- Do not always collapse space between parameter and value for native arguments. (#17708) +- Remove `PSNativePSPathResolution` experimental feature (#17670) + +### General Cmdlet Updates and Fixes + +- Fix for deserializing imported ordered dictionary (#15545) (Thanks @davidBar-On!) +- Make generated implicit remoting modules backwards compatible with PowerShell 5.1 (#17227) (Thanks @Tadas!) +- Re-enable IDE0031: Use Null propagation (#17811) (Thanks @fflaten!) +- Allow commands to still be executed even if the current working directory no longer exists (#17579) +- Stop referencing `Microsoft.PowerShell.Security` when the core snapin is used (#17771) +- Add support for HTTPS with `Set-AuthenticodeSignature -TimeStampServer` (#16134) (Thanks @Ryan-Hutchison-USAF!) +- Add type accelerator `ordered` for `OrderedDictionary` (#17804) (Thanks @fflaten!) +- Fix the definition of the `PDH_COUNTER_INFO` struct (#17779) +- Adding Virtualization Based Security feature names to Get-ComputerInfo (#16415) (Thanks @mattifestation!) +- Fix `FileSystemProvider` to work with volume and pipe paths (#15873) +- Remove pre-parse for array-based JSON (#15684) (Thanks @strawgate!) +- Improve type inference for `$_` (#17716) (Thanks @MartinGC94!) +- Prevent braces from being removed when completing variables (#17751) (Thanks @MartinGC94!) +- Fix type inference for `ICollection` (#17752) (Thanks @MartinGC94!) +- Fix `Test-Json` not handling non-object types at root (#17741) (Thanks @dkaszews!) +- Change `Get-ChildItem` to treat trailing slash in path as indicating a directory when used with `-Recurse` (#17704) +- Add `find.exe` to legacy argument binding behavior for Windows (#17715) +- Add completion for index expressions for dictionaries (#17619) (Thanks @MartinGC94!) +- Fix enum-ranges for `ValidateRange` in proxy commands (#17572) (Thanks @fflaten!) +- Fix type completion for attribute tokens (#17484) (Thanks @MartinGC94!) +- Add `-noprofileloadtime` switch to `pwsh` (#17535) (Thanks @rkeithhill!) +- Fix legacy `ErrorView` types to use `$host.PrivateData` colors (#17705) +- Improve dynamic parameter tab completion (#17661) (Thanks @MartinGC94!) +- Avoid binding positional parameters when completing parameter in front of value (#17693) (Thanks @MartinGC94!) +- Render decimal numbers in a table using current culture (#17650) + +### Code Cleanup + +
+ + + +

We thank the following contributors!

+

@fflaten, @Molkree, @eltociear

+ +
+ +
    +
  • Fix other path constructions using Path.Join (#17825)
  • +
  • Use null propagation (#17787)(#17789)(#17790)(#17791)(#17792)(#17795) (Thanks @fflaten!)
  • +
  • Re-enable compound assignment preference (#17784) (Thanks @Molkree!)
  • +
  • Use null-coalescing assignment (#17719)(#17720)(#17721)(#17722)(#17723)(#17724)(#17725)(#17726)(#17727)(#17728)(#17729) (Thanks @Molkree!)
  • +
  • Disable the warning IDE0031 to take .NET 7 Preview 7 (#17770)
  • +
  • Fix typo in ModuleCmdletBase.cs (#17714) (Thanks @eltociear!)
  • +
+ +
+ +### Tests + +- Re-enable tests because the corresponding dotnet issues were fixed (#17839) +- Add test for `LanguageMode` using remoting (#17803) (Thanks @fflaten!) +- Fix test perf by stopping ongoing `write-progress` (#17749) (Thanks @fflaten!) +- Re-enable the test `TestLoadNativeInMemoryAssembly` (#17738) + +### Build and Packaging Improvements + +
+ + + +

We thank the following contributors!

+

@varunsh-coder, @dkaszews, @Molkree, @ChuckieChen945

+ +
+ +
    +
  • Update release pipeline to use Approvals and automate some manual tasks (#17837)
  • +
  • Add GitHub token permissions for workflows (#17781) (Thanks @varunsh-coder!)
  • +
  • Bump actions/github-script from 3 to 6 (#17842)
  • +
  • Bump cirrus-actions/rebase from 1.6 to 1.7 (#17843)
  • +
  • Remove unneeded verbose message in build (#17840)
  • +
  • Detect default runtime using dotnet --info in build.psm1 (#17818) (Thanks @dkaszews!)
  • +
  • Bump actions/checkout from 2 to 3 (#17828)
  • +
  • Bump actions/download-artifact from 2 to 3 (#17829)
  • +
  • Bump github/codeql-action from 1 to 2 (#17830)
  • +
  • Bump peter-evans/create-pull-request from 3 to 4 (#17831)
  • +
  • Bump actions/upload-artifact from 2 to 3 (#17832)
  • +
  • Enable Dependabot for GitHub Actions (#17775) (Thanks @Molkree!)
  • +
  • Update .NET SDK version from 7.0.100-preview.6.22352.1 to 7.0.100-preview.7.22377.5 (#17776)
  • +
  • Fix a bug in install-powershell.ps1 (#17794) (Thanks @ChuckieChen945!)
  • +
  • Bump xunit from 2.4.1 to 2.4.2 (#17817)
  • +
  • Update how to update homebrew (#17798)
  • +
  • Don't run link check on forks (#17797)
  • +
  • Update dotnetmetadata.json to start consuming .NET 7 preview 7 builds (#17736)
  • +
  • Bump PackageManagement from 1.4.7 to 1.4.8.1 (#17709)
  • +
  • Exclude ARM images from running in CI (#17713)
  • +
+ +
+ +### Documentation and Help Content + +- Update the comment about why R2R is disabled (#17850) +- Update changelog and `.spelling` for `7.3.0-preview.6` release (#17835) +- Updated `ADOPTERS.md` for Power BI (#17766) +- Update README.md with the current Fedora version (#15717) (Thanks @ananya26-vishnoi!) +- Update `README` and `metadata.json` for next release (#17676) (Thanks @SeeminglyScience!) + +[7.3.0-preview.7]: https://github.com/PowerShell/PowerShell/compare/v7.3.0-preview.6...v7.3.0-preview.7 + +## [7.3.0-preview.6] - 2022-07-18 + +### General Cmdlet Updates and Fixes + +- Fix `Export-PSSession` to not throw error when a rooted path is specified for `-OutputModule` (#17671) +- Change `ConvertFrom-Json -AsHashtable` to use ordered hashtable (#17405) +- Remove potential ANSI escape sequences in strings before using in `Out-GridView` (#17664) +- Add the `-Milliseconds` parameter to `New-TimeSpan` (#17621) (Thanks @NoMoreFood!) +- Update `Set-AuthenticodeSignature` to use `SHA256` as the default (#17560) (Thanks @jborean93!) +- Fix tab completion regression when completing `ValidateSet` values (#17628) (Thanks @MartinGC94!) +- Show optional parameters as such when displaying method definition and overloads (#13799) (Thanks @eugenesmlv!) + +### Code Cleanup + +
+ + + +

We thank the following contributors!

+

@sethvs, @MartinGC94, @eltociear

+ +
+ +
    +
  • Fix comment in InternalCommands.cs (#17669) (Thanks @sethvs!)
  • +
  • Use discards for unused variables (#17620) (Thanks @MartinGC94!)
  • +
  • Fix typo in CommonCommandParameters.cs (#17524) (Thanks @eltociear!)
  • +
+ +
+ +### Tests + +- Fix SDK tests for release build (#17678) + +### Build and Packaging Improvements + +
+ + + +

We thank the following contributors!

+

@tamasvajk

+ +
+ +
    +
  • Create test artifacts for Windows ARM64 (#17675)
  • +
  • Update to the latest NOTICES file (#17607)
  • +
  • Update .NET SDK version from 7.0.100-preview.5.22307.18 to 7.0.100-preview.6.22352.1 (#17634)
  • +
  • Set the compound assignment preference to false (#17632)
  • +
  • Update DotnetMetadata.json to start consuming .NET 7 Preview 6 builds (#17630)
  • +
  • Install .NET 3.1 as it is required by the vPack task (#17600)
  • +
  • Update to use PSReadLine v2.2.6 (#17595)
  • +
  • Fix build.psm1 to not specify both version and quality for dotnet-install (#17589) (Thanks @tamasvajk!)
  • +
  • Bump Newtonsoft.Json in /test/perf/dotnet-tools/Reporting (#17592)
  • +
  • Bump Newtonsoft.Json in /test/perf/dotnet-tools/ResultsComparer (#17566)
  • +
  • Disable RPM SBOM test. (#17532)
  • +
+ +
+ +### Documentation and Help Content + +- Remove `katacoda.com` from doc as it now returns 404 (#17625) +- Update change log for `v7.2.5` and `v7.3.0-preview.5` (#17565) +- Update `README.md` and `metadata.json` for upcoming releases (#17526) + +[7.3.0-preview.6]: https://github.com/PowerShell/PowerShell/compare/v7.3.0-preview.5...v7.3.0-preview.6 + +## [7.3.0-preview.5] - 2022-06-21 + +### Engine Updates and Fixes + +- Improve type inference and completions (#16963) (Thanks @MartinGC94!) +- Make `Out-String` and `Out-File` keep string input unchanged (#17455) +- Make `AnsiRegex` able to capture Hyperlink ANSI sequences (#17442) +- Add the `-ConfigurationFile` command line parameter to `pwsh` to support local session configuration (#17447) +- Fix native library loading for `osx-arm64` (#17365) (Thanks @awakecoding!) +- Fix formatting to act appropriately when the style of table header or list label is empty string (#17463) + +### General Cmdlet Updates and Fixes + +- Fix various completion issues inside the `param` block (#17489) (Thanks @MartinGC94!) +- Add Amended switch to `Get-CimClass` cmdlet (#17477) (Thanks @iSazonov!) +- Improve completion on operators (#17486) (Thanks @MartinGC94!) +- Improve array element completion for command arguments (#17078) (Thanks @matt9ucci!) +- Use AST extent for `PSScriptRoot` path completion (#17376) +- Add type inference support for generic methods with type parameters (#16951) (Thanks @MartinGC94!) +- Write out OSC indicator only if the `stdout` is not redirected (#17419) +- Remove the assert and use a relatively larger capacity to cover possible increase of .NET reference assemblies (#17423) +- Increase reference assembly count to 161 (#17420) + +### Code Cleanup + +
+ + + +

We thank the following contributors!

+

@Yulv-git, @eltociear

+ +
+ +
    +
  • Fix some typos in source code (#17481) (Thanks @Yulv-git!)
  • +
  • Fix typo in `AsyncResult.cs` (#17396) (Thanks @eltociear!)
  • +
+ +
+ +### Tools + +- Update script to pin to .NET 7 preview 5 version (#17448) +- Start-PSPester: argument completer for `-Path` (#17334) (Thanks @powercode!) +- Add reminder workflows (#17387) +- Move to configuring the fabric bot via JSON (#17411) +- Update Documentation Issue Template URL (#17410) (Thanks @michaeltlombardi!) +- Update script to automatically take new preview pre-release builds (#17375) + +### Tests + +- Make Assembly Load Native test work on a FX Dependent Linux Install (#17380) +- Update `Get-Error` test to not depend on DNS APIs (#17471) + +### Build and Packaging Improvements + +
+ +
    +
  • Update .NET SDK version from 7.0.100-preview.4.22252.9 to 7.0.100-preview.5.22307.18 (#17402)
  • +
  • Downgrade the Microsoft.CodeAnalysis.NetAnalyzers package to 7.0.0-preview1.22217.1 (#17515)
  • +
  • Rename mariner package to cm (#17505)
  • +
  • Bump Microsoft.CodeAnalysis.NetAnalyzers (#17476)
  • +
  • Bump NJsonSchema from 10.7.1 to 10.7.2 (#17475)
  • +
  • Publish preview versions of mariner to preview repo (#17451)
  • +
  • Update to the latest NOTICES file (#17421)
  • +
  • Do not publish package for Mariner 1.0 (#17415)
  • +
  • Add AppX capabilities in MSIX manifest so that PS7 can call the AppX APIs (#17416)
  • +
  • Update to the latest NOTICES file (#17401)
  • +
  • Fix mariner mappings (#17413)
  • +
  • Update the cgmanifest (#17393)
  • +
  • Bump `NJsonSchema` from `10.7.0` to `10.7.1` (#17381)
  • +
+ +
+ +### Documentation and Help Content + +- Update to the latest NOTICES file (#17493) (Thanks @github-actions[bot]!) +- Update the cgmanifest (#17478) (Thanks @github-actions[bot]!) +- Correct spelling in Comments and tests (#17480) (Thanks @Yulv-git!) +- Fix spelling errors introduced in changelog (#17414) +- Update change log for v7.3.0-preview.4 release (#17412) +- Update readme and metadata for 7.3.0-preview.4 release (#17378) + +[7.3.0-preview.5]: https://github.com/PowerShell/PowerShell/compare/v7.3.0-preview.4...v7.3.0-preview.5 + +## [7.3.0-preview.4] - 2022-05-23 + +### Engine Updates and Fixes + +
    +
  • Remove the use of BinaryFormatter in PSRP serialization (#17133) (Thanks @jborean93!)
  • +
  • Update telemetry collection removing unused data and adding some new data (#17304)
  • +
  • Fix the word wrapping in formatting to handle escape sequences properly (#17316)
  • +
  • Fix the error message in Hashtable-to-object conversion (#17329)
  • +
  • Add support for new WDAC API (#17247)
  • +
  • On Windows, reset cursor visibility back to previous state when rendering progress (#16782)
  • +
  • Fix the list view to not leak VT decorations (#17262)
  • +
  • Fix formatting truncation to handle strings with VT sequences (#17251)
  • +
  • Fix line breakpoints for return statements without a value (#17179)
  • +
  • Fix for partial PowerShell module search paths, that can be resolved to CWD locations (#17231) (Internal 20126)
  • +
  • Change logic in the testing helper module for determining whether PSHOME is writable (#17218)
  • +
  • Make a variable assignment in a ParenExpression to return the variable value (#17174)
  • +
  • Use new Windows signature APIs from Microsoft.Security.Extensions package (#17159)
  • +
  • Do not include node names when sending telemetry. (#16981)
  • +
  • Support forward slashes in network share (UNC path) completion (#17111) (#17117) (Thanks @sba923!)
  • +
  • Do not generate clean block in proxy function when the feature is disabled (#17112)
  • +
  • Ignore failure attempting to set console window title (#16948)
  • +
  • Update regex used to remove ANSI escape sequences to be more specific to decoration and CSI sequences (#16811)
  • +
  • Improve member auto completion (#16504) (Thanks @MartinGC94!)
  • +
  • Prioritize ValidateSet completions over Enums for parameters (#15257) (Thanks @MartinGC94!)
  • +
  • Add Custom Remote Connections Feature (#17011)
  • +
+ +### General Cmdlet Updates and Fixes + +
    +
  • Add check for ScriptBlock wrapped in PSObject to $using used in ForEach-Object -Parallel (#17234) (Thanks @ryneandal!)
  • +
  • Fix ForEach method to set property on a scalar object (#17213)
  • +
  • Fix Sort-Object -Stable -Unique to actually do stable sorting (#17189) (Thanks @m1k0net!)
  • +
  • Add OutputType attribute to various commands (#16962) (Thanks @MartinGC94!)
  • +
  • Make Stop-Service only request needed privileges when not setting SDDL. (#16663) (Thanks @kvprasoon!)
  • +
+ +### Code Cleanup + +
    +
  • Remove EventLogLogProvider and its related legacy code (#17027)
  • +
  • Fix typos in names of method (#17003) (Thanks @al-cheb!)
  • +
  • SemanticChecks: Avoid repeated type resolution of [ordered] (#17328) (Thanks IISResetMe!)
  • +
  • Redo the change that was reverted by #15853 (#17357)
  • +
  • Correct spelling of pseudo in Compiler.cs (#17285) (Thanks @eltociear!)
  • +
  • MakeNameObscurerTelemetryInitializer internal (#17214)
  • +
  • Make NameObscurerTelemetryInitializer internal (#17167)
  • +
  • Correct Typo in the resource string PathResolvedToMultiple (#17098) (Thanks @charltonstanley!)
  • +
  • Fix typo in ComRuntimeHelpers.cs (#17104) (Thanks @eltociear!)
  • +
+ +### Documentation and Help Content + +
    +
  • Update link to PowerShell remoting in depth video (#17166)
  • +
+ +### Tests + +
    +
  • Add -because to the failing test to aid in debugging (#17030)
  • +
  • Simplify Enum generator for the -bnot operator test (#17014)
  • +
  • Improve unique naming for tests (#17043)
  • +
  • Use a random string for the missing help topic to improve the chances that the help topic really won't be found. (#17042)
  • +
+ +### Build and Packaging Improvements + +
    +
  • Update README.md and metadata.json for v7.3.0-preview.3 release (#17029)
  • +
  • Do not pull dotnet updates from internal feed (#17007)
  • +
  • Simplify Get-WSManSupport based on current .NET Distro Support (#17356)
  • +
  • Update to the latest NOTICES file (#17372, #17332, #17311, #17275)
  • +
  • Run on every PR and let the action skip (#17366)
  • +
  • Make sure verbose message is not null (#17363)
  • +
  • Release changelogs (#17364)
  • +
  • Update build versions (#17318)
  • +
  • Add Daily Link Check GitHub Workflow (#17351)
  • +
  • Update the cgmanifest (#17361, #17344, #17324, #17302, #17268)
  • +
  • Bump NJsonSchema from 10.6.10 to 10.7.0 (#17350)
  • +
  • Disable broken macOS CI job, which is unused (#17221)
  • +
  • Have rebase workflow Post a message when it starts (#17341)
  • +
  • Update DotnetRuntimeMetadata.json for .NET 7 Preview 4 (#17336)
  • +
  • Update Ubuntu 22 to be detected as not supported WSMan (#17338)
  • +
  • Bump xunit.runner.visualstudio from 2.4.3 to 2.4.5 (#17274)
  • +
  • Make sure we execute tests on LTS package for older LTS releases (#17326)
  • +
  • Bump Microsoft.NET.Test.Sdk from 17.1.0 to 17.2.0 (#17320)
  • +
  • Add fedora to the OS's that can't run WSMan (#17325)
  • +
  • Add sles15 support to install-powershell.sh (#16984)
  • +
  • Start rotating through all images (#17315)
  • +
  • Update .NET SDK version from 7.0.100-preview.2.22153.17 to 7.0.100-preview.4.22252.9 (#17061)
  • +
  • Disable release security analysis for SSH CI (#17303)
  • +
  • Add a finalize template which causes jobs with issues to fail (#17314)
  • +
  • Add mapping for ubuntu22.04 jammy (#17317)
  • +
  • Enable more tests to be run in a container. (#17294)
  • +
  • Fix build.psm1 to find the required .NET SDK version when a higher version is installed (#17299)
  • +
  • Improve how Linux container CI builds are identified (#17295)
  • +
  • Only inject NuGet security analysis if we are using secure nuget.config (#17293)
  • +
  • Reduce unneeded verbose message from build.psm1 (#17291)
  • +
  • Switch to using GitHub action to verify markdown links for PRs (#17281)
  • +
  • Put Secure supply chain analysis at correct place (#17273)
  • +
  • Fix build id variable name when selecting CI container (#17279)
  • +
  • Add rotation between the two mariner images (#17277)
  • +
  • Update to use mcr.microsoft.com (#17272)
  • +
  • Update engine working group members (#17271)
  • +
  • Bump PSReadLine from 2.2.2 to 2.2.5 in /src/Modules (#17252)
  • +
  • Update timeout for daily (#17263)
  • +
  • Bump NJsonSchema from 10.6.9 to 10.6.10 (#16902)
  • +
  • Update the cgmanifest (#17260)
  • +
  • Fix Generate checksum file for packages build failure - v7.1.7 (#17219) (Internal 20274)
  • +
  • Move cgmanifest generation to daily (#17258)
  • +
  • Bump Microsoft.CodeAnalysis.NetAnalyzers (#17245)
  • +
  • Update to the latest notice file (#17238)
  • +
  • Add container to Linux CI (#17233)
  • +
  • Mark Microsoft.Management.Infrastructure.Runtime.Win as a developer dependency to hide in notice file (#17230)
  • +
  • Fixing dotnet SDK version parsing in build.psm1 (#17198) (Thanks @powercode!)
  • +
  • Fixed package names verification to support multi-digit versions (#17220)
  • +
  • Bump Microsoft.CodeAnalysis.CSharp from 4.2.0-1.final to 4.2.0-4.final (#17210)
  • +
  • Add backport action (#17212)
  • +
  • Updated change logs for v7.0.9 / v7.0.10 / v7.1.6 / v7.1.7 / v7.2.2 / v7.2.3 (#17207)
  • +
  • Updated metadata.json and README.md for v7.2.3 and v7.0.10 (#17158)
  • +
  • Update package fallback list for ubuntu (from those updated for ubuntu 22.04) (deb) (#17180)
  • +
  • Update wix to include security extensions package (#17171)
  • +
  • Update rebase.yml (#17170)
  • +
  • Adds sha256 digests to RPM packages (#16896) (Thanks @ngharo!)
  • +
  • Make mariner packages Framework dependent (#17151)
  • +
  • Update to the latest notice file (#17169)
  • +
  • Update to the latest notice file (#17146)
  • +
  • Replace . in notices container name (#17154)
  • +
  • Allow multiple installations of dotnet. (#17141)
  • +
  • Bump Microsoft.CodeAnalysis.NetAnalyzers (#17105)
  • +
  • Update to the latest notice file (#16437)
  • +
  • Skip failing scriptblock tests (#17093)
  • +
  • Update dotnet-install script download link (#17086)
  • +
  • Fix the version of the Microsoft.CodeAnalysis.NetAnalyzers package (#17075)
  • +
  • Update dotnetmetadata.json to accept .NET 7 preview 3 builds (#17063)
  • +
  • Re-enable PowerShellGet tests targeting PowerShell gallery (#17062)
  • +
  • Add mariner 1.0 amd64 package (#17057)
  • +
  • Create checksum file for global tools (#17056)
  • +
  • Bump Microsoft.CodeAnalysis.NetAnalyzers (#17065)
  • +
  • Use new cask format (#17064)
  • +
+ +[7.3.0-preview.4]: https://github.com/PowerShell/PowerShell/compare/v7.3.0-preview.3...v7.3.0-preview.4 + +## [7.3.0-preview.3] - 2022-03-21 + +### Engine Updates and Fixes + +- Fix the parsing code for .NET method generic arguments (#16937) +- Allow the `PSGetMemberBinder` to get value of `ByRef` property (#16956) +- Allow a collection that contains `Automation.Null` elements to be piped to pipeline (#16957) + +### General Cmdlet Updates and Fixes + +- Add the module `CompatPowerShellGet` to the allow-list of telemetry modules (#16935) +- Fix `Enter-PSHostProcess` and `Get-PSHostProcessInfo` cmdlets by handling processes that have exited (#16946) +- Improve Hashtable completion in multiple scenarios (#16498) (Thanks @MartinGC94!) + +### Code Cleanup + +- Fix a typo in `CommandHelpProvider.cs` (#16949) (Thanks @eltociear!) + +### Tests + +- Update a few tests to make them more stable in CI (#16944) +- Roll back Windows images used in testing to Windows Server 2019 (#16958) + +### Build and Packaging Improvements + +
+ + +

Update .NET SDK to 7.0.0-preview.2

+
+ +
    +
  • Update .NET to 7.0.0-preview.2 build (#16930)
  • +
  • Update AzureFileCopy task and fix the syntax for specifying pool (#17013)
  • +
+ +
+ +[7.3.0-preview.3]: https://github.com/PowerShell/PowerShell/compare/v7.3.0-preview.2...v7.3.0-preview.3 + +## [7.3.0-preview.2] - 2022-02-24 + +### Engine Updates and Fixes + +- Fix the `clean` block for generated proxy function (#16827) +- Add support to allow invoking method with generic type arguments (#12412 and #16822) (Thanks @vexx32!) +- Report error when PowerShell built-in modules are missing (#16628) + +### General Cmdlet Updates and Fixes + +- Prevent command completion if the word to complete is a single dash (#16781) (Thanks @ayousuf23!) +- Use `FindFirstFileW` instead of `FindFirstFileExW` to correctly handle Unicode file names on FAT32 (#16840) (Thanks @iSazonov!) +- Add completion for loop labels after Break/Continue (#16438) (Thanks @MartinGC94!) +- Support OpenSSH options for `PSRP` over SSH commands (#12802) (Thanks @BrannenGH!) +- Adds a `.ResolvedTarget` Property to `File-System` Items to Reflect a Symlink's Target as `FileSystemInfo` (#16490) (Thanks @hammy3502!) +- Use `NotifyEndApplication` to re-enable VT mode (#16612) +- Add new parameter to `Start-Sleep`: `[-Duration] ` (#16185) (Thanks @IISResetMe!) +- Add lock and null check to remoting internals (#16542) (#16683) (Thanks @SergeyZalyadeev!) +- Make `Measure-Object` ignore missing properties unless running in strict mode (#16589) (Thanks @KiwiThePoodle!) +- Add `-StrictMode` to `Invoke-Command` to allow specifying strict mode when invoking command locally (#16545) (Thanks @Thomas-Yu!) +- Fix `$PSNativeCommandArgPassing` = `Windows` to handle empty args correctly (#16639) +- Reduce the amount of startup banner text (#16516) (Thanks @rkeithhill!) +- Add `exec` cmdlet for bash compatibility (#16462) +- Add AMSI method invocation logging as experimental feature (#16496) +- Fix web cmdlets so that an empty `Get` does not include a `content-length` header (#16587) +- Update `HelpInfoUri` for 7.3 release (#16646) +- Fix parsing `SemanticVersion` build label from version string (#16608) +- Fix `ForEach-Object -Parallel` when passing in script block variable (#16564) + +### Code Cleanup + +
+ + + +

We thank the following contributors!

+

@eltociear, @iSazonov, @xtqqczze

+ +
+ +
    +
  • Fix typo in PowerShellExecutionHelper.cs (#16776) (Thanks @eltociear!)
  • +
  • Use more efficient platform detection API (#16760) (Thanks @iSazonov!)
  • +
  • Seal ClientRemotePowerShell (#15802) (Thanks @xtqqczze!)
  • +
  • Fix the DSC overview URL in a markdown file and some small cleanup changes (#16629)
  • +
+ +
+ +### Tools + +- Fix automation to update experimental JSON files in GitHub action (#16837) + +### Tests + +- Update `markdownlint` to the latest version (#16825) +- Bump the package `path-parse` from `1.0.6` to `1.0.7` (#16820) +- Remove assert that is incorrect and affecting our tests (#16588) + +### Build and Packaging Improvements + +
+ + + +

We thank the following contributors!

+

@dahlia

+ +
+ +
    +
  • Update NuGet Testing to not re-install dotnet, +when not needed and dynamically determine the DOTNET_ROOT (Internal 19268, 19269, 19272, 19273, and 19274)
  • +
  • Remove SkipExperimentalFeatureGeneration when building alpine (Internal 19248)
  • +
  • Revert .NET 7 changes, Update to the latest .NET 6 and Update WXS file due to blocking issue in .NET 7 Preview 1
  • +
  • Install and Find AzCopy
  • +
  • Use Start-PSBootStrap for installing .NET during nuget packaging
  • +
  • Fix pool syntax for deployments (Internal 19189)
  • +
  • Bump NJsonSchema from 10.5.2 to 10.6.9 (#16888)
  • +
  • Update projects and scripts to use .NET 7 preview 1 pre-release builds (#16856)
  • +
  • Add warning messages when package precheck fails (#16867)
  • +
  • Refactor Global Tool packaging to include SBOM generation (#16860)
  • +
  • Update to use windows-latest as the build agent image (#16831)
  • +
  • Ensure alpine and arm SKUs have powershell.config.json file with experimental features enabled (#16823)
  • +
  • Update experimental feature json files (#16838) (Thanks @github-actions[bot]!)
  • +
  • Remove WiX install (#16834)
  • +
  • Add experimental json update automation (#16833)
  • +
  • Update .NET SDK to 6.0.101 and fix Microsoft.PowerShell.GlobalTool.Shim.csproj (#16821)
  • +
  • Add SBOM manifest to nuget packages (#16711)
  • +
  • Improve logic for updating .NET in CI (#16808)
  • +
  • Add Linux package dependencies for packaging (#16807)
  • +
  • Switch to our custom images for build and release (#16801)
  • +
  • Remove all references to cmake for the builds in this repo (#16578)
  • +
  • Fix build for new InvokeCommand attributes (#16800)
  • +
  • Let macOS installer run without Rosetta on Apple Silicon (#16742) (Thanks @dahlia!)
  • +
  • Update the expect .NET SDK quality to GA for installing dotnet (#16784)
  • +
  • Change nuget release yaml to use UseDotNet task (#16701)
  • +
  • Bump Microsoft.ApplicationInsights from 2.19.0 to 2.20.0 (#16642)
  • +
  • Register NuGet source when generating CGManifest (#16570)
  • +
  • Update Images used for release (#16580)
  • +
  • Update SBOM generation (#16641)
  • +
  • Bring changes from 7.3.0-preview.1 (#16640)
  • +
  • Update the vmImage and PowerShell root directory for macOS builds (#16611)
  • +
  • Update macOS build image and root folder for build (#16609)
  • +
  • Disabled Yarn cache in markdown.yml (#16599)
  • +
  • Update cgmanifest (#16600)
  • +
  • Fix broken links in markdown (#16598)
  • +
+ +
+ +### Documentation and Help Content + +- Add newly joined members to their respective Working Groups (#16849) +- Update Engine Working Group members (#16780) +- Replace the broken link about pull request (#16771) +- Update change log to remove a broken URL (#16735) +- Updated `README.md` and `metadata.json` for `v7.3.0-preview.1` release (#16627) +- Updating changelog for `7.2.1` (#16616) +- Updated `README.md` and `metadata.json` for `7.2.1` release (#16586) + +[7.3.0-preview.2]: https://github.com/PowerShell/PowerShell/compare/v7.3.0-preview.1...v7.3.0-preview.2 + +## [7.3.0-preview.1] - 2021-12-16 + +### Breaking Changes + +- Add `clean` block to script block as a peer to `begin`, `process`, and `end` to allow easy resource cleanup (#15177) +- Change default for `$PSStyle.OutputRendering` to `Ansi` (Internal 18449) + +### Engine Updates and Fixes + +- Remove duplicate remote server mediator code (#16027) +- Fix `PSVersion` parameter version checks and error messages for PowerShell 7 remoting (#16228) +- Use the same temporary home directory when `HOME` env variable is not set (#16263) +- Fix parser to generate error when array has more than 32 dimensions (#16276) + +### Performance + +- Avoid validation for built-in file extension and color VT sequences (#16320) (Thanks @iSazonov!) + +### General Cmdlet Updates and Fixes + +- Update `README.md` and `metadata.json` for next preview release (#16107) +- Use `PlainText` when writing to a host that doesn't support VT (#16092) +- Remove support for `AppExeCLinks` to retrieve target (#16044) +- Move `GetOuputString()` and `GetFormatStyleString()` to `PSHostUserInterface` as public API (#16075) +- Fix `ConvertTo-SecureString` with key regression due to .NET breaking change (#16068) +- Fix regression in `Move-Item` to only fallback to `copy and delete` in specific cases (#16029) +- Set `$?` correctly for command expression with redirections (#16046) +- Use `CurrentCulture` when handling conversions to `DateTime` in `Add-History` (#16005) (Thanks @vexx32!) +- Fix link header parsing to handle unquoted `rel` types (#15973) (Thanks @StevenLiekens!) +- Fix a casting error when using `$PSNativeCommandUsesErrorActionPreference` (#15993) +- Format-Wide: Fix `NullReferenceException` (#15990) (Thanks @DarylGraves!) +- Make the native command error handling optionally honor `ErrorActionPreference` (#15897) +- Remove declaration of experimental features in Utility module manifest as they are stable (#16460) +- Fix race condition between `DisconnectAsync` and `Dispose` (#16536) (Thanks @i3arnon!) +- Fix the `Max_PATH` condition check to handle long path correctly (#16487) (Thanks @Shriram0908!) +- Update `HelpInfoUri` for 7.2 release (#16456) +- Fix tab completion within the script block specified for the `ValidateScriptAttribute`. (#14550) (Thanks @MartinGC94!) +- Update `README.md` to specify gathered telemetry (#16379) +- Fix typo for "privacy" in MSI installer (#16407) +- Remove unneeded call to `File.ResolveLinkTarget` from `IsWindowsApplication` (#16371) (Thanks @iSazonov!) +- Add `-HttpVersion` parameter to web cmdlets (#15853) (Thanks @hayhay27!) +- Add support to web cmdlets for open-ended input tags (#16193) (Thanks @farmerau!) +- Add more tests to `Tee-Object -Encoding` (#14539) (Thanks @rpolley!) +- Don't throw exception when trying to resolve a possible link path (#16310) +- Fix `ConvertTo-Json -Depth` to allow 100 at maximum (#16197) (Thanks @KevRitchie!) +- Fix for SSH remoting when banner is enabled on SSHD endpoint (#16205) +- Disallow all COM for AppLocker system lock down (#16268) +- Configure `ApplicationInsights` to not send cloud role name (#16246) +- Disallow `Add-Type` in NoLanguage mode on a locked down machine (#16245) +- Specify the executable path as `TargetObect` for non-zero exit code `ErrorRecord` (#16108) (Thanks @rkeithhill!) +- Don't allow `Move-Item` with FileSystemProvider to move a directory into itself (#16198) +- Make property names for the color VT sequences consistent with documentations (#16212) +- Fix `PipelineVariable` to set variable in the right scope (#16199) +- Invoke-Command: improve handling of variables with $using: expression (#16113) (Thanks @dwtaber!) +- Change `Target` from a `CodeProperty` to be an `AliasProperty` that points to `FileSystemInfo.LinkTarget` (#16165) + +### Code Cleanup + +
+ + + +

We thank the following contributors!

+

@xtqqczze, @eltociear, @iSazonov

+ +
+ +
    +
  • Improve CommandInvocationIntrinsics API documentation and style (#14369)
  • +
  • Use bool?.GetValueOrDefault() in FormatWideCommand (#15988) (Thanks @xtqqczze!)
  • +
  • Remove 4 assertions which cause debug build test runs to fail (#15963)
  • +
  • Fix typo in `Job.cs` (#16454) (Thanks @eltociear!)
  • +
  • Remove unnecessary call to `ToArray` (#16307) (Thanks @iSazonov!)
  • +
  • Remove the unused `FollowSymLink` function (#16231)
  • +
  • Fix typo in `TypeTable.cs` (#16220) (Thanks @eltociear!)
  • +
  • Fixes #16176 - replace snippet tag with code tag in comments (#16177)
  • +
+ +
+ +### Tools + +- Fix typo in build.psm1 (#16038) (Thanks @eltociear!) +- Add `.stylecop` to `filetypexml` and format it (#16025) +- Enable sending Teams notification when workflow fails (#15982) +- Use `Convert-Path` for unknown drive in `Build.psm1` (#16416) (Thanks @matt9ucci!) + +### Tests + +- Add benchmark to test compiler performance (#16083) +- Enable two previously disabled `Get-Process` tests (#15845) (Thanks @iSazonov!) +- Set clean state before testing `UseMU` in the MSI (#16543) +- Fix global tool and SDK tests in release pipeline (#16342) +- Remove the outdated test (#16269) +- Removed old not-used-anymore docker-based tests for PS release packages (#16224) + +### Build and Packaging Improvements + +
+ + + +

We thank the following contributors!

+

@github-actions[bot], @kondratyev-nv

+ +
+ +
    +
  • fix issue with hash file getting created before we have finished get-childitem (#16170)
  • +
  • Add sha256 hashes to release (#16147)
  • +
  • Change path for Component Governance for build to the path we actually use to build (#16137)
  • +
  • Update Microsoft.CodeAnalysis.CSharp version (#16138)
  • +
  • Bump Microsoft.CodeAnalysis.NetAnalyzers (#16070)
  • +
  • Update .NET to 6.0.100-rc.1.21458.32 (#16066)
  • +
  • Update minimum required OS version for macOS (#16088)
  • +
  • Set locale correctly on Linux CI (#16073)
  • +
  • Ensure locale is set correctly on Ubuntu 20.04 in CI (#16067)
  • +
  • Bump Microsoft.CodeAnalysis.NetAnalyzers (#16045)
  • +
  • Update .NET SDK version from `6.0.100-rc.1.21430.44` to `6.0.100-rc.1.21455.2` (#16041) (Thanks @github-actions[bot]!)
  • +
  • Fix the GitHub Action for updating .NET daily builds (#16042)
  • +
  • Bump Microsoft.CodeAnalysis.CSharp from 4.0.0-3.final to 4.0.0-4.21430.4 (#16036)
  • +
  • Bump .NET to `6.0.100-rc.1.21430.44` (#16028)
  • +
  • Move from PkgES hosted agents to 1ES hosted agents (#16023)
  • +
  • Bump Microsoft.CodeAnalysis.NetAnalyzers (#16021)
  • +
  • Update Ubuntu images to use Ubuntu 20.04 (#15906)
  • +
  • Fix the mac build by updating the pool image name (#16010)
  • +
  • Use Alpine 3.12 for building PowerShell for alpine (#16008)
  • +
  • Update .NET SDK version from `6.0.100-preview.6.21355.2` to `6.0.100-rc.1.21426.1` (#15648) (Thanks @github-actions[bot]!)
  • +
  • Ignore error from Find-Package (#15999)
  • +
  • Find packages separately for each source in UpdateDotnetRuntime.ps1 script (#15998)
  • +
  • Update metadata to start using .NET 6 RC1 builds (#15981)
  • +
  • Bump Microsoft.CodeAnalysis.NetAnalyzers (#15985)
  • +
  • Merge the v7.2.0-preview.9 release branch back to GitHub master (#15983)
  • +
  • Publish global tool package for stable releases (#15961)
  • +
  • Bump Microsoft.CodeAnalysis.NetAnalyzers to newer version (#15962)
  • +
  • Disabled Yarn cache in markdown.yml (#16599)
  • +
  • Update cgmanifest (#16600)
  • +
  • Fix broken links in markdown (#16598)
  • +
  • Add explicit job name for approval tasks in Snap stage (#16579)
  • +
  • Bring back pwsh.exe for framework dependent packages to support Start-Job (#16535)
  • +
  • Fix NuGet package generation in release build (#16509)
  • +
  • Add `Microsoft.PowerShell.Commands.SetStrictModeCommand.ArgumentToPSVersionTransformationAttribute` to list of patterns to remove for generated ref assembly (#16489)
  • +
  • Bump Microsoft.CodeAnalysis.CSharp from `4.0.0-6.final` to `4.0.1` (#16423)
  • +
  • use different containers for different branches (#16434)
  • +
  • Add import so we can use common GitHub workflow function. (#16433)
  • +
  • Remove pre-release .NET 6 build sources (#16418)
  • +
  • Update release instructions with link to new build (#16419)
  • +
  • Bump Microsoft.ApplicationInsights from 2.18.0 to 2.19.0 (#16413)
  • +
  • Update metadata.json to make 7.2.0 the latest LTS (#16417)
  • +
  • Make static CI a matrix (#16397)
  • +
  • Update metadata.json in preparation on 7.3.0-preview.1 release (#16406)
  • +
  • Update cgmanifest (#16405)
  • +
  • Add diagnostics used to take corrective action when releasing `buildInfoJson` (#16404)
  • +
  • `vPack` release should use `buildInfoJson` new to 7.2 (#16402)
  • +
  • Update the usage of metadata.json for getting LTS information (#16381)
  • +
  • Add checkout to build json stage to get `ci.psm1` (#16399)
  • +
  • Update CgManifest.json for 6.0.0 .NET packages (#16398)
  • +
  • Add current folder to the beginning of the module import (#16353)
  • +
  • Increment RC MSI build number by 100 (#16354)
  • +
  • Bump XunitXml.TestLogger from 3.0.66 to 3.0.70 (#16356)
  • +
  • Move PR Quantifier config to subfolder (#16352)
  • +
  • Release build info json when it is preview (#16335)
  • +
  • Add an approval for releasing build-info json (#16351)
  • +
  • Generate manifest with latest public version of the packages (#16337)
  • +
  • Update to the latest notices file (#16339) (Thanks @github-actions[bot]!)
  • +
  • Use notice task to generate license assuming cgmanifest contains all components (#16340)
  • +
  • Refactor cgmanifest generator to include all components (#16326)
  • +
  • Fix issues in release build (#16332)
  • +
  • Update feed and analyzer dependency (#16327)
  • +
  • Bump Microsoft.NET.Test.Sdk from 16.11.0 to 17.0.0 (#16312)
  • +
  • Update license and cgmanifest (#16325) (Thanks @github-actions[bot]!)
  • +
  • Fix condition in cgmanifest logic (#16324)
  • +
  • Add GitHub Workflow to keep notices up to date (#16284)
  • +
  • Update to latest .NET 6 GA build 6.0.100-rtm.21527.11 (#16309)
  • +
  • Create compliance build (#16286)
  • +
  • Move mapping file into product repo and add Debian 11 (#16316)
  • +
  • Add a major-minor build info JSON file (#16301)
  • +
  • Clean up crossgen related build scripts also generate native symbols for R2R images (#16297)
  • +
  • Fix Windows build ZIP packaging (#16299) (Thanks @kondratyev-nv!)
  • +
  • Revert "Update to use .NET 6 GA build (#16296)" (#16308)
  • +
  • Add wget as a dependency for Bootstrap script (#16303) (Thanks @kondratyev-nv!)
  • +
  • Fix issues reported by code signing verification tool (#16291)
  • +
  • Update to use .NET 6 GA build (#16296)
  • +
  • Revert "add GH workflow to keep the cgmanifest up to date." (#16294)
  • +
  • Update ChangeLog for 7.2.0-rc.1 and also fix RPM packaging (#16290)
  • +
  • Bump Microsoft.CodeAnalysis.NetAnalyzers (#16271)
  • +
  • add GH workflow to keep the cgmanifest up to date.
  • +
  • Update ThirdPartyNotices.txt (#16283)
  • +
  • Update `testartifacts.yml` to use ubuntu-latest image (#16279)
  • +
  • Update version of Microsoft.PowerShell.Native and Microsoft.PowerShell.MarkdownRender packages (#16277)
  • +
  • Add script to generate cgmanifest.json (#16278)
  • +
  • Add cgmanifest.json for generating correct third party notice file (#16266)
  • +
  • Bump Microsoft.CodeAnalysis.NetAnalyzers from `6.0.0-rtm.21504.2` to `6.0.0-rtm.21516.1` (#16264)
  • +
  • Only upload stable buildinfo for stable releases (#16251)
  • +
  • Make RPM license recognized (#16189)
  • +
  • Don't upload dep or tar.gz for RPM because there are none. (#16230)
  • +
  • Add condition to generate release files in local dev build only (#16259)
  • +
  • Update .NET 6 to version 6.0.100-rc.2.21505.57 (#16249)
  • +
  • change order of try-catch-finally and split out arm runs (#16252)
  • +
  • Ensure psoptions.json and manifest.spdx.json files always exist in packages (#16258)
  • +
  • Update to vPack task version to 12 (#16250)
  • +
  • Remove unneeded `NuGetConfigFile` resource string (#16232)
  • +
  • Add Software Bill of Materials to the main packages (#16202)
  • +
  • Sign third party exes (#16229)
  • +
  • Upgrade set-value package for markdown test (#16196)
  • +
  • Use Ubuntu 20.04 for SSH remoting test (#16225)
  • +
  • Bump Microsoft.CodeAnalysis.NetAnalyzers (#16194)
  • +
  • Bump `Microsoft.CodeAnalysis.NetAnalyzers` from `6.0.0-rc2.21458.5` to `6.0.0-rtm.21480.8` (#16183)
  • +
  • Move vPack build to 1ES Pool (#16169)
  • +
  • Fix Microsoft update spelling issue. (#16178)
  • +
+ +
+ +### Documentation and Help Content + +- Update Windows PowerShell issues link (#16105) (Thanks @andschwa!) +- Remove Joey from Committee and WG membership (#16119) +- Update more docs for `net6.0` TFM (#16102) (Thanks @xtqqczze!) +- Change `snippet` tag to `code` tag in XML comments (#16106) +- Update build documentation to reflect .NET 6 (#15751) (Thanks @Kellen-Stuart!) +- Update `README.md` about the change logs (#16471) (Thanks @powershellpr0mpt!) +- Update change log for 7.2.0 (#16401) +- Update `metadata.json` and `README.md` for 7.2.0 release (#16395) +- Update `README.md` and `metadata.json` files for `v7.2.0-rc.1` release (#16285) +- Update the change logs for `v7.0.8` and `v7.1.5` releases (#16248) + +[7.3.0-preview.1]: https://github.com/PowerShell/PowerShell/compare/v7.2.0-preview.10...v7.3.0-preview.1 diff --git a/CHANGELOG/preview.md b/CHANGELOG/preview.md index 96163085408..035db721385 100644 --- a/CHANGELOG/preview.md +++ b/CHANGELOG/preview.md @@ -1,897 +1 @@ # Current preview release - -## [7.3.0-rc.1] - 2022-10-26 - -### Breaking Change - -- Update to use `ComputeCore.dll` for PowerShell Direct (#18194) - -### Engine Updates and Fixes - -- On Unix, explicitly terminate the native process during cleanup only if it's not running in background (#18215) - -### General Cmdlet Updates and Fixes - -- Remove the `ProcessorArchitecture` portion from the full name as it's obsolete (#18320) - -### Tests - -- Add missing `-Tag 'CI'` to describe blocks. (#18317) - -### Build and Packaging Improvements - -
- - -

Bump to .NET 7 to 7.0.100-rc.2.22477.20 (#18328)(#18286)

-
- -
    -
  • Update ThirdPartyNotices (Internal 22987)
  • -
  • Remove API sets (#18304) (#18376)
  • -
  • Do not cleanup pwsh.deps.json for framework dependent packages (#18300)
  • -
  • Bump Microsoft.PowerShell.Native from 7.3.0-preview.1 to 7.3.0-rc.1 (#18217)
  • -
  • Remove unnecessary native dependencies from the package (#18213)
  • -
  • Make the link to minimal package blob public during release (#18158)
  • -
  • Create tasks to collect and publish hashes for build files. (#18276)(#18277)
  • -
  • Add branch counter to compliance build (#18214)
  • -
  • Move APIScan to compliance build (#18191)
  • -
  • Update MSI exit message (#18137)
  • -
  • Remove XML files for min-size package (#18189)
  • -
- -
- -[7.3.0-rc.1]: https://github.com/PowerShell/PowerShell/compare/v7.3.0-preview.8...v7.3.0-rc.1 - -## [7.3.0-preview.8] - 2022-09-20 - -### General Cmdlet Updates and Fixes - -- Filter out compiler generated types for `Add-Type -PassThru` (#18095) -- Fix error formatting to use color defined in `$PSStyle.Formatting` (#17987) -- Handle `PSObject` argument specially in method invocation logging (#18060) -- Revert the experimental feature `PSStrictModeAssignment` (#18040) -- Make experimental feature `PSAMSIMethodInvocationLogging` stable (#18041) -- Make experimental feature `PSAnsiRenderingFileInfo` stable (#18042) -- Make experimental feature `PSCleanBlock` stable (#18043) -- Make experimental feature `PSNativeCommandArgumentPassing` stable (#18044) -- Make experimental feature `PSExec` stable (#18045) -- Make experimental feature `PSRemotingSSHTransportErrorHandling` stable (#18046) -- Add the `ConfigurationFile` option to the PowerShell help content (#18093) - -### Build and Packaging Improvements - - -

Bump .NET SDK to version `7.0.100-rc.1`

-
- -
-
    -
  • Update ThirdPartyNotices.txt for 7.3.0-preview.8 (Internal 22553)
  • -
  • Update cgmanifest.json for 7.3.0-preview.8 (Internal 22551)
  • -
  • Re-enable building with Ready-to-Run (#18107)
  • -
  • Make sure Security.types.ps1xml gets signed in release build (#17930)
  • -
  • Update DotnetRuntimeMetadata.json for .NET 7 RC1 build (#18106)
  • -
  • Add XML reference documents to NuPkg files for SDK (#18017)
  • -
  • Make Register MU timeout (#17995)
  • -
  • Bump Microsoft.NET.Test.Sdk from 17.2.0 to 17.3.0 (#17924)
  • -
  • Update list of PS team members in release tools (#17928)
  • -
  • Update to use version 2.21.0 of Application Insights (#17927)
  • -
  • Complete ongoing Write-Progress in test (#17922)
  • -
-
- -[7.3.0-preview.8]: https://github.com/PowerShell/PowerShell/compare/v7.3.0-preview.7...v7.3.0-preview.8 - -## [7.3.0-preview.7] - 2022-08-09 - -### Breaking Changes - -- Move the type data definition of `System.Security.AccessControl.ObjectSecurity` to the `Microsoft.PowerShell.Security` module (#16355) (Thanks @iSazonov!) - -### Engine Updates and Fixes - -- Enable searching for assemblies in `GAC_Arm64` on Windows (#17816) -- Fix parser exception in using statements with empty aliases (#16745) (Thanks @MartinGC94!) -- Do not always collapse space between parameter and value for native arguments. (#17708) -- Remove `PSNativePSPathResolution` experimental feature (#17670) - -### General Cmdlet Updates and Fixes - -- Fix for deserializing imported ordered dictionary (#15545) (Thanks @davidBar-On!) -- Make generated implicit remoting modules backwards compatible with PowerShell 5.1 (#17227) (Thanks @Tadas!) -- Re-enable IDE0031: Use Null propagation (#17811) (Thanks @fflaten!) -- Allow commands to still be executed even if the current working directory no longer exists (#17579) -- Stop referencing `Microsoft.PowerShell.Security` when the core snapin is used (#17771) -- Add support for HTTPS with `Set-AuthenticodeSignature -TimeStampServer` (#16134) (Thanks @Ryan-Hutchison-USAF!) -- Add type accelerator `ordered` for `OrderedDictionary` (#17804) (Thanks @fflaten!) -- Fix the definition of the `PDH_COUNTER_INFO` struct (#17779) -- Adding Virtualization Based Security feature names to Get-ComputerInfo (#16415) (Thanks @mattifestation!) -- Fix `FileSystemProvider` to work with volume and pipe paths (#15873) -- Remove pre-parse for array-based JSON (#15684) (Thanks @strawgate!) -- Improve type inference for `$_` (#17716) (Thanks @MartinGC94!) -- Prevent braces from being removed when completing variables (#17751) (Thanks @MartinGC94!) -- Fix type inference for `ICollection` (#17752) (Thanks @MartinGC94!) -- Fix `Test-Json` not handling non-object types at root (#17741) (Thanks @dkaszews!) -- Change `Get-ChildItem` to treat trailing slash in path as indicating a directory when used with `-Recurse` (#17704) -- Add `find.exe` to legacy argument binding behavior for Windows (#17715) -- Add completion for index expressions for dictionaries (#17619) (Thanks @MartinGC94!) -- Fix enum-ranges for `ValidateRange` in proxy commands (#17572) (Thanks @fflaten!) -- Fix type completion for attribute tokens (#17484) (Thanks @MartinGC94!) -- Add `-noprofileloadtime` switch to `pwsh` (#17535) (Thanks @rkeithhill!) -- Fix legacy `ErrorView` types to use `$host.PrivateData` colors (#17705) -- Improve dynamic parameter tab completion (#17661) (Thanks @MartinGC94!) -- Avoid binding positional parameters when completing parameter in front of value (#17693) (Thanks @MartinGC94!) -- Render decimal numbers in a table using current culture (#17650) - -### Code Cleanup - -
- - - -

We thank the following contributors!

-

@fflaten, @Molkree, @eltociear

- -
- -
    -
  • Fix other path constructions using Path.Join (#17825)
  • -
  • Use null propagation (#17787)(#17789)(#17790)(#17791)(#17792)(#17795) (Thanks @fflaten!)
  • -
  • Re-enable compound assignment preference (#17784) (Thanks @Molkree!)
  • -
  • Use null-coalescing assignment (#17719)(#17720)(#17721)(#17722)(#17723)(#17724)(#17725)(#17726)(#17727)(#17728)(#17729) (Thanks @Molkree!)
  • -
  • Disable the warning IDE0031 to take .NET 7 Preview 7 (#17770)
  • -
  • Fix typo in ModuleCmdletBase.cs (#17714) (Thanks @eltociear!)
  • -
- -
- -### Tests - -- Re-enable tests because the corresponding dotnet issues were fixed (#17839) -- Add test for `LanguageMode` using remoting (#17803) (Thanks @fflaten!) -- Fix test perf by stopping ongoing `write-progress` (#17749) (Thanks @fflaten!) -- Re-enable the test `TestLoadNativeInMemoryAssembly` (#17738) - -### Build and Packaging Improvements - -
- - - -

We thank the following contributors!

-

@varunsh-coder, @dkaszews, @Molkree, @ChuckieChen945

- -
- -
    -
  • Update release pipeline to use Approvals and automate some manual tasks (#17837)
  • -
  • Add GitHub token permissions for workflows (#17781) (Thanks @varunsh-coder!)
  • -
  • Bump actions/github-script from 3 to 6 (#17842)
  • -
  • Bump cirrus-actions/rebase from 1.6 to 1.7 (#17843)
  • -
  • Remove unneeded verbose message in build (#17840)
  • -
  • Detect default runtime using dotnet --info in build.psm1 (#17818) (Thanks @dkaszews!)
  • -
  • Bump actions/checkout from 2 to 3 (#17828)
  • -
  • Bump actions/download-artifact from 2 to 3 (#17829)
  • -
  • Bump github/codeql-action from 1 to 2 (#17830)
  • -
  • Bump peter-evans/create-pull-request from 3 to 4 (#17831)
  • -
  • Bump actions/upload-artifact from 2 to 3 (#17832)
  • -
  • Enable Dependabot for GitHub Actions (#17775) (Thanks @Molkree!)
  • -
  • Update .NET SDK version from 7.0.100-preview.6.22352.1 to 7.0.100-preview.7.22377.5 (#17776)
  • -
  • Fix a bug in install-powershell.ps1 (#17794) (Thanks @ChuckieChen945!)
  • -
  • Bump xunit from 2.4.1 to 2.4.2 (#17817)
  • -
  • Update how to update homebrew (#17798)
  • -
  • Don't run link check on forks (#17797)
  • -
  • Update dotnetmetadata.json to start consuming .NET 7 preview 7 builds (#17736)
  • -
  • Bump PackageManagement from 1.4.7 to 1.4.8.1 (#17709)
  • -
  • Exclude ARM images from running in CI (#17713)
  • -
- -
- -### Documentation and Help Content - -- Update the comment about why R2R is disabled (#17850) -- Update changelog and `.spelling` for `7.3.0-preview.6` release (#17835) -- Updated `ADOPTERS.md` for Power BI (#17766) -- Update README.md with the current Fedora version (#15717) (Thanks @ananya26-vishnoi!) -- Update `README` and `metadata.json` for next release (#17676) (Thanks @SeeminglyScience!) - -[7.3.0-preview.7]: https://github.com/PowerShell/PowerShell/compare/v7.3.0-preview.6...v7.3.0-preview.7 - -## [7.3.0-preview.6] - 2022-07-18 - -### General Cmdlet Updates and Fixes - -- Fix `Export-PSSession` to not throw error when a rooted path is specified for `-OutputModule` (#17671) -- Change `ConvertFrom-Json -AsHashtable` to use ordered hashtable (#17405) -- Remove potential ANSI escape sequences in strings before using in `Out-GridView` (#17664) -- Add the `-Milliseconds` parameter to `New-TimeSpan` (#17621) (Thanks @NoMoreFood!) -- Update `Set-AuthenticodeSignature` to use `SHA256` as the default (#17560) (Thanks @jborean93!) -- Fix tab completion regression when completing `ValidateSet` values (#17628) (Thanks @MartinGC94!) -- Show optional parameters as such when displaying method definition and overloads (#13799) (Thanks @eugenesmlv!) - -### Code Cleanup - -
- - - -

We thank the following contributors!

-

@sethvs, @MartinGC94, @eltociear

- -
- -
    -
  • Fix comment in InternalCommands.cs (#17669) (Thanks @sethvs!)
  • -
  • Use discards for unused variables (#17620) (Thanks @MartinGC94!)
  • -
  • Fix typo in CommonCommandParameters.cs (#17524) (Thanks @eltociear!)
  • -
- -
- -### Tests - -- Fix SDK tests for release build (#17678) - -### Build and Packaging Improvements - -
- - - -

We thank the following contributors!

-

@tamasvajk

- -
- -
    -
  • Create test artifacts for Windows ARM64 (#17675)
  • -
  • Update to the latest NOTICES file (#17607)
  • -
  • Update .NET SDK version from 7.0.100-preview.5.22307.18 to 7.0.100-preview.6.22352.1 (#17634)
  • -
  • Set the compound assignment preference to false (#17632)
  • -
  • Update DotnetMetadata.json to start consuming .NET 7 Preview 6 builds (#17630)
  • -
  • Install .NET 3.1 as it is required by the vPack task (#17600)
  • -
  • Update to use PSReadLine v2.2.6 (#17595)
  • -
  • Fix build.psm1 to not specify both version and quality for dotnet-install (#17589) (Thanks @tamasvajk!)
  • -
  • Bump Newtonsoft.Json in /test/perf/dotnet-tools/Reporting (#17592)
  • -
  • Bump Newtonsoft.Json in /test/perf/dotnet-tools/ResultsComparer (#17566)
  • -
  • Disable RPM SBOM test. (#17532)
  • -
- -
- -### Documentation and Help Content - -- Remove `katacoda.com` from doc as it now returns 404 (#17625) -- Update change log for `v7.2.5` and `v7.3.0-preview.5` (#17565) -- Update `README.md` and `metadata.json` for upcoming releases (#17526) - -[7.3.0-preview.6]: https://github.com/PowerShell/PowerShell/compare/v7.3.0-preview.5...v7.3.0-preview.6 - -## [7.3.0-preview.5] - 2022-06-21 - -### Engine Updates and Fixes - -- Improve type inference and completions (#16963) (Thanks @MartinGC94!) -- Make `Out-String` and `Out-File` keep string input unchanged (#17455) -- Make `AnsiRegex` able to capture Hyperlink ANSI sequences (#17442) -- Add the `-ConfigurationFile` command line parameter to `pwsh` to support local session configuration (#17447) -- Fix native library loading for `osx-arm64` (#17365) (Thanks @awakecoding!) -- Fix formatting to act appropriately when the style of table header or list label is empty string (#17463) - -### General Cmdlet Updates and Fixes - -- Fix various completion issues inside the `param` block (#17489) (Thanks @MartinGC94!) -- Add Amended switch to `Get-CimClass` cmdlet (#17477) (Thanks @iSazonov!) -- Improve completion on operators (#17486) (Thanks @MartinGC94!) -- Improve array element completion for command arguments (#17078) (Thanks @matt9ucci!) -- Use AST extent for `PSScriptRoot` path completion (#17376) -- Add type inference support for generic methods with type parameters (#16951) (Thanks @MartinGC94!) -- Write out OSC indicator only if the `stdout` is not redirected (#17419) -- Remove the assert and use a relatively larger capacity to cover possible increase of .NET reference assemblies (#17423) -- Increase reference assembly count to 161 (#17420) - -### Code Cleanup - -
- - - -

We thank the following contributors!

-

@Yulv-git, @eltociear

- -
- -
    -
  • Fix some typos in source code (#17481) (Thanks @Yulv-git!)
  • -
  • Fix typo in `AsyncResult.cs` (#17396) (Thanks @eltociear!)
  • -
- -
- -### Tools - -- Update script to pin to .NET 7 preview 5 version (#17448) -- Start-PSPester: argument completer for `-Path` (#17334) (Thanks @powercode!) -- Add reminder workflows (#17387) -- Move to configuring the fabric bot via JSON (#17411) -- Update Documentation Issue Template URL (#17410) (Thanks @michaeltlombardi!) -- Update script to automatically take new preview pre-release builds (#17375) - -### Tests - -- Make Assembly Load Native test work on a FX Dependent Linux Install (#17380) -- Update `Get-Error` test to not depend on DNS APIs (#17471) - -### Build and Packaging Improvements - -
- -
    -
  • Update .NET SDK version from 7.0.100-preview.4.22252.9 to 7.0.100-preview.5.22307.18 (#17402)
  • -
  • Downgrade the Microsoft.CodeAnalysis.NetAnalyzers package to 7.0.0-preview1.22217.1 (#17515)
  • -
  • Rename mariner package to cm (#17505)
  • -
  • Bump Microsoft.CodeAnalysis.NetAnalyzers (#17476)
  • -
  • Bump NJsonSchema from 10.7.1 to 10.7.2 (#17475)
  • -
  • Publish preview versions of mariner to preview repo (#17451)
  • -
  • Update to the latest NOTICES file (#17421)
  • -
  • Do not publish package for Mariner 1.0 (#17415)
  • -
  • Add AppX capabilities in MSIX manifest so that PS7 can call the AppX APIs (#17416)
  • -
  • Update to the latest NOTICES file (#17401)
  • -
  • Fix mariner mappings (#17413)
  • -
  • Update the cgmanifest (#17393)
  • -
  • Bump `NJsonSchema` from `10.7.0` to `10.7.1` (#17381)
  • -
- -
- -### Documentation and Help Content - -- Update to the latest NOTICES file (#17493) (Thanks @github-actions[bot]!) -- Update the cgmanifest (#17478) (Thanks @github-actions[bot]!) -- Correct spelling in Comments and tests (#17480) (Thanks @Yulv-git!) -- Fix spelling errors introduced in changelog (#17414) -- Update change log for v7.3.0-preview.4 release (#17412) -- Update readme and metadata for 7.3.0-preview.4 release (#17378) - -[7.3.0-preview.5]: https://github.com/PowerShell/PowerShell/compare/v7.3.0-preview.4...v7.3.0-preview.5 - -## [7.3.0-preview.4] - 2022-05-23 - -### Engine Updates and Fixes - -
    -
  • Remove the use of BinaryFormatter in PSRP serialization (#17133) (Thanks @jborean93!)
  • -
  • Update telemetry collection removing unused data and adding some new data (#17304)
  • -
  • Fix the word wrapping in formatting to handle escape sequences properly (#17316)
  • -
  • Fix the error message in Hashtable-to-object conversion (#17329)
  • -
  • Add support for new WDAC API (#17247)
  • -
  • On Windows, reset cursor visibility back to previous state when rendering progress (#16782)
  • -
  • Fix the list view to not leak VT decorations (#17262)
  • -
  • Fix formatting truncation to handle strings with VT sequences (#17251)
  • -
  • Fix line breakpoints for return statements without a value (#17179)
  • -
  • Fix for partial PowerShell module search paths, that can be resolved to CWD locations (#17231) (Internal 20126)
  • -
  • Change logic in the testing helper module for determining whether PSHOME is writable (#17218)
  • -
  • Make a variable assignment in a ParenExpression to return the variable value (#17174)
  • -
  • Use new Windows signature APIs from Microsoft.Security.Extensions package (#17159)
  • -
  • Do not include node names when sending telemetry. (#16981)
  • -
  • Support forward slashes in network share (UNC path) completion (#17111) (#17117) (Thanks @sba923!)
  • -
  • Do not generate clean block in proxy function when the feature is disabled (#17112)
  • -
  • Ignore failure attempting to set console window title (#16948)
  • -
  • Update regex used to remove ANSI escape sequences to be more specific to decoration and CSI sequences (#16811)
  • -
  • Improve member auto completion (#16504) (Thanks @MartinGC94!)
  • -
  • Prioritize ValidateSet completions over Enums for parameters (#15257) (Thanks @MartinGC94!)
  • -
  • Add Custom Remote Connections Feature (#17011)
  • -
- -### General Cmdlet Updates and Fixes - -
    -
  • Add check for ScriptBlock wrapped in PSObject to $using used in ForEach-Object -Parallel (#17234) (Thanks @ryneandal!)
  • -
  • Fix ForEach method to set property on a scalar object (#17213)
  • -
  • Fix Sort-Object -Stable -Unique to actually do stable sorting (#17189) (Thanks @m1k0net!)
  • -
  • Add OutputType attribute to various commands (#16962) (Thanks @MartinGC94!)
  • -
  • Make Stop-Service only request needed privileges when not setting SDDL. (#16663) (Thanks @kvprasoon!)
  • -
- -### Code Cleanup - -
    -
  • Remove EventLogLogProvider and its related legacy code (#17027)
  • -
  • Fix typos in names of method (#17003) (Thanks @al-cheb!)
  • -
  • SemanticChecks: Avoid repeated type resolution of [ordered] (#17328) (Thanks IISResetMe!)
  • -
  • Redo the change that was reverted by #15853 (#17357)
  • -
  • Correct spelling of pseudo in Compiler.cs (#17285) (Thanks @eltociear!)
  • -
  • MakeNameObscurerTelemetryInitializer internal (#17214)
  • -
  • Make NameObscurerTelemetryInitializer internal (#17167)
  • -
  • Correct Typo in the resource string PathResolvedToMultiple (#17098) (Thanks @charltonstanley!)
  • -
  • Fix typo in ComRuntimeHelpers.cs (#17104) (Thanks @eltociear!)
  • -
- -### Documentation and Help Content - -
    -
  • Update link to PowerShell remoting in depth video (#17166)
  • -
- -### Tests - -
    -
  • Add -because to the failing test to aid in debugging (#17030)
  • -
  • Simplify Enum generator for the -bnot operator test (#17014)
  • -
  • Improve unique naming for tests (#17043)
  • -
  • Use a random string for the missing help topic to improve the chances that the help topic really won't be found. (#17042)
  • -
- -### Build and Packaging Improvements - -
    -
  • Update README.md and metadata.json for v7.3.0-preview.3 release (#17029)
  • -
  • Do not pull dotnet updates from internal feed (#17007)
  • -
  • Simplify Get-WSManSupport based on current .NET Distro Support (#17356)
  • -
  • Update to the latest NOTICES file (#17372, #17332, #17311, #17275)
  • -
  • Run on every PR and let the action skip (#17366)
  • -
  • Make sure verbose message is not null (#17363)
  • -
  • Release changelogs (#17364)
  • -
  • Update build versions (#17318)
  • -
  • Add Daily Link Check GitHub Workflow (#17351)
  • -
  • Update the cgmanifest (#17361, #17344, #17324, #17302, #17268)
  • -
  • Bump NJsonSchema from 10.6.10 to 10.7.0 (#17350)
  • -
  • Disable broken macOS CI job, which is unused (#17221)
  • -
  • Have rebase workflow Post a message when it starts (#17341)
  • -
  • Update DotnetRuntimeMetadata.json for .NET 7 Preview 4 (#17336)
  • -
  • Update Ubuntu 22 to be detected as not supported WSMan (#17338)
  • -
  • Bump xunit.runner.visualstudio from 2.4.3 to 2.4.5 (#17274)
  • -
  • Make sure we execute tests on LTS package for older LTS releases (#17326)
  • -
  • Bump Microsoft.NET.Test.Sdk from 17.1.0 to 17.2.0 (#17320)
  • -
  • Add fedora to the OS's that can't run WSMan (#17325)
  • -
  • Add sles15 support to install-powershell.sh (#16984)
  • -
  • Start rotating through all images (#17315)
  • -
  • Update .NET SDK version from 7.0.100-preview.2.22153.17 to 7.0.100-preview.4.22252.9 (#17061)
  • -
  • Disable release security analysis for SSH CI (#17303)
  • -
  • Add a finalize template which causes jobs with issues to fail (#17314)
  • -
  • Add mapping for ubuntu22.04 jammy (#17317)
  • -
  • Enable more tests to be run in a container. (#17294)
  • -
  • Fix build.psm1 to find the required .NET SDK version when a higher version is installed (#17299)
  • -
  • Improve how Linux container CI builds are identified (#17295)
  • -
  • Only inject NuGet security analysis if we are using secure nuget.config (#17293)
  • -
  • Reduce unneeded verbose message from build.psm1 (#17291)
  • -
  • Switch to using GitHub action to verify markdown links for PRs (#17281)
  • -
  • Put Secure supply chain analysis at correct place (#17273)
  • -
  • Fix build id variable name when selecting CI container (#17279)
  • -
  • Add rotation between the two mariner images (#17277)
  • -
  • Update to use mcr.microsoft.com (#17272)
  • -
  • Update engine working group members (#17271)
  • -
  • Bump PSReadLine from 2.2.2 to 2.2.5 in /src/Modules (#17252)
  • -
  • Update timeout for daily (#17263)
  • -
  • Bump NJsonSchema from 10.6.9 to 10.6.10 (#16902)
  • -
  • Update the cgmanifest (#17260)
  • -
  • Fix Generate checksum file for packages build failure - v7.1.7 (#17219) (Internal 20274)
  • -
  • Move cgmanifest generation to daily (#17258)
  • -
  • Bump Microsoft.CodeAnalysis.NetAnalyzers (#17245)
  • -
  • Update to the latest notice file (#17238)
  • -
  • Add container to Linux CI (#17233)
  • -
  • Mark Microsoft.Management.Infrastructure.Runtime.Win as a developer dependency to hide in notice file (#17230)
  • -
  • Fixing dotnet SDK version parsing in build.psm1 (#17198) (Thanks @powercode!)
  • -
  • Fixed package names verification to support multi-digit versions (#17220)
  • -
  • Bump Microsoft.CodeAnalysis.CSharp from 4.2.0-1.final to 4.2.0-4.final (#17210)
  • -
  • Add backport action (#17212)
  • -
  • Updated change logs for v7.0.9 / v7.0.10 / v7.1.6 / v7.1.7 / v7.2.2 / v7.2.3 (#17207)
  • -
  • Updated metadata.json and README.md for v7.2.3 and v7.0.10 (#17158)
  • -
  • Update package fallback list for ubuntu (from those updated for ubuntu 22.04) (deb) (#17180)
  • -
  • Update wix to include security extensions package (#17171)
  • -
  • Update rebase.yml (#17170)
  • -
  • Adds sha256 digests to RPM packages (#16896) (Thanks @ngharo!)
  • -
  • Make mariner packages Framework dependent (#17151)
  • -
  • Update to the latest notice file (#17169)
  • -
  • Update to the latest notice file (#17146)
  • -
  • Replace . in notices container name (#17154)
  • -
  • Allow multiple installations of dotnet. (#17141)
  • -
  • Bump Microsoft.CodeAnalysis.NetAnalyzers (#17105)
  • -
  • Update to the latest notice file (#16437)
  • -
  • Skip failing scriptblock tests (#17093)
  • -
  • Update dotnet-install script download link (#17086)
  • -
  • Fix the version of the Microsoft.CodeAnalysis.NetAnalyzers package (#17075)
  • -
  • Update dotnetmetadata.json to accept .NET 7 preview 3 builds (#17063)
  • -
  • Re-enable PowerShellGet tests targeting PowerShell gallery (#17062)
  • -
  • Add mariner 1.0 amd64 package (#17057)
  • -
  • Create checksum file for global tools (#17056)
  • -
  • Bump Microsoft.CodeAnalysis.NetAnalyzers (#17065)
  • -
  • Use new cask format (#17064)
  • -
- -[7.3.0-preview.4]: https://github.com/PowerShell/PowerShell/compare/v7.3.0-preview.3...v7.3.0-preview.4 - -## [7.3.0-preview.3] - 2022-03-21 - -### Engine Updates and Fixes - -- Fix the parsing code for .NET method generic arguments (#16937) -- Allow the `PSGetMemberBinder` to get value of `ByRef` property (#16956) -- Allow a collection that contains `Automation.Null` elements to be piped to pipeline (#16957) - -### General Cmdlet Updates and Fixes - -- Add the module `CompatPowerShellGet` to the allow-list of telemetry modules (#16935) -- Fix `Enter-PSHostProcess` and `Get-PSHostProcessInfo` cmdlets by handling processes that have exited (#16946) -- Improve Hashtable completion in multiple scenarios (#16498) (Thanks @MartinGC94!) - -### Code Cleanup - -- Fix a typo in `CommandHelpProvider.cs` (#16949) (Thanks @eltociear!) - -### Tests - -- Update a few tests to make them more stable in CI (#16944) -- Roll back Windows images used in testing to Windows Server 2019 (#16958) - -### Build and Packaging Improvements - -
- - -

Update .NET SDK to 7.0.0-preview.2

-
- -
    -
  • Update .NET to 7.0.0-preview.2 build (#16930)
  • -
  • Update AzureFileCopy task and fix the syntax for specifying pool (#17013)
  • -
- -
- -[7.3.0-preview.3]: https://github.com/PowerShell/PowerShell/compare/v7.3.0-preview.2...v7.3.0-preview.3 - -## [7.3.0-preview.2] - 2022-02-24 - -### Engine Updates and Fixes - -- Fix the `clean` block for generated proxy function (#16827) -- Add support to allow invoking method with generic type arguments (#12412 and #16822) (Thanks @vexx32!) -- Report error when PowerShell built-in modules are missing (#16628) - -### General Cmdlet Updates and Fixes - -- Prevent command completion if the word to complete is a single dash (#16781) (Thanks @ayousuf23!) -- Use `FindFirstFileW` instead of `FindFirstFileExW` to correctly handle Unicode file names on FAT32 (#16840) (Thanks @iSazonov!) -- Add completion for loop labels after Break/Continue (#16438) (Thanks @MartinGC94!) -- Support OpenSSH options for `PSRP` over SSH commands (#12802) (Thanks @BrannenGH!) -- Adds a `.ResolvedTarget` Property to `File-System` Items to Reflect a Symlink's Target as `FileSystemInfo` (#16490) (Thanks @hammy3502!) -- Use `NotifyEndApplication` to re-enable VT mode (#16612) -- Add new parameter to `Start-Sleep`: `[-Duration] ` (#16185) (Thanks @IISResetMe!) -- Add lock and null check to remoting internals (#16542) (#16683) (Thanks @SergeyZalyadeev!) -- Make `Measure-Object` ignore missing properties unless running in strict mode (#16589) (Thanks @KiwiThePoodle!) -- Add `-StrictMode` to `Invoke-Command` to allow specifying strict mode when invoking command locally (#16545) (Thanks @Thomas-Yu!) -- Fix `$PSNativeCommandArgPassing` = `Windows` to handle empty args correctly (#16639) -- Reduce the amount of startup banner text (#16516) (Thanks @rkeithhill!) -- Add `exec` cmdlet for bash compatibility (#16462) -- Add AMSI method invocation logging as experimental feature (#16496) -- Fix web cmdlets so that an empty `Get` does not include a `content-length` header (#16587) -- Update `HelpInfoUri` for 7.3 release (#16646) -- Fix parsing `SemanticVersion` build label from version string (#16608) -- Fix `ForEach-Object -Parallel` when passing in script block variable (#16564) - -### Code Cleanup - -
- - - -

We thank the following contributors!

-

@eltociear, @iSazonov, @xtqqczze

- -
- -
    -
  • Fix typo in PowerShellExecutionHelper.cs (#16776) (Thanks @eltociear!)
  • -
  • Use more efficient platform detection API (#16760) (Thanks @iSazonov!)
  • -
  • Seal ClientRemotePowerShell (#15802) (Thanks @xtqqczze!)
  • -
  • Fix the DSC overview URL in a markdown file and some small cleanup changes (#16629)
  • -
- -
- -### Tools - -- Fix automation to update experimental JSON files in GitHub action (#16837) - -### Tests - -- Update `markdownlint` to the latest version (#16825) -- Bump the package `path-parse` from `1.0.6` to `1.0.7` (#16820) -- Remove assert that is incorrect and affecting our tests (#16588) - -### Build and Packaging Improvements - -
- - - -

We thank the following contributors!

-

@dahlia

- -
- -
    -
  • Update NuGet Testing to not re-install dotnet, -when not needed and dynamically determine the DOTNET_ROOT (Internal 19268, 19269, 19272, 19273, and 19274)
  • -
  • Remove SkipExperimentalFeatureGeneration when building alpine (Internal 19248)
  • -
  • Revert .NET 7 changes, Update to the latest .NET 6 and Update WXS file due to blocking issue in .NET 7 Preview 1
  • -
  • Install and Find AzCopy
  • -
  • Use Start-PSBootStrap for installing .NET during nuget packaging
  • -
  • Fix pool syntax for deployments (Internal 19189)
  • -
  • Bump NJsonSchema from 10.5.2 to 10.6.9 (#16888)
  • -
  • Update projects and scripts to use .NET 7 preview 1 pre-release builds (#16856)
  • -
  • Add warning messages when package precheck fails (#16867)
  • -
  • Refactor Global Tool packaging to include SBOM generation (#16860)
  • -
  • Update to use windows-latest as the build agent image (#16831)
  • -
  • Ensure alpine and arm SKUs have powershell.config.json file with experimental features enabled (#16823)
  • -
  • Update experimental feature json files (#16838) (Thanks @github-actions[bot]!)
  • -
  • Remove WiX install (#16834)
  • -
  • Add experimental json update automation (#16833)
  • -
  • Update .NET SDK to 6.0.101 and fix Microsoft.PowerShell.GlobalTool.Shim.csproj (#16821)
  • -
  • Add SBOM manifest to nuget packages (#16711)
  • -
  • Improve logic for updating .NET in CI (#16808)
  • -
  • Add Linux package dependencies for packaging (#16807)
  • -
  • Switch to our custom images for build and release (#16801)
  • -
  • Remove all references to cmake for the builds in this repo (#16578)
  • -
  • Fix build for new InvokeCommand attributes (#16800)
  • -
  • Let macOS installer run without Rosetta on Apple Silicon (#16742) (Thanks @dahlia!)
  • -
  • Update the expect .NET SDK quality to GA for installing dotnet (#16784)
  • -
  • Change nuget release yaml to use UseDotNet task (#16701)
  • -
  • Bump Microsoft.ApplicationInsights from 2.19.0 to 2.20.0 (#16642)
  • -
  • Register NuGet source when generating CGManifest (#16570)
  • -
  • Update Images used for release (#16580)
  • -
  • Update SBOM generation (#16641)
  • -
  • Bring changes from 7.3.0-preview.1 (#16640)
  • -
  • Update the vmImage and PowerShell root directory for macOS builds (#16611)
  • -
  • Update macOS build image and root folder for build (#16609)
  • -
  • Disabled Yarn cache in markdown.yml (#16599)
  • -
  • Update cgmanifest (#16600)
  • -
  • Fix broken links in markdown (#16598)
  • -
- -
- -### Documentation and Help Content - -- Add newly joined members to their respective Working Groups (#16849) -- Update Engine Working Group members (#16780) -- Replace the broken link about pull request (#16771) -- Update change log to remove a broken URL (#16735) -- Updated `README.md` and `metadata.json` for `v7.3.0-preview.1` release (#16627) -- Updating changelog for `7.2.1` (#16616) -- Updated `README.md` and `metadata.json` for `7.2.1` release (#16586) - -[7.3.0-preview.2]: https://github.com/PowerShell/PowerShell/compare/v7.3.0-preview.1...v7.3.0-preview.2 - -## [7.3.0-preview.1] - 2021-12-16 - -### Breaking Changes - -- Add `clean` block to script block as a peer to `begin`, `process`, and `end` to allow easy resource cleanup (#15177) -- Change default for `$PSStyle.OutputRendering` to `Ansi` (Internal 18449) - -### Engine Updates and Fixes - -- Remove duplicate remote server mediator code (#16027) -- Fix `PSVersion` parameter version checks and error messages for PowerShell 7 remoting (#16228) -- Use the same temporary home directory when `HOME` env variable is not set (#16263) -- Fix parser to generate error when array has more than 32 dimensions (#16276) - -### Performance - -- Avoid validation for built-in file extension and color VT sequences (#16320) (Thanks @iSazonov!) - -### General Cmdlet Updates and Fixes - -- Update `README.md` and `metadata.json` for next preview release (#16107) -- Use `PlainText` when writing to a host that doesn't support VT (#16092) -- Remove support for `AppExeCLinks` to retrieve target (#16044) -- Move `GetOuputString()` and `GetFormatStyleString()` to `PSHostUserInterface` as public API (#16075) -- Fix `ConvertTo-SecureString` with key regression due to .NET breaking change (#16068) -- Fix regression in `Move-Item` to only fallback to `copy and delete` in specific cases (#16029) -- Set `$?` correctly for command expression with redirections (#16046) -- Use `CurrentCulture` when handling conversions to `DateTime` in `Add-History` (#16005) (Thanks @vexx32!) -- Fix link header parsing to handle unquoted `rel` types (#15973) (Thanks @StevenLiekens!) -- Fix a casting error when using `$PSNativeCommandUsesErrorActionPreference` (#15993) -- Format-Wide: Fix `NullReferenceException` (#15990) (Thanks @DarylGraves!) -- Make the native command error handling optionally honor `ErrorActionPreference` (#15897) -- Remove declaration of experimental features in Utility module manifest as they are stable (#16460) -- Fix race condition between `DisconnectAsync` and `Dispose` (#16536) (Thanks @i3arnon!) -- Fix the `Max_PATH` condition check to handle long path correctly (#16487) (Thanks @Shriram0908!) -- Update `HelpInfoUri` for 7.2 release (#16456) -- Fix tab completion within the script block specified for the `ValidateScriptAttribute`. (#14550) (Thanks @MartinGC94!) -- Update `README.md` to specify gathered telemetry (#16379) -- Fix typo for "privacy" in MSI installer (#16407) -- Remove unneeded call to `File.ResolveLinkTarget` from `IsWindowsApplication` (#16371) (Thanks @iSazonov!) -- Add `-HttpVersion` parameter to web cmdlets (#15853) (Thanks @hayhay27!) -- Add support to web cmdlets for open-ended input tags (#16193) (Thanks @farmerau!) -- Add more tests to `Tee-Object -Encoding` (#14539) (Thanks @rpolley!) -- Don't throw exception when trying to resolve a possible link path (#16310) -- Fix `ConvertTo-Json -Depth` to allow 100 at maximum (#16197) (Thanks @KevRitchie!) -- Fix for SSH remoting when banner is enabled on SSHD endpoint (#16205) -- Disallow all COM for AppLocker system lock down (#16268) -- Configure `ApplicationInsights` to not send cloud role name (#16246) -- Disallow `Add-Type` in NoLanguage mode on a locked down machine (#16245) -- Specify the executable path as `TargetObect` for non-zero exit code `ErrorRecord` (#16108) (Thanks @rkeithhill!) -- Don't allow `Move-Item` with FileSystemProvider to move a directory into itself (#16198) -- Make property names for the color VT sequences consistent with documentations (#16212) -- Fix `PipelineVariable` to set variable in the right scope (#16199) -- Invoke-Command: improve handling of variables with $using: expression (#16113) (Thanks @dwtaber!) -- Change `Target` from a `CodeProperty` to be an `AliasProperty` that points to `FileSystemInfo.LinkTarget` (#16165) - -### Code Cleanup - -
- - - -

We thank the following contributors!

-

@xtqqczze, @eltociear, @iSazonov

- -
- -
    -
  • Improve CommandInvocationIntrinsics API documentation and style (#14369)
  • -
  • Use bool?.GetValueOrDefault() in FormatWideCommand (#15988) (Thanks @xtqqczze!)
  • -
  • Remove 4 assertions which cause debug build test runs to fail (#15963)
  • -
  • Fix typo in `Job.cs` (#16454) (Thanks @eltociear!)
  • -
  • Remove unnecessary call to `ToArray` (#16307) (Thanks @iSazonov!)
  • -
  • Remove the unused `FollowSymLink` function (#16231)
  • -
  • Fix typo in `TypeTable.cs` (#16220) (Thanks @eltociear!)
  • -
  • Fixes #16176 - replace snippet tag with code tag in comments (#16177)
  • -
- -
- -### Tools - -- Fix typo in build.psm1 (#16038) (Thanks @eltociear!) -- Add `.stylecop` to `filetypexml` and format it (#16025) -- Enable sending Teams notification when workflow fails (#15982) -- Use `Convert-Path` for unknown drive in `Build.psm1` (#16416) (Thanks @matt9ucci!) - -### Tests - -- Add benchmark to test compiler performance (#16083) -- Enable two previously disabled `Get-Process` tests (#15845) (Thanks @iSazonov!) -- Set clean state before testing `UseMU` in the MSI (#16543) -- Fix global tool and SDK tests in release pipeline (#16342) -- Remove the outdated test (#16269) -- Removed old not-used-anymore docker-based tests for PS release packages (#16224) - -### Build and Packaging Improvements - -
- - - -

We thank the following contributors!

-

@github-actions[bot], @kondratyev-nv

- -
- -
    -
  • fix issue with hash file getting created before we have finished get-childitem (#16170)
  • -
  • Add sha256 hashes to release (#16147)
  • -
  • Change path for Component Governance for build to the path we actually use to build (#16137)
  • -
  • Update Microsoft.CodeAnalysis.CSharp version (#16138)
  • -
  • Bump Microsoft.CodeAnalysis.NetAnalyzers (#16070)
  • -
  • Update .NET to 6.0.100-rc.1.21458.32 (#16066)
  • -
  • Update minimum required OS version for macOS (#16088)
  • -
  • Set locale correctly on Linux CI (#16073)
  • -
  • Ensure locale is set correctly on Ubuntu 20.04 in CI (#16067)
  • -
  • Bump Microsoft.CodeAnalysis.NetAnalyzers (#16045)
  • -
  • Update .NET SDK version from `6.0.100-rc.1.21430.44` to `6.0.100-rc.1.21455.2` (#16041) (Thanks @github-actions[bot]!)
  • -
  • Fix the GitHub Action for updating .NET daily builds (#16042)
  • -
  • Bump Microsoft.CodeAnalysis.CSharp from 4.0.0-3.final to 4.0.0-4.21430.4 (#16036)
  • -
  • Bump .NET to `6.0.100-rc.1.21430.44` (#16028)
  • -
  • Move from PkgES hosted agents to 1ES hosted agents (#16023)
  • -
  • Bump Microsoft.CodeAnalysis.NetAnalyzers (#16021)
  • -
  • Update Ubuntu images to use Ubuntu 20.04 (#15906)
  • -
  • Fix the mac build by updating the pool image name (#16010)
  • -
  • Use Alpine 3.12 for building PowerShell for alpine (#16008)
  • -
  • Update .NET SDK version from `6.0.100-preview.6.21355.2` to `6.0.100-rc.1.21426.1` (#15648) (Thanks @github-actions[bot]!)
  • -
  • Ignore error from Find-Package (#15999)
  • -
  • Find packages separately for each source in UpdateDotnetRuntime.ps1 script (#15998)
  • -
  • Update metadata to start using .NET 6 RC1 builds (#15981)
  • -
  • Bump Microsoft.CodeAnalysis.NetAnalyzers (#15985)
  • -
  • Merge the v7.2.0-preview.9 release branch back to GitHub master (#15983)
  • -
  • Publish global tool package for stable releases (#15961)
  • -
  • Bump Microsoft.CodeAnalysis.NetAnalyzers to newer version (#15962)
  • -
  • Disabled Yarn cache in markdown.yml (#16599)
  • -
  • Update cgmanifest (#16600)
  • -
  • Fix broken links in markdown (#16598)
  • -
  • Add explicit job name for approval tasks in Snap stage (#16579)
  • -
  • Bring back pwsh.exe for framework dependent packages to support Start-Job (#16535)
  • -
  • Fix NuGet package generation in release build (#16509)
  • -
  • Add `Microsoft.PowerShell.Commands.SetStrictModeCommand.ArgumentToPSVersionTransformationAttribute` to list of patterns to remove for generated ref assembly (#16489)
  • -
  • Bump Microsoft.CodeAnalysis.CSharp from `4.0.0-6.final` to `4.0.1` (#16423)
  • -
  • use different containers for different branches (#16434)
  • -
  • Add import so we can use common GitHub workflow function. (#16433)
  • -
  • Remove pre-release .NET 6 build sources (#16418)
  • -
  • Update release instructions with link to new build (#16419)
  • -
  • Bump Microsoft.ApplicationInsights from 2.18.0 to 2.19.0 (#16413)
  • -
  • Update metadata.json to make 7.2.0 the latest LTS (#16417)
  • -
  • Make static CI a matrix (#16397)
  • -
  • Update metadata.json in preparation on 7.3.0-preview.1 release (#16406)
  • -
  • Update cgmanifest (#16405)
  • -
  • Add diagnostics used to take corrective action when releasing `buildInfoJson` (#16404)
  • -
  • `vPack` release should use `buildInfoJson` new to 7.2 (#16402)
  • -
  • Update the usage of metadata.json for getting LTS information (#16381)
  • -
  • Add checkout to build json stage to get `ci.psm1` (#16399)
  • -
  • Update CgManifest.json for 6.0.0 .NET packages (#16398)
  • -
  • Add current folder to the beginning of the module import (#16353)
  • -
  • Increment RC MSI build number by 100 (#16354)
  • -
  • Bump XunitXml.TestLogger from 3.0.66 to 3.0.70 (#16356)
  • -
  • Move PR Quantifier config to subfolder (#16352)
  • -
  • Release build info json when it is preview (#16335)
  • -
  • Add an approval for releasing build-info json (#16351)
  • -
  • Generate manifest with latest public version of the packages (#16337)
  • -
  • Update to the latest notices file (#16339) (Thanks @github-actions[bot]!)
  • -
  • Use notice task to generate license assuming cgmanifest contains all components (#16340)
  • -
  • Refactor cgmanifest generator to include all components (#16326)
  • -
  • Fix issues in release build (#16332)
  • -
  • Update feed and analyzer dependency (#16327)
  • -
  • Bump Microsoft.NET.Test.Sdk from 16.11.0 to 17.0.0 (#16312)
  • -
  • Update license and cgmanifest (#16325) (Thanks @github-actions[bot]!)
  • -
  • Fix condition in cgmanifest logic (#16324)
  • -
  • Add GitHub Workflow to keep notices up to date (#16284)
  • -
  • Update to latest .NET 6 GA build 6.0.100-rtm.21527.11 (#16309)
  • -
  • Create compliance build (#16286)
  • -
  • Move mapping file into product repo and add Debian 11 (#16316)
  • -
  • Add a major-minor build info JSON file (#16301)
  • -
  • Clean up crossgen related build scripts also generate native symbols for R2R images (#16297)
  • -
  • Fix Windows build ZIP packaging (#16299) (Thanks @kondratyev-nv!)
  • -
  • Revert "Update to use .NET 6 GA build (#16296)" (#16308)
  • -
  • Add wget as a dependency for Bootstrap script (#16303) (Thanks @kondratyev-nv!)
  • -
  • Fix issues reported by code signing verification tool (#16291)
  • -
  • Update to use .NET 6 GA build (#16296)
  • -
  • Revert "add GH workflow to keep the cgmanifest up to date." (#16294)
  • -
  • Update ChangeLog for 7.2.0-rc.1 and also fix RPM packaging (#16290)
  • -
  • Bump Microsoft.CodeAnalysis.NetAnalyzers (#16271)
  • -
  • add GH workflow to keep the cgmanifest up to date.
  • -
  • Update ThirdPartyNotices.txt (#16283)
  • -
  • Update `testartifacts.yml` to use ubuntu-latest image (#16279)
  • -
  • Update version of Microsoft.PowerShell.Native and Microsoft.PowerShell.MarkdownRender packages (#16277)
  • -
  • Add script to generate cgmanifest.json (#16278)
  • -
  • Add cgmanifest.json for generating correct third party notice file (#16266)
  • -
  • Bump Microsoft.CodeAnalysis.NetAnalyzers from `6.0.0-rtm.21504.2` to `6.0.0-rtm.21516.1` (#16264)
  • -
  • Only upload stable buildinfo for stable releases (#16251)
  • -
  • Make RPM license recognized (#16189)
  • -
  • Don't upload dep or tar.gz for RPM because there are none. (#16230)
  • -
  • Add condition to generate release files in local dev build only (#16259)
  • -
  • Update .NET 6 to version 6.0.100-rc.2.21505.57 (#16249)
  • -
  • change order of try-catch-finally and split out arm runs (#16252)
  • -
  • Ensure psoptions.json and manifest.spdx.json files always exist in packages (#16258)
  • -
  • Update to vPack task version to 12 (#16250)
  • -
  • Remove unneeded `NuGetConfigFile` resource string (#16232)
  • -
  • Add Software Bill of Materials to the main packages (#16202)
  • -
  • Sign third party exes (#16229)
  • -
  • Upgrade set-value package for markdown test (#16196)
  • -
  • Use Ubuntu 20.04 for SSH remoting test (#16225)
  • -
  • Bump Microsoft.CodeAnalysis.NetAnalyzers (#16194)
  • -
  • Bump `Microsoft.CodeAnalysis.NetAnalyzers` from `6.0.0-rc2.21458.5` to `6.0.0-rtm.21480.8` (#16183)
  • -
  • Move vPack build to 1ES Pool (#16169)
  • -
  • Fix Microsoft update spelling issue. (#16178)
  • -
- -
- -### Documentation and Help Content - -- Update Windows PowerShell issues link (#16105) (Thanks @andschwa!) -- Remove Joey from Committee and WG membership (#16119) -- Update more docs for `net6.0` TFM (#16102) (Thanks @xtqqczze!) -- Change `snippet` tag to `code` tag in XML comments (#16106) -- Update build documentation to reflect .NET 6 (#15751) (Thanks @Kellen-Stuart!) -- Update `README.md` about the change logs (#16471) (Thanks @powershellpr0mpt!) -- Update change log for 7.2.0 (#16401) -- Update `metadata.json` and `README.md` for 7.2.0 release (#16395) -- Update `README.md` and `metadata.json` files for `v7.2.0-rc.1` release (#16285) -- Update the change logs for `v7.0.8` and `v7.1.5` releases (#16248) - -[7.3.0-preview.1]: https://github.com/PowerShell/PowerShell/compare/v7.2.0-preview.10...v7.3.0-preview.1 From 58f2b2c8d0196e06fe7260c88384a5741e02a73e Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Wed, 9 Nov 2022 13:55:35 -0800 Subject: [PATCH 181/779] Update to azCopy 10 (#18509) --- build.psm1 | 10 ++++---- .../azureDevOps/releasePipeline.yml | 1 + .../templates/release-CreateGitHubDraft.yml | 22 ++++++++++++++---- .../templates/release-MsixBundle.yml | 23 ++++++++----------- .../azureDevOps/templates/vpackReleaseJob.yml | 13 +++++++++-- 5 files changed, 45 insertions(+), 24 deletions(-) diff --git a/build.psm1 b/build.psm1 index 713ce06f364..ae9938a3f47 100644 --- a/build.psm1 +++ b/build.psm1 @@ -3341,13 +3341,15 @@ function Install-AzCopy { return } - $destination = "$env:TEMP\azcopy81.msi" - Invoke-WebRequest "https://aka.ms/downloadazcopy" -OutFile $destination - Start-Process -FilePath $destination -ArgumentList "/quiet" -Wait + $destination = "$env:TEMP\azcopy10.zip" + $downloadLocation = (Invoke-WebRequest -Uri https://aka.ms/downloadazcopy-v10-windows -MaximumRedirection 0 -ErrorAction SilentlyContinue -SkipHttpErrorCheck).headers.location | Select-Object -First 1 + + Invoke-WebRequest -Uri $downloadLocation -OutFile $destination -Verbose + Expand-archive -Path $destination -Destinationpath '$(Agent.ToolsDirectory)\azcopy10' } function Find-AzCopy { - $searchPaths = "C:\Program Files (x86)\Microsoft SDKs\Azure\AzCopy\AzCopy.exe" + $searchPaths = @('$(Agent.ToolsDirectory)\azcopy10\AzCopy.exe', "C:\Program Files (x86)\Microsoft SDKs\Azure\AzCopy\AzCopy.exe", "C:\azcopy10\AzCopy.exe") foreach ($filter in $searchPaths) { $azCopy = Get-ChildItem -Path $filter -Recurse -ErrorAction SilentlyContinue | Select-Object -ExpandProperty FullName -First 1 diff --git a/tools/releaseBuild/azureDevOps/releasePipeline.yml b/tools/releaseBuild/azureDevOps/releasePipeline.yml index 39e0902f026..b0a3d6f52e6 100644 --- a/tools/releaseBuild/azureDevOps/releasePipeline.yml +++ b/tools/releaseBuild/azureDevOps/releasePipeline.yml @@ -283,6 +283,7 @@ stages: variables: - group: 'Azure Blob variable group' - group: 'AzDevOpsArtifacts' + - group: ReleasePipelineSecrets dependsOn: AzureBlobPublic steps: - template: templates/release-CreateGitHubDraft.yml diff --git a/tools/releaseBuild/azureDevOps/templates/release-CreateGitHubDraft.yml b/tools/releaseBuild/azureDevOps/templates/release-CreateGitHubDraft.yml index 6eed7fbfd9c..dc7cf126630 100644 --- a/tools/releaseBuild/azureDevOps/templates/release-CreateGitHubDraft.yml +++ b/tools/releaseBuild/azureDevOps/templates/release-CreateGitHubDraft.yml @@ -10,15 +10,27 @@ steps: Import-module '$(BUILD.SOURCESDIRECTORY)/build.psm1' Install-AzCopy displayName: Install AzCopy + retryCountOnTaskFailure: 2 - pwsh: | Import-module '$(BUILD.SOURCESDIRECTORY)/build.psm1' $azcopy = Find-AzCopy - & $azcopy /Source:https://$(StorageAccount).blob.core.windows.net/$(AzureVersion) /Dest:$(System.ArtifactsDirectory) /S /SourceKey:$(StorageAccountKey) + Write-Verbose -Verbose "Found AzCopy: $azcopy" + + & $azcopy login --service-principal --application-id $(PowerShellReleaseSPN) + & $azcopy cp https://$(StorageAccount).blob.core.windows.net/$(AzureVersion) $(System.ArtifactsDirectory) --recursive + + $packagesPath = Get-ChildItem -Path $(System.ArtifactsDirectory)\*.deb -Recurse -File | Select-Object -First 1 -ExpandProperty DirectoryName + Write-Host "sending -- vso[task.setvariable variable=PackagesRoot]$packagesPath" + Write-Host "##vso[task.setvariable variable=PackagesRoot]$packagesPath" + displayName: Download Azure Artifacts + retryCountOnTaskFailure: 2 + env: + AZCOPY_SPA_CLIENT_SECRET: $(PowerShellReleaseSPNSecret) - pwsh: | - Get-ChildItem $(System.ArtifactsDirectory)\* -recurse | Select-Object -ExpandProperty Name + Get-ChildItem $(System.ArtifactsDirectory)\* -recurse | Select-Object -ExpandProperty FullName displayName: Capture downloaded artifacts - pwsh: | @@ -26,10 +38,10 @@ steps: displayName: Clone Internal-Tools repository - pwsh: | - $Path = "$(System.ArtifactsDirectory)" + $Path = "$(PackagesRoot)" $OutputPath = Join-Path $Path ‘hashes.sha256’ $srcPaths = @($Path) - $packages = Get-ChildItem -Path $srcPaths -Include * -Recurse + $packages = Get-ChildItem -Path $srcPaths -Include * -Recurse -File $checksums = $packages | ForEach-Object { Write-Verbose -Verbose "Generating checksum file for $($_.FullName)" @@ -77,5 +89,5 @@ steps: Write-Verbose -Verbose "Selected content: `n$clContent" - Publish-ReleaseDraft -Tag '$(ReleaseTag)' -Name '$(ReleaseTag) Release of PowerShell' -Description $clContent -User PowerShell -Repository PowerShell -PackageFolder $(System.ArtifactsDirectory) -Token $(GitHubReleasePat) + Publish-ReleaseDraft -Tag '$(ReleaseTag)' -Name '$(ReleaseTag) Release of PowerShell' -Description $clContent -User PowerShell -Repository PowerShell -PackageFolder $(PackagesRoot) -Token $(GitHubReleasePat) displayName: Publish Release Draft diff --git a/tools/releaseBuild/azureDevOps/templates/release-MsixBundle.yml b/tools/releaseBuild/azureDevOps/templates/release-MsixBundle.yml index c883bc0ff0b..6f3957d0815 100644 --- a/tools/releaseBuild/azureDevOps/templates/release-MsixBundle.yml +++ b/tools/releaseBuild/azureDevOps/templates/release-MsixBundle.yml @@ -65,16 +65,13 @@ jobs: Write-Host "##$vstsCommandString" displayName: Create MsixBundle - - pwsh: | - Import-module '$(BUILD.SOURCESDIRECTORY)/build.psm1' - Install-AzCopy - displayName: Install AzCopy - - - pwsh: | - ## We use AzCopy v8.1 in our release pipeline, see the documentation at: - ## https://docs.microsoft.com/en-us/previous-versions/azure/storage/storage-use-azcopy - - Import-module '$(BUILD.SOURCESDIRECTORY)/build.psm1' - $azcopy = Find-AzCopy - & $azcopy /Source:$(BundleDir) /Dest:https://$(StorageAccount).blob.core.windows.net/$(AzureVersion)-private /DestKey:$(StorageAccountKey) /Pattern:*.msixbundle /Y - displayName: Upload MSIX Bundle package to Az Blob + - task: AzureFileCopy@4 + displayName: 'Upload MSIX Bundle package to Az Blob' + inputs: + SourcePath: '$(BundleDir)/*.msixbundle' + azureSubscription: '$(AzureFileCopySubscription)' + Destination: AzureBlob + storage: '$(StorageAccount)' + ContainerName: '$(AzureVersion)-private' + resourceGroup: '$(StorageResourceGroup)' + condition: succeeded() diff --git a/tools/releaseBuild/azureDevOps/templates/vpackReleaseJob.yml b/tools/releaseBuild/azureDevOps/templates/vpackReleaseJob.yml index a51818e4acb..3e58295ad8f 100644 --- a/tools/releaseBuild/azureDevOps/templates/vpackReleaseJob.yml +++ b/tools/releaseBuild/azureDevOps/templates/vpackReleaseJob.yml @@ -5,6 +5,7 @@ jobs: - job: vpack_${{ parameters.architecture }} variables: - group: vPack + - group: ReleasePipelineSecrets displayName: Build and Publish VPack - ${{ parameters.architecture }} condition: succeeded() @@ -31,14 +32,22 @@ jobs: Import-module '$(BUILD.SOURCESDIRECTORY)/build.psm1' Install-AzCopy displayName: Install AzCopy + retryCountOnTaskFailure: 2 - pwsh: | Import-module '$(BUILD.SOURCESDIRECTORY)/build.psm1' $azcopy = Find-AzCopy + Write-Verbose -Verbose "Found AzCopy: $azcopy" - Write-Host "running: $azcopy /Source:https://$(StorageAccount).blob.core.windows.net/$(AzureVersion) /Dest:$(System.ArtifactsDirectory) /S /SourceKey:****** /Pattern:PowerShell-$(Version)-win-${{ parameters.architecture }}.zip /Z:$(AGENT.TEMPDIRECTORY)" - & $azcopy /Source:https://$(StorageAccount).blob.core.windows.net/$(AzureVersion) /Dest:$(System.ArtifactsDirectory) /S /SourceKey:$(StorageAccountKey) /Pattern:PowerShell-$(Version)-win-${{ parameters.architecture }}.zip /Z:$(AGENT.TEMPDIRECTORY) + & $azcopy login --service-principal --application-id $(PowerShellReleaseSPN) + + Write-Host "running: $azcopy cp https://$(StorageAccount).blob.core.windows.net/$(AzureVersion)/PowerShell-$(Version)-win-${{ parameters.architecture }}.zip $(System.ArtifactsDirectory)" + + & $azcopy cp https://$(StorageAccount).blob.core.windows.net/$(AzureVersion)/PowerShell-$(Version)-win-${{ parameters.architecture }}.zip $(System.ArtifactsDirectory) displayName: 'Download Azure Artifacts' + retryCountOnTaskFailure: 2 + env: + AZCOPY_SPA_CLIENT_SECRET: $(PowerShellReleaseSPNSecret) - pwsh: 'Get-ChildItem $(System.ArtifactsDirectory)\* -recurse | Select-Object -ExpandProperty Name' displayName: 'Capture Artifact Listing' From 00a51d4a112b65544db27bc7e851405df3158182 Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Wed, 9 Nov 2022 13:56:12 -0800 Subject: [PATCH 182/779] Merged PR 23139: Add test for framework dependent package in release pipeline (#18506) --- build.psm1 | 14 +++++++- .../azureDevOps/releasePipeline.yml | 8 +++++ .../templates/release-ValidateFxdPackage.yml | 36 +++++++++++++++++-- .../release-ValidatePackageNames.yml | 13 +++---- .../azureDevOps/templates/signBuildFiles.yml | 8 +++++ 5 files changed, 69 insertions(+), 10 deletions(-) diff --git a/build.psm1 b/build.psm1 index ae9938a3f47..73036bf9ce7 100644 --- a/build.psm1 +++ b/build.psm1 @@ -2361,7 +2361,11 @@ function Start-ResGen } } -function Find-Dotnet() { +function Find-Dotnet { + param ( + [switch] $SetDotnetRoot + ) + Write-Verbose "In Find-DotNet" $originalPath = $env:PATH @@ -2388,6 +2392,14 @@ function Find-Dotnet() { Write-Warning "The 'dotnet' in the current path can't find SDK version ${dotnetCLIRequiredVersion}, prepending $dotnetPath to PATH." # Globally installed dotnet doesn't have the required SDK version, prepend the user local dotnet location $env:PATH = $dotnetPath + [IO.Path]::PathSeparator + $env:PATH + + if ($SetDotnetRoot) { + Write-Verbose -Verbose "Setting DOTNET_ROOT to $dotnetPath" + $env:DOTNET_ROOT = $dotnetPath + } + } elseif ($SetDotnetRoot) { + Write-Verbose -Verbose "Expected dotnet version found, setting DOTNET_ROOT to $dotnetPath" + $env:DOTNET_ROOT = $dotnetPath } } else { diff --git a/tools/releaseBuild/azureDevOps/releasePipeline.yml b/tools/releaseBuild/azureDevOps/releasePipeline.yml index b0a3d6f52e6..05b86ff3d20 100644 --- a/tools/releaseBuild/azureDevOps/releasePipeline.yml +++ b/tools/releaseBuild/azureDevOps/releasePipeline.yml @@ -113,6 +113,14 @@ stages: imageName: ubuntu-latest packageNamePattern: '**/*fxdependent.tar.gz' + - template: templates/release-ValidateFxdPackage.yml + parameters: + jobName: FxdPackageLinuxonARM + displayName: Fxd Package Test Linux ARM64 + imageName: 'PSMMSUbuntu20.04-ARM64-secure' + packageNamePattern: '**/*fxdependent.tar.gz' + use1ES: true + - stage: StaticPkgValidation dependsOn: [] displayName: Static package validation diff --git a/tools/releaseBuild/azureDevOps/templates/release-ValidateFxdPackage.yml b/tools/releaseBuild/azureDevOps/templates/release-ValidateFxdPackage.yml index a4d473cf3b8..6843cf2a2dd 100644 --- a/tools/releaseBuild/azureDevOps/templates/release-ValidateFxdPackage.yml +++ b/tools/releaseBuild/azureDevOps/templates/release-ValidateFxdPackage.yml @@ -3,13 +3,18 @@ parameters: displayName: "" imageName: "" packageNamePattern: "" + use1ES: false jobs: - job: ${{ parameters.jobName }} displayName: ${{ parameters.displayName }} + variables: + - group: DotNetPrivateBuildAccess pool: - # testing - vmImage: ${{ parameters.imageName }} + ${{ if eq(parameters.use1ES, 'false') }}: + vmImage: ${{ parameters.imageName }} + ${{ else }}: + name: 'PS-MSCodeHub-ARM' # add ImageOverride to select image steps: - checkout: self clean: true @@ -26,6 +31,16 @@ jobs: patterns: '${{ parameters.packageNamePattern }}' path: '$(Pipeline.Workspace)/releasePipeline/finalResults' + - pwsh: | + $env:DOTNET_SKIP_FIRST_TIME_EXPERIENCE=1 + Import-Module "$(Build.SourcesDirectory)/build.psm1" -Force + Start-PSBootstrap + Write-Verbose -Message "Installing .NET SDK completed." -Verbose + displayName: Install .NET + env: + __DONET_RUNTIME_FEED: $(RUNTIME_SOURCEFEED) + __DONET_RUNTIME_FEED_KEY: $(RUNTIME_SOURCEFEED_KEY) + - pwsh: | Get-ChildItem -Path '$(Pipeline.Workspace)/releasePipeline/finalResults' -Recurse displayName: Capture downloaded package @@ -53,9 +68,24 @@ jobs: displayName: Expand fxd package - pwsh: | + $env:DOTNET_SKIP_FIRST_TIME_EXPERIENCE=1 + Import-Module "$(Build.SourcesDirectory)/build.psm1" -Force + Find-Dotnet -SetDotnetRoot + Write-Verbose -Verbose "DOTNET_ROOT: $env:DOTNET_ROOT" + Write-Verbose -Verbose "Check dotnet install" + dotnet --info + Write-Verbose -Verbose "Start test" $packageNameFilter = '${{ parameters.packageNamePattern }}' $pwshExeName = if ($packageNameFilter.EndsWith('tar.gz')) { 'pwsh' } else { 'pwsh.exe' } - $actualOutput = & $pwshExeName -c 'Start-Job -ScriptBlock { "1" } | Wait-Job | Receive-Job' + $pwshPath = Join-Path '$(Pipeline.Workspace)/releasePipeline/finalResults/fxd' $pwshExeName + + if ($IsLinux) { + chmod u+x $pwshPath + } + + $pwshDllPath = Join-Path '$(Pipeline.Workspace)/releasePipeline/finalResults/fxd' 'pwsh.dll' + + $actualOutput = & dotnet $pwshDllPath -c 'Start-ThreadJob -ScriptBlock { "1" } | Wait-Job | Receive-Job' Write-Verbose -Verbose "Actual output: $actualOutput" if ($actualOutput -ne 1) { throw "Actual output is not as expected" diff --git a/tools/releaseBuild/azureDevOps/templates/release-ValidatePackageNames.yml b/tools/releaseBuild/azureDevOps/templates/release-ValidatePackageNames.yml index c6925ba8a0e..8a95ab82015 100644 --- a/tools/releaseBuild/azureDevOps/templates/release-ValidatePackageNames.yml +++ b/tools/releaseBuild/azureDevOps/templates/release-ValidatePackageNames.yml @@ -11,17 +11,18 @@ steps: Write-Host "##vso[build.updatebuildnumber]$name" displayName: Set Release Name -- pwsh: | - Import-module '$(BUILD.SOURCESDIRECTORY)/build.psm1' - Install-AzCopy - displayName: Install AzCopy - - pwsh: | Import-module '$(BUILD.SOURCESDIRECTORY)/build.psm1' $azcopy = Find-AzCopy + Write-Verbose -Verbose "Found AzCopy: $azcopy" + + & $azcopy login --service-principal --application-id $(PowerShellReleaseSPN) + + & $azcopy cp https://$(StorageAccount).blob.core.windows.net/$(AzureVersion)/* $(System.ArtifactsDirectory) --recursive - & $azcopy /Source:https://$(StorageAccount).blob.core.windows.net/$(AzureVersion) /Dest:$(System.ArtifactsDirectory) /S /SourceKey:$(StorageAccountKey) displayName: Download Azure Artifacts + env: + AZCOPY_SPA_CLIENT_SECRET: $(PowerShellReleaseSPNSecret) - pwsh: | Get-ChildItem $(System.ArtifactsDirectory)\* -recurse | Select-Object -ExpandProperty Name diff --git a/tools/releaseBuild/azureDevOps/templates/signBuildFiles.yml b/tools/releaseBuild/azureDevOps/templates/signBuildFiles.yml index e628f2ca81d..8e4d86e3b51 100644 --- a/tools/releaseBuild/azureDevOps/templates/signBuildFiles.yml +++ b/tools/releaseBuild/azureDevOps/templates/signBuildFiles.yml @@ -113,9 +113,17 @@ steps: Write-Verbose -verbose "to be signed:`r`n $($missingSignatures | Out-String)" $filesToSignDirectory = "$(System.ArtifactsDirectory)\thirdPartyToBeSigned" + if (Test-Path $filesToSignDirectory) { + Remove-Item -Path $filesToSignDirectory -Recurse -Force + } + $null = New-Item -ItemType Directory -Path $filesToSignDirectory -Force -Verbose $signedFilesDirectory = "$(System.ArtifactsDirectory)\thirdPartySigned" + if (Test-Path $signedFilesDirectory) { + Remove-Item -Path $signedFilesDirectory -Recurse -Force + } + $null = New-Item -ItemType Directory -Path $signedFilesDirectory -Force -Verbose $missingSignatures | ForEach-Object { From 1ae9faddb8e5862e26ab2af3ffff1999859b18a8 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Wed, 9 Nov 2022 14:23:09 -0800 Subject: [PATCH 183/779] Update the cgmanifest (#18415) Co-authored-by: adityapatwardhan --- tools/cgmanifest.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tools/cgmanifest.json b/tools/cgmanifest.json index 30a149dfd26..779714a2255 100644 --- a/tools/cgmanifest.json +++ b/tools/cgmanifest.json @@ -1,4 +1,5 @@ { + "$schema": "https://json.schemastore.org/component-detection-manifest.json", "Registrations": [ { "Component": { @@ -175,7 +176,7 @@ "Type": "nuget", "Nuget": { "Name": "Microsoft.PowerShell.Native", - "Version": "7.2.0" + "Version": "7.3.0" } }, "DevelopmentDependency": false @@ -1400,6 +1401,5 @@ }, "DevelopmentDependency": false } - ], - "$schema": "https://json.schemastore.org/component-detection-manifest.json" + ] } From fe76300a5fb1151535804af4d7a9070925c1f59a Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Wed, 9 Nov 2022 14:27:13 -0800 Subject: [PATCH 184/779] Update security reporting policy to recommend security portal for more streamlined reporting (#18437) --- .github/SECURITY.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/SECURITY.md b/.github/SECURITY.md index 10633f0d6d1..6241b2c57b5 100644 --- a/.github/SECURITY.md +++ b/.github/SECURITY.md @@ -8,5 +8,5 @@ change, but PowerShell must be secure by default. ## Reporting a security vulnerability If you believe that there is a security vulnerability in PowerShell, -it **must** be reported to [secure@microsoft.com](https://technet.microsoft.com/security/ff852094.aspx) to allow for [Coordinated Vulnerability Disclosure](https://technet.microsoft.com/security/dn467923). -**Only** file an issue, if [secure@microsoft.com](https://www.microsoft.com/en-us/msrc/faqs-report-an-issue?rtc=1) has confirmed filing an issue is appropriate. +it **must** be reported using [https://aka.ms/secure-at](https://aka.ms/secure-at) to allow for [Coordinated Vulnerability Disclosure](https://technet.microsoft.com/security/dn467923). +**Only** file an issue, if [MSRC](https://www.microsoft.com/en-us/msrc/faqs-report-an-issue?rtc=1) has confirmed filing an issue is appropriate. From 67135b47d7e148ea5c96a881d6564339214acaa1 Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Wed, 9 Nov 2022 14:37:13 -0800 Subject: [PATCH 185/779] Insert the pre-release nuget feed before building test artifacts (#18507) --- build.psm1 | 11 ++++++++++- .../azureDevOps/templates/testartifacts.yml | 5 +++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/build.psm1 b/build.psm1 index 73036bf9ce7..ca1a87c41ef 100644 --- a/build.psm1 +++ b/build.psm1 @@ -1140,7 +1140,16 @@ function Publish-PSTestTools { $runtime = $Options.Runtime } - dotnet publish --output bin --configuration $Options.Configuration --framework $Options.Framework --runtime $runtime --self-contained + Write-Verbose -Verbose -Message "Starting dotnet publish for $toolPath with runtime $runtime" + + dotnet publish --output bin --configuration $Options.Configuration --framework $Options.Framework --runtime $runtime --self-contained | Out-String | Write-Verbose -Verbose + + $dll = $null + $dll = Get-ChildItem -Path bin -Recurse -Filter "*.dll" + + if (-not $dll) { + throw "Failed to find exe in $toolPath" + } if ( -not $env:PATH.Contains($toolPath) ) { $env:PATH = $toolPath+$TestModulePathSeparator+$($env:PATH) diff --git a/tools/releaseBuild/azureDevOps/templates/testartifacts.yml b/tools/releaseBuild/azureDevOps/templates/testartifacts.yml index b75ade828a3..0eec5cd25a6 100644 --- a/tools/releaseBuild/azureDevOps/templates/testartifacts.yml +++ b/tools/releaseBuild/azureDevOps/templates/testartifacts.yml @@ -14,6 +14,10 @@ jobs: - checkout: self clean: true + - template: /tools/releaseBuild/azureDevOps/templates/insert-nuget-config-azfeed.yml + parameters: + repoRoot: $(Build.SourcesDirectory) + - pwsh: | Import-Module ./build.psm1 Start-PSBootstrap @@ -59,5 +63,6 @@ jobs: BuildTestPackage -runtime linux-musl-x64 displayName: Build test package and upload + retryCountOnTaskFailure: 1 - template: /tools/releaseBuild/azureDevOps/templates/step/finalize.yml From 665bf21fcb80476e399712b9b47a891808a2e32f Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Wed, 9 Nov 2022 14:51:24 -0800 Subject: [PATCH 186/779] Bump to use internal .NET 7 GA build (#18508) --- .vsts-ci/templates/verify-xunit.yml | 4 ++-- DotnetRuntimeMetadata.json | 6 +++--- assets/wix/files.wxs | 8 ++++---- build.psm1 | 8 +++++--- global.json | 2 +- ...icrosoft.PowerShell.Commands.Management.csproj | 2 +- .../Microsoft.PowerShell.Commands.Utility.csproj | 9 +++++---- .../Microsoft.PowerShell.CoreCLR.Eventing.csproj | 2 +- .../Microsoft.PowerShell.SDK.csproj | 15 ++++++++++----- .../Microsoft.WSMan.Management.csproj | 2 +- .../System.Management.Automation.csproj | 15 ++++++++------- test/tools/TestService/TestService.csproj | 2 +- test/tools/WebListener/WebListener.csproj | 4 ++-- .../azureDevOps/templates/compliance/apiscan.yml | 4 ++++ .../templates/linux-authenticode-sign.yml | 2 +- .../azureDevOps/templates/linux-packaging.yml | 4 ++++ .../releaseBuild/azureDevOps/templates/linux.yml | 4 ++++ .../azureDevOps/templates/mac-package-build.yml | 7 +++++++ tools/releaseBuild/azureDevOps/templates/mac.yml | 7 +++++++ .../releaseBuild/azureDevOps/templates/nuget.yml | 4 ++++ .../templates/release-GlobalToolTest.yml | 12 ++++++++++++ .../azureDevOps/templates/release-SDKTests.yml | 7 +++++++ .../azureDevOps/templates/testartifacts.yml | 4 ++++ .../templates/windows-hosted-build.yml | 4 ++++ .../azureDevOps/templates/windows-packaging.yml | 4 ++++ 25 files changed, 106 insertions(+), 36 deletions(-) diff --git a/.vsts-ci/templates/verify-xunit.yml b/.vsts-ci/templates/verify-xunit.yml index d2799f53ae0..b43cb9339f9 100644 --- a/.vsts-ci/templates/verify-xunit.yml +++ b/.vsts-ci/templates/verify-xunit.yml @@ -19,12 +19,12 @@ jobs: xunit/**/* downloadPath: '$(System.ArtifactsDirectory)' - - powershell: | + - pwsh: | dir "$(System.ArtifactsDirectory)\*" -Recurse displayName: 'Capture artifacts directory' continueOnError: true - - powershell: | + - pwsh: | Import-Module .\tools\ci.psm1 $xUnitTestResultsFile = "$(System.ArtifactsDirectory)\xunit\xUnitTestResults.xml" diff --git a/DotnetRuntimeMetadata.json b/DotnetRuntimeMetadata.json index 2f4b4442efc..3e84f733c4d 100644 --- a/DotnetRuntimeMetadata.json +++ b/DotnetRuntimeMetadata.json @@ -1,13 +1,13 @@ { "sdk": { - "channel": "7.0.1xx-rc2", + "channel": "7.0.1xx", "quality": "daily", "qualityFallback": "preview", - "packageVersionPattern": "7.0.0-rc.2", + "packageVersionPattern": "7.0.0", "sdkImageVersion": "7.0.100", "nextChannel": "7.0.1xx-rc2", "azureFeed": "", - "sdkImageOverride": "" + "sdkImageOverride": "7.0.100-rtm.22521.12" }, "internalfeed": { "url": "" diff --git a/assets/wix/files.wxs b/assets/wix/files.wxs index 47501d9303e..408ad21805e 100644 --- a/assets/wix/files.wxs +++ b/assets/wix/files.wxs @@ -2775,12 +2775,12 @@ - - - + + + @@ -3667,9 +3667,9 @@ - + diff --git a/build.psm1 b/build.psm1 index ca1a87c41ef..01d8b4ded78 100644 --- a/build.psm1 +++ b/build.psm1 @@ -19,7 +19,8 @@ $script:Options = $null $dotnetMetadata = Get-Content $PSScriptRoot/DotnetRuntimeMetadata.json | ConvertFrom-Json $dotnetCLIChannel = $dotnetMetadata.Sdk.Channel $dotnetCLIQuality = $dotnetMetadata.Sdk.Quality -$dotnetAzureFeed = $dotnetMetadata.Sdk.azureFeed +$dotnetAzureFeed = $env:__DONET_RUNTIME_FEED ?? $dotnetMetadata.Sdk.azureFeed +$dotnetAzureFeedSecret = $env:__DONET_RUNTIME_FEED_KEY $dotnetSDKVersionOveride = $dotnetMetadata.Sdk.sdkImageOverride $dotnetCLIRequiredVersion = $(Get-Content $PSScriptRoot/global.json | ConvertFrom-Json).Sdk.Version @@ -1969,7 +1970,8 @@ function Install-Dotnet { $psArgs += @('-SkipNonVersionedFiles') - $psArgs -join ' ' | Write-Verbose -Verbose + # Removing the verbose message to not expose the secret + # $psArgs -join ' ' | Write-Verbose -Verbose Start-NativeExecution { & $fullPSPath @psArgs @@ -2189,7 +2191,7 @@ function Start-PSBootstrap { if ($dotnetAzureFeed) { $null = $DotnetArguments.Add("AzureFeed", $dotnetAzureFeed) - $null = $DotnetArguments.Add("FeedCredential", $null) + $null = $DotnetArguments.Add("FeedCredential", $dotnetAzureFeedSecret) } Install-Dotnet @DotnetArguments diff --git a/global.json b/global.json index 76bca39fb4f..70e3dcc5080 100644 --- a/global.json +++ b/global.json @@ -1,5 +1,5 @@ { "sdk": { - "version": "7.0.100-rc.2.22477.23" + "version": "7.0.100" } } diff --git a/src/Microsoft.PowerShell.Commands.Management/Microsoft.PowerShell.Commands.Management.csproj b/src/Microsoft.PowerShell.Commands.Management/Microsoft.PowerShell.Commands.Management.csproj index 414c338a2c4..06bd7872cbe 100644 --- a/src/Microsoft.PowerShell.Commands.Management/Microsoft.PowerShell.Commands.Management.csproj +++ b/src/Microsoft.PowerShell.Commands.Management/Microsoft.PowerShell.Commands.Management.csproj @@ -47,7 +47,7 @@ - + diff --git a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj index d502b7048e3..ad1269ae241 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj +++ b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj @@ -8,6 +8,7 @@ + @@ -31,10 +32,10 @@ - - - - + + + + diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/Microsoft.PowerShell.CoreCLR.Eventing.csproj b/src/Microsoft.PowerShell.CoreCLR.Eventing/Microsoft.PowerShell.CoreCLR.Eventing.csproj index c33fc10ccd1..26376c5609f 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/Microsoft.PowerShell.CoreCLR.Eventing.csproj +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/Microsoft.PowerShell.CoreCLR.Eventing.csproj @@ -8,7 +8,7 @@ - + diff --git a/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj b/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj index 4159ee8e569..bd26318a6b1 100644 --- a/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj +++ b/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj @@ -15,12 +15,17 @@ + + + + + - + - - - + + + @@ -29,7 +34,7 @@ - + diff --git a/src/Microsoft.WSMan.Management/Microsoft.WSMan.Management.csproj b/src/Microsoft.WSMan.Management/Microsoft.WSMan.Management.csproj index 3b45803af9d..94a13515348 100644 --- a/src/Microsoft.WSMan.Management/Microsoft.WSMan.Management.csproj +++ b/src/Microsoft.WSMan.Management/Microsoft.WSMan.Management.csproj @@ -10,7 +10,7 @@ - + diff --git a/src/System.Management.Automation/System.Management.Automation.csproj b/src/System.Management.Automation/System.Management.Automation.csproj index 9cde2d2494d..53204b1de73 100644 --- a/src/System.Management.Automation/System.Management.Automation.csproj +++ b/src/System.Management.Automation/System.Management.Automation.csproj @@ -34,16 +34,17 @@ - - - + + + + - + - - - + + + diff --git a/test/tools/TestService/TestService.csproj b/test/tools/TestService/TestService.csproj index aeb87b00ad1..2ab58a57ddf 100644 --- a/test/tools/TestService/TestService.csproj +++ b/test/tools/TestService/TestService.csproj @@ -13,7 +13,7 @@ - + diff --git a/test/tools/WebListener/WebListener.csproj b/test/tools/WebListener/WebListener.csproj index a80dcd0d97b..3977af31fba 100644 --- a/test/tools/WebListener/WebListener.csproj +++ b/test/tools/WebListener/WebListener.csproj @@ -7,8 +7,8 @@ - - + + diff --git a/tools/releaseBuild/azureDevOps/templates/compliance/apiscan.yml b/tools/releaseBuild/azureDevOps/templates/compliance/apiscan.yml index aa81407e3e8..cae5e0e0231 100644 --- a/tools/releaseBuild/azureDevOps/templates/compliance/apiscan.yml +++ b/tools/releaseBuild/azureDevOps/templates/compliance/apiscan.yml @@ -16,6 +16,7 @@ jobs: value: $[format('{0:yyyyMMdd}-{1}', pipeline.startTime,variables['Build.SourceBranch'])] - name: branchCounter value: $[counter(variables['branchCounterKey'], 1)] + - group: DotNetPrivateBuildAccess pool: name: PowerShell1ES @@ -38,6 +39,9 @@ jobs: workingDirectory: '$(Build.SourcesDirectory)' retryCountOnTaskFailure: 2 displayName: 'Bootstrap' + env: + __DONET_RUNTIME_FEED: $(RUNTIME_SOURCEFEED) + __DONET_RUNTIME_FEED_KEY: $(RUNTIME_SOURCEFEED_KEY) - pwsh: | Import-Module .\build.psm1 -force diff --git a/tools/releaseBuild/azureDevOps/templates/linux-authenticode-sign.yml b/tools/releaseBuild/azureDevOps/templates/linux-authenticode-sign.yml index d014cf74320..39eeb7dd5fa 100644 --- a/tools/releaseBuild/azureDevOps/templates/linux-authenticode-sign.yml +++ b/tools/releaseBuild/azureDevOps/templates/linux-authenticode-sign.yml @@ -70,7 +70,7 @@ jobs: parameters: repoRoot: $(PowerShellRoot) - - powershell: | + - pwsh: | Set-Location $env:POWERSHELLROOT import-module "$env:POWERSHELLROOT/build.psm1" Sync-PSTags -AddRemoteIfMissing diff --git a/tools/releaseBuild/azureDevOps/templates/linux-packaging.yml b/tools/releaseBuild/azureDevOps/templates/linux-packaging.yml index f5e298f7139..f75ca3971a8 100644 --- a/tools/releaseBuild/azureDevOps/templates/linux-packaging.yml +++ b/tools/releaseBuild/azureDevOps/templates/linux-packaging.yml @@ -20,6 +20,7 @@ jobs: - name: NugetSecurityAnalysisWarningLevel value: none - group: ESRP + - group: DotNetPrivateBuildAccess steps: - ${{ if or(eq(variables.build,'deb'), eq(variables.build,'rpm')) }} : @@ -162,6 +163,9 @@ jobs: displayName: 'Bootstrap' condition: and(succeeded(), ne(variables['SkipBuild'], 'true')) workingDirectory: $(PowerShellRoot) + env: + __DONET_RUNTIME_FEED: $(RUNTIME_SOURCEFEED) + __DONET_RUNTIME_FEED_KEY: $(RUNTIME_SOURCEFEED_KEY) - powershell: | try { diff --git a/tools/releaseBuild/azureDevOps/templates/linux.yml b/tools/releaseBuild/azureDevOps/templates/linux.yml index e7caa41bc30..ab551a16dd0 100644 --- a/tools/releaseBuild/azureDevOps/templates/linux.yml +++ b/tools/releaseBuild/azureDevOps/templates/linux.yml @@ -20,6 +20,7 @@ jobs: - name: NugetSecurityAnalysisWarningLevel value: none - group: ESRP + - group: DotNetPrivateBuildAccess steps: - checkout: self @@ -60,6 +61,9 @@ jobs: displayName: 'Bootstrap' condition: and(succeeded(), ne(variables['SkipBuild'], 'true')) workingDirectory: $(PowerShellRoot) + env: + __DONET_RUNTIME_FEED: $(RUNTIME_SOURCEFEED) + __DONET_RUNTIME_FEED_KEY: $(RUNTIME_SOURCEFEED_KEY) - pwsh: | try { diff --git a/tools/releaseBuild/azureDevOps/templates/mac-package-build.yml b/tools/releaseBuild/azureDevOps/templates/mac-package-build.yml index e61ea99004f..0f5b9acbc13 100644 --- a/tools/releaseBuild/azureDevOps/templates/mac-package-build.yml +++ b/tools/releaseBuild/azureDevOps/templates/mac-package-build.yml @@ -17,6 +17,7 @@ jobs: value: false - name: NugetSecurityAnalysisWarningLevel value: none + - group: DotNetPrivateBuildAccess steps: - checkout: self clean: true @@ -116,6 +117,9 @@ jobs: throw } displayName: 'Bootstrap VM' + env: + __DONET_RUNTIME_FEED: $(RUNTIME_SOURCEFEED) + __DONET_RUNTIME_FEED_KEY: $(RUNTIME_SOURCEFEED_KEY) - pwsh: | # Add -SkipReleaseChecks as a mitigation to unblock release. @@ -127,6 +131,9 @@ jobs: throw } displayName: 'Package' + env: + __DONET_RUNTIME_FEED: $(RUNTIME_SOURCEFEED) + __DONET_RUNTIME_FEED_KEY: $(RUNTIME_SOURCEFEED_KEY) - task: ms.vss-governance-buildtask.governance-build-task-component-detection.ComponentGovernanceComponentDetection@0 displayName: 'Component Detection' diff --git a/tools/releaseBuild/azureDevOps/templates/mac.yml b/tools/releaseBuild/azureDevOps/templates/mac.yml index 776382c952d..7bf1a2121df 100644 --- a/tools/releaseBuild/azureDevOps/templates/mac.yml +++ b/tools/releaseBuild/azureDevOps/templates/mac.yml @@ -15,6 +15,7 @@ jobs: value: false - name: NugetSecurityAnalysisWarningLevel value: none + - group: DotNetPrivateBuildAccess steps: #- task: @ # inputs: @@ -41,6 +42,9 @@ jobs: - pwsh: | tools/releaseBuild/macOS/PowerShellPackageVsts.ps1 -location $(PowerShellRoot) -BootStrap displayName: 'Bootstrap VM' + env: + __DONET_RUNTIME_FEED: $(RUNTIME_SOURCEFEED) + __DONET_RUNTIME_FEED_KEY: $(RUNTIME_SOURCEFEED_KEY) - template: /tools/releaseBuild/azureDevOps/templates/insert-nuget-config-azfeed.yml parameters: @@ -53,6 +57,9 @@ jobs: $(Build.SourcesDirectory)/tools/releaseBuild/macOS/PowerShellPackageVsts.ps1 -ReleaseTag $(ReleaseTagVar) -Destination $(System.ArtifactsDirectory) -Symbols -location $(PowerShellRoot) -Build -ArtifactName macosBinResults -Runtime 'osx-${{ parameters.buildArchitecture }}' -SkipReleaseChecks $env:AzDevOpsFeedPAT2 = $null displayName: 'Build' + env: + __DONET_RUNTIME_FEED: $(RUNTIME_SOURCEFEED) + __DONET_RUNTIME_FEED_KEY: $(RUNTIME_SOURCEFEED_KEY) - task: ms.vss-governance-buildtask.governance-build-task-component-detection.ComponentGovernanceComponentDetection@0 displayName: 'Component Detection' diff --git a/tools/releaseBuild/azureDevOps/templates/nuget.yml b/tools/releaseBuild/azureDevOps/templates/nuget.yml index f514ca7741b..f38e1a718c6 100644 --- a/tools/releaseBuild/azureDevOps/templates/nuget.yml +++ b/tools/releaseBuild/azureDevOps/templates/nuget.yml @@ -32,6 +32,7 @@ jobs: value: '$(System.ArtifactsDirectory)/winFxdWinDesktop' - name: linuxFxdPath value: '$(System.ArtifactsDirectory)/linuxFxd' + - group: DotNetPrivateBuildAccess steps: - checkout: self @@ -56,6 +57,9 @@ jobs: # We just need .NET but we fixed this in an urgent situation. Start-PSBootStrap -Verbose displayName: Bootstrap + env: + __DONET_RUNTIME_FEED: $(RUNTIME_SOURCEFEED) + __DONET_RUNTIME_FEED_KEY: $(RUNTIME_SOURCEFEED_KEY) - task: DownloadBuildArtifacts@0 displayName: 'Download PowerShell build artifacts - finalResults' diff --git a/tools/releaseBuild/azureDevOps/templates/release-GlobalToolTest.yml b/tools/releaseBuild/azureDevOps/templates/release-GlobalToolTest.yml index 8ac318db921..bd353baaec8 100644 --- a/tools/releaseBuild/azureDevOps/templates/release-GlobalToolTest.yml +++ b/tools/releaseBuild/azureDevOps/templates/release-GlobalToolTest.yml @@ -12,6 +12,9 @@ jobs: pool: # test vmImage: ${{ parameters.imageName }} + variables: + - group: DotNetPrivateBuildAccess + steps: - checkout: self clean: true @@ -57,6 +60,9 @@ jobs: Write-Verbose -Message "Installing .NET SDK completed." -Verbose displayName: Install .NET + env: + __DONET_RUNTIME_FEED: $(RUNTIME_SOURCEFEED) + __DONET_RUNTIME_FEED_KEY: $(RUNTIME_SOURCEFEED_KEY) - pwsh: | $branch = $ENV:BUILD_SOURCEBRANCH @@ -78,6 +84,9 @@ jobs: Get-ChildItem -Path $toolPath displayName: Install global tool + env: + __DONET_RUNTIME_FEED: $(RUNTIME_SOURCEFEED) + __DONET_RUNTIME_FEED_KEY: $(RUNTIME_SOURCEFEED_KEY) - pwsh: | $toolPath = "$(System.DefaultWorkingDirectory)/toolPath/${{ parameters.globalToolExeName }}" @@ -138,3 +147,6 @@ jobs: write-verbose -verbose "Got expected year: $dateYear" } displayName: Basic validation + env: + __DONET_RUNTIME_FEED: $(RUNTIME_SOURCEFEED) + __DONET_RUNTIME_FEED_KEY: $(RUNTIME_SOURCEFEED_KEY) diff --git a/tools/releaseBuild/azureDevOps/templates/release-SDKTests.yml b/tools/releaseBuild/azureDevOps/templates/release-SDKTests.yml index b417df7da08..0efffbee99e 100644 --- a/tools/releaseBuild/azureDevOps/templates/release-SDKTests.yml +++ b/tools/releaseBuild/azureDevOps/templates/release-SDKTests.yml @@ -11,6 +11,7 @@ jobs: vmImage: ${{ parameters.imageName }} variables: - group: AzDevOpsArtifacts + - group: DotNetPrivateBuildAccess steps: - checkout: self clean: true @@ -95,6 +96,9 @@ jobs: Write-Verbose -Message "Installing .NET SDK completed." -Verbose displayName: Install .NET + env: + __DONET_RUNTIME_FEED: $(RUNTIME_SOURCEFEED) + __DONET_RUNTIME_FEED_KEY: $(RUNTIME_SOURCEFEED_KEY) - pwsh: | $env:DOTNET_SKIP_FIRST_TIME_EXPERIENCE=1 @@ -131,6 +135,9 @@ jobs: dotnet test /property:RELEASE_VERSION=$releaseVersion --test-adapter-path:. "--logger:xunit;LogFilePath=$(System.DefaultWorkingDirectory)/test-hosting.xml" displayName: Restore and execute tests + env: + __DONET_RUNTIME_FEED: $(RUNTIME_SOURCEFEED) + __DONET_RUNTIME_FEED_KEY: $(RUNTIME_SOURCEFEED_KEY) - task: PublishTestResults@2 displayName: 'Publish Test Results **\test-hosting.xml' diff --git a/tools/releaseBuild/azureDevOps/templates/testartifacts.yml b/tools/releaseBuild/azureDevOps/templates/testartifacts.yml index 0eec5cd25a6..b76ec0514be 100644 --- a/tools/releaseBuild/azureDevOps/templates/testartifacts.yml +++ b/tools/releaseBuild/azureDevOps/templates/testartifacts.yml @@ -5,6 +5,7 @@ jobs: value: false - name: NugetSecurityAnalysisWarningLevel value: none + - group: DotNetPrivateBuildAccess displayName: Build test artifacts condition: succeeded() pool: @@ -22,6 +23,9 @@ jobs: Import-Module ./build.psm1 Start-PSBootstrap displayName: Bootstrap + env: + __DONET_RUNTIME_FEED: $(RUNTIME_SOURCEFEED) + __DONET_RUNTIME_FEED_KEY: $(RUNTIME_SOURCEFEED_KEY) - pwsh: | Import-Module ./build.psm1 diff --git a/tools/releaseBuild/azureDevOps/templates/windows-hosted-build.yml b/tools/releaseBuild/azureDevOps/templates/windows-hosted-build.yml index 1201edf98b7..fd04f5ba5f7 100644 --- a/tools/releaseBuild/azureDevOps/templates/windows-hosted-build.yml +++ b/tools/releaseBuild/azureDevOps/templates/windows-hosted-build.yml @@ -30,6 +30,7 @@ jobs: value: ${{ parameters.Architecture }} - name: DOTNET_SKIP_FIRST_TIME_EXPERIENCE value: 1 + - group: DotNetPrivateBuildAccess steps: @@ -65,6 +66,9 @@ jobs: tools/releaseBuild/Images/microsoft_powershell_windowsservercore/PowerShellPackage.ps1 -location '$(PowerShellRoot)' -destination '$(Build.ArtifactStagingDirectory)/Symbols_$(Architecture)' -Runtime $runtime -ReleaseTag '$(ReleaseTagVar)' -Symbols @params displayName: 'Build Windows Universal - $(Architecture)-$(BuildConfiguration) Symbols zip' + env: + __DONET_RUNTIME_FEED: $(RUNTIME_SOURCEFEED) + __DONET_RUNTIME_FEED_KEY: $(RUNTIME_SOURCEFEED_KEY) - pwsh: | $packageName = (Get-ChildItem '$(Build.ArtifactStagingDirectory)\Symbols_$(Architecture)').FullName diff --git a/tools/releaseBuild/azureDevOps/templates/windows-packaging.yml b/tools/releaseBuild/azureDevOps/templates/windows-packaging.yml index befcebf3bd3..0b9ff979ef0 100644 --- a/tools/releaseBuild/azureDevOps/templates/windows-packaging.yml +++ b/tools/releaseBuild/azureDevOps/templates/windows-packaging.yml @@ -27,6 +27,7 @@ jobs: - name: DOTNET_SKIP_FIRST_TIME_EXPERIENCE value: 1 - group: ESRP + - group: DotNetPrivateBuildAccess steps: @@ -257,6 +258,9 @@ jobs: $(PowerShellRoot)/tools/releaseBuild/Images/microsoft_powershell_windowsservercore/PowerShellPackage.ps1 -BuildZip $signedPkg -location '$(PowerShellRoot)' -destination '$(System.ArtifactsDirectory)\pkgSigned' -Runtime $runtime -ReleaseTag '$(ReleaseTagVar)' @params displayName: 'Build Windows Universal - $(Architecture) Package' + env: + __DONET_RUNTIME_FEED: $(RUNTIME_SOURCEFEED) + __DONET_RUNTIME_FEED_KEY: $(RUNTIME_SOURCEFEED_KEY) - pwsh: | Get-ChildItem '$(System.ArtifactsDirectory)\pkgSigned' | ForEach-Object { From 9c55989a2e3b4e7f3a1f4110e39248146a089435 Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Wed, 9 Nov 2022 15:04:21 -0800 Subject: [PATCH 187/779] Mark charset test as pending (#18511) --- .../Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 | 1 + 1 file changed, 1 insertion(+) diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 index 2e7c9f00cb4..0a84f60cd76 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 @@ -2019,6 +2019,7 @@ Describe "Invoke-WebRequest tests" -Tags "Feature", "RequireAdminOnWindows" { } It "Charset Parsing" { + Set-ItResult -Pending -Because "We need a better way to test this and .NET has made bad regex's run faster" $dosUri = Get-WebListenerUrl -Test 'Dos' -query @{ dosType='charset' dosLength='2850' From bd89dce2f1b8b4bdc96e2ebf0da636156d024966 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 9 Nov 2022 23:30:15 +0000 Subject: [PATCH 188/779] Bump System.Data.SqlClient from 4.8.4 to 4.8.5 in /src/Microsoft.PowerShell.SDK (#18515) Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj b/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj index bd26318a6b1..039402fd3a4 100644 --- a/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj +++ b/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj @@ -21,7 +21,7 @@ - + From 21a7ab7cdde162015ef16c7ccf2cd48bca2a10dd Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Wed, 9 Nov 2022 17:24:07 -0800 Subject: [PATCH 189/779] Update `release-MsixBundle.yml` to add retries (#18465) --- .../releaseBuild/azureDevOps/templates/release-MsixBundle.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tools/releaseBuild/azureDevOps/templates/release-MsixBundle.yml b/tools/releaseBuild/azureDevOps/templates/release-MsixBundle.yml index 6f3957d0815..a9591b2d251 100644 --- a/tools/releaseBuild/azureDevOps/templates/release-MsixBundle.yml +++ b/tools/releaseBuild/azureDevOps/templates/release-MsixBundle.yml @@ -15,6 +15,7 @@ jobs: - template: release-SetReleaseTagAndContainerName.yml - task: DownloadPipelineArtifact@2 + retryCountOnTaskFailure: 2 inputs: source: specific project: PowerShellCore @@ -46,6 +47,7 @@ jobs: Write-Host "sending " + $vstsCommandString Write-Host "##$vstsCommandString" displayName: Install makeappx tool + retryCountOnTaskFailure: 1 - pwsh: | $sourceDir = '$(Pipeline.Workspace)\releasePipeline\msix' @@ -64,9 +66,11 @@ jobs: Write-Host "sending " + $vstsCommandString Write-Host "##$vstsCommandString" displayName: Create MsixBundle + retryCountOnTaskFailure: 1 - task: AzureFileCopy@4 displayName: 'Upload MSIX Bundle package to Az Blob' + retryCountOnTaskFailure: 2 inputs: SourcePath: '$(BundleDir)/*.msixbundle' azureSubscription: '$(AzureFileCopySubscription)' From 18093283ed958371818b8bd6b180955b2c6f697c Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Wed, 9 Nov 2022 17:26:53 -0800 Subject: [PATCH 190/779] Avoid depending on the pre-generated experimental feature list in private and CI builds (#18484) --- build.psm1 | 37 ++++++++++++------- .../releaseBuild/azureDevOps/releaseBuild.yml | 2 + 2 files changed, 25 insertions(+), 14 deletions(-) diff --git a/build.psm1 b/build.psm1 index 01d8b4ded78..1b9bd8aef37 100644 --- a/build.psm1 +++ b/build.psm1 @@ -635,32 +635,41 @@ Fix steps: } # publish powershell.config.json - $config = @{} + $config = [ordered]@{} if ($Options.Runtime -like "*win*") { - # Execution Policy is only supported on Windows - $config = @{ "Microsoft.PowerShell:ExecutionPolicy" = "RemoteSigned"; - "WindowsPowerShellCompatibilityModuleDenyList" = @("PSScheduledJob", "BestPractices", "UpdateServices") - } + # Execution Policy and WinCompat feature are only supported on Windows. + $config.Add("Microsoft.PowerShell:ExecutionPolicy", "RemoteSigned") + $config.Add("WindowsPowerShellCompatibilityModuleDenyList", @("PSScheduledJob", "BestPractices", "UpdateServices")) } if (-not $SkipExperimentalFeatureGeneration -and (Test-IsPreview $psVersion) -and -not (Test-IsReleaseCandidate $psVersion) ) { - - $ExperimentalFeatureJsonFilePath = if ($Options.Runtime -like "*win*") { - "$PSScriptRoot/experimental-feature-windows.json" + if (-not $env:PS_RELEASE_BUILD -and -not $Runtime.Contains("arm") -and -not ($Runtime -like 'fxdependent*')) { + Write-Verbose "Build experimental feature list by running 'Get-ExperimentalFeature'" -Verbose + $json = & $publishPath\pwsh -noprofile -command { + $expFeatures = Get-ExperimentalFeature | ForEach-Object -MemberName Name + ConvertTo-Json $expFeatures + } } else { - "$PSScriptRoot/experimental-feature-linux.json" - } + Write-Verbose "Build experimental feature list by using the pre-generated JSON files" -Verbose + $ExperimentalFeatureJsonFilePath = if ($Options.Runtime -like "*win*") { + "$PSScriptRoot/experimental-feature-windows.json" + } else { + "$PSScriptRoot/experimental-feature-linux.json" + } + + if (-not (Test-Path $ExperimentalFeatureJsonFilePath)) { + throw "ExperimentalFeatureJsonFilePath: $ExperimentalFeatureJsonFilePath does not exist" + } - if (-not (Test-Path $ExperimentalFeatureJsonFilePath)) { - throw "ExperimentalFeatureJsonFilePath: $ExperimentalFeatureJsonFilePath does not exist" + $json = Get-Content -Raw $ExperimentalFeatureJsonFilePath } - $json = Get-Content -Raw $ExperimentalFeatureJsonFilePath - $config += @{ ExperimentalFeatures = ([string[]] ($json | ConvertFrom-Json)) } + $config.Add('ExperimentalFeatures', [string[]]($json | ConvertFrom-Json)); + } else { Write-Warning -Message "Experimental features are not enabled in powershell.config.json file" } diff --git a/tools/releaseBuild/azureDevOps/releaseBuild.yml b/tools/releaseBuild/azureDevOps/releaseBuild.yml index e21b4fe0c4e..32f6bcca599 100644 --- a/tools/releaseBuild/azureDevOps/releaseBuild.yml +++ b/tools/releaseBuild/azureDevOps/releaseBuild.yml @@ -28,6 +28,8 @@ resources: ref: master variables: + - name: PS_RELEASE_BUILD + value: 1 - name: DOTNET_CLI_TELEMETRY_OPTOUT value: 1 - name: POWERSHELL_TELEMETRY_OPTOUT From 9f459c05f617fe530dac340aa546d198724d85da Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Wed, 9 Nov 2022 19:24:11 -0800 Subject: [PATCH 191/779] Replace DllImport with LibraryImport in engine (#18496) --- .../CoreCLR/CorePsPlatform.cs | 90 +++++++++---------- .../engine/NativeCommandProcessor.cs | 23 ++--- .../engine/ProcessCodeMethods.cs | 6 +- 3 files changed, 58 insertions(+), 61 deletions(-) diff --git a/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs b/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs index 28b02a6d706..8f379acc717 100644 --- a/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs +++ b/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs @@ -13,7 +13,7 @@ namespace System.Management.Automation /// /// These are platform abstractions and platform specific implementations. /// - public static class Platform + public static partial class Platform { /// /// True if the current platform is Linux. @@ -453,18 +453,18 @@ internal static int NonWindowsWaitPid(int pid, bool nohang) return Unix.NativeMethods.WaitPid(pid, nohang); } - internal static class Windows + internal static partial class Windows { /// The native methods class. - internal static class NativeMethods + internal static partial class NativeMethods { private const string ole32Lib = "api-ms-win-core-com-l1-1-0.dll"; - [DllImport(ole32Lib)] - internal static extern int CoInitializeEx(IntPtr reserve, int coinit); + [LibraryImport(ole32Lib)] + internal static partial int CoInitializeEx(IntPtr reserve, int coinit); - [DllImport(ole32Lib)] - internal static extern void CoUninitialize(); + [LibraryImport(ole32Lib)] + internal static partial void CoUninitialize(); } } @@ -475,7 +475,7 @@ internal static class NativeMethods // to a PAL value and calls strerror_r underneath to generate the message. /// Unix specific implementations of required functionality. - internal static class Unix + internal static partial class Unix { private static readonly Dictionary usernameCache = new(); private static readonly Dictionary groupnameCache = new(); @@ -925,35 +925,35 @@ public static int GetProcFSParentPid(int pid) } /// The native methods class. - internal static class NativeMethods + internal static partial class NativeMethods { private const string psLib = "libpsl-native"; // Ansi is a misnomer, it is hardcoded to UTF-8 on Linux and macOS // C bools are 1 byte and so must be marshaled as I1 - [DllImport(psLib, CharSet = CharSet.Ansi)] - internal static extern int GetErrorCategory(int errno); + [LibraryImport(psLib)] + internal static partial int GetErrorCategory(int errno); - [DllImport(psLib)] - internal static extern int GetPPid(int pid); + [LibraryImport(psLib)] + internal static partial int GetPPid(int pid); - [DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)] - internal static extern int GetLinkCount([MarshalAs(UnmanagedType.LPStr)] string filePath, out int linkCount); + [LibraryImport(psLib, StringMarshalling = StringMarshalling.Utf8, SetLastError = true)] + internal static partial int GetLinkCount(string filePath, out int linkCount); - [DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)] + [LibraryImport(psLib, StringMarshalling = StringMarshalling.Utf8)] [return: MarshalAs(UnmanagedType.I1)] - internal static extern bool IsExecutable([MarshalAs(UnmanagedType.LPStr)] string filePath); + internal static partial bool IsExecutable(string filePath); - [DllImport(psLib, CharSet = CharSet.Ansi)] - internal static extern uint GetCurrentThreadId(); + [LibraryImport(psLib)] + internal static partial uint GetCurrentThreadId(); - [DllImport(psLib)] + [LibraryImport(psLib)] [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool KillProcess(int pid); + internal static partial bool KillProcess(int pid); - [DllImport(psLib)] - internal static extern int WaitPid(int pid, bool nohang); + [LibraryImport(psLib)] + internal static partial int WaitPid(int pid, [MarshalAs(UnmanagedType.Bool)] bool nohang); // This is a struct tm from . [StructLayout(LayoutKind.Sequential)] @@ -1003,29 +1003,25 @@ internal static UnixTm DateTimeToUnixTm(DateTime date) return tm; } - [DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)] - internal static extern unsafe int SetDate(UnixTm* tm); + [LibraryImport(psLib)] + internal static unsafe partial int SetDate(UnixTm* tm); - [DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)] - internal static extern int CreateSymLink([MarshalAs(UnmanagedType.LPStr)] string filePath, - [MarshalAs(UnmanagedType.LPStr)] string target); + [LibraryImport(psLib, StringMarshalling = StringMarshalling.Utf8)] + internal static partial int CreateSymLink(string filePath, string target); - [DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)] - internal static extern int CreateHardLink([MarshalAs(UnmanagedType.LPStr)] string filePath, - [MarshalAs(UnmanagedType.LPStr)] string target); + [LibraryImport(psLib, StringMarshalling = StringMarshalling.Utf8)] + internal static partial int CreateHardLink(string filePath, string target); - [DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)] + [LibraryImport(psLib)] [return: MarshalAs(UnmanagedType.LPStr)] - internal static extern string GetUserFromPid(int pid); + internal static partial string GetUserFromPid(int pid); - [DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)] + [LibraryImport(psLib, StringMarshalling = StringMarshalling.Utf8)] [return: MarshalAs(UnmanagedType.I1)] - internal static extern bool IsSameFileSystemItem([MarshalAs(UnmanagedType.LPStr)] string filePathOne, - [MarshalAs(UnmanagedType.LPStr)] string filePathTwo); + internal static partial bool IsSameFileSystemItem(string filePathOne, string filePathTwo); - [DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)] - internal static extern int GetInodeData([MarshalAs(UnmanagedType.LPStr)] string path, - out ulong device, out ulong inode); + [LibraryImport(psLib, StringMarshalling = StringMarshalling.Utf8)] + internal static partial int GetInodeData(string path, out ulong device, out ulong inode); /// /// This is a struct from getcommonstat.h in the native library. @@ -1103,17 +1099,17 @@ internal struct CommonStatStruct internal int IsSticky; } - [DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)] - internal static extern unsafe int GetCommonLStat(string filePath, [Out] out CommonStatStruct cs); + [LibraryImport(psLib, StringMarshalling = StringMarshalling.Utf8, SetLastError = true)] + internal static unsafe partial int GetCommonLStat(string filePath, out CommonStatStruct cs); - [DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)] - internal static extern unsafe int GetCommonStat(string filePath, [Out] out CommonStatStruct cs); + [LibraryImport(psLib, StringMarshalling = StringMarshalling.Utf8, SetLastError = true)] + internal static unsafe partial int GetCommonStat(string filePath, out CommonStatStruct cs); - [DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)] - internal static extern string GetPwUid(int id); + [LibraryImport(psLib, StringMarshalling = StringMarshalling.Utf8)] + internal static partial string GetPwUid(int id); - [DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)] - internal static extern string GetGrGid(int id); + [LibraryImport(psLib, StringMarshalling = StringMarshalling.Utf8)] + internal static partial string GetGrGid(int id); } } } diff --git a/src/System.Management.Automation/engine/NativeCommandProcessor.cs b/src/System.Management.Automation/engine/NativeCommandProcessor.cs index e9a1a13e231..06283ac2a34 100644 --- a/src/System.Management.Automation/engine/NativeCommandProcessor.cs +++ b/src/System.Management.Automation/engine/NativeCommandProcessor.cs @@ -2154,15 +2154,15 @@ internal void Done() /// Static class that allows you to show and hide the console window /// associated with this process. /// - internal static class ConsoleVisibility + internal static partial class ConsoleVisibility { /// /// If set to true, then native commands will always be run redirected... /// public static bool AlwaysCaptureApplicationIO { get; set; } - [DllImport("Kernel32.dll")] - internal static extern IntPtr GetConsoleWindow(); + [LibraryImport("Kernel32.dll")] + internal static partial IntPtr GetConsoleWindow(); internal const int SW_HIDE = 0; internal const int SW_SHOWNORMAL = 1; @@ -2186,32 +2186,33 @@ internal static class ConsoleVisibility /// The window to show... /// The command to do. /// True if it was successful. - [DllImport("user32.dll")] - internal static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); + [LibraryImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + internal static partial bool ShowWindow(IntPtr hWnd, int nCmdShow); /// /// Code to allocate a console... /// /// True if a console was created... - [DllImport("kernel32.dll", SetLastError = true)] + [LibraryImport("kernel32.dll")] [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool AllocConsole(); + internal static partial bool AllocConsole(); /// /// Called to save the foreground window before allocating a hidden console window. /// /// A handle to the foreground window. - [DllImport("user32.dll")] - private static extern IntPtr GetForegroundWindow(); + [LibraryImport("user32.dll")] + private static partial IntPtr GetForegroundWindow(); /// /// Called to restore the foreground window after allocating a hidden console window. /// /// A handle to the window that should be activated and brought to the foreground. /// True if the window was brought to the foreground. - [DllImport("user32.dll")] + [LibraryImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] - private static extern bool SetForegroundWindow(IntPtr hWnd); + private static partial bool SetForegroundWindow(IntPtr hWnd); /// /// If no console window is attached to this process, then allocate one, diff --git a/src/System.Management.Automation/engine/ProcessCodeMethods.cs b/src/System.Management.Automation/engine/ProcessCodeMethods.cs index 604ac3787ad..c54d992989e 100644 --- a/src/System.Management.Automation/engine/ProcessCodeMethods.cs +++ b/src/System.Management.Automation/engine/ProcessCodeMethods.cs @@ -11,7 +11,7 @@ namespace Microsoft.PowerShell /// /// Helper functions for process info. /// - public static class ProcessCodeMethods + public static partial class ProcessCodeMethods { private const int InvalidProcessId = -1; @@ -79,8 +79,8 @@ private struct PROCESS_BASIC_INFORMATION public IntPtr InheritedFromUniqueProcessId; } - [DllImport("ntdll.dll", SetLastError = true)] - private static extern int NtQueryInformationProcess( + [LibraryImport("ntdll.dll")] + private static partial int NtQueryInformationProcess( IntPtr processHandle, int processInformationClass, out PROCESS_BASIC_INFORMATION processInformation, From b84652745c83a4693f2ca5860daad5f557fb4e0d Mon Sep 17 00:00:00 2001 From: Ilya Date: Sat, 12 Nov 2022 16:48:27 +0500 Subject: [PATCH 192/779] Replace DllImport with LibraryImport in SMA 1 (#18520) --- .../CommandCompletion/CompletionCompleters.cs | 6 +- .../namespaces/FileSystemProvider.cs | 87 ++++++++++--------- .../utils/ClrFacade.cs | 8 +- 3 files changed, 54 insertions(+), 47 deletions(-) diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs index 3e9f16bc4bd..60a2c31124c 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs @@ -30,7 +30,7 @@ namespace System.Management.Automation { /// /// - public static class CompletionCompleters + public static partial class CompletionCompleters { static CompletionCompleters() { @@ -4751,8 +4751,8 @@ private struct SHARE_INFO_1 AttributesToSkip = 0 // Default is to skip Hidden and System files, so we clear this to retain existing behavior }; - [DllImport("Netapi32.dll", CharSet = CharSet.Unicode)] - private static extern int NetShareEnum(string serverName, int level, out IntPtr bufptr, int prefMaxLen, + [LibraryImport("Netapi32.dll", StringMarshalling = StringMarshalling.Utf16)] + private static partial int NetShareEnum(string serverName, int level, out IntPtr bufptr, int prefMaxLen, out uint entriesRead, out uint totalEntries, ref uint resumeHandle); internal static List GetFileShares(string machine, bool ignoreHidden) diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index 79ed698f45e..e528a9bb5a6 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -7150,7 +7150,7 @@ internal static bool WinPathIsNetworkPath(string path) return NativeMethods.PathIsNetworkPath(path); // call the native method } - private static class NativeMethods + private static partial class NativeMethods { /// /// WNetAddConnection2 API makes a connection to a network resource @@ -7196,8 +7196,8 @@ private static class NativeMethods /// else the error code describing the type of failure that occurred while /// trying to remove the connection is returned. /// - [DllImport("mpr.dll", CharSet = CharSet.Unicode)] - internal static extern int WNetCancelConnection2(string driveName, int flags, bool force); + [LibraryImport("mpr.dll", EntryPoint ="WNetCancelConnection2W", StringMarshalling = StringMarshalling.Utf16)] + internal static partial int WNetCancelConnection2(string driveName, int flags, [MarshalAs(UnmanagedType.Bool)] bool force); /// /// WNetGetConnection function retrieves the name of the network resource associated with a local device. @@ -7223,8 +7223,8 @@ private static class NativeMethods /// Path of the file being executed /// /// Returns 0 through 25 (corresponding to 'A' through 'Z') if the path has a drive letter, or -1 otherwise. - [DllImport("api-ms-win-core-shlwapi-legacy-l1-1-0.dll", CharSet = CharSet.Unicode)] - internal static extern int PathGetDriveNumber(string path); + [LibraryImport("api-ms-win-core-shlwapi-legacy-l1-1-0.dll", EntryPoint ="PathGetDriveNumberW", StringMarshalling = StringMarshalling.Utf16)] + internal static partial int PathGetDriveNumber(string path); private static bool _WNetApiAvailable = true; @@ -7288,9 +7288,9 @@ internal static bool PathIsNetworkPath(string path) /// Path of the file being executed. /// /// True if the path is a network path or else returns false. - [DllImport("shlwapi.dll", CharSet = CharSet.Unicode)] + [LibraryImport("shlwapi.dll", EntryPoint = "PathIsNetworkPathW", StringMarshalling = StringMarshalling.Utf16)] [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool PathIsNetworkPath(string path); + internal static partial bool PathIsNetworkPath(string path); #endif /// @@ -7320,9 +7320,9 @@ internal static bool PathIsNetworkPath(string path) /// Path of the target of the symbolic link. /// Flag values from SymbolicLinkFlags enum. /// 1 on successful creation. - [DllImport(PinvokeDllNames.CreateSymbolicLinkDllName, CharSet = CharSet.Unicode, SetLastError = true)] + [LibraryImport(PinvokeDllNames.CreateSymbolicLinkDllName, EntryPoint = "CreateSymbolicLinkW", StringMarshalling = StringMarshalling.Utf16)] [return: MarshalAs(UnmanagedType.I1)] - internal static extern bool CreateSymbolicLink(string name, string destination, SymbolicLinkFlags symbolicLinkFlags); + internal static partial bool CreateSymbolicLink(string name, string destination, SymbolicLinkFlags symbolicLinkFlags); /// /// Flags used when creating a symbolic link. @@ -7353,9 +7353,9 @@ internal enum SymbolicLinkFlags /// Path to the target of the hard link. /// /// - [DllImport(PinvokeDllNames.CreateHardLinkDllName, CharSet = CharSet.Unicode, SetLastError = true)] + [LibraryImport(PinvokeDllNames.CreateHardLinkDllName, EntryPoint = "CreateHardLinkW", StringMarshalling = StringMarshalling.Utf16)] [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool CreateHardLink(string name, string existingFileName, IntPtr SecurityAttributes); + internal static partial bool CreateHardLink(string name, string existingFileName, IntPtr SecurityAttributes); // OneDrive placeholder support #if !UNIX @@ -7363,16 +7363,16 @@ internal enum SymbolicLinkFlags /// Returns the placeholder compatibility mode for the current process. /// /// The process's placeholder compatibily mode (PHCM_xxx), or a negative value on error (PCHM_ERROR_xxx). - [DllImport("ntdll.dll")] - internal static extern sbyte RtlQueryProcessPlaceholderCompatibilityMode(); + [LibraryImport("ntdll.dll")] + internal static partial sbyte RtlQueryProcessPlaceholderCompatibilityMode(); /// /// Sets the placeholder compatibility mode for the current process. /// /// The placeholder compatibility mode to set. /// The process's previous placeholder compatibily mode (PHCM_xxx), or a negative value on error (PCHM_ERROR_xxx). - [DllImport("ntdll.dll")] - internal static extern sbyte RtlSetProcessPlaceholderCompatibilityMode(sbyte pcm); + [LibraryImport("ntdll.dll")] + internal static partial sbyte RtlSetProcessPlaceholderCompatibilityMode(sbyte pcm); internal const sbyte PHCM_APPLICATION_DEFAULT = 0; internal const sbyte PHCM_DISGUISE_PLACEHOLDER = 1; @@ -7870,7 +7870,7 @@ public class FileSystemProviderRemoveItemDynamicParameters /// /// Class to find the symbolic link target. /// - public static class InternalSymbolicLinkLinkCodeMethods + public static partial class InternalSymbolicLinkLinkCodeMethods { // This size comes from measuring the size of the header of REPARSE_GUID_DATA_BUFFER private const int REPARSE_GUID_DATA_BUFFER_HEADER_SIZE = 24; @@ -7984,9 +7984,9 @@ private struct REPARSE_DATA_BUFFER_MOUNTPOINT private struct BY_HANDLE_FILE_INFORMATION { public uint FileAttributes; - public System.Runtime.InteropServices.ComTypes.FILETIME CreationTime; - public System.Runtime.InteropServices.ComTypes.FILETIME LastAccessTime; - public System.Runtime.InteropServices.ComTypes.FILETIME LastWriteTime; + public FILE_TIME CreationTime; + public FILE_TIME LastAccessTime; + public FILE_TIME LastWriteTime; public uint VolumeSerialNumber; public uint FileSizeHigh; public uint FileSizeLow; @@ -7995,6 +7995,12 @@ private struct BY_HANDLE_FILE_INFORMATION public uint FileIndexLow; } + internal struct FILE_TIME + { + public uint dwLowDateTime; + public uint dwHighDateTime; + } + [StructLayout(LayoutKind.Sequential)] private struct GUID { @@ -8018,20 +8024,21 @@ private struct REPARSE_GUID_DATA_BUFFER public char[] DataBuffer; } - [DllImport(PinvokeDllNames.DeviceIoControlDllName, CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)] - private static extern bool DeviceIoControl(IntPtr hDevice, uint dwIoControlCode, + [LibraryImport(PinvokeDllNames.DeviceIoControlDllName, StringMarshalling = StringMarshalling.Utf16, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool DeviceIoControl(IntPtr hDevice, uint dwIoControlCode, IntPtr InBuffer, int nInBufferSize, IntPtr OutBuffer, int nOutBufferSize, out int pBytesReturned, IntPtr lpOverlapped); - [DllImport(PinvokeDllNames.GetFileInformationByHandleDllName, SetLastError = true, CharSet = CharSet.Unicode)] + [LibraryImport(PinvokeDllNames.GetFileInformationByHandleDllName)] [return: MarshalAs(UnmanagedType.Bool)] - private static extern bool GetFileInformationByHandle( + private static partial bool GetFileInformationByHandle( IntPtr hFile, out BY_HANDLE_FILE_INFORMATION lpFileInformation); - [DllImport(PinvokeDllNames.CreateFileDllName, SetLastError = true, CharSet = CharSet.Unicode)] - internal static extern IntPtr CreateFile( + [LibraryImport(PinvokeDllNames.CreateFileDllName, EntryPoint = "CreateFileW", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)] + internal static partial IntPtr CreateFile( string lpFileName, FileDesiredAccess dwDesiredAccess, FileShareMode dwShareMode, @@ -8040,7 +8047,7 @@ internal static extern IntPtr CreateFile( FileAttributes dwFlagsAndAttributes, IntPtr hTemplateFile); - internal sealed class SafeFindHandle : SafeHandleZeroOrMinusOneIsInvalid + internal sealed partial class SafeFindHandle : SafeHandleZeroOrMinusOneIsInvalid { private SafeFindHandle() : base(true) { } @@ -8049,23 +8056,23 @@ protected override bool ReleaseHandle() return FindClose(this.handle); } - [DllImport(PinvokeDllNames.FindCloseDllName)] + [LibraryImport(PinvokeDllNames.FindCloseDllName)] [return: MarshalAs(UnmanagedType.Bool)] - private static extern bool FindClose(IntPtr handle); + private static partial bool FindClose(IntPtr handle); } // We use 'FindFirstFileW' instead of 'FindFirstFileExW' because the latter doesn't work correctly with Unicode file names on FAT32. // See https://github.com/PowerShell/PowerShell/issues/16804 - [DllImport(PinvokeDllNames.FindFirstFileDllName, EntryPoint = "FindFirstFileW", SetLastError = true, CharSet = CharSet.Unicode)] - private static extern SafeFindHandle FindFirstFile(string lpFileName, ref WIN32_FIND_DATA lpFindFileData); + [LibraryImport(PinvokeDllNames.FindFirstFileDllName, EntryPoint = "FindFirstFileW", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)] + private static partial SafeFindHandle FindFirstFile(string lpFileName, ref WIN32_FIND_DATA lpFindFileData); [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal unsafe struct WIN32_FIND_DATA { internal uint dwFileAttributes; - internal System.Runtime.InteropServices.ComTypes.FILETIME ftCreationTime; - internal System.Runtime.InteropServices.ComTypes.FILETIME ftLastAccessTime; - internal System.Runtime.InteropServices.ComTypes.FILETIME ftLastWriteTime; + internal FILE_TIME ftCreationTime; + internal FILE_TIME ftLastAccessTime; + internal FILE_TIME ftLastWriteTime; internal uint nFileSizeHigh; internal uint nFileSizeLow; internal uint dwReserved0; @@ -8539,7 +8546,7 @@ public class AlternateStreamData /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes", Justification = "Needed by both the FileSystem provider and Unblock-File cmdlet.")] - public static class AlternateDataStreamUtilities + public static partial class AlternateDataStreamUtilities { /// /// List all of the streams on a file. @@ -8704,15 +8711,15 @@ internal static void SetZoneOfOrigin(string path, SecurityZone securityZone) // the code above seems cleaner and more robust than the IAttachmentExecute approach } - internal static class NativeMethods + internal static partial class NativeMethods { internal const int ERROR_HANDLE_EOF = 38; internal const int ERROR_INVALID_PARAMETER = 87; internal enum StreamInfoLevels { FindStreamInfoStandard = 0 } - [DllImport(PinvokeDllNames.CreateFileDllName, CharSet = CharSet.Unicode, SetLastError = true)] - internal static extern SafeFileHandle CreateFile(string lpFileName, + [LibraryImport(PinvokeDllNames.CreateFileDllName, EntryPoint = "CreateFileW", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)] + internal static partial SafeFileHandle CreateFile(string lpFileName, FileAccess dwDesiredAccess, FileShare dwShareMode, IntPtr lpSecurityAttributes, FileMode dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile); @@ -8733,7 +8740,7 @@ internal static extern bool FindNextStreamW( AlternateStreamNativeData lpFindStreamData); } - internal sealed class SafeFindHandle : SafeHandleZeroOrMinusOneIsInvalid + internal sealed partial class SafeFindHandle : SafeHandleZeroOrMinusOneIsInvalid { private SafeFindHandle() : base(true) { } @@ -8742,9 +8749,9 @@ protected override bool ReleaseHandle() return FindClose(this.handle); } - [DllImport(PinvokeDllNames.FindCloseDllName)] + [LibraryImport(PinvokeDllNames.FindCloseDllName)] [return: MarshalAs(UnmanagedType.Bool)] - private static extern bool FindClose(IntPtr handle); + private static partial bool FindClose(IntPtr handle); } /// diff --git a/src/System.Management.Automation/utils/ClrFacade.cs b/src/System.Management.Automation/utils/ClrFacade.cs index 2331eb15ce9..0bccb456e6c 100644 --- a/src/System.Management.Automation/utils/ClrFacade.cs +++ b/src/System.Management.Automation/utils/ClrFacade.cs @@ -19,7 +19,7 @@ namespace System.Management.Automation /// ClrFacade contains all diverging code (different implementation for FullCLR and CoreCLR using if/def). /// It exposes common APIs that can be used by the rest of the code base. /// - internal static class ClrFacade + internal static partial class ClrFacade { /// /// Initialize powershell AssemblyLoadContext and register the 'Resolving' event, if it's not done already. @@ -366,13 +366,13 @@ internal static string ToDmtfDateTime(DateTime date) /// /// Native methods that are used by facade methods. /// - private static class NativeMethods + private static partial class NativeMethods { /// /// Pinvoke for GetOEMCP to get the OEM code page. /// - [DllImport(PinvokeDllNames.GetOEMCPDllName, SetLastError = false, CharSet = CharSet.Unicode)] - internal static extern uint GetOEMCP(); + [LibraryImport(PinvokeDllNames.GetOEMCPDllName)] + internal static partial uint GetOEMCP(); } } } From c740a07e10b6f8a01a14104ec93db51274f67f9c Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Mon, 14 Nov 2022 09:45:23 -0800 Subject: [PATCH 193/779] Change public API mention of `monad` to PowerShell (#18491) * Change public API mention of `monad` to PowerShell * looks like I forgot to save changes in some files --- .../commands/management/Navigation.cs | 6 +++--- .../singleshell/installer/MshUtilityMshSnapin.cs | 4 +--- .../singleshell/installer/EngineInstaller.cs | 5 +---- .../singleshell/installer/MshHostMshSnapin.cs | 5 +---- .../installer/MshSecurityMshSnapin.cs | 4 +--- .../engine/ApplicationInfo.cs | 2 +- .../engine/ErrorPackage.cs | 4 ++-- .../engine/ICommandRuntime.cs | 6 +++--- .../engine/MshCommandRuntime.cs | 2 +- .../engine/MshReference.cs | 2 +- .../engine/cmdlet.cs | 2 +- .../engine/hostifaces/MshHost.cs | 2 +- .../engine/serialization.cs | 1 - .../namespaces/ItemProviderBase.cs | 4 ++-- .../namespaces/ProviderDeclarationAttribute.cs | 16 ++++++++-------- .../security/SecurityManager.cs | 8 ++++---- .../security/SecuritySupport.cs | 6 +++--- .../singleshell/config/MshSnapinInfo.cs | 2 +- .../utils/ExecutionExceptions.cs | 12 ++++++------ .../utils/MshArgumentException.cs | 2 +- .../utils/MshArgumentNullException.cs | 2 +- .../utils/MshArgumentOutOfRangeException.cs | 2 +- .../utils/MshInvalidOperationException.cs | 2 +- .../utils/MshNotImplementedException.cs | 2 +- .../utils/MshNotSupportedException.cs | 2 +- .../utils/MshObjectDisposedException.cs | 2 +- .../utils/MshTraceSource.cs | 4 ++-- .../utils/RuntimeException.cs | 6 +++--- .../utils/StructuredTraceSource.cs | 2 +- 29 files changed, 54 insertions(+), 65 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Navigation.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Navigation.cs index c00c374611e..9e81db105be 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Navigation.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Navigation.cs @@ -1075,7 +1075,7 @@ protected override void ProcessRecord() #region NewPSDriveCommand /// - /// Mounts a drive in the Monad namespace. + /// Mounts a drive in PowerShell runspace. /// [Cmdlet(VerbsCommon.New, "PSDrive", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Low, SupportsTransactions = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096815")] @@ -1477,7 +1477,7 @@ internal List GetMatchingDrives( #region RemovePSDriveCommand /// - /// Removes a drive that is mounted in the Monad namespace. + /// Removes a drive that is mounted in the PowerShell runspace. /// [Cmdlet(VerbsCommon.Remove, "PSDrive", DefaultParameterSetName = NameParameterSet, SupportsShouldProcess = true, SupportsTransactions = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097050")] @@ -1653,7 +1653,7 @@ protected override void ProcessRecord() #region GetPSDriveCommand /// - /// Gets a specified or listing of drives that are mounted in the Monad + /// Gets a specified or listing of drives that are mounted in PowerShell /// namespace. /// [Cmdlet(VerbsCommon.Get, "PSDrive", DefaultParameterSetName = NameParameterSet, SupportsTransactions = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096494")] diff --git a/src/Microsoft.PowerShell.Commands.Utility/singleshell/installer/MshUtilityMshSnapin.cs b/src/Microsoft.PowerShell.Commands.Utility/singleshell/installer/MshUtilityMshSnapin.cs index 038db11916b..ebb3325d0b7 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/singleshell/installer/MshUtilityMshSnapin.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/singleshell/installer/MshUtilityMshSnapin.cs @@ -8,9 +8,7 @@ namespace Microsoft.PowerShell { /// /// PSUtilityPSSnapIn is a class for facilitating registry - /// of necessary information for monad utility PSSnapin. - /// - /// This class will be built with monad utility dll. + /// of necessary information for PowerShell utility PSSnapin. /// [RunInstaller(true)] public sealed class PSUtilityPSSnapIn : PSSnapIn diff --git a/src/Microsoft.PowerShell.ConsoleHost/singleshell/installer/EngineInstaller.cs b/src/Microsoft.PowerShell.ConsoleHost/singleshell/installer/EngineInstaller.cs index 1b3f939158f..ec2b702a144 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/singleshell/installer/EngineInstaller.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/singleshell/installer/EngineInstaller.cs @@ -12,10 +12,7 @@ namespace Microsoft.PowerShell { /// /// EngineInstaller is a class for facilitating registry of necessary - /// information for monad engine. - /// - /// This class will be built with monad console host dll - /// (System.Management.Automation.dll). + /// information for PowerShell engine. /// /// At install time, installation utilities (like InstallUtil.exe) will /// call install this engine assembly based on the implementation in diff --git a/src/Microsoft.PowerShell.ConsoleHost/singleshell/installer/MshHostMshSnapin.cs b/src/Microsoft.PowerShell.ConsoleHost/singleshell/installer/MshHostMshSnapin.cs index ce2fd7b3967..e1132d75751 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/singleshell/installer/MshHostMshSnapin.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/singleshell/installer/MshHostMshSnapin.cs @@ -8,10 +8,7 @@ namespace Microsoft.PowerShell { /// /// PSHostPSSnapIn is a class for facilitating registry - /// of necessary information for monad host PSSnapin. - /// - /// This class will be built with monad host engine dll - /// (Microsoft.PowerShell.ConsoleHost.dll). + /// of necessary information for PowerShell host PSSnapin. /// [RunInstaller(true)] public sealed class PSHostPSSnapIn : PSSnapIn diff --git a/src/Microsoft.PowerShell.Security/singleshell/installer/MshSecurityMshSnapin.cs b/src/Microsoft.PowerShell.Security/singleshell/installer/MshSecurityMshSnapin.cs index 56690e45953..e92502e3911 100644 --- a/src/Microsoft.PowerShell.Security/singleshell/installer/MshSecurityMshSnapin.cs +++ b/src/Microsoft.PowerShell.Security/singleshell/installer/MshSecurityMshSnapin.cs @@ -17,9 +17,7 @@ namespace Microsoft.PowerShell { /// /// PSSecurityPSSnapIn is a class for facilitating registry - /// of necessary information for monad security PSSnapin. - /// - /// This class will be built with monad security dll. + /// of necessary information for PowerShell security PSSnapin. /// [RunInstaller(true)] public sealed class PSSecurityPSSnapIn : PSSnapIn diff --git a/src/System.Management.Automation/engine/ApplicationInfo.cs b/src/System.Management.Automation/engine/ApplicationInfo.cs index 5fe76424f5a..ca46023b66b 100644 --- a/src/System.Management.Automation/engine/ApplicationInfo.cs +++ b/src/System.Management.Automation/engine/ApplicationInfo.cs @@ -8,7 +8,7 @@ namespace System.Management.Automation { /// - /// Provides information for applications that are not directly executable by Monad. + /// Provides information for applications that are not directly executable by PowerShell. /// /// /// An application is any file that is executable by Windows either directly or through diff --git a/src/System.Management.Automation/engine/ErrorPackage.cs b/src/System.Management.Automation/engine/ErrorPackage.cs index 8cdc0ee8d4c..a0e95e083e7 100644 --- a/src/System.Management.Automation/engine/ErrorPackage.cs +++ b/src/System.Management.Automation/engine/ErrorPackage.cs @@ -18,7 +18,7 @@ namespace System.Management.Automation { /// - /// Errors reported by Monad will be in one of these categories. + /// Errors reported by PowerShell will be in one of these categories. /// /// /// Do not specify ErrorCategory.NotSpecified when creating an @@ -132,7 +132,7 @@ public enum ErrorCategory WriteError = 23, /// - /// A non-Monad command reported an error to its STDERR pipe. + /// A native command reported an error to its STDERR pipe. /// /// /// The Engine uses this ErrorCategory when it executes a native diff --git a/src/System.Management.Automation/engine/ICommandRuntime.cs b/src/System.Management.Automation/engine/ICommandRuntime.cs index 5ad67039d2e..4fd0c0061b1 100644 --- a/src/System.Management.Automation/engine/ICommandRuntime.cs +++ b/src/System.Management.Automation/engine/ICommandRuntime.cs @@ -15,8 +15,8 @@ namespace System.Management.Automation /// When a cmdlet is instantiated and run directly, all calls to the stream APIs will be proxied /// through to an instance of this class. For example, when a cmdlet calls WriteObject, the /// WriteObject implementation on the instance of the class implementing this interface will be - /// called. The Monad implementation provides a default implementation of this class for use with - /// standalone cmdlets as well as the implementation provided for running in the monad engine itself. + /// called. PowerShell implementation provides a default implementation of this class for use with + /// standalone cmdlets as well as the implementation provided for running in the engine itself. /// /// If you do want to run Cmdlet instances standalone and capture their output with more /// fidelity than is provided for with the default implementation, then you should create your own @@ -174,7 +174,7 @@ public interface ICommandRuntime /// pipeline execution log. /// /// If LogPipelineExecutionDetail is turned on, this information will be written - /// to monad log under log category "Pipeline execution detail" + /// to PowerShell log under log category "Pipeline execution detail" /// /// /// diff --git a/src/System.Management.Automation/engine/MshCommandRuntime.cs b/src/System.Management.Automation/engine/MshCommandRuntime.cs index 738c3d13981..fcc7f5b4588 100644 --- a/src/System.Management.Automation/engine/MshCommandRuntime.cs +++ b/src/System.Management.Automation/engine/MshCommandRuntime.cs @@ -876,7 +876,7 @@ internal void WriteInformation(InformationRecord record, bool overrideInquire = /// pipeline execution log. /// /// If LogPipelineExecutionDetail is turned on, this information will be written - /// to monad log under log category "Pipeline execution detail" + /// to PowerShell log under log category "Pipeline execution detail" /// /// /// diff --git a/src/System.Management.Automation/engine/MshReference.cs b/src/System.Management.Automation/engine/MshReference.cs index a021e09f794..fa8b6f13583 100644 --- a/src/System.Management.Automation/engine/MshReference.cs +++ b/src/System.Management.Automation/engine/MshReference.cs @@ -8,7 +8,7 @@ namespace System.Management.Automation { /// - /// Define type for a reference object in Monad scripting language. + /// Define type for a reference object in PowerShell scripting language. /// /// /// This class is used to describe both kinds of references: diff --git a/src/System.Management.Automation/engine/cmdlet.cs b/src/System.Management.Automation/engine/cmdlet.cs index 20e04a7bd21..612705e6d95 100644 --- a/src/System.Management.Automation/engine/cmdlet.cs +++ b/src/System.Management.Automation/engine/cmdlet.cs @@ -511,7 +511,7 @@ public void WriteWarning(string text) /// pipeline execution log. /// /// If LogPipelineExecutionDetail is turned on, this information will be written - /// to monad log under log category "Pipeline execution detail" + /// to PowerShell log under log category "Pipeline execution detail" /// /// /// diff --git a/src/System.Management.Automation/engine/hostifaces/MshHost.cs b/src/System.Management.Automation/engine/hostifaces/MshHost.cs index 7e9a5a81877..ea5449f5325 100644 --- a/src/System.Management.Automation/engine/hostifaces/MshHost.cs +++ b/src/System.Management.Automation/engine/hostifaces/MshHost.cs @@ -79,7 +79,7 @@ public abstract string Name /// /// /// When implementing this member, it should return the product version number for the product - /// that is hosting the Monad engine. + /// that is hosting the PowerShell engine. /// /// /// The version number of the hosting application. diff --git a/src/System.Management.Automation/engine/serialization.cs b/src/System.Management.Automation/engine/serialization.cs index a5ad0091db3..198f10e45f3 100644 --- a/src/System.Management.Automation/engine/serialization.cs +++ b/src/System.Management.Automation/engine/serialization.cs @@ -6628,7 +6628,6 @@ namespace Microsoft.PowerShell /// - PropertySerializationSet= /// - TargetTypeForDeserialization=DeserializingTypeConverter /// - Add a field of that type in unit tests / S.M.A.Test.SerializationTest+RehydratedType - /// (testsrc\admintest\monad\DRT\engine\UnitTests\SerializationTest.cs) /// --> public sealed class DeserializingTypeConverter : PSTypeConverter { diff --git a/src/System.Management.Automation/namespaces/ItemProviderBase.cs b/src/System.Management.Automation/namespaces/ItemProviderBase.cs index 57754273db7..e282093de49 100644 --- a/src/System.Management.Automation/namespaces/ItemProviderBase.cs +++ b/src/System.Management.Automation/namespaces/ItemProviderBase.cs @@ -12,11 +12,11 @@ namespace System.Management.Automation.Provider /// /// /// The ItemCmdletProvider class is a base class that a provider derives from to - /// inherit a set of methods that allows the Monad engine + /// inherit a set of methods that allows the PowerShell engine /// to provide a core set of commands for getting and setting of data on one or /// more items. A provider should derive from this class if they want /// to take advantage of the item core commands that are - /// already implemented by the Monad engine. This allows users to have common + /// already implemented by the engine. This allows users to have common /// commands and semantics across multiple providers. /// public abstract class ItemCmdletProvider : DriveCmdletProvider diff --git a/src/System.Management.Automation/namespaces/ProviderDeclarationAttribute.cs b/src/System.Management.Automation/namespaces/ProviderDeclarationAttribute.cs index d0c7bd018a1..0601adce6be 100644 --- a/src/System.Management.Automation/namespaces/ProviderDeclarationAttribute.cs +++ b/src/System.Management.Automation/namespaces/ProviderDeclarationAttribute.cs @@ -77,30 +77,30 @@ public enum ProviderCapabilities { /// /// The provider does not add any additional capabilities beyond what the - /// Monad engine provides. + /// PowerShell engine provides. /// None = 0x0, /// /// The provider does the inclusion filtering for those commands that take an Include - /// parameter. The Monad engine should not try to do the filtering on behalf of this + /// parameter. The PowerShell engine should not try to do the filtering on behalf of this /// provider. /// /// /// Note, the provider should make every effort to filter in a way that is consistent - /// with the Monad engine. This option is allowed because in many cases the provider + /// with the PowerShell engine. This option is allowed because in many cases the provider /// can be much more efficient at filtering. /// Include = 0x1, /// /// The provider does the exclusion filtering for those commands that take an Exclude - /// parameter. The Monad engine should not try to do the filtering on behalf of this + /// parameter. The PowerShell engine should not try to do the filtering on behalf of this /// provider. /// /// /// Note, the provider should make every effort to filter in a way that is consistent - /// with the Monad engine. This option is allowed because in many cases the provider + /// with the PowerShell engine. This option is allowed because in many cases the provider /// can be much more efficient at filtering. /// Exclude = 0x2, @@ -111,18 +111,18 @@ public enum ProviderCapabilities /// /// When this attribute is specified a provider specific filter can be passed from /// the Core Commands to the provider. This filter string is not interpreted in any - /// way by the Monad engine. + /// way by the PowerShell engine. /// Filter = 0x4, /// - /// The provider does the wildcard matching for those commands that allow for it. The Monad + /// The provider does the wildcard matching for those commands that allow for it. The PowerShell /// engine should not try to do the wildcard matching on behalf of the provider when this /// flag is set. /// /// /// Note, the provider should make every effort to do the wildcard matching in a way that is consistent - /// with the Monad engine. This option is allowed because in many cases wildcard matching + /// with the PowerShell engine. This option is allowed because in many cases wildcard matching /// cannot occur via the path name or because the provider can do the matching in a much more /// efficient manner. /// diff --git a/src/System.Management.Automation/security/SecurityManager.cs b/src/System.Management.Automation/security/SecurityManager.cs index 25fb544507b..2baf1560a38 100644 --- a/src/System.Management.Automation/security/SecurityManager.cs +++ b/src/System.Management.Automation/security/SecurityManager.cs @@ -19,7 +19,7 @@ namespace Microsoft.PowerShell { /// /// Defines the authorization policy that controls the way scripts - /// (and other command types) are handled by Monad. This authorization + /// (and other command types) are handled by PowerShell. This authorization /// policy enforces one of four levels, as defined by the 'ExecutionPolicy' /// value in one of the following locations: /// @@ -40,14 +40,14 @@ namespace Microsoft.PowerShell /// signed, and by a trusted publisher. If you haven't made a trust decision /// on the publisher yet, prompting is done as in AllSigned mode. /// AllSigned - All .ps1 and .ps1xml files must be digitally signed. If - /// signed and executed, Monad prompts to determine if files from the + /// signed and executed, PowerShell prompts to determine if files from the /// signing publisher should be run or not. /// RemoteSigned - Only .ps1 and .ps1xml files originating from the internet - /// must be digitally signed. If remote, signed, and executed, Monad + /// must be digitally signed. If remote, signed, and executed, PowerShell /// prompts to determine if files from the signing publisher should be /// run or not. This is the default setting. /// Unrestricted - No files must be signed. If a file originates from the - /// internet, Monad provides a warning prompt to alert the user. To + /// internet, PowerShell provides a warning prompt to alert the user. To /// suppress this warning message, right-click on the file in File Explorer, /// select "Properties," and then "Unblock." Requires Shell. /// Bypass - No files must be signed, and internet origin is not verified. diff --git a/src/System.Management.Automation/security/SecuritySupport.cs b/src/System.Management.Automation/security/SecuritySupport.cs index 74fb58350d3..9492b1eaaf1 100644 --- a/src/System.Management.Automation/security/SecuritySupport.cs +++ b/src/System.Management.Automation/security/SecuritySupport.cs @@ -32,19 +32,19 @@ namespace Microsoft.PowerShell public enum ExecutionPolicy { /// Unrestricted - No files must be signed. If a file originates from the - /// internet, Monad provides a warning prompt to alert the user. To + /// internet, PowerShell provides a warning prompt to alert the user. To /// suppress this warning message, right-click on the file in File Explorer, /// select "Properties," and then "Unblock." Unrestricted = 0, /// RemoteSigned - Only .ps1 and .ps1xml files originating from the internet - /// must be digitally signed. If remote, signed, and executed, Monad + /// must be digitally signed. If remote, signed, and executed, PowerShell /// prompts to determine if files from the signing publisher should be /// run or not. This is the default setting. RemoteSigned = 1, /// AllSigned - All .ps1 and .ps1xml files must be digitally signed. If - /// signed and executed, Monad prompts to determine if files from the + /// signed and executed, PowerShell prompts to determine if files from the /// signing publisher should be run or not. AllSigned = 2, diff --git a/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs b/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs index 932271fce20..5cd08f18674 100644 --- a/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs +++ b/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs @@ -231,7 +231,7 @@ internal string AbsoluteModulePath } /// - /// Monad version used by PSSnapin. + /// PowerShell version used by PSSnapin. /// public Version PSVersion { get; } diff --git a/src/System.Management.Automation/utils/ExecutionExceptions.cs b/src/System.Management.Automation/utils/ExecutionExceptions.cs index ed04086101e..4c3cbb261e5 100644 --- a/src/System.Management.Automation/utils/ExecutionExceptions.cs +++ b/src/System.Management.Automation/utils/ExecutionExceptions.cs @@ -307,13 +307,13 @@ private static Exception GetInnerException(Exception e) /// user hitting CTRL-C, or by a call to /// . /// - /// When a cmdlet or provider sees this exception thrown from a Monad API such as + /// When a cmdlet or provider sees this exception thrown from a PowerShell API such as /// WriteObject(object) /// this means that the command was already stopped. The cmdlet or provider /// should clean up and return. /// Catching this exception is optional; if the cmdlet or providers chooses not to /// handle PipelineStoppedException and instead allow it to propagate to the - /// Monad Engine's call to ProcessRecord, the Monad Engine will handle it properly. + /// PowerShell Engine's call to ProcessRecord, the PowerShell Engine will handle it properly. /// [Serializable] public class PipelineStoppedException : RuntimeException @@ -616,13 +616,13 @@ public override ErrorRecord ErrorRecord #region ParentContainsErrorRecordException /// /// ParentContainsErrorRecordException is the exception contained by the ErrorRecord - /// which is associated with a Monad engine custom exception through + /// which is associated with a PowerShell engine custom exception through /// the IContainsErrorRecord interface. /// /// /// We use this exception class /// so that there is not a recursive "containment" relationship - /// between the Monad engine exception and its ErrorRecord. + /// between the PowerShell engine exception and its ErrorRecord. /// [Serializable] public class ParentContainsErrorRecordException : SystemException @@ -808,8 +808,8 @@ protected RedirectedException(SerializationInfo info, /// exceeds the configured maximum. /// /// - /// When one Monad command or script calls another, this creates an additional - /// scope. Some script expressions also create a scope. Monad imposes a maximum + /// When one PowerShell command or script calls another, this creates an additional + /// scope. Some script expressions also create a scope. PowerShell imposes a maximum /// call depth to prevent stack overflows. The maximum call depth is configurable /// but generally high enough that scripts which are not deeply recursive /// should not have a problem. diff --git a/src/System.Management.Automation/utils/MshArgumentException.cs b/src/System.Management.Automation/utils/MshArgumentException.cs index 8bc58e6c429..d1e14a92f3b 100644 --- a/src/System.Management.Automation/utils/MshArgumentException.cs +++ b/src/System.Management.Automation/utils/MshArgumentException.cs @@ -13,7 +13,7 @@ namespace System.Management.Automation /// /// /// Instances of this exception class are usually generated by the - /// Monad Engine. It is unusual for code outside the Monad Engine + /// PowerShell Engine. It is unusual for code outside the PowerShell Engine /// to create an instance of this class. /// [Serializable] diff --git a/src/System.Management.Automation/utils/MshArgumentNullException.cs b/src/System.Management.Automation/utils/MshArgumentNullException.cs index 294c91ea438..66f0a35dbbf 100644 --- a/src/System.Management.Automation/utils/MshArgumentNullException.cs +++ b/src/System.Management.Automation/utils/MshArgumentNullException.cs @@ -13,7 +13,7 @@ namespace System.Management.Automation /// /// /// Instances of this exception class are usually generated by the - /// Monad Engine. It is unusual for code outside the Monad Engine + /// PowerShell Engine. It is unusual for code outside the PowerShell Engine /// to create an instance of this class. /// [Serializable] diff --git a/src/System.Management.Automation/utils/MshArgumentOutOfRangeException.cs b/src/System.Management.Automation/utils/MshArgumentOutOfRangeException.cs index b8db294e99c..955d5009256 100644 --- a/src/System.Management.Automation/utils/MshArgumentOutOfRangeException.cs +++ b/src/System.Management.Automation/utils/MshArgumentOutOfRangeException.cs @@ -13,7 +13,7 @@ namespace System.Management.Automation /// /// /// Instances of this exception class are usually generated by the - /// Monad Engine. It is unusual for code outside the Monad Engine + /// PowerShell Engine. It is unusual for code outside the PowerShell Engine /// to create an instance of this class. /// [Serializable] diff --git a/src/System.Management.Automation/utils/MshInvalidOperationException.cs b/src/System.Management.Automation/utils/MshInvalidOperationException.cs index ff238ef20ca..520818cb405 100644 --- a/src/System.Management.Automation/utils/MshInvalidOperationException.cs +++ b/src/System.Management.Automation/utils/MshInvalidOperationException.cs @@ -13,7 +13,7 @@ namespace System.Management.Automation /// /// /// Instances of this exception class are usually generated by the - /// Monad Engine. It is unusual for code outside the Monad Engine + /// PowerShell Engine. It is unusual for code outside the PowerShell Engine /// to create an instance of this class. /// [Serializable] diff --git a/src/System.Management.Automation/utils/MshNotImplementedException.cs b/src/System.Management.Automation/utils/MshNotImplementedException.cs index e6e1d1b54eb..e939c593842 100644 --- a/src/System.Management.Automation/utils/MshNotImplementedException.cs +++ b/src/System.Management.Automation/utils/MshNotImplementedException.cs @@ -13,7 +13,7 @@ namespace System.Management.Automation /// /// /// Instances of this exception class are usually generated by the - /// Monad Engine. It is unusual for code outside the Monad Engine + /// PowerShell Engine. It is unusual for code outside the PowerShell Engine /// to create an instance of this class. /// [Serializable] diff --git a/src/System.Management.Automation/utils/MshNotSupportedException.cs b/src/System.Management.Automation/utils/MshNotSupportedException.cs index d7002f9111e..8c878660ba4 100644 --- a/src/System.Management.Automation/utils/MshNotSupportedException.cs +++ b/src/System.Management.Automation/utils/MshNotSupportedException.cs @@ -13,7 +13,7 @@ namespace System.Management.Automation /// /// /// Instances of this exception class are usually generated by the - /// Monad Engine. It is unusual for code outside the Monad Engine + /// PowerShell Engine. It is unusual for code outside the PowerShell Engine /// to create an instance of this class. /// [Serializable] diff --git a/src/System.Management.Automation/utils/MshObjectDisposedException.cs b/src/System.Management.Automation/utils/MshObjectDisposedException.cs index 8ceabb84227..af2658ed25d 100644 --- a/src/System.Management.Automation/utils/MshObjectDisposedException.cs +++ b/src/System.Management.Automation/utils/MshObjectDisposedException.cs @@ -13,7 +13,7 @@ namespace System.Management.Automation /// /// /// Instances of this exception class are usually generated by the - /// Monad Engine. It is unusual for code outside the Monad Engine + /// PowerShell Engine. It is unusual for code outside the PowerShell Engine /// to create an instance of this class. /// [Serializable] diff --git a/src/System.Management.Automation/utils/MshTraceSource.cs b/src/System.Management.Automation/utils/MshTraceSource.cs index 8ed5949c31a..25fcc7b940e 100644 --- a/src/System.Management.Automation/utils/MshTraceSource.cs +++ b/src/System.Management.Automation/utils/MshTraceSource.cs @@ -10,14 +10,14 @@ namespace System.Management.Automation { /// /// An PSTraceSource is a representation of a System.Diagnostics.TraceSource instance - /// that is used in the Monad components to produce trace output. + /// that is used in the PowerShell components to produce trace output. /// /// /// It is permitted to subclass /// but there is no established scenario for doing this, nor has it been tested. /// /// - + From ab868781e462ddb89e2b0e9039709a5d4e0ad40d Mon Sep 17 00:00:00 2001 From: Berkan Diler Date: Mon, 28 Nov 2022 20:17:22 +0100 Subject: [PATCH 225/779] Use static `DateTime.UnixEpoch` and `RandomNumberGenerator.Fill()` (#18621) --- .../commands/utility/GetDateCommand.cs | 4 +--- .../engine/hostifaces/MshHostUserInterface.cs | 4 ++-- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetDateCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetDateCommand.cs index 40e0bbeefd7..62a2d276ebf 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetDateCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetDateCommand.cs @@ -376,8 +376,6 @@ protected override void ProcessRecord() } } - private static readonly DateTime s_epoch = new(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); - /// /// This is more an implementation of the UNIX strftime. /// @@ -501,7 +499,7 @@ private string UFormatDateString(DateTime dateTime) break; case 's': - sb.Append(StringUtil.Format("{0:0}", dateTime.ToUniversalTime().Subtract(s_epoch).TotalSeconds)); + sb.Append(StringUtil.Format("{0:0}", dateTime.ToUniversalTime().Subtract(DateTime.UnixEpoch).TotalSeconds)); break; case 'T': diff --git a/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs index 452ae134602..53ca3f5617a 100644 --- a/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs @@ -1167,8 +1167,8 @@ internal static string GetTranscriptPath(string baseDirectory, bool includeDate) // bytes of randomness (2^48 = 2.8e14) would take an attacker about 891 years to guess // a filename (assuming they knew the time the transcript was started). // (5 bytes = 3 years, 4 bytes = about a month) - byte[] randomBytes = new byte[6]; - System.Security.Cryptography.RandomNumberGenerator.Create().GetBytes(randomBytes); + Span randomBytes = stackalloc byte[6]; + System.Security.Cryptography.RandomNumberGenerator.Fill(randomBytes); string filename = string.Format( Globalization.CultureInfo.InvariantCulture, "PowerShell_transcript.{0}.{1}.{2:yyyyMMddHHmmss}.txt", From 019c3b87df68d970a98f88124c46a66179361016 Mon Sep 17 00:00:00 2001 From: Ilya Date: Tue, 29 Nov 2022 00:18:04 +0500 Subject: [PATCH 226/779] Replace `DllImport` with `LibraryImport` in SMA - 7 (#18594) --- .../Interop/Windows/EventActivityIdControl.cs | 54 +++++++++++++++++++ .../utils/tracing/EtwActivity.cs | 42 +-------------- 2 files changed, 55 insertions(+), 41 deletions(-) create mode 100644 src/System.Management.Automation/engine/Interop/Windows/EventActivityIdControl.cs diff --git a/src/System.Management.Automation/engine/Interop/Windows/EventActivityIdControl.cs b/src/System.Management.Automation/engine/Interop/Windows/EventActivityIdControl.cs new file mode 100644 index 00000000000..8152a793149 --- /dev/null +++ b/src/System.Management.Automation/engine/Interop/Windows/EventActivityIdControl.cs @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +#if !UNIX +using System; +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal static partial class Windows + { + internal enum ActivityControl : uint + { + /// + /// Gets the ActivityId from thread local storage. + /// + Get = 1, + + /// + /// Sets the ActivityId in the thread local storage. + /// + Set = 2, + + /// + /// Creates a new activity id. + /// + Create = 3, + + /// + /// Sets the activity id in thread local storage and returns the previous value. + /// + GetSet = 4, + + /// + /// Creates a new activity id, sets thread local storage, and returns the previous value. + /// + CreateSet = 5 + } + + [LibraryImport("api-ms-win-eventing-provider-l1-1-0.dll")] + internal static unsafe partial int EventActivityIdControl(ActivityControl controlCode, Guid* activityId); + + internal static unsafe int GetEventActivityIdControl(ref Guid activityId) + { + fixed (Guid* guidPtr = &activityId) + { + return EventActivityIdControl(ActivityControl.Get, guidPtr); + } + } + } +} +#endif diff --git a/src/System.Management.Automation/utils/tracing/EtwActivity.cs b/src/System.Management.Automation/utils/tracing/EtwActivity.cs index dfe642ee840..6a0285682df 100644 --- a/src/System.Management.Automation/utils/tracing/EtwActivity.cs +++ b/src/System.Management.Automation/utils/tracing/EtwActivity.cs @@ -300,7 +300,7 @@ public static Guid CreateActivityId() public static Guid GetActivityId() { Guid activityId = Guid.Empty; - uint hresult = UnsafeNativeMethods.EventActivityIdControl(UnsafeNativeMethods.ActivityControlCode.Get, ref activityId); + Interop.Windows.GetEventActivityIdControl(ref activityId); return activityId; } @@ -496,46 +496,6 @@ private EventProvider GetProvider() return currentProvider; } - - private static class UnsafeNativeMethods - { - internal enum ActivityControlCode : uint - { - /// - /// Gets the ActivityId from thread local storage. - /// - Get = 1, - - /// - /// Sets the ActivityId in the thread local storage. - /// - Set = 2, - - /// - /// Creates a new activity id. - /// - Create = 3, - - /// - /// Sets the activity id in thread local storage and returns the previous value. - /// - GetSet = 4, - - /// - /// Creates a new activity id, sets thread local storage, and returns the previous value. - /// - CreateSet = 5 - } - - /// - /// Provides interop access to creating, querying and setting the current activity identifier. - /// - /// The indicating the type of operation to perform. - /// The activity id to set or retrieve. - /// Zero on success. - [DllImport(PinvokeDllNames.EventActivityIdControlDllName, ExactSpelling = true, EntryPoint = "EventActivityIdControl", CharSet = CharSet.Unicode)] - internal static extern unsafe uint EventActivityIdControl([In] ActivityControlCode controlCode, [In][Out] ref Guid activityId); - } } } From 8686612cfe08f58e42acd4b1dc030f8c38c2728a Mon Sep 17 00:00:00 2001 From: Ilya Date: Tue, 29 Nov 2022 08:08:02 +0500 Subject: [PATCH 227/779] Replace DllImport with LibraryImport in SMA 3 (#18564) --- .../engine/Interop/Windows/FindExecutable.cs | 50 +++++++++++++++ .../engine/NativeCommandProcessor.cs | 62 +++---------------- 2 files changed, 60 insertions(+), 52 deletions(-) create mode 100644 src/System.Management.Automation/engine/Interop/Windows/FindExecutable.cs diff --git a/src/System.Management.Automation/engine/Interop/Windows/FindExecutable.cs b/src/System.Management.Automation/engine/Interop/Windows/FindExecutable.cs new file mode 100644 index 00000000000..7b52c317c87 --- /dev/null +++ b/src/System.Management.Automation/engine/Interop/Windows/FindExecutable.cs @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +#if !UNIX +using System; +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal static unsafe partial class Windows + { + // The FindExecutable API is defined in shellapi.h as + // SHSTDAPI_(HINSTANCE) FindExecutableW(LPCWSTR lpFile, LPCWSTR lpDirectory, __out_ecount(MAX_PATH) LPWSTR lpResult); + // HINSTANCE is void* so we need to use IntPtr (nint) as API return value. + [LibraryImport("shell32.dll", EntryPoint = "FindExecutableW", StringMarshalling = StringMarshalling.Utf16)] + internal static partial nint FindExecutableW(string fileName, string directoryPath, char* pathFound); + + internal static string? FindExecutable(string filename) + { + string? result = null; + + // HINSTANCE == PVOID == nint + nint resultCode = 0; + + const int MAX_PATH = 260; + Span buffer = stackalloc char[MAX_PATH]; + unsafe + { + fixed (char* lpBuffer = buffer) + { + resultCode = FindExecutableW(filename, string.Empty, lpBuffer); + + // If FindExecutable returns a result > 32, then it succeeded + // and we return the string that was found, otherwise we + // return null. + if (resultCode > 32) + { + result = Marshal.PtrToStringUni((IntPtr)lpBuffer); + return result; + } + } + } + + return null; + } + } +} +#endif diff --git a/src/System.Management.Automation/engine/NativeCommandProcessor.cs b/src/System.Management.Automation/engine/NativeCommandProcessor.cs index 3e64658644b..1c43f421a9d 100644 --- a/src/System.Management.Automation/engine/NativeCommandProcessor.cs +++ b/src/System.Management.Automation/engine/NativeCommandProcessor.cs @@ -583,12 +583,18 @@ private void InitNativeProcess() } catch (Win32Exception) { - // On Unix platforms, nothing can be further done, so just throw +#if UNIX + // On Unix platforms, nothing can be further done, so just throw. + throw; +#else // On headless Windows SKUs, there is no shell to fall back to, so just throw - if (!Platform.IsWindowsDesktop) { throw; } + if (!Platform.IsWindowsDesktop) + { + throw; + } // on Windows desktops, see if there is a file association for this command. If so then we'll use that. - string executable = FindExecutable(startInfo.FileName); + string executable = Interop.Windows.FindExecutable(startInfo.FileName); bool notDone = true; // check to see what mode we should be in for argument passing if (!string.IsNullOrEmpty(executable)) @@ -650,6 +656,7 @@ private void InitNativeProcess() throw; } } +#endif } } @@ -1590,55 +1597,6 @@ private bool IsExecutable(string path) #endif } - #region Interop for FindExecutable... - - // Constant used to determine the buffer size for a path - // when looking for an executable. MAX_PATH is defined as 260 - // so this is much larger than what should be permitted - private const int MaxExecutablePath = 1024; - - // The FindExecutable API is defined in shellapi.h as - // SHSTDAPI_(HINSTANCE) FindExecutableW(LPCWSTR lpFile, LPCWSTR lpDirectory, __out_ecount(MAX_PATH) LPWSTR lpResult); - // HINSTANCE is void* so we need to use IntPtr as API return value. - - [DllImport("shell32.dll", EntryPoint = "FindExecutable")] - [SuppressMessage("Microsoft.Globalization", "CA2101:SpecifyMarshalingForPInvokeStringArguments", MessageId = "0")] - [SuppressMessage("Microsoft.Globalization", "CA2101:SpecifyMarshalingForPInvokeStringArguments", MessageId = "1")] - [SuppressMessage("Microsoft.Globalization", "CA2101:SpecifyMarshalingForPInvokeStringArguments", MessageId = "2")] - private static extern IntPtr FindExecutableW( - string fileName, string directoryPath, StringBuilder pathFound); - - private static string FindExecutable(string filename) - { - // Preallocate a - StringBuilder objResultBuffer = new StringBuilder(MaxExecutablePath); - IntPtr resultCode = (IntPtr)0; - - try - { - resultCode = FindExecutableW(filename, string.Empty, objResultBuffer); - } - catch (System.IndexOutOfRangeException e) - { - // If we got an index-out-of-range exception here, it's because - // of a buffer overrun error so we fail fast instead of - // continuing to run in an possibly unstable environment.... - Environment.FailFast(e.Message, e); - } - - // If FindExecutable returns a result >= 32, then it succeeded - // and we return the string that was found, otherwise we - // return null. - if ((long)resultCode >= 32) - { - return objResultBuffer.ToString(); - } - - return null; - } - - #endregion - #region Minishell Interop private bool _isMiniShell = false; From d03a5553c237c39dcbe7fac0c1d39eef9f140ec6 Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Tue, 29 Nov 2022 08:41:12 -0800 Subject: [PATCH 228/779] Fix `Start-Job` to check the existence of working directory using the PowerShell way (#18675) * Fix `Start-Job` to check the existence of working directory using the PowerShell way * Add a test * Update * Fix the test --- .../engine/remoting/commands/StartJob.cs | 4 ++-- test/powershell/engine/Job/Jobs.Tests.ps1 | 15 +++++++++++++-- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/src/System.Management.Automation/engine/remoting/commands/StartJob.cs b/src/System.Management.Automation/engine/remoting/commands/StartJob.cs index ff7b844d7fa..3a2f5d6d55d 100644 --- a/src/System.Management.Automation/engine/remoting/commands/StartJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/StartJob.cs @@ -484,7 +484,7 @@ public virtual ScriptBlock InitializationScript /// Gets or sets an initial working directory for the powershell background job. /// [Parameter] - [ValidateNotNullOrEmpty] + [ValidateNotNullOrWhiteSpace] public string WorkingDirectory { get; set; } /// @@ -601,7 +601,7 @@ protected override void BeginProcessing() ThrowTerminatingError(errorRecord); } - if (WorkingDirectory != null && !Directory.Exists(WorkingDirectory)) + if (WorkingDirectory != null && !InvokeProvider.Item.IsContainer(WorkingDirectory)) { string message = StringUtil.Format(RemotingErrorIdStrings.StartJobWorkingDirectoryNotFound, WorkingDirectory); var errorRecord = new ErrorRecord( diff --git a/test/powershell/engine/Job/Jobs.Tests.ps1 b/test/powershell/engine/Job/Jobs.Tests.ps1 index 61765b3f9bd..df292db2a1a 100644 --- a/test/powershell/engine/Job/Jobs.Tests.ps1 +++ b/test/powershell/engine/Job/Jobs.Tests.ps1 @@ -86,6 +86,17 @@ Describe 'Basic Job Tests' -Tags 'Feature' { $jobOutput | Should -BeExactly $path.ToString() } + It 'Can specify the working directory with a PSPath' { + try { + Push-Location 'Temp:\' + $job = Start-Job -ScriptBlock { $PWD } -WorkingDirectory $pwd.Path | Wait-Job + $jobOutput = Receive-Job $job + $jobOutput | Should -BeExactly $pwd.Path + } finally { + Pop-Location + } + } + It 'Can use the user specified working directory parameter with quote' -Skip:($IsWindows) { $path = Join-Path -Path $TestDrive -ChildPath "My ""Dir" $null = New-Item -ItemType Directory -Path "$path" @@ -100,9 +111,9 @@ Describe 'Basic Job Tests' -Tags 'Feature' { } It 'Throws an error when the working directory parameter is ' -TestCases $invalidPathTestCases { - param($path, $case, $expectedErrorId) + param($path, $case, $errorId) - {Start-Job -ScriptBlock { 1 + 1 } -WorkingDirectory $path} | Should -Throw -ErrorId $expectedErrorId + {Start-Job -ScriptBlock { 1 + 1 } -WorkingDirectory $path} | Should -Throw -ErrorId $errorId } It 'Verifies that the current working directory is preserved' { From 52ea41966297c2972313fca1ebdec537ada3eac7 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Tue, 29 Nov 2022 16:13:59 -0800 Subject: [PATCH 229/779] Add `Dim` and `DimOff` to `$PSStyle` (#18653) --- .../DefaultFormatters/PowerShellCore_format_ps1xml.cs | 2 ++ .../FormatAndOutput/common/PSStyle.cs | 10 ++++++++++ test/powershell/engine/Formatting/PSStyle.Tests.ps1 | 4 ++++ 3 files changed, 16 insertions(+) diff --git a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs index 7b184cd9a4f..72a1c870cd7 100644 --- a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs +++ b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs @@ -2027,6 +2027,8 @@ private static IEnumerable ViewsOf_System_Management_Autom .AddItemScriptBlock(@"""$($_.Blink)$($_.Blink.Replace(""""`e"""",'`e'))$($_.Reset)""", label: "Blink") .AddItemScriptBlock(@"""$($_.BoldOff)$($_.BoldOff.Replace(""""`e"""",'`e'))$($_.Reset)""", label: "BoldOff") .AddItemScriptBlock(@"""$($_.Bold)$($_.Bold.Replace(""""`e"""",'`e'))$($_.Reset)""", label: "Bold") + .AddItemScriptBlock(@"""$($_.DimOff)$($_.DimOff.Replace(""""`e"""",'`e'))$($_.Reset)""", label: "DimOff") + .AddItemScriptBlock(@"""$($_.Dim)$($_.Dim.Replace(""""`e"""",'`e'))$($_.Reset)""", label: "Dim") .AddItemScriptBlock(@"""$($_.Hidden)$($_.Hidden.Replace(""""`e"""",'`e'))$($_.Reset)""", label: "Hidden") .AddItemScriptBlock(@"""$($_.HiddenOff)$($_.HiddenOff.Replace(""""`e"""",'`e'))$($_.Reset)""", label: "HiddenOff") .AddItemScriptBlock(@"""$($_.Reverse)$($_.Reverse.Replace(""""`e"""",'`e'))$($_.Reset)""", label: "Reverse") diff --git a/src/System.Management.Automation/FormatAndOutput/common/PSStyle.cs b/src/System.Management.Automation/FormatAndOutput/common/PSStyle.cs index ec3955c29bc..59626f91599 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/PSStyle.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/PSStyle.cs @@ -652,6 +652,16 @@ public FileInfoFormatting() /// public string Bold { get; } = "\x1b[1m"; + /// + /// Gets value to turn off dim. + /// + public string DimOff { get; } = "\x1b[22m"; + + /// + /// Gets value to turn on dim. + /// + public string Dim { get; } = "\x1b[2m"; + /// /// Gets value to turn on hidden. /// diff --git a/test/powershell/engine/Formatting/PSStyle.Tests.ps1 b/test/powershell/engine/Formatting/PSStyle.Tests.ps1 index 725fc400cf3..ba7910cb942 100644 --- a/test/powershell/engine/Formatting/PSStyle.Tests.ps1 +++ b/test/powershell/engine/Formatting/PSStyle.Tests.ps1 @@ -9,6 +9,8 @@ Describe 'Tests for $PSStyle automatic variable' -Tag 'CI' { Blink = "`e[5m" BoldOff = "`e[22m" Bold = "`e[1m" + DimOff = "`e[22m" + Dim = "`e[2m" HiddenOff = "`e[28m" Hidden = "`e[8m" ReverseOff = "`e[27m" @@ -225,6 +227,8 @@ Describe 'Tests for $PSStyle automatic variable' -Tag 'CI' { @{ Submember = 'Blink' } @{ Submember = 'BoldOff' } @{ Submember = 'Bold' } + @{ Submember = 'DimOff' } + @{ Submember = 'Dim' } @{ Submember = 'HiddenOff' } @{ Submember = 'Hidden' } @{ Submember = 'ItalicOff' } From 3dc95ced87d38c347a9fc3a222eb4c52eaad4615 Mon Sep 17 00:00:00 2001 From: Ilya Date: Wed, 30 Nov 2022 23:00:12 +0500 Subject: [PATCH 230/779] Replace `DllImport` with `LibraryImport` - 1 (#18603) --- .../CoreCLR/CorePsPlatform.cs | 24 +-- .../System.Management.Automation.csproj | 8 +- .../CommandCompletion/CompletionCompleters.cs | 39 ++--- .../engine/Interop/Windows/AllocConsole.cs | 16 ++ .../engine/Interop/Windows/CoInitializeEx.cs | 18 ++ .../engine/Interop/Windows/CoUninitialize.cs | 15 ++ .../engine/Interop/Windows/CreateHardLink.cs | 16 ++ .../Interop/Windows/CreateSymbolicLink.cs | 25 +++ .../engine/Interop/Windows/FindClose.cs | 16 ++ .../engine/Interop/Windows/FindFirstFile.cs | 55 ++++++ .../Interop/Windows/GetConsoleWindow.cs | 15 ++ .../Interop/Windows/GetCurrentThreadId.cs | 2 - .../Interop/Windows/GetForegroundWindow.cs | 15 ++ .../engine/Interop/Windows/GetOEMCP.cs | 15 ++ .../engine/Interop/Windows/NetShareEnum.cs | 28 ++++ .../Windows/NtQueryInformationProcess.cs | 31 ++++ .../engine/Interop/Windows/QueryDosDevice.cs | 2 - ...ueryProcessPlaceholderCompatibilityMode.cs | 25 +++ .../engine/Interop/Windows/SHGetFileInfo.cs | 2 - .../Interop/Windows/SetForegroundWindow.cs | 16 ++ .../engine/Interop/Windows/ShowWindow.cs | 32 ++++ .../engine/Interop/Windows/VariantClear.cs | 2 - .../Interop/Windows/WNetCancelConnection2.cs | 15 ++ .../engine/NativeCommandProcessor.cs | 114 ++----------- .../engine/ProcessCodeMethods.cs | 26 +-- .../namespaces/FileSystemProvider.cs | 157 ++---------------- .../utils/ClrFacade.cs | 17 +- 27 files changed, 413 insertions(+), 333 deletions(-) create mode 100644 src/System.Management.Automation/engine/Interop/Windows/AllocConsole.cs create mode 100644 src/System.Management.Automation/engine/Interop/Windows/CoInitializeEx.cs create mode 100644 src/System.Management.Automation/engine/Interop/Windows/CoUninitialize.cs create mode 100644 src/System.Management.Automation/engine/Interop/Windows/CreateHardLink.cs create mode 100644 src/System.Management.Automation/engine/Interop/Windows/CreateSymbolicLink.cs create mode 100644 src/System.Management.Automation/engine/Interop/Windows/FindClose.cs create mode 100644 src/System.Management.Automation/engine/Interop/Windows/FindFirstFile.cs create mode 100644 src/System.Management.Automation/engine/Interop/Windows/GetConsoleWindow.cs create mode 100644 src/System.Management.Automation/engine/Interop/Windows/GetForegroundWindow.cs create mode 100644 src/System.Management.Automation/engine/Interop/Windows/GetOEMCP.cs create mode 100644 src/System.Management.Automation/engine/Interop/Windows/NetShareEnum.cs create mode 100644 src/System.Management.Automation/engine/Interop/Windows/NtQueryInformationProcess.cs create mode 100644 src/System.Management.Automation/engine/Interop/Windows/RtlQueryProcessPlaceholderCompatibilityMode.cs create mode 100644 src/System.Management.Automation/engine/Interop/Windows/SetForegroundWindow.cs create mode 100644 src/System.Management.Automation/engine/Interop/Windows/ShowWindow.cs create mode 100644 src/System.Management.Automation/engine/Interop/Windows/WNetCancelConnection2.cs diff --git a/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs b/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs index 8f379acc717..39ba394842a 100644 --- a/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs +++ b/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs @@ -163,19 +163,16 @@ public static bool IsStaSupported private static readonly Lazy _isStaSupported = new Lazy(() => { - // See objbase.h - const int COINIT_APARTMENTTHREADED = 0x2; - const int E_NOTIMPL = unchecked((int)0X80004001); - int result = Windows.NativeMethods.CoInitializeEx(IntPtr.Zero, COINIT_APARTMENTTHREADED); + int result = Interop.Windows.CoInitializeEx(IntPtr.Zero, Interop.Windows.COINIT_APARTMENTTHREADED); // If 0 is returned the thread has been initialized for the first time // as an STA and thus supported and needs to be uninitialized. if (result > 0) { - Windows.NativeMethods.CoUninitialize(); + Interop.Windows.CoUninitialize(); } - return result != E_NOTIMPL; + return result != Interop.Windows.E_NOTIMPL; }); private static bool? _isNanoServer = null; @@ -453,21 +450,6 @@ internal static int NonWindowsWaitPid(int pid, bool nohang) return Unix.NativeMethods.WaitPid(pid, nohang); } - internal static partial class Windows - { - /// The native methods class. - internal static partial class NativeMethods - { - private const string ole32Lib = "api-ms-win-core-com-l1-1-0.dll"; - - [LibraryImport(ole32Lib)] - internal static partial int CoInitializeEx(IntPtr reserve, int coinit); - - [LibraryImport(ole32Lib)] - internal static partial void CoUninitialize(); - } - } - // Please note that `Win32Exception(Marshal.GetLastWin32Error())` // works *correctly* on Linux in that it creates an exception with // the string perror would give you for the last set value of errno. diff --git a/src/System.Management.Automation/System.Management.Automation.csproj b/src/System.Management.Automation/System.Management.Automation.csproj index 115e6ab3540..97d6416128d 100644 --- a/src/System.Management.Automation/System.Management.Automation.csproj +++ b/src/System.Management.Automation/System.Management.Automation.csproj @@ -86,10 +86,11 @@ - - + + + @@ -97,4 +98,7 @@ + + + diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs index 60a2c31124c..467526a0158 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs @@ -30,7 +30,7 @@ namespace System.Management.Automation { /// /// - public static partial class CompletionCompleters + public static class CompletionCompleters { static CompletionCompleters() { @@ -4739,47 +4739,48 @@ private struct SHARE_INFO_1 public string remark; } - private const int MAX_PREFERRED_LENGTH = -1; - private const int NERR_Success = 0; - private const int ERROR_MORE_DATA = 234; - private const int STYPE_DISKTREE = 0; - private const int STYPE_MASK = 0x000000FF; - private static readonly System.IO.EnumerationOptions _enumerationOptions = new System.IO.EnumerationOptions { MatchCasing = MatchCasing.CaseInsensitive, AttributesToSkip = 0 // Default is to skip Hidden and System files, so we clear this to retain existing behavior }; - [LibraryImport("Netapi32.dll", StringMarshalling = StringMarshalling.Utf16)] - private static partial int NetShareEnum(string serverName, int level, out IntPtr bufptr, int prefMaxLen, - out uint entriesRead, out uint totalEntries, ref uint resumeHandle); - internal static List GetFileShares(string machine, bool ignoreHidden) { #if UNIX return new List(); #else - IntPtr shBuf; - uint numEntries; + nint shBuf = nint.Zero; + uint numEntries = 0; uint totalEntries; uint resumeHandle = 0; - int result = NetShareEnum(machine, 1, out shBuf, - MAX_PREFERRED_LENGTH, out numEntries, out totalEntries, - ref resumeHandle); + int result = Interop.Windows.NetShareEnum( + machine, + level: 1, + out shBuf, + Interop.Windows.MAX_PREFERRED_LENGTH, + out numEntries, + out totalEntries, + ref resumeHandle); var shares = new List(); - if (result == NERR_Success || result == ERROR_MORE_DATA) + if (result == Interop.Windows.NERR_Success || result == Interop.Windows.ERROR_MORE_DATA) { for (int i = 0; i < numEntries; ++i) { - IntPtr curInfoPtr = (IntPtr)((long)shBuf + (Marshal.SizeOf() * i)); + nint curInfoPtr = shBuf + (Marshal.SizeOf() * i); SHARE_INFO_1 shareInfo = Marshal.PtrToStructure(curInfoPtr); - if ((shareInfo.type & STYPE_MASK) != STYPE_DISKTREE) + if ((shareInfo.type & Interop.Windows.STYPE_MASK) != Interop.Windows.STYPE_DISKTREE) + { continue; + } + if (ignoreHidden && shareInfo.netname.EndsWith('$')) + { continue; + } + shares.Add(shareInfo.netname); } } diff --git a/src/System.Management.Automation/engine/Interop/Windows/AllocConsole.cs b/src/System.Management.Automation/engine/Interop/Windows/AllocConsole.cs new file mode 100644 index 00000000000..072e5d1b18e --- /dev/null +++ b/src/System.Management.Automation/engine/Interop/Windows/AllocConsole.cs @@ -0,0 +1,16 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal static unsafe partial class Windows + { + [LibraryImport("kernel32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + internal static partial bool AllocConsole(); + } +} diff --git a/src/System.Management.Automation/engine/Interop/Windows/CoInitializeEx.cs b/src/System.Management.Automation/engine/Interop/Windows/CoInitializeEx.cs new file mode 100644 index 00000000000..a3eae4fd596 --- /dev/null +++ b/src/System.Management.Automation/engine/Interop/Windows/CoInitializeEx.cs @@ -0,0 +1,18 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal static partial class Windows + { + internal const int COINIT_APARTMENTTHREADED = 0x2; + internal const int E_NOTIMPL = unchecked((int)0X80004001); + + [LibraryImport("api-ms-win-core-com-l1-1-0.dll")] + internal static partial int CoInitializeEx(nint reserve, int coinit); + } +} diff --git a/src/System.Management.Automation/engine/Interop/Windows/CoUninitialize.cs b/src/System.Management.Automation/engine/Interop/Windows/CoUninitialize.cs new file mode 100644 index 00000000000..d872cf17f3e --- /dev/null +++ b/src/System.Management.Automation/engine/Interop/Windows/CoUninitialize.cs @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal static partial class Windows + { + [LibraryImport("api-ms-win-core-com-l1-1-0.dll")] + internal static partial void CoUninitialize(); + } +} diff --git a/src/System.Management.Automation/engine/Interop/Windows/CreateHardLink.cs b/src/System.Management.Automation/engine/Interop/Windows/CreateHardLink.cs new file mode 100644 index 00000000000..a6cbc61619e --- /dev/null +++ b/src/System.Management.Automation/engine/Interop/Windows/CreateHardLink.cs @@ -0,0 +1,16 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal static unsafe partial class Windows + { + [LibraryImport("api-ms-win-core-file-l2-1-0.dll", EntryPoint = "CreateHardLinkW", StringMarshalling = StringMarshalling.Utf16)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static partial bool CreateHardLink(string name, string existingFileName, nint securityAttributes); + } +} diff --git a/src/System.Management.Automation/engine/Interop/Windows/CreateSymbolicLink.cs b/src/System.Management.Automation/engine/Interop/Windows/CreateSymbolicLink.cs new file mode 100644 index 00000000000..2c4995d8786 --- /dev/null +++ b/src/System.Management.Automation/engine/Interop/Windows/CreateSymbolicLink.cs @@ -0,0 +1,25 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System; +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal static unsafe partial class Windows + { + [Flags] + internal enum SymbolicLinkFlags + { + File = 0, + Directory = 1, + AllowUnprivilegedCreate = 2, + } + + [LibraryImport("api-ms-win-core-file-l2-1-0.dll", EntryPoint = "CreateSymbolicLinkW", StringMarshalling = StringMarshalling.Utf16)] + [return: MarshalAs(UnmanagedType.I1)] + internal static partial bool CreateSymbolicLink(string name, string destination, SymbolicLinkFlags symbolicLinkFlags); + } +} diff --git a/src/System.Management.Automation/engine/Interop/Windows/FindClose.cs b/src/System.Management.Automation/engine/Interop/Windows/FindClose.cs new file mode 100644 index 00000000000..a5903c72c70 --- /dev/null +++ b/src/System.Management.Automation/engine/Interop/Windows/FindClose.cs @@ -0,0 +1,16 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal static unsafe partial class Windows + { + [LibraryImport("api-ms-win-core-file-l1-1-0.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + internal static partial bool FindClose(nint handle); + } +} diff --git a/src/System.Management.Automation/engine/Interop/Windows/FindFirstFile.cs b/src/System.Management.Automation/engine/Interop/Windows/FindFirstFile.cs new file mode 100644 index 00000000000..b3cd84b028e --- /dev/null +++ b/src/System.Management.Automation/engine/Interop/Windows/FindFirstFile.cs @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System.Diagnostics.CodeAnalysis; +using System.Runtime.InteropServices; + +using Microsoft.Win32.SafeHandles; + +internal static partial class Interop +{ + [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1305:FieldNamesMustNotUseHungarianNotation", Justification = "Keep native struct names.")] + [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1307:AccessibleFieldsMustBeginWithUpperCaseLetter", Justification = "Keep native struct names.")] + internal static unsafe partial class Windows + { + internal const int MAX_PATH = 260; + + internal struct FILE_TIME + { + public uint dwLowDateTime; + public uint dwHighDateTime; + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + internal unsafe struct WIN32_FIND_DATA + { + internal uint dwFileAttributes; + internal FILE_TIME ftCreationTime; + internal FILE_TIME ftLastAccessTime; + internal FILE_TIME ftLastWriteTime; + internal uint nFileSizeHigh; + internal uint nFileSizeLow; + internal uint dwReserved0; + internal uint dwReserved1; + internal fixed char cFileName[MAX_PATH]; + internal fixed char cAlternateFileName[14]; + } + + internal sealed class SafeFindHandle : SafeHandleZeroOrMinusOneIsInvalid + { + private SafeFindHandle() : base(true) { } + + protected override bool ReleaseHandle() + { + return Interop.Windows.FindClose(this.handle); + } + } + + // We use 'FindFirstFileW' instead of 'FindFirstFileExW' because the latter doesn't work correctly with Unicode file names on FAT32. + // See https://github.com/PowerShell/PowerShell/issues/16804 + [LibraryImport("api-ms-win-core-file-l1-1-0.dll", EntryPoint = "FindFirstFileW", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)] + internal static partial SafeFindHandle FindFirstFile(string lpFileName, ref WIN32_FIND_DATA lpFindFileData); + } +} diff --git a/src/System.Management.Automation/engine/Interop/Windows/GetConsoleWindow.cs b/src/System.Management.Automation/engine/Interop/Windows/GetConsoleWindow.cs new file mode 100644 index 00000000000..60d9229ea64 --- /dev/null +++ b/src/System.Management.Automation/engine/Interop/Windows/GetConsoleWindow.cs @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal static unsafe partial class Windows + { + [LibraryImport("Kernel32.dll")] + internal static partial nint GetConsoleWindow(); + } +} diff --git a/src/System.Management.Automation/engine/Interop/Windows/GetCurrentThreadId.cs b/src/System.Management.Automation/engine/Interop/Windows/GetCurrentThreadId.cs index 84da911898d..80a0c7a4c43 100644 --- a/src/System.Management.Automation/engine/Interop/Windows/GetCurrentThreadId.cs +++ b/src/System.Management.Automation/engine/Interop/Windows/GetCurrentThreadId.cs @@ -3,7 +3,6 @@ #nullable enable -#if !UNIX using System.Runtime.InteropServices; internal static partial class Interop @@ -14,4 +13,3 @@ internal static partial class Windows internal static partial uint GetCurrentThreadId(); } } -#endif diff --git a/src/System.Management.Automation/engine/Interop/Windows/GetForegroundWindow.cs b/src/System.Management.Automation/engine/Interop/Windows/GetForegroundWindow.cs new file mode 100644 index 00000000000..2ba57535162 --- /dev/null +++ b/src/System.Management.Automation/engine/Interop/Windows/GetForegroundWindow.cs @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal static unsafe partial class Windows + { + [LibraryImport("user32.dll")] + internal static partial nint GetForegroundWindow(); + } +} diff --git a/src/System.Management.Automation/engine/Interop/Windows/GetOEMCP.cs b/src/System.Management.Automation/engine/Interop/Windows/GetOEMCP.cs new file mode 100644 index 00000000000..4267deb1167 --- /dev/null +++ b/src/System.Management.Automation/engine/Interop/Windows/GetOEMCP.cs @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal static unsafe partial class Windows + { + [LibraryImport("api-ms-win-core-localization-l1-2-0.dll")] + internal static partial uint GetOEMCP(); + } +} diff --git a/src/System.Management.Automation/engine/Interop/Windows/NetShareEnum.cs b/src/System.Management.Automation/engine/Interop/Windows/NetShareEnum.cs new file mode 100644 index 00000000000..c3b430dec14 --- /dev/null +++ b/src/System.Management.Automation/engine/Interop/Windows/NetShareEnum.cs @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal static unsafe partial class Windows + { + internal const int MAX_PREFERRED_LENGTH = -1; + internal const int NERR_Success = 0; + internal const int ERROR_MORE_DATA = 234; + internal const int STYPE_DISKTREE = 0; + internal const int STYPE_MASK = 0x000000FF; + + [LibraryImport("Netapi32.dll", StringMarshalling = StringMarshalling.Utf16)] + internal static partial int NetShareEnum( + string serverName, + int level, + out nint bufptr, + int prefMaxLen, + out uint entriesRead, + out uint totalEntries, + ref uint resumeHandle); + } +} diff --git a/src/System.Management.Automation/engine/Interop/Windows/NtQueryInformationProcess.cs b/src/System.Management.Automation/engine/Interop/Windows/NtQueryInformationProcess.cs new file mode 100644 index 00000000000..1a839529737 --- /dev/null +++ b/src/System.Management.Automation/engine/Interop/Windows/NtQueryInformationProcess.cs @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal static unsafe partial class Windows + { + [StructLayout(LayoutKind.Sequential)] + internal struct PROCESS_BASIC_INFORMATION + { + public nint ExitStatus; + public nint PebBaseAddress; + public nint AffinityMask; + public nint BasePriority; + public nint UniqueProcessId; + public nint InheritedFromUniqueProcessId; + } + + [LibraryImport("ntdll.dll")] + internal static partial int NtQueryInformationProcess( + nint processHandle, + int processInformationClass, + out PROCESS_BASIC_INFORMATION processInformation, + int processInformationLength, + out int returnLength); + } +} diff --git a/src/System.Management.Automation/engine/Interop/Windows/QueryDosDevice.cs b/src/System.Management.Automation/engine/Interop/Windows/QueryDosDevice.cs index 670c6254cf3..419a4ef127b 100644 --- a/src/System.Management.Automation/engine/Interop/Windows/QueryDosDevice.cs +++ b/src/System.Management.Automation/engine/Interop/Windows/QueryDosDevice.cs @@ -3,7 +3,6 @@ #nullable enable -#if !UNIX using System; using System.Buffers; using System.ComponentModel; @@ -123,4 +122,3 @@ internal static string GetDosDeviceForNetworkPath(char deviceName) } } } -#endif diff --git a/src/System.Management.Automation/engine/Interop/Windows/RtlQueryProcessPlaceholderCompatibilityMode.cs b/src/System.Management.Automation/engine/Interop/Windows/RtlQueryProcessPlaceholderCompatibilityMode.cs new file mode 100644 index 00000000000..9e82f2c66c1 --- /dev/null +++ b/src/System.Management.Automation/engine/Interop/Windows/RtlQueryProcessPlaceholderCompatibilityMode.cs @@ -0,0 +1,25 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal static unsafe partial class Windows + { + internal const sbyte PHCM_APPLICATION_DEFAULT = 0; + internal const sbyte PHCM_DISGUISE_PLACEHOLDER = 1; + internal const sbyte PHCM_EXPOSE_PLACEHOLDERS = 2; + internal const sbyte PHCM_MAX = 2; + internal const sbyte PHCM_ERROR_INVALID_PARAMETER = -1; + internal const sbyte PHCM_ERROR_NO_TEB = -2; + + [LibraryImport("ntdll.dll")] + internal static partial sbyte RtlQueryProcessPlaceholderCompatibilityMode(); + + [LibraryImport("ntdll.dll")] + internal static partial sbyte RtlSetProcessPlaceholderCompatibilityMode(sbyte pcm); + } +} diff --git a/src/System.Management.Automation/engine/Interop/Windows/SHGetFileInfo.cs b/src/System.Management.Automation/engine/Interop/Windows/SHGetFileInfo.cs index 5843a1c639a..a6deaa39c41 100644 --- a/src/System.Management.Automation/engine/Interop/Windows/SHGetFileInfo.cs +++ b/src/System.Management.Automation/engine/Interop/Windows/SHGetFileInfo.cs @@ -3,7 +3,6 @@ #nullable enable -#if !UNIX using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; @@ -37,4 +36,3 @@ internal static int SHGetFileInfo(string pszPath) } } } -#endif diff --git a/src/System.Management.Automation/engine/Interop/Windows/SetForegroundWindow.cs b/src/System.Management.Automation/engine/Interop/Windows/SetForegroundWindow.cs new file mode 100644 index 00000000000..5945fac9608 --- /dev/null +++ b/src/System.Management.Automation/engine/Interop/Windows/SetForegroundWindow.cs @@ -0,0 +1,16 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal static unsafe partial class Windows + { + [LibraryImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + internal static partial bool SetForegroundWindow(nint hWnd); + } +} diff --git a/src/System.Management.Automation/engine/Interop/Windows/ShowWindow.cs b/src/System.Management.Automation/engine/Interop/Windows/ShowWindow.cs new file mode 100644 index 00000000000..d33b0a0e244 --- /dev/null +++ b/src/System.Management.Automation/engine/Interop/Windows/ShowWindow.cs @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal static unsafe partial class Windows + { + internal const int SW_HIDE = 0; + internal const int SW_SHOWNORMAL = 1; + internal const int SW_NORMAL = 1; + internal const int SW_SHOWMINIMIZED = 2; + internal const int SW_SHOWMAXIMIZED = 3; + internal const int SW_MAXIMIZE = 3; + internal const int SW_SHOWNOACTIVATE = 4; + internal const int SW_SHOW = 5; + internal const int SW_MINIMIZE = 6; + internal const int SW_SHOWMINNOACTIVE = 7; + internal const int SW_SHOWNA = 8; + internal const int SW_RESTORE = 9; + internal const int SW_SHOWDEFAULT = 10; + internal const int SW_FORCEMINIMIZE = 11; + internal const int SW_MAX = 11; + + [LibraryImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + internal static partial bool ShowWindow(nint hWnd, int nCmdShow); + } +} diff --git a/src/System.Management.Automation/engine/Interop/Windows/VariantClear.cs b/src/System.Management.Automation/engine/Interop/Windows/VariantClear.cs index a3c0ce70d8c..414a0912c81 100644 --- a/src/System.Management.Automation/engine/Interop/Windows/VariantClear.cs +++ b/src/System.Management.Automation/engine/Interop/Windows/VariantClear.cs @@ -3,7 +3,6 @@ #nullable enable -#if !UNIX using System.Runtime.InteropServices; internal static partial class Interop @@ -14,4 +13,3 @@ internal static partial class Windows internal static partial void VariantClear(nint pVariant); } } -#endif diff --git a/src/System.Management.Automation/engine/Interop/Windows/WNetCancelConnection2.cs b/src/System.Management.Automation/engine/Interop/Windows/WNetCancelConnection2.cs new file mode 100644 index 00000000000..841fdc7f129 --- /dev/null +++ b/src/System.Management.Automation/engine/Interop/Windows/WNetCancelConnection2.cs @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal static unsafe partial class Windows + { + [LibraryImport("mpr.dll", EntryPoint = "WNetCancelConnection2W", StringMarshalling = StringMarshalling.Utf16)] + internal static partial int WNetCancelConnection2(string driveName, int flags, [MarshalAs(UnmanagedType.Bool)] bool force); + } +} diff --git a/src/System.Management.Automation/engine/NativeCommandProcessor.cs b/src/System.Management.Automation/engine/NativeCommandProcessor.cs index 1c43f421a9d..ecf5e79de14 100644 --- a/src/System.Management.Automation/engine/NativeCommandProcessor.cs +++ b/src/System.Management.Automation/engine/NativeCommandProcessor.cs @@ -2078,66 +2078,13 @@ internal void Done() /// Static class that allows you to show and hide the console window /// associated with this process. /// - internal static partial class ConsoleVisibility + internal static class ConsoleVisibility { /// /// If set to true, then native commands will always be run redirected... /// public static bool AlwaysCaptureApplicationIO { get; set; } - [LibraryImport("Kernel32.dll")] - internal static partial IntPtr GetConsoleWindow(); - - internal const int SW_HIDE = 0; - internal const int SW_SHOWNORMAL = 1; - internal const int SW_NORMAL = 1; - internal const int SW_SHOWMINIMIZED = 2; - internal const int SW_SHOWMAXIMIZED = 3; - internal const int SW_MAXIMIZE = 3; - internal const int SW_SHOWNOACTIVATE = 4; - internal const int SW_SHOW = 5; - internal const int SW_MINIMIZE = 6; - internal const int SW_SHOWMINNOACTIVE = 7; - internal const int SW_SHOWNA = 8; - internal const int SW_RESTORE = 9; - internal const int SW_SHOWDEFAULT = 10; - internal const int SW_FORCEMINIMIZE = 11; - internal const int SW_MAX = 11; - - /// - /// Code to control the display properties of the a window... - /// - /// The window to show... - /// The command to do. - /// True if it was successful. - [LibraryImport("user32.dll")] - [return: MarshalAs(UnmanagedType.Bool)] - internal static partial bool ShowWindow(IntPtr hWnd, int nCmdShow); - - /// - /// Code to allocate a console... - /// - /// True if a console was created... - [LibraryImport("kernel32.dll")] - [return: MarshalAs(UnmanagedType.Bool)] - internal static partial bool AllocConsole(); - - /// - /// Called to save the foreground window before allocating a hidden console window. - /// - /// A handle to the foreground window. - [LibraryImport("user32.dll")] - private static partial IntPtr GetForegroundWindow(); - - /// - /// Called to restore the foreground window after allocating a hidden console window. - /// - /// A handle to the window that should be activated and brought to the foreground. - /// True if the window was brought to the foreground. - [LibraryImport("user32.dll")] - [return: MarshalAs(UnmanagedType.Bool)] - private static partial bool SetForegroundWindow(IntPtr hWnd); - /// /// If no console window is attached to this process, then allocate one, /// hide it and return true. If there's already a console window attached, then @@ -2146,77 +2093,44 @@ internal static partial class ConsoleVisibility /// internal static bool AllocateHiddenConsole() { +#if UNIX + return false; +#else // See if there is already a console attached. - IntPtr hwnd = ConsoleVisibility.GetConsoleWindow(); - if (hwnd != IntPtr.Zero) + IntPtr hwnd = Interop.Windows.GetConsoleWindow(); + if (hwnd != nint.Zero) { return false; } // save the foreground window since allocating a console window might remove focus from it - IntPtr savedForeground = ConsoleVisibility.GetForegroundWindow(); + IntPtr savedForeground = Interop.Windows.GetForegroundWindow(); // Since there is no console window, allocate and then hide it... // Suppress the PreFAST warning about not using Marshal.GetLastWin32Error() to // get the error code. -#pragma warning disable 56523 - ConsoleVisibility.AllocConsole(); - hwnd = ConsoleVisibility.GetConsoleWindow(); + Interop.Windows.AllocConsole(); + hwnd = Interop.Windows.GetConsoleWindow(); bool returnValue; - if (hwnd == IntPtr.Zero) + if (hwnd == nint.Zero) { returnValue = false; } else { returnValue = true; - ConsoleVisibility.ShowWindow(hwnd, ConsoleVisibility.SW_HIDE); + Interop.Windows.ShowWindow(hwnd, Interop.Windows.SW_HIDE); AlwaysCaptureApplicationIO = true; } - if (savedForeground != IntPtr.Zero && ConsoleVisibility.GetForegroundWindow() != savedForeground) + if (savedForeground != nint.Zero && Interop.Windows.GetForegroundWindow() != savedForeground) { - ConsoleVisibility.SetForegroundWindow(savedForeground); + Interop.Windows.SetForegroundWindow(savedForeground); } return returnValue; - } - - /// - /// If there is a console attached, then make it visible - /// and allow interactive console applications to be run. - /// - public static void Show() - { - IntPtr hwnd = GetConsoleWindow(); - if (hwnd != IntPtr.Zero) - { - ShowWindow(hwnd, SW_SHOW); - AlwaysCaptureApplicationIO = false; - } - else - { - throw PSTraceSource.NewInvalidOperationException(); - } - } - - /// - /// If there is a console attached, then hide it and always capture - /// output from the child process. - /// - public static void Hide() - { - IntPtr hwnd = GetConsoleWindow(); - if (hwnd != IntPtr.Zero) - { - ShowWindow(hwnd, SW_HIDE); - AlwaysCaptureApplicationIO = true; - } - else - { - throw PSTraceSource.NewInvalidOperationException(); - } +#endif } } diff --git a/src/System.Management.Automation/engine/ProcessCodeMethods.cs b/src/System.Management.Automation/engine/ProcessCodeMethods.cs index c54d992989e..68d47fbec71 100644 --- a/src/System.Management.Automation/engine/ProcessCodeMethods.cs +++ b/src/System.Management.Automation/engine/ProcessCodeMethods.cs @@ -11,7 +11,7 @@ namespace Microsoft.PowerShell /// /// Helper functions for process info. /// - public static partial class ProcessCodeMethods + public static class ProcessCodeMethods { private const int InvalidProcessId = -1; @@ -61,32 +61,12 @@ internal static int GetParentPid(Process process) internal static int GetParentPid(Process process) { Diagnostics.Assert(process != null, "Ensure process is not null before calling"); - PROCESS_BASIC_INFORMATION pbi; + Interop.Windows.PROCESS_BASIC_INFORMATION pbi; int size; - var res = NtQueryInformationProcess(process.Handle, 0, out pbi, Marshal.SizeOf(), out size); + var res = Interop.Windows.NtQueryInformationProcess(process.Handle, 0, out pbi, Marshal.SizeOf(), out size); return res != 0 ? InvalidProcessId : pbi.InheritedFromUniqueProcessId.ToInt32(); } - - [StructLayout(LayoutKind.Sequential)] - private struct PROCESS_BASIC_INFORMATION - { - public IntPtr ExitStatus; - public IntPtr PebBaseAddress; - public IntPtr AffinityMask; - public IntPtr BasePriority; - public IntPtr UniqueProcessId; - public IntPtr InheritedFromUniqueProcessId; - } - - [LibraryImport("ntdll.dll")] - private static partial int NtQueryInformationProcess( - IntPtr processHandle, - int processInformationClass, - out PROCESS_BASIC_INFORMATION processInformation, - int processInformationLength, - out int returnLength); #endif - } } diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index e13ac80fa10..6b18e44b885 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -474,9 +474,9 @@ protected override ProviderInfo Start(ProviderInfo providerInfo) if (OperatingSystem.IsWindowsVersionAtLeast(10, 0, 17134, 0)) { // let's be safe, don't change the PlaceHolderCompatibilityMode if the current one is not what we expect - if (NativeMethods.RtlQueryProcessPlaceholderCompatibilityMode() == NativeMethods.PHCM_DISGUISE_PLACEHOLDER) + if (Interop.Windows.RtlQueryProcessPlaceholderCompatibilityMode() == Interop.Windows.PHCM_DISGUISE_PLACEHOLDER) { - NativeMethods.RtlSetProcessPlaceholderCompatibilityMode(NativeMethods.PHCM_EXPOSE_PLACEHOLDERS); + Interop.Windows.RtlSetProcessPlaceholderCompatibilityMode(Interop.Windows.PHCM_EXPOSE_PLACEHOLDERS); } } #endif @@ -725,12 +725,6 @@ protected override PSDriveInfo RemoveDrive(PSDriveInfo drive) #if UNIX return drive; #else - return WinRemoveDrive(drive); -#endif - } - - private PSDriveInfo WinRemoveDrive(PSDriveInfo drive) - { if (IsNetworkMappedDrive(drive)) { const int CONNECT_UPDATE_PROFILE = 0x00000001; @@ -758,7 +752,7 @@ private PSDriveInfo WinRemoveDrive(PSDriveInfo drive) { try { - code = NativeMethods.WNetCancelConnection2(driveName, flags, true); + code = Interop.Windows.WNetCancelConnection2(driveName, flags, true); } catch (System.DllNotFoundException) { @@ -774,6 +768,7 @@ private PSDriveInfo WinRemoveDrive(PSDriveInfo drive) } return drive; +#endif } /// @@ -2446,7 +2441,7 @@ protected override void NewItem( #if UNIX success = Platform.NonWindowsCreateHardLink(path, strTargetPath); #else - success = WinCreateHardLink(path, strTargetPath); + success = Interop.Windows.CreateHardLink(path, strTargetPath, IntPtr.Zero); #endif } @@ -2649,25 +2644,21 @@ protected override void NewItem( } } +#if !UNIX private static bool WinCreateSymbolicLink(string path, string strTargetPath, bool isDirectory) { // The new AllowUnprivilegedCreate is only available on Win10 build 14972 or newer - var flags = isDirectory ? NativeMethods.SymbolicLinkFlags.Directory : NativeMethods.SymbolicLinkFlags.File; + var flags = isDirectory ? Interop.Windows.SymbolicLinkFlags.Directory : Interop.Windows.SymbolicLinkFlags.File; if (OperatingSystem.IsWindowsVersionAtLeast(10, 0, 14972, 0)) { - flags |= NativeMethods.SymbolicLinkFlags.AllowUnprivilegedCreate; + flags |= Interop.Windows.SymbolicLinkFlags.AllowUnprivilegedCreate; } - var created = NativeMethods.CreateSymbolicLink(path, strTargetPath, flags); + var created = Interop.Windows.CreateSymbolicLink(path, strTargetPath, flags); return created; } - - private static bool WinCreateHardLink(string path, string strTargetPath) - { - bool success = NativeMethods.CreateHardLink(path, strTargetPath, IntPtr.Zero); - return success; - } +#endif private static bool WinCreateJunction(string path, string strTargetPath) { @@ -7114,27 +7105,6 @@ private static partial class NativeMethods [DllImport("mpr.dll", CharSet = CharSet.Unicode)] internal static extern int WNetAddConnection2(ref NetResource netResource, byte[] password, string username, int flags); - /// - /// WNetCancelConnection2 function cancels an existing network connection. - /// - /// - /// PSDrive Name. - /// - /// - /// Connection Type. - /// - /// - /// Specifies whether the disconnection should occur if there are open files or jobs - /// on the connection. If this parameter is FALSE, the function fails - /// if there are open files or jobs. - /// - /// If connection is removed then success is returned or - /// else the error code describing the type of failure that occurred while - /// trying to remove the connection is returned. - /// - [LibraryImport("mpr.dll", EntryPoint ="WNetCancelConnection2W", StringMarshalling = StringMarshalling.Utf16)] - internal static partial int WNetCancelConnection2(string driveName, int flags, [MarshalAs(UnmanagedType.Bool)] bool force); - /// /// WNetGetConnection function retrieves the name of the network resource associated with a local device. /// @@ -7228,75 +7198,6 @@ internal static bool PathIsNetworkPath(string path) [return: MarshalAs(UnmanagedType.Bool)] internal static partial bool PathIsNetworkPath(string path); #endif - - /// - /// Creates a symbolic link using the native API. - /// - /// Path of the symbolic link. - /// Path of the target of the symbolic link. - /// Flag values from SymbolicLinkFlags enum. - /// 1 on successful creation. - [LibraryImport(PinvokeDllNames.CreateSymbolicLinkDllName, EntryPoint = "CreateSymbolicLinkW", StringMarshalling = StringMarshalling.Utf16)] - [return: MarshalAs(UnmanagedType.I1)] - internal static partial bool CreateSymbolicLink(string name, string destination, SymbolicLinkFlags symbolicLinkFlags); - - /// - /// Flags used when creating a symbolic link. - /// - [Flags] - internal enum SymbolicLinkFlags - { - /// - /// Symbolic link is a file. - /// - File = 0, - - /// - /// Symbolic link is a directory. - /// - Directory = 1, - - /// - /// Allow creation of symbolic link without elevation. Requires Developer mode. - /// - AllowUnprivilegedCreate = 2, - } - - /// - /// Creates a hard link using the native API. - /// - /// Name of the hard link. - /// Path to the target of the hard link. - /// - /// - [LibraryImport(PinvokeDllNames.CreateHardLinkDllName, EntryPoint = "CreateHardLinkW", StringMarshalling = StringMarshalling.Utf16)] - [return: MarshalAs(UnmanagedType.Bool)] - internal static partial bool CreateHardLink(string name, string existingFileName, IntPtr SecurityAttributes); - - // OneDrive placeholder support -#if !UNIX - /// - /// Returns the placeholder compatibility mode for the current process. - /// - /// The process's placeholder compatibily mode (PHCM_xxx), or a negative value on error (PCHM_ERROR_xxx). - [LibraryImport("ntdll.dll")] - internal static partial sbyte RtlQueryProcessPlaceholderCompatibilityMode(); - - /// - /// Sets the placeholder compatibility mode for the current process. - /// - /// The placeholder compatibility mode to set. - /// The process's previous placeholder compatibily mode (PHCM_xxx), or a negative value on error (PCHM_ERROR_xxx). - [LibraryImport("ntdll.dll")] - internal static partial sbyte RtlSetProcessPlaceholderCompatibilityMode(sbyte pcm); - - internal const sbyte PHCM_APPLICATION_DEFAULT = 0; - internal const sbyte PHCM_DISGUISE_PLACEHOLDER = 1; - internal const sbyte PHCM_EXPOSE_PLACEHOLDERS = 2; - internal const sbyte PHCM_MAX = 2; - internal const sbyte PHCM_ERROR_INVALID_PARAMETER = -1; - internal const sbyte PHCM_ERROR_NO_TEB = -2; -#endif } /// @@ -7963,40 +7864,6 @@ internal static partial IntPtr CreateFile( FileAttributes dwFlagsAndAttributes, IntPtr hTemplateFile); - internal sealed partial class SafeFindHandle : SafeHandleZeroOrMinusOneIsInvalid - { - private SafeFindHandle() : base(true) { } - - protected override bool ReleaseHandle() - { - return FindClose(this.handle); - } - - [LibraryImport(PinvokeDllNames.FindCloseDllName)] - [return: MarshalAs(UnmanagedType.Bool)] - private static partial bool FindClose(IntPtr handle); - } - - // We use 'FindFirstFileW' instead of 'FindFirstFileExW' because the latter doesn't work correctly with Unicode file names on FAT32. - // See https://github.com/PowerShell/PowerShell/issues/16804 - [LibraryImport(PinvokeDllNames.FindFirstFileDllName, EntryPoint = "FindFirstFileW", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)] - private static partial SafeFindHandle FindFirstFile(string lpFileName, ref WIN32_FIND_DATA lpFindFileData); - - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - internal unsafe struct WIN32_FIND_DATA - { - internal uint dwFileAttributes; - internal FILE_TIME ftCreationTime; - internal FILE_TIME ftLastAccessTime; - internal FILE_TIME ftLastWriteTime; - internal uint nFileSizeHigh; - internal uint nFileSizeLow; - internal uint dwReserved0; - internal uint dwReserved1; - internal fixed char cFileName[MAX_PATH]; - internal fixed char cAlternateFileName[14]; - } - /// /// Gets the target of the specified reparse point. /// @@ -8162,14 +8029,14 @@ internal static bool IsReparsePointLikeSymlink(FileSystemInfo fileInfo) return !InternalTestHooks.OneDriveTestRecurseOn; } - WIN32_FIND_DATA data = default; + Interop.Windows.WIN32_FIND_DATA data = default; string fullPath = Path.TrimEndingDirectorySeparator(fileInfo.FullName); if (fullPath.Length >= MAX_PATH) { fullPath = PathUtils.EnsureExtendedPrefix(fullPath); } - using (SafeFindHandle handle = FindFirstFile(fullPath, ref data)) + using (Interop.Windows.SafeFindHandle handle = Interop.Windows.FindFirstFile(fullPath, ref data)) { if (handle.IsInvalid) { diff --git a/src/System.Management.Automation/utils/ClrFacade.cs b/src/System.Management.Automation/utils/ClrFacade.cs index 0bccb456e6c..cbd10e6c83a 100644 --- a/src/System.Management.Automation/utils/ClrFacade.cs +++ b/src/System.Management.Automation/utils/ClrFacade.cs @@ -7,7 +7,6 @@ using System.Management.Automation.Internal; using System.Management.Automation.Language; using System.Reflection; -using System.Runtime.InteropServices; using System.Runtime.Loader; using System.Security; using System.Text; @@ -19,7 +18,7 @@ namespace System.Management.Automation /// ClrFacade contains all diverging code (different implementation for FullCLR and CoreCLR using if/def). /// It exposes common APIs that can be used by the rest of the code base. /// - internal static partial class ClrFacade + internal static class ClrFacade { /// /// Initialize powershell AssemblyLoadContext and register the 'Resolving' event, if it's not done already. @@ -113,7 +112,7 @@ internal static Encoding GetOEMEncoding() #if UNIX s_oemEncoding = new UTF8Encoding(false); #else - uint oemCp = NativeMethods.GetOEMCP(); + uint oemCp = Interop.Windows.GetOEMCP(); s_oemEncoding = Encoding.GetEncoding((int)oemCp); #endif } @@ -362,17 +361,5 @@ internal static string ToDmtfDateTime(DateTime date) } #endregion Misc - - /// - /// Native methods that are used by facade methods. - /// - private static partial class NativeMethods - { - /// - /// Pinvoke for GetOEMCP to get the OEM code page. - /// - [LibraryImport(PinvokeDllNames.GetOEMCPDllName)] - internal static partial uint GetOEMCP(); - } } } From 8ff6a06f975426c8fff24b767b51a60dba6cfce1 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Thu, 1 Dec 2022 16:13:42 -0800 Subject: [PATCH 231/779] Switch `$PSNativeCommandUseErrorActionPreference` to `$true` when feature is enabled (#18695) --- src/System.Management.Automation/engine/InitialSessionState.cs | 2 +- test/powershell/Host/ConsoleHost.Tests.ps1 | 1 + .../Modules/Microsoft.PowerShell.Utility/Write-Error.Tests.ps1 | 3 ++- 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/System.Management.Automation/engine/InitialSessionState.cs b/src/System.Management.Automation/engine/InitialSessionState.cs index a47d1d5e545..5e5758340e8 100644 --- a/src/System.Management.Automation/engine/InitialSessionState.cs +++ b/src/System.Management.Automation/engine/InitialSessionState.cs @@ -4486,7 +4486,7 @@ static InitialSessionState() builtinVariables.Add( new SessionStateVariableEntry( SpecialVariables.PSNativeCommandUseErrorActionPreference, - value: false, + value: true, // when this feature is changed to stable, this should default to `false` RunspaceInit.PSNativeCommandUseErrorActionPreferenceDescription, ScopedItemOptions.None, new ArgumentTypeConverterAttribute(typeof(bool)))); diff --git a/test/powershell/Host/ConsoleHost.Tests.ps1 b/test/powershell/Host/ConsoleHost.Tests.ps1 index ccec3d7455f..5def52d255c 100644 --- a/test/powershell/Host/ConsoleHost.Tests.ps1 +++ b/test/powershell/Host/ConsoleHost.Tests.ps1 @@ -24,6 +24,7 @@ Describe 'minishell for native executables' -Tag 'CI' { } It 'gets the error stream from minishell' { + $PSNativeCommandUseErrorActionPreference = $false $output = & $powershell -noprofile { Write-Error 'foo' } 2>&1 ($output | Measure-Object).Count | Should -Be 1 $output | Should -BeOfType System.Management.Automation.ErrorRecord diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Write-Error.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Write-Error.Tests.ps1 index d243ec07988..45ff1614d42 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Write-Error.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Write-Error.Tests.ps1 @@ -101,8 +101,9 @@ Describe "Write-Error Tests" -Tags "CI" { while ($longtext.Length -lt [console]::WindowWidth) { $longtext += $longtext } + $PSNativeCommandUseErrorActionPreference = $false $result = & "$PSHOME/pwsh" -noprofile -command "`$ErrorView = 'NormalView'; Write-Error -Message '$longtext'" 2>&1 - $result.Count | Should -BeExactly 3 + $result.Count | Should -BeExactly 3 -Because ($result | Out-String) $result[0] | Should -Match $longtext } From ae3c3169eeec222f6b1ba73f60991cee437d5236 Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Thu, 1 Dec 2022 22:26:43 -0800 Subject: [PATCH 232/779] Fix `SuspiciousContentChecker.Match` to detect a pre-defined string when the text starts with it (#18693) --- .../engine/runtime/CompiledScriptBlock.cs | 2 +- .../Api/SuspiciousContentChecker.Tests.ps1 | 35 +++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 test/powershell/engine/Api/SuspiciousContentChecker.Tests.ps1 diff --git a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs index 8d4e60ae0a2..9feeab94364 100644 --- a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs +++ b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs @@ -2033,7 +2033,7 @@ public static string Match(string text) continue; } - for (int j = Math.Min(i, runningHash.Length) - 1; j > 0; j--) + for (int j = Math.Min(i, runningHash.Length - 1); j > 0; j--) { // Say our input is: `Emit` (our shortest pattern, len 4). // Towards the end just before matching, we will: diff --git a/test/powershell/engine/Api/SuspiciousContentChecker.Tests.ps1 b/test/powershell/engine/Api/SuspiciousContentChecker.Tests.ps1 new file mode 100644 index 00000000000..8d532dac04e --- /dev/null +++ b/test/powershell/engine/Api/SuspiciousContentChecker.Tests.ps1 @@ -0,0 +1,35 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +Describe 'SuspiciousContentChecker verification' -Tags "CI" { + BeforeAll { + $type = [psobject].Assembly.GetType('System.Management.Automation.ScriptBlock+SuspiciousContentChecker') + + $testCases = @( + @{ id = 'Should Detect (1)'; text = "add-TyPe"; expected = "Add-Type" } + @{ id = 'Should Detect (2)'; text = "GetDelegateForFunctionPointer"; expected = "GetDelegateForFunctionPointer" } + @{ id = 'Should Detect (3)'; text = "ZeroFreeGlobalAllocUnicode"; expected = "ZeroFreeGlobalAllocUnicode" } + @{ id = 'Should Detect (4)'; text = "Hello world emit new"; expected = "Emit" } + @{ id = 'Should Detect (5)'; text = "xxxx yyyyMakeByRefTypecccc Type 'help' to get help"; expected = "MakeByRefType" } + @{ id = 'Should Detect (6)'; text = "emjt TypeHandlebegood"; expected = "TypeHandle" } + @{ id = 'Should Detect (7)'; text = "emit*&)(@~>-type"; expected = "Emit" } + @{ id = 'Should Detect (8)'; text = "*&)(@~>-typeemit"; expected = "Emit" } + @{ id = 'Should Detect (9)'; text = "Type`u{48}andle`u{2122}"; expected = "TypeHandle" } + @{ id = 'Should Detect (10)'; text = "`u{2122}Type`u{48}andle`u{2122}"; expected = "TypeHandle" } + @{ id = 'Should Detect (11)'; text = "`u{D83D}`u{DE00}Type`u{48}andle`u{D83D}`u{DE00}"; expected = "TypeHandle" } ## use surrogate pairs in the string. + @{ id = 'Should Detect (12)'; text = "xx`u{48}`u{48}xx()xxx--xx[]xx;'xpox?/xxemit"; expected = "Emit" } ## suspicious string starts at the index 29. + + @{ id = 'Should NOT Detect (1)'; text = "PowerShell Preview Extension v2022.11.2"; expected = $null } + @{ id = 'Should NOT Detect (2)'; text = "add-typu"; expected = $null } + @{ id = 'Should NOT Detect (3)'; text = "GetDelegateForFunctionPointfr"; expected = $null } + @{ id = 'Should NOT Detect (4)'; text = "emjt TypeHandlfe"; expected = $null } + @{ id = 'Should NOT Detect (5)'; text = "Get*&)(@~>-Types"; expected = $null } + ) + } + + It "Smoke testing the suspicious content detection - " -TestCases $testCases { + param($text, $expected) + + $type::Match($text) | Should -BeExactly $expected + } +} From 11ffaf1e331ff89f5a12da9cd5149d2208b63c47 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 2 Dec 2022 17:25:12 +0500 Subject: [PATCH 233/779] Bump Microsoft.CodeAnalysis.CSharp from 4.4.0-4.final to 4.4.0 (#18562) Bumps [Microsoft.CodeAnalysis.CSharp](https://github.com/dotnet/roslyn) from 4.4.0-4.final to 4.4.0. - [Release notes](https://github.com/dotnet/roslyn/releases) - [Changelog](https://github.com/dotnet/roslyn/blob/main/docs/Breaking%20API%20Changes.md) - [Commits](https://github.com/dotnet/roslyn/commits/Visual-Studio-2019-Version-16.0-Preview-4.4) --- updated-dependencies: - dependency-name: Microsoft.CodeAnalysis.CSharp dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .../Microsoft.PowerShell.Commands.Utility.csproj | 2 +- .../PSVersionInfoGenerator/PSVersionInfoGenerator.csproj | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj index ad1269ae241..ea2280fac56 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj +++ b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj @@ -32,7 +32,7 @@ - + diff --git a/src/System.Management.Automation/SourceGenerators/PSVersionInfoGenerator/PSVersionInfoGenerator.csproj b/src/System.Management.Automation/SourceGenerators/PSVersionInfoGenerator/PSVersionInfoGenerator.csproj index 5b9c4cffffe..56fa17a6f25 100644 --- a/src/System.Management.Automation/SourceGenerators/PSVersionInfoGenerator/PSVersionInfoGenerator.csproj +++ b/src/System.Management.Automation/SourceGenerators/PSVersionInfoGenerator/PSVersionInfoGenerator.csproj @@ -12,7 +12,7 @@ - + From 6fa7260db9a4574b124661edf438b9939d2faceb Mon Sep 17 00:00:00 2001 From: Jordan Borean Date: Sat, 3 Dec 2022 04:23:00 +1000 Subject: [PATCH 234/779] Fix the process `CommandLine` on Linux (#18710) --- .../engine/TypeTable_Types_Ps1Xml.cs | 3 ++- .../Get-Process.Tests.ps1 | 22 ++++++++++++++++--- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/src/System.Management.Automation/engine/TypeTable_Types_Ps1Xml.cs b/src/System.Management.Automation/engine/TypeTable_Types_Ps1Xml.cs index 5ecd5914904..22bdd8bcd35 100644 --- a/src/System.Management.Automation/engine/TypeTable_Types_Ps1Xml.cs +++ b/src/System.Management.Automation/engine/TypeTable_Types_Ps1Xml.cs @@ -1164,7 +1164,8 @@ private void Process_Types_Ps1Xml(string filePath, ConcurrentBag errors) if ($IsWindows) { (Get-CimInstance Win32_Process -Filter ""ProcessId = $($this.Id)"").CommandLine } elseif ($IsLinux) { - Get-Content -LiteralPath ""/proc/$($this.Id)/cmdline"" + $rawCmd = Get-Content -LiteralPath ""/proc/$($this.Id)/cmdline"" + $rawCmd.Substring(0, $rawCmd.Length - 1) -replace ""`0"", "" "" } "), setterScript: null, diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Process.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Process.Tests.ps1 index 79b592f31f3..4cde8baefee 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Process.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Process.Tests.ps1 @@ -96,9 +96,25 @@ Describe "Get-Process" -Tags "CI" { } It "Should return CommandLine property" -Skip:($IsMacOS) { - $command = "(Get-Process -Id `$pid).CommandLine" - $result = & "$PSHOME/pwsh" -NoProfile -NonInteractive -Command $command - $result | Should -BeLike "*$command*" + if ($IsWindows) { + # Windows will convert the bound parameters and quote them if it + # contains whitespace. Any inner double quotes are escaped with \". + $expected = "`"$PSHOME\pwsh.exe`" -NoProfile -NoLogo -NonInteractive -Command `"(Get-Process -Id \`"`$pid\`").CommandLine`"" + + $actual = & { + $PSNativeCommandArgumentPassing = 'Windows' + & $PSHOME/pwsh -NoProfile -NoLogo -NonInteractive -Command '(Get-Process -Id "$pid").CommandLine' + } + } else { + # Linux passes arguments as they are bound. As there is no actual + # command line string, pwsh just joins each array with a space + # without attempting to use some sort of quoting rule. + $expected = "$PSHOME/pwsh -NoProfile -NoLogo -NonInteractive -Command (Get-Process -Id `"`$pid`").CommandLine" + + $actual = & "$PSHOME/pwsh" -NoProfile -NoLogo -NonInteractive -Command '(Get-Process -Id "$pid").CommandLine' + } + + $actual | Should -Be $expected } } From 4c580f7330cae70f70b820dc282f5e81a4b96c31 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 2 Dec 2022 10:44:29 -0800 Subject: [PATCH 235/779] Bump `decode-uri-component` from 0.2.0 to 0.2.2 (#18712) --- test/common/markdown-lint/yarn.lock | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/test/common/markdown-lint/yarn.lock b/test/common/markdown-lint/yarn.lock index 05d7f7c793c..1bf37b9eadf 100644 --- a/test/common/markdown-lint/yarn.lock +++ b/test/common/markdown-lint/yarn.lock @@ -453,9 +453,9 @@ decamelize@^1.1.1, decamelize@^1.2.0: integrity sha1-9lNNFRSCabIDUue+4m9QH5oZEpA= decode-uri-component@^0.2.0: - version "0.2.0" - resolved "https://registry.yarnpkg.com/decode-uri-component/-/decode-uri-component-0.2.0.tgz" - integrity sha1-6zkTMzRYd1y4TNGh+uBiEGu4dUU= + version "0.2.2" + resolved "https://registry.yarnpkg.com/decode-uri-component/-/decode-uri-component-0.2.2.tgz#e69dbe25d37941171dd540e024c444cd5188e1e9" + integrity sha512-FqUYQ+8o158GyGTrMFJms9qh3CqTKvAqgqsTnkLI8sKu0028orqBhxNMFkFen0zGyg6epACD32pjVk58ngIErQ== default-compare@^1.0.0: version "1.0.0" From bdea7735985d5c73048a90823b866a44e5d35136 Mon Sep 17 00:00:00 2001 From: Ilya Date: Sat, 3 Dec 2022 17:16:26 +0500 Subject: [PATCH 236/779] Replace DllImport with LibraryImport for WNetGetConnection (#18690) --- .../CommandCompletion/CompletionCompleters.cs | 2 +- .../engine/Interop/Windows/Errors.cs | 18 +++ .../engine/Interop/Windows/NetShareEnum.cs | 2 - .../Interop/Windows/WNetGetConnection.cs | 82 +++++++++++ .../namespaces/FileSystemProvider.cs | 129 +++--------------- 5 files changed, 120 insertions(+), 113 deletions(-) create mode 100644 src/System.Management.Automation/engine/Interop/Windows/Errors.cs create mode 100644 src/System.Management.Automation/engine/Interop/Windows/WNetGetConnection.cs diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs index 467526a0158..4674fe33271 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs @@ -4764,7 +4764,7 @@ internal static List GetFileShares(string machine, bool ignoreHidden) ref resumeHandle); var shares = new List(); - if (result == Interop.Windows.NERR_Success || result == Interop.Windows.ERROR_MORE_DATA) + if (result == Interop.Windows.ERROR_SUCCESS || result == Interop.Windows.ERROR_MORE_DATA) { for (int i = 0; i < numEntries; ++i) { diff --git a/src/System.Management.Automation/engine/Interop/Windows/Errors.cs b/src/System.Management.Automation/engine/Interop/Windows/Errors.cs new file mode 100644 index 00000000000..d1654933211 --- /dev/null +++ b/src/System.Management.Automation/engine/Interop/Windows/Errors.cs @@ -0,0 +1,18 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +internal static partial class Interop +{ + internal static partial class Windows + { + // List of error constants https://learn.microsoft.com/en-us/windows/win32/debug/system-error-codes + internal const int ERROR_SUCCESS = 0; + internal const int ERROR_GEN_FAILURE = 31; + internal const int ERROR_NOT_SUPPORTED = 50; + internal const int ERROR_NO_NETWORK = 1222; + internal const int ERROR_MORE_DATA = 234; + internal const int ERROR_CONNECTION_UNAVAIL = 1201; + } +} diff --git a/src/System.Management.Automation/engine/Interop/Windows/NetShareEnum.cs b/src/System.Management.Automation/engine/Interop/Windows/NetShareEnum.cs index c3b430dec14..7efad887f1a 100644 --- a/src/System.Management.Automation/engine/Interop/Windows/NetShareEnum.cs +++ b/src/System.Management.Automation/engine/Interop/Windows/NetShareEnum.cs @@ -10,8 +10,6 @@ internal static partial class Interop internal static unsafe partial class Windows { internal const int MAX_PREFERRED_LENGTH = -1; - internal const int NERR_Success = 0; - internal const int ERROR_MORE_DATA = 234; internal const int STYPE_DISKTREE = 0; internal const int STYPE_MASK = 0x000000FF; diff --git a/src/System.Management.Automation/engine/Interop/Windows/WNetGetConnection.cs b/src/System.Management.Automation/engine/Interop/Windows/WNetGetConnection.cs new file mode 100644 index 00000000000..cf6685e4ddc --- /dev/null +++ b/src/System.Management.Automation/engine/Interop/Windows/WNetGetConnection.cs @@ -0,0 +1,82 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System; +using System.Buffers; +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal static unsafe partial class Windows + { + private static bool s_WNetApiNotAvailable; + + [LibraryImport("mpr.dll", EntryPoint = "WNetGetConnectionW")] + internal static partial int WNetGetConnection(ReadOnlySpan localName, Span remoteName, ref uint remoteNameLength); + + internal static int GetUNCForNetworkDrive(char drive, out string? uncPath) + { + uncPath = null; + if (s_WNetApiNotAvailable) + { + return ERROR_NOT_SUPPORTED; + } + + uint bufferSize = MAX_PATH; + +#if DEBUG + // In Debug mode buffer size is initially set to 3 and if additional buffer is required, the + // required buffer size is allocated and the WNetGetConnection API is executed with the newly + // allocated buffer size. + bufferSize = 3; +#endif + + // TODO: change ushort with char after LibraryImport will support 'ref char' + // without applying the 'System.Runtime.CompilerServices.DisableRuntimeMarshallingAttribute' + // to the assembly. + ReadOnlySpan driveName = stackalloc ushort[] { drive, ':', '\0' }; + Span uncBuffer = stackalloc ushort[(int)bufferSize]; + int errorCode; + + try + { + errorCode = WNetGetConnection(driveName, uncBuffer, ref bufferSize); + } + catch (System.DllNotFoundException) + { + s_WNetApiNotAvailable = true; + return ERROR_NOT_SUPPORTED; + } + + if (errorCode == ERROR_SUCCESS) + { + uncPath = uncBuffer.Slice((int)bufferSize).ToString(); + } + else if (errorCode == ERROR_MORE_DATA) + { + ushort[]? rentedArray = null; + try + { + uncBuffer = rentedArray = ArrayPool.Shared.Rent((int)bufferSize); + errorCode = WNetGetConnection(driveName, uncBuffer, ref bufferSize); + + if (errorCode == ERROR_SUCCESS) + { + uncPath = uncBuffer.Slice((int)bufferSize).ToString(); + } + } + finally + { + if (rentedArray is not null) + { + ArrayPool.Shared.Return(rentedArray); + } + } + } + + return errorCode; + } + } +} diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index 6b18e44b885..4bc9a1d5794 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -810,54 +810,23 @@ internal static string GetUNCForNetworkDrive(string driveName) #endif } +#if !UNIX private static string WinGetUNCForNetworkDrive(string driveName) { - const int ERROR_NO_NETWORK = 1222; string uncPath = null; if (!string.IsNullOrEmpty(driveName) && driveName.Length == 1) { - // By default buffer size is set to 300 which would generally be sufficient in most of the cases. - int bufferSize = 300; -#if DEBUG - // In Debug mode buffer size is initially set to 3 and if additional buffer is required, the - // required buffer size is allocated and the WNetGetConnection API is executed with the newly - // allocated buffer size. - bufferSize = 3; -#endif - - StringBuilder uncBuffer = new StringBuilder(bufferSize); - driveName += ':'; - - // Call the windows API - int errorCode = ERROR_NO_NETWORK; - - try - { - errorCode = NativeMethods.WNetGetConnection(driveName, uncBuffer, ref bufferSize); - } - catch (System.DllNotFoundException) - { - return null; - } - - // error code 234 is returned whenever the required buffer size is greater - // than the specified buffer size. - if (errorCode == 234) - { - uncBuffer = new StringBuilder(bufferSize); - errorCode = NativeMethods.WNetGetConnection(driveName, uncBuffer, ref bufferSize); - } + int errorCode = Interop.Windows.GetUNCForNetworkDrive(driveName[0], out uncPath); - if (errorCode != 0) + if (errorCode != Interop.Windows.ERROR_SUCCESS) { throw new System.ComponentModel.Win32Exception(errorCode); } - - uncPath = uncBuffer.ToString(); } return uncPath; } +#endif /// /// Get the substituted path of a NetWork type MS-DOS device that is created by 'subst' command. @@ -7072,11 +7041,6 @@ internal static bool PathIsNetworkPath(string path) #endif } - internal static bool WinPathIsNetworkPath(string path) - { - return NativeMethods.PathIsNetworkPath(path); // call the native method - } - private static partial class NativeMethods { /// @@ -7104,43 +7068,16 @@ private static partial class NativeMethods /// the connection is returned. [DllImport("mpr.dll", CharSet = CharSet.Unicode)] internal static extern int WNetAddConnection2(ref NetResource netResource, byte[] password, string username, int flags); + } - /// - /// WNetGetConnection function retrieves the name of the network resource associated with a local device. - /// - /// - /// Local name of the PSDrive. - /// - /// - /// The remote name to which the PSDrive is getting mapped to. - /// - /// - /// length of the remote name of the created PSDrive. - /// - /// - [DllImport("mpr.dll", CharSet = CharSet.Unicode)] - internal static extern int WNetGetConnection(string localName, StringBuilder remoteName, ref int remoteNameLength); - -#if CORECLR // TODO:CORECLR Win32 function 'PathIsNetworkPath' is in an extension API set which is currently not on CSS. - /// - /// Searches a path for a drive letter within the range of 'A' to 'Z' and returns the corresponding drive number. - /// - /// - /// Path of the file being executed - /// - /// Returns 0 through 25 (corresponding to 'A' through 'Z') if the path has a drive letter, or -1 otherwise. - [LibraryImport("api-ms-win-core-shlwapi-legacy-l1-1-0.dll", EntryPoint ="PathGetDriveNumberW", StringMarshalling = StringMarshalling.Utf16)] - internal static partial int PathGetDriveNumber(string path); - - private static bool _WNetApiAvailable = true; - - /// - /// The API 'PathIsNetworkPath' is not available in CoreSystem. - /// This implementation is based on the 'PathIsNetworkPath' API. - /// - /// - /// - internal static bool PathIsNetworkPath(string path) +#if !UNIX + /// + /// The API 'PathIsNetworkPath' is not available in CoreSystem. + /// This implementation is based on the 'PathIsNetworkPath' API. + /// + /// A file system path. + /// True if the path is a network path. + internal static bool WinPathIsNetworkPath(string path) { if (string.IsNullOrEmpty(path)) { @@ -7152,33 +7089,17 @@ internal static bool PathIsNetworkPath(string path) return true; } - if (!_WNetApiAvailable) - { - return false; - } - - // 0 - 25 corresponding to 'A' - 'Z' - int driveId = PathGetDriveNumber(path); - if (driveId >= 0 && driveId < 26) + if (path.Length > 1 && path[1] == ':' && char.IsAsciiLetter(path[0])) { - string driveName = (char)('A' + driveId) + ":"; - - int bufferSize = 260; // MAX_PATH from EhStorIoctl.h - StringBuilder uncBuffer = new StringBuilder(bufferSize); + // path[0] is ASCII letter, e.g. is in 'A'-'Z' or 'a'-'z'. int errorCode = -1; - try - { - errorCode = WNetGetConnection(driveName, uncBuffer, ref bufferSize); - } - catch (System.DllNotFoundException) - { - _WNetApiAvailable = false; - return false; - } + errorCode = Interop.Windows.GetUNCForNetworkDrive(path[0], out string _); // From the 'IsNetDrive' API. // 0: success; 1201: connection closed; 31: device error - if (errorCode == 0 || errorCode == 1201 || errorCode == 31) + if (errorCode == Interop.Windows.ERROR_SUCCESS || + errorCode == Interop.Windows.ERROR_CONNECTION_UNAVAIL || + errorCode == Interop.Windows.ERROR_GEN_FAILURE) { return true; } @@ -7186,19 +7107,7 @@ internal static bool PathIsNetworkPath(string path) return false; } -#else - /// - /// Facilitates to validate if the supplied path exists locally or on the network share. - /// - /// - /// Path of the file being executed. - /// - /// True if the path is a network path or else returns false. - [LibraryImport("shlwapi.dll", EntryPoint = "PathIsNetworkPathW", StringMarshalling = StringMarshalling.Utf16)] - [return: MarshalAs(UnmanagedType.Bool)] - internal static partial bool PathIsNetworkPath(string path); #endif - } /// /// Managed equivalent of NETRESOURCE structure of WNet API. From 5d9835f46ea0f4c0c71915dce6f73de0878fb5ae Mon Sep 17 00:00:00 2001 From: Ilya Date: Mon, 5 Dec 2022 22:38:45 +0500 Subject: [PATCH 237/779] Use File.OpenHandle() instead CreateFileW pinvoke (#18722) --- .../commands/management/Process.cs | 59 +++++-------------- .../remoting/common/RunspaceConnectionInfo.cs | 33 +++-------- 2 files changed, 24 insertions(+), 68 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs index fdf3917965d..3f2c6740dcf 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs @@ -640,7 +640,7 @@ protected override void ProcessRecord() WriteNonTerminatingError(process, ex, ProcessResources.CouldNotEnumerateModules, "CouldNotEnumerateModules", ErrorCategory.PermissionDenied); } } - catch (PipelineStoppedException) + catch (PipelineStoppedException) { throw; } @@ -2261,28 +2261,22 @@ private void WriteToStandardInput(Process p) writer.Dispose(); } #else - private SafeFileHandle GetSafeFileHandleForRedirection(string RedirectionPath, uint dwCreationDisposition) - { - System.IntPtr hFileHandle = System.IntPtr.Zero; - ProcessNativeMethods.SECURITY_ATTRIBUTES lpSecurityAttributes = new(); - - hFileHandle = ProcessNativeMethods.CreateFileW(RedirectionPath, - ProcessNativeMethods.GENERIC_READ | ProcessNativeMethods.GENERIC_WRITE, - ProcessNativeMethods.FILE_SHARE_WRITE | ProcessNativeMethods.FILE_SHARE_READ, - lpSecurityAttributes, - dwCreationDisposition, - ProcessNativeMethods.FILE_ATTRIBUTE_NORMAL, - System.IntPtr.Zero); - if (hFileHandle == System.IntPtr.Zero) - { - int error = Marshal.GetLastWin32Error(); - Win32Exception win32ex = new(error); + + private SafeFileHandle GetSafeFileHandleForRedirection(string RedirectionPath, FileMode mode) + { + SafeFileHandle sf = null; + try + { + sf = File.OpenHandle(RedirectionPath, mode, FileAccess.ReadWrite, FileShare.ReadWrite | FileShare.Inheritable, FileOptions.WriteThrough); + } + catch (Win32Exception win32ex) + { + sf?.Dispose(); string message = StringUtil.Format(ProcessResources.InvalidStartProcess, win32ex.Message); ErrorRecord er = new(new InvalidOperationException(message), "InvalidOperationException", ErrorCategory.InvalidOperation, null); ThrowTerminatingError(er); } - SafeFileHandle sf = new(hFileHandle, true); return sf; } @@ -2343,7 +2337,7 @@ private void SetStartupInfo(ProcessStartInfo startinfo, ref ProcessNativeMethods { startinfo.RedirectStandardInput = true; _redirectstandardinput = ResolveFilePath(_redirectstandardinput); - lpStartupInfo.hStdInput = GetSafeFileHandleForRedirection(_redirectstandardinput, ProcessNativeMethods.OPEN_EXISTING); + lpStartupInfo.hStdInput = GetSafeFileHandleForRedirection(_redirectstandardinput, FileMode.Open); } else { @@ -2355,7 +2349,7 @@ private void SetStartupInfo(ProcessStartInfo startinfo, ref ProcessNativeMethods { startinfo.RedirectStandardOutput = true; _redirectstandardoutput = ResolveFilePath(_redirectstandardoutput); - lpStartupInfo.hStdOutput = GetSafeFileHandleForRedirection(_redirectstandardoutput, ProcessNativeMethods.CREATE_ALWAYS); + lpStartupInfo.hStdOutput = GetSafeFileHandleForRedirection(_redirectstandardoutput, FileMode.Create); } else { @@ -2367,7 +2361,7 @@ private void SetStartupInfo(ProcessStartInfo startinfo, ref ProcessNativeMethods { startinfo.RedirectStandardError = true; _redirectstandarderror = ResolveFilePath(_redirectstandarderror); - lpStartupInfo.hStdError = GetSafeFileHandleForRedirection(_redirectstandarderror, ProcessNativeMethods.CREATE_ALWAYS); + lpStartupInfo.hStdError = GetSafeFileHandleForRedirection(_redirectstandarderror, FileMode.Create); } else { @@ -2687,18 +2681,6 @@ internal struct JOBOBJECT_BASIC_PROCESS_ID_LIST internal static class ProcessNativeMethods { - // Fields - internal static readonly UInt32 GENERIC_READ = 0x80000000; - internal static readonly UInt32 GENERIC_WRITE = 0x40000000; - internal static readonly UInt32 FILE_ATTRIBUTE_NORMAL = 0x80000000; - internal static readonly UInt32 CREATE_ALWAYS = 2; - internal static readonly UInt32 FILE_SHARE_WRITE = 0x00000002; - internal static readonly UInt32 FILE_SHARE_READ = 0x00000001; - internal static readonly UInt32 OF_READWRITE = 0x00000002; - internal static readonly UInt32 OPEN_EXISTING = 3; - - // Methods - [DllImport(PinvokeDllNames.GetStdHandleDllName, SetLastError = true)] public static extern IntPtr GetStdHandle(int whichHandle); @@ -2732,17 +2714,6 @@ public static extern bool CreateProcess([MarshalAs(UnmanagedType.LPWStr)] string [DllImport(PinvokeDllNames.ResumeThreadDllName, CharSet = CharSet.Unicode, SetLastError = true)] public static extern uint ResumeThread(IntPtr threadHandle); - [DllImport(PinvokeDllNames.CreateFileDllName, CharSet = CharSet.Unicode, SetLastError = true)] - public static extern FileNakedHandle CreateFileW( - [In, MarshalAs(UnmanagedType.LPWStr)] string lpFileName, - DWORD dwDesiredAccess, - DWORD dwShareMode, - ProcessNativeMethods.SECURITY_ATTRIBUTES lpSecurityAttributes, - DWORD dwCreationDisposition, - DWORD dwFlagsAndAttributes, - System.IntPtr hTemplateFile - ); - [DllImport("userenv.dll", CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool CreateEnvironmentBlock(out IntPtr lpEnvironment, IntPtr hToken, bool bInherit); diff --git a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs index f2ea47228cb..9a50d9b8d94 100644 --- a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs +++ b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs @@ -2698,9 +2698,9 @@ private static Process CreateProcessWithRedirectedStd( stdInPipeServer = null; stdOutPipeServer = null; stdErrPipeServer = null; - SafePipeHandle stdInPipeClient = null; - SafePipeHandle stdOutPipeClient = null; - SafePipeHandle stdErrPipeClient = null; + SafeFileHandle stdInPipeClient = null; + SafeFileHandle stdOutPipeClient = null; + SafeFileHandle stdErrPipeClient = null; string randomName = System.IO.Path.GetFileNameWithoutExtension(System.IO.Path.GetRandomFileName()); try @@ -2746,9 +2746,9 @@ private static Process CreateProcessWithRedirectedStd( startInfo.FileName, string.Join(' ', startInfo.ArgumentList)); - lpStartupInfo.hStdInput = new SafeFileHandle(stdInPipeClient.DangerousGetHandle(), false); - lpStartupInfo.hStdOutput = new SafeFileHandle(stdOutPipeClient.DangerousGetHandle(), false); - lpStartupInfo.hStdError = new SafeFileHandle(stdErrPipeClient.DangerousGetHandle(), false); + lpStartupInfo.hStdInput = stdInPipeClient; + lpStartupInfo.hStdOutput = stdOutPipeClient; + lpStartupInfo.hStdError = stdErrPipeClient; lpStartupInfo.dwFlags = 0x100; // No new window: Inherit the parent process's console window @@ -2808,25 +2808,10 @@ private static Process CreateProcessWithRedirectedStd( } } - private static SafePipeHandle GetNamedPipeHandle(string pipeName) + private static SafeFileHandle GetNamedPipeHandle(string pipeName) { - // Get handle to pipe. - var fileHandle = PlatformInvokes.CreateFileW( - lpFileName: pipeName, - dwDesiredAccess: NamedPipeNative.GENERIC_READ | NamedPipeNative.GENERIC_WRITE, - dwShareMode: 0, - lpSecurityAttributes: new PlatformInvokes.SECURITY_ATTRIBUTES(), // Create an inheritable handle. - dwCreationDisposition: NamedPipeNative.OPEN_EXISTING, - dwFlagsAndAttributes: NamedPipeNative.FILE_FLAG_OVERLAPPED, // Open in asynchronous mode. - hTemplateFile: IntPtr.Zero); - - int lastError = Marshal.GetLastWin32Error(); - if (fileHandle == PlatformInvokes.INVALID_HANDLE_VALUE) - { - throw new System.ComponentModel.Win32Exception(lastError); - } - - return new SafePipeHandle(fileHandle, true); + SafeFileHandle sf = File.OpenHandle(pipeName, FileMode.Open, FileAccess.ReadWrite, FileShare.Inheritable, FileOptions.Asynchronous); + return sf; } private static SafePipeHandle CreateNamedPipe( From 07175ae0ff8eb7306fe0b0fc7d19bdef4fbf2d67 Mon Sep 17 00:00:00 2001 From: Ilya Date: Mon, 5 Dec 2022 23:50:22 +0500 Subject: [PATCH 238/779] Replace `DllImport` with `LibraryImport` for WNetAddConnection2 (#18721) --- .../Interop/Windows/WNetAddConnection2.cs | 73 ++++++++ .../Interop/Windows/WNetCancelConnection2.cs | 24 ++- .../Interop/Windows/WNetGetConnection.cs | 2 +- .../namespaces/FileSystemProvider.cs | 157 +++--------------- 4 files changed, 118 insertions(+), 138 deletions(-) create mode 100644 src/System.Management.Automation/engine/Interop/Windows/WNetAddConnection2.cs diff --git a/src/System.Management.Automation/engine/Interop/Windows/WNetAddConnection2.cs b/src/System.Management.Automation/engine/Interop/Windows/WNetAddConnection2.cs new file mode 100644 index 00000000000..df66e743897 --- /dev/null +++ b/src/System.Management.Automation/engine/Interop/Windows/WNetAddConnection2.cs @@ -0,0 +1,73 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal static partial class Windows + { + internal const int CONNECT_NOPERSIST = 0x00000000; + internal const int CONNECT_UPDATE_PROFILE = 0x00000001; + internal const int RESOURCE_GLOBALNET = 0x00000002; + internal const int RESOURCETYPE_ANY = 0x00000000; + internal const int RESOURCEDISPLAYTYPE_GENERIC = 0x00000000; + internal const int RESOURCEUSAGE_CONNECTABLE = 0x00000001; + + [StructLayout(LayoutKind.Sequential)] + internal unsafe struct NETRESOURCEW + { + public int Scope; + public int Type; + public int DisplayType; + public int Usage; + public char* LocalName; + public char* RemoteName; + public char* Comment; + public char* Provider; + } + + [LibraryImport("mpr.dll", EntryPoint = "WNetAddConnection2W", StringMarshalling = StringMarshalling.Utf16)] + internal static partial int WNetAddConnection2(ref NETRESOURCEW netResource, byte[] password, string userName, int flags); + + internal static unsafe int WNetAddConnection2(string localName, string remoteName, byte[] password, string userName, int connectType) + { + if (s_WNetApiNotAvailable) + { + return ERROR_NOT_SUPPORTED; + } + + int errorCode = ERROR_NO_NETWORK; + + fixed (char* pinnedLocalName = localName) + fixed (char* pinnedRemoteName = remoteName) + { + NETRESOURCEW resource = new NETRESOURCEW() + { + Comment = null, + DisplayType = RESOURCEDISPLAYTYPE_GENERIC, + LocalName = pinnedLocalName, + Provider = null, + RemoteName = pinnedRemoteName, + Scope = RESOURCE_GLOBALNET, + Type = RESOURCETYPE_ANY, + Usage = RESOURCEUSAGE_CONNECTABLE + }; + + try + { + errorCode = WNetAddConnection2(ref resource, password, userName, connectType); + } + catch (System.DllNotFoundException) + { + s_WNetApiNotAvailable = true; + return ERROR_NOT_SUPPORTED; + } + } + + return errorCode; + } + } +} diff --git a/src/System.Management.Automation/engine/Interop/Windows/WNetCancelConnection2.cs b/src/System.Management.Automation/engine/Interop/Windows/WNetCancelConnection2.cs index 841fdc7f129..0ff720ffd3e 100644 --- a/src/System.Management.Automation/engine/Interop/Windows/WNetCancelConnection2.cs +++ b/src/System.Management.Automation/engine/Interop/Windows/WNetCancelConnection2.cs @@ -10,6 +10,28 @@ internal static partial class Interop internal static unsafe partial class Windows { [LibraryImport("mpr.dll", EntryPoint = "WNetCancelConnection2W", StringMarshalling = StringMarshalling.Utf16)] - internal static partial int WNetCancelConnection2(string driveName, int flags, [MarshalAs(UnmanagedType.Bool)] bool force); + internal static partial int WNetCancelConnection2W(string driveName, int flags, [MarshalAs(UnmanagedType.Bool)] bool force); + + internal static int WNetCancelConnection2(string driveName, int flags, bool force) + { + if (s_WNetApiNotAvailable) + { + return ERROR_NOT_SUPPORTED; + } + + int errorCode = ERROR_NO_NETWORK; + + try + { + errorCode = WNetCancelConnection2W(driveName, flags, force: true); + } + catch (System.DllNotFoundException) + { + s_WNetApiNotAvailable = true; + return ERROR_NOT_SUPPORTED; + } + + return errorCode; + } } } diff --git a/src/System.Management.Automation/engine/Interop/Windows/WNetGetConnection.cs b/src/System.Management.Automation/engine/Interop/Windows/WNetGetConnection.cs index cf6685e4ddc..bf7742526f1 100644 --- a/src/System.Management.Automation/engine/Interop/Windows/WNetGetConnection.cs +++ b/src/System.Management.Automation/engine/Interop/Windows/WNetGetConnection.cs @@ -38,7 +38,7 @@ internal static int GetUNCForNetworkDrive(char drive, out string? uncPath) // to the assembly. ReadOnlySpan driveName = stackalloc ushort[] { drive, ':', '\0' }; Span uncBuffer = stackalloc ushort[(int)bufferSize]; - int errorCode; + int errorCode = ERROR_NO_NETWORK; try { diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index 4bc9a1d5794..34e4b01d4a3 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -528,7 +528,7 @@ protected override PSDriveInfo NewDrive(PSDriveInfo drive) { // MapNetworkDrive facilitates to map the newly // created PS Drive to a network share. - this.MapNetworkDrive(drive); + MapNetworkDrive(drive); } // The drive is valid if the item exists or the @@ -587,35 +587,18 @@ protected override PSDriveInfo NewDrive(PSDriveInfo drive) /// MapNetworkDrive facilitates to map the newly created PS Drive to a network share. /// /// The PSDrive info that would be used to create a new PS drive. + [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "Can be static on Unix but not on Windows.")] + private void MapNetworkDrive(PSDriveInfo drive) { +#if UNIX + throw new PlatformNotSupportedException(); +#else // Porting note: mapped network drives are only supported on Windows - if (Platform.IsWindows) - { - WinMapNetworkDrive(drive); - } - else - { - throw new PlatformNotSupportedException(); - } - } - - private static bool _WNetApiAvailable = true; - - private void WinMapNetworkDrive(PSDriveInfo drive) - { if (drive != null && !string.IsNullOrEmpty(drive.Root)) { - const int CONNECT_UPDATE_PROFILE = 0x00000001; - const int CONNECT_NOPERSIST = 0x00000000; - const int RESOURCE_GLOBALNET = 0x00000002; - const int RESOURCETYPE_ANY = 0x00000000; - const int RESOURCEDISPLAYTYPE_GENERIC = 0x00000000; - const int RESOURCEUSAGE_CONNECTABLE = 0x00000001; - const int ERROR_NO_NETWORK = 1222; - // By default the connection is not persisted. - int CONNECT_TYPE = CONNECT_NOPERSIST; + int connectType = Interop.Windows.CONNECT_NOPERSIST; string driveName = null; byte[] passwd = null; @@ -625,13 +608,12 @@ private void WinMapNetworkDrive(PSDriveInfo drive) { if (IsSupportedDriveForPersistence(drive)) { - CONNECT_TYPE = CONNECT_UPDATE_PROFILE; + connectType = Interop.Windows.CONNECT_UPDATE_PROFILE; driveName = drive.Name + ":"; drive.DisplayRoot = drive.Root; } else { - // error. ErrorRecord er = new ErrorRecord(new InvalidOperationException(FileSystemProviderStrings.InvalidDriveName), "DriveNameNotSupportedForPersistence", ErrorCategory.InvalidOperation, drive); ThrowTerminatingError(er); } @@ -647,37 +629,15 @@ private void WinMapNetworkDrive(PSDriveInfo drive) try { - NetResource resource = new NetResource(); - resource.Comment = null; - resource.DisplayType = RESOURCEDISPLAYTYPE_GENERIC; - resource.LocalName = driveName; - resource.Provider = null; - resource.RemoteName = drive.Root; - resource.Scope = RESOURCE_GLOBALNET; - resource.Type = RESOURCETYPE_ANY; - resource.Usage = RESOURCEUSAGE_CONNECTABLE; + int errorCode = Interop.Windows.WNetAddConnection2(driveName, drive.Root, passwd, userName, connectType); - int code = ERROR_NO_NETWORK; - - if (_WNetApiAvailable) + if (errorCode != Interop.Windows.ERROR_SUCCESS) { - try - { - code = NativeMethods.WNetAddConnection2(ref resource, passwd, userName, CONNECT_TYPE); - } - catch (System.DllNotFoundException) - { - _WNetApiAvailable = false; - } - } - - if (code != 0) - { - ErrorRecord er = new ErrorRecord(new System.ComponentModel.Win32Exception(code), "CouldNotMapNetworkDrive", ErrorCategory.InvalidOperation, drive); + ErrorRecord er = new ErrorRecord(new System.ComponentModel.Win32Exception(errorCode), "CouldNotMapNetworkDrive", ErrorCategory.InvalidOperation, drive); ThrowTerminatingError(er); } - if (CONNECT_TYPE == CONNECT_UPDATE_PROFILE) + if (connectType == Interop.Windows.CONNECT_UPDATE_PROFILE) { // Update the current PSDrive to be a persisted drive. drive.IsNetworkDrive = true; @@ -692,10 +652,11 @@ private void WinMapNetworkDrive(PSDriveInfo drive) // Clear the password in the memory. if (passwd != null) { - Array.Clear(passwd, 0, passwd.Length - 1); + Array.Clear(passwd); } } } +#endif } /// @@ -727,15 +688,12 @@ protected override PSDriveInfo RemoveDrive(PSDriveInfo drive) #else if (IsNetworkMappedDrive(drive)) { - const int CONNECT_UPDATE_PROFILE = 0x00000001; - const int ERROR_NO_NETWORK = 1222; - - int flags = 0; + int flags = Interop.Windows.CONNECT_NOPERSIST; string driveName; if (drive.IsNetworkDrive) { // Here we are removing only persisted network drives. - flags = CONNECT_UPDATE_PROFILE; + flags = Interop.Windows.CONNECT_UPDATE_PROFILE; driveName = drive.Name + ":"; } else @@ -746,23 +704,11 @@ protected override PSDriveInfo RemoveDrive(PSDriveInfo drive) } // You need to actually remove the drive. - int code = ERROR_NO_NETWORK; - - if (_WNetApiAvailable) - { - try - { - code = Interop.Windows.WNetCancelConnection2(driveName, flags, true); - } - catch (System.DllNotFoundException) - { - _WNetApiAvailable = false; - } - } + int errorCode = Interop.Windows.WNetCancelConnection2(driveName, flags, force: true); - if (code != 0) + if (errorCode != Interop.Windows.ERROR_SUCCESS) { - ErrorRecord er = new ErrorRecord(new System.ComponentModel.Win32Exception(code), "CouldRemoveNetworkDrive", ErrorCategory.InvalidOperation, drive); + ErrorRecord er = new ErrorRecord(new System.ComponentModel.Win32Exception(errorCode), "CouldRemoveNetworkDrive", ErrorCategory.InvalidOperation, drive); ThrowTerminatingError(er); } } @@ -806,13 +752,6 @@ internal static string GetUNCForNetworkDrive(string driveName) #if UNIX return driveName; #else - return WinGetUNCForNetworkDrive(driveName); -#endif - } - -#if !UNIX - private static string WinGetUNCForNetworkDrive(string driveName) - { string uncPath = null; if (!string.IsNullOrEmpty(driveName) && driveName.Length == 1) { @@ -825,8 +764,8 @@ private static string WinGetUNCForNetworkDrive(string driveName) } return uncPath; - } #endif + } /// /// Get the substituted path of a NetWork type MS-DOS device that is created by 'subst' command. @@ -7041,35 +6980,6 @@ internal static bool PathIsNetworkPath(string path) #endif } - private static partial class NativeMethods - { - /// - /// WNetAddConnection2 API makes a connection to a network resource - /// and can redirect a local device to the network resource. - /// This API simulates the "new Use" functionality used to connect to - /// network resource. - /// - /// - /// The netResource structure contains information - /// about a network resource. - /// - /// The password used to get connected to network resource. - /// - /// - /// The username used to get connected to network resource. - /// - /// - /// The flags parameter is used to indicate if the created network - /// resource has to be persisted or not. - /// - /// If connection is established to the network resource - /// then success is returned or else the error code describing the - /// type of failure that occurred while establishing - /// the connection is returned. - [DllImport("mpr.dll", CharSet = CharSet.Unicode)] - internal static extern int WNetAddConnection2(ref NetResource netResource, byte[] password, string username, int flags); - } - #if !UNIX /// /// The API 'PathIsNetworkPath' is not available in CoreSystem. @@ -7092,8 +7002,7 @@ internal static bool WinPathIsNetworkPath(string path) if (path.Length > 1 && path[1] == ':' && char.IsAsciiLetter(path[0])) { // path[0] is ASCII letter, e.g. is in 'A'-'Z' or 'a'-'z'. - int errorCode = -1; - errorCode = Interop.Windows.GetUNCForNetworkDrive(path[0], out string _); + int errorCode = Interop.Windows.GetUNCForNetworkDrive(path[0], out string _); // From the 'IsNetDrive' API. // 0: success; 1201: connection closed; 31: device error @@ -7109,30 +7018,6 @@ internal static bool WinPathIsNetworkPath(string path) } #endif - /// - /// Managed equivalent of NETRESOURCE structure of WNet API. - /// - [StructLayout(LayoutKind.Sequential)] - private struct NetResource - { - public int Scope; - public int Type; - public int DisplayType; - public int Usage; - - [MarshalAs(UnmanagedType.LPWStr)] - public string LocalName; - - [MarshalAs(UnmanagedType.LPWStr)] - public string RemoteName; - - [MarshalAs(UnmanagedType.LPWStr)] - public string Comment; - - [MarshalAs(UnmanagedType.LPWStr)] - public string Provider; - } - #region InodeTracker /// /// Tracks visited files/directories by caching their device IDs and inodes. From bd6edfdd9c6083188a853b5aaa4a949250204959 Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Tue, 6 Dec 2022 10:31:54 -0800 Subject: [PATCH 239/779] Add `testexe.exe -echocmdline` to output raw command line received by the process on Windows (#18591) --- test/tools/TestExe/TestExe.cs | 53 +++++++++++++++++++++++++++++++++-- 1 file changed, 50 insertions(+), 3 deletions(-) diff --git a/test/tools/TestExe/TestExe.cs b/test/tools/TestExe/TestExe.cs index fa57fb57215..ab8f76d5425 100644 --- a/test/tools/TestExe/TestExe.cs +++ b/test/tools/TestExe/TestExe.cs @@ -4,6 +4,7 @@ using System; using System.Threading; using System.Diagnostics; +using System.Runtime.InteropServices; namespace TestExe { @@ -11,6 +12,7 @@ internal class TestExe { private static int Main(string[] args) { + int exitCode = 0; if (args.Length > 0) { switch (args[0].ToLowerInvariant()) @@ -18,6 +20,9 @@ private static int Main(string[] args) case "-echoargs": EchoArgs(args); break; + case "-echocmdline": + EchoCmdLine(); + break; case "-createchildprocess": CreateChildProcess(args); break; @@ -28,17 +33,23 @@ private static int Main(string[] args) case "-stderr": Console.Error.WriteLine(args[1]); break; + case "--help": + case "-h": + PrintHelp(); + break; default: - Console.WriteLine("Unknown test {0}", args[0]); + exitCode = 1; + Console.Error.WriteLine("Unknown test {0}. Run with '-h' for help.", args[0]); break; } } else { - Console.WriteLine("Test not specified"); + exitCode = 1; + Console.Error.WriteLine("Test not specified"); } - return 0; + return exitCode; } // @@ -52,6 +63,36 @@ private static void EchoArgs(string[] args) } } + // + // Echos the raw command line received by the process plus the arguments passed in. + // + private static void EchoCmdLine() + { + string rawCmdLine = "N/A"; + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + nint cmdLinePtr = Interop.GetCommandLineW(); + rawCmdLine = Marshal.PtrToStringUni(cmdLinePtr); + } + + Console.WriteLine(rawCmdLine); + } + + // + // Print help content. + // + private static void PrintHelp() + { + const string Content = @" +Options for echoing args are: + -echoargs Echos back to stdout the arguments passed in. + -echocmdline Echos the raw command line received by the process. + +Other options are for specific tests only. Read source code for details. +"; + Console.WriteLine(Content); + } + // // First argument is the number of child processes to create which are instances of itself // Processes automatically exit after 100 seconds @@ -73,4 +114,10 @@ private static void CreateChildProcess(string[] args) Thread.Sleep(100000); } } + + internal static partial class Interop + { + [LibraryImport("Kernel32.dll")] + internal static partial nint GetCommandLineW(); + } } From 67a78d3004e071992fcea2eff518ad57d71b8ab8 Mon Sep 17 00:00:00 2001 From: Ilya Date: Tue, 6 Dec 2022 23:36:47 +0500 Subject: [PATCH 240/779] Remove one CreateFileW (#18732) --- .../utils/PlatformInvokes.cs | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/src/System.Management.Automation/utils/PlatformInvokes.cs b/src/System.Management.Automation/utils/PlatformInvokes.cs index 2901f7d9b6e..109eef919d6 100644 --- a/src/System.Management.Automation/utils/PlatformInvokes.cs +++ b/src/System.Management.Automation/utils/PlatformInvokes.cs @@ -678,16 +678,6 @@ internal static extern bool CreateProcess( internal static readonly uint RESUME_THREAD_FAILED = System.UInt32.MaxValue; // (DWORD)-1 - [DllImport(PinvokeDllNames.CreateFileDllName, CharSet = CharSet.Unicode, SetLastError = true)] - public static extern System.IntPtr CreateFileW( - [In, MarshalAs(UnmanagedType.LPWStr)] string lpFileName, - UInt32 dwDesiredAccess, - UInt32 dwShareMode, - SECURITY_ATTRIBUTES lpSecurityAttributes, - UInt32 dwCreationDisposition, - UInt32 dwFlagsAndAttributes, - System.IntPtr hTemplateFile); - #endif #endregion From 061947969de7208f394475f865549310ee69e104 Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Tue, 6 Dec 2022 21:16:06 -0800 Subject: [PATCH 241/779] Allow non-default encodings to be used in user's script/code (#18605) --- .../engine/AutomationEngine.cs | 11 +++++++++-- .../utils/ClrFacade.cs | 12 +----------- .../utils/EncodingUtils.cs | 16 ++++++++-------- test/powershell/Host/Startup.Tests.ps1 | 1 + .../Scripting/Scripting.Followup.Tests.ps1 | 6 ++++++ 5 files changed, 25 insertions(+), 21 deletions(-) diff --git a/src/System.Management.Automation/engine/AutomationEngine.cs b/src/System.Management.Automation/engine/AutomationEngine.cs index 7da8f4200e5..61952f7739f 100644 --- a/src/System.Management.Automation/engine/AutomationEngine.cs +++ b/src/System.Management.Automation/engine/AutomationEngine.cs @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -using System.Linq; using System.Management.Automation.Host; using System.Management.Automation.Language; using System.Management.Automation.Runspaces; +using System.Text; namespace System.Management.Automation { @@ -14,8 +14,15 @@ namespace System.Management.Automation /// internal class AutomationEngine { + static AutomationEngine() + { + // Register the encoding provider to load encodings that are not supported by default, + // so as to allow them to be used in user's script/code. + Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); + } + // Holds the parser to use for this instance of the engine... - internal Language.Parser EngineParser; + internal Parser EngineParser; /// /// Returns the handle to the execution context diff --git a/src/System.Management.Automation/utils/ClrFacade.cs b/src/System.Management.Automation/utils/ClrFacade.cs index cbd10e6c83a..8905b18087a 100644 --- a/src/System.Management.Automation/utils/ClrFacade.cs +++ b/src/System.Management.Automation/utils/ClrFacade.cs @@ -107,10 +107,8 @@ internal static Encoding GetOEMEncoding() { if (s_oemEncoding == null) { - // load all available encodings - EncodingRegisterProvider(); #if UNIX - s_oemEncoding = new UTF8Encoding(false); + s_oemEncoding = Encoding.Default; #else uint oemCp = Interop.Windows.GetOEMCP(); s_oemEncoding = Encoding.GetEncoding((int)oemCp); @@ -122,14 +120,6 @@ internal static Encoding GetOEMEncoding() private static volatile Encoding s_oemEncoding; - private static void EncodingRegisterProvider() - { - if (s_oemEncoding == null) - { - Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); - } - } - #endregion Encoding #if !UNIX diff --git a/src/System.Management.Automation/utils/EncodingUtils.cs b/src/System.Management.Automation/utils/EncodingUtils.cs index b2ee2d8c877..029de9d94e9 100644 --- a/src/System.Management.Automation/utils/EncodingUtils.cs +++ b/src/System.Management.Automation/utils/EncodingUtils.cs @@ -30,21 +30,21 @@ internal static class EncodingConversion internal static readonly Dictionary encodingMap = new Dictionary(StringComparer.OrdinalIgnoreCase) { - { Ascii, System.Text.Encoding.ASCII }, - { BigEndianUnicode, System.Text.Encoding.BigEndianUnicode }, + { Ascii, Encoding.ASCII }, + { BigEndianUnicode, Encoding.BigEndianUnicode }, { BigEndianUtf32, new UTF32Encoding(bigEndian: true, byteOrderMark: true) }, { Default, Encoding.Default }, { OEM, ClrFacade.GetOEMEncoding() }, - { Unicode, System.Text.Encoding.Unicode }, + { Unicode, Encoding.Unicode }, #pragma warning disable SYSLIB0001 - { Utf7, System.Text.Encoding.UTF7 }, + { Utf7, Encoding.UTF7 }, #pragma warning restore SYSLIB0001 { Utf8, Encoding.Default }, - { Utf8Bom, System.Text.Encoding.UTF8 }, + { Utf8Bom, Encoding.UTF8 }, { Utf8NoBom, Encoding.Default }, - { Utf32, System.Text.Encoding.UTF32 }, - { String, System.Text.Encoding.Unicode }, - { Unknown, System.Text.Encoding.Unicode }, + { Utf32, Encoding.UTF32 }, + { String, Encoding.Unicode }, + { Unknown, Encoding.Unicode }, }; /// diff --git a/test/powershell/Host/Startup.Tests.ps1 b/test/powershell/Host/Startup.Tests.ps1 index ddaa2736a5c..c8df4fe8017 100644 --- a/test/powershell/Host/Startup.Tests.ps1 +++ b/test/powershell/Host/Startup.Tests.ps1 @@ -49,6 +49,7 @@ Describe "Validate start of console host" -Tag CI { 'System.Security.AccessControl.dll' 'System.Security.Cryptography.dll' 'System.Security.Principal.Windows.dll' + 'System.Text.Encoding.CodePages.dll' 'System.Text.Encoding.Extensions.dll' 'System.Text.RegularExpressions.dll' 'System.Threading.dll' diff --git a/test/powershell/Language/Scripting/Scripting.Followup.Tests.ps1 b/test/powershell/Language/Scripting/Scripting.Followup.Tests.ps1 index 960c739499d..888c43b3578 100644 --- a/test/powershell/Language/Scripting/Scripting.Followup.Tests.ps1 +++ b/test/powershell/Language/Scripting/Scripting.Followup.Tests.ps1 @@ -128,4 +128,10 @@ public class NullStringTest { [NullStringTest]::Get([NullString]::Value) | Should -BeExactly 'System.String' [NullStringTest]::Get(@('foo', [NullString]::Value, 'bar')) | Should -BeExactly 'System.String[]; 2nd element is NULL' } + + It 'Non-default encoding should work in PowerShell' { + $powershell = Join-Path -Path $PSHOME -ChildPath "pwsh" + $result = & $powershell -noprofile -c '[System.Text.Encoding]::GetEncoding("IBM437").WebName' + $result | Should -BeExactly "ibm437" + } } From 97fd1421a72debd52e4fd5dd4e723d1b3d05fe0b Mon Sep 17 00:00:00 2001 From: Ikko Ashimine Date: Tue, 13 Dec 2022 03:42:12 +0900 Subject: [PATCH 242/779] Fix typo in OutOfProcTransportManager.cs (#18766) accomodate -> accommodate --- .../engine/remoting/fanin/OutOfProcTransportManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs b/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs index e270a3efeb2..9b8b7b3af3b 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs @@ -1474,7 +1474,7 @@ protected void ProcessReaderThread(object state) { if (e is ArgumentOutOfRangeException) { - Dbg.Assert(false, "Need to adjust transport fragmentor to accomodate read buffer size."); + Dbg.Assert(false, "Need to adjust transport fragmentor to accommodate read buffer size."); } string errorMsg = e.Message ?? string.Empty; From e7c68af8bbd506d136f2cfa7674b5b98e9a7f606 Mon Sep 17 00:00:00 2001 From: Ilya Date: Tue, 13 Dec 2022 00:26:27 +0500 Subject: [PATCH 243/779] Enable pending test for `Start-Process` (#18724) --- .../Start-Process.Tests.ps1 | 43 +++++++++---------- 1 file changed, 21 insertions(+), 22 deletions(-) diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Start-Process.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Start-Process.Tests.ps1 index c097d9700f8..db89dd681fc 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Start-Process.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Start-Process.Tests.ps1 @@ -32,25 +32,25 @@ Describe "Start-Process" -Tag "Feature","RequireAdminOnWindows" { It "Should process arguments without error" { $process = Start-Process ping -ArgumentList $pingParam -PassThru -RedirectStandardOutput "$TESTDRIVE/output" @extraArgs - $process.Length | Should -Be 1 - $process.Id | Should -BeGreaterThan 1 - # $process.ProcessName | Should -Be "ping" + $process.Length | Should -Be 1 + $process.Id | Should -BeGreaterThan 1 + # $process.ProcessName | Should -Be "ping" } It "Should work correctly when used with full path name" { $process = Start-Process $pingCommand -ArgumentList $pingParam -PassThru -RedirectStandardOutput "$TESTDRIVE/output" @extraArgs - $process.Length | Should -Be 1 - $process.Id | Should -BeGreaterThan 1 - # $process.ProcessName | Should -Be "ping" + $process.Length | Should -Be 1 + $process.Id | Should -BeGreaterThan 1 + # $process.ProcessName | Should -Be "ping" } It "Should invoke correct path when used with FilePath argument" { $process = Start-Process -FilePath $pingCommand -ArgumentList $pingParam -PassThru -RedirectStandardOutput "$TESTDRIVE/output" @extraArgs - $process.Length | Should -Be 1 - $process.Id | Should -BeGreaterThan 1 - # $process.ProcessName | Should -Be "ping" + $process.Length | Should -Be 1 + $process.Id | Should -BeGreaterThan 1 + # $process.ProcessName | Should -Be "ping" } It "Should invoke correct path when used with Path alias argument" { @@ -67,26 +67,26 @@ Describe "Start-Process" -Tag "Feature","RequireAdminOnWindows" { It "Should work correctly with WorkingDirectory argument" { $process = Start-Process ping -WorkingDirectory $pingDirectory -ArgumentList $pingParam -PassThru -RedirectStandardOutput "$TESTDRIVE/output" @extraArgs - $process.Length | Should -Be 1 - $process.Id | Should -BeGreaterThan 1 - # $process.ProcessName | Should -Be "ping" + $process.Length | Should -Be 1 + $process.Id | Should -BeGreaterThan 1 + # $process.ProcessName | Should -Be "ping" } - + It "Should work correctly within an unspecified WorkingDirectory with wildcard-type characters" { Push-Location -LiteralPath $tempDirectory - $process = Start-Process ping -ArgumentList $pingParam -PassThru -RedirectStandardOutput "$TESTDRIVE/output" @extraArgs - $process.Length | Should -Be 1 - $process.Id | Should -BeGreaterThan 1 - # $process.ProcessName | Should -Be "ping" + $process = Start-Process ping -ArgumentList $pingParam -PassThru -RedirectStandardOutput "$TESTDRIVE/output" @extraArgs + $process.Length | Should -Be 1 + $process.Id | Should -BeGreaterThan 1 + # $process.ProcessName | Should -Be "ping" Pop-Location } It "Should handle stderr redirection without error" { $process = Start-Process ping -ArgumentList $pingParam -PassThru -RedirectStandardError $tempFile -RedirectStandardOutput "$TESTDRIVE/output" @extraArgs - $process.Length | Should -Be 1 - $process.Id | Should -BeGreaterThan 1 - # $process.ProcessName | Should -Be "ping" + $process.Length | Should -Be 1 + $process.Id | Should -BeGreaterThan 1 + # $process.ProcessName | Should -Be "ping" } It "Should handle stdout redirection without error" { @@ -95,8 +95,7 @@ Describe "Start-Process" -Tag "Feature","RequireAdminOnWindows" { $dirEntry.Length | Should -BeGreaterThan 0 } - # Marking this test 'pending' to unblock daily builds. Filed issue : https://github.com/PowerShell/PowerShell/issues/2396 - It "Should handle stdin redirection without error" -Pending { + It "Should handle stdin redirection without error" { $process = Start-Process sort -Wait -RedirectStandardOutput $tempFile -RedirectStandardInput $assetsFile @extraArgs $dirEntry = Get-ChildItem $tempFile $dirEntry.Length | Should -BeGreaterThan 0 From b6f83e752012f1006ab003afe06b6fbc23f27eb1 Mon Sep 17 00:00:00 2001 From: MartinGC94 <42123497+MartinGC94@users.noreply.github.com> Date: Tue, 13 Dec 2022 06:40:35 +0100 Subject: [PATCH 244/779] Add output types to Format commands (#18746) --- .../utility/FormatAndOutput/format-list/Format-List.cs | 3 ++- .../utility/FormatAndOutput/format-object/Format-Object.cs | 3 ++- .../utility/FormatAndOutput/format-table/Format-Table.cs | 3 ++- .../utility/FormatAndOutput/format-wide/Format-Wide.cs | 3 ++- 4 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-list/Format-List.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-list/Format-List.cs index 7237cd46834..182ea53e258 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-list/Format-List.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-list/Format-List.cs @@ -8,9 +8,10 @@ namespace Microsoft.PowerShell.Commands { /// - /// Implementation for the format-table command. + /// Implementation for the Format-List command. /// [Cmdlet(VerbsCommon.Format, "List", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096928")] + [OutputType(typeof(FormatStartData), typeof(FormatEntryData), typeof(FormatEndData), typeof(GroupStartData), typeof(GroupEndData))] public class FormatListCommand : OuterFormatTableAndListBase { /// diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-object/Format-Object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-object/Format-Object.cs index 9e064ba37db..cd965431c36 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-object/Format-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-object/Format-Object.cs @@ -8,9 +8,10 @@ namespace Microsoft.PowerShell.Commands { /// - /// Implementation for the format-custom command. It just calls the formatting engine on complex shape. + /// Implementation for the Format-Custom command. It just calls the formatting engine on complex shape. /// [Cmdlet(VerbsCommon.Format, "Custom", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096929")] + [OutputType(typeof(FormatStartData), typeof(FormatEntryData), typeof(FormatEndData), typeof(GroupStartData), typeof(GroupEndData))] public class FormatCustomCommand : OuterFormatShapeCommandBase { /// diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-table/Format-Table.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-table/Format-Table.cs index e831981568e..a9e35fcdbc3 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-table/Format-Table.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-table/Format-Table.cs @@ -8,9 +8,10 @@ namespace Microsoft.PowerShell.Commands { /// - /// Implementation for the format-table command. + /// Implementation for the Format-Table command. /// [Cmdlet(VerbsCommon.Format, "Table", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096703")] + [OutputType(typeof(FormatStartData), typeof(FormatEntryData), typeof(FormatEndData), typeof(GroupStartData), typeof(GroupEndData))] public class FormatTableCommand : OuterFormatTableBase { /// diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-wide/Format-Wide.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-wide/Format-Wide.cs index b3e593160b5..ba7cff6a08e 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-wide/Format-Wide.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-wide/Format-Wide.cs @@ -10,9 +10,10 @@ namespace Microsoft.PowerShell.Commands { /// - /// Implementation for the format-table command. + /// Implementation for the Format-Wide command. /// [Cmdlet(VerbsCommon.Format, "Wide", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096930")] + [OutputType(typeof(FormatStartData), typeof(FormatEntryData), typeof(FormatEndData), typeof(GroupStartData), typeof(GroupEndData))] public class FormatWideCommand : OuterFormatShapeCommandBase { /// From c3a080caf9c46c2a742b032e4a85d05c21129fe4 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Tue, 13 Dec 2022 14:18:16 +0100 Subject: [PATCH 245/779] WebResponseObject.Common merge partials atomic commits (#18703) --- .../Common/WebResponseObject.Common.cs | 152 +++++++----------- 1 file changed, 58 insertions(+), 94 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebResponseObject.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebResponseObject.Common.cs index 6f9c14638f9..f92296905e0 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebResponseObject.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebResponseObject.Common.cs @@ -13,48 +13,26 @@ namespace Microsoft.PowerShell.Commands /// /// WebResponseObject. /// - public partial class WebResponseObject + public class WebResponseObject { #region Properties /// - /// Gets or protected sets the response body content. - /// - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public byte[] Content { get; protected set; } - - /// - /// Gets the response status code. + /// Gets or sets the BaseResponse property. /// - public int StatusCode - { - get { return (WebResponseHelper.GetStatusCode(BaseResponse)); } - } + public HttpResponseMessage BaseResponse { get; set; } /// - /// Gets the response status description. + /// Gets or protected sets the response body content. /// - public string StatusDescription - { - get { return (WebResponseHelper.GetStatusDescription(BaseResponse)); } - } + public byte[] Content { get; protected set; } - private MemoryStream _rawContentStream; /// - /// Gets the response body content as a . + /// Gets the Headers property. /// - public MemoryStream RawContentStream - { - get { return (_rawContentStream); } - } + public Dictionary> Headers => _headers ??= WebResponseHelper.GetHeadersDictionary(BaseResponse); - /// - /// Gets the length (in bytes) of . - /// - public long RawContentLength - { - get { return (RawContentStream == null ? -1 : RawContentStream.Length); } - } + private Dictionary> _headers = null; /// /// Gets or protected sets the full response content. @@ -64,79 +42,32 @@ public long RawContentLength /// public string RawContent { get; protected set; } - #endregion Properties - - #region Methods - /// - /// Reads the response content from the web response. + /// Gets the length (in bytes) of . /// - private void InitializeContent() - { - this.Content = this.RawContentStream.ToArray(); - } - - private static bool IsPrintable(char c) - { - return (char.IsLetterOrDigit(c) || char.IsPunctuation(c) || char.IsSeparator(c) || char.IsSymbol(c) || char.IsWhiteSpace(c)); - } + public long RawContentLength => RawContentStream is null ? -1 : RawContentStream.Length; /// - /// Returns the string representation of this web response. + /// Gets or protected sets the response body content as a . /// - /// The string representation of this web response. - public sealed override string ToString() - { - char[] stringContent = System.Text.Encoding.ASCII.GetChars(Content); - for (int counter = 0; counter < stringContent.Length; counter++) - { - if (!IsPrintable(stringContent[counter])) - { - stringContent[counter] = '.'; - } - } - - return new string(stringContent); - } - - #endregion Methods - } - - // TODO: Merge Partials - - /// - /// WebResponseObject. - /// - public partial class WebResponseObject - { - #region Properties + public MemoryStream RawContentStream { get; protected set; } /// - /// Gets or sets the BaseResponse property. + /// Gets the RelationLink property. /// - public HttpResponseMessage BaseResponse { get; set; } + public Dictionary RelationLink { get; internal set; } /// - /// Gets the Headers property. + /// Gets the response status code. /// - public Dictionary> Headers - { - get - { - _headers ??= WebResponseHelper.GetHeadersDictionary(BaseResponse); - - return _headers; - } - } - - private Dictionary> _headers = null; + public int StatusCode => WebResponseHelper.GetStatusCode(BaseResponse); /// - /// Gets the RelationLink property. + /// Gets the response status description. /// - public Dictionary RelationLink { get; internal set; } + public string StatusDescription => WebResponseHelper.GetStatusDescription(BaseResponse); - #endregion + #endregion Properties #region Constructors @@ -165,6 +96,14 @@ public WebResponseObject(HttpResponseMessage response, Stream contentStream) #region Methods + /// + /// Reads the response content from the web response. + /// + private void InitializeContent() + { + this.Content = this.RawContentStream.ToArray(); + } + private void InitializeRawContent(HttpResponseMessage baseResponse) { StringBuilder raw = ContentHelper.GetRawContentHeader(baseResponse); @@ -178,21 +117,27 @@ private void InitializeRawContent(HttpResponseMessage baseResponse) this.RawContent = raw.ToString(); } + private static bool IsPrintable(char c) => char.IsLetterOrDigit(c) + || char.IsPunctuation(c) + || char.IsSeparator(c) + || char.IsSymbol(c) + || char.IsWhiteSpace(c); + private void SetResponse(HttpResponseMessage response, Stream contentStream) { - if (response == null) { throw new ArgumentNullException(nameof(response)); } + if (response is null) { throw new ArgumentNullException(nameof(response)); } BaseResponse = response; MemoryStream ms = contentStream as MemoryStream; if (ms != null) { - _rawContentStream = ms; + RawContentStream = ms; } else { Stream st = contentStream; - if (contentStream == null) + if (contentStream is null) { st = StreamHelper.GetResponseStream(response); } @@ -204,11 +149,30 @@ private void SetResponse(HttpResponseMessage response, Stream contentStream) } int initialCapacity = (int)Math.Min(contentLength, StreamHelper.DefaultReadBuffer); - _rawContentStream = new WebResponseContentMemoryStream(st, initialCapacity, cmdlet: null, response.Content.Headers.ContentLength.GetValueOrDefault()); + RawContentStream = new WebResponseContentMemoryStream(st, initialCapacity, cmdlet: null, response.Content.Headers.ContentLength.GetValueOrDefault()); } // set the position of the content stream to the beginning - _rawContentStream.Position = 0; + RawContentStream.Position = 0; } - #endregion + + /// + /// Returns the string representation of this web response. + /// + /// The string representation of this web response. + public sealed override string ToString() + { + char[] stringContent = System.Text.Encoding.ASCII.GetChars(Content); + for (int counter = 0; counter < stringContent.Length; counter++) + { + if (!IsPrintable(stringContent[counter])) + { + stringContent[counter] = '.'; + } + } + + return new string(stringContent); + } + + #endregion Methods } } From eb9ca7c351f3b0e0a4c678313389c05fbe0d0087 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Tue, 13 Dec 2022 09:09:28 -0800 Subject: [PATCH 246/779] Fix `New-Item -ItemType Hardlink` to resolve target to absolute path and not allow link to itself (#18634) --- .../namespaces/FileSystemProvider.cs | 14 ++++++++++++++ .../resources/FileSystemProviderStrings.resx | 5 ++++- .../FileSystem.Tests.ps1 | 18 ++++++++++++++++++ 3 files changed, 36 insertions(+), 1 deletion(-) diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index 34e4b01d4a3..dbd80ceaa6f 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -2251,6 +2251,13 @@ protected override void NewItem( } else { + // for hardlinks we resolve the target to an absolute path + if (!IsAbsolutePath(strTargetPath)) + { + // there is already a check before here so that strTargetPath should only resolve to 1 path + strTargetPath = SessionState.Path.GetResolvedPSPathFromPSPath(strTargetPath).FirstOrDefault()?.Path; + } + exists = GetFileSystemInfo(strTargetPath, out isDirectory) != null; } } @@ -2293,6 +2300,13 @@ protected override void NewItem( if (Force) { + if (itemType == ItemType.HardLink && string.Equals(path, strTargetPath, StringComparison.OrdinalIgnoreCase)) + { + string message = StringUtil.Format(FileSystemProviderStrings.NewItemTargetIsSameAsLink, path); + WriteError(new ErrorRecord(new InvalidOperationException(message), "TargetIsSameAsLink", ErrorCategory.InvalidOperation, path)); + return; + } + try { if (!isSymLinkDirectory && symLinkExists) diff --git a/src/System.Management.Automation/resources/FileSystemProviderStrings.resx b/src/System.Management.Automation/resources/FileSystemProviderStrings.resx index 894fe5f6afd..436e03df32e 100644 --- a/src/System.Management.Automation/resources/FileSystemProviderStrings.resx +++ b/src/System.Management.Automation/resources/FileSystemProviderStrings.resx @@ -328,7 +328,7 @@ Maximum size for drive has been exceeded: {0}. - Cannot create symbolic link because the path {0} already exists. + Cannot create link because the path already exists: {0}. Skip already-visited directory {0}. @@ -336,4 +336,7 @@ Destination path cannot be a subdirectory of the source: {0}. + + The target and path cannot be the same. + diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/FileSystem.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/FileSystem.Tests.ps1 index bec4ad83b80..5e55630c06c 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/FileSystem.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/FileSystem.Tests.ps1 @@ -600,6 +600,24 @@ Describe "Hard link and symbolic link tests" -Tags "CI", "RequireAdminOnWindows" New-Item -ItemType Junction -Path $junctionToDir -Value $realDir > $null Test-Path $junctionToDir | Should -BeTrue } + + It 'New-Item can create hardlink with relative path' { + try { + Push-Location $TestDrive + 1 > 1.txt + New-Item -ItemType HardLink -Path 2.txt -Target 1.txt -ErrorAction Stop + $hl = Get-Item -Path .\2.txt -ErrorAction Stop + $hl.LinkType | Should -BeExactly "HardLink" + } + finally { + Pop-Location + } + } + + It 'New-Item will fail to forcibly create hardlink to itself' { + $i = New-Item -ItemType File -Path "$TestDrive\file.txt" -Force -ErrorAction Ignore + { New-Item -ItemType HardLink -Path $i -Target $i -Force -ErrorAction Stop } | Should -Throw -ErrorId "TargetIsSameAsLink,Microsoft.PowerShell.Commands.NewItemCommand" + } } Context "Get-ChildItem and symbolic links" { From bc3b0d60e65c52a012b613e8d32bfdade70108ee Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Tue, 13 Dec 2022 09:36:11 -0800 Subject: [PATCH 247/779] Update readme and metadata form 7.3.1 and 7.2.8 release (#18780) * Update readme and metadata form 7.3.1 and 7.2.8 release * Revert "Update readme and metadata form 7.3.1 and 7.2.8 release" This reverts commit 2af4b6d53870b402fc81de483f1f5fc11fd75efd. --- README.md | 54 ++++++++++++++++++++++----------------------- tools/metadata.json | 6 ++--- 2 files changed, 30 insertions(+), 30 deletions(-) diff --git a/README.md b/README.md index 1f4f2018dbb..1da7248e30e 100644 --- a/README.md +++ b/README.md @@ -64,33 +64,33 @@ You can also download the PowerShell binary archives for Windows, macOS and Linu | Windows (Arm) | [64-bit][rl-winarm64] (preview) | [64-bit][pv-winarm64] | [Instructions][in-arm] | | Raspbian (Arm) | [32-bit][rl-arm32]/[64-bit][rl-arm64] | [32-bit][pv-arm32]/[64-bit][pv-arm64] | [Instructions][in-raspbian] | -[lts-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.7/PowerShell-7.2.7-win-x86.msi -[lts-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.7/PowerShell-7.2.7-win-x64.msi -[lts-deb]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.7/powershell-lts_7.2.7-1.deb_amd64.deb -[lts-rh]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.7/powershell-lts-7.2.7-1.rh.x86_64.rpm -[lts-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.7/powershell-lts-7.2.7-osx-x64.pkg -[lts-macos-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.7/powershell-lts-7.2.7-osx-arm64.pkg - -[rl-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0/PowerShell-7.3.0-win-x64.msi -[rl-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0/PowerShell-7.3.0-win-x86.msi -[rl-ubuntu20]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0/powershell_7.3.0-1.deb_amd64.deb -[rl-ubuntu18]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0/powershell_7.3.0-1.deb_amd64.deb -[rl-ubuntu16]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0/powershell_7.3.0-1.deb_amd64.deb -[rl-debian9]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0/powershell_7.3.0-1.deb_amd64.deb -[rl-debian10]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0/powershell_7.3.0-1.deb_amd64.deb -[rl-debian11]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0/powershell_7.3.0-1.deb_amd64.deb -[rl-centos]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0/powershell-7.3.0-1.rh.x86_64.rpm -[rl-centos8]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0/powershell-7.3.0-1.rh.x86_64.rpm -[rl-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0/powershell-7.3.0-osx-x64.pkg -[rl-macos-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0/powershell-7.3.0-osx-arm64.pkg -[rl-winarm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0/PowerShell-7.3.0-win-arm64.zip -[rl-winx86-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0/PowerShell-7.3.0-win-x86.zip -[rl-winx64-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0/PowerShell-7.3.0-win-x64.zip -[rl-macos-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0/powershell-7.3.0-osx-x64.tar.gz -[rl-macos-tar-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0/powershell-7.3.0-osx-arm64.tar.gz -[rl-linux-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0/powershell-7.3.0-linux-x64.tar.gz -[rl-arm32]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0/powershell-7.3.0-linux-arm32.tar.gz -[rl-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0/powershell-7.3.0-linux-arm64.tar.gz +[lts-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.8/PowerShell-7.2.8-win-x86.msi +[lts-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.8/PowerShell-7.2.8-win-x64.msi +[lts-deb]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.8/powershell-lts_7.2.8-1.deb_amd64.deb +[lts-rh]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.8/powershell-lts-7.2.8-1.rh.x86_64.rpm +[lts-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.8/powershell-lts-7.2.8-osx-x64.pkg +[lts-macos-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.8/powershell-lts-7.2.8-osx-arm64.pkg + +[rl-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.1/PowerShell-7.3.1-win-x64.msi +[rl-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.1/PowerShell-7.3.1-win-x86.msi +[rl-ubuntu20]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.1/powershell_7.3.1-1.deb_amd64.deb +[rl-ubuntu18]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.1/powershell_7.3.1-1.deb_amd64.deb +[rl-ubuntu16]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.1/powershell_7.3.1-1.deb_amd64.deb +[rl-debian9]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.1/powershell_7.3.1-1.deb_amd64.deb +[rl-debian10]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.1/powershell_7.3.1-1.deb_amd64.deb +[rl-debian11]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.1/powershell_7.3.1-1.deb_amd64.deb +[rl-centos]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.1/powershell-7.3.1-1.rh.x86_64.rpm +[rl-centos8]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.1/powershell-7.3.1-1.rh.x86_64.rpm +[rl-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.1/powershell-7.3.1-osx-x64.pkg +[rl-macos-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.1/powershell-7.3.1-osx-arm64.pkg +[rl-winarm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.1/PowerShell-7.3.1-win-arm64.zip +[rl-winx86-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.1/PowerShell-7.3.1-win-x86.zip +[rl-winx64-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.1/PowerShell-7.3.1-win-x64.zip +[rl-macos-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.1/powershell-7.3.1-osx-x64.tar.gz +[rl-macos-tar-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.1/powershell-7.3.1-osx-arm64.tar.gz +[rl-linux-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.1/powershell-7.3.1-linux-x64.tar.gz +[rl-arm32]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.1/powershell-7.3.1-linux-arm32.tar.gz +[rl-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.1/powershell-7.3.1-linux-arm64.tar.gz [rl-snap]: https://snapcraft.io/powershell [pv-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-rc.1/PowerShell-7.3.0-rc.1-win-x64.msi diff --git a/tools/metadata.json b/tools/metadata.json index 9b834950bef..bf3fddb126d 100644 --- a/tools/metadata.json +++ b/tools/metadata.json @@ -1,9 +1,9 @@ { - "StableReleaseTag": "v7.3.0", + "StableReleaseTag": "v7.3.1", "PreviewReleaseTag": "v7.3.0-rc.1", "ServicingReleaseTag": "v7.0.13", - "ReleaseTag": "v7.3.0", - "LTSReleaseTag" : ["v7.2.7", "v7.0.13"], + "ReleaseTag": "v7.3.1", + "LTSReleaseTag" : ["v7.2.8", "v7.0.13"], "NextReleaseTag": "v7.3.0-preview.9", "LTSRelease": { "Latest": false, "Package": false }, "StableRelease": { "Latest": false, "Package": false } From 4ff581e906329d22053c6f0420a75742849a541c Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Tue, 13 Dec 2022 18:13:18 +0000 Subject: [PATCH 248/779] Replace `GetDirectories` in `CimDscParser` (#14319) --- .../DscSupport/CimDSCParser.cs | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/System.Management.Automation/DscSupport/CimDSCParser.cs b/src/System.Management.Automation/DscSupport/CimDSCParser.cs index d94e41998ac..d13deea5d67 100644 --- a/src/System.Management.Automation/DscSupport/CimDSCParser.cs +++ b/src/System.Management.Automation/DscSupport/CimDSCParser.cs @@ -3250,14 +3250,15 @@ public static bool ImportCimKeywordsFromModule(PSModuleInfo module, string resou // try { - var dscResourceDirectories = Directory.GetDirectories(dscResourcesPath); - foreach (var directory in dscResourceDirectories) + foreach (var directory in Directory.EnumerateDirectories(dscResourcesPath)) { - var schemaFiles = Directory.GetFiles(directory, "*.schema.mof", SearchOption.TopDirectoryOnly); - if (schemaFiles.Length > 0) + IEnumerable schemaFiles = Directory.EnumerateFiles(directory, "*.schema.mof", SearchOption.TopDirectoryOnly); + string tempSchemaFilepath = schemaFiles.FirstOrDefault(); + + Debug.Assert(schemaFiles.Count() == 1, "A valid DSCResource module can have only one schema mof file"); + + if (tempSchemaFilepath is not null) { - Debug.Assert(schemaFiles.Length == 1, "A valid DSCResource module can have only one schema mof file"); - var tempSchemaFilepath = schemaFiles[0]; var classes = GetCachedClassByFileName(tempSchemaFilepath) ?? ImportClasses(tempSchemaFilepath, new Tuple(module.Name, module.Version), errors); if (classes != null) { From 88077bd98560d9bd98291a6b9a8e9a29ced9b970 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Wed, 14 Dec 2022 05:48:13 +0100 Subject: [PATCH 249/779] InvokeRestMethodCommand.Common cleanup and merge partials (#18736) --- .../Common/InvokeRestMethodCommand.Common.cs | 286 ++++++++---------- 1 file changed, 133 insertions(+), 153 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs index 3847fd9bab8..9876d0a2ca2 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs @@ -13,7 +13,15 @@ namespace Microsoft.PowerShell.Commands { - public partial class InvokeRestMethodCommand + /// + /// The Invoke-RestMethod command + /// This command makes an HTTP or HTTPS request to a web service, + /// and returns the response in an appropriate way. + /// Intended to work against the wide spectrum of "RESTful" web services + /// currently deployed across the web. + /// + [Cmdlet(VerbsLifecycle.Invoke, "RestMethod", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096706", DefaultParameterSetName = "StandardMethod")] + public class InvokeRestMethodCommand : WebRequestPSCmdlet { #region Parameters @@ -83,8 +91,124 @@ public int MaximumFollowRelLink #endregion Parameters + #region Virtual Method Overrides + + /// + /// Process the web response and output corresponding objects. + /// + /// + internal override void ProcessResponse(HttpResponseMessage response) + { + if (response == null) { throw new ArgumentNullException(nameof(response)); } + + var baseResponseStream = StreamHelper.GetResponseStream(response); + + if (ShouldWriteToPipeline) + { + using var responseStream = new BufferingStreamReader(baseResponseStream); + + // First see if it is an RSS / ATOM feed, in which case we can + // stream it - unless the user has overridden it with a return type of "XML" + if (TryProcessFeedStream(responseStream)) + { + // Do nothing, content has been processed. + } + else + { + // determine the response type + RestReturnType returnType = CheckReturnType(response); + + // Try to get the response encoding from the ContentType header. + Encoding encoding = null; + string charSet = response.Content.Headers.ContentType?.CharSet; + if (!string.IsNullOrEmpty(charSet)) + { + StreamHelper.TryGetEncoding(charSet, out encoding); + } + + object obj = null; + Exception ex = null; + + string str = StreamHelper.DecodeStream(responseStream, ref encoding); + + string encodingVerboseName; + try + { + encodingVerboseName = string.IsNullOrEmpty(encoding.HeaderName) ? encoding.EncodingName : encoding.HeaderName; + } + catch (NotSupportedException) + { + encodingVerboseName = encoding.EncodingName; + } + + // NOTE: Tests use this verbose output to verify the encoding. + WriteVerbose(string.Format(System.Globalization.CultureInfo.InvariantCulture, "Content encoding: {0}", encodingVerboseName)); + + bool convertSuccess = false; + + if (returnType == RestReturnType.Json) + { + convertSuccess = TryConvertToJson(str, out obj, ref ex) || TryConvertToXml(str, out obj, ref ex); + } + // default to try xml first since it's more common + else + { + convertSuccess = TryConvertToXml(str, out obj, ref ex) || TryConvertToJson(str, out obj, ref ex); + } + + if (!convertSuccess) + { + // fallback to string + obj = str; + } + + WriteObject(obj); + } + } + else if (ShouldSaveToOutFile) + { + StreamHelper.SaveStreamToFile(baseResponseStream, QualifiedOutFile, this, response.Content.Headers.ContentLength.GetValueOrDefault(), _cancelToken.Token); + } + + if (!string.IsNullOrEmpty(StatusCodeVariable)) + { + PSVariableIntrinsics vi = SessionState.PSVariable; + vi.Set(StatusCodeVariable, (int)response.StatusCode); + } + + if (!string.IsNullOrEmpty(ResponseHeadersVariable)) + { + PSVariableIntrinsics vi = SessionState.PSVariable; + vi.Set(ResponseHeadersVariable, WebResponseHelper.GetHeadersDictionary(response)); + } + } + + #endregion Virtual Method Overrides + #region Helper Methods + private static RestReturnType CheckReturnType(HttpResponseMessage response) + { + if (response == null) { throw new ArgumentNullException(nameof(response)); } + + RestReturnType rt = RestReturnType.Detect; + string contentType = ContentHelper.GetContentType(response); + if (string.IsNullOrEmpty(contentType)) + { + rt = RestReturnType.Detect; + } + else if (ContentHelper.IsJson(contentType)) + { + rt = RestReturnType.Json; + } + else if (ContentHelper.IsXml(contentType)) + { + rt = RestReturnType.Xml; + } + + return rt; + } + private bool TryProcessFeedStream(Stream responseStream) { bool isRssOrFeed = false; @@ -111,7 +235,8 @@ private bool TryProcessFeedStream(Stream responseStream) if (isRssOrFeed) { XmlDocument workingDocument = new(); - // performing a Read() here to avoid rrechecking + + // Performing a Read() here to avoid rechecking // "rss" or "feed" items reader.Read(); while (!reader.EOF) @@ -122,7 +247,7 @@ private bool TryProcessFeedStream(Stream responseStream) string.Equals("Entry", reader.Name, StringComparison.OrdinalIgnoreCase)) ) { - // this one will do reader.Read() internally + // This one will do reader.Read() internally XmlNode result = workingDocument.ReadNode(reader); WriteObject(result); } @@ -178,7 +303,7 @@ private static bool TryConvertToXml(string xml, out object doc, ref Exception ex doc = null; } - return (doc != null); + return doc != null; } private static bool TryConvertToJson(string json, out object obj, ref Exception exRef) @@ -226,7 +351,7 @@ private static bool TryConvertToJson(string json, out object obj, ref Exception return converted; } - #endregion + #endregion Helper Methods /// /// Enum for rest return type. @@ -265,20 +390,11 @@ internal BufferingStreamReader(Stream baseStream) private readonly MemoryStream _streamBuffer; private readonly byte[] _copyBuffer; - public override bool CanRead - { - get { return true; } - } + public override bool CanRead => true; - public override bool CanSeek - { - get { return true; } - } + public override bool CanSeek => true; - public override bool CanWrite - { - get { return false; } - } + public override bool CanWrite => false; public override void Flush() { @@ -359,140 +475,4 @@ public override void Write(byte[] buffer, int offset, int count) } } } - - // TODO: Merge Partials - - /// - /// The Invoke-RestMethod command - /// This command makes an HTTP or HTTPS request to a web service, - /// and returns the response in an appropriate way. - /// Intended to work against the wide spectrum of "RESTful" web services - /// currently deployed across the web. - /// - [Cmdlet(VerbsLifecycle.Invoke, "RestMethod", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096706", DefaultParameterSetName = "StandardMethod")] - public partial class InvokeRestMethodCommand : WebRequestPSCmdlet - { - #region Virtual Method Overrides - - /// - /// Process the web response and output corresponding objects. - /// - /// - internal override void ProcessResponse(HttpResponseMessage response) - { - if (response == null) { throw new ArgumentNullException(nameof(response)); } - - var baseResponseStream = StreamHelper.GetResponseStream(response); - - if (ShouldWriteToPipeline) - { - using var responseStream = new BufferingStreamReader(baseResponseStream); - - // First see if it is an RSS / ATOM feed, in which case we can - // stream it - unless the user has overridden it with a return type of "XML" - if (TryProcessFeedStream(responseStream)) - { - // Do nothing, content has been processed. - } - else - { - // determine the response type - RestReturnType returnType = CheckReturnType(response); - - // Try to get the response encoding from the ContentType header. - Encoding encoding = null; - string charSet = response.Content.Headers.ContentType?.CharSet; - if (!string.IsNullOrEmpty(charSet)) - { - StreamHelper.TryGetEncoding(charSet, out encoding); - } - - object obj = null; - Exception ex = null; - - string str = StreamHelper.DecodeStream(responseStream, ref encoding); - - string encodingVerboseName; - try - { - encodingVerboseName = string.IsNullOrEmpty(encoding.HeaderName) ? encoding.EncodingName : encoding.HeaderName; - } - catch (NotSupportedException) - { - encodingVerboseName = encoding.EncodingName; - } - // NOTE: Tests use this verbose output to verify the encoding. - WriteVerbose(string.Format - ( - System.Globalization.CultureInfo.InvariantCulture, - "Content encoding: {0}", - encodingVerboseName) - ); - bool convertSuccess = false; - - if (returnType == RestReturnType.Json) - { - convertSuccess = TryConvertToJson(str, out obj, ref ex) || TryConvertToXml(str, out obj, ref ex); - } - // default to try xml first since it's more common - else - { - convertSuccess = TryConvertToXml(str, out obj, ref ex) || TryConvertToJson(str, out obj, ref ex); - } - - if (!convertSuccess) - { - // fallback to string - obj = str; - } - - WriteObject(obj); - } - } - else if (ShouldSaveToOutFile) - { - StreamHelper.SaveStreamToFile(baseResponseStream, QualifiedOutFile, this, response.Content.Headers.ContentLength.GetValueOrDefault(), _cancelToken.Token); - } - - if (!string.IsNullOrEmpty(StatusCodeVariable)) - { - PSVariableIntrinsics vi = SessionState.PSVariable; - vi.Set(StatusCodeVariable, (int)response.StatusCode); - } - - if (!string.IsNullOrEmpty(ResponseHeadersVariable)) - { - PSVariableIntrinsics vi = SessionState.PSVariable; - vi.Set(ResponseHeadersVariable, WebResponseHelper.GetHeadersDictionary(response)); - } - } - - #endregion Virtual Method Overrides - - #region Helper Methods - - private static RestReturnType CheckReturnType(HttpResponseMessage response) - { - if (response == null) { throw new ArgumentNullException(nameof(response)); } - - RestReturnType rt = RestReturnType.Detect; - string contentType = ContentHelper.GetContentType(response); - if (string.IsNullOrEmpty(contentType)) - { - rt = RestReturnType.Detect; - } - else if (ContentHelper.IsJson(contentType)) - { - rt = RestReturnType.Json; - } - else if (ContentHelper.IsXml(contentType)) - { - rt = RestReturnType.Xml; - } - - return (rt); - } - - #endregion Helper Methods - } } From 9cc914e1e5df1f251b01c214efb032099668afb8 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Wed, 14 Dec 2022 05:51:15 +0100 Subject: [PATCH 250/779] Cleanup webresponseobject.common (#18785) --- .../WebCmdlet/Common/WebResponseObject.Common.cs | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebResponseObject.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebResponseObject.Common.cs index f92296905e0..8db9064022c 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebResponseObject.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebResponseObject.Common.cs @@ -75,8 +75,7 @@ public class WebResponseObject /// Initializes a new instance of the class. /// /// - public WebResponseObject(HttpResponseMessage response) - : this(response, null) + public WebResponseObject(HttpResponseMessage response) : this(response, null) { } /// @@ -101,7 +100,7 @@ public WebResponseObject(HttpResponseMessage response, Stream contentStream) /// private void InitializeContent() { - this.Content = this.RawContentStream.ToArray(); + Content = RawContentStream.ToArray(); } private void InitializeRawContent(HttpResponseMessage baseResponse) @@ -114,7 +113,7 @@ private void InitializeRawContent(HttpResponseMessage baseResponse) raw.Append(this.ToString()); } - this.RawContent = raw.ToString(); + RawContent = raw.ToString(); } private static bool IsPrintable(char c) => char.IsLetterOrDigit(c) @@ -125,12 +124,12 @@ private static bool IsPrintable(char c) => char.IsLetterOrDigit(c) private void SetResponse(HttpResponseMessage response, Stream contentStream) { - if (response is null) { throw new ArgumentNullException(nameof(response)); } + ArgumentNullException.ThrowIfNull(response); BaseResponse = response; MemoryStream ms = contentStream as MemoryStream; - if (ms != null) + if (ms is not null) { RawContentStream = ms; } From 9d0bac5addf3e9791331c96a3d96191b31d5c662 Mon Sep 17 00:00:00 2001 From: John Bevan Date: Wed, 14 Dec 2022 05:39:41 +0000 Subject: [PATCH 251/779] Implement SupportsShouldProcess in Stop-Transcript (#18731) --- .../host/msh/StopTranscriptCmdlet.cs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/StopTranscriptCmdlet.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/StopTranscriptCmdlet.cs index a48fa105437..71e90854dc4 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/StopTranscriptCmdlet.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/StopTranscriptCmdlet.cs @@ -10,7 +10,7 @@ namespace Microsoft.PowerShell.Commands /// /// Implements the stop-transcript cmdlet. /// - [Cmdlet(VerbsLifecycle.Stop, "Transcript", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096798")] + [Cmdlet(VerbsLifecycle.Stop, "Transcript", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.None, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096798")] [OutputType(typeof(string))] public sealed class StopTranscriptCommand : PSCmdlet { @@ -21,6 +21,11 @@ protected override void BeginProcessing() { + if (!ShouldProcess(string.Empty)) + { + return; + } + try { string outFilename = Host.UI.StopTranscribing(); From b7096e8cb610c3db04b3dde6df2b290f0a62b36d Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Wed, 14 Dec 2022 10:20:53 +0100 Subject: [PATCH 252/779] WebCmdlets get Retry-After from headers if StatusCode is 429 (#18717) --- .../Common/WebRequestPSCmdlet.Common.cs | 26 ++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index 21be97d567e..c47ee9641ca 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -690,7 +690,7 @@ internal virtual void PrepareSession() { WebSession.MaximumRetryCount = MaximumRetryCount; - // only set retry interval if retry count is set. + // Only set retry interval if retry count is set. WebSession.RetryIntervalInSeconds = RetryIntervalSec; } } @@ -1439,16 +1439,36 @@ internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestM // When MaximumRetryCount is not specified, the totalRequests == 1. if (totalRequests > 1 && ShouldRetry(response.StatusCode)) { + int retryIntervalInSeconds = WebSession.RetryIntervalInSeconds; + + // If the status code is 429 get the retry interval from the Headers. + // Ignore broken header and its value. + if (response.StatusCode is HttpStatusCode.Conflict && response.Headers.TryGetValues(HttpKnownHeaderNames.RetryAfter, out IEnumerable retryAfter)) + { + try + { + IEnumerator enumerator = retryAfter.GetEnumerator(); + if (enumerator.MoveNext()) + { + retryIntervalInSeconds = Convert.ToInt32(enumerator.Current); + } + } + catch + { + // Ignore broken header. + } + } + string retryMessage = string.Format( CultureInfo.CurrentCulture, WebCmdletStrings.RetryVerboseMsg, - RetryIntervalSec, + retryIntervalInSeconds, response.StatusCode); WriteVerbose(retryMessage); _cancelToken = new CancellationTokenSource(); - Task.Delay(WebSession.RetryIntervalInSeconds * 1000, _cancelToken.Token).GetAwaiter().GetResult(); + Task.Delay(retryIntervalInSeconds * 1000, _cancelToken.Token).GetAwaiter().GetResult(); _cancelToken.Cancel(); _cancelToken = null; From 2ddc63f1512e35f8dce696ae10de49f8f69a2738 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Wed, 14 Dec 2022 14:30:33 +0100 Subject: [PATCH 253/779] Replace ArgumentNullException(nameof()) -> ArgumentNullException.ThrowIfNull() (#18784) --- .../HelpWindow/ParagraphBuilder.cs | 10 +--- .../Common/IntegralConverter.cs | 5 +- .../Common/InverseBooleanConverter.cs | 5 +- .../ManagementList/Common/IsEqualConverter.cs | 5 +- .../Common/StringFormatConverter.cs | 5 +- .../ManagementList/Common/Utilities.cs | 10 +--- .../Common/VisualToAncestorDataConverter.cs | 10 +--- .../Common/WeakEventListener.cs | 5 +- .../ManagementList/Common/WpfHelp.cs | 36 +++-------- .../ResizerGripThicknessConverter.cs | 5 +- .../DefaultFilterRuleCustomizationFactory.cs | 35 +++-------- .../FilterCore/FilterEvaluator.cs | 10 +--- .../FilterCore/FilterExceptionEventArgs.cs | 5 +- .../FilterExpressionAndOperatorNode.cs | 5 +- .../FilterExpressionOperandNode.cs | 5 +- .../FilterExpressionOrOperatorNode.cs | 5 +- .../FilterRuleCustomizationFactory.cs | 5 +- .../FilterRules/FilterRuleExtensions.cs | 5 +- .../PropertyValueSelectorFilterRule.cs | 5 +- .../FilterCore/FilterRules/TextFilterRule.cs | 10 +--- .../FilterCore/ValidatingValue.cs | 5 +- .../FilterCore/ValidatingValueBase.cs | 10 +--- .../FilterProviders/FilterRulePanel.cs | 15 +---- .../FilterRulePanelController.cs | 10 +--- .../FilterProviders/FilterRulePanelItem.cs | 5 +- .../InputFieldBackgroundTextConverter.cs | 5 +- .../FilterProviders/SearchBox.cs | 10 +--- .../FilterProviders/SearchTextParseResult.cs | 5 +- .../FilterProviders/SearchTextParser.cs | 25 ++------ ...tingSelectorValueToDisplayNameConverter.cs | 5 +- .../ManagementList/ColumnPicker.xaml.cs | 12 +--- .../ManagementList/InnerListGridView.cs | 5 +- .../ManagementList/Innerlist.cs | 5 +- .../ManagementListStateDescriptor.cs | 10 +--- .../ManagementList/PropertyValueGetter.cs | 5 +- .../ManagementList/innerlistcolumn.cs | 5 +- .../ManagementList/managementlist.cs | 20 ++----- .../ViewModel/AllModulesViewModel.cs | 5 +- .../ShowCommand/ViewModel/CommandViewModel.cs | 5 +- .../ShowCommand/ViewModel/ModuleViewModel.cs | 5 +- .../ViewModel/ParameterSetViewModel.cs | 10 +--- .../ViewModel/ParameterViewModel.cs | 10 +--- .../cmdletization/SessionBasedWrapper.cs | 7 ++- .../cmdletization/cim/CimJobException.cs | 10 +--- .../cmdletization/cim/cimConverter.cs | 2 +- .../cimSupport/cmdletization/cim/cimQuery.cs | 5 +- .../commands/management/Process.cs | 5 +- .../commands/management/Service.cs | 10 +--- .../commands/utility/CsvCommands.cs | 25 ++------ .../OutGridView/OutWindowProxy.cs | 25 ++------ .../commands/utility/MatchString.cs | 5 +- .../commands/utility/Select-Object.cs | 5 +- .../ShowCommand/ShowCommandCommandInfo.cs | 10 +--- .../ShowCommand/ShowCommandModuleInfo.cs | 10 +--- .../ShowCommand/ShowCommandParameterInfo.cs | 10 +--- .../ShowCommandParameterSetInfo.cs | 10 +--- .../ShowCommand/ShowCommandParameterType.cs | 10 +--- .../Common/InvokeRestMethodCommand.Common.cs | 2 +- .../Common/WebRequestPSCmdlet.Common.cs | 52 ++++++---------- .../InvokeWebRequestCommand.CoreClr.cs | 2 +- .../utility/WebCmdlet/CoreCLR/WebProxy.cs | 10 +--- .../commands/utility/WebCmdlet/JsonObject.cs | 5 +- .../utility/WebCmdlet/StreamHelper.cs | 5 +- .../utility/trace/TraceExpressionCommand.cs | 12 +--- .../host/msh/ConsoleHost.cs | 2 +- .../host/msh/ManagedEntrance.cs | 5 +- .../host/msh/ProgressPane.cs | 2 +- .../DotNetCode/Eventing/EventProvider.cs | 10 +--- .../Eventing/EventProviderTraceListener.cs | 3 +- .../LocalAccounts/Sam.cs | 3 +- .../ScheduledJobTrigger.cs | 15 +---- .../CurrentConfigurations.cs | 25 ++------ src/Microsoft.WSMan.Management/WsManHelper.cs | 5 +- .../FormatAndOutput/common/PSStyle.cs | 5 +- .../cmdletization/MethodInvocationInfo.cs | 4 +- .../cmdletization/ObjectModelWrapper.cs | 16 ++--- ...lets-over-objects.xmlSerializer.autogen.cs | 5 +- .../other/ciminstancetypeadapter.cs | 15 +---- .../engine/CommandInfo.cs | 5 +- .../engine/EngineIntrinsics.cs | 5 +- .../engine/ErrorPackage.cs | 5 +- .../engine/EventManager.cs | 17 ++---- .../engine/GetCommandCommand.cs | 5 +- .../engine/InitialSessionState.cs | 41 +++---------- .../engine/Modules/ModuleSpecification.cs | 10 +--- .../engine/MshCmdlet.cs | 3 +- .../engine/ProxyCommand.cs | 5 +- .../engine/SessionStateUtils.cs | 5 +- .../engine/ThirdPartyAdapter.cs | 5 +- .../engine/TypeTable.cs | 17 ++---- .../engine/Utils.cs | 5 +- .../engine/cmdlet.cs | 3 +- .../engine/hostifaces/ListModifier.cs | 5 +- .../engine/hostifaces/PowerShell.cs | 10 +--- .../engine/lang/scriptblock.cs | 15 +---- .../engine/parser/Parser.cs | 5 +- .../engine/parser/ast.cs | 20 ++----- .../engine/regex.cs | 5 +- .../engine/remoting/client/Job2.cs | 9 +-- .../engine/remoting/client/JobManager.cs | 10 +--- .../remoting/client/RemotingErrorRecord.cs | 2 +- .../engine/remoting/client/ThrottlingJob.cs | 6 +- .../remoting/commands/PSRemotingCmdlet.cs | 5 +- .../remoting/common/RunspaceConnectionInfo.cs | 20 ++----- .../fanin/InitialSessionStateProvider.cs | 9 +-- .../ServerRemoteHostRawUserInterface.cs | 10 +--- .../engine/runtime/CompiledScriptBlock.cs | 5 +- .../engine/runtime/Operations/MiscOps.cs | 6 +- .../engine/serialization.cs | 5 +- .../namespaces/FileSystemProvider.cs | 17 ++---- .../namespaces/TransactedRegistryKey.cs | 3 +- .../security/SecureStringHelper.cs | 10 +--- .../utils/CryptoUtils.cs | 25 ++------ .../utils/ExecutionExceptions.cs | 25 ++------ .../utils/ObjectReader.cs | 5 +- .../utils/ObjectWriter.cs | 5 +- .../utils/SessionStateExceptions.cs | 5 +- .../perfCounters/CounterSetRegistrarBase.cs | 10 +--- .../utils/tracing/EtwActivity.cs | 60 ++++--------------- .../EtwActivityReverterMethodInvoker.cs | 5 +- .../utils/tracing/EtwEventCorrelator.cs | 5 +- src/powershell/Program.cs | 10 +--- 122 files changed, 272 insertions(+), 921 deletions(-) diff --git a/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphBuilder.cs b/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphBuilder.cs index 3d3613c1860..5878e5f029e 100644 --- a/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphBuilder.cs +++ b/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphBuilder.cs @@ -43,10 +43,7 @@ internal class ParagraphBuilder : INotifyPropertyChanged /// Paragraph we will be adding lines to in BuildParagraph. internal ParagraphBuilder(Paragraph paragraph) { - if (paragraph == null) - { - throw new ArgumentNullException("paragraph"); - } + ArgumentNullException.ThrowIfNull(paragraph); this.paragraph = paragraph; this.boldSpans = new List(); @@ -185,10 +182,7 @@ internal void HighlightAllInstancesOf(string search, bool caseSensitive, bool wh /// True if the text should be bold. internal void AddText(string str, bool bold) { - if (str == null) - { - throw new ArgumentNullException("str"); - } + ArgumentNullException.ThrowIfNull(str); if (str.Length == 0) { diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/IntegralConverter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/IntegralConverter.cs index dff537f00bb..27c45ef288b 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/IntegralConverter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/IntegralConverter.cs @@ -31,10 +31,7 @@ public class IntegralConverter : IMultiValueConverter /// public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) { - if (values == null) - { - throw new ArgumentNullException("values"); - } + ArgumentNullException.ThrowIfNull(values); if (values.Length != 2) { diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/InverseBooleanConverter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/InverseBooleanConverter.cs index 55b57d76a3f..efefb08bae9 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/InverseBooleanConverter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/InverseBooleanConverter.cs @@ -22,10 +22,7 @@ public class InverseBooleanConverter : IValueConverter /// The inverted boolean value. public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { - if (value == null) - { - throw new ArgumentNullException("value"); - } + ArgumentNullException.ThrowIfNull(value); var boolValue = (bool)value; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/IsEqualConverter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/IsEqualConverter.cs index 83cd762198f..dbd806a64d6 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/IsEqualConverter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/IsEqualConverter.cs @@ -31,10 +31,7 @@ public class IsEqualConverter : IMultiValueConverter /// public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) { - if (values == null) - { - throw new ArgumentNullException("values"); - } + ArgumentNullException.ThrowIfNull(values); if (values.Length != 2) { diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/StringFormatConverter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/StringFormatConverter.cs index a2e2b144ad6..d8cf0b253aa 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/StringFormatConverter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/StringFormatConverter.cs @@ -23,10 +23,7 @@ public class StringFormatConverter : IValueConverter /// The formatted string. public object Convert(object value, Type targetType, Object parameter, CultureInfo culture) { - if (parameter == null) - { - throw new ArgumentNullException("parameter"); - } + ArgumentNullException.ThrowIfNull(parameter); string str = (string)value; string formatString = (string)parameter; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/Utilities.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/Utilities.cs index c6bcfcb1737..9cc60c8411c 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/Utilities.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/Utilities.cs @@ -83,10 +83,7 @@ public static class Utilities /// The specified value is a null reference. public static bool AreAllItemsOfType(IEnumerable items) { - if (items == null) - { - throw new ArgumentNullException("items"); - } + ArgumentNullException.ThrowIfNull(items); foreach (object item in items) { @@ -108,10 +105,7 @@ public static bool AreAllItemsOfType(IEnumerable items) /// The specified value is a null reference. public static T Find(this IEnumerable items) { - if (items == null) - { - throw new ArgumentNullException("items"); - } + ArgumentNullException.ThrowIfNull(items); foreach (object item in items) { diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/VisualToAncestorDataConverter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/VisualToAncestorDataConverter.cs index 85a7d00a61f..868e9a9b25b 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/VisualToAncestorDataConverter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/VisualToAncestorDataConverter.cs @@ -27,15 +27,9 @@ public class VisualToAncestorDataConverter : IValueConverter /// The specified value is a null reference. public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - if (value == null) - { - throw new ArgumentNullException("value"); - } + ArgumentNullException.ThrowIfNull(value); - if (parameter == null) - { - throw new ArgumentNullException("parameter"); - } + ArgumentNullException.ThrowIfNull(parameter); Type dataType = (Type)parameter; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/WeakEventListener.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/WeakEventListener.cs index cc18509092f..d005dd909ee 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/WeakEventListener.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/WeakEventListener.cs @@ -20,10 +20,7 @@ internal class WeakEventListener : IWeakEventListener where TEventAr /// The handler for the event. public WeakEventListener(EventHandler handler) { - if (handler == null) - { - throw new ArgumentNullException("handler"); - } + ArgumentNullException.ThrowIfNull(handler); this.realHander = handler; } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/WpfHelp.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/WpfHelp.cs index 23ff80d9974..b0839c6ccd2 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/WpfHelp.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/WpfHelp.cs @@ -153,10 +153,7 @@ public bool IsEmpty /// The specified value does not have a parent that supports removal. public static void RemoveFromParent(FrameworkElement element) { - if (element == null) - { - throw new ArgumentNullException("element"); - } + ArgumentNullException.ThrowIfNull(element); // If the element has already been detached, do nothing \\ if (element.Parent == null) @@ -215,10 +212,7 @@ public static void RemoveFromParent(FrameworkElement element) /// The specified value does not have a parent that supports removal. public static void AddChild(FrameworkElement parent, FrameworkElement element) { - if (element == null) - { - throw new ArgumentNullException("element"); - } + ArgumentNullException.ThrowIfNull(element); if (parent == null) { @@ -310,10 +304,8 @@ public static List FindVisualChildren(DependencyObject obj) where T : DependencyObject { Debug.Assert(obj != null, "obj is null"); - if (obj == null) - { - throw new ArgumentNullException("obj"); - } + + ArgumentNullException.ThrowIfNull(obj); List childrenOfType = new List(); @@ -348,10 +340,7 @@ public static List FindVisualChildren(DependencyObject obj) public static T FindVisualAncestorData(this DependencyObject obj) where T : class { - if (obj == null) - { - throw new ArgumentNullException("obj"); - } + ArgumentNullException.ThrowIfNull(obj); FrameworkElement parent = obj.FindVisualAncestor(); @@ -413,10 +402,7 @@ public static T FindVisualAncestor(this DependencyObject @object) where T : c /// The specified value is a null reference. public static bool TryExecute(this RoutedCommand command, object parameter, IInputElement target) { - if (command == null) - { - throw new ArgumentNullException("command"); - } + ArgumentNullException.ThrowIfNull(command); if (command.CanExecute(parameter, target)) { @@ -437,10 +423,7 @@ public static bool TryExecute(this RoutedCommand command, object parameter, IInp /// The reference to the child, or null if the template part wasn't found. public static T GetOptionalTemplateChild(Control templateParent, string childName) where T : FrameworkElement { - if (templateParent == null) - { - throw new ArgumentNullException("templateParent"); - } + ArgumentNullException.ThrowIfNull(templateParent); if (string.IsNullOrEmpty(childName)) { @@ -566,10 +549,7 @@ public static RoutedPropertyChangedEventArgs CreateRoutedPropertyChangedEvent /// The specified index is not valid for the specified collection. public static void ChangeIndex(ItemCollection items, object item, int newIndex) { - if (items == null) - { - throw new ArgumentNullException("items"); - } + ArgumentNullException.ThrowIfNull(items); if (!items.Contains(item)) { diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/ResizerGripThicknessConverter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/ResizerGripThicknessConverter.cs index 4cdf51f63f6..c371a6391b5 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/ResizerGripThicknessConverter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/ResizerGripThicknessConverter.cs @@ -38,10 +38,7 @@ public ResizerGripThicknessConverter() /// A converted value. If the method returns nullNothingnullptra null reference (Nothing in Visual Basic), the valid null value is used. public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { - if (values == null) - { - throw new ArgumentNullException("values"); - } + ArgumentNullException.ThrowIfNull(values); if (object.ReferenceEquals(values[0], DependencyProperty.UnsetValue) || object.ReferenceEquals(values[1], DependencyProperty.UnsetValue)) diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/DefaultFilterRuleCustomizationFactory.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/DefaultFilterRuleCustomizationFactory.cs index bd5faf32d63..cd5e40a8bd9 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/DefaultFilterRuleCustomizationFactory.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/DefaultFilterRuleCustomizationFactory.cs @@ -36,10 +36,7 @@ public override IPropertyValueGetter PropertyValueGetter set { - if (value == null) - { - throw new ArgumentNullException("value"); - } + ArgumentNullException.ThrowIfNull(value); this.propertyValueGetter = value; } @@ -106,15 +103,9 @@ public override ICollection CreateDefaultFilterRulesForPropertyValue /// public override void TransferValues(FilterRule oldRule, FilterRule newRule) { - if (oldRule == null) - { - throw new ArgumentNullException("oldRule"); - } + ArgumentNullException.ThrowIfNull(oldRule); - if (newRule == null) - { - throw new ArgumentNullException("newRule"); - } + ArgumentNullException.ThrowIfNull(newRule); if (this.TryTransferValuesAsSingleValueComparableValueFilterRule(oldRule, newRule)) { @@ -130,10 +121,7 @@ public override void TransferValues(FilterRule oldRule, FilterRule newRule) /// public override void ClearValues(FilterRule rule) { - if (rule == null) - { - throw new ArgumentNullException("rule"); - } + ArgumentNullException.ThrowIfNull(rule); if (this.TryClearValueFromSingleValueComparableValueFilterRule(rule)) { @@ -163,10 +151,7 @@ public override void ClearValues(FilterRule rule) /// public override string GetErrorMessageForInvalidValue(string value, Type typeToParseTo) { - if (typeToParseTo == null) - { - throw new ArgumentNullException("typeToParseTo"); - } + ArgumentNullException.ThrowIfNull(typeToParseTo); bool isNumericType = typeToParseTo == typeof(byte) || typeToParseTo == typeof(sbyte) @@ -222,10 +207,7 @@ private object GetValueFromValidatingValue(FilterRule rule, string propertyName) Debug.Assert(rule != null && !string.IsNullOrEmpty(propertyName), "rule and propertyname are not null"); // NOTE: This isn't needed but OACR is complaining - if (rule == null) - { - throw new ArgumentNullException("rule"); - } + ArgumentNullException.ThrowIfNull(rule); Type ruleType = rule.GetType(); @@ -241,10 +223,7 @@ private void SetValueOnValidatingValue(FilterRule rule, string propertyName, obj Debug.Assert(rule != null && !string.IsNullOrEmpty(propertyName), "rule and propertyname are not null"); // NOTE: This isn't needed but OACR is complaining - if (rule == null) - { - throw new ArgumentNullException("rule"); - } + ArgumentNullException.ThrowIfNull(rule); Type ruleType = rule.GetType(); diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterEvaluator.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterEvaluator.cs index 3e811368476..cf885d813c5 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterEvaluator.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterEvaluator.cs @@ -145,10 +145,7 @@ public FilterExpressionNode FilterExpression /// public void AddFilterExpressionProvider(IFilterExpressionProvider provider) { - if (provider == null) - { - throw new ArgumentNullException("provider"); - } + ArgumentNullException.ThrowIfNull(provider); this.filterExpressionProviders.Add(provider); provider.FilterExpressionChanged += this.FilterProvider_FilterExpressionChanged; @@ -162,10 +159,7 @@ public void AddFilterExpressionProvider(IFilterExpressionProvider provider) /// public void RemoveFilterExpressionProvider(IFilterExpressionProvider provider) { - if (provider == null) - { - throw new ArgumentNullException("provider"); - } + ArgumentNullException.ThrowIfNull(provider); this.filterExpressionProviders.Remove(provider); provider.FilterExpressionChanged -= this.FilterProvider_FilterExpressionChanged; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExceptionEventArgs.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExceptionEventArgs.cs index b7a26757b21..77460f61fc9 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExceptionEventArgs.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExceptionEventArgs.cs @@ -32,10 +32,7 @@ public Exception Exception /// public FilterExceptionEventArgs(Exception exception) { - if (exception == null) - { - throw new ArgumentNullException("exception"); - } + ArgumentNullException.ThrowIfNull(exception); this.Exception = exception; } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionAndOperatorNode.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionAndOperatorNode.cs index f255973dce8..0227362bf28 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionAndOperatorNode.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionAndOperatorNode.cs @@ -52,10 +52,7 @@ public FilterExpressionAndOperatorNode() /// public FilterExpressionAndOperatorNode(IEnumerable children) { - if (children == null) - { - throw new ArgumentNullException("children"); - } + ArgumentNullException.ThrowIfNull(children); this.children.AddRange(children); } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionOperandNode.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionOperandNode.cs index f6bfd17377b..3161dc30283 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionOperandNode.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionOperandNode.cs @@ -38,10 +38,7 @@ public FilterRule Rule /// public FilterExpressionOperandNode(FilterRule rule) { - if (rule == null) - { - throw new ArgumentNullException("rule"); - } + ArgumentNullException.ThrowIfNull(rule); this.Rule = rule; } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionOrOperatorNode.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionOrOperatorNode.cs index 201316a433e..ff92e42cf2d 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionOrOperatorNode.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionOrOperatorNode.cs @@ -52,10 +52,7 @@ public FilterExpressionOrOperatorNode() /// public FilterExpressionOrOperatorNode(IEnumerable children) { - if (children == null) - { - throw new ArgumentNullException("children"); - } + ArgumentNullException.ThrowIfNull(children); this.children.AddRange(children); } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRuleCustomizationFactory.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRuleCustomizationFactory.cs index 75019cdbf5d..b61c9933aef 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRuleCustomizationFactory.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRuleCustomizationFactory.cs @@ -32,10 +32,7 @@ public static FilterRuleCustomizationFactory FactoryInstance set { - if (value == null) - { - throw new ArgumentNullException("value"); - } + ArgumentNullException.ThrowIfNull(value); factoryInstance = value; } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/FilterRuleExtensions.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/FilterRuleExtensions.cs index 1ccc3d1d227..ce8728c873e 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/FilterRuleExtensions.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/FilterRuleExtensions.cs @@ -27,10 +27,7 @@ public static class FilterRuleExtensions /// public static FilterRule DeepCopy(this FilterRule rule) { - if (rule == null) - { - throw new ArgumentNullException("rule"); - } + ArgumentNullException.ThrowIfNull(rule); Debug.Assert(rule.GetType().IsSerializable, "rule is serializable"); diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/PropertyValueSelectorFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/PropertyValueSelectorFilterRule.cs index e8927c74826..f1bf8520a99 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/PropertyValueSelectorFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/PropertyValueSelectorFilterRule.cs @@ -76,10 +76,7 @@ public PropertyValueSelectorFilterRule(string propertyName, string propertyDispl throw new ArgumentNullException("propertyDisplayName"); } - if (rules == null) - { - throw new ArgumentNullException("rules"); - } + ArgumentNullException.ThrowIfNull(rules); this.PropertyName = propertyName; this.DisplayName = propertyDisplayName; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextFilterRule.cs index 3440935889f..ad1f2949972 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextFilterRule.cs @@ -101,15 +101,9 @@ protected internal string GetParsedValue(out bool evaluateAsExactMatch) /// The specified value is a null reference. protected internal string GetRegexPattern(string pattern, string exactMatchPattern) { - if (pattern == null) - { - throw new ArgumentNullException("pattern"); - } + ArgumentNullException.ThrowIfNull(pattern); - if (exactMatchPattern == null) - { - throw new ArgumentNullException("exactMatchPattern"); - } + ArgumentNullException.ThrowIfNull(exactMatchPattern); Debug.Assert(this.IsValid, "is valid"); diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValue.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValue.cs index cf9c553f6b4..beb139b0131 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValue.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValue.cs @@ -165,10 +165,7 @@ private bool TryGetCastValue(object rawValue, out T castValue) { castValue = default(T); - if (rawValue == null) - { - throw new ArgumentNullException("rawValue"); - } + ArgumentNullException.ThrowIfNull(rawValue); if (typeof(T).IsEnum) { diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValueBase.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValueBase.cs index ea2b255063f..f33862846a9 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValueBase.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValueBase.cs @@ -141,10 +141,7 @@ public string Error /// The validation rule to add. public void AddValidationRule(DataErrorInfoValidationRule rule) { - if (rule == null) - { - throw new ArgumentNullException("rule"); - } + ArgumentNullException.ThrowIfNull(rule); this.validationRules.Add(rule); @@ -162,10 +159,7 @@ public void AddValidationRule(DataErrorInfoValidationRule rule) /// The rule to remove. public void RemoveValidationRule(DataErrorInfoValidationRule rule) { - if (rule == null) - { - throw new ArgumentNullException("rule"); - } + ArgumentNullException.ThrowIfNull(rule); this.validationRules.Remove(rule); diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanel.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanel.cs index 35060a1b8ff..3e577d3cb9f 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanel.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanel.cs @@ -154,15 +154,9 @@ public FilterRulePanel() /// public void AddFilterRulePanelItemContentTemplate(Type type, DataTemplate dataTemplate) { - if (type == null) - { - throw new ArgumentNullException("type"); - } + ArgumentNullException.ThrowIfNull(type); - if (dataTemplate == null) - { - throw new ArgumentNullException("dataTemplate"); - } + ArgumentNullException.ThrowIfNull(dataTemplate); this.filterRuleTemplateSelector.TemplateDictionary.Add(new KeyValuePair(type, dataTemplate)); } @@ -176,10 +170,7 @@ public void AddFilterRulePanelItemContentTemplate(Type type, DataTemplate dataTe /// public void RemoveFilterRulePanelItemContentTemplate(Type type) { - if (type == null) - { - throw new ArgumentNullException("type"); - } + ArgumentNullException.ThrowIfNull(type); this.filterRuleTemplateSelector.TemplateDictionary.Remove(type); } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanelController.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanelController.cs index c4956063aa3..6d3b18da484 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanelController.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanelController.cs @@ -88,10 +88,7 @@ public FilterRulePanelController() /// public void AddFilterRulePanelItem(FilterRulePanelItem item) { - if (item == null) - { - throw new ArgumentNullException("item"); - } + ArgumentNullException.ThrowIfNull(item); int insertionIndex = this.GetInsertionIndex(item); this.filterRulePanelItems.Insert(insertionIndex, item); @@ -116,10 +113,7 @@ private void Rule_EvaluationResultInvalidated(object sender, EventArgs e) /// public void RemoveFilterRulePanelItem(FilterRulePanelItem item) { - if (item == null) - { - throw new ArgumentNullException("item"); - } + ArgumentNullException.ThrowIfNull(item); item.Rule.EvaluationResultInvalidated -= this.Rule_EvaluationResultInvalidated; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanelItem.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanelItem.cs index 7f9a5afcc4c..2378f9238d8 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanelItem.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanelItem.cs @@ -79,10 +79,7 @@ protected internal set /// public FilterRulePanelItem(FilterRule rule, string groupId) { - if (rule == null) - { - throw new ArgumentNullException("rule"); - } + ArgumentNullException.ThrowIfNull(rule); if (string.IsNullOrEmpty(groupId)) { diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/InputFieldBackgroundTextConverter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/InputFieldBackgroundTextConverter.cs index 0017f2a4340..28adfa82c86 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/InputFieldBackgroundTextConverter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/InputFieldBackgroundTextConverter.cs @@ -40,10 +40,7 @@ public class InputFieldBackgroundTextConverter : IValueConverter /// public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - if (value == null) - { - throw new ArgumentNullException("value"); - } + ArgumentNullException.ThrowIfNull(value); Type inputType = null; if (this.IsOfTypeValidatingValue(value)) diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchBox.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchBox.cs index b6471b6f653..ac9b5267f31 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchBox.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchBox.cs @@ -88,10 +88,7 @@ public SearchTextParser Parser set { - if (value == null) - { - throw new ArgumentNullException("value"); - } + ArgumentNullException.ThrowIfNull(value); this.parser = value; } @@ -120,10 +117,7 @@ partial void OnClearTextExecutedImplementation(ExecutedRoutedEventArgs e) /// The specified value is a null reference. protected static FilterExpressionNode ConvertToFilterExpression(ICollection searchBoxItems) { - if (searchBoxItems == null) - { - throw new ArgumentNullException("searchBoxItems"); - } + ArgumentNullException.ThrowIfNull(searchBoxItems); if (searchBoxItems.Count == 0) { diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchTextParseResult.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchTextParseResult.cs index 5fa5e3e7703..10843087587 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchTextParseResult.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchTextParseResult.cs @@ -18,10 +18,7 @@ public class SearchTextParseResult /// The specified value is a null reference. public SearchTextParseResult(FilterRule rule) { - if (rule == null) - { - throw new ArgumentNullException("rule"); - } + ArgumentNullException.ThrowIfNull(rule); this.FilterRule = rule; } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchTextParser.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchTextParser.cs index 04ba32ece6d..c64683c7301 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchTextParser.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchTextParser.cs @@ -45,10 +45,7 @@ public TextFilterRule FullTextRule public bool TryAddSearchableRule(SelectorFilterRule selectorRule) where T : TextFilterRule { - if (selectorRule == null) - { - throw new ArgumentNullException("selectorRule"); - } + ArgumentNullException.ThrowIfNull(selectorRule); T textRule = selectorRule.AvailableRules.AvailableValues.Find(); @@ -193,20 +190,11 @@ protected class SearchableRule /// The specified value is a null reference. public SearchableRule(string uniqueId, SelectorFilterRule selectorFilterRule, TextFilterRule childRule) { - if (uniqueId == null) - { - throw new ArgumentNullException("uniqueId"); - } + ArgumentNullException.ThrowIfNull(uniqueId); - if (selectorFilterRule == null) - { - throw new ArgumentNullException("selectorFilterRule"); - } + ArgumentNullException.ThrowIfNull(selectorFilterRule); - if (childRule == null) - { - throw new ArgumentNullException("childRule"); - } + ArgumentNullException.ThrowIfNull(childRule); this.UniqueId = uniqueId; this.selectorFilterRule = selectorFilterRule; @@ -240,10 +228,7 @@ public string Pattern /// The specified value is a null reference. public SelectorFilterRule GetRuleWithValueSet(string value) { - if (value == null) - { - throw new ArgumentNullException("value"); - } + ArgumentNullException.ThrowIfNull(value); SelectorFilterRule selectorRule = (SelectorFilterRule)this.selectorFilterRule.DeepCopy(); selectorRule.AvailableRules.SelectedIndex = this.selectorFilterRule.AvailableRules.AvailableValues.IndexOf(this.childRule); diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/ValidatingSelectorValueToDisplayNameConverter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/ValidatingSelectorValueToDisplayNameConverter.cs index e8708b92a15..010fbbeef75 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/ValidatingSelectorValueToDisplayNameConverter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/ValidatingSelectorValueToDisplayNameConverter.cs @@ -38,10 +38,7 @@ public class ValidatingSelectorValueToDisplayNameConverter : IMultiValueConverte /// public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) { - if (values == null) - { - throw new ArgumentNullException("values"); - } + ArgumentNullException.ThrowIfNull(values); if (values.Length != 2) { diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ColumnPicker.xaml.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ColumnPicker.xaml.cs index 470a7670860..8a919959968 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ColumnPicker.xaml.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ColumnPicker.xaml.cs @@ -59,15 +59,9 @@ internal ColumnPicker( ICollection availableColumns) : this() { - if (columns == null) - { - throw new ArgumentNullException("columns"); - } - - if (availableColumns == null) - { - throw new ArgumentNullException("availableColumns"); - } + ArgumentNullException.ThrowIfNull(columns); + + ArgumentNullException.ThrowIfNull(availableColumns); // Add visible columns to Selected list, preserving order // Note that availableColumns is not necessarily in the order diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/InnerListGridView.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/InnerListGridView.cs index 73222cae639..2761dcf36da 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/InnerListGridView.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/InnerListGridView.cs @@ -45,10 +45,7 @@ public InnerListGridView() /// The specified value is a null reference. internal InnerListGridView(ObservableCollection availableColumns) { - if (availableColumns == null) - { - throw new ArgumentNullException("availableColumns"); - } + ArgumentNullException.ThrowIfNull(availableColumns); // Setting the AvailableColumns property won't trigger CollectionChanged, so we have to do it manually \\ this.AvailableColumns = availableColumns; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/Innerlist.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/Innerlist.cs index 868e17d85c4..fe9e0fdcd1e 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/Innerlist.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/Innerlist.cs @@ -191,10 +191,7 @@ public void RefreshColumns() /// The specified value is a null reference. public void ApplySort(InnerListColumn column, bool shouldScrollIntoView) { - if (column == null) - { - throw new ArgumentNullException("column"); - } + ArgumentNullException.ThrowIfNull(column); // NOTE : By setting the column here, it will be used // later to set the sorted column when the UI state diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ManagementListStateDescriptor.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ManagementListStateDescriptor.cs index 841175c97da..93e035f7bc5 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ManagementListStateDescriptor.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ManagementListStateDescriptor.cs @@ -63,10 +63,7 @@ public ManagementListStateDescriptor(string name) /// public override void SaveState(ManagementList subject) { - if (subject == null) - { - throw new ArgumentNullException("subject"); - } + ArgumentNullException.ThrowIfNull(subject); this.SaveColumns(subject); this.SaveSortOrder(subject); @@ -100,10 +97,7 @@ public override void RestoreState(ManagementList subject) /// public void RestoreState(ManagementList subject, bool applyRestoredFilter) { - if (subject == null) - { - throw new ArgumentNullException("subject"); - } + ArgumentNullException.ThrowIfNull(subject); // Clear the sort, otherwise restoring columns and filters may trigger extra sorting \\ subject.List.ClearSort(); diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/PropertyValueGetter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/PropertyValueGetter.cs index 61a1a71938c..2e9326cd909 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/PropertyValueGetter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/PropertyValueGetter.cs @@ -48,10 +48,7 @@ public virtual bool TryGetPropertyValue(string propertyName, object value, out o throw new ArgumentException("propertyName is empty", "propertyName"); } - if (value == null) - { - throw new ArgumentNullException("value"); - } + ArgumentNullException.ThrowIfNull(value); PropertyDescriptor descriptor = this.GetPropertyDescriptor(propertyName, value); if (descriptor == null) diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/innerlistcolumn.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/innerlistcolumn.cs index 9f91f2b74e8..965a66239d0 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/innerlistcolumn.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/innerlistcolumn.cs @@ -68,10 +68,7 @@ public InnerListColumn(UIPropertyGroupDescription dataDescription, bool isVisibl /// Whether the column should create a default binding using the specified data's property. public InnerListColumn(UIPropertyGroupDescription dataDescription, bool isVisible, bool createDefaultBinding) { - if (dataDescription == null) - { - throw new ArgumentNullException("dataDescription"); - } + ArgumentNullException.ThrowIfNull(dataDescription); GridViewColumnHeader header = new GridViewColumnHeader(); header.Content = dataDescription.DisplayContent; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/managementlist.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/managementlist.cs index 7c36244e0f1..4ac51c702d8 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/managementlist.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/managementlist.cs @@ -50,10 +50,7 @@ public IStateDescriptorFactory SavedViewFactory set { - if (value == null) - { - throw new ArgumentNullException("value"); - } + ArgumentNullException.ThrowIfNull(value); this.savedViewFactory = value; } @@ -177,10 +174,7 @@ private void Evaluator_PropertyChanged(object sender, PropertyChangedEventArgs e /// The specified value is a null reference. public void AddColumn(InnerListColumn column) { - if (column == null) - { - throw new ArgumentNullException("column"); - } + ArgumentNullException.ThrowIfNull(column); this.AddColumn(column, this.IsFilterShown); } @@ -193,10 +187,7 @@ public void AddColumn(InnerListColumn column) /// The specified value is a null reference. public void AddColumn(InnerListColumn column, bool addDefaultFilterRules) { - if (column == null) - { - throw new ArgumentNullException("column"); - } + ArgumentNullException.ThrowIfNull(column); this.List.Columns.Add(column); @@ -229,10 +220,7 @@ public void AddColumn(InnerListColumn column, bool addDefaultFilterRules) /// The specified value is a null reference. public void AddRule(FilterRule rule) { - if (rule == null) - { - throw new ArgumentNullException("rule"); - } + ArgumentNullException.ThrowIfNull(rule); this.AddFilterRulePicker.ShortcutFilterRules.Add(new AddFilterRulePickerItem(new FilterRulePanelItem(rule, rule.DisplayName))); } diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/AllModulesViewModel.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/AllModulesViewModel.cs index 34159c8f837..da51550c084 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/AllModulesViewModel.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/AllModulesViewModel.cs @@ -95,10 +95,7 @@ public AllModulesViewModel(Dictionary importedMod /// True not to show common parameters. public AllModulesViewModel(Dictionary importedModules, IEnumerable commands, bool noCommonParameter) { - if (commands == null) - { - throw new ArgumentNullException("commands"); - } + ArgumentNullException.ThrowIfNull(commands); this.Initialization(importedModules, commands, noCommonParameter); } diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/CommandViewModel.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/CommandViewModel.cs index 33908ea732f..367b5d08131 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/CommandViewModel.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/CommandViewModel.cs @@ -490,10 +490,7 @@ internal static bool IsSharedParameterSetName(string name) /// The CommandViewModel corresponding to commandInfo. internal static CommandViewModel GetCommandViewModel(ModuleViewModel module, ShowCommandCommandInfo commandInfo, bool noCommonParameters) { - if (commandInfo == null) - { - throw new ArgumentNullException("commandInfo"); - } + ArgumentNullException.ThrowIfNull(commandInfo); CommandViewModel returnValue = new CommandViewModel(); returnValue.commandInfo = commandInfo; diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ModuleViewModel.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ModuleViewModel.cs index 95e45123d22..950dbe93758 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ModuleViewModel.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ModuleViewModel.cs @@ -67,10 +67,7 @@ public class ModuleViewModel : INotifyPropertyChanged /// All loaded modules. public ModuleViewModel(string name, Dictionary importedModules) { - if (name == null) - { - throw new ArgumentNullException("name"); - } + ArgumentNullException.ThrowIfNull(name); this.name = name; this.commands = new List(); diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterSetViewModel.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterSetViewModel.cs index 1521aab7742..9d59ca3dc1d 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterSetViewModel.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterSetViewModel.cs @@ -45,15 +45,9 @@ public ParameterSetViewModel( string name, List parameters) { - if (name == null) - { - throw new ArgumentNullException("name"); - } + ArgumentNullException.ThrowIfNull(name); - if (parameters == null) - { - throw new ArgumentNullException("parameters"); - } + ArgumentNullException.ThrowIfNull(parameters); parameters.Sort(Compare); diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterViewModel.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterViewModel.cs index ccd2fd635c8..32eb8271938 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterViewModel.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterViewModel.cs @@ -48,15 +48,9 @@ public class ParameterViewModel : INotifyPropertyChanged /// The name of the parameter set this parameter is in. public ParameterViewModel(ShowCommandParameterInfo parameter, string parameterSetName) { - if (parameter == null) - { - throw new ArgumentNullException("parameter"); - } + ArgumentNullException.ThrowIfNull(parameter); - if (parameterSetName == null) - { - throw new ArgumentNullException("parameterSetName"); - } + ArgumentNullException.ThrowIfNull(parameterSetName); this.parameter = parameter; this.parameterSetName = parameterSetName; diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs index cca50c4bb91..58a1fbb4c2d 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs @@ -577,8 +577,9 @@ private TSession GetImpliedSession() /// if successful method invocations should emit downstream the being operated on. public override void ProcessRecord(TObjectInstance objectInstance, MethodInvocationInfo methodInvocationInfo, bool passThru) { - if (objectInstance == null) throw new ArgumentNullException(nameof(objectInstance)); - if (methodInvocationInfo == null) throw new ArgumentNullException(nameof(methodInvocationInfo)); + ArgumentNullException.ThrowIfNull(objectInstance); + + ArgumentNullException.ThrowIfNull(methodInvocationInfo); foreach (TSession sessionForJob in this.GetSessionsToActAgainst(objectInstance)) { @@ -603,7 +604,7 @@ public override void ProcessRecord(TObjectInstance objectInstance, MethodInvocat /// Method invocation details. public override void ProcessRecord(MethodInvocationInfo methodInvocationInfo) { - if (methodInvocationInfo == null) throw new ArgumentNullException(nameof(methodInvocationInfo)); + ArgumentNullException.ThrowIfNull(methodInvocationInfo); foreach (TSession sessionForJob in this.GetSessionsToActAgainst(methodInvocationInfo)) { diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs index 0ffa5bdf98f..4ad6ecc9698 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs @@ -54,10 +54,7 @@ protected CimJobException( SerializationInfo info, StreamingContext context) : base(info, context) { - if (info == null) - { - throw new ArgumentNullException(nameof(info)); - } + ArgumentNullException.ThrowIfNull(info); _errorRecord = (ErrorRecord)info.GetValue("errorRecord", typeof(ErrorRecord)); } @@ -69,10 +66,7 @@ protected CimJobException( /// The that contains contextual information about the source or destination. public override void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info == null) - { - throw new ArgumentNullException(nameof(info)); - } + ArgumentNullException.ThrowIfNull(info); base.GetObjectData(info, context); info.AddValue("errorRecord", _errorRecord); diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimConverter.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimConverter.cs index 74f0f922cc5..7a3eb0ce326 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimConverter.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimConverter.cs @@ -352,7 +352,7 @@ internal static object ConvertFromDotNetToCim(object dotNetObject) /// The only kind of exception this method can throw. internal static object ConvertFromCimToDotNet(object cimObject, Type expectedDotNetType) { - if (expectedDotNetType == null) { throw new ArgumentNullException(nameof(expectedDotNetType)); } + ArgumentNullException.ThrowIfNull(expectedDotNetType); if (cimObject == null) { diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimQuery.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimQuery.cs index d2e920b7f9d..2c5c91fb1c8 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimQuery.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimQuery.cs @@ -319,10 +319,7 @@ public override void AddQueryOption(string optionName, object optionValue) throw new ArgumentNullException(nameof(optionName)); } - if (optionValue == null) - { - throw new ArgumentNullException(nameof(optionValue)); - } + ArgumentNullException.ThrowIfNull(optionValue); this.queryOptions[optionName] = optionValue; } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs index 3f2c6740dcf..8bfa485ff24 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs @@ -2962,9 +2962,8 @@ public override void GetObjectData( { base.GetObjectData(info, context); - if (info == null) - throw new ArgumentNullException(nameof(info)); - + ArgumentNullException.ThrowIfNull(info); + info.AddValue("ProcessName", _processName); } #endregion Serialization diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs index 69fb051519f..d6190573a38 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs @@ -2569,10 +2569,7 @@ public ServiceCommandException(string message, Exception innerException) protected ServiceCommandException(SerializationInfo info, StreamingContext context) : base(info, context) { - if (info == null) - { - throw new ArgumentNullException(nameof(info)); - } + ArgumentNullException.ThrowIfNull(info); _serviceName = info.GetString("ServiceName"); } @@ -2583,10 +2580,7 @@ protected ServiceCommandException(SerializationInfo info, StreamingContext conte /// Streaming context. public override void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info == null) - { - throw new ArgumentNullException(nameof(info)); - } + ArgumentNullException.ThrowIfNull(info); base.GetObjectData(info, context); info.AddValue("ServiceName", _serviceName); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs index c42977996ae..1d1c235165b 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs @@ -951,10 +951,7 @@ internal static IList BuildPropertyNames(PSObject source, IList /// Converted string. internal string ConvertPropertyNamesCSV(IList propertyNames) { - if (propertyNames == null) - { - throw new ArgumentNullException(nameof(propertyNames)); - } + ArgumentNullException.ThrowIfNull(propertyNames); _outputString.Clear(); bool first = true; @@ -1018,10 +1015,7 @@ internal string ConvertPropertyNamesCSV(IList propertyNames) /// internal string ConvertPSObjectToCSV(PSObject mshObject, IList propertyNames) { - if (propertyNames == null) - { - throw new ArgumentNullException(nameof(propertyNames)); - } + ArgumentNullException.ThrowIfNull(propertyNames); _outputString.Clear(); bool first = true; @@ -1107,10 +1101,7 @@ internal string ConvertPSObjectToCSV(PSObject mshObject, IList propertyN /// ToString() value. internal static string GetToStringValueForProperty(PSPropertyInfo property) { - if (property == null) - { - throw new ArgumentNullException(nameof(property)); - } + ArgumentNullException.ThrowIfNull(property); string value = null; try @@ -1272,15 +1263,9 @@ internal class ImportCsvHelper internal ImportCsvHelper(PSCmdlet cmdlet, char delimiter, IList header, string typeName, StreamReader streamReader) { - if (cmdlet == null) - { - throw new ArgumentNullException(nameof(cmdlet)); - } + ArgumentNullException.ThrowIfNull(cmdlet); - if (streamReader == null) - { - throw new ArgumentNullException(nameof(streamReader)); - } + ArgumentNullException.ThrowIfNull(streamReader); _cmdlet = cmdlet; _delimiter = delimiter; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutWindowProxy.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutWindowProxy.cs index c7f2c622c08..d9de50ef52c 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutWindowProxy.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutWindowProxy.cs @@ -58,20 +58,11 @@ internal OutWindowProxy(string title, OutputModeOption outPutMode, OutGridViewCo /// An array of types to add. internal void AddColumns(string[] propertyNames, string[] displayNames, Type[] types) { - if (propertyNames == null) - { - throw new ArgumentNullException(nameof(propertyNames)); - } + ArgumentNullException.ThrowIfNull(propertyNames); - if (displayNames == null) - { - throw new ArgumentNullException(nameof(displayNames)); - } + ArgumentNullException.ThrowIfNull(displayNames); - if (types == null) - { - throw new ArgumentNullException(nameof(types)); - } + ArgumentNullException.ThrowIfNull(types); try { @@ -177,10 +168,7 @@ private void AddExtraProperties(PSObject staleObject, PSObject liveObject) /// internal void AddItem(PSObject livePSObject) { - if (livePSObject == null) - { - throw new ArgumentNullException(nameof(livePSObject)); - } + ArgumentNullException.ThrowIfNull(livePSObject); if (_headerInfo == null) { @@ -203,10 +191,7 @@ internal void AddItem(PSObject livePSObject) /// internal void AddHeteroViewItem(PSObject livePSObject) { - if (livePSObject == null) - { - throw new ArgumentNullException(nameof(livePSObject)); - } + ArgumentNullException.ThrowIfNull(livePSObject); if (_headerInfo == null) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs index d6e0b004bdf..c1643218ce1 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs @@ -532,10 +532,7 @@ public bool Contains(T item) public void CopyTo(T[] array, int arrayIndex) { - if (array == null) - { - throw new ArgumentNullException(nameof(array)); - } + ArgumentNullException.ThrowIfNull(array); if (arrayIndex < 0) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Select-Object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Select-Object.cs index b57be43f25f..d7ce5310c98 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Select-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Select-Object.cs @@ -24,10 +24,7 @@ internal sealed class PSPropertyExpressionFilter /// Array of pattern strings to use. internal PSPropertyExpressionFilter(string[] wildcardPatternsStrings) { - if (wildcardPatternsStrings == null) - { - throw new ArgumentNullException(nameof(wildcardPatternsStrings)); - } + ArgumentNullException.ThrowIfNull(wildcardPatternsStrings); _wildcardPatterns = new WildcardPattern[wildcardPatternsStrings.Length]; for (int k = 0; k < wildcardPatternsStrings.Length; k++) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandCommandInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandCommandInfo.cs index 163b5d5028c..e2ba41fb3fc 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandCommandInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandCommandInfo.cs @@ -22,10 +22,7 @@ public class ShowCommandCommandInfo /// public ShowCommandCommandInfo(CommandInfo other) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } + ArgumentNullException.ThrowIfNull(other); this.Name = other.Name; this.ModuleName = other.ModuleName; @@ -71,10 +68,7 @@ public ShowCommandCommandInfo(CommandInfo other) /// public ShowCommandCommandInfo(PSObject other) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } + ArgumentNullException.ThrowIfNull(other); this.Name = other.Members["Name"].Value as string; this.ModuleName = other.Members["ModuleName"].Value as string; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandModuleInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandModuleInfo.cs index b12cc5651f4..f31bc93525d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandModuleInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandModuleInfo.cs @@ -20,10 +20,7 @@ public class ShowCommandModuleInfo /// public ShowCommandModuleInfo(PSModuleInfo other) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } + ArgumentNullException.ThrowIfNull(other); this.Name = other.Name; } @@ -37,10 +34,7 @@ public ShowCommandModuleInfo(PSModuleInfo other) /// public ShowCommandModuleInfo(PSObject other) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } + ArgumentNullException.ThrowIfNull(other); this.Name = other.Members["Name"].Value as string; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterInfo.cs index 88a75dfe610..9bf79c5bd76 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterInfo.cs @@ -22,10 +22,7 @@ public class ShowCommandParameterInfo /// public ShowCommandParameterInfo(CommandParameterInfo other) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } + ArgumentNullException.ThrowIfNull(other); this.Name = other.Name; this.IsMandatory = other.IsMandatory; @@ -50,10 +47,7 @@ public ShowCommandParameterInfo(CommandParameterInfo other) /// public ShowCommandParameterInfo(PSObject other) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } + ArgumentNullException.ThrowIfNull(other); this.Name = other.Members["Name"].Value as string; this.IsMandatory = (bool)(other.Members["IsMandatory"].Value); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterSetInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterSetInfo.cs index 75f0675eb87..c5ec1c74c08 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterSetInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterSetInfo.cs @@ -22,10 +22,7 @@ public class ShowCommandParameterSetInfo /// public ShowCommandParameterSetInfo(CommandParameterSetInfo other) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } + ArgumentNullException.ThrowIfNull(other); this.Name = other.Name; this.IsDefault = other.IsDefault; @@ -41,10 +38,7 @@ public ShowCommandParameterSetInfo(CommandParameterSetInfo other) /// public ShowCommandParameterSetInfo(PSObject other) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } + ArgumentNullException.ThrowIfNull(other); this.Name = other.Members["Name"].Value as string; this.IsDefault = (bool)(other.Members["IsDefault"].Value); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterType.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterType.cs index 1daf0350dbc..01da285a1d7 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterType.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterType.cs @@ -21,10 +21,7 @@ public class ShowCommandParameterType /// public ShowCommandParameterType(Type other) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } + ArgumentNullException.ThrowIfNull(other); this.FullName = other.FullName; if (other.IsEnum) @@ -51,10 +48,7 @@ public ShowCommandParameterType(Type other) /// public ShowCommandParameterType(PSObject other) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } + ArgumentNullException.ThrowIfNull(other); this.IsEnum = (bool)(other.Members["IsEnum"].Value); this.FullName = other.Members["FullName"].Value as string; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs index 9876d0a2ca2..50a88bb6754 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs @@ -99,7 +99,7 @@ public int MaximumFollowRelLink /// internal override void ProcessResponse(HttpResponseMessage response) { - if (response == null) { throw new ArgumentNullException(nameof(response)); } + ArgumentNullException.ThrowIfNull(response); var baseResponseStream = StreamHelper.GetResponseStream(response); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index c47ee9641ca..06da66dd868 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -762,7 +762,7 @@ private Uri PrepareUri(Uri uri) private static Uri CheckProtocol(Uri uri) { - if (uri == null) { throw new ArgumentNullException(nameof(uri)); } + ArgumentNullException.ThrowIfNull(uri); if (!uri.IsAbsoluteUri) { @@ -780,8 +780,7 @@ private string QualifyFilePath(string path) private static string FormatDictionary(IDictionary content) { - if (content == null) - throw new ArgumentNullException(nameof(content)); + ArgumentNullException.ThrowIfNull(content); StringBuilder bodyBuilder = new(); foreach (string key in content.Keys) @@ -1181,7 +1180,7 @@ internal virtual HttpRequestMessage GetRequest(Uri uri) internal virtual void FillRequestStream(HttpRequestMessage request) { - if (request == null) { throw new ArgumentNullException(nameof(request)); } + ArgumentNullException.ThrowIfNull(request); // set the content type if (ContentType != null) @@ -1352,9 +1351,9 @@ private bool ShouldRetry(HttpStatusCode code) internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestMessage request, bool keepAuthorization) { - if (client == null) { throw new ArgumentNullException(nameof(client)); } + ArgumentNullException.ThrowIfNull(client); - if (request == null) { throw new ArgumentNullException(nameof(request)); } + ArgumentNullException.ThrowIfNull(request); // Add 1 to account for the first request. int totalRequests = WebSession.MaximumRetryCount + 1; @@ -1486,7 +1485,7 @@ internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestM internal virtual void UpdateSession(HttpResponseMessage response) { - if (response == null) { throw new ArgumentNullException(nameof(response)); } + ArgumentNullException.ThrowIfNull(response); } #endregion Virtual Methods @@ -1679,8 +1678,8 @@ protected override void ProcessRecord() /// internal long SetRequestContent(HttpRequestMessage request, byte[] content) { - if (request == null) - throw new ArgumentNullException(nameof(request)); + ArgumentNullException.ThrowIfNull(request); + if (content == null) return 0; @@ -1702,8 +1701,7 @@ internal long SetRequestContent(HttpRequestMessage request, byte[] content) /// internal long SetRequestContent(HttpRequestMessage request, string content) { - if (request == null) - throw new ArgumentNullException(nameof(request)); + ArgumentNullException.ThrowIfNull(request); if (content == null) return 0; @@ -1751,8 +1749,7 @@ internal long SetRequestContent(HttpRequestMessage request, string content) internal long SetRequestContent(HttpRequestMessage request, XmlNode xmlNode) { - if (request == null) - throw new ArgumentNullException(nameof(request)); + ArgumentNullException.ThrowIfNull(request); if (xmlNode == null) return 0; @@ -1788,10 +1785,9 @@ internal long SetRequestContent(HttpRequestMessage request, XmlNode xmlNode) /// internal long SetRequestContent(HttpRequestMessage request, Stream contentStream) { - if (request == null) - throw new ArgumentNullException(nameof(request)); - if (contentStream == null) - throw new ArgumentNullException(nameof(contentStream)); + ArgumentNullException.ThrowIfNull(request); + + ArgumentNullException.ThrowIfNull(contentStream); var streamContent = new StreamContent(contentStream); request.Content = streamContent; @@ -1811,15 +1807,9 @@ internal long SetRequestContent(HttpRequestMessage request, Stream contentStream /// internal long SetRequestContent(HttpRequestMessage request, MultipartFormDataContent multipartContent) { - if (request == null) - { - throw new ArgumentNullException(nameof(request)); - } + ArgumentNullException.ThrowIfNull(request); - if (multipartContent == null) - { - throw new ArgumentNullException(nameof(multipartContent)); - } + ArgumentNullException.ThrowIfNull(multipartContent); request.Content = multipartContent; @@ -1828,10 +1818,9 @@ internal long SetRequestContent(HttpRequestMessage request, MultipartFormDataCon internal long SetRequestContent(HttpRequestMessage request, IDictionary content) { - if (request == null) - throw new ArgumentNullException(nameof(request)); - if (content == null) - throw new ArgumentNullException(nameof(content)); + ArgumentNullException.ThrowIfNull(request); + + ArgumentNullException.ThrowIfNull(content); string body = FormatDictionary(content); return (SetRequestContent(request, body)); @@ -1884,10 +1873,7 @@ internal void ParseLinkHeader(HttpResponseMessage response, System.Uri requestUr /// If true, collection types in will be enumerated. If false, collections will be treated as single value. private void AddMultipartContent(object fieldName, object fieldValue, MultipartFormDataContent formData, bool enumerate) { - if (formData == null) - { - throw new ArgumentNullException(nameof(formData)); - } + ArgumentNullException.ThrowIfNull(formData); // It is possible that the dictionary keys or values are PSObject wrapped depending on how the dictionary is defined and assigned. // Before processing the field name and value we need to ensure we are working with the base objects and not the PSObject wrappers. diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/InvokeWebRequestCommand.CoreClr.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/InvokeWebRequestCommand.CoreClr.cs index f13ad1aa4a3..d4490019772 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/InvokeWebRequestCommand.CoreClr.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/InvokeWebRequestCommand.CoreClr.cs @@ -32,7 +32,7 @@ public InvokeWebRequestCommand() : base() /// internal override void ProcessResponse(HttpResponseMessage response) { - if (response == null) { throw new ArgumentNullException(nameof(response)); } + ArgumentNullException.ThrowIfNull(response); Stream responseStream = StreamHelper.GetResponseStream(response); if (ShouldWriteToPipeline) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebProxy.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebProxy.cs index 226a981f8a2..ddba7af774e 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebProxy.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebProxy.cs @@ -13,10 +13,7 @@ internal class WebProxy : IWebProxy internal WebProxy(Uri address) { - if (address == null) - { - throw new ArgumentNullException(nameof(address)); - } + ArgumentNullException.ThrowIfNull(address); _proxyAddress = address; } @@ -48,10 +45,7 @@ internal bool UseDefaultCredentials public Uri GetProxy(Uri destination) { - if (destination == null) - { - throw new ArgumentNullException(nameof(destination)); - } + ArgumentNullException.ThrowIfNull(destination); if (destination.IsLoopback) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs index 8e156152020..c9f99c524fa 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs @@ -152,10 +152,7 @@ public static object ConvertFromJson(string input, bool returnHashtable, out Err [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Preferring Json over JSON")] public static object ConvertFromJson(string input, bool returnHashtable, int? maxDepth, out ErrorRecord error) { - if (input == null) - { - throw new ArgumentNullException(nameof(input)); - } + ArgumentNullException.ThrowIfNull(input); error = null; try diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs index 9314cfd1a5d..afa17912244 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs @@ -290,10 +290,7 @@ internal static class StreamHelper internal static void WriteToStream(Stream input, Stream output, PSCmdlet cmdlet, long? contentLength, CancellationToken cancellationToken) { - if (cmdlet == null) - { - throw new ArgumentNullException(nameof(cmdlet)); - } + ArgumentNullException.ThrowIfNull(cmdlet); Task copyTask = input.CopyToAsync(output, cancellationToken); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs index 7ae437525dd..4a38d14845c 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs @@ -330,15 +330,9 @@ internal TracePipelineWriter( bool writeError, Collection matchingSources) { - if (cmdlet == null) - { - throw new ArgumentNullException(nameof(cmdlet)); - } - - if (matchingSources == null) - { - throw new ArgumentNullException(nameof(matchingSources)); - } + ArgumentNullException.ThrowIfNull(cmdlet); + + ArgumentNullException.ThrowIfNull(matchingSources); _cmdlet = cmdlet; _writeError = writeError; diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs index ab2698ab7ec..abe0d59b43a 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs @@ -771,7 +771,7 @@ public class ConsoleColorProxy public ConsoleColorProxy(ConsoleHostUserInterface ui) { - if (ui == null) throw new ArgumentNullException(nameof(ui)); + ArgumentNullException.ThrowIfNull(ui); _ui = ui; } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ManagedEntrance.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ManagedEntrance.cs index 345a6dd0154..6dfd5d54e6f 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ManagedEntrance.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ManagedEntrance.cs @@ -49,10 +49,7 @@ public static int Start(string consoleFilePath, [MarshalAs(UnmanagedType.LPArray /// public static int Start([MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr, SizeParamIndex = 1)] string[] args, int argc) { - if (args == null) - { - throw new ArgumentNullException(nameof(args)); - } + ArgumentNullException.ThrowIfNull(args); #if DEBUG if (args.Length > 0 && !string.IsNullOrEmpty(args[0]) && args[0]!.Equals("-isswait", StringComparison.OrdinalIgnoreCase)) diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs index 404477fa6a3..99ecc222300 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs @@ -26,7 +26,7 @@ class ProgressPane internal ProgressPane(ConsoleHostUserInterface ui) { - if (ui == null) throw new ArgumentNullException(nameof(ui)); + ArgumentNullException.ThrowIfNull(ui); _ui = ui; _rawui = ui.RawUI; } diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs index 9713ac0b0b5..d283a5dd298 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs @@ -437,10 +437,7 @@ public bool WriteMessageEvent(string eventMessage, byte eventLevel, long eventKe { int status = 0; - if (eventMessage == null) - { - throw new ArgumentNullException(nameof(eventMessage)); - } + ArgumentNullException.ThrowIfNull(eventMessage); if (IsEnabled(eventLevel, eventKeywords)) { @@ -508,10 +505,7 @@ public bool WriteEvent(in EventDescriptor eventDescriptor, string data) { uint status = 0; - if (data == null) - { - throw new ArgumentNullException(nameof(data)); - } + ArgumentNullException.ThrowIfNull(data); if (IsEnabled(eventDescriptor.Level, eventDescriptor.Keywords)) { diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProviderTraceListener.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProviderTraceListener.cs index 9e7befb3e38..94eb340b21c 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProviderTraceListener.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProviderTraceListener.cs @@ -72,8 +72,7 @@ public EventProviderTraceListener(string providerId, string name) public EventProviderTraceListener(string providerId, string name, string delimiter) : base(name) { - if (delimiter == null) - throw new ArgumentNullException(nameof(delimiter)); + ArgumentNullException.ThrowIfNull(delimiter); if (delimiter.Length == 0) throw new ArgumentException(DotNetEventingStrings.Argument_NeedNonemptyDelimiter); diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Sam.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Sam.cs index 2ec7f41499c..3e6bbcafd10 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Sam.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Sam.cs @@ -3145,8 +3145,7 @@ internal sealed class OperatingSystem internal OperatingSystem(Version version, string servicePack) { - if (version == null) - throw new ArgumentNullException("version"); + ArgumentNullException.ThrowIfNull(version); _version = version; _servicePack = servicePack; diff --git a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobTrigger.cs b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobTrigger.cs index f32f33ce008..7bb4977b79d 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobTrigger.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobTrigger.cs @@ -709,10 +709,7 @@ public sealed class JobTriggerToCimInstanceConverter : PSTypeConverter /// True if the converter can convert the parameter to the parameter, otherwise false. public override bool CanConvertFrom(object sourceValue, Type destinationType) { - if (destinationType == null) - { - throw new ArgumentNullException("destinationType"); - } + ArgumentNullException.ThrowIfNull(destinationType); return (sourceValue is ScheduledJobTrigger) && (destinationType.Equals(typeof(CimInstance))); } @@ -728,15 +725,9 @@ public override bool CanConvertFrom(object sourceValue, Type destinationType) /// If no conversion was possible. public override object ConvertFrom(object sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase) { - if (destinationType == null) - { - throw new ArgumentNullException("destinationType"); - } + ArgumentNullException.ThrowIfNull(destinationType); - if (sourceValue == null) - { - throw new ArgumentNullException("sourceValue"); - } + ArgumentNullException.ThrowIfNull(sourceValue); ScheduledJobTrigger originalTrigger = (ScheduledJobTrigger) sourceValue; using (CimSession cimSession = CimSession.Create(null)) diff --git a/src/Microsoft.WSMan.Management/CurrentConfigurations.cs b/src/Microsoft.WSMan.Management/CurrentConfigurations.cs index 95b8f4ba584..81d4ecfd870 100644 --- a/src/Microsoft.WSMan.Management/CurrentConfigurations.cs +++ b/src/Microsoft.WSMan.Management/CurrentConfigurations.cs @@ -61,10 +61,7 @@ public XmlDocument RootDocument /// Current server session. public CurrentConfigurations(IWSManSession serverSession) { - if (serverSession == null) - { - throw new ArgumentNullException(nameof(serverSession)); - } + ArgumentNullException.ThrowIfNull(serverSession); this.rootDocument = new XmlDocument(); this.serverSession = serverSession; @@ -117,10 +114,7 @@ public void PutConfigurationOnServer(string resourceUri) /// Path with namespace to the node from Root element. Must not end with '/'. public void RemoveOneConfiguration(string pathToNodeFromRoot) { - if (pathToNodeFromRoot == null) - { - throw new ArgumentNullException(nameof(pathToNodeFromRoot)); - } + ArgumentNullException.ThrowIfNull(pathToNodeFromRoot); XmlNode nodeToRemove = this.documentElement.SelectSingleNode( @@ -150,20 +144,14 @@ public void RemoveOneConfiguration(string pathToNodeFromRoot) /// Value of the configurations. public void UpdateOneConfiguration(string pathToNodeFromRoot, string configurationName, string configurationValue) { - if (pathToNodeFromRoot == null) - { - throw new ArgumentNullException(nameof(pathToNodeFromRoot)); - } + ArgumentNullException.ThrowIfNull(pathToNodeFromRoot); if (string.IsNullOrEmpty(configurationName)) { throw new ArgumentNullException(nameof(configurationName)); } - if (configurationValue == null) - { - throw new ArgumentNullException(nameof(configurationValue)); - } + ArgumentNullException.ThrowIfNull(configurationValue); XmlNode nodeToUpdate = this.documentElement.SelectSingleNode( @@ -195,10 +183,7 @@ public void UpdateOneConfiguration(string pathToNodeFromRoot, string configurati /// Value of the Node, or Null if no node present. public string GetOneConfiguration(string pathFromRoot) { - if (pathFromRoot == null) - { - throw new ArgumentNullException(nameof(pathFromRoot)); - } + ArgumentNullException.ThrowIfNull(pathFromRoot); XmlNode requiredNode = this.documentElement.SelectSingleNode( diff --git a/src/Microsoft.WSMan.Management/WsManHelper.cs b/src/Microsoft.WSMan.Management/WsManHelper.cs index a4917ee461e..71672f3232f 100644 --- a/src/Microsoft.WSMan.Management/WsManHelper.cs +++ b/src/Microsoft.WSMan.Management/WsManHelper.cs @@ -178,10 +178,7 @@ private static string FormatResourceMsgFromResourcetextS( string resourceName, object[] args) { - if (resourceManager == null) - { - throw new ArgumentNullException(nameof(resourceManager)); - } + ArgumentNullException.ThrowIfNull(resourceManager); if (string.IsNullOrEmpty(resourceName)) { diff --git a/src/System.Management.Automation/FormatAndOutput/common/PSStyle.cs b/src/System.Management.Automation/FormatAndOutput/common/PSStyle.cs index 59626f91599..930e86d4acc 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/PSStyle.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/PSStyle.cs @@ -761,10 +761,7 @@ private PSStyle() private static string ValidateNoContent(string text) { - if (text is null) - { - throw new ArgumentNullException(nameof(text)); - } + ArgumentNullException.ThrowIfNull(text); var decorartedString = new ValueStringDecorated(text); if (decorartedString.ContentLength > 0) diff --git a/src/System.Management.Automation/cimSupport/cmdletization/MethodInvocationInfo.cs b/src/System.Management.Automation/cimSupport/cmdletization/MethodInvocationInfo.cs index 1640dec33b9..d8ea4ed2398 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/MethodInvocationInfo.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/MethodInvocationInfo.cs @@ -21,8 +21,8 @@ public sealed class MethodInvocationInfo /// Return value of the method (ok to pass if the method doesn't return anything). public MethodInvocationInfo(string name, IEnumerable parameters, MethodParameter returnValue) { - if (name == null) throw new ArgumentNullException(nameof(name)); - if (parameters == null) throw new ArgumentNullException(nameof(parameters)); + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(parameters); // returnValue can be null MethodName = name; diff --git a/src/System.Management.Automation/cimSupport/cmdletization/ObjectModelWrapper.cs b/src/System.Management.Automation/cimSupport/cmdletization/ObjectModelWrapper.cs index ab6b741280e..e52582fc985 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/ObjectModelWrapper.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/ObjectModelWrapper.cs @@ -17,25 +17,17 @@ public abstract class CmdletAdapter { internal void Initialize(PSCmdlet cmdlet, string className, string classVersion, IDictionary privateData) { - if (cmdlet == null) - { - throw new ArgumentNullException(nameof(cmdlet)); - } + ArgumentNullException.ThrowIfNull(cmdlet); if (string.IsNullOrEmpty(className)) { throw new ArgumentNullException(nameof(className)); } - if (classVersion == null) // possible and ok to have classVersion==string.Empty - { - throw new ArgumentNullException(nameof(classVersion)); - } + // possible and ok to have classVersion==string.Empty + ArgumentNullException.ThrowIfNull(classVersion); - if (privateData == null) - { - throw new ArgumentNullException(nameof(privateData)); - } + ArgumentNullException.ThrowIfNull(privateData); _cmdlet = cmdlet; _className = className; diff --git a/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.xmlSerializer.autogen.cs b/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.xmlSerializer.autogen.cs index ece48f33d0b..3d46fbf28c2 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.xmlSerializer.autogen.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.xmlSerializer.autogen.cs @@ -6678,10 +6678,7 @@ internal sealed class PowerShellMetadataSerializer { internal object Deserialize(XmlReader reader) { - if (reader == null) - { - throw new ArgumentNullException(nameof(reader)); - } + ArgumentNullException.ThrowIfNull(reader); XmlSerializationReader1 cdxmlSerializationReader = new XmlSerializationReader1(reader); return cdxmlSerializationReader.Read50_PowerShellMetadata(); diff --git a/src/System.Management.Automation/cimSupport/other/ciminstancetypeadapter.cs b/src/System.Management.Automation/cimSupport/other/ciminstancetypeadapter.cs index ad98e0c50a1..6b1b85c125d 100644 --- a/src/System.Management.Automation/cimSupport/other/ciminstancetypeadapter.cs +++ b/src/System.Management.Automation/cimSupport/other/ciminstancetypeadapter.cs @@ -195,10 +195,7 @@ internal static string CimTypeToTypeNameDisplayString(CimType cimType) /// public override string GetPropertyTypeName(PSAdaptedProperty adaptedProperty) { - if (adaptedProperty == null) - { - throw new ArgumentNullException(nameof(adaptedProperty)); - } + ArgumentNullException.ThrowIfNull(adaptedProperty); CimProperty cimProperty = adaptedProperty.Tag as CimProperty; if (cimProperty != null) @@ -220,10 +217,7 @@ public override string GetPropertyTypeName(PSAdaptedProperty adaptedProperty) /// public override object GetPropertyValue(PSAdaptedProperty adaptedProperty) { - if (adaptedProperty == null) - { - throw new ArgumentNullException(nameof(adaptedProperty)); - } + ArgumentNullException.ThrowIfNull(adaptedProperty); CimProperty cimProperty = adaptedProperty.Tag as CimProperty; if (cimProperty != null) @@ -375,10 +369,7 @@ public override bool IsSettable(PSAdaptedProperty adaptedProperty) /// public override void SetPropertyValue(PSAdaptedProperty adaptedProperty, object value) { - if (adaptedProperty == null) - { - throw new ArgumentNullException(nameof(adaptedProperty)); - } + ArgumentNullException.ThrowIfNull(adaptedProperty); if (!IsSettable(adaptedProperty)) { diff --git a/src/System.Management.Automation/engine/CommandInfo.cs b/src/System.Management.Automation/engine/CommandInfo.cs index d0e6dd7effa..7cd213a025c 100644 --- a/src/System.Management.Automation/engine/CommandInfo.cs +++ b/src/System.Management.Automation/engine/CommandInfo.cs @@ -110,10 +110,7 @@ internal CommandInfo(string name, CommandTypes type) // The name can be empty for functions and filters but it // can't be null - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); Name = name; CommandType = type; diff --git a/src/System.Management.Automation/engine/EngineIntrinsics.cs b/src/System.Management.Automation/engine/EngineIntrinsics.cs index a492a5215fc..e2a63a527a9 100644 --- a/src/System.Management.Automation/engine/EngineIntrinsics.cs +++ b/src/System.Management.Automation/engine/EngineIntrinsics.cs @@ -35,10 +35,7 @@ private EngineIntrinsics() /// internal EngineIntrinsics(ExecutionContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); _context = context; _host = context.EngineHostInterface; diff --git a/src/System.Management.Automation/engine/ErrorPackage.cs b/src/System.Management.Automation/engine/ErrorPackage.cs index a0e95e083e7..e802d376a14 100644 --- a/src/System.Management.Automation/engine/ErrorPackage.cs +++ b/src/System.Management.Automation/engine/ErrorPackage.cs @@ -193,10 +193,7 @@ public class ErrorCategoryInfo #region ctor internal ErrorCategoryInfo(ErrorRecord errorRecord) { - if (errorRecord == null) - { - throw new ArgumentNullException(nameof(errorRecord)); - } + ArgumentNullException.ThrowIfNull(errorRecord); _errorRecord = errorRecord; } diff --git a/src/System.Management.Automation/engine/EventManager.cs b/src/System.Management.Automation/engine/EventManager.cs index 78304819289..f7ffbddd852 100644 --- a/src/System.Management.Automation/engine/EventManager.cs +++ b/src/System.Management.Automation/engine/EventManager.cs @@ -817,10 +817,7 @@ public override void UnsubscribeEvent(PSEventSubscriber subscriber) /// private void UnsubscribeEvent(PSEventSubscriber subscriber, bool skipDraining) { - if (subscriber == null) - { - throw new ArgumentNullException(nameof(subscriber)); - } + ArgumentNullException.ThrowIfNull(subscriber); Delegate existingSubscriber = null; lock (_eventSubscribers) @@ -2368,10 +2365,7 @@ public class PSEventArgsCollection : IEnumerable /// Don't add events to the collection directly; use the EventManager instead internal void Add(PSEventArgs eventToAdd) { - if (eventToAdd == null) - { - throw new ArgumentNullException(nameof(eventToAdd)); - } + ArgumentNullException.ThrowIfNull(eventToAdd); _eventCollection.Add(eventToAdd); @@ -2486,10 +2480,9 @@ public PSEventJob( string name) : base(action?.ToString(), name) { - if (eventManager == null) - throw new ArgumentNullException(nameof(eventManager)); - if (subscriber == null) - throw new ArgumentNullException(nameof(subscriber)); + ArgumentNullException.ThrowIfNull(eventManager); + + ArgumentNullException.ThrowIfNull(subscriber); UsesResultsCollection = true; ScriptBlock = action; diff --git a/src/System.Management.Automation/engine/GetCommandCommand.cs b/src/System.Management.Automation/engine/GetCommandCommand.cs index 3c253504f01..113ba8121b8 100644 --- a/src/System.Management.Automation/engine/GetCommandCommand.cs +++ b/src/System.Management.Automation/engine/GetCommandCommand.cs @@ -303,10 +303,7 @@ public PSTypeName[] ParameterType set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); // if '...CimInstance#Win32_Process' is specified, then exclude '...CimInstance' List filteredParameterTypes = new List(value.Length); diff --git a/src/System.Management.Automation/engine/InitialSessionState.cs b/src/System.Management.Automation/engine/InitialSessionState.cs index 5e5758340e8..2dbb12fb253 100644 --- a/src/System.Management.Automation/engine/InitialSessionState.cs +++ b/src/System.Management.Automation/engine/InitialSessionState.cs @@ -980,10 +980,7 @@ public InitialSessionStateEntryCollection() /// public InitialSessionStateEntryCollection(IEnumerable items) { - if (items == null) - { - throw new ArgumentNullException(nameof(items)); - } + ArgumentNullException.ThrowIfNull(items); _internalCollection = new Collection(); @@ -1154,10 +1151,7 @@ public void Clear() /// The type of object to remove, can be null to remove any type. public void Remove(string name, object type) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); lock (_syncObject) { @@ -1192,10 +1186,7 @@ public void Remove(string name, object type) /// The item to add... public void Add(T item) { - if (item == null) - { - throw new ArgumentNullException(nameof(item)); - } + ArgumentNullException.ThrowIfNull(item); lock (_syncObject) { @@ -1209,10 +1200,7 @@ public void Add(T item) /// public void Add(IEnumerable items) { - if (items == null) - { - throw new ArgumentNullException(nameof(items)); - } + ArgumentNullException.ThrowIfNull(items); lock (_syncObject) { @@ -1870,10 +1858,7 @@ public Microsoft.PowerShell.ExecutionPolicy ExecutionPolicy /// public void ImportPSModule(params string[] name) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); foreach (string n in name) { @@ -1898,10 +1883,7 @@ internal void ClearPSModules() /// public void ImportPSModule(IEnumerable modules) { - if (modules == null) - { - throw new ArgumentNullException(nameof(modules)); - } + ArgumentNullException.ThrowIfNull(modules); foreach (var moduleSpecification in modules) { @@ -1929,10 +1911,7 @@ public void ImportPSModulesFromPath(string path) /// internal void ImportPSCoreModule(string[] name) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); foreach (string n in name) { @@ -4931,10 +4910,8 @@ internal static void AnalyzePSSnapInAssembly( out string helpFile) { helpFile = null; - if (assembly == null) - { - throw new ArgumentNullException(nameof(assembly)); - } + + ArgumentNullException.ThrowIfNull(assembly); cmdlets = null; aliases = null; diff --git a/src/System.Management.Automation/engine/Modules/ModuleSpecification.cs b/src/System.Management.Automation/engine/Modules/ModuleSpecification.cs index 315cf3aaf64..b539b191909 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleSpecification.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleSpecification.cs @@ -67,10 +67,7 @@ public ModuleSpecification(string moduleName) /// The module specification as a hashtable. public ModuleSpecification(Hashtable moduleSpecification) { - if (moduleSpecification == null) - { - throw new ArgumentNullException(nameof(moduleSpecification)); - } + ArgumentNullException.ThrowIfNull(moduleSpecification); var exception = ModuleSpecificationInitHelper(this, moduleSpecification); if (exception != null) @@ -172,10 +169,7 @@ internal static Exception ModuleSpecificationInitHelper(ModuleSpecification modu internal ModuleSpecification(PSModuleInfo moduleInfo) { - if (moduleInfo == null) - { - throw new ArgumentNullException(nameof(moduleInfo)); - } + ArgumentNullException.ThrowIfNull(moduleInfo); this.Name = moduleInfo.Name; this.Version = moduleInfo.Version; diff --git a/src/System.Management.Automation/engine/MshCmdlet.cs b/src/System.Management.Automation/engine/MshCmdlet.cs index ebc2f164c6e..9711b64f8b0 100644 --- a/src/System.Management.Automation/engine/MshCmdlet.cs +++ b/src/System.Management.Automation/engine/MshCmdlet.cs @@ -801,8 +801,7 @@ public Collection InvokeScript( IList input, params object[] args) { - if (script == null) - throw new ArgumentNullException(nameof(script)); + ArgumentNullException.ThrowIfNull(script); // Compile the script text into an executable script block. ScriptBlock sb = ScriptBlock.Create(_context, script); diff --git a/src/System.Management.Automation/engine/ProxyCommand.cs b/src/System.Management.Automation/engine/ProxyCommand.cs index 6a2e6dce66d..80d70377e87 100644 --- a/src/System.Management.Automation/engine/ProxyCommand.cs +++ b/src/System.Management.Automation/engine/ProxyCommand.cs @@ -376,10 +376,7 @@ private static void AppendType(StringBuilder sb, string section, PSObject parent /// When the help argument is not recognized as a HelpInfo object. public static string GetHelpComments(PSObject help) { - if (help == null) - { - throw new ArgumentNullException(nameof(help)); - } + ArgumentNullException.ThrowIfNull(help); bool isHelpObject = false; foreach (string typeName in help.InternalTypeNames) diff --git a/src/System.Management.Automation/engine/SessionStateUtils.cs b/src/System.Management.Automation/engine/SessionStateUtils.cs index 754f228633a..6bdc29da198 100644 --- a/src/System.Management.Automation/engine/SessionStateUtils.cs +++ b/src/System.Management.Automation/engine/SessionStateUtils.cs @@ -151,10 +151,7 @@ internal static Collection ConvertArrayToCollection(T[] array) /// internal static bool CollectionContainsValue(IEnumerable collection, object value, IComparer comparer) { - if (collection == null) - { - throw new ArgumentNullException(nameof(collection)); - } + ArgumentNullException.ThrowIfNull(collection); bool result = false; diff --git a/src/System.Management.Automation/engine/ThirdPartyAdapter.cs b/src/System.Management.Automation/engine/ThirdPartyAdapter.cs index bde0c0f3483..d77e700e90e 100644 --- a/src/System.Management.Automation/engine/ThirdPartyAdapter.cs +++ b/src/System.Management.Automation/engine/ThirdPartyAdapter.cs @@ -296,10 +296,7 @@ public abstract class PSPropertyAdapter [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "object")] public virtual Collection GetTypeNameHierarchy(object baseObject) { - if (baseObject == null) - { - throw new ArgumentNullException(nameof(baseObject)); - } + ArgumentNullException.ThrowIfNull(baseObject); Collection types = new Collection(); diff --git a/src/System.Management.Automation/engine/TypeTable.cs b/src/System.Management.Automation/engine/TypeTable.cs index 5e41aec1eb6..a752f9b62df 100644 --- a/src/System.Management.Automation/engine/TypeTable.cs +++ b/src/System.Management.Automation/engine/TypeTable.cs @@ -4732,15 +4732,9 @@ internal void Update( PSHost host, out bool failToLoadFile) { - if (filePath == null) - { - throw new ArgumentNullException(nameof(filePath)); - } + ArgumentNullException.ThrowIfNull(filePath); - if (errors == null) - { - throw new ArgumentNullException(nameof(errors)); - } + ArgumentNullException.ThrowIfNull(errors); if (isShared) { @@ -4810,10 +4804,9 @@ internal void Update( ConcurrentBag errors, bool isRemove) { - if (type == null) - throw new ArgumentNullException(nameof(type)); - if (errors == null) - throw new ArgumentNullException(nameof(errors)); + ArgumentNullException.ThrowIfNull(type); + + ArgumentNullException.ThrowIfNull(errors); if (isShared) { diff --git a/src/System.Management.Automation/engine/Utils.cs b/src/System.Management.Automation/engine/Utils.cs index ac16aa4b76a..93a3e80b74b 100644 --- a/src/System.Management.Automation/engine/Utils.cs +++ b/src/System.Management.Automation/engine/Utils.cs @@ -1702,10 +1702,7 @@ internal sealed class ReadOnlyBag : IEnumerable /// internal ReadOnlyBag(HashSet hashset) { - if (hashset == null) - { - throw new ArgumentNullException(nameof(hashset)); - } + ArgumentNullException.ThrowIfNull(hashset); _hashset = hashset; } diff --git a/src/System.Management.Automation/engine/cmdlet.cs b/src/System.Management.Automation/engine/cmdlet.cs index 612705e6d95..e241b972b38 100644 --- a/src/System.Management.Automation/engine/cmdlet.cs +++ b/src/System.Management.Automation/engine/cmdlet.cs @@ -1719,8 +1719,7 @@ public void ThrowTerminatingError(ErrorRecord errorRecord) { using (PSTransactionManager.GetEngineProtectionScope()) { - if (errorRecord == null) - throw new ArgumentNullException(nameof(errorRecord)); + ArgumentNullException.ThrowIfNull(errorRecord); if (commandRuntime != null) { diff --git a/src/System.Management.Automation/engine/hostifaces/ListModifier.cs b/src/System.Management.Automation/engine/hostifaces/ListModifier.cs index 4723db9a1d7..db089b68333 100644 --- a/src/System.Management.Automation/engine/hostifaces/ListModifier.cs +++ b/src/System.Management.Automation/engine/hostifaces/ListModifier.cs @@ -212,10 +212,7 @@ public void ApplyTo(IList collectionToUpdate) /// The collection to update. public void ApplyTo(object collectionToUpdate) { - if (collectionToUpdate == null) - { - throw new ArgumentNullException(nameof(collectionToUpdate)); - } + ArgumentNullException.ThrowIfNull(collectionToUpdate); collectionToUpdate = PSObject.Base(collectionToUpdate); diff --git a/src/System.Management.Automation/engine/hostifaces/PowerShell.cs b/src/System.Management.Automation/engine/hostifaces/PowerShell.cs index 07d17589c3b..1dace005fa7 100644 --- a/src/System.Management.Automation/engine/hostifaces/PowerShell.cs +++ b/src/System.Management.Automation/engine/hostifaces/PowerShell.cs @@ -6157,15 +6157,9 @@ internal class PowerShellStopper : IDisposable internal PowerShellStopper(ExecutionContext context, PowerShell powerShell) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); - if (powerShell == null) - { - throw new ArgumentNullException(nameof(powerShell)); - } + ArgumentNullException.ThrowIfNull(powerShell); _powerShell = powerShell; diff --git a/src/System.Management.Automation/engine/lang/scriptblock.cs b/src/System.Management.Automation/engine/lang/scriptblock.cs index 451d015fdcc..3c7d6576aaa 100644 --- a/src/System.Management.Automation/engine/lang/scriptblock.cs +++ b/src/System.Management.Automation/engine/lang/scriptblock.cs @@ -1096,15 +1096,9 @@ public sealed class SteppablePipeline : IDisposable { internal SteppablePipeline(ExecutionContext context, PipelineProcessor pipeline) { - if (pipeline == null) - { - throw new ArgumentNullException(nameof(pipeline)); - } + ArgumentNullException.ThrowIfNull(pipeline); - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); _pipeline = pipeline; _context = context; @@ -1128,10 +1122,7 @@ internal SteppablePipeline(ExecutionContext context, PipelineProcessor pipeline) /// Context used to figure out how to route the output and errors. public void Begin(bool expectInput, EngineIntrinsics contextToRedirectTo) { - if (contextToRedirectTo == null) - { - throw new ArgumentNullException(nameof(contextToRedirectTo)); - } + ArgumentNullException.ThrowIfNull(contextToRedirectTo); ExecutionContext executionContext = contextToRedirectTo.SessionState.Internal.ExecutionContext; CommandProcessorBase commandProcessor = executionContext.CurrentCommandProcessor; diff --git a/src/System.Management.Automation/engine/parser/Parser.cs b/src/System.Management.Automation/engine/parser/Parser.cs index 9d80edf6500..c0bdd25740a 100644 --- a/src/System.Management.Automation/engine/parser/Parser.cs +++ b/src/System.Management.Automation/engine/parser/Parser.cs @@ -142,10 +142,7 @@ public static ScriptBlockAst ParseInput(string input, out Token[] tokens, out Pa /// The that represents the input script file. public static ScriptBlockAst ParseInput(string input, string fileName, out Token[] tokens, out ParseError[] errors) { - if (input is null) - { - throw new ArgumentNullException(nameof(input)); - } + ArgumentNullException.ThrowIfNull(input); Parser parser = new Parser(); List tokenList = new List(); diff --git a/src/System.Management.Automation/engine/parser/ast.cs b/src/System.Management.Automation/engine/parser/ast.cs index 54424ea4cc7..4ee07ea967d 100644 --- a/src/System.Management.Automation/engine/parser/ast.cs +++ b/src/System.Management.Automation/engine/parser/ast.cs @@ -3884,10 +3884,7 @@ public CommentHelpInfo GetHelpContent() /// public CommentHelpInfo GetHelpContent(Dictionary scriptBlockTokenCache) { - if (scriptBlockTokenCache == null) - { - throw new ArgumentNullException(nameof(scriptBlockTokenCache)); - } + ArgumentNullException.ThrowIfNull(scriptBlockTokenCache); var commentTokens = HelpCommentsParser.GetHelpCommentTokens(this, scriptBlockTokenCache); if (commentTokens != null) @@ -5577,15 +5574,9 @@ public PipelineChainAst( bool background = false) : base(extent) { - if (lhsChain == null) - { - throw new ArgumentNullException(nameof(lhsChain)); - } + ArgumentNullException.ThrowIfNull(lhsChain); - if (rhsPipeline == null) - { - throw new ArgumentNullException(nameof(rhsPipeline)); - } + ArgumentNullException.ThrowIfNull(rhsPipeline); if (chainOperator != TokenKind.AndAnd && chainOperator != TokenKind.OrOr) { @@ -10462,10 +10453,7 @@ public override Ast Copy() [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "We want to get the underlying variable only for the UsingExpressionAst.")] public static VariableExpressionAst ExtractUsingVariable(UsingExpressionAst usingExpressionAst) { - if (usingExpressionAst == null) - { - throw new ArgumentNullException(nameof(usingExpressionAst)); - } + ArgumentNullException.ThrowIfNull(usingExpressionAst); return ExtractUsingVariableImpl(usingExpressionAst); } diff --git a/src/System.Management.Automation/engine/regex.cs b/src/System.Management.Automation/engine/regex.cs index a1e7f9ede94..4efe1ff436a 100644 --- a/src/System.Management.Automation/engine/regex.cs +++ b/src/System.Management.Automation/engine/regex.cs @@ -447,10 +447,7 @@ public class WildcardPatternException : RuntimeException internal WildcardPatternException(ErrorRecord errorRecord) : base(RetrieveMessage(errorRecord)) { - if (errorRecord == null) - { - throw new ArgumentNullException(nameof(errorRecord)); - } + ArgumentNullException.ThrowIfNull(errorRecord); _errorRecord = errorRecord; } diff --git a/src/System.Management.Automation/engine/remoting/client/Job2.cs b/src/System.Management.Automation/engine/remoting/client/Job2.cs index d5f122159ed..3f9c025d954 100644 --- a/src/System.Management.Automation/engine/remoting/client/Job2.cs +++ b/src/System.Management.Automation/engine/remoting/client/Job2.cs @@ -706,10 +706,8 @@ public ContainerParentJob(string command, string name, string jobType) public void AddChildJob(Job2 childJob) { AssertNotDisposed(); - if (childJob == null) - { - throw new ArgumentNullException(nameof(childJob)); - } + + ArgumentNullException.ThrowIfNull(childJob); _tracer.WriteMessage(TraceClassName, "AddChildJob", Guid.Empty, childJob, "Adding Child to Parent with InstanceId : ", InstanceId.ToString()); @@ -2181,8 +2179,7 @@ protected JobFailedException(SerializationInfo serializationInfo, StreamingConte /// The standard StreaminContext. public override void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info == null) - throw new ArgumentNullException(nameof(info)); + ArgumentNullException.ThrowIfNull(info); base.GetObjectData(info, context); diff --git a/src/System.Management.Automation/engine/remoting/client/JobManager.cs b/src/System.Management.Automation/engine/remoting/client/JobManager.cs index f907cf922d8..53161c40fc0 100644 --- a/src/System.Management.Automation/engine/remoting/client/JobManager.cs +++ b/src/System.Management.Automation/engine/remoting/client/JobManager.cs @@ -176,10 +176,7 @@ internal static void SaveJobId(Guid instanceId, int id, string typeName) /// public Job2 NewJob(JobDefinition definition) { - if (definition == null) - { - throw new ArgumentNullException(nameof(definition)); - } + ArgumentNullException.ThrowIfNull(definition); JobSourceAdapter sourceAdapter = GetJobSourceAdapter(definition); Job2 newJob; @@ -216,10 +213,7 @@ public Job2 NewJob(JobDefinition definition) /// public Job2 NewJob(JobInvocationInfo specification) { - if (specification == null) - { - throw new ArgumentNullException(nameof(specification)); - } + ArgumentNullException.ThrowIfNull(specification); if (specification.Definition == null) { diff --git a/src/System.Management.Automation/engine/remoting/client/RemotingErrorRecord.cs b/src/System.Management.Automation/engine/remoting/client/RemotingErrorRecord.cs index 0de48ff6dfc..cf37aa7bb33 100644 --- a/src/System.Management.Automation/engine/remoting/client/RemotingErrorRecord.cs +++ b/src/System.Management.Automation/engine/remoting/client/RemotingErrorRecord.cs @@ -149,7 +149,7 @@ public RemotingProgressRecord(ProgressRecord progressRecord, OriginInfo originIn private static ProgressRecord Validate(ProgressRecord progressRecord) { - if (progressRecord == null) throw new ArgumentNullException(nameof(progressRecord)); + ArgumentNullException.ThrowIfNull(progressRecord); return progressRecord; } } diff --git a/src/System.Management.Automation/engine/remoting/client/ThrottlingJob.cs b/src/System.Management.Automation/engine/remoting/client/ThrottlingJob.cs index 000e544fd57..b9a0cc4dfab 100644 --- a/src/System.Management.Automation/engine/remoting/client/ThrottlingJob.cs +++ b/src/System.Management.Automation/engine/remoting/client/ThrottlingJob.cs @@ -294,7 +294,7 @@ internal void AddChildJobAndPotentiallyBlock( { using (var jobGotEnqueued = new ManualResetEventSlim(initialState: false)) { - if (childJob == null) throw new ArgumentNullException(nameof(childJob)); + ArgumentNullException.ThrowIfNull(childJob); this.AddChildJobWithoutBlocking(childJob, flags, jobGotEnqueued.Set); jobGotEnqueued.Wait(); @@ -308,7 +308,7 @@ internal void AddChildJobAndPotentiallyBlock( { using (var forwardingCancellation = new CancellationTokenSource()) { - if (childJob == null) throw new ArgumentNullException(nameof(childJob)); + ArgumentNullException.ThrowIfNull(childJob); this.AddChildJobWithoutBlocking(childJob, flags, forwardingCancellation.Cancel); this.ForwardAllResultsToCmdlet(cmdlet, forwardingCancellation.Token); @@ -368,7 +368,7 @@ internal void DisableFlowControlForPendingCmdletActionsQueue() /// internal void AddChildJobWithoutBlocking(StartableJob childJob, ChildJobFlags flags, Action jobEnqueuedAction = null) { - if (childJob == null) throw new ArgumentNullException(nameof(childJob)); + ArgumentNullException.ThrowIfNull(childJob); if (childJob.JobStateInfo.State != JobState.NotStarted) throw new ArgumentException(RemotingErrorIdStrings.ThrottlingJobChildAlreadyRunning, nameof(childJob)); this.AssertNotDisposed(); diff --git a/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs b/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs index 23e86e9669a..a24163f66c7 100644 --- a/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs +++ b/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs @@ -2460,10 +2460,7 @@ private List GetUsingVariableValues(List paramUsi /// A list of UsingExpressionAsts ordered by the StartOffset. private static List GetUsingVariables(ScriptBlock localScriptBlock) { - if (localScriptBlock == null) - { - throw new ArgumentNullException(nameof(localScriptBlock), "Caller needs to make sure the parameter value is not null"); - } + ArgumentNullException.ThrowIfNull(localScriptBlock, "Caller needs to make sure the parameter value is not null"); var allUsingExprs = UsingExpressionAstSearcher.FindAllUsingExpressions(localScriptBlock.Ast); return allUsingExprs.Select(static usingExpr => UsingExpressionAst.ExtractUsingVariable((UsingExpressionAst)usingExpr)).ToList(); diff --git a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs index 9a50d9b8d94..700596957f6 100644 --- a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs +++ b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs @@ -168,10 +168,7 @@ public CultureInfo Culture set { - if (value == null) - { - throw new ArgumentNullException("value"); - } + ArgumentNullException.ThrowIfNull(value); _culture = value; } @@ -191,10 +188,7 @@ public CultureInfo UICulture set { - if (value == null) - { - throw new ArgumentNullException("value"); - } + ArgumentNullException.ThrowIfNull(value); _uiCulture = value; } @@ -284,10 +278,7 @@ public int OpenTimeout /// public virtual void SetSessionOptions(PSSessionOption options) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); if (options.Culture != null) { @@ -1029,10 +1020,7 @@ public WSManConnectionInfo(Uri uri) /// public override void SetSessionOptions(PSSessionOption options) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); if ((options.ProxyAccessType == ProxyAccessType.None) && (options.ProxyCredential != null)) { diff --git a/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs b/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs index 8596e87e834..ffcb9a80672 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs @@ -820,14 +820,11 @@ public override InitialSessionState GetInitialSessionState(PSSenderInfo senderIn public override InitialSessionState GetInitialSessionState(PSSessionConfigurationData sessionConfigurationData, PSSenderInfo senderInfo, string configProviderId) { - if (sessionConfigurationData == null) - throw new ArgumentNullException(nameof(sessionConfigurationData)); + ArgumentNullException.ThrowIfNull(sessionConfigurationData); - if (senderInfo == null) - throw new ArgumentNullException(nameof(senderInfo)); + ArgumentNullException.ThrowIfNull(senderInfo); - if (configProviderId == null) - throw new ArgumentNullException(nameof(configProviderId)); + ArgumentNullException.ThrowIfNull(configProviderId); InitialSessionState sessionState = InitialSessionState.CreateDefault2(); // now get all the modules in the specified path and import the same diff --git a/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostRawUserInterface.cs b/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostRawUserInterface.cs index 05448d02d9b..34c10e0a9a0 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostRawUserInterface.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostRawUserInterface.cs @@ -343,10 +343,7 @@ public override void SetBufferContents(Coordinates origin, BufferCell[,] content // to keep the other overload in sync: LengthInBufferCells(string, int) public override int LengthInBufferCells(string source) { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } + ArgumentNullException.ThrowIfNull(source); return source.Length; } @@ -354,10 +351,7 @@ public override int LengthInBufferCells(string source) // more performant than the default implementation provided by PSHostRawUserInterface public override int LengthInBufferCells(string source, int offset) { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } + ArgumentNullException.ThrowIfNull(source); Dbg.Assert(offset >= 0, "offset >= 0"); Dbg.Assert(string.IsNullOrEmpty(source) || (offset < source.Length), "offset < source.Length"); diff --git a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs index 9feeab94364..e2b5ee8376c 100644 --- a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs +++ b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs @@ -2178,10 +2178,7 @@ internal class ScriptBlockSerializationHelper : ISerializable, IObjectReference private ScriptBlockSerializationHelper(SerializationInfo info, StreamingContext context) { - if (info == null) - { - throw new ArgumentNullException(nameof(info)); - } + ArgumentNullException.ThrowIfNull(info); _scriptText = info.GetValue("ScriptText", typeof(string)) as string; if (_scriptText == null) diff --git a/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs b/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs index bd1eb62f19d..5db4829bb41 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs @@ -2777,10 +2777,8 @@ internal static object ForEach(IEnumerator enumerator, object expression, object { Diagnostics.Assert(enumerator != null, "The ForEach() operator should never receive a null enumerator value from the runtime."); Diagnostics.Assert(arguments != null, "The ForEach() operator should never receive a null value for the 'arguments' parameter from the runtime."); - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + + ArgumentNullException.ThrowIfNull(expression); var context = Runspace.DefaultRunspace.ExecutionContext; diff --git a/src/System.Management.Automation/engine/serialization.cs b/src/System.Management.Automation/engine/serialization.cs index 198f10e45f3..d85b56b4470 100644 --- a/src/System.Management.Automation/engine/serialization.cs +++ b/src/System.Management.Automation/engine/serialization.cs @@ -5933,10 +5933,7 @@ public PSPrimitiveDictionary() public PSPrimitiveDictionary(Hashtable other) : base(StringComparer.OrdinalIgnoreCase) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } + ArgumentNullException.ThrowIfNull(other); foreach (DictionaryEntry entry in other) { diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index dbd80ceaa6f..51d84f8f6ab 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -8146,7 +8146,7 @@ public static partial class AlternateDataStreamUtilities /// The list of streams (and their size) in the file. internal static List GetStreams(string path) { - if (path == null) throw new ArgumentNullException(nameof(path)); + ArgumentNullException.ThrowIfNull(path); List alternateStreams = new List(); @@ -8239,15 +8239,9 @@ internal static FileStream CreateFileStream(string path, string streamName, File /// True if the stream was successfully created, otherwise false. internal static bool TryCreateFileStream(string path, string streamName, FileMode mode, FileAccess access, FileShare share, out FileStream stream) { - if (path == null) - { - throw new ArgumentNullException(nameof(path)); - } + ArgumentNullException.ThrowIfNull(path); - if (streamName == null) - { - throw new ArgumentNullException(nameof(streamName)); - } + ArgumentNullException.ThrowIfNull(streamName); if (mode == FileMode.Append) { @@ -8274,8 +8268,9 @@ internal static bool TryCreateFileStream(string path, string streamName, FileMod /// The name of the alternate data stream to delete. internal static void DeleteFileStream(string path, string streamName) { - if (path == null) throw new ArgumentNullException(nameof(path)); - if (streamName == null) throw new ArgumentNullException(nameof(streamName)); + ArgumentNullException.ThrowIfNull(path); + + ArgumentNullException.ThrowIfNull(streamName); string adjustedStreamName = streamName.Trim(); if (adjustedStreamName.IndexOf(':') != 0) diff --git a/src/System.Management.Automation/namespaces/TransactedRegistryKey.cs b/src/System.Management.Automation/namespaces/TransactedRegistryKey.cs index 443c2547dfa..10826d25b21 100644 --- a/src/System.Management.Automation/namespaces/TransactedRegistryKey.cs +++ b/src/System.Management.Automation/namespaces/TransactedRegistryKey.cs @@ -1640,8 +1640,7 @@ public TransactedRegistrySecurity GetAccessControl(AccessControlSections include public void SetAccessControl(TransactedRegistrySecurity registrySecurity) { EnsureWriteable(); - if (registrySecurity == null) - throw new ArgumentNullException("registrySecurity"); + ArgumentNullException.ThrowIfNull(registrySecurity); // Require a transaction. This will throw for "Base" keys because they aren't associated with a transaction. VerifyTransaction(); diff --git a/src/System.Management.Automation/security/SecureStringHelper.cs b/src/System.Management.Automation/security/SecureStringHelper.cs index 2c832a92daf..2f7c991abc4 100644 --- a/src/System.Management.Automation/security/SecureStringHelper.cs +++ b/src/System.Management.Automation/security/SecureStringHelper.cs @@ -430,10 +430,7 @@ internal static class ProtectedData /// public static byte[] Protect(byte[] userData, byte[] optionalEntropy, DataProtectionScope scope) { - if (userData == null) - { - throw new ArgumentNullException(nameof(userData)); - } + ArgumentNullException.ThrowIfNull(userData); GCHandle pbDataIn = new GCHandle(); GCHandle pOptionalEntropy = new GCHandle(); @@ -518,10 +515,7 @@ public static byte[] Protect(byte[] userData, byte[] optionalEntropy, DataProtec /// public static byte[] Unprotect(byte[] encryptedData, byte[] optionalEntropy, DataProtectionScope scope) { - if (encryptedData == null) - { - throw new ArgumentNullException(nameof(encryptedData)); - } + ArgumentNullException.ThrowIfNull(encryptedData); GCHandle pbDataIn = new GCHandle(); GCHandle pOptionalEntropy = new GCHandle(); diff --git a/src/System.Management.Automation/utils/CryptoUtils.cs b/src/System.Management.Automation/utils/CryptoUtils.cs index 26d1fd7d177..390f66884bf 100644 --- a/src/System.Management.Automation/utils/CryptoUtils.cs +++ b/src/System.Management.Automation/utils/CryptoUtils.cs @@ -97,10 +97,7 @@ internal static RSA FromCapiPublicKeyBlob(byte[] blob) private static RSA FromCapiPublicKeyBlob(byte[] blob, int offset) { - if (blob == null) - { - throw new ArgumentNullException(nameof(blob)); - } + ArgumentNullException.ThrowIfNull(blob); if (offset > blob.Length) { @@ -123,10 +120,7 @@ private static RSA FromCapiPublicKeyBlob(byte[] blob, int offset) private static RSAParameters GetParametersFromCapiPublicKeyBlob(byte[] blob, int offset) { - if (blob == null) - { - throw new ArgumentNullException(nameof(blob)); - } + ArgumentNullException.ThrowIfNull(blob); if (offset > blob.Length) { @@ -175,10 +169,7 @@ private static RSAParameters GetParametersFromCapiPublicKeyBlob(byte[] blob, int internal static byte[] ToCapiPublicKeyBlob(RSA rsa) { - if (rsa == null) - { - throw new ArgumentNullException(nameof(rsa)); - } + ArgumentNullException.ThrowIfNull(rsa); RSAParameters p = rsa.ExportParameters(false); int keyLength = p.Modulus.Length; // in bytes @@ -221,10 +212,7 @@ internal static byte[] ToCapiPublicKeyBlob(RSA rsa) internal static byte[] FromCapiSimpleKeyBlob(byte[] blob) { - if (blob == null) - { - throw new ArgumentNullException(nameof(blob)); - } + ArgumentNullException.ThrowIfNull(blob); if (blob.Length < SIMPLEBLOB_HEADER_LEN) { @@ -237,10 +225,7 @@ internal static byte[] FromCapiSimpleKeyBlob(byte[] blob) internal static byte[] ToCapiSimpleKeyBlob(byte[] encryptedKey) { - if (encryptedKey == null) - { - throw new ArgumentNullException(nameof(encryptedKey)); - } + ArgumentNullException.ThrowIfNull(encryptedKey); // formulate the PUBLICKEYSTRUCT byte[] blob = new byte[SIMPLEBLOB_HEADER_LEN + encryptedKey.Length]; diff --git a/src/System.Management.Automation/utils/ExecutionExceptions.cs b/src/System.Management.Automation/utils/ExecutionExceptions.cs index 4c3cbb261e5..cd642683b18 100644 --- a/src/System.Management.Automation/utils/ExecutionExceptions.cs +++ b/src/System.Management.Automation/utils/ExecutionExceptions.cs @@ -30,10 +30,7 @@ public class CmdletInvocationException : RuntimeException internal CmdletInvocationException(ErrorRecord errorRecord) : base(RetrieveMessage(errorRecord), RetrieveException(errorRecord)) { - if (errorRecord == null) - { - throw new ArgumentNullException(nameof(errorRecord)); - } + ArgumentNullException.ThrowIfNull(errorRecord); _errorRecord = errorRecord; if (errorRecord.Exception != null) @@ -55,10 +52,7 @@ internal CmdletInvocationException(Exception innerException, InvocationInfo invocationInfo) : base(RetrieveMessage(innerException), innerException) { - if (innerException == null) - { - throw new ArgumentNullException(nameof(innerException)); - } + ArgumentNullException.ThrowIfNull(innerException); // invocationInfo may be null IContainsErrorRecord icer = innerException as IContainsErrorRecord; @@ -201,10 +195,7 @@ internal CmdletProviderInvocationException( InvocationInfo myInvocation) : base(GetInnerException(innerException), myInvocation) { - if (innerException == null) - { - throw new ArgumentNullException(nameof(innerException)); - } + ArgumentNullException.ThrowIfNull(innerException); _providerInvocationException = innerException; } @@ -464,10 +455,7 @@ public ActionPreferenceStopException() internal ActionPreferenceStopException(ErrorRecord error) : this(RetrieveMessage(error)) { - if (error == null) - { - throw new ArgumentNullException(nameof(error)); - } + ArgumentNullException.ThrowIfNull(error); _errorRecord = error; } @@ -492,10 +480,7 @@ internal ActionPreferenceStopException(InvocationInfo invocationInfo, string message) : this(invocationInfo, message) { - if (errorRecord == null) - { - throw new ArgumentNullException(nameof(errorRecord)); - } + ArgumentNullException.ThrowIfNull(errorRecord); _errorRecord = errorRecord; } diff --git a/src/System.Management.Automation/utils/ObjectReader.cs b/src/System.Management.Automation/utils/ObjectReader.cs index b333ec25be2..cac77b8576a 100644 --- a/src/System.Management.Automation/utils/ObjectReader.cs +++ b/src/System.Management.Automation/utils/ObjectReader.cs @@ -23,10 +23,7 @@ internal abstract class ObjectReaderBase : PipelineReader, IDisposable /// Thrown if the specified stream is null. protected ObjectReaderBase([In, Out] ObjectStreamBase stream) { - if (stream == null) - { - throw new ArgumentNullException(nameof(stream), "stream may not be null"); - } + ArgumentNullException.ThrowIfNull(stream); _stream = stream; } diff --git a/src/System.Management.Automation/utils/ObjectWriter.cs b/src/System.Management.Automation/utils/ObjectWriter.cs index fe7b9c6deac..8f7a86b6801 100644 --- a/src/System.Management.Automation/utils/ObjectWriter.cs +++ b/src/System.Management.Automation/utils/ObjectWriter.cs @@ -23,10 +23,7 @@ internal class ObjectWriter : PipelineWriter /// Thrown if the specified stream is null. public ObjectWriter([In, Out] ObjectStreamBase stream) { - if (stream == null) - { - throw new ArgumentNullException(nameof(stream)); - } + ArgumentNullException.ThrowIfNull(stream); _stream = stream; #if (false) diff --git a/src/System.Management.Automation/utils/SessionStateExceptions.cs b/src/System.Management.Automation/utils/SessionStateExceptions.cs index 34ad5c7f4e0..5734fbc6269 100644 --- a/src/System.Management.Automation/utils/SessionStateExceptions.cs +++ b/src/System.Management.Automation/utils/SessionStateExceptions.cs @@ -95,10 +95,7 @@ internal ProviderInvocationException(ProviderInfo provider, ErrorRecord errorRec : base(RuntimeException.RetrieveMessage(errorRecord), RuntimeException.RetrieveException(errorRecord)) { - if (errorRecord == null) - { - throw new ArgumentNullException(nameof(errorRecord)); - } + ArgumentNullException.ThrowIfNull(errorRecord); _message = base.Message; _providerInfo = provider; diff --git a/src/System.Management.Automation/utils/perfCounters/CounterSetRegistrarBase.cs b/src/System.Management.Automation/utils/perfCounters/CounterSetRegistrarBase.cs index 69cea42b5af..917e04a5e69 100644 --- a/src/System.Management.Automation/utils/perfCounters/CounterSetRegistrarBase.cs +++ b/src/System.Management.Automation/utils/perfCounters/CounterSetRegistrarBase.cs @@ -134,10 +134,7 @@ protected CounterSetRegistrarBase( protected CounterSetRegistrarBase( CounterSetRegistrarBase srcCounterSetRegistrarBase) { - if (srcCounterSetRegistrarBase == null) - { - throw new ArgumentNullException(nameof(srcCounterSetRegistrarBase)); - } + ArgumentNullException.ThrowIfNull(srcCounterSetRegistrarBase); ProviderId = srcCounterSetRegistrarBase.ProviderId; CounterSetId = srcCounterSetRegistrarBase.CounterSetId; @@ -241,10 +238,7 @@ public PSCounterSetRegistrar( PSCounterSetRegistrar srcPSCounterSetRegistrar) : base(srcPSCounterSetRegistrar) { - if (srcPSCounterSetRegistrar == null) - { - throw new ArgumentNullException(nameof(srcPSCounterSetRegistrar)); - } + ArgumentNullException.ThrowIfNull(srcPSCounterSetRegistrar); } #endregion diff --git a/src/System.Management.Automation/utils/tracing/EtwActivity.cs b/src/System.Management.Automation/utils/tracing/EtwActivity.cs index 6a0285682df..433d90297ee 100644 --- a/src/System.Management.Automation/utils/tracing/EtwActivity.cs +++ b/src/System.Management.Automation/utils/tracing/EtwActivity.cs @@ -113,15 +113,9 @@ private sealed class CorrelatedCallback /// public CorrelatedCallback(EtwActivity tracer, CallbackNoParameter callback) { - if (callback == null) - { - throw new ArgumentNullException(nameof(callback)); - } + ArgumentNullException.ThrowIfNull(callback); - if (tracer == null) - { - throw new ArgumentNullException(nameof(tracer)); - } + ArgumentNullException.ThrowIfNull(tracer); this.tracer = tracer; this.parentActivityId = EtwActivity.GetActivityId(); @@ -135,15 +129,9 @@ public CorrelatedCallback(EtwActivity tracer, CallbackNoParameter callback) /// public CorrelatedCallback(EtwActivity tracer, CallbackWithState callback) { - if (callback == null) - { - throw new ArgumentNullException(nameof(callback)); - } + ArgumentNullException.ThrowIfNull(callback); - if (tracer == null) - { - throw new ArgumentNullException(nameof(tracer)); - } + ArgumentNullException.ThrowIfNull(tracer); this.tracer = tracer; this.parentActivityId = EtwActivity.GetActivityId(); @@ -157,15 +145,9 @@ public CorrelatedCallback(EtwActivity tracer, CallbackWithState callback) /// public CorrelatedCallback(EtwActivity tracer, AsyncCallback callback) { - if (callback == null) - { - throw new ArgumentNullException(nameof(callback)); - } + ArgumentNullException.ThrowIfNull(callback); - if (tracer == null) - { - throw new ArgumentNullException(nameof(tracer)); - } + ArgumentNullException.ThrowIfNull(tracer); this.tracer = tracer; this.parentActivityId = EtwActivity.GetActivityId(); @@ -184,15 +166,9 @@ public CorrelatedCallback(EtwActivity tracer, AsyncCallback callback) /// public CorrelatedCallback(EtwActivity tracer, CallbackWithStateAndArgs callback) { - if (callback == null) - { - throw new ArgumentNullException(nameof(callback)); - } + ArgumentNullException.ThrowIfNull(callback); - if (tracer == null) - { - throw new ArgumentNullException(nameof(tracer)); - } + ArgumentNullException.ThrowIfNull(tracer); this.tracer = tracer; this.parentActivityId = EtwActivity.GetActivityId(); @@ -371,10 +347,7 @@ public void Correlate() /// public CallbackNoParameter Correlate(CallbackNoParameter callback) { - if (callback == null) - { - throw new ArgumentNullException(nameof(callback)); - } + ArgumentNullException.ThrowIfNull(callback); return new CorrelatedCallback(this, callback).Callback; } @@ -386,10 +359,7 @@ public CallbackNoParameter Correlate(CallbackNoParameter callback) /// public CallbackWithState Correlate(CallbackWithState callback) { - if (callback == null) - { - throw new ArgumentNullException(nameof(callback)); - } + ArgumentNullException.ThrowIfNull(callback); return new CorrelatedCallback(this, callback).Callback; } @@ -401,10 +371,7 @@ public CallbackWithState Correlate(CallbackWithState callback) /// public AsyncCallback Correlate(AsyncCallback callback) { - if (callback == null) - { - throw new ArgumentNullException(nameof(callback)); - } + ArgumentNullException.ThrowIfNull(callback); return new CorrelatedCallback(this, callback).Callback; } @@ -417,10 +384,7 @@ public AsyncCallback Correlate(AsyncCallback callback) /// public CallbackWithStateAndArgs Correlate(CallbackWithStateAndArgs callback) { - if (callback == null) - { - throw new ArgumentNullException(nameof(callback)); - } + ArgumentNullException.ThrowIfNull(callback); return new CorrelatedCallback(this, callback).Callback; } diff --git a/src/System.Management.Automation/utils/tracing/EtwActivityReverterMethodInvoker.cs b/src/System.Management.Automation/utils/tracing/EtwActivityReverterMethodInvoker.cs index e093f1de933..d9d082879a6 100644 --- a/src/System.Management.Automation/utils/tracing/EtwActivityReverterMethodInvoker.cs +++ b/src/System.Management.Automation/utils/tracing/EtwActivityReverterMethodInvoker.cs @@ -21,10 +21,7 @@ internal class EtwActivityReverterMethodInvoker : public EtwActivityReverterMethodInvoker(IEtwEventCorrelator eventCorrelator) { - if (eventCorrelator == null) - { - throw new ArgumentNullException(nameof(eventCorrelator)); - } + ArgumentNullException.ThrowIfNull(eventCorrelator); _eventCorrelator = eventCorrelator; _invoker = DoInvoke; diff --git a/src/System.Management.Automation/utils/tracing/EtwEventCorrelator.cs b/src/System.Management.Automation/utils/tracing/EtwEventCorrelator.cs index a421b918eb8..a6824193bfb 100644 --- a/src/System.Management.Automation/utils/tracing/EtwEventCorrelator.cs +++ b/src/System.Management.Automation/utils/tracing/EtwEventCorrelator.cs @@ -64,10 +64,7 @@ public class EtwEventCorrelator : /// during activity correlation. public EtwEventCorrelator(EventProvider transferProvider, EventDescriptor transferEvent) { - if (transferProvider == null) - { - throw new ArgumentNullException(nameof(transferProvider)); - } + ArgumentNullException.ThrowIfNull(transferProvider); _transferProvider = transferProvider; _transferEvent = transferEvent; diff --git a/src/powershell/Program.cs b/src/powershell/Program.cs index f5c109a1a76..1fdb1319c5c 100644 --- a/src/powershell/Program.cs +++ b/src/powershell/Program.cs @@ -119,10 +119,7 @@ private static void AttemptExecPwshLogin(string[] args) pwshPath = Marshal.PtrToStringAnsi(linkPathPtr, (int)bufSize); Marshal.FreeHGlobal(linkPathPtr); - if (pwshPath == null) - { - throw new ArgumentNullException(nameof(pwshPath)); - } + ArgumentNullException.ThrowIfNull(pwshPath); // exec pwsh ThrowOnFailure("exec", ExecPwshLogin(args, pwshPath, isMacOS: false)); @@ -207,10 +204,7 @@ private static void AttemptExecPwshLogin(string[] args) // Get the pwshPath from exec_path pwshPath = Marshal.PtrToStringAnsi(executablePathPtr); - if (pwshPath == null) - { - throw new ArgumentNullException(nameof(pwshPath)); - } + ArgumentNullException.ThrowIfNull(pwshPath); // exec pwsh ThrowOnFailure("exec", ExecPwshLogin(args, pwshPath, isMacOS: true)); From 36282c20f2a12a580a0b07bc41e3e08264f2b2c3 Mon Sep 17 00:00:00 2001 From: Jose Sua Date: Wed, 14 Dec 2022 08:42:53 -0800 Subject: [PATCH 254/779] Add Instrumentation to AmsiUtil and make the init variable readonly (#18727) * Add Insturmentation to AmsiUtil and make the init variable readonly * remove unwanted file * Fix task to hex * ingnore AsmiInit when not windows * rename event name * CR feedback * the missing dot in the argument documentation because that is very very important. * CR feedback Co-authored-by: Jose Sua --- .../PowerShell.Core.Instrumentation.man | 52 +++++++++++++++++-- .../engine/remoting/common/PSETWTracer.cs | 4 +- .../logging/LogProvider.cs | 16 ++++++ .../security/SecuritySupport.cs | 23 ++++---- .../utils/tracing/PSEtwLog.cs | 10 ++++ .../utils/tracing/PSEtwLogProvider.cs | 22 +++++++- .../utils/tracing/PSSysLogProvider.cs | 10 ++++ 7 files changed, 123 insertions(+), 14 deletions(-) diff --git a/src/PowerShell.Core.Instrumentation/PowerShell.Core.Instrumentation.man b/src/PowerShell.Core.Instrumentation/PowerShell.Core.Instrumentation.man index ea8fcdc49c5..8979ad8ebe0 100644 --- a/src/PowerShell.Core.Instrumentation/PowerShell.Core.Instrumentation.man +++ b/src/PowerShell.Core.Instrumentation/PowerShell.Core.Instrumentation.man @@ -2208,6 +2208,18 @@ value="0x6017" version="1" /> + - + diff --git a/test/tools/WebListener/WebListener.csproj b/test/tools/WebListener/WebListener.csproj index 3977af31fba..5e4803747cc 100644 --- a/test/tools/WebListener/WebListener.csproj +++ b/test/tools/WebListener/WebListener.csproj @@ -7,7 +7,7 @@ - + From bea1c6ee0eb9e26f00cfe0d7a0106adbe58d3155 Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Wed, 14 Dec 2022 11:46:47 -0800 Subject: [PATCH 257/779] Merged PR 23331: Remove TabExpansion from remote session configuration (#18795) --- .../common/WireDataFormat/EncodeAndDecode.cs | 228 ------------------ .../remoting/server/serverremotesession.cs | 24 +- 2 files changed, 3 insertions(+), 249 deletions(-) diff --git a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/EncodeAndDecode.cs b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/EncodeAndDecode.cs index 2fc70413d1a..70693c4c3d9 100644 --- a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/EncodeAndDecode.cs +++ b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/EncodeAndDecode.cs @@ -125,234 +125,6 @@ internal static class RemoteDataNameStrings // to client to let client know if the negotiation succeeded. internal const string IsNegotiationSucceeded = "IsNegotiationSucceeded"; - #region "PSv2 Tab Expansion Function" - - internal const string PSv2TabExpansionFunction = "TabExpansion"; - - /// - /// This is the PSv2 function for tab expansion. It's only for legacy purpose - used in - /// an interactive remote session from a win7 machine to a win8 machine (or later). - /// - internal const string PSv2TabExpansionFunctionText = @" - param($line, $lastWord) - & { - function Write-Members ($sep='.') - { - Invoke-Expression ('$_val=' + $_expression) - - $_method = [Management.Automation.PSMemberTypes] ` - 'Method,CodeMethod,ScriptMethod,ParameterizedProperty' - if ($sep -eq '.') - { - $params = @{view = 'extended','adapted','base'} - } - else - { - $params = @{static=$true} - } - - foreach ($_m in ,$_val | Get-Member @params $_pat | - Sort-Object membertype,name) - { - if ($_m.MemberType -band $_method) - { - # Return a method... - $_base + $_expression + $sep + $_m.name + '(' - } - else { - # Return a property... - $_base + $_expression + $sep + $_m.name - } - } - } - - # If a command name contains any of these chars, it needs to be quoted - $_charsRequiringQuotes = ('`&@''#{}()$,;|<> ' + ""`t"").ToCharArray() - - # If a variable name contains any of these characters it needs to be in braces - $_varsRequiringQuotes = ('-`&@''#{}()$,;|<> .\/' + ""`t"").ToCharArray() - - switch -regex ($lastWord) - { - # Handle property and method expansion rooted at variables... - # e.g. $a.b. - '(^.*)(\$(\w|:|\.)+)\.([*\w]*)$' { - $_base = $matches[1] - $_expression = $matches[2] - $_pat = $matches[4] + '*' - Write-Members - break; - } - - # Handle simple property and method expansion on static members... - # e.g. [datetime]::n - '(^.*)(\[(\w|\.|\+)+\])(\:\:|\.){0,1}([*\w]*)$' { - $_base = $matches[1] - $_expression = $matches[2] - $_pat = $matches[5] + '*' - Write-Members $(if (! $matches[4]) {'::'} else {$matches[4]}) - break; - } - - # Handle complex property and method expansion on static members - # where there are intermediate properties... - # e.g. [datetime]::now.d - '(^.*)(\[(\w|\.|\+)+\](\:\:|\.)(\w+\.)+)([*\w]*)$' { - $_base = $matches[1] # everything before the expression - $_expression = $matches[2].TrimEnd('.') # expression less trailing '.' - $_pat = $matches[6] + '*' # the member to look for... - Write-Members - break; - } - - # Handle variable name expansion... - '(^.*\$)([*\w:]+)$' { - $_prefix = $matches[1] - $_varName = $matches[2] - $_colonPos = $_varname.IndexOf(':') - if ($_colonPos -eq -1) - { - $_varName = 'variable:' + $_varName - $_provider = '' - } - else - { - $_provider = $_varname.Substring(0, $_colonPos+1) - } - - foreach ($_v in Get-ChildItem ($_varName + '*') | sort Name) - { - $_nameFound = $_v.name - $(if ($_nameFound.IndexOfAny($_varsRequiringQuotes) -eq -1) {'{0}{1}{2}'} - else {'{0}{{{1}{2}}}'}) -f $_prefix, $_provider, $_nameFound - } - - break; - } - - # Do completion on parameters... - '^-([*\w0-9]*)' { - $_pat = $matches[1] + '*' - - # extract the command name from the string - # first split the string into statements and pipeline elements - # This doesn't handle strings however. - $_command = [regex]::Split($line, '[|;=]')[-1] - - # Extract the trailing unclosed block e.g. ls | foreach { cp - if ($_command -match '\{([^\{\}]*)$') - { - $_command = $matches[1] - } - - # Extract the longest unclosed parenthetical expression... - if ($_command -match '\(([^()]*)$') - { - $_command = $matches[1] - } - - # take the first space separated token of the remaining string - # as the command to look up. Trim any leading or trailing spaces - # so you don't get leading empty elements. - $_command = $_command.TrimEnd('-') - $_command,$_arguments = $_command.Trim().Split() - - # now get the info object for it, -ArgumentList will force aliases to be resolved - # it also retrieves dynamic parameters - try - { - $_command = @(Get-Command -type 'Alias,Cmdlet,Function,Filter,ExternalScript' ` - -Name $_command -ArgumentList $_arguments)[0] - } - catch - { - # see if the command is an alias. If so, resolve it to the real command - if(Test-Path alias:\$_command) - { - $_command = @(Get-Command -Type Alias $_command)[0].Definition - } - - # If we were unsuccessful retrieving the command, try again without the parameters - $_command = @(Get-Command -type 'Cmdlet,Function,Filter,ExternalScript' ` - -Name $_command)[0] - } - - # remove errors generated by the command not being found, and break - if(-not $_command) { $error.RemoveAt(0); break; } - - # expand the parameter sets and emit the matching elements - # need to use psbase.Keys in case 'keys' is one of the parameters - # to the cmdlet - foreach ($_n in $_command.Parameters.psbase.Keys) - { - if ($_n -like $_pat) { '-' + $_n } - } - - break; - } - - # Tab complete against history either # or # - '^#(\w*)' { - $_pattern = $matches[1] - if ($_pattern -match '^[0-9]+$') - { - Get-History -ea SilentlyContinue -Id $_pattern | ForEach-Object { $_.CommandLine } - } - else - { - $_pattern = '*' + $_pattern + '*' - Get-History -Count 32767 | Sort-Object -Descending Id| ForEach-Object { $_.CommandLine } | where { $_ -like $_pattern } - } - - break; - } - - # try to find a matching command... - default { - # parse the script... - $_tokens = [System.Management.Automation.PSParser]::Tokenize($line, - [ref] $null) - - if ($_tokens) - { - $_lastToken = $_tokens[$_tokens.count - 1] - if ($_lastToken.Type -eq 'Command') - { - $_cmd = $_lastToken.Content - - # don't look for paths... - if ($_cmd.IndexOfAny('/\:') -eq -1) - { - # handle parsing errors - the last token string should be the last - # string in the line... - if ($lastword.Length -ge $_cmd.Length -and - $lastword.substring($lastword.length-$_cmd.length) -eq $_cmd) - { - $_pat = $_cmd + '*' - $_base = $lastword.substring(0, $lastword.length-$_cmd.length) - - # get files in current directory first, then look for commands... - $( try {Resolve-Path -ea SilentlyContinue -Relative $_pat } catch {} ; - try { $ExecutionContext.InvokeCommand.GetCommandName($_pat, $true, $false) | - Sort-Object -Unique } catch {} ) | - # If the command contains non-word characters (space, ) ] ; ) etc.) - # then it needs to be quoted and prefixed with & - ForEach-Object { - if ($_.IndexOfAny($_charsRequiringQuotes) -eq -1) { $_ } - elseif ($_.IndexOf('''') -ge 0) {'& ''{0}''' -f $_.Replace('''','''''') } - else { '& ''{0}''' -f $_ }} | - ForEach-Object {'{0}{1}' -f $_base,$_ } - } - } - } - } - } - } - } - "; - - #endregion "PSv2 Tab Expansion Function" - #region Host Related Strings internal const string CallId = "ci"; diff --git a/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs b/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs index 96aedc03ac3..7f0e5636a4e 100644 --- a/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs +++ b/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs @@ -802,32 +802,14 @@ private void HandleCreateRunspacePool(object sender, RemoteDataEventArgs createR RemotingErrorIdStrings.PSSenderInfoDescription), ScopedItemOptions.ReadOnly)); - // check if the current scenario is Win7(client) to Win8(server). Add back the PSv2 version TabExpansion - // function if necessary. + // Get client PS version from PSSenderInfo. Version psClientVersion = null; if (_senderInfo.ApplicationArguments != null && _senderInfo.ApplicationArguments.ContainsKey("PSversionTable")) { var value = PSObject.Base(_senderInfo.ApplicationArguments["PSversionTable"]) as PSPrimitiveDictionary; - if (value != null) + if (value != null && value.ContainsKey("PSVersion")) { - if (value.ContainsKey("WSManStackVersion")) - { - var wsmanStackVersion = PSObject.Base(value["WSManStackVersion"]) as Version; - if (wsmanStackVersion != null && wsmanStackVersion.Major < 3) - { - // The client side is PSv2. This is the Win7 to Win8 scenario. We need to add the PSv2 - // TabExpansion function back in to keep the tab expansion functionable on the client side. - rsSessionStateToUse.Commands.Add( - new SessionStateFunctionEntry( - RemoteDataNameStrings.PSv2TabExpansionFunction, - RemoteDataNameStrings.PSv2TabExpansionFunctionText)); - } - } - - if (value.ContainsKey("PSVersion")) - { - psClientVersion = PSObject.Base(value["PSVersion"]) as Version; - } + psClientVersion = PSObject.Base(value["PSVersion"]) as Version; } } From 218c6cea15b0faf3f518a4282a8fe469e93ad552 Mon Sep 17 00:00:00 2001 From: Ilya Date: Thu, 15 Dec 2022 11:05:07 +0500 Subject: [PATCH 258/779] Unify CreateFile pinvoke in SMA (#18751) --- .../CoreCLR/CorePsPlatform.cs | 14 -- .../engine/Interop/Windows/CreateFile.cs | 95 +++++++ .../engine/Interop/Windows/Errors.cs | 1 + .../engine/Interop/Windows/FindExecutable.cs | 1 - .../engine/Interop/Windows/FindFirstFile.cs | 12 +- .../remoting/common/RemoteSessionNamedPipe.cs | 66 ++--- .../namespaces/FileSystemProvider.cs | 238 ++++-------------- .../utils/PathUtils.cs | 39 ++- 8 files changed, 212 insertions(+), 254 deletions(-) create mode 100644 src/System.Management.Automation/engine/Interop/Windows/CreateFile.cs diff --git a/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs b/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs index 39ba394842a..1790cc72b52 100644 --- a/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs +++ b/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs @@ -365,11 +365,6 @@ internal static string GetFolderPath(Environment.SpecialFolder folder) // - only to be used with the IsWindows feature query, and only if // no other more specific feature query makes sense - internal static bool NonWindowsIsHardLink(ref IntPtr handle) - { - return Unix.IsHardLink(ref handle); - } - internal static bool NonWindowsIsHardLink(FileSystemInfo fileInfo) { return Unix.IsHardLink(fileInfo); @@ -716,15 +711,6 @@ internal static ErrorCategory GetErrorCategory(int errno) return (ErrorCategory)Unix.NativeMethods.GetErrorCategory(errno); } - /// Is this a hardlink. - /// The handle to a file. - /// A boolean that represents whether the item is a hardlink. - public static bool IsHardLink(ref IntPtr handle) - { - // TODO:PSL implement using fstat to query inode refcount to see if it is a hard link - return false; - } - /// Determine if the item is a hardlink. /// A FileSystemInfo to check to determine if it is a hardlink. /// A boolean that represents whether the item is a hardlink. diff --git a/src/System.Management.Automation/engine/Interop/Windows/CreateFile.cs b/src/System.Management.Automation/engine/Interop/Windows/CreateFile.cs new file mode 100644 index 00000000000..fa1552c91c5 --- /dev/null +++ b/src/System.Management.Automation/engine/Interop/Windows/CreateFile.cs @@ -0,0 +1,95 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System; +using System.IO; +using System.Management.Automation; +using System.Runtime.InteropServices; + +using Microsoft.Win32.SafeHandles; + +internal static partial class Interop +{ + internal static unsafe partial class Windows + { + // dwDesiredAccess of CreateFile + [Flags] + internal enum FileDesiredAccess : uint + { + GenericZero = 0, + GenericRead = 0x80000000, + GenericWrite = 0x40000000, + GenericExecute = 0x20000000, + GenericAll = 0x10000000, + } + + // dwFlagsAndAttributes + [Flags] + internal enum FileAttributes : uint + { + Readonly = 0x00000001, + Hidden = 0x00000002, + System = 0x00000004, + Archive = 0x00000020, + Encrypted = 0x00004000, + Write_Through = 0x80000000, + Overlapped = 0x40000000, + NoBuffering = 0x20000000, + RandomAccess = 0x10000000, + SequentialScan = 0x08000000, + DeleteOnClose = 0x04000000, + BackupSemantics = 0x02000000, + PosixSemantics = 0x01000000, + OpenReparsePoint = 0x00200000, + OpenNoRecall = 0x00100000, + SessionAware = 0x00800000, + Normal = 0x00000080 + } + + // WARNING: This method does not implicitly handle long paths. Use CreateFile. + [LibraryImport("api-ms-win-core-file-l1-1-0.dll", EntryPoint = "CreateFileW", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)] + private static unsafe partial SafeFileHandle CreateFilePrivate( + string lpFileName, + uint dwDesiredAccess, + FileShare dwShareMode, + nint lpSecurityAttributes, + FileMode dwCreationDisposition, + FileAttributes dwFlagsAndAttributes, + IntPtr hTemplateFile); + + [LibraryImport("api-ms-win-core-file-l1-1-0.dll", EntryPoint = "CreateFileW", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)] + private static unsafe partial nint CreateFileWithPipeHandlePrivate( + string lpFileName, + uint dwDesiredAccess, + FileShare dwShareMode, + nint lpSecurityAttributes, + FileMode dwCreationDisposition, + FileAttributes dwFlagsAndAttributes, + IntPtr hTemplateFile); + + internal static unsafe SafeFileHandle CreateFileWithSafeFileHandle( + string lpFileName, + FileAccess dwDesiredAccess, + FileShare dwShareMode, + FileMode dwCreationDisposition, + FileAttributes dwFlagsAndAttributes) + { + lpFileName = Path.TrimEndingDirectorySeparator(lpFileName); + lpFileName = PathUtils.EnsureExtendedPrefixIfNeeded(lpFileName); + + return CreateFilePrivate(lpFileName, (uint)dwDesiredAccess, dwShareMode, nint.Zero, dwCreationDisposition, dwFlagsAndAttributes, nint.Zero); + } + + internal static unsafe nint CreateFileWithPipeHandle( + string lpFileName, + FileAccess dwDesiredAccess, + FileShare dwShareMode, + FileMode dwCreationDisposition, + FileAttributes dwFlagsAndAttributes) + { + return CreateFileWithPipeHandlePrivate(lpFileName, (uint)dwDesiredAccess, dwShareMode, nint.Zero, dwCreationDisposition, dwFlagsAndAttributes, nint.Zero); + } + } +} diff --git a/src/System.Management.Automation/engine/Interop/Windows/Errors.cs b/src/System.Management.Automation/engine/Interop/Windows/Errors.cs index d1654933211..bef9e172193 100644 --- a/src/System.Management.Automation/engine/Interop/Windows/Errors.cs +++ b/src/System.Management.Automation/engine/Interop/Windows/Errors.cs @@ -9,6 +9,7 @@ internal static partial class Windows { // List of error constants https://learn.microsoft.com/en-us/windows/win32/debug/system-error-codes internal const int ERROR_SUCCESS = 0; + internal const int ERROR_FILE_NOT_FOUND = 2; internal const int ERROR_GEN_FAILURE = 31; internal const int ERROR_NOT_SUPPORTED = 50; internal const int ERROR_NO_NETWORK = 1222; diff --git a/src/System.Management.Automation/engine/Interop/Windows/FindExecutable.cs b/src/System.Management.Automation/engine/Interop/Windows/FindExecutable.cs index 7b52c317c87..2184e57a519 100644 --- a/src/System.Management.Automation/engine/Interop/Windows/FindExecutable.cs +++ b/src/System.Management.Automation/engine/Interop/Windows/FindExecutable.cs @@ -24,7 +24,6 @@ internal static unsafe partial class Windows // HINSTANCE == PVOID == nint nint resultCode = 0; - const int MAX_PATH = 260; Span buffer = stackalloc char[MAX_PATH]; unsafe { diff --git a/src/System.Management.Automation/engine/Interop/Windows/FindFirstFile.cs b/src/System.Management.Automation/engine/Interop/Windows/FindFirstFile.cs index b3cd84b028e..1873ada4bf4 100644 --- a/src/System.Management.Automation/engine/Interop/Windows/FindFirstFile.cs +++ b/src/System.Management.Automation/engine/Interop/Windows/FindFirstFile.cs @@ -4,6 +4,8 @@ #nullable enable using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Management.Automation; using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles; @@ -50,6 +52,14 @@ protected override bool ReleaseHandle() // We use 'FindFirstFileW' instead of 'FindFirstFileExW' because the latter doesn't work correctly with Unicode file names on FAT32. // See https://github.com/PowerShell/PowerShell/issues/16804 [LibraryImport("api-ms-win-core-file-l1-1-0.dll", EntryPoint = "FindFirstFileW", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)] - internal static partial SafeFindHandle FindFirstFile(string lpFileName, ref WIN32_FIND_DATA lpFindFileData); + private static partial SafeFindHandle FindFirstFileW(string lpFileName, ref WIN32_FIND_DATA lpFindFileData); + + internal static SafeFindHandle FindFirstFile(string lpFileName, ref WIN32_FIND_DATA lpFindFileData) + { + lpFileName = Path.TrimEndingDirectorySeparator(lpFileName); + lpFileName = PathUtils.EnsureExtendedPrefixIfNeeded(lpFileName); + + return FindFirstFileW(lpFileName, ref lpFindFileData); + } } } diff --git a/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs b/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs index 13ded67a04d..e80c51fb816 100644 --- a/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs +++ b/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs @@ -190,26 +190,6 @@ internal static class NamedPipeNative internal const uint ERROR_IO_INCOMPLETE = 996; internal const uint ERROR_IO_PENDING = 997; - // File function constants - internal const uint GENERIC_READ = 0x80000000; - internal const uint GENERIC_WRITE = 0x40000000; - internal const uint GENERIC_EXECUTE = 0x20000000; - internal const uint GENERIC_ALL = 0x10000000; - - internal const uint CREATE_NEW = 1; - internal const uint CREATE_ALWAYS = 2; - internal const uint OPEN_EXISTING = 3; - internal const uint OPEN_ALWAYS = 4; - internal const uint TRUNCATE_EXISTING = 5; - - internal const uint SECURITY_IMPERSONATIONLEVEL_ANONYMOUS = 0; - internal const uint SECURITY_IMPERSONATIONLEVEL_IDENTIFICATION = 1; - internal const uint SECURITY_IMPERSONATIONLEVEL_IMPERSONATION = 2; - internal const uint SECURITY_IMPERSONATIONLEVEL_DELEGATION = 3; - - // Infinite timeout - internal const uint INFINITE = 0xFFFFFFFF; - #endregion #region Data structures @@ -265,15 +245,6 @@ internal static SECURITY_ATTRIBUTES GetSecurityAttributes(GCHandle securityDescr return securityAttributes; } - [DllImport(PinvokeDllNames.CreateFileDllName, SetLastError = true, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] - internal static extern SafePipeHandle CreateFile( - string lpFileName, - uint dwDesiredAccess, - uint dwShareMode, - IntPtr SecurityAttributes, - uint dwCreationDisposition, - uint dwFlagsAndAttributes, - IntPtr hTemplateFile); #endregion } @@ -1279,30 +1250,34 @@ public ContainerSessionNamedPipeClient( /// protected override NamedPipeClientStream DoConnect(int timeout) { +#if UNIX + // TODO: `CreateFileWithSafePipeHandle` pinvoke below clearly says + // that the code is only for Windows and we could exclude + // a lot of code from compilation on Unix. + throw new NotSupportedException(nameof(DoConnect)); +#else // // WaitNamedPipe API is not supported by Windows Server container now, so we need to repeatedly // attempt connection to pipe server until timeout expires. // int startTime = Environment.TickCount; int elapsedTime = 0; - SafePipeHandle pipeHandle = null; + nint handle; do { // Get handle to pipe. - pipeHandle = NamedPipeNative.CreateFile( + handle = Interop.Windows.CreateFileWithPipeHandle( lpFileName: PipeName, - dwDesiredAccess: NamedPipeNative.GENERIC_READ | NamedPipeNative.GENERIC_WRITE, - dwShareMode: 0, - SecurityAttributes: IntPtr.Zero, - dwCreationDisposition: NamedPipeNative.OPEN_EXISTING, - dwFlagsAndAttributes: NamedPipeNative.FILE_FLAG_OVERLAPPED, - hTemplateFile: IntPtr.Zero); - - int lastError = Marshal.GetLastWin32Error(); - if (pipeHandle.IsInvalid) + FileAccess.ReadWrite, + FileShare.None, + FileMode.Open, + Interop.Windows.FileAttributes.Overlapped); + + if (handle == nint.Zero || handle == (nint)(-1)) { - if (lastError == NamedPipeNative.ERROR_FILE_NOT_FOUND) + int lastError = Marshal.GetLastPInvokeError(); + if (lastError == Interop.Windows.ERROR_FILE_NOT_FOUND) { elapsedTime = unchecked(Environment.TickCount - startTime); Thread.Sleep(100); @@ -1320,19 +1295,22 @@ protected override NamedPipeClientStream DoConnect(int timeout) } } while (elapsedTime < timeout); + SafePipeHandle pipeHandle = null; try { + pipeHandle = new SafePipeHandle(handle, ownsHandle: true); return new NamedPipeClientStream( PipeDirection.InOut, - true, - true, + isAsync: true, + isConnected: true, pipeHandle); } catch (Exception) { - pipeHandle.Dispose(); + pipeHandle?.Dispose(); throw; } +#endif } #endregion diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index 51d84f8f6ab..7edf50b5141 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -7497,13 +7497,6 @@ public class FileSystemProviderRemoveItemDynamicParameters /// public static partial class InternalSymbolicLinkLinkCodeMethods { - // This size comes from measuring the size of the header of REPARSE_GUID_DATA_BUFFER - private const int REPARSE_GUID_DATA_BUFFER_HEADER_SIZE = 24; - - // Maximum reparse buffer info size. The max user defined reparse - // data is 16KB, plus there's a header. - private const int MAX_REPARSE_SIZE = (16 * 1024) + REPARSE_GUID_DATA_BUFFER_HEADER_SIZE; - private const int FSCTL_GET_REPARSE_POINT = 0x000900A8; private const int FSCTL_SET_REPARSE_POINT = 0x000900A4; @@ -7518,62 +7511,6 @@ public static partial class InternalSymbolicLinkLinkCodeMethods private const string NonInterpretedPathPrefix = @"\??\"; - private const int MAX_PATH = 260; - - [Flags] - // dwDesiredAccess of CreateFile - internal enum FileDesiredAccess : uint - { - GenericZero = 0, - GenericRead = 0x80000000, - GenericWrite = 0x40000000, - GenericExecute = 0x20000000, - GenericAll = 0x10000000, - } - - [Flags] - // dwShareMode of CreateFile - internal enum FileShareMode : uint - { - None = 0x00000000, - Read = 0x00000001, - Write = 0x00000002, - Delete = 0x00000004, - } - - // dwCreationDisposition of CreateFile - internal enum FileCreationDisposition : uint - { - New = 1, - CreateAlways = 2, - OpenExisting = 3, - OpenAlways = 4, - TruncateExisting = 5, - } - - [Flags] - // dwFlagsAndAttributes - internal enum FileAttributes : uint - { - Readonly = 0x00000001, - Hidden = 0x00000002, - System = 0x00000004, - Archive = 0x00000020, - Encrypted = 0x00004000, - Write_Through = 0x80000000, - Overlapped = 0x40000000, - NoBuffering = 0x20000000, - RandomAccess = 0x10000000, - SequentialScan = 0x08000000, - DeleteOnClose = 0x04000000, - BackupSemantics = 0x02000000, - PosixSemantics = 0x01000000, - OpenReparsePoint = 0x00200000, - OpenNoRecall = 0x00100000, - SessionAware = 0x00800000, - Normal = 0x00000080 - } - [StructLayout(LayoutKind.Sequential)] private struct REPARSE_DATA_BUFFER_SYMBOLICLINK { @@ -7626,29 +7563,6 @@ internal struct FILE_TIME public uint dwHighDateTime; } - [StructLayout(LayoutKind.Sequential)] - private struct GUID - { - public uint Data1; - public ushort Data2; - public ushort Data3; - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] - public char[] Data4; - } - - [StructLayout(LayoutKind.Sequential)] - private struct REPARSE_GUID_DATA_BUFFER - { - public uint ReparseTag; - public ushort ReparseDataLength; - public ushort Reserved; - public GUID ReparseGuid; - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = MAX_REPARSE_SIZE)] - public char[] DataBuffer; - } - [LibraryImport(PinvokeDllNames.DeviceIoControlDllName, StringMarshalling = StringMarshalling.Utf16, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static partial bool DeviceIoControl(IntPtr hDevice, uint dwIoControlCode, @@ -7662,16 +7576,6 @@ private static partial bool GetFileInformationByHandle( IntPtr hFile, out BY_HANDLE_FILE_INFORMATION lpFileInformation); - [LibraryImport(PinvokeDllNames.CreateFileDllName, EntryPoint = "CreateFileW", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)] - internal static partial IntPtr CreateFile( - string lpFileName, - FileDesiredAccess dwDesiredAccess, - FileShareMode dwShareMode, - IntPtr lpSecurityAttributes, - FileCreationDisposition dwCreationDisposition, - FileAttributes dwFlagsAndAttributes, - IntPtr hTemplateFile); - /// /// Gets the target of the specified reparse point. /// @@ -7729,16 +7633,14 @@ public static string GetLinkType(PSObject instance) private static string InternalGetLinkType(FileSystemInfo fileInfo) { - if (Platform.IsWindows) - { - return WinInternalGetLinkType(fileInfo.FullName); - } - else - { - return Platform.NonWindowsInternalGetLinkType(fileInfo); - } +#if UNIX + return Platform.NonWindowsInternalGetLinkType(fileInfo); +#else + return WinInternalGetLinkType(fileInfo.FullName); +#endif } +#if !UNIX [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods")] private static string WinInternalGetLinkType(string filePath) { @@ -7746,7 +7648,7 @@ private static string WinInternalGetLinkType(string filePath) // If this parameter is zero, the application can query certain metadata // such as file, directory, or device attributes without accessing // that file or device, even if GENERIC_READ access would have been denied. - using (SafeFileHandle handle = WinOpenReparsePoint(filePath, FileDesiredAccess.GenericZero)) + using (SafeFileHandle handle = WinOpenReparsePoint(filePath, (FileAccess)0)) { int outBufferSize = Marshal.SizeOf(); @@ -7778,7 +7680,7 @@ private static string WinInternalGetLinkType(string filePath) if (!result) { // It's not a reparse point or the file system doesn't support reparse points. - return IsHardLink(ref dangerousHandle) ? "HardLink" : null; + return WinIsHardLink(ref dangerousHandle) ? "HardLink" : null; } REPARSE_DATA_BUFFER_SYMBOLICLINK reparseDataBuffer = Marshal.PtrToStructure(outBuffer); @@ -7811,13 +7713,28 @@ private static string WinInternalGetLinkType(string filePath) } } } +#endif internal static bool IsHardLink(FileSystemInfo fileInfo) { #if UNIX return Platform.NonWindowsIsHardLink(fileInfo); #else - return WinIsHardLink(fileInfo); + bool isHardLink = false; + + // only check for hard link if the item is not directory + if ((fileInfo.Attributes & System.IO.FileAttributes.Directory) != System.IO.FileAttributes.Directory) + { + SafeFileHandle handle = Interop.Windows.CreateFileWithSafeFileHandle(fileInfo.FullName, FileAccess.Read, FileShare.Read, FileMode.Open, Interop.Windows.FileAttributes.Normal); + + using (handle) + { + var dangerousHandle = handle.DangerousGetHandle(); + isHardLink = InternalSymbolicLinkLinkCodeMethods.WinIsHardLink(ref dangerousHandle); + } + } + + return isHardLink; #endif } @@ -7838,13 +7755,7 @@ internal static bool IsReparsePointLikeSymlink(FileSystemInfo fileInfo) } Interop.Windows.WIN32_FIND_DATA data = default; - string fullPath = Path.TrimEndingDirectorySeparator(fileInfo.FullName); - if (fullPath.Length >= MAX_PATH) - { - fullPath = PathUtils.EnsureExtendedPrefix(fullPath); - } - - using (Interop.Windows.SafeFindHandle handle = Interop.Windows.FindFirstFile(fullPath, ref data)) + using (Interop.Windows.SafeFindHandle handle = Interop.Windows.FindFirstFile(fileInfo.FullName, ref data)) { if (handle.IsInvalid) { @@ -7877,43 +7788,6 @@ internal static bool IsReparsePointLikeSymlink(FileSystemInfo fileInfo) #endif } - internal static bool WinIsHardLink(FileSystemInfo fileInfo) - { - bool isHardLink = false; - - // only check for hard link if the item is not directory - if ((fileInfo.Attributes & System.IO.FileAttributes.Directory) != System.IO.FileAttributes.Directory) - { - IntPtr nativeHandle = InternalSymbolicLinkLinkCodeMethods.CreateFile( - fileInfo.FullName, - InternalSymbolicLinkLinkCodeMethods.FileDesiredAccess.GenericRead, - InternalSymbolicLinkLinkCodeMethods.FileShareMode.Read, - IntPtr.Zero, - InternalSymbolicLinkLinkCodeMethods.FileCreationDisposition.OpenExisting, - InternalSymbolicLinkLinkCodeMethods.FileAttributes.Normal, - IntPtr.Zero); - - using (SafeFileHandle handle = new SafeFileHandle(nativeHandle, true)) - { - bool success = false; - - try - { - handle.DangerousAddRef(ref success); - IntPtr dangerousHandle = handle.DangerousGetHandle(); - isHardLink = InternalSymbolicLinkLinkCodeMethods.IsHardLink(ref dangerousHandle); - } - finally - { - if (success) - handle.DangerousRelease(); - } - } - } - - return isHardLink; - } - internal static bool IsSameFileSystemItem(string pathOne, string pathTwo) { #if UNIX @@ -7926,13 +7800,10 @@ internal static bool IsSameFileSystemItem(string pathOne, string pathTwo) #if !UNIX private static bool WinIsSameFileSystemItem(string pathOne, string pathTwo) { - const FileAccess access = FileAccess.Read; - const FileShare share = FileShare.Read; - const FileMode creation = FileMode.Open; - const FileAttributes attributes = FileAttributes.BackupSemantics | FileAttributes.PosixSemantics; + const Interop.Windows.FileAttributes Attributes = Interop.Windows.FileAttributes.BackupSemantics | Interop.Windows.FileAttributes.PosixSemantics; - using (var sfOne = AlternateDataStreamUtilities.NativeMethods.CreateFile(pathOne, access, share, IntPtr.Zero, creation, (int)attributes, IntPtr.Zero)) - using (var sfTwo = AlternateDataStreamUtilities.NativeMethods.CreateFile(pathTwo, access, share, IntPtr.Zero, creation, (int)attributes, IntPtr.Zero)) + using (var sfOne = Interop.Windows.CreateFileWithSafeFileHandle(pathOne, FileAccess.Read, FileShare.Read, FileMode.Open, Attributes)) + using (var sfTwo = Interop.Windows.CreateFileWithSafeFileHandle(pathTwo, FileAccess.Read, FileShare.Read, FileMode.Open, Attributes)) { if (!sfOne.IsInvalid && !sfTwo.IsInvalid) { @@ -7965,12 +7836,9 @@ internal static bool GetInodeData(string path, out System.ValueTuple inodeData) { - const FileAccess access = FileAccess.Read; - const FileShare share = FileShare.Read; - const FileMode creation = FileMode.Open; - const FileAttributes attributes = FileAttributes.BackupSemantics | FileAttributes.PosixSemantics; + const Interop.Windows.FileAttributes Attributes = Interop.Windows.FileAttributes.BackupSemantics | Interop.Windows.FileAttributes.PosixSemantics; - using (var sf = AlternateDataStreamUtilities.NativeMethods.CreateFile(path, access, share, IntPtr.Zero, creation, (int)attributes, IntPtr.Zero)) + using (var sf = Interop.Windows.CreateFileWithSafeFileHandle(path, FileAccess.Read, FileShare.Read, FileMode.Open, Attributes)) { if (!sf.IsInvalid) { @@ -7994,15 +7862,6 @@ private static bool WinGetInodeData(string path, out System.ValueTuple + /// Adds the extended path prefix (\\?\) if not already a device path, IF the path is not relative, + /// AND the path is more than 259 characters. (> MAX_PATH + null). This will also insert the extended + /// prefix if the path ends with a period or a space. Trailing periods and spaces are normally eaten + /// away from paths during normalization, but if we see such a path at this point it should be + /// normalized and has retained the final characters. (Typically from one of the *Info classes). + /// + /// File path. + /// File path (with extended prefix if the path is long path). + [return: NotNullIfNotNull(nameof(path))] + internal static string? EnsureExtendedPrefixIfNeeded(string? path) + { + if (path != null && (path.Length >= MaxShortPath || EndsWithPeriodOrSpace(path))) + { + return EnsureExtendedPrefix(path); + } + else + { + return path; + } + } + internal static string EnsureExtendedPrefix(string path) { if (IsPartiallyQualified(path) || IsDevice(path)) @@ -495,10 +520,22 @@ internal static string EnsureExtendedPrefix(string path) private const string UncDevicePrefixToInsert = @"?\UNC\"; private const string UncExtendedPathPrefix = @"\\?\UNC\"; private const string DevicePathPrefix = @"\\.\"; + private const int MaxShortPath = 260; // \\?\, \\.\, \??\ private const int DevicePrefixLength = 4; + private static bool EndsWithPeriodOrSpace(string? path) + { + if (string.IsNullOrEmpty(path)) + { + return false; + } + + char c = path[path.Length - 1]; + return c == ' ' || c == '.'; + } + /// /// Returns true if the given character is a valid drive letter /// From bae00ec7d2a0c38951ffd12e386a94cbfd3ff672 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 15 Dec 2022 16:23:48 +0000 Subject: [PATCH 259/779] Bump Microsoft.CodeAnalysis.NetAnalyzers (#18750) Bumps [Microsoft.CodeAnalysis.NetAnalyzers](https://github.com/dotnet/roslyn-analyzers) from 7.0.0-preview1.22551.1 to 7.0.0. - [Release notes](https://github.com/dotnet/roslyn-analyzers/releases) - [Changelog](https://github.com/dotnet/roslyn-analyzers/blob/main/PostReleaseActivities.md) - [Commits](https://github.com/dotnet/roslyn-analyzers/commits/7.0.0) --- updated-dependencies: - dependency-name: Microsoft.CodeAnalysis.NetAnalyzers dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- Analyzers.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Analyzers.props b/Analyzers.props index f2d6a44ec1c..192d9433fda 100644 --- a/Analyzers.props +++ b/Analyzers.props @@ -1,7 +1,7 @@ - + From bcb0a9425d37d9fe3de2fc0792488bfe65b95628 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Thu, 15 Dec 2022 18:55:50 +0100 Subject: [PATCH 260/779] Cleanup webrequestpscmdlet.common.cs (#18596) --- .../Common/WebRequestPSCmdlet.Common.cs | 273 ++++++++---------- 1 file changed, 117 insertions(+), 156 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index 06da66dd868..dbbe169ae3d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -237,14 +237,7 @@ public abstract partial class WebRequestPSCmdlet : PSCmdlet /// [Parameter] [ValidateRange(0, int.MaxValue)] - public virtual int MaximumRedirection - { - get { return _maximumRedirection; } - - set { _maximumRedirection = value; } - } - - private int _maximumRedirection = -1; + public virtual int MaximumRedirection { get; set; } = -1; /// /// Gets or sets the MaximumRetryCount property, which determines the number of retries of a failed web request. @@ -269,14 +262,7 @@ public virtual int MaximumRedirection /// [Parameter(ParameterSetName = "StandardMethod")] [Parameter(ParameterSetName = "StandardMethodNoProxy")] - public virtual WebRequestMethod Method - { - get { return _method; } - - set { _method = value; } - } - - private WebRequestMethod _method = WebRequestMethod.Default; + public virtual WebRequestMethod Method { get; set; } = WebRequestMethod.Default; /// /// Gets or sets the CustomMethod property. @@ -285,14 +271,7 @@ public virtual WebRequestMethod Method [Parameter(Mandatory = true, ParameterSetName = "CustomMethodNoProxy")] [Alias("CM")] [ValidateNotNullOrEmpty] - public virtual string CustomMethod - { - get { return _customMethod; } - - set { _customMethod = value; } - } - - private string _customMethod; + public virtual string CustomMethod { get; set; } #endregion @@ -410,102 +389,89 @@ public virtual string CustomMethod internal virtual void ValidateParameters() { // sessions - if ((WebSession != null) && (SessionVariable != null)) + if (WebSession is not null && SessionVariable is not null) { - ErrorRecord error = GetValidationError(WebCmdletStrings.SessionConflict, - "WebCmdletSessionConflictException"); + ErrorRecord error = GetValidationError(WebCmdletStrings.SessionConflict, "WebCmdletSessionConflictException"); ThrowTerminatingError(error); } // Authentication - if (UseDefaultCredentials && (Authentication != WebAuthenticationType.None)) + if (UseDefaultCredentials && Authentication != WebAuthenticationType.None) { - ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationConflict, - "WebCmdletAuthenticationConflictException"); + ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationConflict, "WebCmdletAuthenticationConflictException"); ThrowTerminatingError(error); } - if ((Authentication != WebAuthenticationType.None) && (Token != null) && (Credential != null)) + if (Authentication != WebAuthenticationType.None && Token is not null && Credential is not null) { - ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationTokenConflict, - "WebCmdletAuthenticationTokenConflictException"); + ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationTokenConflict, "WebCmdletAuthenticationTokenConflictException"); ThrowTerminatingError(error); } - if ((Authentication == WebAuthenticationType.Basic) && (Credential == null)) + if (Authentication == WebAuthenticationType.Basic && Credential is null) { - ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationCredentialNotSupplied, - "WebCmdletAuthenticationCredentialNotSuppliedException"); + ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationCredentialNotSupplied, "WebCmdletAuthenticationCredentialNotSuppliedException"); ThrowTerminatingError(error); } - if ((Authentication == WebAuthenticationType.OAuth || Authentication == WebAuthenticationType.Bearer) && (Token == null)) + if ((Authentication == WebAuthenticationType.OAuth || Authentication == WebAuthenticationType.Bearer) && Token is null) { - ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationTokenNotSupplied, - "WebCmdletAuthenticationTokenNotSuppliedException"); + ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationTokenNotSupplied, "WebCmdletAuthenticationTokenNotSuppliedException"); ThrowTerminatingError(error); } - if (!AllowUnencryptedAuthentication && (Authentication != WebAuthenticationType.None) && (Uri.Scheme != "https")) + if (!AllowUnencryptedAuthentication && Authentication != WebAuthenticationType.None && Uri.Scheme != "https") { - ErrorRecord error = GetValidationError(WebCmdletStrings.AllowUnencryptedAuthenticationRequired, - "WebCmdletAllowUnencryptedAuthenticationRequiredException"); + ErrorRecord error = GetValidationError(WebCmdletStrings.AllowUnencryptedAuthenticationRequired, "WebCmdletAllowUnencryptedAuthenticationRequiredException"); ThrowTerminatingError(error); } - if (!AllowUnencryptedAuthentication && (Credential != null || UseDefaultCredentials) && (Uri.Scheme != "https")) + if (!AllowUnencryptedAuthentication && (Credential is not null || UseDefaultCredentials) && Uri.Scheme != "https") { - ErrorRecord error = GetValidationError(WebCmdletStrings.AllowUnencryptedAuthenticationRequired, - "WebCmdletAllowUnencryptedAuthenticationRequiredException"); + ErrorRecord error = GetValidationError(WebCmdletStrings.AllowUnencryptedAuthenticationRequired, "WebCmdletAllowUnencryptedAuthenticationRequiredException"); ThrowTerminatingError(error); } // credentials - if (UseDefaultCredentials && (Credential != null)) + if (UseDefaultCredentials && Credential is not null) { - ErrorRecord error = GetValidationError(WebCmdletStrings.CredentialConflict, - "WebCmdletCredentialConflictException"); + ErrorRecord error = GetValidationError(WebCmdletStrings.CredentialConflict, "WebCmdletCredentialConflictException"); ThrowTerminatingError(error); } // Proxy server - if (ProxyUseDefaultCredentials && (ProxyCredential != null)) + if (ProxyUseDefaultCredentials && ProxyCredential is not null) { - ErrorRecord error = GetValidationError(WebCmdletStrings.ProxyCredentialConflict, - "WebCmdletProxyCredentialConflictException"); + ErrorRecord error = GetValidationError(WebCmdletStrings.ProxyCredentialConflict, "WebCmdletProxyCredentialConflictException"); ThrowTerminatingError(error); } - else if ((Proxy == null) && ((ProxyCredential != null) || ProxyUseDefaultCredentials)) + else if (Proxy is null && (ProxyCredential is not null || ProxyUseDefaultCredentials)) { - ErrorRecord error = GetValidationError(WebCmdletStrings.ProxyUriNotSupplied, - "WebCmdletProxyUriNotSuppliedException"); + ErrorRecord error = GetValidationError(WebCmdletStrings.ProxyUriNotSupplied, "WebCmdletProxyUriNotSuppliedException"); ThrowTerminatingError(error); } // request body content - if ((Body != null) && (InFile != null)) + if (Body is not null && InFile is not null) { - ErrorRecord error = GetValidationError(WebCmdletStrings.BodyConflict, - "WebCmdletBodyConflictException"); + ErrorRecord error = GetValidationError(WebCmdletStrings.BodyConflict, "WebCmdletBodyConflictException"); ThrowTerminatingError(error); } - if ((Body != null) && (Form != null)) + if (Body is not null && Form is not null) { - ErrorRecord error = GetValidationError(WebCmdletStrings.BodyFormConflict, - "WebCmdletBodyFormConflictException"); + ErrorRecord error = GetValidationError(WebCmdletStrings.BodyFormConflict, "WebCmdletBodyFormConflictException"); ThrowTerminatingError(error); } - if ((InFile != null) && (Form != null)) + if (InFile is not null && Form is not null) { - ErrorRecord error = GetValidationError(WebCmdletStrings.FormInFileConflict, - "WebCmdletFormInFileConflictException"); + ErrorRecord error = GetValidationError(WebCmdletStrings.FormInFileConflict, "WebCmdletFormInFileConflictException"); ThrowTerminatingError(error); } // validate InFile path - if (InFile != null) + if (InFile is not null) { ProviderInfo provider = null; ErrorRecord errorRecord = null; @@ -516,27 +482,23 @@ internal virtual void ValidateParameters() if (!provider.Name.Equals(FileSystemProvider.ProviderName, StringComparison.OrdinalIgnoreCase)) { - errorRecord = GetValidationError(WebCmdletStrings.NotFilesystemPath, - "WebCmdletInFileNotFilesystemPathException", InFile); + errorRecord = GetValidationError(WebCmdletStrings.NotFilesystemPath, "WebCmdletInFileNotFilesystemPathException", InFile); } else { if (providerPaths.Count > 1) { - errorRecord = GetValidationError(WebCmdletStrings.MultiplePathsResolved, - "WebCmdletInFileMultiplePathsResolvedException", InFile); + errorRecord = GetValidationError(WebCmdletStrings.MultiplePathsResolved, "WebCmdletInFileMultiplePathsResolvedException", InFile); } else if (providerPaths.Count == 0) { - errorRecord = GetValidationError(WebCmdletStrings.NoPathResolved, - "WebCmdletInFileNoPathResolvedException", InFile); + errorRecord = GetValidationError(WebCmdletStrings.NoPathResolved, "WebCmdletInFileNoPathResolvedException", InFile); } else { if (Directory.Exists(providerPaths[0])) { - errorRecord = GetValidationError(WebCmdletStrings.DirectoryPathSpecified, - "WebCmdletInFileNotFilePathException", InFile); + errorRecord = GetValidationError(WebCmdletStrings.DirectoryPathSpecified, "WebCmdletInFileNotFilePathException", InFile); } _originalFilePath = InFile; @@ -557,25 +519,23 @@ internal virtual void ValidateParameters() errorRecord = new ErrorRecord(driveNotFound.ErrorRecord, driveNotFound); } - if (errorRecord != null) + if (errorRecord is not null) { ThrowTerminatingError(errorRecord); } } // output ?? - if (PassThru && (OutFile == null)) + if (PassThru && OutFile is null) { - ErrorRecord error = GetValidationError(WebCmdletStrings.OutFileMissing, - "WebCmdletOutFileMissingException", nameof(PassThru)); + ErrorRecord error = GetValidationError(WebCmdletStrings.OutFileMissing, "WebCmdletOutFileMissingException", nameof(PassThru)); ThrowTerminatingError(error); } // Resume requires OutFile. - if (Resume.IsPresent && OutFile == null) + if (Resume.IsPresent && OutFile is null) { - ErrorRecord error = GetValidationError(WebCmdletStrings.OutFileMissing, - "WebCmdletOutFileMissingException", nameof(Resume)); + ErrorRecord error = GetValidationError(WebCmdletStrings.OutFileMissing, "WebCmdletOutFileMissingException", nameof(Resume)); ThrowTerminatingError(error); } } @@ -585,17 +545,15 @@ internal virtual void PrepareSession() // make sure we have a valid WebRequestSession object to work with WebSession ??= new WebRequestSession(); - if (SessionVariable != null) + if (SessionVariable is not null) { // save the session back to the PS environment if requested PSVariableIntrinsics vi = SessionState.PSVariable; vi.Set(SessionVariable, WebSession); } - // // handle credentials - // - if (Credential != null && Authentication == WebAuthenticationType.None) + if (Credential is not null && Authentication == WebAuthenticationType.None) { // get the relevant NetworkCredential NetworkCredential netCred = Credential.GetNetworkCredential(); @@ -604,7 +562,7 @@ internal virtual void PrepareSession() // supplying a credential overrides the UseDefaultCredentials setting WebSession.UseDefaultCredentials = false; } - else if ((Credential != null || Token != null) && Authentication != WebAuthenticationType.None) + else if ((Credential is not null || Token is not null) && Authentication != WebAuthenticationType.None) { ProcessAuthentication(); } @@ -613,7 +571,7 @@ internal virtual void PrepareSession() WebSession.UseDefaultCredentials = true; } - if (CertificateThumbprint != null) + if (CertificateThumbprint is not null) { X509Store store = new(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly); @@ -632,25 +590,23 @@ internal virtual void PrepareSession() } } - if (Certificate != null) + if (Certificate is not null) { WebSession.AddCertificate(Certificate); } - // // handle the user agent - // - if (UserAgent != null) + if (UserAgent is not null) { // store the UserAgent string WebSession.UserAgent = UserAgent; } - if (Proxy != null) + if (Proxy is not null) { WebProxy webProxy = new(Proxy); webProxy.BypassProxyOnLocal = false; - if (ProxyCredential != null) + if (ProxyCredential is not null) { webProxy.Credentials = ProxyCredential.GetNetworkCredential(); } @@ -670,7 +626,7 @@ internal virtual void PrepareSession() } // store the other supplied headers - if (Headers != null) + if (Headers is not null) { foreach (string key in Headers.Keys) { @@ -699,33 +655,18 @@ internal virtual void PrepareSession() #region Helper Properties - internal string QualifiedOutFile - { - get { return (QualifyFilePath(OutFile)); } - } + internal string QualifiedOutFile => QualifyFilePath(OutFile); - internal bool ShouldSaveToOutFile - { - get { return (!string.IsNullOrEmpty(OutFile)); } - } + internal bool ShouldSaveToOutFile => !string.IsNullOrEmpty(OutFile); - internal bool ShouldWriteToPipeline - { - get { return (!ShouldSaveToOutFile || PassThru); } - } + internal bool ShouldWriteToPipeline => !ShouldSaveToOutFile || PassThru; - internal bool ShouldCheckHttpStatus - { - get { return !SkipHttpErrorCheck; } - } + internal bool ShouldCheckHttpStatus => !SkipHttpErrorCheck; /// /// Determines whether writing to a file should Resume and append rather than overwrite. /// - internal bool ShouldResume - { - get { return (Resume.IsPresent && _resumeSuccess); } - } + internal bool ShouldResume => Resume.IsPresent && _resumeSuccess; #endregion Helper Properties @@ -738,12 +679,12 @@ private Uri PrepareUri(Uri uri) // preprocess Body if content is a dictionary and method is GET (set as query) IDictionary bodyAsDictionary; LanguagePrimitives.TryConvertTo(Body, out bodyAsDictionary); - if ((bodyAsDictionary != null) + if (bodyAsDictionary is not null && ((IsStandardMethodSet() && (Method == WebRequestMethod.Default || Method == WebRequestMethod.Get)) || (IsCustomMethodSet() && CustomMethod.ToUpperInvariant() == "GET"))) { UriBuilder uriBuilder = new(uri); - if (uriBuilder.Query != null && uriBuilder.Query.Length > 1) + if (uriBuilder.Query is not null && uriBuilder.Query.Length > 1) { uriBuilder.Query = string.Concat(uriBuilder.Query.AsSpan(1), "&", FormatDictionary(bodyAsDictionary)); } @@ -769,7 +710,7 @@ private static Uri CheckProtocol(Uri uri) uri = new Uri("http://" + uri.OriginalString); } - return (uri); + return uri; } private string QualifyFilePath(string path) @@ -795,7 +736,7 @@ private static string FormatDictionary(IDictionary content) // URLEncode the key and value string encodedKey = WebUtility.UrlEncode(key); string encodedValue = string.Empty; - if (value != null) + if (value is not null) { encodedValue = WebUtility.UrlEncode(value.ToString()); } @@ -810,7 +751,7 @@ private ErrorRecord GetValidationError(string msg, string errorId) { var ex = new ValidationMetadataException(msg); var error = new ErrorRecord(ex, errorId, ErrorCategory.InvalidArgument, this); - return (error); + return error; } private ErrorRecord GetValidationError(string msg, string errorId, params object[] args) @@ -818,7 +759,7 @@ private ErrorRecord GetValidationError(string msg, string errorId, params object msg = string.Format(CultureInfo.InvariantCulture, msg, args); var ex = new ValidationMetadataException(msg); var error = new ErrorRecord(ex, errorId, ErrorCategory.InvalidArgument, this); - return (error); + return error; } private bool IsStandardMethodSet() @@ -1001,7 +942,7 @@ internal virtual HttpClient GetHttpClient(bool handleRedirect) // the UseDefaultCredentials flag overrides other supplied credentials handler.UseDefaultCredentials = true; } - else if (WebSession.Credentials != null) + else if (WebSession.Credentials is not null) { handler.Credentials = WebSession.Credentials; } @@ -1010,12 +951,12 @@ internal virtual HttpClient GetHttpClient(bool handleRedirect) { handler.UseProxy = false; } - else if (WebSession.Proxy != null) + else if (WebSession.Proxy is not null) { handler.Proxy = WebSession.Proxy; } - if (WebSession.Certificates != null) + if (WebSession.Certificates is not null) { handler.ClientCertificates.AddRange(WebSession.Certificates); } @@ -1149,7 +1090,7 @@ internal virtual HttpRequestMessage GetRequest(Uri uri) } // Set 'Transfer-Encoding' - if (TransferEncoding != null) + if (TransferEncoding is not null) { request.Headers.TransferEncodingChunked = true; var headerValue = new TransferCodingHeaderValue(TransferEncoding); @@ -1175,7 +1116,7 @@ internal virtual HttpRequestMessage GetRequest(Uri uri) } } - return (request); + return request; } internal virtual void FillRequestStream(HttpRequestMessage request) @@ -1183,12 +1124,12 @@ internal virtual void FillRequestStream(HttpRequestMessage request) ArgumentNullException.ThrowIfNull(request); // set the content type - if (ContentType != null) + if (ContentType is not null) { WebSession.ContentHeaders[HttpKnownHeaderNames.ContentType] = ContentType; // request } - // ContentType == null + // ContentType is null else if (Method == WebRequestMethod.Post || (IsCustomMethodSet() && CustomMethod.ToUpperInvariant() == "POST")) { // Win8:545310 Invoke-WebRequest does not properly set MIME type for POST @@ -1200,7 +1141,7 @@ internal virtual void FillRequestStream(HttpRequestMessage request) } } - if (Form != null) + if (Form is not null) { // Content headers will be set by MultipartFormDataContent which will throw unless we clear them first WebSession.ContentHeaders.Clear(); @@ -1215,13 +1156,13 @@ internal virtual void FillRequestStream(HttpRequestMessage request) SetRequestContent(request, formData); } // coerce body into a usable form - else if (Body != null) + else if (Body is not null) { object content = Body; // make sure we're using the base object of the body, not the PSObject wrapper PSObject psBody = Body as PSObject; - if (psBody != null) + if (psBody is not null) { content = psBody.BaseObject; } @@ -1258,7 +1199,7 @@ internal virtual void FillRequestStream(HttpRequestMessage request) (string)LanguagePrimitives.ConvertTo(content, typeof(string), CultureInfo.InvariantCulture)); } } - else if (InFile != null) // copy InFile data + else if (InFile is not null) // copy InFile data { try { @@ -1267,8 +1208,11 @@ internal virtual void FillRequestStream(HttpRequestMessage request) } catch (UnauthorizedAccessException) { - string msg = string.Format(CultureInfo.InvariantCulture, WebCmdletStrings.AccessDenied, - _originalFilePath); + string msg = string.Format( + CultureInfo.InvariantCulture, + WebCmdletStrings.AccessDenied, + _originalFilePath); + throw new UnauthorizedAccessException(msg); } } @@ -1343,6 +1287,7 @@ private static bool IsRedirectToGet(HttpStatusCode code) private bool ShouldRetry(HttpStatusCode code) { int intCode = (int)code; + return ( (intCode == 304 || (intCode >= 400 && intCode <= 599)) && WebSession.MaximumRetryCount > 0 @@ -1368,7 +1313,7 @@ internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestM _cancelToken = new CancellationTokenSource(); response = client.SendAsync(req, HttpCompletionOption.ResponseHeadersRead, _cancelToken.Token).GetAwaiter().GetResult(); - if (keepAuthorization && IsRedirectCode(response.StatusCode) && response.Headers.Location != null) + if (keepAuthorization && IsRedirectCode(response.StatusCode) && response.Headers.Location is not null) { _cancelToken.Cancel(); _cancelToken = null; @@ -1416,7 +1361,7 @@ internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestM { FillRequestStream(requestWithoutRange); long requestContentLength = 0; - if (requestWithoutRange.Content != null) + if (requestWithoutRange.Content is not null) { requestContentLength = requestWithoutRange.Content.Headers.ContentLength.Value; } @@ -1427,6 +1372,7 @@ internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestM requestWithoutRange.Version, requestWithoutRange.Method, requestContentLength); + WriteVerbose(reqVerboseMsg); return GetResponse(client, requestWithoutRange, keepAuthorization); @@ -1435,7 +1381,7 @@ internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestM _resumeSuccess = response.StatusCode == HttpStatusCode.PartialContent; - // When MaximumRetryCount is not specified, the totalRequests == 1. + // When MaximumRetryCount is not specified, the totalRequests is 1. if (totalRequests > 1 && ShouldRetry(response.StatusCode)) { int retryIntervalInSeconds = WebSession.RetryIntervalInSeconds; @@ -1505,13 +1451,10 @@ protected override void ProcessRecord() // if the request contains an authorization header and PreserveAuthorizationOnRedirect is not set, // it needs to be stripped on the first redirect. - bool keepAuthorization = WebSession != null - && - WebSession.Headers != null - && - PreserveAuthorizationOnRedirect.IsPresent - && - WebSession.Headers.ContainsKey(HttpKnownHeaderNames.Authorization); + bool keepAuthorization = WebSession is not null && + WebSession.Headers is not null && + PreserveAuthorizationOnRedirect.IsPresent && + WebSession.Headers.ContainsKey(HttpKnownHeaderNames.Authorization); using (HttpClient client = GetHttpClient(keepAuthorization)) { @@ -1521,9 +1464,11 @@ protected override void ProcessRecord() { if (followedRelLink > 0) { - string linkVerboseMsg = string.Format(CultureInfo.CurrentCulture, + string linkVerboseMsg = string.Format( + CultureInfo.CurrentCulture, WebCmdletStrings.FollowingRelLinkVerboseMsg, uri.AbsoluteUri); + WriteVerbose(linkVerboseMsg); } @@ -1533,7 +1478,7 @@ protected override void ProcessRecord() try { long requestContentLength = 0; - if (request.Content != null) + if (request.Content is not null) requestContentLength = request.Content.Headers.ContentLength.Value; string reqVerboseMsg = string.Format( @@ -1548,10 +1493,12 @@ protected override void ProcessRecord() HttpResponseMessage response = GetResponse(client, request, keepAuthorization); string contentType = ContentHelper.GetContentType(response); - string respVerboseMsg = string.Format(CultureInfo.CurrentCulture, + string respVerboseMsg = string.Format( + CultureInfo.CurrentCulture, WebCmdletStrings.WebResponseVerboseMsg, response.Content.Headers.ContentLength, contentType); + WriteVerbose(respVerboseMsg); bool _isSuccess = response.IsSuccessStatusCode; @@ -1564,15 +1511,23 @@ protected override void ProcessRecord() response.Content.Headers.ContentRange.Length == _resumeFileSize) { _isSuccess = true; - WriteVerbose(string.Format(CultureInfo.CurrentCulture, WebCmdletStrings.OutFileWritingSkipped, OutFile)); + WriteVerbose(string.Format( + CultureInfo.CurrentCulture, + WebCmdletStrings.OutFileWritingSkipped, + OutFile)); + // Disable writing to the OutFile. OutFile = null; } if (ShouldCheckHttpStatus && !_isSuccess) { - string message = string.Format(CultureInfo.CurrentCulture, WebCmdletStrings.ResponseStatusCodeFailure, - (int)response.StatusCode, response.ReasonPhrase); + string message = string.Format( + CultureInfo.CurrentCulture, + WebCmdletStrings.ResponseStatusCodeFailure, + (int)response.StatusCode, + response.ReasonPhrase); + HttpResponseException httpEx = new(message, response); ErrorRecord er = new(httpEx, "WebCmdletWebResponseException", ErrorCategory.InvalidOperation, request); string detailMsg = string.Empty; @@ -1612,7 +1567,7 @@ protected override void ProcessRecord() // Errors with redirection counts of greater than 0 are handled automatically by .NET, but are // impossible to detect programmatically when we hit this limit. By handling this ourselves // (and still writing out the result), users can debug actual HTTP redirect problems. - if (WebSession.MaximumRedirection == 0 && IsRedirectCode(response.StatusCode)) // Indicate "HttpClientHandler.AllowAutoRedirect == false" + if (WebSession.MaximumRedirection == 0 && IsRedirectCode(response.StatusCode)) // Indicate "HttpClientHandler.AllowAutoRedirect is false" { ErrorRecord er = new(new InvalidOperationException(), "MaximumRedirectExceeded", ErrorCategory.InvalidOperation, request); er.ErrorDetails = new ErrorDetails(WebCmdletStrings.MaximumRedirectionCountExceeded); @@ -1622,7 +1577,7 @@ protected override void ProcessRecord() catch (HttpRequestException ex) { ErrorRecord er = new(ex, "WebCmdletWebResponseException", ErrorCategory.InvalidOperation, request); - if (ex.InnerException != null) + if (ex.InnerException is not null) { er.ErrorDetails = new ErrorDetails(ex.InnerException.Message); } @@ -1680,8 +1635,10 @@ internal long SetRequestContent(HttpRequestMessage request, byte[] content) { ArgumentNullException.ThrowIfNull(request); - if (content == null) + if (content is null) + { return 0; + } var byteArrayContent = new ByteArrayContent(content); request.Content = byteArrayContent; @@ -1703,11 +1660,13 @@ internal long SetRequestContent(HttpRequestMessage request, string content) { ArgumentNullException.ThrowIfNull(request); - if (content == null) + if (content is null) + { return 0; - + } + Encoding encoding = null; - if (ContentType != null) + if (ContentType is not null) { // If Content-Type contains the encoding format (as CharSet), use this encoding format // to encode the Body of the WebRequest sent to the server. Default Encoding format @@ -1751,8 +1710,10 @@ internal long SetRequestContent(HttpRequestMessage request, XmlNode xmlNode) { ArgumentNullException.ThrowIfNull(request); - if (xmlNode == null) + if (xmlNode is null) + { return 0; + } byte[] bytes = null; XmlDocument doc = xmlNode as XmlDocument; @@ -1823,12 +1784,12 @@ internal long SetRequestContent(HttpRequestMessage request, IDictionary content) ArgumentNullException.ThrowIfNull(content); string body = FormatDictionary(content); - return (SetRequestContent(request, body)); + return SetRequestContent(request, body); } internal void ParseLinkHeader(HttpResponseMessage response, System.Uri requestUri) { - if (_relationLink == null) + if (_relationLink is null) { // Must ignore the case of relation links. See RFC 8288 (https://tools.ietf.org/html/rfc8288) _relationLink = new Dictionary(StringComparer.OrdinalIgnoreCase); From 30d56b6586a9ccd0c7ec264da9153b95d34801b8 Mon Sep 17 00:00:00 2001 From: MartinGC94 <42123497+MartinGC94@users.noreply.github.com> Date: Thu, 15 Dec 2022 19:11:27 +0100 Subject: [PATCH 261/779] Use Pattern matching in ast.cs (#18794) --- .../engine/parser/ast.cs | 107 +++++++----------- 1 file changed, 42 insertions(+), 65 deletions(-) diff --git a/src/System.Management.Automation/engine/parser/ast.cs b/src/System.Management.Automation/engine/parser/ast.cs index 4ee07ea967d..53a76bfc62f 100644 --- a/src/System.Management.Automation/engine/parser/ast.cs +++ b/src/System.Management.Automation/engine/parser/ast.cs @@ -320,20 +320,20 @@ internal bool IsInWorkflow() while (current != null && !stopScanning) { - ScriptBlockAst scriptBlock = current as ScriptBlockAst; - if (scriptBlock != null) + if (current is ScriptBlockAst scriptBlock) { // See if this uses the workflow keyword - FunctionDefinitionAst functionDefinition = scriptBlock.Parent as FunctionDefinitionAst; - if ((functionDefinition != null)) + if (scriptBlock.Parent is FunctionDefinitionAst functionDefinition) { stopScanning = true; - if (functionDefinition.IsWorkflow) { return true; } + if (functionDefinition.IsWorkflow) + { + return true; + } } } - CommandAst commandAst = current as CommandAst; - if (commandAst != null && + if (current is CommandAst commandAst && string.Equals(TokenKind.InlineScript.Text(), commandAst.GetCommandName(), StringComparison.OrdinalIgnoreCase) && this != commandAst) { @@ -388,8 +388,7 @@ internal static TypeDefinitionAst GetAncestorTypeDefinitionAst(Ast ast) // Nested function isn't really a member of the type so stop looking // Anonymous script blocks are though - var functionDefinitionAst = ast as FunctionDefinitionAst; - if (functionDefinitionAst != null && functionDefinitionAst.Parent is not FunctionMemberAst) + if (ast is FunctionDefinitionAst functionDefinitionAst && functionDefinitionAst.Parent is not FunctionMemberAst) break; ast = ast.Parent; } @@ -1373,8 +1372,7 @@ internal string ToStringForSerialization(Tuple, stri // We are done processing the section that we care about if (astStartOffset >= endOffset) { break; } - var varAst = ast as VariableExpressionAst; - if (varAst != null) + if (ast is VariableExpressionAst varAst) { VariablePath varPath = varAst.VariablePath; string varName = varPath.IsDriveQualified ? $"{varPath.DriveName}_{varPath.UnqualifiedPath}" : $"{varPath.UnqualifiedPath}"; @@ -1454,8 +1452,7 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) if (action == AstVisitAction.SkipChildren) return visitor.CheckForPostAction(this, AstVisitAction.Continue); - var visitor2 = visitor as AstVisitor2; - if (visitor2 != null) + if (visitor is AstVisitor2 visitor2) { if (action == AstVisitAction.Continue) { @@ -1943,8 +1940,7 @@ public NamedBlockAst(IScriptExtent extent, TokenKind blockName, StatementBlockAs if (!unnamed) { - var statementsExtent = statementBlock.Extent as InternalScriptExtent; - if (statementsExtent != null) + if (statementBlock.Extent is InternalScriptExtent statementsExtent) { this.OpenCurlyExtent = new InternalScriptExtent(statementsExtent.PositionHelper, statementsExtent.StartOffset, statementsExtent.StartOffset + 1); this.CloseCurlyExtent = new InternalScriptExtent(statementsExtent.PositionHelper, statementsExtent.EndOffset - 1, statementsExtent.EndOffset); @@ -2820,8 +2816,7 @@ internal override object Accept(ICustomAstVisitor visitor) internal override AstVisitAction InternalVisit(AstVisitor visitor) { var action = AstVisitAction.Continue; - var visitor2 = visitor as AstVisitor2; - if (visitor2 != null) + if (visitor is AstVisitor2 visitor2) { action = visitor2.VisitTypeDefinition(this); if (action == AstVisitAction.SkipChildren) @@ -3068,8 +3063,7 @@ internal override object Accept(ICustomAstVisitor visitor) internal override AstVisitAction InternalVisit(AstVisitor visitor) { var action = AstVisitAction.Continue; - var visitor2 = visitor as AstVisitor2; - if (visitor2 != null) + if (visitor is AstVisitor2 visitor2) { action = visitor2.VisitUsingStatement(this); if (action != AstVisitAction.Continue) @@ -3296,8 +3290,7 @@ internal override object Accept(ICustomAstVisitor visitor) internal override AstVisitAction InternalVisit(AstVisitor visitor) { var action = AstVisitAction.Continue; - var visitor2 = visitor as AstVisitor2; - if (visitor2 != null) + if (visitor is AstVisitor2 visitor2) { action = visitor2.VisitPropertyMember(this); if (action == AstVisitAction.SkipChildren) @@ -3312,7 +3305,10 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) { var attributeAst = Attributes[index]; action = attributeAst.InternalVisit(visitor); - if (action != AstVisitAction.Continue) break; + if (action != AstVisitAction.Continue) + { + break; + } } } @@ -3546,8 +3542,7 @@ internal override object Accept(ICustomAstVisitor visitor) internal override AstVisitAction InternalVisit(AstVisitor visitor) { var action = AstVisitAction.Continue; - var visitor2 = visitor as AstVisitor2; - if (visitor2 != null) + if (visitor is AstVisitor2 visitor2) { action = visitor2.VisitFunctionMember(this); if (action == AstVisitAction.SkipChildren) @@ -3558,7 +3553,10 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) { var attributeAst = Attributes[index]; action = attributeAst.InternalVisit(visitor); - if (action != AstVisitAction.Continue) break; + if (action != AstVisitAction.Continue) + { + break; + } } } @@ -6415,19 +6413,13 @@ public AssignmentStatementAst(IScriptExtent extent, ExpressionAst left, TokenKin // If the assignment is just an expression and the expression is not backgrounded then // remove the pipeline wrapping the expression. - var pipelineAst = right as PipelineAst; - if (pipelineAst != null && !pipelineAst.Background) + if (right is PipelineAst pipelineAst + && !pipelineAst.Background + && pipelineAst.PipelineElements.Count == 1 + && pipelineAst.PipelineElements[0] is CommandExpressionAst commandExpressionAst) { - if (pipelineAst.PipelineElements.Count == 1) - { - var commandExpressionAst = pipelineAst.PipelineElements[0] as CommandExpressionAst; - - if (commandExpressionAst != null) - { - right = commandExpressionAst; - right.ClearParent(); - } - } + right = commandExpressionAst; + right.ClearParent(); } this.Operator = @operator; @@ -6476,8 +6468,7 @@ public override Ast Copy() /// All of the expressions assigned by the assignment statement. public IEnumerable GetAssignmentTargets() { - var arrayExpression = Left as ArrayLiteralAst; - if (arrayExpression != null) + if (Left is ArrayLiteralAst arrayExpression) { foreach (var element in arrayExpression.Elements) { @@ -6616,8 +6607,7 @@ internal override object Accept(ICustomAstVisitor visitor) internal override AstVisitAction InternalVisit(AstVisitor visitor) { var action = AstVisitAction.Continue; - var visitor2 = visitor as AstVisitor2; - if (visitor2 != null) + if (visitor is AstVisitor2 visitor2) { action = visitor2.VisitConfigurationDefinition(this); if (action == AstVisitAction.SkipChildren) @@ -7085,8 +7075,7 @@ internal override object Accept(ICustomAstVisitor visitor) internal override AstVisitAction InternalVisit(AstVisitor visitor) { var action = AstVisitAction.Continue; - var visitor2 = visitor as AstVisitor2; - if (visitor2 != null) + if (visitor is AstVisitor2 visitor2) { action = visitor2.VisitDynamicKeywordStatement(this); if (action == AstVisitAction.SkipChildren) @@ -7188,7 +7177,6 @@ internal PipelineAst GenerateCommandCallPipelineAst() } ExpressionAst expr = BodyExpression; - HashtableAst hashtable = expr as HashtableAst; if (Keyword.DirectCall) { // If this keyword takes a name, then add it as the parameter -InstanceName @@ -7207,7 +7195,7 @@ internal PipelineAst GenerateCommandCallPipelineAst() // in the hash literal expression and map them to parameters. // We've already checked to make sure that they're all valid names. // - if (hashtable != null) + if (expr is HashtableAst hashtable) { bool isHashtableValid = true; // @@ -7391,10 +7379,7 @@ protected ExpressionAst(IScriptExtent extent) /// internal virtual bool ShouldPreserveOutputInCaseOfException() { - var parenExpr = this as ParenExpressionAst; - var subExpr = this as SubExpressionAst; - - if (parenExpr == null && subExpr == null) + if (this is not ParenExpressionAst and not SubExpressionAst) { PSTraceSource.NewInvalidOperationException(); } @@ -7410,8 +7395,7 @@ internal virtual bool ShouldPreserveOutputInCaseOfException() return false; } - var parenExpressionAst = pipelineAst.Parent as ParenExpressionAst; - if (parenExpressionAst != null) + if (pipelineAst.Parent is ParenExpressionAst parenExpressionAst) { return parenExpressionAst.ShouldPreserveOutputInCaseOfException(); } @@ -7993,8 +7977,7 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) IAssignableValue ISupportsAssignment.GetAssignableValue() { - var varExpr = Child as VariableExpressionAst; - if (varExpr != null && varExpr.TupleIndex >= 0) + if (Child is VariableExpressionAst varExpr && varExpr.TupleIndex >= 0) { // In the common case of a single cast on the lhs of an assignment, we may have saved the type of the // variable in the mutable tuple, so conversions will get generated elsewhere, and we can just use @@ -8366,8 +8349,7 @@ public BaseCtorInvokeMemberExpressionAst(IScriptExtent baseKeywordExtent, IScrip internal override AstVisitAction InternalVisit(AstVisitor visitor) { AstVisitAction action = AstVisitAction.Continue; - var visitor2 = visitor as AstVisitor2; - if (visitor2 != null) + if (visitor is AstVisitor2 visitor2) { action = visitor2.VisitBaseCtorInvokeMemberExpression(this); if (action == AstVisitAction.SkipChildren) @@ -8557,8 +8539,7 @@ internal bool HasDefaultCtor() bool hasExplicitCtor = false; foreach (var member in _typeDefinitionAst.Members) { - var function = member as FunctionMemberAst; - if (function != null) + if (member is FunctionMemberAst function) { if (function.IsConstructor) { @@ -9831,8 +9812,7 @@ public ExpandableStringExpressionAst(IScriptExtent extent, } var ast = Language.Parser.ScanString(value); - var expandableStringAst = ast as ExpandableStringExpressionAst; - if (expandableStringAst != null) + if (ast is ExpandableStringExpressionAst expandableStringAst) { this.FormatExpression = expandableStringAst.FormatExpression; this.NestedExpressions = expandableStringAst.NestedExpressions; @@ -10465,10 +10445,9 @@ public static VariableExpressionAst ExtractUsingVariable(UsingExpressionAst usin /// private static VariableExpressionAst ExtractUsingVariableImpl(ExpressionAst expression) { - var usingExpr = expression as UsingExpressionAst; VariableExpressionAst variableExpr; - if (usingExpr != null) + if (expression is UsingExpressionAst usingExpr) { variableExpr = usingExpr.SubExpression as VariableExpressionAst; if (variableExpr != null) @@ -10479,8 +10458,7 @@ private static VariableExpressionAst ExtractUsingVariableImpl(ExpressionAst expr return ExtractUsingVariableImpl(usingExpr.SubExpression); } - var indexExpr = expression as IndexExpressionAst; - if (indexExpr != null) + if (expression is IndexExpressionAst indexExpr) { variableExpr = indexExpr.Target as VariableExpressionAst; if (variableExpr != null) @@ -10491,8 +10469,7 @@ private static VariableExpressionAst ExtractUsingVariableImpl(ExpressionAst expr return ExtractUsingVariableImpl(indexExpr.Target); } - var memberExpr = expression as MemberExpressionAst; - if (memberExpr != null) + if (expression is MemberExpressionAst memberExpr) { variableExpr = memberExpr.Expression as VariableExpressionAst; if (variableExpr != null) From 2b38f80855e90523b078e56da6e8dab970d648cc Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Thu, 15 Dec 2022 10:43:55 -0800 Subject: [PATCH 262/779] Update the release tag in `metadata.json` for next preview (#18799) --- src/System.Management.Automation/engine/PSVersionInfo.cs | 3 ++- test/powershell/Host/PSVersionTable.Tests.ps1 | 2 +- test/powershell/Language/Scripting/Requires.Tests.ps1 | 2 +- tools/metadata.json | 2 +- 4 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/System.Management.Automation/engine/PSVersionInfo.cs b/src/System.Management.Automation/engine/PSVersionInfo.cs index 009f6704fad..ec78842da18 100644 --- a/src/System.Management.Automation/engine/PSVersionInfo.cs +++ b/src/System.Management.Automation/engine/PSVersionInfo.cs @@ -76,6 +76,7 @@ private const int Version_Major private static readonly Version s_psV7Version = new(7, 0, 0); private static readonly Version s_psV71Version = new(7, 1, 0); private static readonly Version s_psV72Version = new(7, 2, 0); + private static readonly Version s_psV73Version = new(7, 3, 0); private static readonly Version s_psVersion; private static readonly SemanticVersion s_psSemVersion; @@ -97,7 +98,7 @@ static PSVersionInfo() s_psVersionTable[PSVersionName] = s_psSemVersion; s_psVersionTable[PSEditionName] = PSEditionValue; s_psVersionTable[PSGitCommitIdName] = GitCommitId; - s_psVersionTable[PSCompatibleVersionsName] = new Version[] { s_psV1Version, s_psV2Version, s_psV3Version, s_psV4Version, s_psV5Version, s_psV51Version, s_psV6Version, s_psV61Version, s_psV62Version, s_psV7Version, s_psV71Version, s_psV72Version, s_psVersion }; + s_psVersionTable[PSCompatibleVersionsName] = new Version[] { s_psV1Version, s_psV2Version, s_psV3Version, s_psV4Version, s_psV5Version, s_psV51Version, s_psV6Version, s_psV61Version, s_psV62Version, s_psV7Version, s_psV71Version, s_psV72Version, s_psV73Version, s_psVersion }; s_psVersionTable[SerializationVersionName] = new Version(InternalSerializer.DefaultVersion); s_psVersionTable[PSRemotingProtocolVersionName] = RemotingConstants.ProtocolVersion; s_psVersionTable[WSManStackVersionName] = GetWSManStackVersion(); diff --git a/test/powershell/Host/PSVersionTable.Tests.ps1 b/test/powershell/Host/PSVersionTable.Tests.ps1 index 3f6ccfcd8ba..173239fe9d4 100644 --- a/test/powershell/Host/PSVersionTable.Tests.ps1 +++ b/test/powershell/Host/PSVersionTable.Tests.ps1 @@ -23,7 +23,7 @@ Describe "PSVersionTable" -Tags "CI" { $unexpectectGitCommitIdPattern = $fullVersionPattern } - $powerShellVersions = "1.0", "2.0", "3.0", "4.0", "5.0", "5.1", "6.0", "6.1", "6.2", "7.0", "7.1", "7.2", "7.3" + $powerShellVersions = "1.0", "2.0", "3.0", "4.0", "5.0", "5.1", "6.0", "6.1", "6.2", "7.0", "7.1", "7.2", "7.3", "7.4" $powerShellCompatibleVersions = $PSVersionTable.PSCompatibleVersions | ForEach-Object {$_.ToString(2).SubString(0,3)} } diff --git a/test/powershell/Language/Scripting/Requires.Tests.ps1 b/test/powershell/Language/Scripting/Requires.Tests.ps1 index 4675a9ce864..30dd73451c6 100644 --- a/test/powershell/Language/Scripting/Requires.Tests.ps1 +++ b/test/powershell/Language/Scripting/Requires.Tests.ps1 @@ -41,7 +41,7 @@ Describe "Requires tests" -Tags "CI" { BeforeAll { $currentVersion = $PSVersionTable.PSVersion - $powerShellVersions = "1.0", "2.0", "3.0", "4.0", "5.0", "5.1", "6.0", "6.1", "6.2", "7.0", "7.1", "7.2", "7.3" + $powerShellVersions = "1.0", "2.0", "3.0", "4.0", "5.0", "5.1", "6.0", "6.1", "6.2", "7.0", "7.1", "7.2", "7.3", "7.4" $latestVersion = [version]($powerShellVersions | Sort-Object -Descending -Top 1) $nonExistingMinor = "$($latestVersion.Major).$($latestVersion.Minor + 1)" $nonExistingMajor = "$($latestVersion.Major + 1).0" diff --git a/tools/metadata.json b/tools/metadata.json index bf3fddb126d..23698dda348 100644 --- a/tools/metadata.json +++ b/tools/metadata.json @@ -4,7 +4,7 @@ "ServicingReleaseTag": "v7.0.13", "ReleaseTag": "v7.3.1", "LTSReleaseTag" : ["v7.2.8", "v7.0.13"], - "NextReleaseTag": "v7.3.0-preview.9", + "NextReleaseTag": "v7.4.0-preview.1", "LTSRelease": { "Latest": false, "Package": false }, "StableRelease": { "Latest": false, "Package": false } } From c0e6a9c82c143dd2a1212aae2dc40a52f3f890de Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Thu, 15 Dec 2022 11:33:35 -0800 Subject: [PATCH 263/779] Remove unnecessary reference to `System.Runtime.CompilerServices.Unsafe` (#18806) --- .../System.Management.Automation.csproj | 1 - 1 file changed, 1 deletion(-) diff --git a/src/System.Management.Automation/System.Management.Automation.csproj b/src/System.Management.Automation/System.Management.Automation.csproj index 97d6416128d..8dd51bbf126 100644 --- a/src/System.Management.Automation/System.Management.Automation.csproj +++ b/src/System.Management.Automation/System.Management.Automation.csproj @@ -40,7 +40,6 @@ - From 61d04b62b10ac61656a8fa3ff63d8d3b0672a775 Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Thu, 15 Dec 2022 11:45:24 -0800 Subject: [PATCH 264/779] Bump `Microsoft.PowerShell.Native` to the latest preview version `v7.4.0-preview.1` (#18805) --- .../System.Management.Automation.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/System.Management.Automation/System.Management.Automation.csproj b/src/System.Management.Automation/System.Management.Automation.csproj index 8dd51bbf126..48fc97827f1 100644 --- a/src/System.Management.Automation/System.Management.Automation.csproj +++ b/src/System.Management.Automation/System.Management.Automation.csproj @@ -46,7 +46,7 @@ - + From b48943ce31534b12736df9768efc670c76a09163 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Fri, 16 Dec 2022 12:46:45 +0100 Subject: [PATCH 265/779] Replace ArgumentNullException(nameof()) -> ArgumentNullException.ThrowIfNull() 2 (#18792) --- .../CimRegisterCimIndication.cs | 6 ++---- .../Utils.cs | 5 +---- .../ManagementList/Common/WpfHelp.cs | 10 ++-------- .../ManagementList/DefaultStringConverter.cs | 4 +++- .../ShowCommand/ViewModel/AllModulesViewModel.cs | 4 +++- .../cimSupport/cmdletization/SessionBasedWrapper.cs | 3 ++- .../commands/management/TestConnectionCommand.cs | 4 +++- .../Common/InvokeRestMethodCommand.Common.cs | 2 +- .../host/msh/CommandLineParameterParser.cs | 5 +---- .../Eventing/EventProviderTraceListener.cs | 3 +-- src/Microsoft.WSMan.Management/ConfigProvider.cs | 2 +- .../CoreCLR/CorePsAssemblyLoadContext.cs | 2 ++ .../engine/ComInterop/Helpers.cs | 5 +---- .../engine/DefaultCommandRuntime.cs | 3 +-- .../engine/GetCommandCommand.cs | 4 +++- .../engine/InitialSessionState.cs | 12 ++---------- .../engine/PSClassInfo.cs | 2 ++ src/System.Management.Automation/engine/Utils.cs | 9 ++++----- .../engine/lang/scriptblock.cs | 7 +++---- .../engine/parser/SafeValues.cs | 8 ++++---- .../engine/remoting/commands/JobRepository.cs | 10 ++-------- .../namespaces/FileSystemProvider.cs | 1 - .../namespaces/TransactedRegistryKey.cs | 8 ++------ .../utils/BackgroundDispatcher.cs | 3 ++- .../utils/ParserException.cs | 4 +++- .../utils/perfCounters/CounterSetRegistrarBase.cs | 6 ++++-- 26 files changed, 55 insertions(+), 77 deletions(-) diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRegisterCimIndication.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRegisterCimIndication.cs index 24b9332bde5..c08fa0c44ea 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRegisterCimIndication.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRegisterCimIndication.cs @@ -149,10 +149,8 @@ public void RegisterCimIndication( uint operationTimeout) { DebugHelper.WriteLogEx("queryDialect = '{0}'; queryExpression = '{1}'", 0, queryDialect, queryExpression); - if (cimSession == null) - { - throw new ArgumentNullException(string.Format(CultureInfo.CurrentUICulture, CimCmdletStrings.NullArgument, nameof(cimSession))); - } + + ArgumentNullException.ThrowIfNull(cimSession, string.Format(CultureInfo.CurrentUICulture, CimCmdletStrings.NullArgument, nameof(cimSession))); this.TargetComputerName = cimSession.ComputerName; CimSessionProxy proxy = CreateSessionProxy(cimSession, operationTimeout); diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/Utils.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/Utils.cs index 955d7f8613f..61afc00a676 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/Utils.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/Utils.cs @@ -371,10 +371,7 @@ internal static class ValidationHelper /// public static void ValidateNoNullArgument(object obj, string argumentName) { - if (obj == null) - { - throw new ArgumentNullException(argumentName); - } + ArgumentNullException.ThrowIfNull(obj, argumentName); } /// diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/WpfHelp.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/WpfHelp.cs index b0839c6ccd2..4bc9ebef28d 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/WpfHelp.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/WpfHelp.cs @@ -214,10 +214,7 @@ public static void AddChild(FrameworkElement parent, FrameworkElement element) { ArgumentNullException.ThrowIfNull(element); - if (parent == null) - { - throw new ArgumentNullException("element"); - } + ArgumentNullException.ThrowIfNull(parent, nameof(element)); ContentControl parentContentControl = parent as ContentControl; @@ -370,10 +367,7 @@ public static T FindVisualAncestorData(this DependencyObject obj) /// The specified value is a null reference. public static T FindVisualAncestor(this DependencyObject @object) where T : class { - if (@object == null) - { - throw new ArgumentNullException("object"); - } + ArgumentNullException.ThrowIfNull(@object, nameof(@object)); DependencyObject parent = VisualTreeHelper.GetParent(@object); diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/DefaultStringConverter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/DefaultStringConverter.cs index cf85d79ae36..2d590904097 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/DefaultStringConverter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/DefaultStringConverter.cs @@ -62,7 +62,9 @@ public string DefaultValue /// public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) { - if (values == null || values.Length != 1) + ArgumentNullException.ThrowIfNull(values); + + if (values.Length != 1) { throw new ArgumentNullException("values"); } diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/AllModulesViewModel.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/AllModulesViewModel.cs index da51550c084..d2899b994d6 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/AllModulesViewModel.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/AllModulesViewModel.cs @@ -79,7 +79,9 @@ public class AllModulesViewModel : INotifyPropertyChanged /// Commands to show. public AllModulesViewModel(Dictionary importedModules, IEnumerable commands) { - if (commands == null || !commands.GetEnumerator().MoveNext()) + ArgumentNullException.ThrowIfNull(commands); + + if (!commands.GetEnumerator().MoveNext()) { throw new ArgumentNullException("commands"); } diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs index 58a1fbb4c2d..8da4d7f4c78 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs @@ -82,7 +82,8 @@ protected TSession[] Session set { - _session = value ?? throw new ArgumentNullException(nameof(value)); + ArgumentNullException.ThrowIfNull(value); + _session = value; _sessionWasSpecified = true; } } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/TestConnectionCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/TestConnectionCommand.cs index e6b33142457..e11be68156a 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/TestConnectionCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/TestConnectionCommand.cs @@ -575,10 +575,12 @@ private void ProcessMTUSize(string targetNameOrAddress) } else { + ArgumentNullException.ThrowIfNull(replyResult); + WriteObject(new PingMtuStatus( Source, resolvedTargetName, - replyResult ?? throw new ArgumentNullException(nameof(replyResult)), + replyResult, CurrentMTUSize)); } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs index 50a88bb6754..a6a2a6290b0 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs @@ -189,7 +189,7 @@ internal override void ProcessResponse(HttpResponseMessage response) private static RestReturnType CheckReturnType(HttpResponseMessage response) { - if (response == null) { throw new ArgumentNullException(nameof(response)); } + ArgumentNullException.ThrowIfNull(response); RestReturnType rt = RestReturnType.Detect; string contentType = ContentHelper.GetContentType(response); diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs index c3e2e196cbb..9e555bd428b 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs @@ -833,10 +833,7 @@ internal void Parse(string[] args) for (int i = 0; i < args.Length; i++) { - if (args[i] is null) - { - throw new ArgumentNullException(nameof(args), CommandLineParameterParserStrings.NullElementInArgs); - } + ArgumentNullException.ThrowIfNull(args[i], CommandLineParameterParserStrings.NullElementInArgs); } // Indicates that we've called this method on this instance, and that when it's done, the state variables diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProviderTraceListener.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProviderTraceListener.cs index 94eb340b21c..1c82891b654 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProviderTraceListener.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProviderTraceListener.cs @@ -41,8 +41,7 @@ public string Delimiter [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] set { - if (value == null) - throw new ArgumentNullException(nameof(Delimiter)); + ArgumentNullException.ThrowIfNull(value, nameof(Delimiter)); if (value.Length == 0) throw new ArgumentException(DotNetEventingStrings.Argument_NeedNonemptyDelimiter); diff --git a/src/Microsoft.WSMan.Management/ConfigProvider.cs b/src/Microsoft.WSMan.Management/ConfigProvider.cs index de99812b01d..98c76e31c89 100644 --- a/src/Microsoft.WSMan.Management/ConfigProvider.cs +++ b/src/Microsoft.WSMan.Management/ConfigProvider.cs @@ -3413,7 +3413,7 @@ private static string NormalizePath(string path, string host) /// private PSObject GetItemValue(string path) { - if (string.IsNullOrEmpty(path) || (path.Length == 0)) + if (string.IsNullOrEmpty(path)) { throw new ArgumentNullException(path); } diff --git a/src/System.Management.Automation/CoreCLR/CorePsAssemblyLoadContext.cs b/src/System.Management.Automation/CoreCLR/CorePsAssemblyLoadContext.cs index 2e4e7fe0f9b..5cd38cec25b 100644 --- a/src/System.Management.Automation/CoreCLR/CorePsAssemblyLoadContext.cs +++ b/src/System.Management.Automation/CoreCLR/CorePsAssemblyLoadContext.cs @@ -580,7 +580,9 @@ public static class PowerShellAssemblyLoadContextInitializer public static void SetPowerShellAssemblyLoadContext([MarshalAs(UnmanagedType.LPWStr)] string basePaths) { if (string.IsNullOrEmpty(basePaths)) + { throw new ArgumentNullException(nameof(basePaths)); + } PowerShellAssemblyLoadContext.InitializeSingleton(basePaths); } diff --git a/src/System.Management.Automation/engine/ComInterop/Helpers.cs b/src/System.Management.Automation/engine/ComInterop/Helpers.cs index 513c3126476..814e93825a7 100644 --- a/src/System.Management.Automation/engine/ComInterop/Helpers.cs +++ b/src/System.Management.Automation/engine/ComInterop/Helpers.cs @@ -35,10 +35,7 @@ internal static class Requires [System.Diagnostics.Conditional("DEBUG")] internal static void NotNull(object value, string paramName) { - if (value == null) - { - throw new ArgumentNullException(paramName); - } + ArgumentNullException.ThrowIfNull(value, paramName); } [System.Diagnostics.Conditional("DEBUG")] diff --git a/src/System.Management.Automation/engine/DefaultCommandRuntime.cs b/src/System.Management.Automation/engine/DefaultCommandRuntime.cs index 48d74667dae..88a2a2ee427 100644 --- a/src/System.Management.Automation/engine/DefaultCommandRuntime.cs +++ b/src/System.Management.Automation/engine/DefaultCommandRuntime.cs @@ -21,8 +21,7 @@ internal class DefaultCommandRuntime : ICommandRuntime2 /// public DefaultCommandRuntime(List outputList) { - if (outputList == null) - throw new System.ArgumentNullException(nameof(outputList)); + ArgumentNullException.ThrowIfNull(outputList); _output = outputList; } diff --git a/src/System.Management.Automation/engine/GetCommandCommand.cs b/src/System.Management.Automation/engine/GetCommandCommand.cs index 113ba8121b8..81675d7b663 100644 --- a/src/System.Management.Automation/engine/GetCommandCommand.cs +++ b/src/System.Management.Automation/engine/GetCommandCommand.cs @@ -278,7 +278,9 @@ public string[] ParameterName set { - _parameterNames = value ?? throw new ArgumentNullException(nameof(value)); + ArgumentNullException.ThrowIfNull(value); + + _parameterNames = value; _parameterNameWildcards = SessionStateUtilities.CreateWildcardsFromStrings( _parameterNames, WildcardOptions.CultureInvariant | WildcardOptions.IgnoreCase); diff --git a/src/System.Management.Automation/engine/InitialSessionState.cs b/src/System.Management.Automation/engine/InitialSessionState.cs index 2dbb12fb253..e041b0d7006 100644 --- a/src/System.Management.Automation/engine/InitialSessionState.cs +++ b/src/System.Management.Automation/engine/InitialSessionState.cs @@ -3738,11 +3738,7 @@ internal PSSnapInInfo ImportCorePSSnapIn() internal PSSnapInInfo ImportPSSnapIn(PSSnapInInfo psSnapInInfo, out PSSnapInException warning) { - if (psSnapInInfo == null) - { - ArgumentNullException e = new ArgumentNullException(nameof(psSnapInInfo)); - throw e; - } + ArgumentNullException.ThrowIfNull(psSnapInInfo); // See if the snapin is already loaded. If has been then there will be an entry in the // Assemblies list for it already... @@ -3918,11 +3914,7 @@ internal static Assembly LoadAssemblyFromFile(string fileName) internal void ImportCmdletsFromAssembly(Assembly assembly, PSModuleInfo module) { - if (assembly == null) - { - ArgumentNullException e = new ArgumentNullException(nameof(assembly)); - throw e; - } + ArgumentNullException.ThrowIfNull(assembly); string assemblyPath = assembly.Location; PSSnapInHelpers.AnalyzePSSnapInAssembly( diff --git a/src/System.Management.Automation/engine/PSClassInfo.cs b/src/System.Management.Automation/engine/PSClassInfo.cs index fd0ca8d8936..c73e9250071 100644 --- a/src/System.Management.Automation/engine/PSClassInfo.cs +++ b/src/System.Management.Automation/engine/PSClassInfo.cs @@ -62,7 +62,9 @@ public sealed class PSClassMemberInfo internal PSClassMemberInfo(string name, string memberType, string defaultValue) { if (string.IsNullOrEmpty(name)) + { throw new ArgumentNullException(nameof(name)); + } this.Name = name; this.TypeName = memberType; diff --git a/src/System.Management.Automation/engine/Utils.cs b/src/System.Management.Automation/engine/Utils.cs index 93a3e80b74b..b472393ff53 100644 --- a/src/System.Management.Automation/engine/Utils.cs +++ b/src/System.Management.Automation/engine/Utils.cs @@ -1740,10 +1740,7 @@ internal static class Requires { internal static void NotNull(object value, string paramName) { - if (value == null) - { - throw new ArgumentNullException(paramName); - } + ArgumentNullException.ThrowIfNull(value, paramName); } internal static void NotNullOrEmpty(string value, string paramName) @@ -1756,7 +1753,9 @@ internal static void NotNullOrEmpty(string value, string paramName) internal static void NotNullOrEmpty(ICollection value, string paramName) { - if (value == null || value.Count == 0) + ArgumentNullException.ThrowIfNull(value, paramName); + + if (value.Count == 0) { throw new ArgumentNullException(paramName); } diff --git a/src/System.Management.Automation/engine/lang/scriptblock.cs b/src/System.Management.Automation/engine/lang/scriptblock.cs index 3c7d6576aaa..cc2f8ef9138 100644 --- a/src/System.Management.Automation/engine/lang/scriptblock.cs +++ b/src/System.Management.Automation/engine/lang/scriptblock.cs @@ -1138,10 +1138,9 @@ public void Begin(bool expectInput, EngineIntrinsics contextToRedirectTo) /// The command you're calling this from (i.e. instance of PSCmdlet or value of $PSCmdlet variable). public void Begin(InternalCommand command) { - if (command == null || command.MyInvocation == null) - { - throw new ArgumentNullException(nameof(command)); - } + ArgumentNullException.ThrowIfNull(command); + + ArgumentNullException.ThrowIfNull(command.MyInvocation, nameof(command)); Begin(command.MyInvocation.ExpectingInput, command.commandRuntime); } diff --git a/src/System.Management.Automation/engine/parser/SafeValues.cs b/src/System.Management.Automation/engine/parser/SafeValues.cs index 0e41f87a318..f551270c372 100644 --- a/src/System.Management.Automation/engine/parser/SafeValues.cs +++ b/src/System.Management.Automation/engine/parser/SafeValues.cs @@ -530,10 +530,10 @@ public object VisitIndexExpression(IndexExpressionAst indexExpressionAst) // Get the value of the index and value and call the compiler var index = indexExpressionAst.Index.Accept(this); var target = indexExpressionAst.Target.Accept(this); - if (index == null || target == null) - { - throw new ArgumentNullException(nameof(indexExpressionAst)); - } + + ArgumentNullException.ThrowIfNull(index, nameof(indexExpressionAst)); + + ArgumentNullException.ThrowIfNull(target, nameof(indexExpressionAst)); return GetIndexedValueFromTarget(target, index); } diff --git a/src/System.Management.Automation/engine/remoting/commands/JobRepository.cs b/src/System.Management.Automation/engine/remoting/commands/JobRepository.cs index 7bb52abcb1e..29d107a074f 100644 --- a/src/System.Management.Automation/engine/remoting/commands/JobRepository.cs +++ b/src/System.Management.Automation/engine/remoting/commands/JobRepository.cs @@ -19,10 +19,7 @@ public abstract class Repository where T : class /// Object to add. public void Add(T item) { - if (item == null) - { - throw new ArgumentNullException(_identifier); - } + ArgumentNullException.ThrowIfNull(item, _identifier); lock (_syncObject) { @@ -45,10 +42,7 @@ public void Add(T item) /// Object to remove. public void Remove(T item) { - if (item == null) - { - throw new ArgumentNullException(_identifier); - } + ArgumentNullException.ThrowIfNull(item, _identifier); lock (_syncObject) { diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index 7edf50b5141..0ffc79ff6c4 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -7884,7 +7884,6 @@ internal static bool CreateJunction(string path, string target) { throw new ArgumentNullException(nameof(target)); } - using (SafeHandle handle = WinOpenReparsePoint(path, FileAccess.Write)) { byte[] mountPointBytes = Encoding.Unicode.GetBytes(NonInterpretedPathPrefix + Path.GetFullPath(target)); diff --git a/src/System.Management.Automation/namespaces/TransactedRegistryKey.cs b/src/System.Management.Automation/namespaces/TransactedRegistryKey.cs index 10826d25b21..32fce575a1b 100644 --- a/src/System.Management.Automation/namespaces/TransactedRegistryKey.cs +++ b/src/System.Management.Automation/namespaces/TransactedRegistryKey.cs @@ -1388,8 +1388,7 @@ public void SetValue(string name, object value) [ComVisible(false)] public unsafe void SetValue(string name, object value, RegistryValueKind valueKind) { - if (value == null) - throw new ArgumentNullException(RegistryProviderStrings.Arg_Value); + ArgumentNullException.ThrowIfNull(value, RegistryProviderStrings.Arg_Value); if (name != null && name.Length > MaxValueNameLength) { @@ -2031,10 +2030,7 @@ private RegistryKeyPermissionCheck GetSubKeyPermissionCheck(bool subkeyWritable) private static void ValidateKeyName(string name) { - if (name == null) - { - throw new ArgumentNullException(RegistryProviderStrings.Arg_Name); - } + ArgumentNullException.ThrowIfNull(name, RegistryProviderStrings.Arg_Name); int nextSlash = name.IndexOf('\\'); int current = 0; diff --git a/src/System.Management.Automation/utils/BackgroundDispatcher.cs b/src/System.Management.Automation/utils/BackgroundDispatcher.cs index 8ef105ce0ea..ac74a32d352 100644 --- a/src/System.Management.Automation/utils/BackgroundDispatcher.cs +++ b/src/System.Management.Automation/utils/BackgroundDispatcher.cs @@ -70,7 +70,8 @@ public BackgroundDispatcher(EventProvider transferProvider, EventDescriptor tran // internal for unit testing only. Otherwise, would be private. internal BackgroundDispatcher(IMethodInvoker etwActivityMethodInvoker) { - _etwActivityMethodInvoker = etwActivityMethodInvoker ?? throw new ArgumentNullException(nameof(etwActivityMethodInvoker)); + ArgumentNullException.ThrowIfNull(etwActivityMethodInvoker); + _etwActivityMethodInvoker = etwActivityMethodInvoker; _invokerWaitCallback = DoInvoker; } diff --git a/src/System.Management.Automation/utils/ParserException.cs b/src/System.Management.Automation/utils/ParserException.cs index 4c953be0276..b7056108218 100644 --- a/src/System.Management.Automation/utils/ParserException.cs +++ b/src/System.Management.Automation/utils/ParserException.cs @@ -131,7 +131,9 @@ public ParseException(string message, Justification = "ErrorRecord is not overridden in classes deriving from ParseException")] public ParseException(Language.ParseError[] errors) { - if ((errors == null) || (errors.Length == 0)) + ArgumentNullException.ThrowIfNull(errors); + + if (errors.Length == 0) { throw new ArgumentNullException(nameof(errors)); } diff --git a/src/System.Management.Automation/utils/perfCounters/CounterSetRegistrarBase.cs b/src/System.Management.Automation/utils/perfCounters/CounterSetRegistrarBase.cs index 917e04a5e69..33e03e67a47 100644 --- a/src/System.Management.Automation/utils/perfCounters/CounterSetRegistrarBase.cs +++ b/src/System.Management.Automation/utils/perfCounters/CounterSetRegistrarBase.cs @@ -107,8 +107,10 @@ protected CounterSetRegistrarBase( CounterSetId = counterSetId; CounterSetInstType = counterSetInstType; CounterSetName = counterSetName; - if ((counterInfoArray == null) - || (counterInfoArray.Length == 0)) + + ArgumentNullException.ThrowIfNull(counterInfoArray); + + if (counterInfoArray.Length == 0) { throw new ArgumentNullException(nameof(counterInfoArray)); } From b11554121e637c748ae7155e01d891a9b6a30596 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Fri, 16 Dec 2022 11:27:50 -0800 Subject: [PATCH 266/779] Update the cgmanifest (#18676) --- tools/cgmanifest.json | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/tools/cgmanifest.json b/tools/cgmanifest.json index deb58e7cfa4..ce5b8f243a1 100644 --- a/tools/cgmanifest.json +++ b/tools/cgmanifest.json @@ -66,7 +66,7 @@ "Type": "nuget", "Nuget": { "Name": "Microsoft.CodeAnalysis.Common", - "Version": "4.3.1" + "Version": "4.4.0" } }, "DevelopmentDependency": false @@ -76,7 +76,7 @@ "Type": "nuget", "Nuget": { "Name": "Microsoft.CodeAnalysis.CSharp", - "Version": "4.3.1" + "Version": "4.4.0" } }, "DevelopmentDependency": false @@ -86,7 +86,7 @@ "Type": "nuget", "Nuget": { "Name": "Microsoft.CodeAnalysis.NetAnalyzers", - "Version": "6.0.0" + "Version": "7.0.0" } }, "DevelopmentDependency": true @@ -106,7 +106,7 @@ "Type": "nuget", "Nuget": { "Name": "Microsoft.Extensions.ObjectPool", - "Version": "7.0.0" + "Version": "7.0.1" } }, "DevelopmentDependency": false @@ -176,7 +176,7 @@ "Type": "nuget", "Nuget": { "Name": "Microsoft.PowerShell.Native", - "Version": "7.3.0" + "Version": "7.3.1" } }, "DevelopmentDependency": false @@ -246,7 +246,7 @@ "Type": "nuget", "Nuget": { "Name": "Newtonsoft.Json", - "Version": "13.0.1" + "Version": "13.0.2" } }, "DevelopmentDependency": false From bbb03f350bb9bdc77da9a4ad724e53b13b169317 Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Mon, 19 Dec 2022 15:02:13 -0800 Subject: [PATCH 267/779] Fix reference assembly generation logic for `Microsoft.PowerShell.Commands.Utility` (#18818) --- .vsts-ci/windows/templates/windows-packaging.yml | 8 ++++++++ tools/packaging/packaging.psm1 | 3 ++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/.vsts-ci/windows/templates/windows-packaging.yml b/.vsts-ci/windows/templates/windows-packaging.yml index 832fe73af5e..90655ee6298 100644 --- a/.vsts-ci/windows/templates/windows-packaging.yml +++ b/.vsts-ci/windows/templates/windows-packaging.yml @@ -71,6 +71,14 @@ jobs: displayName: SBOM sourceScanPath: '$(repoPath)\tools' + # This is needed as SBOM task removed the installed .NET and installs .NET 3.1 + - pwsh: | + Import-Module .\tools\ci.psm1 + Invoke-CIInstall -SkipUser + displayName: Bootstrap + condition: succeeded() + workingDirectory: $(repoPath) + - pwsh: | Import-Module .\tools\ci.psm1 New-CodeCoverageAndTestPackage diff --git a/tools/packaging/packaging.psm1 b/tools/packaging/packaging.psm1 index 28cb7bae632..daa493f19eb 100644 --- a/tools/packaging/packaging.psm1 +++ b/tools/packaging/packaging.psm1 @@ -2574,7 +2574,8 @@ function CleanupGeneratedSourceCode '[Microsoft.PowerShell.Commands.HttpVersionCompletionsAttribute]' '[System.Management.Automation.ArgumentToVersionTransformationAttribute]' '[Microsoft.PowerShell.Commands.InvokeCommandCommand.ArgumentToPSVersionTransformationAttribute]' - '[Microsoft.PowerShell.Commands.InvokeCommandCommand.ValidateVersionAttribute]' + '[Microsoft.PowerShell.Commands.InvokeCommandCommand.ValidateVersionAttribute]', + '[System.Management.Automation.OutputTypeAttribute(new System.Type[]{ typeof(Microsoft.PowerShell.Commands.Internal.Format.FormatStartData), typeof(Microsoft.PowerShell.Commands.Internal.Format.FormatEntryData), typeof(Microsoft.PowerShell.Commands.Internal.Format.FormatEndData), typeof(Microsoft.PowerShell.Commands.Internal.Format.GroupStartData), typeof(Microsoft.PowerShell.Commands.Internal.Format.GroupEndData)})]' ) $patternsToReplace = @( From 9a7db33ee079b1281ea14d4eec8b81cfcec9ac31 Mon Sep 17 00:00:00 2001 From: MartinGC94 <42123497+MartinGC94@users.noreply.github.com> Date: Tue, 20 Dec 2022 09:26:43 +0100 Subject: [PATCH 268/779] Add completion for Using keywords (#16514) --- .../CommandCompletion/CompletionAnalysis.cs | 95 ++++++++++++++++++- .../resources/TabCompletionStrings.resx | 24 +++++ .../TabCompletion/TabCompletion.Tests.ps1 | 16 +++- 3 files changed, 133 insertions(+), 2 deletions(-) diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs index c73f6e64106..cc7ba18284a 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs @@ -423,6 +423,12 @@ internal List GetResultHelper(CompletionContext completionCont case TokenKind.Identifier: if (!tokenAtCursor.TokenFlags.HasFlag(TokenFlags.TypeName)) { + result = CompleteUsingKeywords(completionContext.CursorPosition.Offset, _tokens, ref replacementIndex, ref replacementLength); + if (result is not null) + { + return result; + } + result = GetResultForIdentifier(completionContext, ref replacementIndex, ref replacementLength, isQuotedString); } @@ -774,6 +780,12 @@ internal List GetResultHelper(CompletionContext completionCont } break; default: + result = CompleteUsingKeywords(completionContext.CursorPosition.Offset, _tokens, ref replacementIndex, ref replacementLength); + if (result is not null) + { + return result; + } + if ((tokenAtCursor.TokenFlags & TokenFlags.Keyword) != 0) { completionContext.WordToComplete = tokenAtCursor.Text; @@ -998,6 +1010,7 @@ internal List GetResultHelper(CompletionContext completionCont result = GetResultForEnumPropertyValueOfDSCResource(completionContext, string.Empty, ref replacementIndex, ref replacementLength, out _); break; } + case TokenKind.Break: case TokenKind.Continue: { @@ -1008,6 +1021,10 @@ internal List GetResultHelper(CompletionContext completionCont } break; } + + case TokenKind.Using: + return CompleteUsingKeywords(completionContext.CursorPosition.Offset, _tokens, ref replacementIndex, ref replacementLength); + case TokenKind.Dot: case TokenKind.ColonColon: case TokenKind.QuestionDot: @@ -1956,10 +1973,10 @@ private static List GetResultForIdentifierInConfiguration( private static List GetResultForIdentifier(CompletionContext completionContext, ref int replacementIndex, ref int replacementLength, bool isQuotedString) { + List result = null; var tokenAtCursor = completionContext.TokenAtCursor; var lastAst = completionContext.RelatedAsts.Last(); - List result = null; var tokenAtCursorText = tokenAtCursor.Text; completionContext.WordToComplete = tokenAtCursorText; @@ -2487,5 +2504,81 @@ private static List CompleteLoopLabel(CompletionContext comple return result; } + + private static List CompleteUsingKeywords(int cursorOffset, Token[] tokens, ref int replacementIndex, ref int replacementLength) + { + var result = new List(); + Token tokenBeforeCursor = null; + Token tokenAtCursor = null; + + for (int i = tokens.Length - 1; i >= 0; i--) + { + if (tokens[i].Extent.EndOffset < cursorOffset && tokens[i].Kind != TokenKind.LineContinuation) + { + tokenBeforeCursor = tokens[i]; + break; + } + else if (tokens[i].Extent.StartOffset <= cursorOffset && tokens[i].Extent.EndOffset >= cursorOffset && tokens[i].Kind != TokenKind.LineContinuation) + { + tokenAtCursor = tokens[i]; + } + } + + if (tokenBeforeCursor is not null && tokenBeforeCursor.Kind == TokenKind.Using) + { + string wordToComplete = null; + if (tokenAtCursor is not null) + { + replacementIndex = tokenAtCursor.Extent.StartOffset; + replacementLength = tokenAtCursor.Extent.Text.Length; + wordToComplete = tokenAtCursor.Text; + } + else + { + replacementIndex = cursorOffset; + replacementLength = 0; + } + + foreach (var keyword in s_usingKeywords) + { + if (string.IsNullOrEmpty(wordToComplete) || keyword.StartsWith(wordToComplete, StringComparison.OrdinalIgnoreCase)) + { + result.Add(new CompletionResult(keyword, keyword, CompletionResultType.Keyword, GetUsingKeywordToolTip(keyword))); + } + } + } + + if (result.Count > 0) + { + return result; + } + + return null; + } + + private static string GetUsingKeywordToolTip(string keyword) + { + switch (keyword) + { + case "assembly": + return TabCompletionStrings.AssemblyKeywordDescription; + case "module": + return TabCompletionStrings.ModuleKeywordDescription; + case "namespace": + return TabCompletionStrings.NamespaceKeywordDescription; + case "type": + return TabCompletionStrings.TypeKeywordDescription; + default: + return null; + } + } + + private static readonly string[] s_usingKeywords = new string[] + { + "assembly", + "module", + "namespace", + "type" + }; } } diff --git a/src/System.Management.Automation/resources/TabCompletionStrings.resx b/src/System.Management.Automation/resources/TabCompletionStrings.resx index 33710a77176..26d4dc4e14e 100644 --- a/src/System.Management.Automation/resources/TabCompletionStrings.resx +++ b/src/System.Management.Automation/resources/TabCompletionStrings.resx @@ -329,4 +329,28 @@ Shift Right bit operator. Inserts zero in the left-most bit position. For signed values, sign bit is preserved. + + Specifies the path to a .NET assembly to load. + +using assembly <.NET-assembly-path> + + + Specifies a PowerShell module to load classes from. + +using module <ModuleName or Path> + +using module <ModuleSpecification hashtable> + + + Specifies a .NET namespace to resolve types from or a namespace alias. + +using namespace <.NET-namespace> + +using namespace <AliasName> = <.NET-namespace> + + + Specifies an alias for a .NET Type. + +using type <AliasName> = <.NET-type> + diff --git a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 index 528b81c23ac..a76013edb26 100644 --- a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 +++ b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 @@ -341,11 +341,25 @@ switch ($x) $res.CompletionMatches.Count | Should -BeGreaterThan 0 } - It 'Should complete keyword' -Skip { + It 'Should complete keyword with partial input' { $res = TabExpansion2 -inputScript 'using nam' -cursorColumn 'using nam'.Length $res.CompletionMatches[0].CompletionText | Should -BeExactly 'namespace' } + It 'Should complete keyword with no input' { + $res = TabExpansion2 -inputScript 'using ' -cursorColumn 'using '.Length + $res.CompletionMatches.CompletionText | Should -BeExactly 'assembly','module','namespace','type' + } + + It 'Should complete keyword with no input after line continuation' { + $InputScript = @' +using ` + +'@ + $res = TabExpansion2 -inputScript $InputScript -cursorColumn $InputScript.Length + $res.CompletionMatches.CompletionText | Should -BeExactly 'assembly','module','namespace','type' + } + It 'Should first suggest -Full and then -Functionality when using Get-Help -Fu' -Skip { $res = TabExpansion2 -inputScript 'Get-Help -Fu' -cursorColumn 'Get-Help -Fu'.Length $res.CompletionMatches[0].CompletionText | Should -BeExactly '-Full' From 8f7c980ca3304949863b84885bd2674bbfe14315 Mon Sep 17 00:00:00 2001 From: MartinGC94 <42123497+MartinGC94@users.noreply.github.com> Date: Tue, 20 Dec 2022 11:38:25 +0100 Subject: [PATCH 269/779] Fix type inference for all scope vars (#18758) --- .../engine/SpecialVariables.cs | 33 ++++++++++--------- .../engine/parser/TypeInferenceVisitor.cs | 19 ++++++++++- .../engine/Api/TypeInference.Tests.ps1 | 17 ++++++++++ 3 files changed, 52 insertions(+), 17 deletions(-) diff --git a/src/System.Management.Automation/engine/SpecialVariables.cs b/src/System.Management.Automation/engine/SpecialVariables.cs index d093cdbbb50..d1d90e3507c 100644 --- a/src/System.Management.Automation/engine/SpecialVariables.cs +++ b/src/System.Management.Automation/engine/SpecialVariables.cs @@ -2,6 +2,7 @@ // Licensed under the MIT License. using System.Collections.Generic; +using System.Management.Automation.Internal; namespace System.Management.Automation { @@ -357,22 +358,22 @@ internal static class SpecialVariables // see an assignment to any of these variables so that they get handled properly (either throwing an exception // because they are constant/readonly, or having the value persist in parent scopes where the allscope variable // also exists. - internal static readonly string[] AllScopeVariables = { - SpecialVariables.Question, - SpecialVariables.ExecutionContext, - SpecialVariables.False, - SpecialVariables.Home, - SpecialVariables.Host, - SpecialVariables.PID, - SpecialVariables.PSCulture, - SpecialVariables.PSHome, - SpecialVariables.PSUICulture, - SpecialVariables.PSVersionTable, - SpecialVariables.PSEdition, - SpecialVariables.ShellId, - SpecialVariables.True, - SpecialVariables.EnabledExperimentalFeatures, - }; + internal static readonly Dictionary AllScopeVariables = new(StringComparer.OrdinalIgnoreCase) { + { Question, typeof(bool) }, + { ExecutionContext, typeof(EngineIntrinsics) }, + { False, typeof(bool) }, + { Home, typeof(string) }, + { Host, typeof(object) }, + { PID, typeof(int) }, + { PSCulture, typeof(string) }, + { PSHome, typeof(string) }, + { PSUICulture, typeof(string) }, + { PSVersionTable, typeof(PSVersionHashTable) }, + { PSEdition, typeof(string) }, + { ShellId, typeof(string) }, + { True, typeof(bool) }, + { EnabledExperimentalFeatures, typeof(ReadOnlyBag) } + }; private static readonly HashSet s_classMethodsAccessibleVariables = new HashSet ( diff --git a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs index f21fb0f4f6d..206c0737c10 100644 --- a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs +++ b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs @@ -1846,7 +1846,7 @@ private void InferTypeFrom(VariableExpressionAst variableExpressionAst, List Date: Tue, 20 Dec 2022 15:04:37 -0800 Subject: [PATCH 270/779] Update `README.md` and `metadata.json` for `v7.4.0-preview.1` release (#18831) --- README.md | 28 ++++++++++++++-------------- tools/metadata.json | 4 ++-- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index 1da7248e30e..ba40324d7b7 100644 --- a/README.md +++ b/README.md @@ -93,20 +93,20 @@ You can also download the PowerShell binary archives for Windows, macOS and Linu [rl-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.1/powershell-7.3.1-linux-arm64.tar.gz [rl-snap]: https://snapcraft.io/powershell -[pv-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-rc.1/PowerShell-7.3.0-rc.1-win-x64.msi -[pv-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-rc.1/PowerShell-7.3.0-rc.1-win-x86.msi -[pv-deb]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-rc.1/powershell-preview_7.3.0-rc.1-1.deb_amd64.deb -[pv-rpm]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-rc.1/powershell-preview-7.3.0_rc.1-1.rh.x86_64.rpm -[pv-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-rc.1/powershell-7.3.0-rc.1-osx-x64.pkg -[pv-macos-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-rc.1/powershell-7.3.0-rc.1-osx-arm64.pkg -[pv-winarm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-rc.1/PowerShell-7.3.0-rc.1-win-arm64.zip -[pv-winx86-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-rc.1/PowerShell-7.3.0-rc.1-win-x86.zip -[pv-winx64-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-rc.1/PowerShell-7.3.0-rc.1-win-x64.zip -[pv-macos-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-rc.1/powershell-7.3.0-rc.1-osx-x64.tar.gz -[pv-macos-tar-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-rc.1/powershell-7.3.0-rc.1-osx-arm64.tar.gz -[pv-linux-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-rc.1/powershell-7.3.0-rc.1-linux-x64.tar.gz -[pv-arm32]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-rc.1/powershell-7.3.0-rc.1-linux-arm32.tar.gz -[pv-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.0-rc.1/powershell-7.3.0-rc.1-linux-arm64.tar.gz +[pv-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.1/PowerShell-7.4.0-preview.1-win-x64.msi +[pv-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.1/PowerShell-7.4.0-preview.1-win-x86.msi +[pv-deb]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.1/powershell-preview_7.4.0-preview.1-1.deb_amd64.deb +[pv-rpm]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.1/powershell-preview-7.4.0_preview.1-1.rh.x86_64.rpm +[pv-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.1/powershell-7.4.0-preview.1-osx-x64.pkg +[pv-macos-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.1/powershell-7.4.0-preview.1-osx-arm64.pkg +[pv-winarm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.1/PowerShell-7.4.0-preview.1-win-arm64.zip +[pv-winx86-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.1/PowerShell-7.4.0-preview.1-win-x86.zip +[pv-winx64-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.1/PowerShell-7.4.0-preview.1-win-x64.zip +[pv-macos-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.1/powershell-7.4.0-preview.1-osx-x64.tar.gz +[pv-macos-tar-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.1/powershell-7.4.0-preview.1-osx-arm64.tar.gz +[pv-linux-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.1/powershell-7.4.0-preview.1-linux-x64.tar.gz +[pv-arm32]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.1/powershell-7.4.0-preview.1-linux-arm32.tar.gz +[pv-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.1/powershell-7.4.0-preview.1-linux-arm64.tar.gz [pv-snap]: https://snapcraft.io/powershell-preview [in-windows]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-windows diff --git a/tools/metadata.json b/tools/metadata.json index 23698dda348..31599f72322 100644 --- a/tools/metadata.json +++ b/tools/metadata.json @@ -1,10 +1,10 @@ { "StableReleaseTag": "v7.3.1", - "PreviewReleaseTag": "v7.3.0-rc.1", + "PreviewReleaseTag": "v7.4.0-preview.1", "ServicingReleaseTag": "v7.0.13", "ReleaseTag": "v7.3.1", "LTSReleaseTag" : ["v7.2.8", "v7.0.13"], - "NextReleaseTag": "v7.4.0-preview.1", + "NextReleaseTag": "v7.4.0-preview.2", "LTSRelease": { "Latest": false, "Package": false }, "StableRelease": { "Latest": false, "Package": false } } From 025b58cb39297679f3586082534a46da9e4448fd Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Tue, 20 Dec 2022 16:39:03 -0800 Subject: [PATCH 271/779] Change log for v7.4.0-preview.1 release (#18835) Change log for v7.4.0-preview.1 release --- .spelling | 69 ++++++++++ CHANGELOG/preview.md | 291 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 360 insertions(+) diff --git a/.spelling b/.spelling index b776bf0f562..3afd5ed7ada 100644 --- a/.spelling +++ b/.spelling @@ -14,6 +14,7 @@ 32-bit 4.final 64-bit +AAATechGuy about_ about_debuggers about_jobs @@ -60,14 +61,17 @@ appimage applocker appveyor appx +ArchitectureSensitiveAttribute args argumentlist arm32 arm64 asp.net +ast.cs assemblyloadcontext AssemblyInfo assessibility +AtariDreams authenticode authenticodesignature azdevops @@ -109,10 +113,12 @@ build.psm1 bulid buildInfoJson callmejoebob +CarloToso catchable cdxml celsius CentOS +CimDscParser codeql-action CGManifest cgmanifest.json @@ -131,6 +137,7 @@ chibi childitem ChuckieChen945 ChrisLGardner +chrullrich cimsession cimsupport ci.psm1 @@ -158,6 +165,7 @@ CommandSearcher comobject Compiler.cs composability +computerinfo ComRuntimeHelpers.cs config connect-pssession @@ -186,6 +194,8 @@ CorePsAssemblyLoadContext.cs coveralls.exe coveralls.io. coveralls.net +CreateFile +CreateFileW credssp cron crontab @@ -203,6 +213,7 @@ DarylGraves darquewarrior darwinjs DateTime +DateTime.UnixEpoch daxian-dbw dayofweek dchristian3188 @@ -240,6 +251,7 @@ distro distros dkaszews dll +DllImport dlls dlwyatt dockerbasedbuild @@ -302,6 +314,7 @@ felixfbecker ffeldhaus ffi fflaten +File.OpenHandle filecatalog filename filesystem @@ -372,6 +385,7 @@ GetExceptionForHR getparentprocess gettype Geweldig +GigaScratch gitcommitid github githug @@ -383,6 +397,7 @@ GoogleTest GUIs gzip hackathons +HashData HashSet hashtable hashtables @@ -423,6 +438,7 @@ includeide includeusername informationrecord initializers +InitialSessionState.cs install-packageprovider IntelliSense interactivetesting @@ -433,6 +449,7 @@ invoke-cimmethod Invoke-DSCResource invoke-restmethod invoke-wsmanaction +InvokeRestMethodCommand.Common iot isazonov iscore @@ -452,6 +469,7 @@ joandrsn joeltankam joeyaiello jokajak +JohnLBevan joshuacooper journalctl jpsnover @@ -489,6 +507,7 @@ lee303 Leonhardt Libera.Chat libicu +LibraryImport libpsl libpsl-native libunwind8 @@ -588,6 +607,7 @@ NameObscurerTelemetryInitializer namespace nano nanoserver +NativeCultureResolver nativeexecution net5.0 netcoreapp5.0 @@ -672,6 +692,8 @@ perfview perfview.exe peter-evans petseral +pinvoke +pinvokes plaintext pluggable pluralsight @@ -697,6 +719,7 @@ powershellproperties ppadmavilasom pre-build pre-compiled +pre-defined pre-generated pre-installed pre-parse @@ -773,6 +796,7 @@ pwsh.deps.json qmfrederik raghav710 RandomNoun7 +RandomNumberGenerator.Fill raspbian rc rc.1 @@ -806,6 +830,7 @@ register-packagesource register-psrepository registryprovider relationlink +RemoteSessionNamedPipe remotesigned remoting remove-ciminstance @@ -852,6 +877,7 @@ runtimes Ryan-Hutchison-USAF SA1026CodeMustNotContainSpaceAfterNewKeywordInImplicitlyTypedArrayAllocation Saancreed +SafeRegistryHandle sample-dotnet1 sample-dotnet2 sarithsutha @@ -988,8 +1014,10 @@ toolset tracesource travisez13 travisty +trossr32 truher TSAUpload +turbedi TValue tylerleonhardt typecataloggen @@ -1015,6 +1043,7 @@ update-modulemanifest update-scriptfileinfo update-typedata uri +urizen-source urls userdata uservoice @@ -1057,7 +1086,10 @@ v7.1.0 v7.1.6 v7.1.7 v7.2.2 +v7.2.6 v7.3.0 +v7.4.0 +v7.0.12 v7.0.13 validatenotnullorempty ValidateSet @@ -1077,6 +1109,8 @@ walkthrough webcmdlets weblistener webrequest +webrequestpscmdlet.common.cs +webresponseobject.common weltner wesholton84 wget @@ -1093,6 +1127,9 @@ windowspsmodulepath windowsversion winrm wix +wmentha +WNetGetConnection +WNetAddConnection2 worrenb wpr wprui.exe @@ -1282,6 +1319,7 @@ weltkante kilasuit tnieto88 Orca88 +OrderBy centreboard romero126 Greg-Smulko @@ -1311,7 +1349,9 @@ Francisco-Gamino adamdriscoll analytics deserialized +string.Join string.Split +StringSplitOptions.TrimEntries Dictionary.TryAdd Environment.NewLine ParseError.ToString @@ -1334,6 +1374,35 @@ SetVersionVariables yml DateTime DeploymentScripts +GetValues +GetNames +SessionStateStrings +Enum.HasFlags +ConsoleInfoErrorStrings.resx +ContentHelper.Common.cs +FusionAssemblyIdentity +GlobalAssemblyCache +StringManipulationHelper +testexe.exe +echocmdline +MemoryExtensions.IndexOfAny +PSv2CompletionCompleter +RemoteRunspacePoolInternal.cs +PSVersionInfo +WildcardPattern +UTF8Encoding +PowerShell.Core.Instrumentation.man +Encoding.Default +WinTrust +System.Runtime.CompilerServices.Unsafe +azCopy +APISets +ApiScan +System.Data.SqlClient +minimatch +2.final +SessionStateInternal +Microsoft.PowerShell.SDK Markdig.Signed - docs/debugging/README.md corehost diff --git a/CHANGELOG/preview.md b/CHANGELOG/preview.md index 035db721385..8cd84ae8158 100644 --- a/CHANGELOG/preview.md +++ b/CHANGELOG/preview.md @@ -1 +1,292 @@ # Current preview release + +## [7.4.0-preview.1] - 2022-12-20 + +### Engine Updates and Fixes + +- Add Instrumentation to `AmsiUtil` and make the init variable readonly (#18727) +- Fix typo in `OutOfProcTransportManager.cs` (#18766) (Thanks @eltociear!) +- Allow non-default encodings to be used in user's script/code (#18605) +- Add `Dim` and `DimOff` to `$PSStyle` (#18653) +- Change `exec` from alias to function to handle arbitrary arguments (#18567) +- The command prefix should also be in the error color for `NormalView` (#18555) +- Skip cloud files marked as "not on disk" during command discovery (#18152) +- Replace `UTF8Encoding(false)` with `Encoding.Default` (#18356) (Thanks @xtqqczze!) +- Fix `Switch-Process` to set `termios` appropriate for child process (#18467) +- On Unix, only explicitly terminate the native process if not in background (#18215) +- Treat `[NullString]::Value` as the string type when resolving methods (#18080) +- Improve pseudo binding for dynamic parameters (#18030) (Thanks @MartinGC94!) +- Make experimental feature `PSAnsiRenderingFileInfo` stable (#18042) +- Update to use version `2.21.0` of Application Insights. (#17903) +- Do not preserve temporary results when no need to do so (#17856) + +### Performance + +- Remove some static constants from `Utils.Separators` (#18154) (Thanks @iSazonov!) +- Avoid using regex when unnecessary in `ScriptWriter` (#18348) +- Use source generator for `PSVersionInfo` to improve startup time (#15603) (Thanks @iSazonov!) +- Skip evaluating suggestions at startup (#18232) +- Avoid using `Regex` when not necessary (#18210) + +### General Cmdlet Updates and Fixes + +- Update to use `ComputeCore.dll` for PowerShell Direct (#18194) +- Replace `ArgumentNullException(nameof())` with `ArgumentNullException.ThrowIfNull()` (#18792)(#18784) (Thanks @CarloToso!) +- Remove `TabExpansion` from remote session configuration (#18795) (Internal 23331) +- WebCmdlets get Retry-After from headers if status code is 429 (#18717) (Thanks @CarloToso!) +- Implement `SupportsShouldProcess` in `Stop-Transcript` (#18731) (Thanks @JohnLBevan!) +- Fix `New-Item -ItemType Hardlink` to resolve target to absolute path and not allow link to itself (#18634) +- Add output types to Format commands (#18746) (Thanks @MartinGC94!) +- Fix the process `CommandLine` on Linux (#18710) (Thanks @jborean93!) +- Fix `SuspiciousContentChecker.Match` to detect a pre-defined string when the text starts with it (#18693) +- Switch `$PSNativeCommandUseErrorActionPreference` to `$true` when feature is enabled (#18695) +- Fix `Start-Job` to check the existence of working directory using the PowerShell way (#18675) +- Webcmdlets add 308 to redirect codes and small cleanup (#18536) (Thanks @CarloToso!) +- Ensure `HelpInfo.Category` is consistently a string (#18254) +- Remove `gcloud` from the legacy list because it's resolved to a .ps1 script (#18575) +- Add `gcloud` and `sqlcmd` to list to use legacy argument passing (#18559) +- Fix native access violation (#18545) (#18547) (Thanks @chrullrich!) +- Fix issue when completing the first command in a script with an empty array expression (#18355) (Thanks @MartinGC94!) +- Improve type inference of hashtable keys (#17907) (Thanks @MartinGC94!) +- Fix `Switch-Process` to copy the current env to the new process (#18452) +- Fix `Switch-Process` error to include the command that is not found (#18443) +- Update `Out-Printer` to remove all decorating ANSI escape sequences from PowerShell formatting (#18425) +- Web cmdlets set default charset encoding to `UTF8` (#18219) (Thanks @CarloToso!) +- Fix incorrect cmdlet name in the script used by `Restart-Computer` (#18374) (Thanks @urizen-source!) +- Add the function `cd~` (#18308) (Thanks @GigaScratch!) +- Fix type inference error for empty return statements (#18351) (Thanks @MartinGC94!) +- Fix the exception reporting in `ConvertFrom-StringData` (#18336) (Thanks @GigaScratch!) +- Implement `IDisposable` in `NamedPipeClient` (#18341) (Thanks @xtqqczze!) +- Replace command-error suggestion with new implementation based on subsystem plugin (#18252) +- Remove the `ProcessorArchitecture` portion from the full name as it's obsolete (#18320) +- Make the fuzzy searching flexible by passing in the fuzzy matcher (#18270) +- Add `-FuzzyMinimumDistance` parameter to `Get-Command` (#18261) +- Improve startup time by triggering initialization of additional types on background thread (#18195) +- Fix decompression in web cmdlets (#17955) (Thanks @iSazonov!) +- Add `CustomTableHeaderLabel` formatting to differentiate table header labels that are not property names (#17346) +- Remove the extra new line form List formatting (#18185) +- Minor update to the `FileInfo` table formatting on Unix to make it more concise (#18183) +- Fix Parent property on processes with complex name (#17545) (Thanks @jborean93!) +- Make PowerShell class not affiliate with `Runspace` when declaring the `NoRunspaceAffinity` attribute (#18138) +- Complete the progress bar rendering in `Invoke-WebRequest` when downloading is complete or cancelled (#18130) +- Display download progress in human readable format for `Invoke-WebRequest` (#14611) (Thanks @bergmeister!) +- Update `WriteConsole` to not use `stackalloc` for buffer with too large size (#18084) +- Filter out compiler generated types for `Add-Type -PassThru` (#18095) +- Fixing `CA2014` warnings and removing the warning suppression (#17982) (Thanks @creative-cloud!) +- Make experimental feature `PSNativeCommandArgumentPassing` stable (#18044) +- Make experimental feature `PSAMSIMethodInvocationLogging` stable (#18041) +- Handle `PSObject` argument specially in method invocation logging (#18060) +- Fix typos in `EventResource.resx` (#18063) (Thanks @eltociear!) +- Make experimental feature `PSRemotingSSHTransportErrorHandling` stable (#18046) +- Make experimental feature `PSExec` stable (#18045) +- Make experimental feature `PSCleanBlock` stable (#18043) +- Fix error formatting to use color defined in `$PSStyle.Formatting` (#17987) +- Remove unneeded use of `chmod 777` (#17974) +- Support mapping foreground/background `ConsoleColor` values to VT escape sequences (#17938) +- Make `pwsh` server modes implicitly not show banner (#17921) +- Add output type attributes for `Get-WinEvent` (#17948) (Thanks @MartinGC94!) +- Remove 1 second minimum delay in `Invoke-WebRequest` for small files, and prevent file-download-error suppression. (#17896) (Thanks @AAATechGuy!) +- Add completion for values in comparisons when comparing Enums (#17654) (Thanks @MartinGC94!) +- Fix positional argument completion (#17796) (Thanks @MartinGC94!) +- Fix member completion in attribute argument (#17902) (Thanks @MartinGC94!) +- Throw when too many parameter sets are defined (#17881) (Thanks @fflaten!) +- Limit searching of `charset` attribute in `meta` tag for HTML to first 1024 characters in webcmdlets (#17813) +- Fix `Update-Help` failing silently with implicit non-US culture. (#17780) (Thanks @dkaszews!) +- Add the `ValidateNotNullOrWhiteSpace` attribute (#17191) (Thanks @wmentha!) +- Improve enumeration of inferred types in pipeline (#17799) (Thanks @MartinGC94!) + +### Code Cleanup + +
+ + + +

We thank the following contributors!

+

@MartinGC94, @CarloToso, @iSazonov, @xtqqczze, @turbedi, @trossr32, @eltociear, @AtariDreams, @jborean93

+ +
+ +
    +
  • Add TSAUpload for APIScan (#18446)
  • +
  • Use Pattern matching in ast.cs (#18794) (Thanks @MartinGC94!)
  • +
  • Cleanup webrequestpscmdlet.common.cs (#18596) (Thanks @CarloToso!)
  • +
  • Unify CreateFile pinvoke in SMA (#18751) (Thanks @iSazonov!)
  • +
  • Cleanup webresponseobject.common (#18785) (Thanks @CarloToso!)
  • +
  • InvokeRestMethodCommand.Common cleanup and merge partials (#18736) (Thanks @CarloToso!)
  • +
  • Replace GetDirectories in CimDscParser (#14319) (Thanks @xtqqczze!)
  • +
  • WebResponseObject.Common merge partials atomic commits (#18703) (Thanks @CarloToso!)
  • +
  • Enable pending test for Start-Process (#18724) (Thanks @iSazonov!)
  • +
  • Remove one CreateFileW (#18732) (Thanks @iSazonov!)
  • +
  • Replace DllImport with LibraryImport for WNetAddConnection2 (#18721) (Thanks @iSazonov!)
  • +
  • Use File.OpenHandle() instead CreateFileW pinvoke (#18722) (Thanks @iSazonov!)
  • +
  • Replace DllImport with LibraryImport for WNetGetConnection (#18690) (Thanks @iSazonov!)
  • +
  • Replace DllImport with LibraryImport - 1 (#18603) (Thanks @iSazonov!)
  • +
  • Replace DllImport with LibraryImport in SMA 3 (#18564) (Thanks @iSazonov!)
  • +
  • Replace DllImport with LibraryImport in SMA - 7 (#18594) (Thanks @iSazonov!)
  • +
  • Use static DateTime.UnixEpoch and RandomNumberGenerator.Fill() (#18621) (Thanks @turbedi!)
  • +
  • Rewrite Get-FileHash to use static HashData methods (#18471) (Thanks @turbedi!)
  • +
  • Replace DllImport with LibraryImport in SMA 8 (#18599) (Thanks @iSazonov!)
  • +
  • Replace DllImport with LibraryImport in SMA 4 (#18579) (Thanks @iSazonov!)
  • +
  • Remove NativeCultureResolver as dead code (#18582) (Thanks @iSazonov!)
  • +
  • Replace DllImport with LibraryImport in SMA 6 (#18581) (Thanks @iSazonov!)
  • +
  • Replace DllImport with LibraryImport in SMA 2 (#18543) (Thanks @iSazonov!)
  • +
  • Use standard SBCS detection (#18593) (Thanks @iSazonov!)
  • +
  • Remove unused pinvokes in RemoteSessionNamedPipe (#18583) (Thanks @iSazonov!)
  • +
  • Replace DllImport with LibraryImport in SMA 5 (#18580) (Thanks @iSazonov!)
  • +
  • Remove SafeRegistryHandle (#18597) (Thanks @iSazonov!)
  • +
  • Remove ArchitectureSensitiveAttribute from the code base (#18598) (Thanks @iSazonov!)
  • +
  • Build COM adapter only on Windows (#18590)
  • +
  • Include timer instantiation for legacy telemetry in conditional compiler statements in Get-Help (#18475) (Thanks @trossr32!)
  • +
  • Convert DllImport to LibraryImport for recycle bin, clipboard, and computerinfo cmdlets (#18526)
  • +
  • Replace DllImport with LibraryImport in SMA 1 (#18520) (Thanks @iSazonov!)
  • +
  • Replace DllImport with LibraryImport in engine (#18496)
  • +
  • Fix typo in InitialSessionState.cs (#18435) (Thanks @eltociear!)
  • +
  • Remove remaining unused strings from resx files (#18448)
  • +
  • Use new LINQ Order() methods instead of OrderBy(static x => x) (#18395) (Thanks @turbedi!)
  • +
  • Make use of StringSplitOptions.TrimEntries when possible (#18412) (Thanks @turbedi!)
  • +
  • Replace some string.Join(string) calls with string.Join(char) (#18411) (Thanks @turbedi!)
  • +
  • Remove unused strings from FileSystem and Registry providers (#18403)
  • +
  • Use generic GetValues<T>, GetNames<T> enum methods (#18391) (Thanks @xtqqczze!)
  • +
  • Remove unused resource strings from SessionStateStrings (#18394)
  • +
  • Remove unused resource strings in System.Management.Automation (#18388)
  • +
  • Use Enum.HasFlags part 1 (#18386) (Thanks @xtqqczze!)
  • +
  • Remove unused strings from parser (#18383)
  • +
  • Remove unused strings from Utility module (#18370)
  • +
  • Remove unused console strings (#18369)
  • +
  • Remove unused strings from ConsoleInfoErrorStrings.resx (#18367)
  • +
  • Code cleanup in ContentHelper.Common.cs (#18288) (Thanks @CarloToso!)
  • +
  • Remove FusionAssemblyIdentity and GlobalAssemblyCache as they are not used (#18334) (Thanks @iSazonov!)
  • +
  • Remove some static initializations in StringManipulationHelper (#18243) (Thanks @xtqqczze!)
  • +
  • Use MemoryExtensions.IndexOfAny in PSv2CompletionCompleter (#18245) (Thanks @xtqqczze!)
  • +
  • Use MemoryExtensions.IndexOfAny in WildcardPattern (#18242) (Thanks @xtqqczze!)
  • +
  • Small cleanup of the stub code (#18301) (Thanks @CarloToso!)
  • +
  • Fix typo in RemoteRunspacePoolInternal.cs (#18263) (Thanks @eltociear!)
  • +
  • Some more code cleanup related to the use of PSVersionInfo (#18231)
  • +
  • Use MemoryExtensions.IndexOfAny in SessionStateInternal (#18244) (Thanks @xtqqczze!)
  • +
  • Use overload APIs that take char instead of string when it's possible (#18179) (Thanks @iSazonov!)
  • +
  • Replace UTF8Encoding(false) with Encoding.Default (#18144) (Thanks @xtqqczze!)
  • +
  • Remove unused variables (#18058) (Thanks @AtariDreams!)
  • +
  • Fix typo in PowerShell.Core.Instrumentation.man (#17963) (Thanks @eltociear!)
  • +
  • Migrate WinTrust functions to a common location (#17598) (Thanks @jborean93!)
  • +
+ +
+ +### Tools + +- Add a function to get the PR Back-port report (#18299) +- Add a workaround in automatic rebase workflow to continue on error (#18176) +- Update list of PowerShell team members in release tools (#17909) +- Don't block if we fail to create the comment (#17869) + +### Tests + +- Add `testexe.exe -echocmdline` to output raw command line received by the process on Windows (#18591) +- Mark charset test as pending (#18511) +- Skip output rendering tests on Windows Server 2012 R2 (#18382) +- Increase timeout to make subsystem tests more reliable (#18380) +- Add missing -Tag 'CI' to describe blocks. (#18316) +- Use short path instead of multiple quotes in `Get-Item` test relying on node (#18250) +- Replace the CIM class used for `-Amended` parameter test (#17884) (Thanks @sethvs!) +- Stop ongoing progress-bar in `Write-Progress` test (#17880) (Thanks @fflaten!) + +### Build and Packaging Improvements + +
+ + + +

We thank the following contributors!

+ +
+ +
    +
  • Fix reference assembly generation logic for Microsoft.PowerShell.Commands.Utility (#18818)
  • +
  • Update the cgmanifest (#18676)(#18521)(#18415)(#18408)(#18197)(#18111)(#18051)(#17913)(#17867)(#17934)(#18088)
  • +
  • Bump Microsoft.PowerShell.Native to the latest preview version v7.4.0-preview.1 (#18805)
  • +
  • Remove unnecessary reference to System.Runtime.CompilerServices.Unsafe (#18806)
  • +
  • Update the release tag in metadata.json for next preview (#18799)
  • +
  • Bump Microsoft.CodeAnalysis.NetAnalyzers (#18750)
  • +
  • Bump .NET SDK to version 7.0.101 (#18786)
  • +
  • Bump cirrus-actions/rebase from 1.7 to 1.8 (#18788)
  • +
  • Bump decode-uri-component from 0.2.0 to 0.2.2 (#18712)
  • +
  • Bump Microsoft.CodeAnalysis.CSharp from 4.4.0-4.final to 4.4.0 (#18562)
  • +
  • Bump Newtonsoft.Json from 13.0.1 to 13.0.2 (#18657)
  • +
  • Apply expected file permissions to Linux files after Authenticode signing (#18643)
  • +
  • Remove extra quotes after agent moves to pwsh 7.3 (#18577)
  • +
  • Don't install based on build-id for RPM (#18560)
  • +
  • Bump Microsoft.NET.Test.Sdk from 17.3.2 to 17.4.0 (#18487)
  • +
  • Bump minimatch from 3.0.4 to 3.1.2 (#18514)
  • +
  • Avoid depending on the pre-generated experimental feature list in private and CI builds (#18484)
  • +
  • Update release-MsixBundle.yml to add retries (#18465)
  • +
  • Bump System.Data.SqlClient from 4.8.4 to 4.8.5 in /src/Microsoft.PowerShell.SDK (#18515)
  • +
  • Bump to use internal .NET 7 GA build (#18508)
  • +
  • Insert the pre-release nuget feed before building test artifacts (#18507)
  • +
  • Add test for framework dependent package in release pipeline (#18506) (Internal 23139)
  • +
  • Update to azCopy 10 (#18509)
  • +
  • Fix issues with uploading changelog to GitHub release draft (#18504)
  • +
  • Bump Microsoft.CodeAnalysis.NetAnalyzers (#18442)
  • +
  • Add authenticode signing for assemblies on linux builds (#18440)
  • +
  • Do not remove penimc_cor3.dll from build (#18438)
  • +
  • Bump Microsoft.PowerShell.Native from 7.3.0-rc.1 to 7.3.0 (#18405)
  • +
  • Allow two-digit revisions in vPack package validation pattern (#18392)
  • +
  • Bump Microsoft.CodeAnalysis.NetAnalyzers (#18363)
  • +
  • Bump to .NET 7 RC2 official version (#18328)
  • +
  • Bump to .NET 7 to version 7.0.100-rc.2.22477.20 (#18286)
  • +
  • Replace win7 runtime with win8 and remove APISets (#18304)
  • +
  • Bump Microsoft.CodeAnalysis.NetAnalyzers (#18312)
  • +
  • Recurse the file listing. (#18277)
  • +
  • Create tasks to collect and publish hashes for build files. (#18276)
  • +
  • Bump Microsoft.CodeAnalysis.NetAnalyzers (#18262)
  • +
  • Remove ETW trace collection and uploading for CLR CAP (#18253)
  • +
  • Do not cleanup pwsh.deps.json for framework dependent packages (#18226)
  • +
  • Add branch counter to APIScan build (#18214)
  • +
  • Remove unnecessary native dependencies from the package (#18213)
  • +
  • Remove XML files for min-size package (#18189)
  • +
  • Bump Microsoft.CodeAnalysis.NetAnalyzers (#18216)
  • +
  • Bump Microsoft.PowerShell.Native from 7.3.0-preview.1 to 7.3.0-rc.1 (#18217)
  • +
  • Bump Microsoft.CodeAnalysis.NetAnalyzers (#18201)
  • +
  • Move ApiScan to compliance build (#18191)
  • +
  • Fix the verbose message when using dotnet-install.sh (#18184)
  • +
  • Bump Microsoft.NET.Test.Sdk from 17.3.1 to 17.3.2 (#18163)
  • +
  • Bump Microsoft.CodeAnalysis.NetAnalyzers (#18164)
  • +
  • Make the link to minimal package blob public during release (#18158)
  • +
  • Bump Microsoft.CodeAnalysis.NetAnalyzers (#18147)
  • +
  • Update MSI exit message (#18137)
  • +
  • Bump Microsoft.CodeAnalysis.CSharp from 4.4.0-1.final to 4.4.0-2.final (#18132)
  • +
  • Re-enable building with Ready-to-Run (#18105)
  • +
  • Update DotnetRuntimeMetadata.json for .NET 7 RC1 build (#18091)
  • +
  • Bump Microsoft.CodeAnalysis.NetAnalyzers (#18096)
  • +
  • Add schema for cgmanifest.json (#18036)
  • +
  • Bump Microsoft.CodeAnalysis.CSharp from 4.3.0-3.final to 4.3.0 (#18012)
  • +
  • Add XML reference documents to NuPkg files for SDK (#17997)
  • +
  • Bump Microsoft.NET.Test.Sdk from 17.3.0 to 17.3.1 (#18000)
  • +
  • Bump Microsoft.CodeAnalysis.NetAnalyzers (#17988)
  • +
  • Bump Microsoft.CodeAnalysis.NetAnalyzers (#17983)
  • +
  • Bump Microsoft.CodeAnalysis.NetAnalyzers (#17945)
  • +
  • Make sure Security.types.ps1xml gets signed in release build (#17916)
  • +
  • Make Register Microsoft Update timeout (#17910)
  • +
  • Merge changes from v7.0.12 v7.2.6 and v7.3.0-preview.7
  • +
  • Bump Microsoft.NET.Test.Sdk from 17.2.0 to 17.3.0 (#17871)
  • +
+ +
+ +### Documentation and Help Content + +- Update readme and metadata for releases (#18780)(#18493)(#18393)(#18332)(#18128)(#17870) +- Remove 'please' and 'Core' from README.md per MS style guide (#18578) (Thanks @Rick-Anderson!) +- Change unsupported XML documentation tag (#18608) +- Change public API mention of `monad` to PowerShell (#18491) +- Update security reporting policy to recommend security portal for more streamlined reporting (#18437) +- Change log for v7.3.0 (#18505) (Internal 23161) +- Replace `msh` in public API comment based documentation with PowerShell equivalent (#18483) +- Add missing XML doc elements for methods in `RunspaceFactory` (#18450) +- Change log for `v7.3.0-rc.1` (#18400) +- Update change logs for `v7.2.7` and `v7.0.13` (#18342) +- Update the change log for v7.3.0-preview.8 (#18136) +- Add the `ConfigurationFile` option to the PowerShell help content (#18093) +- Update help content about the PowerShell flag `-NonInteractive` (#17952) + +[7.4.0-preview.1]: https://github.com/PowerShell/PowerShell/compare/v7.3.0-preview.8...v7.4.0-preview.1 + From a581e36419d7862e853e31a6d691f6f4dde359a4 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Sat, 24 Dec 2022 14:09:26 +0100 Subject: [PATCH 272/779] Add StatusCode to HttpResponseException (#18842) --- .../utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index dbbe169ae3d..e82bd7e5772 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -816,7 +816,7 @@ public sealed class HttpResponseException : HttpRequestException /// /// Message for the exception. /// Response from the HTTP server. - public HttpResponseException(string message, HttpResponseMessage response) : base(message) + public HttpResponseException(string message, HttpResponseMessage response) : base(message, inner: null, response.StatusCode) { Response = response; } From f04940b76c648c60371b161626e18225d08ecdf6 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Fri, 30 Dec 2022 23:00:00 -0800 Subject: [PATCH 273/779] Fix `Format-Table -RepeatHeader` for property derived tables (#18870) --- .../FormatAndOutput/common/FormatViewGenerator_Table.cs | 1 + .../Microsoft.PowerShell.Utility/Format-Table.Tests.ps1 | 8 ++++++++ 2 files changed, 9 insertions(+) diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Table.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Table.cs index 7c661a5169a..c6fc9887c9a 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Table.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Table.cs @@ -223,6 +223,7 @@ private TableHeaderInfo GenerateTableHeaderInfoFromProperties(PSObject so) TableHeaderInfo thi = new TableHeaderInfo(); thi.hideHeader = this.HideHeaders; + thi.repeatHeader = this.RepeatHeader; for (int k = 0; k < this.activeAssociationList.Count; k++) { diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Format-Table.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Format-Table.Tests.ps1 index 6eb1e4fa3c9..f5bbae4b0b5 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Format-Table.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Format-Table.Tests.ps1 @@ -813,6 +813,14 @@ A Name B ($lines | Select-String "Name\s*Value").Count | Should -Be ($numHeaders + 1) } + It "-RepeatHeader should output the header at every screen full for custom table" -Skip:([Console]::WindowHeight -eq 0) { + $numHeaders = 4 + $numObjects = [Console]::WindowHeight * $numHeaders + $out = 1..$numObjects | ForEach-Object { [pscustomobject]@{foo=$_;bar=$_;hello=$_;world=$_} } | Format-Table -Property hello, world -RepeatHeader | Out-String + $lines = $out.Split([System.Environment]::NewLine) + ($lines | Select-String "Hello\s*World").Count | Should -Be ($numHeaders + 1) + } + It "Should be formatted correctly if width is declared and using center alignment" { $expectedTable = @" From 4f57804f468c5ad47001708014d8989eac3043bc Mon Sep 17 00:00:00 2001 From: "James Truher [MSFT]" Date: Tue, 3 Jan 2023 12:12:42 -0800 Subject: [PATCH 274/779] Fix up all comments to be in the proper order with proper spacing (#18619) --- .../CimSessionProxy.cs | 4 +- .../management/GetComputerInfoCommand.cs | 6 +- .../commands/management/Process.cs | 8 +- .../commands/management/Service.cs | 16 ++-- .../commands/management/WMIHelper.cs | 12 +-- .../commands/utility/CsvCommands.cs | 20 ++--- .../commands/utility/Get-PSBreakpoint.cs | 3 +- .../commands/utility/ObjectCommandComparer.cs | 2 +- .../commands/utility/XmlCommands.cs | 6 +- .../host/msh/ConsoleHost.cs | 2 +- .../host/msh/ConsoleHostUserInterface.cs | 2 +- .../host/msh/PendingProgress.cs | 2 +- .../host/msh/ProgressPane.cs | 4 +- .../security/CertificateProvider.cs | 2 +- .../ConfigProvider.cs | 6 +- .../CoreCLR/CorePsStub.cs | 2 +- .../DscSupport/CimDSCParser.cs | 2 +- .../engine/CoreAdapter.cs | 8 +- .../engine/EventManager.cs | 62 ++++++------- .../engine/LanguagePrimitives.cs | 4 +- .../engine/Modules/ModuleCmdletBase.cs | 2 +- .../engine/Modules/PSModuleInfo.cs | 2 +- .../engine/MshObject.cs | 2 +- .../engine/PSConfiguration.cs | 1 + .../engine/ProgressRecord.cs | 4 +- .../engine/TransactedString.cs | 6 +- .../engine/TransactionManager.cs | 6 +- .../engine/Utils.cs | 24 +++--- .../engine/hostifaces/Connection.cs | 8 +- .../engine/hostifaces/FieldDescription.cs | 4 +- .../engine/hostifaces/History.cs | 22 ++--- .../engine/hostifaces/LocalPipeline.cs | 6 +- .../hostifaces/MshHostRawUserInterface.cs | 6 +- .../engine/hostifaces/MshHostUserInterface.cs | 2 +- .../engine/hostifaces/RunspacePool.cs | 2 +- .../engine/parser/ast.cs | 6 +- .../engine/remoting/client/Job.cs | 2 +- .../client/RemoteRunspacePoolInternal.cs | 2 +- .../remoting/common/RunspaceConnectionInfo.cs | 1 + .../WireDataFormat/RemotingDataObject.cs | 4 +- .../engine/remoting/common/throttlemanager.cs | 2 +- .../engine/runtime/Operations/ClassOps.cs | 8 +- .../engine/runtime/Operations/MiscOps.cs | 4 +- .../help/HelpCommands.cs | 4 +- .../help/HelpSystem.cs | 4 +- .../help/UpdatableHelpCommandBase.cs | 1 + .../namespaces/FileSystemProvider.cs | 2 +- .../namespaces/ProviderBase.cs | 2 +- .../namespaces/TransactedRegistryKey.cs | 86 +++++++++---------- .../namespaces/TransactedRegistrySecurity.cs | 50 +++++------ .../utils/CryptoUtils.cs | 4 +- .../utils/Verbs.cs | 20 ++--- 52 files changed, 237 insertions(+), 235 deletions(-) diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs index e40ebb40930..bc69a4f5ce7 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs @@ -2154,12 +2154,11 @@ internal class CimSessionProxyNewCimInstance : CimSessionProxy /// /// Initializes a new instance of the class. - /// + /// /// /// Create by given computer name. /// Then create wrapper object. /// - /// public CimSessionProxyNewCimInstance(string computerName, CimNewCimInstance operation) : base(computerName) { @@ -2169,6 +2168,7 @@ public CimSessionProxyNewCimInstance(string computerName, CimNewCimInstance oper /// /// Initializes a new instance of the class. /// + /// /// /// Create by given computer name /// and session options. diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs index 351d6adde3c..7f69d6defd7 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs @@ -3325,9 +3325,9 @@ public enum AdminPasswordStatus [SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue", Justification = "The underlying MOF definition does not contain a zero value. The converter method will handle it appropriately.")] public enum BootOptionAction { - // - // This value is reserved - // + // + // This value is reserved + // // Reserved = 0, /// diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs index 8bfa485ff24..2bdb5fcc2b6 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs @@ -528,18 +528,18 @@ public SwitchParameter IncludeUserName private bool _includeUserName = false; - /// + /// /// To display the modules of a process. - /// + /// [Parameter(ParameterSetName = NameParameterSet)] [Parameter(ParameterSetName = IdParameterSet)] [Parameter(ParameterSetName = InputObjectParameterSet)] [ValidateNotNull] public SwitchParameter Module { get; set; } - /// + /// /// To display the fileversioninfo of the main module of a process. - /// + /// [Parameter(ParameterSetName = NameParameterSet)] [Parameter(ParameterSetName = IdParameterSet)] [Parameter(ParameterSetName = InputObjectParameterSet)] diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs index d6190573a38..f05881751e9 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs @@ -2955,20 +2955,20 @@ internal static ServiceStartupType GetServiceStartupType(ServiceStartMode startM #endregion NativeMethods #region ServiceStartupType - /// - ///Enum for usage with StartupType. Automatic, Manual and Disabled index matched from System.ServiceProcess.ServiceStartMode - /// + /// + /// Enum for usage with StartupType. Automatic, Manual and Disabled index matched from System.ServiceProcess.ServiceStartMode + /// public enum ServiceStartupType { - ///Invalid service + /// Invalid service InvalidValue = -1, - ///Automatic service + /// Automatic service Automatic = 2, - ///Manual service + /// Manual service Manual = 3, - ///Disabled service + /// Disabled service Disabled = 4, - ///Automatic (Delayed Start) service + /// Automatic (Delayed Start) service AutomaticDelayedStart = 10 } #endregion ServiceStartupType diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/WMIHelper.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/WMIHelper.cs index e15a45c0e9a..e617177085b 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/WMIHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/WMIHelper.cs @@ -182,9 +182,9 @@ internal void RaiseOperationCompleteEvent(EventArgs baseEventArgs, OperationStat OperationComplete.SafeInvoke(this, operationStateEventArgs); } - /// + /// /// Raise WMI state changed event - /// + /// internal void RaiseWmiOperationState(EventArgs baseEventArgs, WmiState state) { WmiJobStateEventArgs wmiJobStateEventArgs = new WmiJobStateEventArgs(); @@ -992,16 +992,16 @@ private void ConnectGetWMI() } } - /// + /// /// Event which will be triggered when WMI state is changed. /// Currently it is to notify Jobs that state has changed to running. /// Other states are notified via OperationComplete. - /// + /// internal sealed class WmiJobStateEventArgs : EventArgs { - /// + /// /// WMI state - /// + /// internal WmiState WmiState { get; set; } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs index 1d1c235165b..3557946b24d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs @@ -32,9 +32,9 @@ public abstract class BaseCsvWritingCommand : PSCmdlet [ValidateNotNull] public char Delimiter { get; set; } - /// - ///Culture switch for csv conversion - /// + /// + /// Culture switch for csv conversion + /// [Parameter(ParameterSetName = "UseCulture")] public SwitchParameter UseCulture { get; set; } @@ -586,9 +586,9 @@ public string[] LiteralPath [ValidateNotNull] public SwitchParameter UseCulture { get; set; } - /// + /// /// Gets or sets header property to customize the names. - /// + /// [Parameter(Mandatory = false)] [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] @@ -785,9 +785,9 @@ public sealed class ConvertFromCsvCommand : PSCmdlet [ValidateNotNullOrEmpty] public char Delimiter { get; set; } - /// - ///Culture switch for csv conversion - /// + /// + /// Culture switch for csv conversion + /// [Parameter(ParameterSetName = "UseCulture", Mandatory = true)] [ValidateNotNull] [ValidateNotNullOrEmpty] @@ -802,9 +802,9 @@ public sealed class ConvertFromCsvCommand : PSCmdlet [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public PSObject[] InputObject { get; set; } - /// + /// /// Gets or sets header property to customize the names. - /// + /// [Parameter(Mandatory = false)] [ValidateNotNull] [ValidateNotNullOrEmpty] diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-PSBreakpoint.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-PSBreakpoint.cs index 448e3edf3bd..85bb8fa53b7 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-PSBreakpoint.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-PSBreakpoint.cs @@ -16,8 +16,7 @@ public enum BreakpointType /// Breakpoint on a line within a script Line, - /// - /// Breakpoint on a variable + /// Breakpoint on a variable Variable, /// Breakpoint on a command diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ObjectCommandComparer.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ObjectCommandComparer.cs index 39986943c99..bb71dfdbe1c 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ObjectCommandComparer.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ObjectCommandComparer.cs @@ -190,7 +190,7 @@ internal int Compare(ObjectCommandPropertyValue first, ObjectCommandPropertyValu /// /// /// 0 if they are the same, less than 0 if first is smaller, more than 0 if first is greater. - /// + /// public int Compare(object first, object second) { // This method will never throw exceptions, two null diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs index 1ce259b726e..f39242e1010 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs @@ -803,9 +803,9 @@ internal void Import() } #region Select-Xml - /// - ///This cmdlet is used to search an xml document based on the XPath Query. - /// + /// + /// This cmdlet is used to search an xml document based on the XPath Query. + /// [Cmdlet(VerbsCommon.Select, "Xml", DefaultParameterSetName = "Xml", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097031")] [OutputType(typeof(SelectXmlInfo))] public class SelectXmlCommand : PSCmdlet diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs index abe0d59b43a..19bb79977e7 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs @@ -431,7 +431,7 @@ private static bool BreakIntoDebugger() /// if true, then flag the parent ConsoleHost that it should shutdown the session. If false, then only the current /// executing instance is stopped. /// - /// + /// private static void SpinUpBreakHandlerThread(bool shouldEndSession) { ConsoleHost host = ConsoleHost.SingletonInstance; diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs index d755e042984..f399aa07b7e 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs @@ -255,7 +255,7 @@ public override SecureString ReadLineAsSecureString() /// the advantage is portability through abstraction. Does not support /// arrow key movement, but supports backspace. /// - /// + /// /// True to specify reading a SecureString; false reading a string /// /// diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs index 88aa6d1ffc9..8453ad65072 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs @@ -872,7 +872,7 @@ internal override /// /// The number of nodes that were made invisible during the compression. /// - /// + /// private int CompressToFit(PSHostRawUserInterface rawUi, int maxHeight, int maxWidth) diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs index 99ecc222300..030a359c2d8 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs @@ -13,7 +13,7 @@ namespace Microsoft.PowerShell /// ProgressPane is a class that represents the "window" in which outstanding activities for which the host has received /// progress updates are shown. /// - /// + /// internal class ProgressPane { @@ -37,7 +37,7 @@ class ProgressPane /// /// true if the pane is visible, false if not. /// - /// + /// internal bool IsShowing diff --git a/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs b/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs index a7c30831291..7644f3de620 100644 --- a/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs +++ b/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs @@ -926,7 +926,7 @@ protected override void MoveItem( /// /// The path of the certificate store to create. /// - /// + /// /// Ignored. /// Only support store. /// diff --git a/src/Microsoft.WSMan.Management/ConfigProvider.cs b/src/Microsoft.WSMan.Management/ConfigProvider.cs index 98c76e31c89..d40e4161188 100644 --- a/src/Microsoft.WSMan.Management/ConfigProvider.cs +++ b/src/Microsoft.WSMan.Management/ConfigProvider.cs @@ -5059,9 +5059,9 @@ private static ArrayList ProcessPluginSecurityLevel(ArrayList arrSecurity, XmlDo /// Resource URI for the XML. /// Name of the Host. /// Type of Operation. - ///List of Resources. - ///List of Securities - ///List of initialization parameters. + /// List of Resources. + /// List of Securities + /// List of initialization parameters. /// An Configuration XML, ready to send to server. private static string ConstructPluginXml(PSObject objinputparam, string ResourceURI, string host, string Operation, ArrayList resources, ArrayList securities, ArrayList initParams) { diff --git a/src/System.Management.Automation/CoreCLR/CorePsStub.cs b/src/System.Management.Automation/CoreCLR/CorePsStub.cs index 67775cde747..122eadce990 100644 --- a/src/System.Management.Automation/CoreCLR/CorePsStub.cs +++ b/src/System.Management.Automation/CoreCLR/CorePsStub.cs @@ -464,7 +464,7 @@ internal static bool IsClassInApprovedList(Guid clsid) /// /// Script file path for policy check. /// FileStream object to script file path. - /// Policy check result for script file. + /// Policy check result for script file. public static SystemScriptFileEnforcement GetFilePolicyEnforcement( string filePath, System.IO.FileStream fileStream) diff --git a/src/System.Management.Automation/DscSupport/CimDSCParser.cs b/src/System.Management.Automation/DscSupport/CimDSCParser.cs index d13deea5d67..cd9f5d423de 100644 --- a/src/System.Management.Automation/DscSupport/CimDSCParser.cs +++ b/src/System.Management.Automation/DscSupport/CimDSCParser.cs @@ -1601,8 +1601,8 @@ public static void LoadDefaultCimKeywords(Collection errors) /// /// Load the default system CIM classes and create the corresponding keywords. - /// A dictionary to add the defined functions to, may be null. /// + /// A dictionary to add the defined functions to, may be null. public static void LoadDefaultCimKeywords(Dictionary functionsToDefine) { LoadDefaultCimKeywords(functionsToDefine, null, null, false); diff --git a/src/System.Management.Automation/engine/CoreAdapter.cs b/src/System.Management.Automation/engine/CoreAdapter.cs index 51c8e45eea7..17ddb9eb1e2 100644 --- a/src/System.Management.Automation/engine/CoreAdapter.cs +++ b/src/System.Management.Automation/engine/CoreAdapter.cs @@ -3920,11 +3920,11 @@ protected override ConsolidatedString GetInternedTypeNameHierarchy(object obj) /// /// Get the .NET member based on the given member name. /// - /// + /// /// Dynamic members of an object that implements IDynamicMetaObjectProvider are not included because /// 1. Dynamic members cannot be invoked via reflection; /// 2. Access to dynamic members is handled by the DLR for free. - /// + /// /// Object to retrieve the PSMemberInfo from. /// Name of the member to be retrieved. /// @@ -3957,10 +3957,10 @@ protected override T GetFirstMemberOrDefault(object obj, MemberNamePredicate /// In the case of the DirectoryEntry adapter, this could be a cache of the objectClass /// to the properties available in it. /// - /// + /// /// Dynamic members of an object that implements IDynamicMetaObjectProvider are included because /// we want to view the dynamic members via 'Get-Member' and be able to auto-complete those members. - /// + /// /// Object to get all the member information from. /// All members in obj. protected override PSMemberInfoInternalCollection GetMembers(object obj) diff --git a/src/System.Management.Automation/engine/EventManager.cs b/src/System.Management.Automation/engine/EventManager.cs index f7ffbddd852..75538135b92 100644 --- a/src/System.Management.Automation/engine/EventManager.cs +++ b/src/System.Management.Automation/engine/EventManager.cs @@ -44,6 +44,7 @@ protected int GetNextEventId() /// /// Creates a PowerShell event. + /// /// /// An optional identifier that identifies the source event /// @@ -56,11 +57,11 @@ protected int GetNextEventId() /// /// Any additional data you wish to attach to the event /// - /// protected abstract PSEventArgs CreateEvent(string sourceIdentifier, object sender, object[] args, PSObject extraData); /// /// Generate a PowerShell event. + /// /// /// An optional identifier that identifies the source event /// @@ -73,7 +74,6 @@ protected int GetNextEventId() /// /// Any additional data you wish to attach to the event /// - /// public PSEventArgs GenerateEvent(string sourceIdentifier, object sender, object[] args, PSObject extraData) { return this.GenerateEvent(sourceIdentifier, sender, args, extraData, false, false); @@ -81,6 +81,7 @@ public PSEventArgs GenerateEvent(string sourceIdentifier, object sender, object[ /// /// Generate a PowerShell event. + /// /// /// An optional identifier that identifies the source event /// @@ -100,7 +101,6 @@ public PSEventArgs GenerateEvent(string sourceIdentifier, object sender, object[ /// /// Wait for the event and associated action to be processed and completed. /// - /// public PSEventArgs GenerateEvent(string sourceIdentifier, object sender, object[] args, PSObject extraData, bool processInCurrentThread, bool waitForCompletionInCurrentThread) { @@ -133,14 +133,15 @@ protected internal virtual void ProcessNewEvent(PSEventArgs newEvent, bool proce /// /// Get the event subscription that corresponds to an identifier + /// /// /// The identifier that identifies the source of the events /// - /// public abstract IEnumerable GetEventSubscribers(string sourceIdentifier); /// /// Subscribes to an event on an object. + /// /// /// The source object that defines the event /// @@ -162,12 +163,12 @@ protected internal virtual void ProcessNewEvent(PSEventArgs newEvent, bool proce /// /// Whether events in this subscriber should be forwarded to the client PowerShell during remote executions /// - /// [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] public abstract PSEventSubscriber SubscribeEvent(object source, string eventName, string sourceIdentifier, PSObject data, ScriptBlock action, bool supportEvent, bool forwardEvent); /// /// Subscribes to an event on an object. + /// /// /// The source object that defines the event /// @@ -193,12 +194,12 @@ protected internal virtual void ProcessNewEvent(PSEventArgs newEvent, bool proce /// Indicate how many times the subscriber should be triggered before auto-unregister it /// If the value is equal or less than zero, there is no limit on the number of times the event can be triggered without being unregistered /// - /// [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] public abstract PSEventSubscriber SubscribeEvent(object source, string eventName, string sourceIdentifier, PSObject data, ScriptBlock action, bool supportEvent, bool forwardEvent, int maxTriggerCount); /// /// Subscribes to an event on an object. + /// /// /// The source object that defines the event /// @@ -220,12 +221,12 @@ protected internal virtual void ProcessNewEvent(PSEventArgs newEvent, bool proce /// /// Whether events in this subscriber should be forwarded to the client PowerShell during remote executions /// - /// [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] public abstract PSEventSubscriber SubscribeEvent(object source, string eventName, string sourceIdentifier, PSObject data, PSEventReceivedEventHandler handlerDelegate, bool supportEvent, bool forwardEvent); /// /// Subscribes to an event on an object. + /// /// /// The source object that defines the event /// @@ -251,12 +252,12 @@ protected internal virtual void ProcessNewEvent(PSEventArgs newEvent, bool proce /// Indicate how many times the subscriber should be triggered before auto-unregister it /// If the value is equal or less than zero, there is no limit on the number of times the event can be triggered without being unregistered /// - /// [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] public abstract PSEventSubscriber SubscribeEvent(object source, string eventName, string sourceIdentifier, PSObject data, PSEventReceivedEventHandler handlerDelegate, bool supportEvent, bool forwardEvent, int maxTriggerCount); /// /// Subscribes to an event on an object. + /// /// /// The source object that defines the event /// @@ -286,7 +287,6 @@ protected internal virtual void ProcessNewEvent(PSEventArgs newEvent, bool proce /// If the value is equal or less than zero, there is no limit on the number of times the event can be triggered without being unregistered /// The default value is zero /// - /// [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] internal virtual PSEventSubscriber SubscribeEvent(object source, string eventName, @@ -303,10 +303,10 @@ internal virtual PSEventSubscriber SubscribeEvent(object source, /// /// Unsubscribes from an event on an object. + /// /// /// The subscriber associated with the event subscription /// - /// public abstract void UnsubscribeEvent(PSEventSubscriber subscriber); /// @@ -367,6 +367,7 @@ public override List Subscribers /// /// Subscribes to an event on an object. + /// /// /// The source object that defines the event /// @@ -388,7 +389,6 @@ public override List Subscribers /// /// Whether events in this subscriber should be forwarded to the client PowerShell during remote executions /// - /// [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] public override PSEventSubscriber SubscribeEvent(object source, string eventName, string sourceIdentifier, PSObject data, ScriptBlock action, bool supportEvent, bool forwardEvent) { @@ -397,6 +397,7 @@ public override PSEventSubscriber SubscribeEvent(object source, string eventName /// /// Subscribes to an event on an object. + /// /// /// The source object that defines the event /// @@ -422,7 +423,6 @@ public override PSEventSubscriber SubscribeEvent(object source, string eventName /// Indicate how many times the subscriber should be triggered before auto-unregister it /// If the value is equal or less than zero, there is no limit on the number of times the event can be triggered without being unregistered /// - /// [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] public override PSEventSubscriber SubscribeEvent(object source, string eventName, string sourceIdentifier, PSObject data, ScriptBlock action, bool supportEvent, bool forwardEvent, int maxTriggerCount) { @@ -436,6 +436,7 @@ public override PSEventSubscriber SubscribeEvent(object source, string eventName /// /// Subscribes to an event on an object. + /// /// /// The source object that defines the event /// @@ -465,7 +466,6 @@ public override PSEventSubscriber SubscribeEvent(object source, string eventName /// If the value is equal or less than zero, there is no limit on the number of times the event can be triggered without being unregistered /// The default value is zero /// - /// [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] internal override PSEventSubscriber SubscribeEvent(object source, string eventName, @@ -484,6 +484,7 @@ internal override PSEventSubscriber SubscribeEvent(object source, /// /// Subscribes to an event on an object. + /// /// /// The source object that defines the event /// @@ -505,7 +506,6 @@ internal override PSEventSubscriber SubscribeEvent(object source, /// /// Whether events in this subscriber should be forwarded to the client PowerShell during remote executions /// - /// [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] public override PSEventSubscriber SubscribeEvent(object source, string eventName, string sourceIdentifier, PSObject data, PSEventReceivedEventHandler handlerDelegate, bool supportEvent, bool forwardEvent) { @@ -514,6 +514,7 @@ public override PSEventSubscriber SubscribeEvent(object source, string eventName /// /// Subscribes to an event on an object. + /// /// /// The source object that defines the event /// @@ -539,7 +540,6 @@ public override PSEventSubscriber SubscribeEvent(object source, string eventName /// Indicate how many times the subscriber should be triggered before auto-unregister it /// If the value is equal or less than zero, there is no limit on the number of times the event can be triggered without being unregistered /// - /// [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] public override PSEventSubscriber SubscribeEvent(object source, string eventName, string sourceIdentifier, PSObject data, PSEventReceivedEventHandler handlerDelegate, bool supportEvent, bool forwardEvent, int maxTriggerCount) { @@ -797,10 +797,10 @@ private void ProcessNewSubscriber(PSEventSubscriber subscriber, object source, s /// /// Unsubscribes from an event on an object. + /// /// /// The subscriber associated with the event subscription /// - /// public override void UnsubscribeEvent(PSEventSubscriber subscriber) { UnsubscribeEvent(subscriber, false); @@ -808,13 +808,13 @@ public override void UnsubscribeEvent(PSEventSubscriber subscriber) /// /// Unsubscribes from an event on an object. + /// /// /// The subscriber associated with the event subscription /// /// /// Indicate if we should skip draining /// - /// private void UnsubscribeEvent(PSEventSubscriber subscriber, bool skipDraining) { ArgumentNullException.ThrowIfNull(subscriber); @@ -876,6 +876,7 @@ private void UnsubscribeEvent(PSEventSubscriber subscriber, bool skipDraining) /// /// Creates a PowerShell event. + /// /// /// An optional identifier that identifies the source event /// @@ -888,7 +889,6 @@ private void UnsubscribeEvent(PSEventSubscriber subscriber, bool skipDraining) /// /// Any additional data you wish to attach to the event /// - /// protected override PSEventArgs CreateEvent(string sourceIdentifier, object sender, object[] args, PSObject extraData) { return new PSEventArgs(null, _context.CurrentRunspace.InstanceId, GetNextEventId(), sourceIdentifier, sender, args, extraData); @@ -1287,10 +1287,10 @@ internal bool IsExecutingEventAction /// /// Get the event subscription that corresponds to an identifier + /// /// /// The identifier that identifies the source of the events /// - /// public override IEnumerable GetEventSubscribers(string sourceIdentifier) { return GetEventSubscribers(sourceIdentifier, false); @@ -1516,10 +1516,10 @@ public void Dispose() /// /// Stop the timer if it's not null. /// Unsubscribes from all events. + /// /// /// Whether to actually dispose the object. /// - /// public void Dispose(bool disposing) { if (disposing) @@ -1580,6 +1580,7 @@ public override List Subscribers /// /// Creates a PowerShell event. + /// /// /// An optional identifier that identifies the source event /// @@ -1592,7 +1593,6 @@ public override List Subscribers /// /// Any additional data you wish to attach to the event /// - /// protected override PSEventArgs CreateEvent(string sourceIdentifier, object sender, object[] args, PSObject extraData) { // note that this is a local call, so we use null for the computer name @@ -1648,10 +1648,10 @@ protected internal override void ProcessNewEvent(PSEventArgs newEvent, /// /// Get the event subscription that corresponds to an identifier + /// /// /// The identifier that identifies the source of the events /// - /// public override IEnumerable GetEventSubscribers(string sourceIdentifier) { throw new NotSupportedException(EventingResources.RemoteOperationNotSupported); @@ -1659,6 +1659,7 @@ public override IEnumerable GetEventSubscribers(string source /// /// Subscribes to an event on an object. + /// /// /// The source object that defines the event /// @@ -1680,7 +1681,6 @@ public override IEnumerable GetEventSubscribers(string source /// /// Whether events in this subscriber should be forwarded to the client PowerShell during remote executions /// - /// [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] public override PSEventSubscriber SubscribeEvent(object source, string eventName, string sourceIdentifier, PSObject data, ScriptBlock action, bool supportEvent, bool forwardEvent) { @@ -1689,6 +1689,7 @@ public override PSEventSubscriber SubscribeEvent(object source, string eventName /// /// Subscribes to an event on an object. + /// /// /// The source object that defines the event /// @@ -1714,7 +1715,6 @@ public override PSEventSubscriber SubscribeEvent(object source, string eventName /// Indicate how many times the subscriber should be triggered before auto-unregister it /// If the value is equal or less than zero, there is no limit on the number of times the event can be triggered without being unregistered /// - /// [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] public override PSEventSubscriber SubscribeEvent(object source, string eventName, string sourceIdentifier, PSObject data, ScriptBlock action, bool supportEvent, bool forwardEvent, int maxTriggerCount) { @@ -1723,6 +1723,7 @@ public override PSEventSubscriber SubscribeEvent(object source, string eventName /// /// Subscribes to an event on an object. + /// /// /// The source object that defines the event /// @@ -1744,7 +1745,6 @@ public override PSEventSubscriber SubscribeEvent(object source, string eventName /// /// Whether events in this subscriber should be forwarded to the client PowerShell during remote executions /// - /// [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] public override PSEventSubscriber SubscribeEvent(object source, string eventName, string sourceIdentifier, PSObject data, PSEventReceivedEventHandler handlerDelegate, bool supportEvent, bool forwardEvent) { @@ -1753,6 +1753,7 @@ public override PSEventSubscriber SubscribeEvent(object source, string eventName /// /// Subscribes to an event on an object. + /// /// /// The source object that defines the event /// @@ -1778,7 +1779,6 @@ public override PSEventSubscriber SubscribeEvent(object source, string eventName /// Indicate how many times the subscriber should be triggered before auto-unregister it /// If the value is equal or less than zero, there is no limit on the number of times the event can be triggered without being unregistered /// - /// [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] public override PSEventSubscriber SubscribeEvent(object source, string eventName, string sourceIdentifier, PSObject data, PSEventReceivedEventHandler handlerDelegate, bool supportEvent, bool forwardEvent, int maxTriggerCount) { @@ -1787,10 +1787,10 @@ public override PSEventSubscriber SubscribeEvent(object source, string eventName /// /// Unsubscribes from an event on an object. + /// /// /// The subscriber associated with the event subscription /// - /// public override void UnsubscribeEvent(PSEventSubscriber subscriber) { throw new NotSupportedException(EventingResources.RemoteOperationNotSupported); @@ -2048,10 +2048,10 @@ public override bool Equals(object obj) /// /// Determines if two PSEventSubscriber instances are equal + /// /// /// The PSEventSubscriber to which to compare this instance /// - /// public bool Equals(PSEventSubscriber other) { if (other == null) @@ -2095,6 +2095,7 @@ public PSEventHandler() /// /// Creates a new instance of the PsEventHandler class for a given /// event manager, source identifier, and extra data + /// /// /// The event manager to which we forward events. /// @@ -2108,7 +2109,6 @@ public PSEventHandler() /// /// Any additional data you wish to attach to the event /// - /// public PSEventHandler(PSEventManager eventManager, object sender, string sourceIdentifier, PSObject extraData) { this.eventManager = eventManager; @@ -2460,6 +2460,7 @@ public class PSEventJob : Job { /// /// Creates a new instance of the PSEventJob class. + /// /// /// The event manager that controls the event subscriptions /// @@ -2472,7 +2473,6 @@ public class PSEventJob : Job /// /// The name of the job /// - /// public PSEventJob( PSEventManager eventManager, PSEventSubscriber subscriber, @@ -2549,13 +2549,13 @@ public override string Location /// /// Invoke the script block + /// /// /// The subscriber that generated this event /// /// /// The context of this event /// - /// internal void Invoke(PSEventSubscriber eventSubscriber, PSEventArgs eventArgs) { if (IsFinishedState(JobStateInfo.State)) diff --git a/src/System.Management.Automation/engine/LanguagePrimitives.cs b/src/System.Management.Automation/engine/LanguagePrimitives.cs index 028bfda42a8..b1c7cab0ace 100644 --- a/src/System.Management.Automation/engine/LanguagePrimitives.cs +++ b/src/System.Management.Automation/engine/LanguagePrimitives.cs @@ -3842,11 +3842,11 @@ internal object Convert(object valueToConvert, /// Create a IList to hold all elements, and use the IList to create the object of the resultType. /// The reason for using IList is that it can work on constructors that takes IEnumerable[T], ICollection[T] or IList[T]. /// - /// + /// /// When get to this method, we know the fromType and the toType meet the following two conditions: /// 1. toType is a closed generic type and it has a constructor that takes IEnumerable[T], ICollection[T] or IList[T] /// 2. fromType is System.Array, System.Object[] or it's the same as the element type of toType - /// + /// private sealed class ConvertViaIEnumerableConstructor { internal Func ListCtorLambda; diff --git a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs index e95c9cc0984..117c19c9b1e 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs @@ -4542,7 +4542,7 @@ internal static ModuleLoggingGroupPolicyStatus GetModuleLoggingInformation(out I /// /// Checks to see if the module manifest contains the specified key. /// If it does and it can be converted to the expected type, then it returns and sets to the value. - /// If the key is missing it returns and sets to default(). + /// If the key is missing it returns and sets to default(). /// If the key is invalid then it returns . /// /// The hashtable to look for the key in. diff --git a/src/System.Management.Automation/engine/Modules/PSModuleInfo.cs b/src/System.Management.Automation/engine/Modules/PSModuleInfo.cs index 8dae7db0deb..d4cc2214b05 100644 --- a/src/System.Management.Automation/engine/Modules/PSModuleInfo.cs +++ b/src/System.Management.Automation/engine/Modules/PSModuleInfo.cs @@ -1437,8 +1437,8 @@ internal void SetExportedTypeFiles(ReadOnlyCollection files) /// /// Implements deep copy of a PSModuleInfo instance. - /// A new PSModuleInfo instance. /// + /// A new PSModuleInfo instance. public PSModuleInfo Clone() { PSModuleInfo clone = (PSModuleInfo)this.MemberwiseClone(); diff --git a/src/System.Management.Automation/engine/MshObject.cs b/src/System.Management.Automation/engine/MshObject.cs index 7c6c58a9fd3..018daeed5bb 100644 --- a/src/System.Management.Automation/engine/MshObject.cs +++ b/src/System.Management.Automation/engine/MshObject.cs @@ -2048,7 +2048,7 @@ internal static void CopyDeserializerFields(PSObject source, PSObject target) /// /// Object which is set as core. /// If true, overwrite the type information. - ///This method is to be used only by Serialization code + /// This method is to be used only by Serialization code internal void SetCoreOnDeserialization(object value, bool overrideTypeInfo) { Diagnostics.Assert(this.ImmediateBaseObjectIsEmpty, "BaseObject should be PSCustomObject for deserialized objects"); diff --git a/src/System.Management.Automation/engine/PSConfiguration.cs b/src/System.Management.Automation/engine/PSConfiguration.cs index 16273979a69..e321423f768 100644 --- a/src/System.Management.Automation/engine/PSConfiguration.cs +++ b/src/System.Management.Automation/engine/PSConfiguration.cs @@ -181,6 +181,7 @@ private static string GetExecutionPolicySettingKey(string shellId) : string.Concat(shellId, ":", "ExecutionPolicy"); } + /// /// Get the names of experimental features enabled in the config file. /// internal string[] GetExperimentalFeatures() diff --git a/src/System.Management.Automation/engine/ProgressRecord.cs b/src/System.Management.Automation/engine/ProgressRecord.cs index b721b4003d9..cd5b33107aa 100644 --- a/src/System.Management.Automation/engine/ProgressRecord.cs +++ b/src/System.Management.Automation/engine/ProgressRecord.cs @@ -230,7 +230,7 @@ internal ProgressRecord(ProgressRecord other) /// /// Normally displayed beside the progress bar, as "N seconds remaining." /// - /// + /// /// A value less than 0 means "don't display a time remaining." /// public @@ -512,7 +512,7 @@ internal PSObject ToPSObjectForRemoting() public enum ProgressRecordType { - /// + /// /// Operation just started or is not yet complete. /// /// diff --git a/src/System.Management.Automation/engine/TransactedString.cs b/src/System.Management.Automation/engine/TransactedString.cs index f1bc8f586b4..22a0afe9a9a 100644 --- a/src/System.Management.Automation/engine/TransactedString.cs +++ b/src/System.Management.Automation/engine/TransactedString.cs @@ -25,10 +25,10 @@ public TransactedString() : this(string.Empty) /// /// Constructor for the TransactedString class. + /// /// /// The initial value of the transacted string. /// - /// public TransactedString(string value) { _value = new StringBuilder(value); @@ -71,10 +71,10 @@ void IEnlistmentNotification.Prepare(PreparingEnlistment preparingEnlistment) /// /// Append text to the transacted string. + /// /// /// The text to append. /// - /// public void Append(string text) { ValidateTransactionOrEnlist(); @@ -91,13 +91,13 @@ public void Append(string text) /// /// Remove text from the transacted string. + /// /// /// The position in the string from which to start removing. /// /// /// The length of text to remove. /// - /// public void Remove(int startIndex, int length) { ValidateTransactionOrEnlist(); diff --git a/src/System.Management.Automation/engine/TransactionManager.cs b/src/System.Management.Automation/engine/TransactionManager.cs index bf86d90e812..2add6f288f5 100644 --- a/src/System.Management.Automation/engine/TransactionManager.cs +++ b/src/System.Management.Automation/engine/TransactionManager.cs @@ -185,10 +185,10 @@ public void Dispose() /// /// Disposes the PSTransaction object, which disposes the /// underlying transaction. + /// /// /// Whether to actually dispose the object. /// - /// public void Dispose(bool disposing) { if (disposing) @@ -237,10 +237,10 @@ public void Dispose() /// /// Disposes the PSTransactionContext object, which resets the /// active PSTransaction. + /// /// /// Whether to actually dispose the object. /// - /// private void Dispose(bool disposing) { if (disposing) @@ -682,10 +682,10 @@ public void Dispose() /// /// Disposes the PSTransactionContext object, which resets the /// active PSTransaction. + /// /// /// Whether to actually dispose the object. /// - /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2213:DisposableFieldsShouldBeDisposed", MessageId = "baseTransaction", Justification = "baseTransaction should not be disposed since we do not own it - it belongs to the caller")] public void Dispose(bool disposing) { diff --git a/src/System.Management.Automation/engine/Utils.cs b/src/System.Management.Automation/engine/Utils.cs index b472393ff53..295b7f931ed 100644 --- a/src/System.Management.Automation/engine/Utils.cs +++ b/src/System.Management.Automation/engine/Utils.cs @@ -302,9 +302,9 @@ internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int /// /// Helper fn to check byte[] arg for null. /// - /// arg to check - /// name of the arg - /// Does not return a value. + /// arg to check + /// name of the arg + /// Does not return a value. internal static void CheckKeyArg(byte[] arg, string argName) { if (arg == null) @@ -329,9 +329,9 @@ internal static void CheckKeyArg(byte[] arg, string argName) /// Helper fn to check arg for empty or null. /// Throws ArgumentNullException on either condition. /// - /// arg to check - /// name of the arg - /// Does not return a value. + /// arg to check + /// name of the arg + /// Does not return a value. internal static void CheckArgForNullOrEmpty(string arg, string argName) { if (arg == null) @@ -348,9 +348,9 @@ internal static void CheckArgForNullOrEmpty(string arg, string argName) /// Helper fn to check arg for null. /// Throws ArgumentNullException on either condition. /// - /// arg to check - /// name of the arg - /// Does not return a value. + /// arg to check + /// name of the arg + /// Does not return a value. internal static void CheckArgForNull(object arg, string argName) { if (arg == null) @@ -362,9 +362,9 @@ internal static void CheckArgForNull(object arg, string argName) /// /// Helper fn to check arg for null. /// - /// arg to check - /// name of the arg - /// Does not return a value. + /// arg to check + /// name of the arg + /// Does not return a value. internal static void CheckSecureStringArg(SecureString arg, string argName) { if (arg == null) diff --git a/src/System.Management.Automation/engine/hostifaces/Connection.cs b/src/System.Management.Automation/engine/hostifaces/Connection.cs index ca212c34666..3dfe3a497cc 100644 --- a/src/System.Management.Automation/engine/hostifaces/Connection.cs +++ b/src/System.Management.Automation/engine/hostifaces/Connection.cs @@ -1620,8 +1620,8 @@ public abstract PSEventManager Events /// /// Sets the base transaction for the runspace; any transactions created on this runspace will be nested to this instance. /// - ///The base transaction - ///This overload uses RollbackSeverity.Error; i.e. the transaction will be rolled back automatically on a non-terminating error or worse + /// The base transaction + /// This overload uses RollbackSeverity.Error; i.e. the transaction will be rolled back automatically on a non-terminating error or worse public void SetBaseTransaction(System.Transactions.CommittableTransaction transaction) { this.ExecutionContext.TransactionManager.SetBaseTransaction(transaction, RollbackSeverity.Error); @@ -1630,8 +1630,8 @@ public void SetBaseTransaction(System.Transactions.CommittableTransaction transa /// /// Sets the base transaction for the runspace; any transactions created on this runspace will be nested to this instance. /// - ///The base transaction - ///The severity of error that causes PowerShell to automatically rollback the transaction + /// The base transaction + /// The severity of error that causes PowerShell to automatically rollback the transaction public void SetBaseTransaction(System.Transactions.CommittableTransaction transaction, RollbackSeverity severity) { this.ExecutionContext.TransactionManager.SetBaseTransaction(transaction, severity); diff --git a/src/System.Management.Automation/engine/hostifaces/FieldDescription.cs b/src/System.Management.Automation/engine/hostifaces/FieldDescription.cs index 45f46d65f5f..b8a0793a5f6 100644 --- a/src/System.Management.Automation/engine/hostifaces/FieldDescription.cs +++ b/src/System.Management.Automation/engine/hostifaces/FieldDescription.cs @@ -260,11 +260,11 @@ public string Name /// to pre-populate its UI with. This is a PSObject instance so that the value can be serialized, converted, /// manipulated like any pipeline object. /// - /// + /// /// It is up to the implementer of to decide if it /// can make use of the object in its presentation of the fields prompt. /// - /// + /// public PSObject DefaultValue diff --git a/src/System.Management.Automation/engine/hostifaces/History.cs b/src/System.Management.Automation/engine/hostifaces/History.cs index 3fe2acb19c5..162cf033315 100644 --- a/src/System.Management.Automation/engine/hostifaces/History.cs +++ b/src/System.Management.Automation/engine/hostifaces/History.cs @@ -581,10 +581,10 @@ internal void ClearEntry(long id) } } - /// + /// /// gets the total number of entries added - /// - ///count of total entries added. + /// + /// count of total entries added. internal int Buffercapacity() { return _capacity; @@ -1504,9 +1504,9 @@ private static } } - /// + /// /// This Class implements the Clear History cmdlet - /// + /// [Cmdlet(VerbsCommon.Clear, "History", SupportsShouldProcess = true, DefaultParameterSetName = "IDParameter", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096691")] public class ClearHistoryCommand : PSCmdlet { @@ -1562,9 +1562,9 @@ public string[] CommandLine /// private string[] _commandline = null; - /// + /// /// Clears the specified number of history entries - /// + /// [Parameter(Mandatory = false, Position = 1, HelpMessage = "Clears the specified number of history entries")] [ValidateRangeAttribute((int)1, int.MaxValue)] public int Count @@ -1651,8 +1651,8 @@ protected override void ProcessRecord() /// /// Clears the session history based on the id parameter /// takes no parameters - /// Nothing. /// + /// Nothing. private void ClearHistoryByID() { if (_countParameterSpecified && Count < 0) @@ -1759,8 +1759,8 @@ private void ClearHistoryByID() /// /// Clears the session history based on the Commandline parameter /// takes no parameters - /// Nothing. /// + /// Nothing. private void ClearHistoryByCmdLine() { // throw an exception for invalid count values @@ -1822,12 +1822,12 @@ private void ClearHistoryByCmdLine() /// /// Clears the session history based on the input parameter + /// + /// Nothing. /// Id of the entry to be cleared. /// Count of entries to be cleared. /// Cmdline string to be cleared. /// Order of the entries. - /// Nothing. - /// private void ClearHistoryEntries(long id, int count, string cmdline, SwitchParameter newest) { // if cmdline is null,use default parameter set notion. diff --git a/src/System.Management.Automation/engine/hostifaces/LocalPipeline.cs b/src/System.Management.Automation/engine/hostifaces/LocalPipeline.cs index f77fda65f1f..44e3f3047b2 100644 --- a/src/System.Management.Automation/engine/hostifaces/LocalPipeline.cs +++ b/src/System.Management.Automation/engine/hostifaces/LocalPipeline.cs @@ -269,10 +269,10 @@ private void SetupInvokeThread(Thread invokeThread, bool changeName) } } - /// + /// /// Helper method for asynchronous invoke - ///Unhandled FlowControl exception if InvocationSettings.ExposeFlowControlExceptions is true. - /// + /// + /// Unhandled FlowControl exception if InvocationSettings.ExposeFlowControlExceptions is true. private FlowControlException InvokeHelper() { FlowControlException flowControlException = null; diff --git a/src/System.Management.Automation/engine/hostifaces/MshHostRawUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/MshHostRawUserInterface.cs index 7b0f27b5f82..f0435baec3a 100644 --- a/src/System.Management.Automation/engine/hostifaces/MshHostRawUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/MshHostRawUserInterface.cs @@ -1059,7 +1059,7 @@ public override /// /// Hash code for this instance. /// - /// + /// public override int GetHashCode() @@ -1687,7 +1687,7 @@ char source /// is null; /// Any string in is null or empty /// - /// + /// /// If a character C takes one BufferCell to display as determined by LengthInBufferCells, /// one BufferCell is allocated with its Character set to C and BufferCellType to BufferCell.Complete. /// On the other hand, if C takes two BufferCell, two adjacent BufferCells on a row in @@ -1701,7 +1701,7 @@ char source /// and , respectively. /// The resulting array is suitable for use with /// and . - /// + /// /// /// /// diff --git a/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs index 53ca3f5617a..440252f7611 100644 --- a/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs @@ -1430,7 +1430,7 @@ internal static void BuildHotkeysAndPlainLabels(Collection ch /// /// /// Returns the index into the choices array matching the response string, or -1 if there is no match. - /// + /// internal static int DetermineChoicePicked(string response, Collection choices, string[,] hotkeysAndPlainLabels) { Diagnostics.Assert(choices != null, "choices: expected a value"); diff --git a/src/System.Management.Automation/engine/hostifaces/RunspacePool.cs b/src/System.Management.Automation/engine/hostifaces/RunspacePool.cs index 5f814e0428b..46f4799aaa5 100644 --- a/src/System.Management.Automation/engine/hostifaces/RunspacePool.cs +++ b/src/System.Management.Automation/engine/hostifaces/RunspacePool.cs @@ -1003,7 +1003,7 @@ public Collection CreateDisconnectedPowerShells() return _internalPool.CreateDisconnectedPowerShells(this); } - /// + /// /// Returns RunspacePool capabilities. /// /// RunspacePoolCapability. diff --git a/src/System.Management.Automation/engine/parser/ast.cs b/src/System.Management.Automation/engine/parser/ast.cs index 53a76bfc62f..7a2c27939fb 100644 --- a/src/System.Management.Automation/engine/parser/ast.cs +++ b/src/System.Management.Automation/engine/parser/ast.cs @@ -7448,9 +7448,9 @@ public TernaryExpressionAst(IScriptExtent extent, ExpressionAst condition, Expre /// /// Copy the TernaryExpressionAst instance. /// - /// - /// Retirns a copy of the ast. - /// + /// + /// Returns a copy of the ast. + /// public override Ast Copy() { ExpressionAst newCondition = CopyElement(this.Condition); diff --git a/src/System.Management.Automation/engine/remoting/client/Job.cs b/src/System.Management.Automation/engine/remoting/client/Job.cs index 05ed6dfe1f1..74bd83c1faf 100644 --- a/src/System.Management.Automation/engine/remoting/client/Job.cs +++ b/src/System.Management.Automation/engine/remoting/client/Job.cs @@ -641,7 +641,7 @@ public IList ChildJobs } } - /// + /// /// Success status of the command execution. /// public abstract string StatusMessage { get; } diff --git a/src/System.Management.Automation/engine/remoting/client/RemoteRunspacePoolInternal.cs b/src/System.Management.Automation/engine/remoting/client/RemoteRunspacePoolInternal.cs index 21ac2d3e278..dd365106ced 100644 --- a/src/System.Management.Automation/engine/remoting/client/RemoteRunspacePoolInternal.cs +++ b/src/System.Management.Automation/engine/remoting/client/RemoteRunspacePoolInternal.cs @@ -1215,7 +1215,7 @@ public override Collection CreateDisconnectedPowerShells(RunspacePoo return psCollection; } - /// + /// /// Returns RunspacePool capabilities. /// /// RunspacePoolCapability. diff --git a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs index 700596957f6..571d494c4d7 100644 --- a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs +++ b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs @@ -1988,6 +1988,7 @@ public int ConnectingTimeout set; } + /// /// The SSH options to pass to OpenSSH. /// Gets or sets the SSH options to pass to OpenSSH. /// diff --git a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemotingDataObject.cs b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemotingDataObject.cs index c9887c54991..14cad7613b8 100644 --- a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemotingDataObject.cs +++ b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemotingDataObject.cs @@ -7,11 +7,11 @@ namespace System.Management.Automation.Remoting { - /// + /// /// This is the object used by Runspace,pipeline,host to send data /// to remote end. Transport layer owns breaking this into fragments /// and sending to other end - /// + /// internal class RemoteDataObject { #region Private Members diff --git a/src/System.Management.Automation/engine/remoting/common/throttlemanager.cs b/src/System.Management.Automation/engine/remoting/common/throttlemanager.cs index fca2bf15c1b..7d4a88e98bd 100644 --- a/src/System.Management.Automation/engine/remoting/common/throttlemanager.cs +++ b/src/System.Management.Automation/engine/remoting/common/throttlemanager.cs @@ -117,7 +117,7 @@ internal abstract class IThrottleOperation /// need not be called on the operation (this can be when the /// operation has stop completed or stop has been called and is /// pending) - /// + /// internal bool IgnoreStop { get diff --git a/src/System.Management.Automation/engine/runtime/Operations/ClassOps.cs b/src/System.Management.Automation/engine/runtime/Operations/ClassOps.cs index fdbb91ec404..2b741a29c31 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/ClassOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/ClassOps.cs @@ -115,10 +115,10 @@ public class ScriptBlockMemberMethodWrapper /// We use WeakReference object to point to the default SessionState because if GC already collect the SessionState, /// or the Runspace it chains to is closed and disposed, then we cannot run the static method there anyways. /// - /// + /// /// The default SessionState is used only if a static method is called from a Runspace where the PowerShell class is /// never defined, or is called on a thread without a default Runspace. Usage like those should be rare. - /// + /// private readonly WeakReference _defaultSessionStateToUse; /// @@ -162,7 +162,7 @@ internal ScriptBlockMemberMethodWrapper(IParameterMetadataProvider ast) /// Initialization happens when the script that defines PowerShell class is executed. /// This initialization is required only if this wrapper is for a static method. /// - /// + /// /// When the same script file gets executed multiple times, the .NET type generated from the PowerShell class /// defined in the file will be shared in those executions, and thus this method will be called multiple times /// possibly in the contexts of different Runspace/SessionState. @@ -174,7 +174,7 @@ internal ScriptBlockMemberMethodWrapper(IParameterMetadataProvider ast) /// is declared, and thus we can always get the correct SessionState to use by querying the 'SessionStateKeeper'. /// The default SessionState is used only if a static method is called from a Runspace where the class is never /// defined, or is called on a thread without a default Runspace. - /// + /// internal void InitAtRuntime() { if (_isStatic) diff --git a/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs b/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs index 5db4829bb41..42d78e8a930 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs @@ -1210,10 +1210,10 @@ internal Pipe GetRedirectionPipe(ExecutionContext context, PipelineProcessor par /// After file redirection is done, we need to call 'DoComplete' on the pipeline processor, /// so that 'EndProcessing' of Out-File can be called to wrap up the file write operation. /// - /// + /// /// 'StartStepping' is called after creating the pipeline processor. /// 'Step' is called when an object is added to the pipe created with the pipeline processor. - /// + /// internal void CallDoCompleteForExpression() { // The pipe returned from 'GetRedirectionPipe' could be a NullPipe diff --git a/src/System.Management.Automation/help/HelpCommands.cs b/src/System.Management.Automation/help/HelpCommands.cs index 8164b6e5932..5bde9be118f 100644 --- a/src/System.Management.Automation/help/HelpCommands.cs +++ b/src/System.Management.Automation/help/HelpCommands.cs @@ -737,8 +737,8 @@ public static class GetHelpCodeMethods { /// /// Checks whether the default runspace associated with the current thread has the standard Get-Help cmdlet. - /// - /// True if Get-Help is found, false otherwise. + /// + /// True if Get-Help is found, false otherwise. private static bool DoesCurrentRunspaceIncludeCoreHelpCmdlet() { InitialSessionState iss = Runspace.DefaultRunspace.InitialSessionState; diff --git a/src/System.Management.Automation/help/HelpSystem.cs b/src/System.Management.Automation/help/HelpSystem.cs index a7c86bd5ebd..8880e022cac 100644 --- a/src/System.Management.Automation/help/HelpSystem.cs +++ b/src/System.Management.Automation/help/HelpSystem.cs @@ -903,12 +903,12 @@ internal enum HelpCategory /// All = 0xFFFFF, - /// + /// /// Default Help. /// DefaultHelp = 0x1000, - /// + /// /// Help for a Configuration. /// Configuration = 0x4000, diff --git a/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs b/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs index 1c0576c95b6..2d62970da82 100644 --- a/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs +++ b/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs @@ -899,6 +899,7 @@ public enum UpdateHelpScope { /// /// Save the help content to the user directory. + /// CurrentUser, /// diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index 0ffc79ff6c4..c594b3951b0 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -2102,7 +2102,7 @@ protected override void RenameItem( /// /// The path of the file or directory to create. /// - /// + /// /// Specify "file" to create a file. /// Specify "directory" or "container" to create a directory. /// diff --git a/src/System.Management.Automation/namespaces/ProviderBase.cs b/src/System.Management.Automation/namespaces/ProviderBase.cs index 2eebb56e750..259bfd7fee9 100644 --- a/src/System.Management.Automation/namespaces/ProviderBase.cs +++ b/src/System.Management.Automation/namespaces/ProviderBase.cs @@ -223,7 +223,7 @@ internal object StartDynamicParameters(CmdletProviderContext cmdletProviderConte /// /// /// The context under which this method is being called. - /// + /// internal void Stop(CmdletProviderContext cmdletProviderContext) { Context = cmdletProviderContext; diff --git a/src/System.Management.Automation/namespaces/TransactedRegistryKey.cs b/src/System.Management.Automation/namespaces/TransactedRegistryKey.cs index 32fce575a1b..19e05ce99a7 100644 --- a/src/System.Management.Automation/namespaces/TransactedRegistryKey.cs +++ b/src/System.Management.Automation/namespaces/TransactedRegistryKey.cs @@ -341,11 +341,11 @@ public void Dispose() /// /// Creates a new subkey, or opens an existing one. /// Utilizes Transaction.Current for its transaction. + /// /// Name or path to subkey to create or open. Cannot be null or an empty string, /// otherwise an ArgumentException is thrown. /// A TransactedRegistryKey object for the subkey, which is associated with Transaction.Current. /// returns null if the operation failed. - /// [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey @@ -358,13 +358,13 @@ public TransactedRegistryKey CreateSubKey(string subkey) /// /// Creates a new subkey, or opens an existing one. /// Utilizes Transaction.Current for its transaction. + /// + /// A TransactedRegistryKey object for the subkey, which is associated with Transaction.Current. + /// returns null if the operation failed. /// Name or path to subkey to create or open. Cannot be null or an empty string, /// otherwise an ArgumentException is thrown. /// One of the Microsoft.Win32.RegistryKeyPermissionCheck values that /// specifies whether the key is opened for read or read/write access. - /// A TransactedRegistryKey object for the subkey, which is associated with Transaction.Current. - /// returns null if the operation failed. - /// [ComVisible(false)] [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] @@ -378,14 +378,14 @@ public TransactedRegistryKey CreateSubKey(string subkey, RegistryKeyPermissionCh /// /// Creates a new subkey, or opens an existing one. /// Utilizes Transaction.Current for its transaction. + /// + /// A TransactedRegistryKey object for the subkey, which is associated with Transaction.Current. + /// returns null if the operation failed. /// Name or path to subkey to create or open. Cannot be null or an empty string, /// otherwise an ArgumentException is thrown. /// One of the Microsoft.Win32.RegistryKeyPermissionCheck values that /// specifies whether the key is opened for read or read/write access. /// A TransactedRegistrySecurity object that specifies the access control security for the new key. - /// A TransactedRegistryKey object for the subkey, which is associated with Transaction.Current. - /// returns null if the operation failed. - /// [ComVisible(false)] [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] @@ -486,9 +486,9 @@ private unsafe TransactedRegistryKey CreateSubKeyInternal(string subkey, Registr /// Deletes the specified subkey. Will throw an exception if the subkey has /// subkeys. To delete a tree of subkeys use, DeleteSubKeyTree. /// Utilizes Transaction.Current for its transaction. - /// The subkey to delete. /// Thrown if the subkey as child subkeys. /// + /// The subkey to delete. [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey @@ -502,14 +502,14 @@ public void DeleteSubKey(string subkey) /// Deletes the specified subkey. Will throw an exception if the subkey has /// subkeys. To delete a tree of subkeys use, DeleteSubKeyTree. /// Utilizes Transaction.Current for its transaction. - /// The subkey to delete. - /// Specify true if an ArgumentException should be thrown if - /// the specified subkey does not exist. If false is specified, a missing subkey does not throw - /// an exception. /// Thrown if the subkey as child subkeys. /// Thrown if true is specified for throwOnMissingSubKey and the /// specified subkey does not exist. /// + /// The subkey to delete. + /// Specify true if an ArgumentException should be thrown if + /// the specified subkey does not exist. If false is specified, a missing subkey does not throw + /// an exception. [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey @@ -567,8 +567,8 @@ public void DeleteSubKey(string subkey, bool throwOnMissingSubKey) /// /// Recursively deletes a subkey and any child subkeys. /// Utilizes Transaction.Current for its transaction. - /// The subkey to delete. /// + /// The subkey to delete. [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey @@ -664,8 +664,8 @@ private void DeleteSubKeyTreeInternal(string subkey) /// /// Deletes the specified value from this key. /// Utilizes Transaction.Current for its transaction. - /// Name of the value to delete. /// + /// Name of the value to delete. [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] public void DeleteValue(string name) @@ -676,11 +676,11 @@ public void DeleteValue(string name) /// /// Deletes the specified value from this key. /// Utilizes Transaction.Current for its transaction. + /// /// Name of the value to delete. /// Specify true if an ArgumentException should be thrown if /// the specified value does not exist. If false is specified, a missing value does not throw /// an exception. - /// [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] public void DeleteValue(string name, bool throwOnMissingValue) @@ -748,10 +748,10 @@ internal static TransactedRegistryKey GetBaseKey(IntPtr hKey) /// Retrieves a subkey. If readonly is true, then the subkey is opened with /// read-only access. /// Utilizes Transaction.Current for its transaction. + /// + /// The subkey requested or null if the operation failed. /// Name or path of the subkey to open. /// Set to true of you only need readonly access. - /// The subkey requested or null if the operation failed. - /// [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey @@ -791,11 +791,11 @@ public TransactedRegistryKey OpenSubKey(string name, bool writable) /// /// Retrieves a subkey. /// Utilizes Transaction.Current for its transaction. + /// + /// The subkey requested or null if the operation failed. /// Name or path of the subkey to open. /// One of the Microsoft.Win32.RegistryKeyPermissionCheck values that specifies /// whether the key is opened for read or read/write access. - /// The subkey requested or null if the operation failed. - /// [ComVisible(false)] [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] @@ -810,12 +810,12 @@ public TransactedRegistryKey OpenSubKey(string name, RegistryKeyPermissionCheck /// /// Retrieves a subkey. /// Utilizes Transaction.Current for its transaction. + /// + /// The subkey requested or null if the operation failed. /// Name or path of the subkey to open. /// One of the Microsoft.Win32.RegistryKeyPermissionCheck values that specifies /// whether the key is opened for read or read/write access. /// A bitwise combination of Microsoft.Win32.RegistryRights values that specifies the desired security access. - /// The subkey requested or null if the operation failed. - /// [ComVisible(false)] [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] @@ -897,9 +897,9 @@ internal TransactedRegistryKey InternalOpenSubKey(string name, bool writable) /// /// Retrieves a subkey for readonly access. /// Utilizes Transaction.Current for its transaction. - /// Name or path of the subkey to open. - /// The subkey requested or null if the operation failed. /// + /// The subkey requested or null if the operation failed. + /// Name or path of the subkey to open. [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey @@ -912,8 +912,8 @@ public TransactedRegistryKey OpenSubKey(string name) /// /// Retrieves the count of subkeys. /// Utilizes Transaction.Current for its transaction. - /// The count of subkeys. /// + /// The count of subkeys. // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] public int SubKeyCount @@ -955,8 +955,8 @@ internal int InternalSubKeyCount() /// /// Retrieves an array of strings containing all the subkey names. /// Utilizes Transaction.Current for its transaction. - /// A string array containing all the subkey names. /// + /// A string array containing all the subkey names. // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] public string[] GetSubKeyNames() @@ -1002,8 +1002,8 @@ internal string[] InternalGetSubKeyNames() /// /// Retrieves the count of values. /// Utilizes Transaction.Current for its transaction. - /// A count of values. /// + /// A count of values. public int ValueCount { get @@ -1039,8 +1039,8 @@ internal int InternalValueCount() /// /// Retrieves an array of strings containing all the value names. /// Utilizes Transaction.Current for its transaction. - /// All the value names. /// + /// All the value names. public string[] GetValueNames() { CheckKeyReadPermission(); @@ -1107,9 +1107,9 @@ public string[] GetValueNames() /// doesn't exist. Utilizes Transaction.Current for its transaction. /// Note that name can be null or "", at which point the /// unnamed or default value of this Registry key is returned, if any. - /// Name of value to retrieve. - /// The data associated with the value. /// + /// The data associated with the value. + /// Name of value to retrieve. public object GetValue(string name) { CheckValueReadPermission(name); @@ -1121,10 +1121,10 @@ public object GetValue(string name) /// doesn't exist. Utilizes Transaction.Current for its transaction. /// Note that name can be null or "", at which point the /// unnamed or default value of this Registry key is returned, if any. + /// + /// The data associated with the value. /// Name of value to retrieve. /// Value to return if name doesn't exist. - /// The data associated with the value. - /// public object GetValue(string name, object defaultValue) { CheckValueReadPermission(name); @@ -1136,12 +1136,12 @@ public object GetValue(string name, object defaultValue) /// doesn't exist. Utilizes Transaction.Current for its transaction. /// Note that name can be null or "", at which point the /// unnamed or default value of this Registry key is returned, if any. + /// + /// The data associated with the value. /// Name of value to retrieve. /// Value to return if name doesn't exist. /// One of the Microsoft.Win32.RegistryValueOptions values that specifies /// optional processing of the retrieved value. - /// The data associated with the value. - /// [ComVisible(false)] public object GetValue(string name, object defaultValue, RegistryValueOptions options) { @@ -1307,9 +1307,9 @@ internal object InternalGetValue(string name, object defaultValue, bool doNotExp /// /// Retrieves the registry data type of the value associated with the specified name. /// Utilizes Transaction.Current for its transaction. - /// The value name whose data type is to be retrieved. - /// A RegistryValueKind value representing the registry data type of the value associated with name. /// + /// A RegistryValueKind value representing the registry data type of the value associated with name. + /// The value name whose data type is to be retrieved. [ComVisible(false)] public RegistryValueKind GetValueKind(string name) { @@ -1353,8 +1353,8 @@ private bool IsWritable() /// /// Retrieves the name of the key. - /// The name of the key. /// + /// The name of the key. public string Name { get @@ -1371,9 +1371,9 @@ private void SetDirty() /// /// Sets the specified value. Utilizes Transaction.Current for its transaction. + /// /// Name of value to store data in. /// Data to store. - /// public void SetValue(string name, object value) { SetValue(name, value, RegistryValueKind.Unknown); @@ -1381,10 +1381,10 @@ public void SetValue(string name, object value) /// /// Sets the specified value. Utilizes Transaction.Current for its transaction. + /// /// Name of value to store data in. /// Data to store. /// The registry data type to use when storing the data. - /// [ComVisible(false)] public unsafe void SetValue(string name, object value, RegistryValueKind valueKind) { @@ -1598,8 +1598,8 @@ private RegistryValueKind CalculateValueKind(object value) */ /// /// Retrieves a string representation of this key. - /// A string representing the key. /// + /// A string representing the key. public override string ToString() { EnsureNotDisposed(); @@ -1609,9 +1609,9 @@ public override string ToString() /// /// Returns the access control security for the current registry key. /// Utilizes Transaction.Current for its transaction. + /// /// A TransactedRegistrySecurity object that describes the access control /// permissions on the registry key represented by the current TransactedRegistryKey. - /// public TransactedRegistrySecurity GetAccessControl() { return GetAccessControl(AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group); @@ -1620,10 +1620,10 @@ public TransactedRegistrySecurity GetAccessControl() /// /// Returns the access control security for the current registry key. /// Utilizes Transaction.Current for its transaction. - /// A bitwise combination of AccessControlSections values that specifies the type of security information to get. + /// /// A TransactedRegistrySecurity object that describes the access control /// permissions on the registry key represented by the current TransactedRegistryKey. - /// + /// A bitwise combination of AccessControlSections values that specifies the type of security information to get. public TransactedRegistrySecurity GetAccessControl(AccessControlSections includeSections) { EnsureNotDisposed(); @@ -1634,8 +1634,8 @@ public TransactedRegistrySecurity GetAccessControl(AccessControlSections include /// /// Applies Windows access control security to an existing registry key. /// Utilizes Transaction.Current for its transaction. - /// A TransactedRegistrySecurity object that specifies the access control security to apply to the current subkey. /// + /// A TransactedRegistrySecurity object that specifies the access control security to apply to the current subkey. public void SetAccessControl(TransactedRegistrySecurity registrySecurity) { EnsureWriteable(); diff --git a/src/System.Management.Automation/namespaces/TransactedRegistrySecurity.cs b/src/System.Management.Automation/namespaces/TransactedRegistrySecurity.cs index 46070ea27c8..8bcf8d76880 100644 --- a/src/System.Management.Automation/namespaces/TransactedRegistrySecurity.cs +++ b/src/System.Management.Automation/namespaces/TransactedRegistrySecurity.cs @@ -37,11 +37,11 @@ public sealed class TransactedRegistryAccessRule : AccessRule /// /// Initializes a new instance of the RegistryAccessRule class, specifying the user or group the rule applies to, /// the access rights, and whether the specified access rights are allowed or denied. + /// /// The user or group the rule applies to. Must be of type SecurityIdentifier or a type such as /// NTAccount that can be converted to type SecurityIdentifier. /// A bitwise combination of Microsoft.Win32.RegistryRights values indicating the rights allowed or denied. /// One of the AccessControlType values indicating whether the rights are allowed or denied. - /// internal TransactedRegistryAccessRule(IdentityReference identity, RegistryRights registryRights, AccessControlType type) : this(identity, (int)registryRights, false, InheritanceFlags.None, PropagationFlags.None, type) { @@ -50,10 +50,10 @@ internal TransactedRegistryAccessRule(IdentityReference identity, RegistryRights /// /// Initializes a new instance of the RegistryAccessRule class, specifying the user or group the rule applies to, /// the access rights, and whether the specified access rights are allowed or denied. + /// /// The name of the user or group the rule applies to. /// A bitwise combination of Microsoft.Win32.RegistryRights values indicating the rights allowed or denied. /// One of the AccessControlType values indicating whether the rights are allowed or denied. - /// internal TransactedRegistryAccessRule(string identity, RegistryRights registryRights, AccessControlType type) : this(new NTAccount(identity), (int)registryRights, false, InheritanceFlags.None, PropagationFlags.None, type) { @@ -62,13 +62,13 @@ internal TransactedRegistryAccessRule(string identity, RegistryRights registryRi /// /// Initializes a new instance of the RegistryAccessRule class, specifying the user or group the rule applies to, /// the access rights, and whether the specified access rights are allowed or denied. + /// /// The user or group the rule applies to. Must be of type SecurityIdentifier or a type such as /// NTAccount that can be converted to type SecurityIdentifier. /// A bitwise combination of Microsoft.Win32.RegistryRights values indicating the rights allowed or denied. /// A bitwise combination of InheritanceFlags flags specifying how access rights are inherited from other objects. /// A bitwise combination of PropagationFlags flags specifying how access rights are propagated to other objects. /// One of the AccessControlType values indicating whether the rights are allowed or denied. - /// public TransactedRegistryAccessRule(IdentityReference identity, RegistryRights registryRights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type) : this(identity, (int)registryRights, false, inheritanceFlags, propagationFlags, type) { @@ -77,12 +77,12 @@ public TransactedRegistryAccessRule(IdentityReference identity, RegistryRights r /// /// Initializes a new instance of the RegistryAccessRule class, specifying the user or group the rule applies to, /// the access rights, and whether the specified access rights are allowed or denied. + /// /// The name of the user or group the rule applies to. /// A bitwise combination of Microsoft.Win32.RegistryRights values indicating the rights allowed or denied. /// A bitwise combination of InheritanceFlags flags specifying how access rights are inherited from other objects. /// A bitwise combination of PropagationFlags flags specifying how access rights are propagated to other objects. /// One of the AccessControlType values indicating whether the rights are allowed or denied. - /// internal TransactedRegistryAccessRule(string identity, RegistryRights registryRights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type) : this(new NTAccount(identity), (int)registryRights, false, inheritanceFlags, propagationFlags, type) { @@ -128,13 +128,13 @@ public sealed class TransactedRegistryAuditRule : AuditRule /// /// Initializes a new instance of the RegistryAuditRule class, specifying the user or group to audit, the rights to /// audit, whether to take inheritance into account, and whether to audit success, failure, or both. + /// /// The user or group the rule applies to. Must be of type SecurityIdentifier or a type such as /// NTAccount that can be converted to type SecurityIdentifier. /// A bitwise combination of RegistryRights values specifying the kinds of access to audit. /// A bitwise combination of InheritanceFlags values specifying whether the audit rule applies to subkeys of the current key. /// A bitwise combination of PropagationFlags values that affect the way an inherited audit rule is propagated to subkeys of the current key. /// A bitwise combination of AuditFlags values specifying whether to audit success, failure, or both. - /// internal TransactedRegistryAuditRule(IdentityReference identity, RegistryRights registryRights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags) : this(identity, (int)registryRights, false, inheritanceFlags, propagationFlags, flags) { @@ -143,12 +143,12 @@ internal TransactedRegistryAuditRule(IdentityReference identity, RegistryRights /// /// Initializes a new instance of the RegistryAuditRule class, specifying the user or group to audit, the rights to /// audit, whether to take inheritance into account, and whether to audit success, failure, or both. + /// /// The name of the user or group the rule applies to. /// A bitwise combination of RegistryRights values specifying the kinds of access to audit. /// A bitwise combination of InheritanceFlags values specifying whether the audit rule applies to subkeys of the current key. /// A bitwise combination of PropagationFlags values that affect the way an inherited audit rule is propagated to subkeys of the current key. /// A bitwise combination of AuditFlags values specifying whether to audit success, failure, or both. - /// internal TransactedRegistryAuditRule(string identity, RegistryRights registryRights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags) : this(new NTAccount(identity), (int)registryRights, false, inheritanceFlags, propagationFlags, flags) { @@ -232,14 +232,14 @@ private static Exception _HandleErrorCode(int errorCode, string name, SafeHandle /// /// Creates a new access control rule for the specified user, with the specified access rights, access control, and flags. + /// + /// A TransactedRegistryAccessRule object representing the specified rights for the specified user. /// An IdentityReference that identifies the user or group the rule applies to. /// A bitwise combination of RegistryRights values specifying the access rights to allow or deny, cast to an integer. /// A Boolean value specifying whether the rule is inherited. /// A bitwise combination of InheritanceFlags values specifying how the rule is inherited by subkeys. /// A bitwise combination of PropagationFlags values that modify the way the rule is inherited by subkeys. Meaningless if the value of inheritanceFlags is InheritanceFlags.None. /// One of the AccessControlType values specifying whether the rights are allowed or denied. - /// A TransactedRegistryAccessRule object representing the specified rights for the specified user. - /// public override AccessRule AccessRuleFactory(IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type) { return new TransactedRegistryAccessRule(identityReference, accessMask, isInherited, inheritanceFlags, propagationFlags, type); @@ -248,15 +248,15 @@ public override AccessRule AccessRuleFactory(IdentityReference identityReference /// /// Creates a new audit rule, specifying the user the rule applies to, the access rights to audit, the inheritance and propagation of the /// rule, and the outcome that triggers the rule. + /// + /// A TransactedRegistryAuditRule object representing the specified audit rule for the specified user, with the specified flags. + /// The return type of the method is the base class, AuditRule, but the return value can be cast safely to the derived class. /// An IdentityReference that identifies the user or group the rule applies to. /// A bitwise combination of RegistryRights values specifying the access rights to audit, cast to an integer. /// A Boolean value specifying whether the rule is inherited. /// A bitwise combination of InheritanceFlags values specifying how the rule is inherited by subkeys. /// A bitwise combination of PropagationFlags values that modify the way the rule is inherited by subkeys. Meaningless if the value of inheritanceFlags is InheritanceFlags.None. /// A bitwise combination of AuditFlags values specifying whether to audit successful access, failed access, or both. - /// A TransactedRegistryAuditRule object representing the specified audit rule for the specified user, with the specified flags. - /// The return type of the method is the base class, AuditRule, but the return value can be cast safely to the derived class. - /// public override AuditRule AuditRuleFactory(IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags) { return new TransactedRegistryAuditRule(identityReference, accessMask, isInherited, inheritanceFlags, propagationFlags, flags); @@ -301,8 +301,8 @@ internal void Persist(SafeRegistryHandle hKey, string keyName) /// /// Searches for a matching access control with which the new rule can be merged. If none are found, adds the new rule. - /// The access control rule to add. /// + /// The access control rule to add. // Suppressed because we want to ensure TransactedRegistry* objects. [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] public void AddAccessRule(TransactedRegistryAccessRule rule) @@ -312,8 +312,8 @@ public void AddAccessRule(TransactedRegistryAccessRule rule) /// /// Removes all access control rules with the same user and AccessControlType (allow or deny) as the specified rule, and then adds the specified rule. - /// The TransactedRegistryAccessRule to add. The user and AccessControlType of this rule determine the rules to remove before this rule is added. /// + /// The TransactedRegistryAccessRule to add. The user and AccessControlType of this rule determine the rules to remove before this rule is added. // Suppressed because we want to ensure TransactedRegistry* objects. [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] public void SetAccessRule(TransactedRegistryAccessRule rule) @@ -323,8 +323,8 @@ public void SetAccessRule(TransactedRegistryAccessRule rule) /// /// Removes all access control rules with the same user as the specified rule, regardless of AccessControlType, and then adds the specified rule. - /// The TransactedRegistryAccessRule to add. The user specified by this rule determines the rules to remove before this rule is added. /// + /// The TransactedRegistryAccessRule to add. The user specified by this rule determines the rules to remove before this rule is added. // Suppressed because we want to ensure TransactedRegistry* objects. [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] public void ResetAccessRule(TransactedRegistryAccessRule rule) @@ -335,9 +335,9 @@ public void ResetAccessRule(TransactedRegistryAccessRule rule) /// /// Searches for an access control rule with the same user and AccessControlType (allow or deny) as the specified access rule, and with compatible /// inheritance and propagation flags; if such a rule is found, the rights contained in the specified access rule are removed from it. + /// /// A TransactedRegistryAccessRule that specifies the user and AccessControlType to search for, and a set of inheritance /// and propagation flags that a matching rule, if found, must be compatible with. Specifies the rights to remove from the compatible rule, if found. - /// // Suppressed because we want to ensure TransactedRegistry* objects. [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] public bool RemoveAccessRule(TransactedRegistryAccessRule rule) @@ -347,9 +347,9 @@ public bool RemoveAccessRule(TransactedRegistryAccessRule rule) /// /// Searches for all access control rules with the same user and AccessControlType (allow or deny) as the specified rule and, if found, removes them. + /// /// A TransactedRegistryAccessRule that specifies the user and AccessControlType to search for. Any rights, inheritance flags, or /// propagation flags specified by this rule are ignored. - /// // Suppressed because we want to ensure TransactedRegistry* objects. [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] public void RemoveAccessRuleAll(TransactedRegistryAccessRule rule) @@ -359,8 +359,8 @@ public void RemoveAccessRuleAll(TransactedRegistryAccessRule rule) /// /// Searches for an access control rule that exactly matches the specified rule and, if found, removes it. - /// The TransactedRegistryAccessRule to remove. /// + /// The TransactedRegistryAccessRule to remove. // Suppressed because we want to ensure TransactedRegistry* objects. [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] public void RemoveAccessRuleSpecific(TransactedRegistryAccessRule rule) @@ -370,8 +370,8 @@ public void RemoveAccessRuleSpecific(TransactedRegistryAccessRule rule) /// /// Searches for an audit rule with which the new rule can be merged. If none are found, adds the new rule. - /// The audit rule to add. The user specified by this rule determines the search. /// + /// The audit rule to add. The user specified by this rule determines the search. // Suppressed because we want to ensure TransactedRegistry* objects. [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] public void AddAuditRule(TransactedRegistryAuditRule rule) @@ -381,8 +381,8 @@ public void AddAuditRule(TransactedRegistryAuditRule rule) /// /// Removes all audit rules with the same user as the specified rule, regardless of the AuditFlags value, and then adds the specified rule. - /// The TransactedRegistryAuditRule to add. The user specified by this rule determines the rules to remove before this rule is added. /// + /// The TransactedRegistryAuditRule to add. The user specified by this rule determines the rules to remove before this rule is added. // Suppressed because we want to ensure TransactedRegistry* objects. [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] public void SetAuditRule(TransactedRegistryAuditRule rule) @@ -393,9 +393,9 @@ public void SetAuditRule(TransactedRegistryAuditRule rule) /// /// Searches for an audit control rule with the same user as the specified rule, and with compatible inheritance and propagation flags; /// if a compatible rule is found, the rights contained in the specified rule are removed from it. + /// /// A TransactedRegistryAuditRule that specifies the user to search for, and a set of inheritance and propagation flags that /// a matching rule, if found, must be compatible with. Specifies the rights to remove from the compatible rule, if found. - /// // Suppressed because we want to ensure TransactedRegistry* objects. [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] public bool RemoveAuditRule(TransactedRegistryAuditRule rule) @@ -405,9 +405,9 @@ public bool RemoveAuditRule(TransactedRegistryAuditRule rule) /// /// Searches for all audit rules with the same user as the specified rule and, if found, removes them. + /// /// A TransactedRegistryAuditRule that specifies the user to search for. Any rights, inheritance /// flags, or propagation flags specified by this rule are ignored. - /// // Suppressed because we want to ensure TransactedRegistry* objects. [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] public void RemoveAuditRuleAll(TransactedRegistryAuditRule rule) @@ -417,8 +417,8 @@ public void RemoveAuditRuleAll(TransactedRegistryAuditRule rule) /// /// Searches for an audit rule that exactly matches the specified rule and, if found, removes it. - /// The TransactedRegistryAuditRule to be removed. /// + /// The TransactedRegistryAuditRule to be removed. // Suppressed because we want to ensure TransactedRegistry* objects. [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] public void RemoveAuditRuleSpecific(TransactedRegistryAuditRule rule) @@ -428,8 +428,8 @@ public void RemoveAuditRuleSpecific(TransactedRegistryAuditRule rule) /// /// Gets the enumeration type that the TransactedRegistrySecurity class uses to represent access rights. - /// A Type object representing the RegistryRights enumeration. /// + /// A Type object representing the RegistryRights enumeration. public override Type AccessRightType { get { return typeof(RegistryRights); } @@ -437,8 +437,8 @@ public override Type AccessRightType /// /// Gets the type that the TransactedRegistrySecurity class uses to represent access rules. - /// A Type object representing the TransactedRegistryAccessRule class. /// + /// A Type object representing the TransactedRegistryAccessRule class. public override Type AccessRuleType { get { return typeof(TransactedRegistryAccessRule); } @@ -446,8 +446,8 @@ public override Type AccessRuleType /// /// Gets the type that the TransactedRegistrySecurity class uses to represent audit rules. - /// A Type object representing the TransactedRegistryAuditRule class. /// + /// A Type object representing the TransactedRegistryAuditRule class. public override Type AuditRuleType { get { return typeof(TransactedRegistryAuditRule); } diff --git a/src/System.Management.Automation/utils/CryptoUtils.cs b/src/System.Management.Automation/utils/CryptoUtils.cs index 390f66884bf..ca68766d12b 100644 --- a/src/System.Management.Automation/utils/CryptoUtils.cs +++ b/src/System.Management.Automation/utils/CryptoUtils.cs @@ -43,7 +43,7 @@ internal static class PSCryptoNativeConverter /// public const uint PUBLICKEYBLOB = 0x00000006; - /// + /// /// PUBLICKEYBLOB header length. /// public const int PUBLICKEYBLOB_HEADER_LEN = 20; @@ -53,7 +53,7 @@ internal static class PSCryptoNativeConverter /// public const uint SIMPLEBLOB = 0x00000001; - /// + /// /// SIMPLEBLOB header length. /// public const int SIMPLEBLOB_HEADER_LEN = 12; diff --git a/src/System.Management.Automation/utils/Verbs.cs b/src/System.Management.Automation/utils/Verbs.cs index c6019047fb9..21ef9cbad22 100644 --- a/src/System.Management.Automation/utils/Verbs.cs +++ b/src/System.Management.Automation/utils/Verbs.cs @@ -387,9 +387,9 @@ public static class VerbsLifecycle /// public const string Invoke = "Invoke"; - /// + /// /// Record details about an item in a public store or publishing location - /// + /// public const string Register = "Register"; /// @@ -397,9 +397,9 @@ public static class VerbsLifecycle /// public const string Request = "Request"; - /// + /// /// Terminate existing activity and begin it again (with the same configuration) - /// + /// public const string Restart = "Restart"; /// @@ -412,9 +412,9 @@ public static class VerbsLifecycle /// public const string Start = "Start"; - /// + /// ///Discontinue or cease an activity - /// + /// public const string Stop = "Stop"; /// @@ -432,14 +432,14 @@ public static class VerbsLifecycle /// public const string Uninstall = "Uninstall"; - /// + /// /// Remove details of an item from a public store or publishing location - /// + /// public const string Unregister = "Unregister"; - /// + /// /// Suspend execution until an expected event - /// + /// public const string Wait = "Wait"; } From a1fd61d83ee62e7872d70a3ae62598bca8630875 Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Wed, 4 Jan 2023 09:57:02 -0800 Subject: [PATCH 275/779] Fix support for nanoserver due to lack of AMSI (#18882) --- .../security/SecuritySupport.cs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/src/System.Management.Automation/security/SecuritySupport.cs b/src/System.Management.Automation/security/SecuritySupport.cs index 16d6ca3afee..0892465804d 100644 --- a/src/System.Management.Automation/security/SecuritySupport.cs +++ b/src/System.Management.Automation/security/SecuritySupport.cs @@ -1338,7 +1338,17 @@ internal static class AmsiUtils static AmsiUtils() { #if !UNIX - s_amsiInitFailed = !CheckAmsiInit(); + try + { + s_amsiInitFailed = !CheckAmsiInit(); + } + catch (DllNotFoundException) + { + PSEtwLog.LogAmsiUtilStateEvent("DllNotFoundException", $"{s_amsiContext}-{s_amsiSession}"); + s_amsiInitFailed = true; + return; + } + PSEtwLog.LogAmsiUtilStateEvent($"init-{s_amsiInitFailed}", $"{s_amsiContext}-{s_amsiSession}"); #endif } From eb31d32724c96223d86b9c4112f9c47df1d93c6d Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Thu, 5 Jan 2023 09:51:45 -0800 Subject: [PATCH 276/779] Enable creating composite subsystem implementation in modules (#18888) --- .../PowerShellCore_format_ps1xml.cs | 19 +++ .../DscSubsystem/ICrossPlatformDsc.cs | 5 - .../FeedbackSubsystem/IFeedbackProvider.cs | 7 - .../engine/Subsystem/ISubsystem.cs | 19 +-- .../PredictionSubsystem/ICommandPredictor.cs | 5 - .../engine/Subsystem/SubsystemInfo.cs | 46 +++--- .../engine/Subsystem/SubsystemManager.cs | 28 ++-- .../engine/Utils.cs | 14 -- .../resources/SubsystemStrings.resx | 10 +- test/xUnit/csharp/test_Subsystem.cs | 143 +++++++++++++++--- 10 files changed, 198 insertions(+), 98 deletions(-) diff --git a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs index 72a1c870cd7..549a4e6d4b7 100644 --- a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs +++ b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs @@ -137,6 +137,10 @@ internal static IEnumerable GetFormatData() "System.Management.Automation.Subsystem.SubsystemInfo", ViewsOf_System_Management_Automation_Subsystem_SubsystemInfo()); + yield return new ExtendedTypeDefinition( + "System.Management.Automation.Subsystem.SubsystemInfo+ImplementationInfo", + ViewsOf_System_Management_Automation_Subsystem_SubsystemInfo_ImplementationInfo()); + yield return new ExtendedTypeDefinition( "System.Management.Automation.ShellVariable", ViewsOf_System_Management_Automation_ShellVariable()); @@ -774,6 +778,21 @@ private static IEnumerable ViewsOf_System_Management_Autom .EndTable()); } + private static IEnumerable ViewsOf_System_Management_Automation_Subsystem_SubsystemInfo_ImplementationInfo() + { + yield return new FormatViewDefinition( + "System.Management.Automation.Subsystem.SubsystemInfo+ImplementationInfo", + ListControl.Create() + .StartEntry() + .AddItemProperty(@"Id") + .AddItemProperty(@"Kind") + .AddItemProperty(@"Name") + .AddItemProperty(@"Description") + .AddItemProperty(@"ImplementationType") + .EndEntry() + .EndList()); + } + private static IEnumerable ViewsOf_System_Management_Automation_ShellVariable() { yield return new FormatViewDefinition("ShellVariable", diff --git a/src/System.Management.Automation/engine/Subsystem/DscSubsystem/ICrossPlatformDsc.cs b/src/System.Management.Automation/engine/Subsystem/DscSubsystem/ICrossPlatformDsc.cs index f16c6f245a3..d1fe2234309 100644 --- a/src/System.Management.Automation/engine/Subsystem/DscSubsystem/ICrossPlatformDsc.cs +++ b/src/System.Management.Automation/engine/Subsystem/DscSubsystem/ICrossPlatformDsc.cs @@ -15,11 +15,6 @@ namespace System.Management.Automation.Subsystem.DSC /// public interface ICrossPlatformDsc : ISubsystem { - /// - /// Subsystem kind. - /// - SubsystemKind ISubsystem.Kind => SubsystemKind.CrossPlatformDsc; - /// /// Default implementation. No function is required for this subsystem. /// diff --git a/src/System.Management.Automation/engine/Subsystem/FeedbackSubsystem/IFeedbackProvider.cs b/src/System.Management.Automation/engine/Subsystem/FeedbackSubsystem/IFeedbackProvider.cs index a254cd9b013..ba6d4f8433b 100644 --- a/src/System.Management.Automation/engine/Subsystem/FeedbackSubsystem/IFeedbackProvider.cs +++ b/src/System.Management.Automation/engine/Subsystem/FeedbackSubsystem/IFeedbackProvider.cs @@ -24,11 +24,6 @@ public interface IFeedbackProvider : ISubsystem /// Dictionary? ISubsystem.FunctionsToDefine => null; - /// - /// Default implementation for `ISubsystem.Kind`. - /// - SubsystemKind ISubsystem.Kind => SubsystemKind.FeedbackProvider; - /// /// Gets feedback based on the given commandline and error record. /// @@ -123,8 +118,6 @@ internal UnixCommandNotFound() Dictionary? ISubsystem.FunctionsToDefine => null; - SubsystemKind ISubsystem.Kind => SubsystemKind.FeedbackProvider | SubsystemKind.CommandPredictor; - public Guid Id => _guid; public string Name => "cmd-not-found"; diff --git a/src/System.Management.Automation/engine/Subsystem/ISubsystem.cs b/src/System.Management.Automation/engine/Subsystem/ISubsystem.cs index e8937486d41..72b8a55d148 100644 --- a/src/System.Management.Automation/engine/Subsystem/ISubsystem.cs +++ b/src/System.Management.Automation/engine/Subsystem/ISubsystem.cs @@ -10,9 +10,11 @@ namespace System.Management.Automation.Subsystem { /// /// Define the kinds of subsystems. - /// Allow composite enum values to enable one subsystem implementation to serve as multiple subystems. /// - [Flags] + /// + /// This enum uses power of 2 as the values for the enum elements, so as to make sure + /// the bitwise 'or' operation of the elements always results in an invalid value. + /// public enum SubsystemKind : uint { /// @@ -36,12 +38,8 @@ public enum SubsystemKind : uint /// The API contracts for specific subsystems are defined within the specific interfaces/abstract classes that implements this interface. /// /// - /// There are two purposes to have the internal member `Kind` declared in 'ISubsystem': - /// 1. Make the mapping from an `ISubsystem` implementation to the `SubsystemKind` easy; - /// 2. Make sure a user cannot directly implement 'ISubsystem', but have to derive from one of the concrete subsystem interface or abstract class. - /// - /// The internal member needs to have a default implementation defined by the specific subsystem interfaces or abstract class, - /// because it should be the same for a specific kind of subsystem. + /// A user should not directly implement , but instead should derive from one of the concrete subsystem interfaces or abstract classes. + /// The instance of a type that only implements 'ISubsystem' cannot be registered to the . /// public interface ISubsystem { @@ -65,10 +63,5 @@ public interface ISubsystem /// Key: function name; Value: function script. /// Dictionary? FunctionsToDefine { get; } - - /// - /// Gets the subsystem kind. - /// - internal SubsystemKind Kind { get; } } } diff --git a/src/System.Management.Automation/engine/Subsystem/PredictionSubsystem/ICommandPredictor.cs b/src/System.Management.Automation/engine/Subsystem/PredictionSubsystem/ICommandPredictor.cs index bd8a48a85db..d528067452c 100644 --- a/src/System.Management.Automation/engine/Subsystem/PredictionSubsystem/ICommandPredictor.cs +++ b/src/System.Management.Automation/engine/Subsystem/PredictionSubsystem/ICommandPredictor.cs @@ -21,11 +21,6 @@ public interface ICommandPredictor : ISubsystem /// Dictionary? ISubsystem.FunctionsToDefine => null; - /// - /// Default implementation for `ISubsystem.Kind`. - /// - SubsystemKind ISubsystem.Kind => SubsystemKind.CommandPredictor; - /// /// Get the predictive suggestions. It indicates the start of a suggestion rendering session. /// diff --git a/src/System.Management.Automation/engine/Subsystem/SubsystemInfo.cs b/src/System.Management.Automation/engine/Subsystem/SubsystemInfo.cs index e8d8fe39eae..c290e807ce4 100644 --- a/src/System.Management.Automation/engine/Subsystem/SubsystemInfo.cs +++ b/src/System.Management.Automation/engine/Subsystem/SubsystemInfo.cs @@ -18,22 +18,22 @@ public abstract class SubsystemInfo #region "Metadata of a Subsystem (public)" /// - /// The kind of a concrete subsystem. + /// Gets the kind of a concrete subsystem. /// public SubsystemKind Kind { get; } /// - /// The type of a concrete subsystem. + /// Gets the type of a concrete subsystem. /// public Type SubsystemType { get; } /// - /// Indicate whether the subsystem allows to unregister an implementation. + /// Gets a value indicating whether the subsystem allows to unregister an implementation. /// public bool AllowUnregistration { get; private set; } /// - /// Indicate whether the subsystem allows to have multiple implementations registered. + /// Gets a value indicating whether the subsystem allows to have multiple implementations registered. /// public bool AllowMultipleRegistration { get; private set; } @@ -78,8 +78,6 @@ public abstract class SubsystemInfo private protected SubsystemInfo(SubsystemKind kind, Type subsystemType) { - Requires.OneSpecificSubsystemKind(kind); - _syncObj = new object(); _cachedImplInfos = Utils.EmptyReadOnlyCollection(); @@ -161,10 +159,10 @@ internal static SubsystemInfo Create( /// public class ImplementationInfo { - internal ImplementationInfo(ISubsystem implementation) + internal ImplementationInfo(SubsystemKind kind, ISubsystem implementation) { Id = implementation.Id; - Kind = implementation.Kind; + Kind = kind; Name = implementation.Name; Description = implementation.Description; ImplementationType = implementation.GetType(); @@ -219,6 +217,7 @@ internal SubsystemInfoImpl(SubsystemKind kind) /// In the subsystem scenario, registration operations will be minimum, and in most cases, the registered /// implementation will never be unregistered, so optimization for reading is more important. /// + /// The subsystem implementation to be added. private protected override void AddImplementation(ISubsystem rawImpl) { lock (_syncObj) @@ -228,7 +227,7 @@ private protected override void AddImplementation(ISubsystem rawImpl) if (_registeredImpls.Count == 0) { _registeredImpls = new ReadOnlyCollection(new[] { impl }); - _cachedImplInfos = new ReadOnlyCollection(new[] { new ImplementationInfo(impl) }); + _cachedImplInfos = new ReadOnlyCollection(new[] { new ImplementationInfo(Kind, impl) }); return; } @@ -252,12 +251,17 @@ private protected override void AddImplementation(ISubsystem rawImpl) } } - var list = new List(_registeredImpls.Count + 1); - list.AddRange(_registeredImpls); - list.Add(impl); + int newCapacity = _registeredImpls.Count + 1; + var implList = new List(newCapacity); + implList.AddRange(_registeredImpls); + implList.Add(impl); + + var implInfo = new List(newCapacity); + implInfo.AddRange(_cachedImplInfos); + implInfo.Add(new ImplementationInfo(Kind, impl)); - _registeredImpls = new ReadOnlyCollection(list); - _cachedImplInfos = new ReadOnlyCollection(list.ConvertAll(static s => new ImplementationInfo(s))); + _registeredImpls = new ReadOnlyCollection(implList); + _cachedImplInfos = new ReadOnlyCollection(implInfo); } } @@ -270,6 +274,8 @@ private protected override void AddImplementation(ISubsystem rawImpl) /// In the subsystem scenario, registration operations will be minimum, and in most cases, the registered /// implementation will never be unregistered, so optimization for reading is more important. /// + /// The id of the subsystem implementation to be removed. + /// The subsystem implementation that was removed. private protected override ISubsystem RemoveImplementation(Guid id) { if (!AllowUnregistration) @@ -316,7 +322,10 @@ private protected override ISubsystem RemoveImplementation(Guid id) } else { - var list = new List(_registeredImpls.Count - 1); + int newCapacity = _registeredImpls.Count - 1; + var implList = new List(newCapacity); + var implInfo = new List(newCapacity); + for (int i = 0; i < _registeredImpls.Count; i++) { if (index == i) @@ -324,11 +333,12 @@ private protected override ISubsystem RemoveImplementation(Guid id) continue; } - list.Add(_registeredImpls[i]); + implList.Add(_registeredImpls[i]); + implInfo.Add(_cachedImplInfos[i]); } - _registeredImpls = new ReadOnlyCollection(list); - _cachedImplInfos = new ReadOnlyCollection(list.ConvertAll(static s => new ImplementationInfo(s))); + _registeredImpls = new ReadOnlyCollection(implList); + _cachedImplInfos = new ReadOnlyCollection(implInfo); } return target; diff --git a/src/System.Management.Automation/engine/Subsystem/SubsystemManager.cs b/src/System.Management.Automation/engine/Subsystem/SubsystemManager.cs index 501bebcaddc..1af41a67457 100644 --- a/src/System.Management.Automation/engine/Subsystem/SubsystemManager.cs +++ b/src/System.Management.Automation/engine/Subsystem/SubsystemManager.cs @@ -139,9 +139,12 @@ public static SubsystemInfo GetSubsystemInfo(Type subsystemType) } throw new ArgumentException( - StringUtil.Format( - SubsystemStrings.SubsystemTypeUnknown, - subsystemType.FullName)); + subsystemType == typeof(ISubsystem) + ? SubsystemStrings.MustUseConcreteSubsystemType + : StringUtil.Format( + SubsystemStrings.SubsystemTypeUnknown, + subsystemType.FullName), + nameof(subsystemType)); } /// @@ -151,8 +154,6 @@ public static SubsystemInfo GetSubsystemInfo(Type subsystemType) /// The object that represents the concrete subsystem. public static SubsystemInfo GetSubsystemInfo(SubsystemKind kind) { - Requires.OneSpecificSubsystemKind(kind); - if (s_subSystemKindMap.TryGetValue(kind, out SubsystemInfo? subsystemInfo)) { return subsystemInfo; @@ -161,7 +162,8 @@ public static SubsystemInfo GetSubsystemInfo(SubsystemKind kind) throw new ArgumentException( StringUtil.Format( SubsystemStrings.SubsystemKindUnknown, - kind.ToString())); + kind.ToString()), + nameof(kind)); } #endregion @@ -191,19 +193,19 @@ public static void RegisterSubsystem(TImple public static void RegisterSubsystem(SubsystemKind kind, ISubsystem proxy) { Requires.NotNull(proxy, nameof(proxy)); - Requires.OneSpecificSubsystemKind(kind); - if (!proxy.Kind.HasFlag(kind)) + SubsystemInfo info = GetSubsystemInfo(kind); + if (!info.SubsystemType.IsAssignableFrom(proxy.GetType())) { throw new ArgumentException( StringUtil.Format( - SubsystemStrings.ImplementationMismatch, - proxy.Kind.ToString(), - kind.ToString()), + SubsystemStrings.ConcreteSubsystemNotImplemented, + kind.ToString(), + info.SubsystemType.Name), nameof(proxy)); } - RegisterSubsystem(GetSubsystemInfo(kind), proxy); + RegisterSubsystem(info, proxy); } private static void RegisterSubsystem(SubsystemInfo subsystemInfo, ISubsystem proxy) @@ -278,8 +280,6 @@ public static void UnregisterSubsystem(Guid id) /// The Id of the implementation to be unregistered. public static void UnregisterSubsystem(SubsystemKind kind, Guid id) { - Requires.OneSpecificSubsystemKind(kind); - UnregisterSubsystem(GetSubsystemInfo(kind), id); } diff --git a/src/System.Management.Automation/engine/Utils.cs b/src/System.Management.Automation/engine/Utils.cs index 295b7f931ed..99eaf7678ed 100644 --- a/src/System.Management.Automation/engine/Utils.cs +++ b/src/System.Management.Automation/engine/Utils.cs @@ -1768,19 +1768,5 @@ internal static void Condition([DoesNotReturnIf(false)] bool precondition, strin throw new ArgumentException(paramName); } } - - internal static void OneSpecificSubsystemKind(Subsystem.SubsystemKind kind) - { - uint value = (uint)kind; - if (value == 0 || (value & (value - 1)) != 0) - { - // The value is either invalid or a composite value because it's not power of 2. - throw new ArgumentException( - StringUtil.Format( - SubsystemStrings.RequireOneSpecificSubsystemKind, - kind.ToString()), - nameof(kind)); - } - } } } diff --git a/src/System.Management.Automation/resources/SubsystemStrings.resx b/src/System.Management.Automation/resources/SubsystemStrings.resx index 1ca0453ae31..14ff340bed1 100644 --- a/src/System.Management.Automation/resources/SubsystemStrings.resx +++ b/src/System.Management.Automation/resources/SubsystemStrings.resx @@ -135,11 +135,14 @@ The specified subsystem type '{0}' is unknown. + + You must specify a concrete subsystem type instead of the base interface 'ISubsystem'. + The specified subsystem kind '{0}' is unknown. - - The specified implementation instance implements the subsystem '{0}', which does not match the target subsystem '{1}'. + + For the target subsystem kind '{0}', the specified subsystem instance needs to implement the corresponding concrete interface or abstract class '{1}'. The declared metadata for subsystem kind '{0}' is invalid. A subsystem that requires cmdlets or functions to be defined cannot allow multiple registrations because that would result in one implementation overwriting the commands defined by another implementation. @@ -153,7 +156,4 @@ The 'Description' property of an implementation for the subsystem '{0}' cannot be null or an empty string. - - The subsystem kind here should represent one specific subsystem, but the given value is either invalid or a composite enum value: '{0}'. - diff --git a/test/xUnit/csharp/test_Subsystem.cs b/test/xUnit/csharp/test_Subsystem.cs index 11ac9d55419..724c8747e5a 100644 --- a/test/xUnit/csharp/test_Subsystem.cs +++ b/test/xUnit/csharp/test_Subsystem.cs @@ -2,7 +2,9 @@ // Licensed under the MIT License. using System; +using System.Collections.Generic; using System.Collections.ObjectModel; +using System.Management.Automation; using System.Management.Automation.Subsystem; using System.Management.Automation.Subsystem.DSC; using System.Management.Automation.Subsystem.Feedback; @@ -12,6 +14,78 @@ namespace PSTests.Sequential { + public class MyInvalidSubsystem : ISubsystem + { + private readonly Guid _id; + + public static readonly MyInvalidSubsystem Singleton; + + static MyInvalidSubsystem() + { + Singleton = new MyInvalidSubsystem(Guid.NewGuid()); + } + + private MyInvalidSubsystem(Guid id) + { + _id = id; + } + + public Guid Id => _id; + + public string Name => "Invalid"; + + public string Description => "An invalid subsystem implementation"; + + public Dictionary FunctionsToDefine => null; + } + + public class MyCompositeSubsystem : ICommandPredictor, IFeedbackProvider + { + private readonly Guid _id; + + public static readonly MyCompositeSubsystem Singleton; + + static MyCompositeSubsystem() + { + Singleton = new MyCompositeSubsystem(Guid.NewGuid()); + } + + private MyCompositeSubsystem(Guid id) + { + _id = id; + } + + public Guid Id => _id; + + public string Name => "Composite"; + + public string Description => "A composite implementation that serves as both a feedback provider and a command predictor."; + + Dictionary ISubsystem.FunctionsToDefine => null; + + #region IFeedbackProvider + + public string GetFeedback(string commandLine, ErrorRecord errorRecord, CancellationToken token) => "nothing"; + + #endregion + + #region ICommandPredictor + + public bool CanAcceptFeedback(PredictionClient client, PredictorFeedbackKind feedback) => false; + + public SuggestionPackage GetSuggestion(PredictionClient client, PredictionContext context, CancellationToken cancellationToken) => default; + + public void OnCommandLineAccepted(PredictionClient client, IReadOnlyList history) { } + + public void OnSuggestionDisplayed(PredictionClient client, uint session, int countOrIndex) { } + + public void OnSuggestionAccepted(PredictionClient client, uint session, string acceptedSuggestion) { } + + public void OnCommandLineExecuted(PredictionClient client, string commandLine, bool success) { } + + #endregion + } + public static class SubsystemTests { private static readonly MyPredictor predictor1, predictor2; @@ -106,26 +180,62 @@ public static void GetSubsystemInfo() } [Fact] - public static void RegisterSubsystem() + public static void RegisterSubsystemExpectedFailures() + { + Assert.Throws( + paramName: "proxy", + () => SubsystemManager.RegisterSubsystem(null)); + Assert.Throws( + paramName: "proxy", + () => SubsystemManager.RegisterSubsystem(SubsystemKind.CommandPredictor, null)); + + ArgumentException ex = Assert.Throws( + paramName: "proxy", + () => SubsystemManager.RegisterSubsystem(SubsystemKind.CrossPlatformDsc, predictor1)); + Assert.Contains(nameof(ICrossPlatformDsc), ex.Message); + + ex = Assert.Throws( + paramName: "kind", + () => SubsystemManager.RegisterSubsystem((SubsystemKind)0, predictor1)); + Assert.Contains("0", ex.Message); + + ex = Assert.Throws( + paramName: "kind", + () => SubsystemManager.RegisterSubsystem(SubsystemKind.CommandPredictor | SubsystemKind.CrossPlatformDsc, predictor1)); + Assert.Contains("3", ex.Message); + + // You cannot register the instance of a type that only implements 'ISubsystem'. + ex = Assert.Throws( + paramName: "proxy", + () => SubsystemManager.RegisterSubsystem(SubsystemKind.CommandPredictor, MyInvalidSubsystem.Singleton)); + Assert.Contains(nameof(ICommandPredictor), ex.Message); + + ex = Assert.Throws( + paramName: "subsystemType", + () => SubsystemManager.RegisterSubsystem(MyInvalidSubsystem.Singleton)); + Assert.Contains(nameof(ISubsystem), ex.Message); + } + + [Fact] + public static void RegisterSubsystemForCompositeImplementation() { try { - Assert.Throws( - paramName: "proxy", - () => SubsystemManager.RegisterSubsystem(null)); - Assert.Throws( - paramName: "proxy", - () => SubsystemManager.RegisterSubsystem(SubsystemKind.CommandPredictor, null)); - Assert.Throws( - paramName: "proxy", - () => SubsystemManager.RegisterSubsystem(SubsystemKind.CrossPlatformDsc, predictor1)); - Assert.Throws( - paramName: "kind", - () => SubsystemManager.RegisterSubsystem((SubsystemKind)0, predictor1)); - Assert.Throws( - paramName: "kind", - () => SubsystemManager.RegisterSubsystem(SubsystemKind.CommandPredictor | SubsystemKind.FeedbackProvider, predictor1)); + SubsystemManager.RegisterSubsystem(MyCompositeSubsystem.Singleton); + SubsystemManager.RegisterSubsystem(SubsystemKind.FeedbackProvider, MyCompositeSubsystem.Singleton); + } + finally + { + SubsystemManager.UnregisterSubsystem(SubsystemKind.CommandPredictor, MyCompositeSubsystem.Singleton.Id); + SubsystemManager.UnregisterSubsystem(MyCompositeSubsystem.Singleton.Id); + } + } + [Fact] + public static void RegisterSubsystem() + { + try + { // Register 'predictor1' SubsystemManager.RegisterSubsystem(predictor1); @@ -147,7 +257,6 @@ public static void RegisterSubsystem() ICommandPredictor impl = SubsystemManager.GetSubsystem(); Assert.Same(impl, predictor1); Assert.Null(impl.FunctionsToDefine); - Assert.Equal(SubsystemKind.CommandPredictor, impl.Kind); const string Client = "SubsystemTest"; const string Input = "Hello world"; From 9ea887f62629171e634b1388e20aca800518bf5d Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Thu, 5 Jan 2023 15:21:35 -0800 Subject: [PATCH 277/779] Add `-CommandWithArgs` parameter to pwsh (#18726) * Add `-CommandWithArgs` parameter to pwsh * Update src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs Co-authored-by: Ilya * address Ilya and Mikey's comments * reset i Co-authored-by: Ilya --- .../host/msh/CommandLineParameterParser.cs | 118 ++++++++++-------- .../CommandLineParameterParserStrings.resx | 2 +- .../resources/ManagedEntranceStrings.resx | 20 +++ .../ExperimentalFeature.cs | 4 + test/powershell/Host/ConsoleHost.Tests.ps1 | 22 ++++ 5 files changed, 112 insertions(+), 54 deletions(-) diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs index 9e555bd428b..30106d9a1e7 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs @@ -174,6 +174,7 @@ internal static int MaxNameLength() "sta", "mta", "command", + "commandwithargs", "configurationname", "custompipename", "encodedcommand", @@ -230,6 +231,7 @@ internal enum ParameterBitmap : long WorkingDirectory = 0x02000000, // -WorkingDirectory | -wd ConfigurationFile = 0x04000000, // -ConfigurationFile NoProfileLoadTime = 0x08000000, // -NoProfileLoadTime + CommandWithArgs = 0x10000000, // -CommandWithArgs | -cwa // Enum values for specified ExecutionPolicy EPUnrestricted = 0x0000000100000000, // ExecutionPolicy unrestricted EPRemoteSigned = 0x0000000200000000, // ExecutionPolicy remote signed @@ -995,6 +997,19 @@ private void ParseHelper(string[] args) _customPipeName = args[i]; ParametersUsed |= ParameterBitmap.CustomPipeName; } + else if (MatchSwitch(switchKey, "commandwithargs", "commandwithargs") || MatchSwitch(switchKey, "cwa", "cwa")) + { + _commandHasArgs = true; + + if (!ParseCommand(args, ref i, noexitSeen, false)) + { + break; + } + + i++; + CollectPSArgs(args, ref i); + ParametersUsed |= ParameterBitmap.CommandWithArgs; + } else if (MatchSwitch(switchKey, "command", "c")) { if (!ParseCommand(args, ref i, noexitSeen, false)) @@ -1247,15 +1262,6 @@ private void ParseExecutionPolicy(string[] args, ref int i, ref string? executio // treat -command as an argument to the script... private bool ParseFile(string[] args, ref int i, bool noexitSeen) { - // Try parse '$true', 'true', '$false' and 'false' values. - static object ConvertToBoolIfPossible(string arg) - { - // Before parsing we skip '$' if present. - return arg.Length > 0 && bool.TryParse(arg.AsSpan(arg[0] == '$' ? 1 : 0), out bool boolValue) - ? (object)boolValue - : (object)arg; - } - ++i; if (i >= args.Length) { @@ -1343,51 +1349,64 @@ static object ConvertToBoolIfPossible(string arg) i++; - string? pendingParameter = null; + CollectPSArgs(args, ref i); + } - // Accumulate the arguments to this script... - while (i < args.Length) - { - string arg = args[i]; + return true; + } - // If there was a pending parameter, add a named parameter - // using the pending parameter and current argument - if (pendingParameter != null) - { - _collectedArgs.Add(new CommandParameter(pendingParameter, arg)); - pendingParameter = null; - } - else if (!string.IsNullOrEmpty(arg) && CharExtensions.IsDash(arg[0]) && arg.Length > 1) + private void CollectPSArgs(string[] args, ref int i) + { + // Try parse '$true', 'true', '$false' and 'false' values. + static object ConvertToBoolIfPossible(string arg) + { + // Before parsing we skip '$' if present. + return arg.Length > 0 && bool.TryParse(arg.AsSpan(arg[0] == '$' ? 1 : 0), out bool boolValue) + ? (object)boolValue + : (object)arg; + } + + string? pendingParameter = null; + + while (i < args.Length) + { + string arg = args[i]; + + // If there was a pending parameter, add a named parameter + // using the pending parameter and current argument + if (pendingParameter != null) + { + _collectedArgs.Add(new CommandParameter(pendingParameter, arg)); + pendingParameter = null; + } + else if (!string.IsNullOrEmpty(arg) && CharExtensions.IsDash(arg[0]) && arg.Length > 1) + { + int offset = arg.IndexOf(':'); + if (offset >= 0) { - int offset = arg.IndexOf(':'); - if (offset >= 0) + if (offset == arg.Length - 1) { - if (offset == arg.Length - 1) - { - pendingParameter = arg.TrimEnd(':'); - } - else - { - string argValue = arg.Substring(offset + 1); - string argName = arg.Substring(0, offset); - _collectedArgs.Add(new CommandParameter(argName, ConvertToBoolIfPossible(argValue))); - } + pendingParameter = arg.TrimEnd(':'); } else { - _collectedArgs.Add(new CommandParameter(arg)); + string argValue = arg.Substring(offset + 1); + string argName = arg.Substring(0, offset); + _collectedArgs.Add(new CommandParameter(argName, ConvertToBoolIfPossible(argValue))); } } else { - _collectedArgs.Add(new CommandParameter(null, arg)); + _collectedArgs.Add(new CommandParameter(arg)); } - - ++i; } - } + else + { + _collectedArgs.Add(new CommandParameter(null, arg)); + } - return true; + ++i; + } } private bool ParseCommand(string[] args, ref int i, bool noexitSeen, bool isEncoded) @@ -1443,23 +1462,15 @@ private bool ParseCommand(string[] args, ref int i, bool noexitSeen, bool isEnco } else { - // Collect the remaining parameters and combine them into a single command to be run. - - StringBuilder cmdLineCmdSB = new StringBuilder(); - - while (i < args.Length) + if (_commandHasArgs) { - cmdLineCmdSB.Append(args[i] + " "); - ++i; + _commandLineCommand = args[i]; } - - if (cmdLineCmdSB.Length > 0) + else { - // remove the last blank - cmdLineCmdSB.Remove(cmdLineCmdSB.Length - 1, 1); + _commandLineCommand = string.Join(' ', args, i, args.Length - i); + i = args.Length; } - - _commandLineCommand = cmdLineCmdSB.ToString(); } if (!noexitSeen && !_explicitReadCommandsFromStdin) @@ -1531,6 +1542,7 @@ private bool CollectArgs(string[] args, ref int i) private bool _noPrompt; private string? _commandLineCommand; private bool _wasCommandEncoded; + private bool _commandHasArgs; private uint _exitCode = ConsoleHost.ExitCodeSuccess; private bool _dirty; private Serialization.DataFormat _outFormat = Serialization.DataFormat.Text; diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/CommandLineParameterParserStrings.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/CommandLineParameterParserStrings.resx index 92f0cf0f1e7..decca21bb00 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/resources/CommandLineParameterParserStrings.resx +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/CommandLineParameterParserStrings.resx @@ -118,7 +118,7 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - Cannot process command because a command is already specified with -Command or -EncodedCommand. + Cannot process command because a command is already specified with -Command, -CommandWithArgs, or -EncodedCommand. Cannot process the command because of a missing parameter. A command must follow -Command. diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/ManagedEntranceStrings.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/ManagedEntranceStrings.resx index df68fb8e70a..aa78f3bd245 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/resources/ManagedEntranceStrings.resx +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/ManagedEntranceStrings.resx @@ -145,6 +145,7 @@ Usage: pwsh[.exe] [-Login] [[-File] <filePath> [args]] [-Command { - | <script-block> [-args <arg-array>] | <string> [<CommandParameters>] } ] + [-CommandWithArgs <string> [<CommandParameters>] [-ConfigurationName <string>] [-ConfigurationFile <filePath>] [-CustomPipeName <string>] [-EncodedCommand <Base64EncodedCommand>] [-ExecutionPolicy <ExecutionPolicy>] [-InputFormat {Text | XML}] @@ -281,6 +282,25 @@ All parameters are case-insensitive. (runspace-terminating) error, such as a throw or -ErrorAction Stop, occurs or when execution is interrupted with Ctrl-C. +-CommandWithArgs | -cwa + + [Experimental] + Executes a PowerShell command with arguments. Unlike `-Command`, this + parameter populates the `$args built-in variable which can be used by the + command. + + The first string is the command and subsequent strings delimited by whitespace + are the arguments. + + For example: + + pwsh -CommandWithArgs '$args | % { "arg: $_" }' arg1 arg2 + + This example produces the following output: + + arg: arg1 + arg: arg2 + -ConfigurationName | -config Specifies a configuration endpoint in which PowerShell is run. This can be diff --git a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs index 55036d87fce..b059c861cef 100644 --- a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs +++ b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs @@ -25,6 +25,7 @@ public class ExperimentalFeature internal const string PSModuleAutoLoadSkipOfflineFilesFeatureName = "PSModuleAutoLoadSkipOfflineFiles"; internal const string PSCustomTableHeaderLabelDecoration = "PSCustomTableHeaderLabelDecoration"; internal const string PSFeedbackProvider = "PSFeedbackProvider"; + internal const string PSCommandWithArgs = "PSCommandWithArgs"; #endregion @@ -128,6 +129,9 @@ static ExperimentalFeature() new ExperimentalFeature( name: PSFeedbackProvider, description: "Replace the hard-coded suggestion framework with the extensible feedback provider"), + new ExperimentalFeature( + name: PSCommandWithArgs, + description: "Enable `-CommandWithArgs` parameter for pwsh"), }; EngineExperimentalFeatures = new ReadOnlyCollection(engineFeatures); diff --git a/test/powershell/Host/ConsoleHost.Tests.ps1 b/test/powershell/Host/ConsoleHost.Tests.ps1 index 5def52d255c..7ee7fd07a46 100644 --- a/test/powershell/Host/ConsoleHost.Tests.ps1 +++ b/test/powershell/Host/ConsoleHost.Tests.ps1 @@ -917,6 +917,28 @@ $powershell -c '[System.Management.Automation.Platform]::SelectProductNameForDir $out[0] | Should -MatchExactly $expectedPromptPattern } } + + Context 'CommandWithArgs tests' { + It 'Should be able to run a pipeline with arguments using ' -TestCases @( + @{ param = '-commandwithargs' } + @{ param = '-cwa' } + ){ + param($param) + $out = pwsh -nologo -noprofile $param '$args | % { "[$_]" }' '$fun' '@times' + $out.Count | Should -Be 2 -Because ($out | Out-String) + $out[0] | Should -BeExactly '[$fun]' + $out[1] | Should -BeExactly '[@times]' + } + + It 'Should be able to handle boolean switch: ' -TestCases @( + @{ param = '-switch:$true'; expected = 'True'} + @{ param = '-switch:$false'; expected = 'False'} + ){ + param($param, $expected) + $out = pwsh -nologo -noprofile -cwa 'param([switch]$switch) $switch.IsPresent' $param + $out | Should -Be $expected + } + } } Describe "WindowStyle argument" -Tag Feature { From eda2bd62794036c7ba83a2ff6c937206eafb478f Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Thu, 5 Jan 2023 16:34:55 -0800 Subject: [PATCH 278/779] Update build to include `WinForms` / `WPF` in all Windows builds (#18859) --- build.psm1 | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/build.psm1 b/build.psm1 index 1b9bd8aef37..fd2858ba288 100644 --- a/build.psm1 +++ b/build.psm1 @@ -529,7 +529,7 @@ Fix steps: if ($Options.Runtime -notlike 'fxdependent*' -or $Options.Runtime -match $optimizedFddRegex) { Write-Verbose "Building without shim" -Verbose $sdkToUse = 'Microsoft.NET.Sdk' - if ($Options.Runtime -like 'win7-*' -and !$ForMinimalSize) { + if (($Options.Runtime -like 'win7-*' -or $Options.Runtime -eq 'win-arm64') -and !$ForMinimalSize) { ## WPF/WinForm and the PowerShell GraphicalHost assemblies are included ## when 'Microsoft.NET.Sdk.WindowsDesktop' is used. $sdkToUse = 'Microsoft.NET.Sdk.WindowsDesktop' @@ -731,7 +731,7 @@ function Restore-PSPackage } else { $sdkToUse = 'Microsoft.NET.Sdk' - if ($Options.Runtime -like 'win7-*' -and !$Options.ForMinimalSize) { + if (($Options.Runtime -like 'win7-*' -or $Options.Runtime -eq 'win-arm64') -and !$Options.ForMinimalSize) { $sdkToUse = 'Microsoft.NET.Sdk.WindowsDesktop' } } From 30bc32a0835694b05a086681a20254d83d235481 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Fri, 6 Jan 2023 18:47:21 +0100 Subject: [PATCH 279/779] Cleanup InvokeRestMethodCommand.Common.cs (#18861) --- .../Common/InvokeRestMethodCommand.Common.cs | 28 ++++++++----------- 1 file changed, 12 insertions(+), 16 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs index a6a2a6290b0..a2418efbb86 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs @@ -32,9 +32,9 @@ public class InvokeRestMethodCommand : WebRequestPSCmdlet [Parameter(ParameterSetName = "StandardMethodNoProxy")] public override WebRequestMethod Method { - get { return base.Method; } + get => base.Method; - set { base.Method = value; } + set => base.Method = value; } /// @@ -46,9 +46,9 @@ public override WebRequestMethod Method [ValidateNotNullOrEmpty] public override string CustomMethod { - get { return base.CustomMethod; } + get => base.CustomMethod; - set { base.CustomMethod = value; } + set => base.CustomMethod = value; } /// @@ -58,9 +58,9 @@ public override string CustomMethod [Alias("FL")] public SwitchParameter FollowRelLink { - get { return base._followRelLink; } + get => base._followRelLink; - set { base._followRelLink = value; } + set => base._followRelLink = value; } /// @@ -71,9 +71,9 @@ public SwitchParameter FollowRelLink [ValidateRange(1, int.MaxValue)] public int MaximumFollowRelLink { - get { return base._maximumFollowRelLink; } + get => base._maximumFollowRelLink; - set { base._maximumFollowRelLink = value; } + set => base._maximumFollowRelLink = value; } /// @@ -401,18 +401,15 @@ public override void Flush() _streamBuffer.SetLength(0); } - public override long Length - { - get { return _length; } - } + public override long Length => _length; private long _length; public override long Position { - get { return _streamBuffer.Position; } + get => _streamBuffer.Position; - set { _streamBuffer.Position = value; } + set => _streamBuffer.Position = value; } public override int Read(byte[] buffer, int offset, int count) @@ -420,8 +417,7 @@ public override int Read(byte[] buffer, int offset, int count) long previousPosition = Position; bool consumedStream = false; int totalCount = count; - while ((!consumedStream) && - ((Position + totalCount) > _streamBuffer.Length)) + while (!consumedStream && (Position + totalCount) > _streamBuffer.Length) { // If we don't have enough data to fill this from memory, cache more. // We try to read 4096 bytes from base stream every time, so at most we From 078866987b3a0abe7a12b8d1950c4296ef61990d Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Sat, 7 Jan 2023 16:11:01 +0100 Subject: [PATCH 280/779] Requires.NotNull-->ArgumentNullException.ThrowIfNull (#18820) --- .../Subsystem/PredictionSubsystem/CommandPrediction.cs | 2 +- .../Subsystem/PredictionSubsystem/ICommandPredictor.cs | 4 ++-- .../engine/Subsystem/SubsystemManager.cs | 6 +++--- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/System.Management.Automation/engine/Subsystem/PredictionSubsystem/CommandPrediction.cs b/src/System.Management.Automation/engine/Subsystem/PredictionSubsystem/CommandPrediction.cs index 7a87b259314..7ed70e247a5 100644 --- a/src/System.Management.Automation/engine/Subsystem/PredictionSubsystem/CommandPrediction.cs +++ b/src/System.Management.Automation/engine/Subsystem/PredictionSubsystem/CommandPrediction.cs @@ -142,7 +142,7 @@ await Task.WhenAny( /// History command lines provided as references for prediction. public static void OnCommandLineAccepted(PredictionClient client, IReadOnlyList history) { - Requires.NotNull(history, nameof(history)); + ArgumentNullException.ThrowIfNull(history); var predictors = SubsystemManager.GetSubsystems(); if (predictors.Count == 0) diff --git a/src/System.Management.Automation/engine/Subsystem/PredictionSubsystem/ICommandPredictor.cs b/src/System.Management.Automation/engine/Subsystem/PredictionSubsystem/ICommandPredictor.cs index d528067452c..95e8487bbad 100644 --- a/src/System.Management.Automation/engine/Subsystem/PredictionSubsystem/ICommandPredictor.cs +++ b/src/System.Management.Automation/engine/Subsystem/PredictionSubsystem/ICommandPredictor.cs @@ -181,8 +181,8 @@ public sealed class PredictionContext /// The objects from parsing the current command line input. public PredictionContext(Ast inputAst, Token[] inputTokens) { - Requires.NotNull(inputAst, nameof(inputAst)); - Requires.NotNull(inputTokens, nameof(inputTokens)); + ArgumentNullException.ThrowIfNull(inputAst); + ArgumentNullException.ThrowIfNull(inputTokens); var cursor = inputAst.Extent.EndScriptPosition; var astContext = CompletionAnalysis.ExtractAstContext(inputAst, inputTokens, cursor); diff --git a/src/System.Management.Automation/engine/Subsystem/SubsystemManager.cs b/src/System.Management.Automation/engine/Subsystem/SubsystemManager.cs index 1af41a67457..022c163a16c 100644 --- a/src/System.Management.Automation/engine/Subsystem/SubsystemManager.cs +++ b/src/System.Management.Automation/engine/Subsystem/SubsystemManager.cs @@ -131,7 +131,7 @@ public static ReadOnlyCollection GetAllSubsystemInfo() /// The object that represents the concrete subsystem. public static SubsystemInfo GetSubsystemInfo(Type subsystemType) { - Requires.NotNull(subsystemType, nameof(subsystemType)); + ArgumentNullException.ThrowIfNull(subsystemType); if (s_subSystemTypeMap.TryGetValue(subsystemType, out SubsystemInfo? subsystemInfo)) { @@ -180,7 +180,7 @@ public static void RegisterSubsystem(TImple where TConcreteSubsystem : class, ISubsystem where TImplementation : class, TConcreteSubsystem { - Requires.NotNull(proxy, nameof(proxy)); + ArgumentNullException.ThrowIfNull(proxy); RegisterSubsystem(GetSubsystemInfo(typeof(TConcreteSubsystem)), proxy); } @@ -192,7 +192,7 @@ public static void RegisterSubsystem(TImple /// An instance of the implementation. public static void RegisterSubsystem(SubsystemKind kind, ISubsystem proxy) { - Requires.NotNull(proxy, nameof(proxy)); + ArgumentNullException.ThrowIfNull(proxy); SubsystemInfo info = GetSubsystemInfo(kind); if (!info.SubsystemType.IsAssignableFrom(proxy.GetType())) From 27b5a0632de55c092002eca92a48500e93341c0f Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Mon, 9 Jan 2023 09:40:40 -0800 Subject: [PATCH 281/779] Add `-ProgressAction` common parameter (#18887) --- .../utility/ImplicitRemotingCommands.cs | 2 +- .../engine/CommonCommandParameters.cs | 21 +++++++++++++++++++ .../engine/InternalCommands.cs | 3 ++- .../engine/MshCommandRuntime.cs | 8 ++++--- .../engine/ReflectionParameterBinder.cs | 6 ++++++ .../engine/SpecialVariables.cs | 1 + .../engine/cmdlet.cs | 2 +- .../engine/runtime/CompiledScriptBlock.cs | 5 +++++ .../TabCompletion/TabCompletion.Tests.ps1 | 6 +++--- .../Scripting/ActionPreference.Tests.ps1 | 1 + .../ExperimentalFeature.Basic.Tests.ps1 | 10 ++++----- 11 files changed, 51 insertions(+), 14 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs index 8c378c41658..c6197a4b7bf 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs @@ -2740,7 +2740,7 @@ function Get-PSImplicitRemotingClientSideParameters $clientSideParameters = @{} - $parametersToLeaveRemote = 'ErrorAction', 'WarningAction', 'InformationAction' + $parametersToLeaveRemote = 'ErrorAction', 'WarningAction', 'InformationAction', 'ProgressAction' Modify-PSImplicitRemotingParameters $clientSideParameters $PSBoundParameters 'AsJob' if ($proxyForCmdlet) diff --git a/src/System.Management.Automation/engine/CommonCommandParameters.cs b/src/System.Management.Automation/engine/CommonCommandParameters.cs index c3630fe0b43..ea636dc5838 100644 --- a/src/System.Management.Automation/engine/CommonCommandParameters.cs +++ b/src/System.Management.Automation/engine/CommonCommandParameters.cs @@ -123,6 +123,27 @@ public ActionPreference InformationAction set { _commandRuntime.InformationPreference = value; } } + /// + /// Gets or sets the value of the ProgressAction parameter for the cmdlet. + /// + /// + /// This parameter tells the command what to do when a progress record occurs. + /// + /// + [Parameter] + [Alias("proga")] + public ActionPreference ProgressAction + { + get { return _commandRuntime.ProgressPreference; } + + set { _commandRuntime.ProgressPreference = value; } + } + /// /// Gets or sets the value of the ErrorVariable parameter for the cmdlet. /// diff --git a/src/System.Management.Automation/engine/InternalCommands.cs b/src/System.Management.Automation/engine/InternalCommands.cs index 2afb9c516c6..8ef6976c446 100644 --- a/src/System.Management.Automation/engine/InternalCommands.cs +++ b/src/System.Management.Automation/engine/InternalCommands.cs @@ -385,10 +385,11 @@ public void Dispose() private void InitParallelParameterSet() { // The following common parameters are not (yet) supported in this parameter set. - // ErrorAction, WarningAction, InformationAction, PipelineVariable. + // ErrorAction, WarningAction, InformationAction, ProgressAction, PipelineVariable. if (MyInvocation.BoundParameters.ContainsKey(nameof(CommonParamSet.ErrorAction)) || MyInvocation.BoundParameters.ContainsKey(nameof(CommonParamSet.WarningAction)) || MyInvocation.BoundParameters.ContainsKey(nameof(CommonParamSet.InformationAction)) || + MyInvocation.BoundParameters.ContainsKey(nameof(CommonParamSet.ProgressAction)) || MyInvocation.BoundParameters.ContainsKey(nameof(CommonParamSet.PipelineVariable))) { ThrowTerminatingError( diff --git a/src/System.Management.Automation/engine/MshCommandRuntime.cs b/src/System.Management.Automation/engine/MshCommandRuntime.cs index fcc7f5b4588..d8bb95b59e6 100644 --- a/src/System.Management.Automation/engine/MshCommandRuntime.cs +++ b/src/System.Management.Automation/engine/MshCommandRuntime.cs @@ -3330,7 +3330,7 @@ internal ActionPreference ProgressPreference { get { - if (_isProgressPreferenceSet) + if (IsProgressActionSet) return _progressPreference; if (!_isProgressPreferenceCached) @@ -3351,12 +3351,14 @@ internal ActionPreference ProgressPreference } _progressPreference = value; - _isProgressPreferenceSet = true; + IsProgressActionSet = true; } } private ActionPreference _progressPreference = InitialSessionState.DefaultProgressPreference; - private bool _isProgressPreferenceSet = false; + + internal bool IsProgressActionSet { get; private set; } = false; + private bool _isProgressPreferenceCached = false; /// diff --git a/src/System.Management.Automation/engine/ReflectionParameterBinder.cs b/src/System.Management.Automation/engine/ReflectionParameterBinder.cs index 0fd8bf8b339..5ee84f4c42f 100644 --- a/src/System.Management.Automation/engine/ReflectionParameterBinder.cs +++ b/src/System.Management.Automation/engine/ReflectionParameterBinder.cs @@ -207,6 +207,12 @@ static ReflectionParameterBinder() v ??= LanguagePrimitives.ThrowInvalidCastException(null, typeof(ActionPreference)); ((CommonParameters)o).InformationAction = (ActionPreference)v; }); + s_setterMethods.TryAdd(Tuple.Create(typeof(CommonParameters), "ProgressAction"), + (o, v) => + { + v ??= LanguagePrimitives.ThrowInvalidCastException(null, typeof(ActionPreference)); + ((CommonParameters)o).ProgressAction = (ActionPreference)v; + }); s_setterMethods.TryAdd(Tuple.Create(typeof(CommonParameters), "Verbose"), static (o, v) => ((CommonParameters)o).Verbose = (SwitchParameter)v); s_setterMethods.TryAdd(Tuple.Create(typeof(CommonParameters), "Debug"), static (o, v) => ((CommonParameters)o).Debug = (SwitchParameter)v); s_setterMethods.TryAdd(Tuple.Create(typeof(CommonParameters), "ErrorVariable"), static (o, v) => ((CommonParameters)o).ErrorVariable = (string)v); diff --git a/src/System.Management.Automation/engine/SpecialVariables.cs b/src/System.Management.Automation/engine/SpecialVariables.cs index d1d90e3507c..420b52d4d22 100644 --- a/src/System.Management.Automation/engine/SpecialVariables.cs +++ b/src/System.Management.Automation/engine/SpecialVariables.cs @@ -419,5 +419,6 @@ internal enum PreferenceVariable Warning = 13, Information = 14, Confirm = 15, + Progress = 16, } } diff --git a/src/System.Management.Automation/engine/cmdlet.cs b/src/System.Management.Automation/engine/cmdlet.cs index e241b972b38..9a02adc4c60 100644 --- a/src/System.Management.Automation/engine/cmdlet.cs +++ b/src/System.Management.Automation/engine/cmdlet.cs @@ -50,7 +50,7 @@ public static HashSet CommonParameters () => { return new HashSet(StringComparer.OrdinalIgnoreCase) { - "Verbose", "Debug", "ErrorAction", "WarningAction", "InformationAction", + "Verbose", "Debug", "ErrorAction", "WarningAction", "InformationAction", "ProgressAction", "ErrorVariable", "WarningVariable", "OutVariable", "OutBuffer", "PipelineVariable", "InformationVariable" }; } diff --git a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs index e2b5ee8376c..f6b78c884df 100644 --- a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs +++ b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs @@ -2516,6 +2516,11 @@ private void SetPreferenceVariables() _localsTuple.SetPreferenceVariable(PreferenceVariable.Information, _commandRuntime.InformationPreference); } + if (_commandRuntime.IsProgressActionSet) + { + _localsTuple.SetPreferenceVariable(PreferenceVariable.Progress, _commandRuntime.ProgressPreference); + } + if (_commandRuntime.IsWhatIfFlagSet) { _localsTuple.SetPreferenceVariable(PreferenceVariable.WhatIf, _commandRuntime.WhatIf); diff --git a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 index a76013edb26..c2b930deee3 100644 --- a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 +++ b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 @@ -1620,8 +1620,8 @@ dir -Recurse ` It "Test completion with splatted variable" { $inputStr = 'Get-Content @Splat -P' $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length - $res.CompletionMatches | Should -HaveCount 4 - [string]::Join(',', ($res.CompletionMatches.completiontext | Sort-Object)) | Should -BeExactly "-Path,-PipelineVariable,-PSPath,-pv" + $res.CompletionMatches | Should -HaveCount 6 + [string]::Join(',', ($res.CompletionMatches.completiontext | Sort-Object)) | Should -BeExactly "-Path,-PipelineVariable,-proga,-ProgressAction,-PSPath,-pv" } It "Test completion for HttpVersion parameter name" { @@ -2411,7 +2411,7 @@ Describe "WSMan Config Provider tab complete tests" -Tags Feature,RequireAdminOn @{path = "localhost\plugin"; parameter = "-ru"; expected = "RunAsCredential"}, @{path = "localhost\plugin"; parameter = "-us"; expected = "UseSharedProcess"}, @{path = "localhost\plugin"; parameter = "-au"; expected = "AutoRestart"}, - @{path = "localhost\plugin"; parameter = "-pr"; expected = "ProcessIdleTimeoutSec"}, + @{path = "localhost\plugin"; parameter = "-proc"; expected = "ProcessIdleTimeoutSec"}, @{path = "localhost\Plugin\microsoft.powershell\Resources\"; parameter = "-re"; expected = "ResourceUri"}, @{path = "localhost\Plugin\microsoft.powershell\Resources\"; parameter = "-ca"; expected = "Capability"} ) { diff --git a/test/powershell/Language/Scripting/ActionPreference.Tests.ps1 b/test/powershell/Language/Scripting/ActionPreference.Tests.ps1 index 2f527652500..513fd3adb48 100644 --- a/test/powershell/Language/Scripting/ActionPreference.Tests.ps1 +++ b/test/powershell/Language/Scripting/ActionPreference.Tests.ps1 @@ -194,6 +194,7 @@ Describe "Tests for (error, warning, etc) action preference" -Tags "CI" { @{ name = "ErrorAction"; argValue = "AutomationNull"; arguments = @{ ErrorAction = [System.Management.Automation.Internal.AutomationNull]::Value } } @{ name = "WarningAction"; argValue = "AutomationNull"; arguments = @{ WarningAction = [System.Management.Automation.Internal.AutomationNull]::Value } } @{ name = "InformationAction"; argValue = "AutomationNull"; arguments = @{ InformationAction = [System.Management.Automation.Internal.AutomationNull]::Value } } + @{ name = "ProgressAction"; argValue = "AutomationNull"; arguments = @{ ProgressAction = [System.Management.Automation.Internal.AutomationNull]::Value } } ) { param($arguments) diff --git a/test/powershell/engine/ExperimentalFeature/ExperimentalFeature.Basic.Tests.ps1 b/test/powershell/engine/ExperimentalFeature/ExperimentalFeature.Basic.Tests.ps1 index 2e86672b3ac..8568edf5c9b 100644 --- a/test/powershell/engine/ExperimentalFeature/ExperimentalFeature.Basic.Tests.ps1 +++ b/test/powershell/engine/ExperimentalFeature/ExperimentalFeature.Basic.Tests.ps1 @@ -236,7 +236,7 @@ Describe "Experimental Feature Basic Tests - Feature-Enabled" -Tag "CI" { $command = Get-Command $Name $command.CommandType | Should -Be $CommandType ## Common parameters + '-Name' + '-SwitchOne' + '-SwitchTwo' - $command.Parameters.Count | Should -Be ($CommonParameterCount + 3) + $command.Parameters.Count | Should -Be ($CommonParameterCount + 3) -Because ($command.Parameters.Keys -join ", ") $command.ParameterSets.Count | Should -Be 3 & $Name -Name Joe | Should -BeExactly "Hello World Joe." @@ -254,7 +254,7 @@ Describe "Experimental Feature Basic Tests - Feature-Enabled" -Tag "CI" { ## Common parameters + '-UserName', '-ComputerName', '-ConfigurationName', '-VMName', '-Port', ## '-Token', '-WebSocketUrl', '-ThrottleLimit' and '-Command' - $command.Parameters.Count | Should -Be ($CommonParameterCount + 9) + $command.Parameters.Count | Should -Be ($CommonParameterCount + 9) -Because ($command.Parameters.Keys -join ", ") $command.ParameterSets.Count | Should -Be 3 $command.Parameters["UserName"].ParameterSets.Count | Should -Be 1 @@ -316,7 +316,7 @@ Describe "Experimental Feature Basic Tests - Feature-Enabled" -Tag "CI" { $command = Get-Command $Name $command.CommandType | Should -Be $CommandType ## Common parameters + '-ComputerName' - $command.Parameters.Count | Should -Be ($CommonParameterCount + 1) + $command.Parameters.Count | Should -Be ($CommonParameterCount + 1) -Because ($command.Parameters.Keys -join ", ") $command.Parameters["ComputerName"].ParameterType.FullName | Should -BeExactly "System.String" $command.Parameters.ContainsKey("SessionName") | Should -BeFalse } @@ -329,7 +329,7 @@ Describe "Experimental Feature Basic Tests - Feature-Enabled" -Tag "CI" { $command = Get-Command $Name $command.CommandType | Should -Be $CommandType ## Common parameters + '-ByUrl', '-ByRadio', '-FileName', '-Destination' - $command.Parameters.Count | Should -Be ($CommonParameterCount + 4) + $command.Parameters.Count | Should -Be ($CommonParameterCount + 4) -Because ($command.Parameters.Keys -join ", ") $command.ParameterSets.Count | Should -Be 2 $command.Parameters["ByUrl"].ParameterSets.Count | Should -Be 1 @@ -358,7 +358,7 @@ Describe "Experimental Feature Basic Tests - Feature-Enabled" -Tag "CI" { $command = Get-Command $Name $command.CommandType | Should -Be $CommandType ## Common parameters + '-Name' (dynamic parameters are not triggered) - $command.Parameters.Count | Should -Be ($CommonParameterCount + 1) + $command.Parameters.Count | Should -Be ($CommonParameterCount + 1) -Because ($command.Parameters.Keys -join ", ") $command.Parameters["Name"] | Should -Not -BeNullOrEmpty $command = Get-Command $Name -ArgumentList "Joe" From 232384ce7fbbe0ad6542c26b0cdfbff523783f76 Mon Sep 17 00:00:00 2001 From: MartinGC94 <42123497+MartinGC94@users.noreply.github.com> Date: Mon, 9 Jan 2023 19:30:42 +0100 Subject: [PATCH 282/779] Prioritize the default parameter set when completing positional arguments (#18755) --- .../engine/CommandCompletion/CompletionCompleters.cs | 4 +++- test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 | 6 ++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs index 4674fe33271..d8dda81d2ba 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs @@ -1617,7 +1617,9 @@ private static void CompletePositionalArgument( continue; } - if (bestMatchSet is null || bestMatchSet.Position > positionInParameterSet) + if (bestMatchSet is null + || bestMatchSet.Position > positionInParameterSet + || (isDefaultParameterSetValid && positionInParameterSet == bestMatchSet.Position && defaultParameterSetFlag == parameterSetData.ParameterSetFlag)) { bestMatchParam = param; bestMatchSet = parameterSetData; diff --git a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 index c2b930deee3..982085ff268 100644 --- a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 +++ b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 @@ -837,6 +837,12 @@ Verb-Noun -Param1 Hello ^ $res.CompletionMatches[0].CompletionText | Should -Be "Get-ChildItem" } + it 'Should prefer the default parameterset when completing positional parameters' { + $ScriptInput = 'Get-ChildItem | Where-Object ' + $res = TabExpansion2 -inputScript $ScriptInput -cursorColumn $ScriptInput.Length + $res.CompletionMatches[0].CompletionText | Should -Be "Attributes" + } + Context "Script name completion" { BeforeAll { Setup -f 'install-powershell.ps1' -Content "" From 80b5df4b7f6e749e34a2363e1ef6cc09f2761c89 Mon Sep 17 00:00:00 2001 From: Paul Higinbotham Date: Mon, 9 Jan 2023 10:40:38 -0800 Subject: [PATCH 283/779] Add WDAC events and system lockdown notification (#18893) * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Update PSGalleryModules correctly * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * rebase conflict * Rebase conflict again * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Update PSGalleryModules correctly * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * rebase conflict * Rebase conflict again * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Update PSGalleryModules correctly * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * rebase conflict * Rebase conflict again * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Update PSGalleryModules correctly * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * rebase conflict * Rebase conflict again * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * rebase conflict * Rebase conflict again * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Update PSGalleryModules correctly * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * rebase conflict * Rebase conflict again * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Update PSGalleryModules correctly * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * rebase conflict * Rebase conflict again * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Update PSGalleryModules correctly * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * rebase conflict * Rebase conflict again * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Update PSGalleryModules correctly * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * rebase conflict * Rebase conflict again * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Update PSGalleryModules correctly * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * rebase conflict * Rebase conflict again * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Update PSGalleryModules correctly * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * rebase conflict * Rebase conflict again * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Update PSGalleryModules correctly * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * rebase conflict * Rebase conflict again * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Update PSGalleryModules correctly * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * rebase conflict * Rebase conflict again * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Update PSGalleryModules correctly * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * rebase conflict * Rebase conflict again * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Update PSGalleryModules correctly * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * rebase conflict * Rebase conflict again * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Update PSGalleryModules correctly * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * rebase conflict * Rebase conflict again * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Update PSGalleryModules correctly * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * rebase conflict * Rebase conflict again * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Update PSGalleryModules correctly * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * rebase conflict * Rebase conflict again * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Update PSGalleryModules correctly * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * rebase conflict * Rebase conflict again * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Update PSGalleryModules correctly * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * rebase conflict * Rebase conflict again * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Bump PSReadLine from 2.1.0 to 2.2.2 in /src/Modules Bumps PSReadLine from 2.1.0 to 2.2.2. --- updated-dependencies: - dependency-name: PSReadLine dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Add WDAC events * Fix CodeFactor issues Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .../host/msh/ConsoleHost.cs | 27 ++++++++++++++++-- .../resources/ManagedEntranceStrings.resx | 9 ++++++ .../engine/Utils.cs | 11 ++------ .../engine/remoting/common/PSETWTracer.cs | 4 ++- .../logging/LogProvider.cs | 28 +++++++++++++++++++ .../security/wldpNativeMethods.cs | 21 +++++++++++--- .../utils/tracing/PSEtwLog.cs | 16 +++++++++++ .../utils/tracing/PSEtwLogProvider.cs | 16 +++++++++++ .../utils/tracing/PSSysLogProvider.cs | 16 +++++++++++ 9 files changed, 132 insertions(+), 16 deletions(-) diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs index 19bb79977e7..e2b7bd7b8ba 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs @@ -180,7 +180,7 @@ internal static int Start( // Alternatively, we could call s_theConsoleHost.UI.WriteLine(s_theConsoleHost.Version.ToString()); // or start up the engine and retrieve the information via $psversiontable.GitCommitId // but this returns the semantic version and avoids executing a script - s_theConsoleHost.UI.WriteLine("PowerShell " + PSVersionInfo.GitCommitId); + s_theConsoleHost.UI.WriteLine($"PowerShell {PSVersionInfo.GitCommitId}"); return 0; } @@ -1831,8 +1831,29 @@ private void DoRunspaceInitialization(RunspaceCreationEventArgs args) const string shellId = "Microsoft.PowerShell"; // If the system lockdown policy says "Enforce", do so. Do this after types / formatting, default functions, etc - // are loaded so that they are trusted. (Validation of their signatures is done in F&O) - Utils.EnforceSystemLockDownLanguageMode(_runspaceRef.Runspace.ExecutionContext); + // are loaded so that they are trusted. (Validation of their signatures is done in F&O). + var languageMode = Utils.EnforceSystemLockDownLanguageMode(_runspaceRef.Runspace.ExecutionContext); + // When displaying banner, also display the language mode if running in any restricted mode. + if (s_cpp.ShowBanner) + { + switch (languageMode) + { + case PSLanguageMode.ConstrainedLanguage: + s_theConsoleHost.UI.WriteLine(ManagedEntranceStrings.ShellBannerCLMode); + break; + + case PSLanguageMode.NoLanguage: + s_theConsoleHost.UI.WriteLine(ManagedEntranceStrings.ShellBannerNLMode); + break; + + case PSLanguageMode.RestrictedLanguage: + s_theConsoleHost.UI.WriteLine(ManagedEntranceStrings.ShellBannerRLMode); + break; + + default: + break; + } + } string allUsersProfile = HostUtilities.GetFullProfileFileName(null, false); string allUsersHostSpecificProfile = HostUtilities.GetFullProfileFileName(shellId, false); diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/ManagedEntranceStrings.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/ManagedEntranceStrings.resx index aa78f3bd245..c6f96715fb0 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/resources/ManagedEntranceStrings.resx +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/ManagedEntranceStrings.resx @@ -120,6 +120,15 @@ PowerShell {0} + + [Constrained Language Mode] + + + [No Language Mode] + + + [Restricted Language Mode] + Warning: PowerShell detected that you might be using a screen reader and has disabled PSReadLine for compatibility purposes. If you want to re-enable it, run 'Import-Module PSReadLine'. diff --git a/src/System.Management.Automation/engine/Utils.cs b/src/System.Management.Automation/engine/Utils.cs index 99eaf7678ed..bdf85b54e5e 100644 --- a/src/System.Management.Automation/engine/Utils.cs +++ b/src/System.Management.Automation/engine/Utils.cs @@ -1457,22 +1457,18 @@ internal static bool IsComObject(object obj) /// NoLanguage -> NoLanguage. /// /// ExecutionContext. - /// Previous language mode or null for no language mode change. - internal static PSLanguageMode? EnforceSystemLockDownLanguageMode(ExecutionContext context) + /// The current ExecutionContext language mode. + internal static PSLanguageMode EnforceSystemLockDownLanguageMode(ExecutionContext context) { - PSLanguageMode? oldMode = null; - if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce) { switch (context.LanguageMode) { case PSLanguageMode.FullLanguage: - oldMode = context.LanguageMode; context.LanguageMode = PSLanguageMode.ConstrainedLanguage; break; case PSLanguageMode.RestrictedLanguage: - oldMode = context.LanguageMode; context.LanguageMode = PSLanguageMode.NoLanguage; break; @@ -1482,13 +1478,12 @@ internal static bool IsComObject(object obj) default: Diagnostics.Assert(false, "Unexpected PSLanguageMode"); - oldMode = context.LanguageMode; context.LanguageMode = PSLanguageMode.NoLanguage; break; } } - return oldMode; + return context.LanguageMode; } internal static string DisplayHumanReadableFileSize(long bytes) diff --git a/src/System.Management.Automation/engine/remoting/common/PSETWTracer.cs b/src/System.Management.Automation/engine/remoting/common/PSETWTracer.cs index d59e8828830..b9c599d53e5 100644 --- a/src/System.Management.Automation/engine/remoting/common/PSETWTracer.cs +++ b/src/System.Management.Automation/engine/remoting/common/PSETWTracer.cs @@ -159,6 +159,7 @@ internal enum PSEventId : int Settings = 0x1F04, Engine_Trace = 0x1F06, Amsi_Init = 0x4001, + WDAC_Query = 0x4002, // Experimental Features ExperimentalFeature_InvalidName = 0x3001, @@ -241,7 +242,8 @@ internal enum PSTask : int ScheduledJob = 0x6E, NamedPipe = 0x6F, ISEOperation = 0x78, - Amsi = 0X82 + Amsi = 0X82, + WDAC = 0x83 } /// diff --git a/src/System.Management.Automation/logging/LogProvider.cs b/src/System.Management.Automation/logging/LogProvider.cs index bca5d5fb930..b7de1f60b4e 100644 --- a/src/System.Management.Automation/logging/LogProvider.cs +++ b/src/System.Management.Automation/logging/LogProvider.cs @@ -109,6 +109,19 @@ internal LogProvider() /// The amsiContext handled - Session pair. internal abstract void LogAmsiUtilStateEvent(string state, string context); + /// + /// Provider interface function for logging WDAC query event. + /// + /// Name of the WDAC query. + /// Name of script file for policy query. Can be null value. + /// Query call succeed code. + /// Result code of WDAC query. + internal abstract void LogWDACQueryEvent( + string queryName, + string fileName, + int querySuccess, + int queryResult); + /// /// True if the log provider needs to use logging variables. /// @@ -386,6 +399,21 @@ internal override void LogAmsiUtilStateEvent(string state, string context) { } + /// + /// Provider interface function for logging WDAC query event. + /// + /// Name of the WDAC query. + /// Name of script file for policy query. Can be null value. + /// Query call succeed code. + /// Result code of WDAC query. + internal override void LogWDACQueryEvent( + string queryName, + string fileName, + int querySuccess, + int queryResult) + { + } + #endregion } } diff --git a/src/System.Management.Automation/security/wldpNativeMethods.cs b/src/System.Management.Automation/security/wldpNativeMethods.cs index 970abe541f6..730db922a00 100644 --- a/src/System.Management.Automation/security/wldpNativeMethods.cs +++ b/src/System.Management.Automation/security/wldpNativeMethods.cs @@ -6,9 +6,10 @@ // #if !UNIX +using System.Diagnostics.CodeAnalysis; using System.Management.Automation.Internal; +using System.Management.Automation.Tracing; using System.Runtime.InteropServices; -using System.Diagnostics.CodeAnalysis; namespace System.Management.Automation.Security { @@ -110,6 +111,7 @@ public static SystemScriptFileEnforcement GetFilePolicyEnforcement( SafeHandle fileHandle = fileStream.SafeFileHandle; // First check latest WDAC APIs if available. + Exception errorException = null; if (s_wldpCanExecuteAvailable) { try @@ -124,6 +126,8 @@ public static SystemScriptFileEnforcement GetFilePolicyEnforcement( auditInfo: auditMsg, result: out WLDP_EXECUTION_POLICY canExecuteResult); + PSEtwLog.LogWDACQueryEvent("WldpCanExecuteFile", filePath, hr, (int)canExecuteResult); + if (hr >= 0) { switch (canExecuteResult) @@ -146,15 +150,22 @@ public static SystemScriptFileEnforcement GetFilePolicyEnforcement( // If HResult is unsuccessful (such as E_NOTIMPL (0x80004001)), fall through to legacy system checks. } - catch (DllNotFoundException) + catch (DllNotFoundException ex) { // Fall back to legacy system policy checks. s_wldpCanExecuteAvailable = false; + errorException = ex; } - catch (EntryPointNotFoundException) + catch (EntryPointNotFoundException ex) { // Fall back to legacy system policy checks. s_wldpCanExecuteAvailable = false; + errorException = ex; + } + + if (errorException != null) + { + PSEtwLog.LogWDACQueryEvent("WldpCanExecuteFile_Failed", filePath, errorException.HResult, 0); } } @@ -263,6 +274,7 @@ private static SystemEnforcementMode GetWldpPolicy(string path, SafeHandle handl uint pdwLockdownState = 0; int result = WldpNativeMethods.WldpGetLockdownPolicy(ref hostInformation, ref pdwLockdownState, 0); + PSEtwLog.LogWDACQueryEvent("WldpGetLockdownPolicy", path, result, (int)pdwLockdownState); if (result >= 0) { SystemEnforcementMode resultingLockdownPolicy = GetLockdownPolicyForResult(pdwLockdownState); @@ -281,9 +293,10 @@ private static SystemEnforcementMode GetWldpPolicy(string path, SafeHandle handl return SystemEnforcementMode.Enforce; } } - catch (DllNotFoundException) + catch (DllNotFoundException ex) { s_hadMissingWldpAssembly = true; + PSEtwLog.LogWDACQueryEvent("WldpGetLockdownPolicy_Failed", path, ex.HResult, 0); return s_cachedWldpSystemPolicy.GetValueOrDefault(SystemEnforcementMode.None); } } diff --git a/src/System.Management.Automation/utils/tracing/PSEtwLog.cs b/src/System.Management.Automation/utils/tracing/PSEtwLog.cs index 8212cf55cd8..438d7b5f059 100644 --- a/src/System.Management.Automation/utils/tracing/PSEtwLog.cs +++ b/src/System.Management.Automation/utils/tracing/PSEtwLog.cs @@ -128,6 +128,22 @@ internal static void LogAmsiUtilStateEvent(string state, string context) provider.LogAmsiUtilStateEvent(state, context); } + /// + /// Provider interface function for logging WDAC query event. + /// + /// Name of the WDAC query. + /// Name of script file for policy query. Can be null value. + /// Query call succeed code. + /// Result code of WDAC query. + internal static void LogWDACQueryEvent( + string queryName, + string fileName, + int querySuccess, + int queryResult) + { + provider.LogWDACQueryEvent(queryName, fileName, querySuccess, queryResult); + } + /// /// Provider interface function for logging settings event. /// diff --git a/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs b/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs index 09b1cd9b0f0..9b56da1ae72 100755 --- a/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs +++ b/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs @@ -202,6 +202,22 @@ internal override void LogAmsiUtilStateEvent(string state, string context) WriteEvent(PSEventId.Amsi_Init, PSChannel.Analytic, PSOpcode.Method, PSLevel.Informational, PSTask.Amsi, (PSKeyword)0x0, state, context); } + /// + /// Provider interface function for logging WDAC query event. + /// + /// Name of the WDAC query. + /// Name of script file for policy query. Can be null value. + /// Query call succeed code. + /// Result code of WDAC query. + internal override void LogWDACQueryEvent( + string queryName, + string fileName, + int querySuccess, + int queryResult) + { + WriteEvent(PSEventId.WDAC_Query, PSChannel.Analytic, PSOpcode.Method, PSLevel.Informational, PSTask.WDAC, (PSKeyword)0x0, queryName, fileName, querySuccess, queryResult); + } + /// /// Provider interface function for logging provider lifecycle event. /// diff --git a/src/System.Management.Automation/utils/tracing/PSSysLogProvider.cs b/src/System.Management.Automation/utils/tracing/PSSysLogProvider.cs index 629cdd64476..e7accd6978c 100755 --- a/src/System.Management.Automation/utils/tracing/PSSysLogProvider.cs +++ b/src/System.Management.Automation/utils/tracing/PSSysLogProvider.cs @@ -102,6 +102,22 @@ internal override void LogAmsiUtilStateEvent(string state, string context) WriteEvent(PSEventId.Amsi_Init, PSChannel.Analytic, PSOpcode.Method, PSLevel.Informational, PSTask.Amsi, (PSKeyword)0x0, state, context); } + /// + /// Provider interface function for logging WDAC query event. + /// + /// Name of the WDAC query. + /// Name of script file for policy query. Can be null value. + /// Query call succeed code. + /// Result code of WDAC query. + internal override void LogWDACQueryEvent( + string queryName, + string fileName, + int querySuccess, + int queryResult) + { + WriteEvent(PSEventId.WDAC_Query, PSChannel.Analytic, PSOpcode.Method, PSLevel.Informational, PSTask.WDAC, (PSKeyword)0x0, queryName, fileName, querySuccess, queryResult); + } + /// /// Provider interface function for logging engine lifecycle event. /// From 2c70f3c7d3be52acd986e16337dfe993ba90d4db Mon Sep 17 00:00:00 2001 From: Heath Stewart Date: Mon, 9 Jan 2023 10:44:48 -0800 Subject: [PATCH 284/779] Add checks for Win8.1 and Server2012 in the MSI installer (#18904) --- assets/wix/Product.wxs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/assets/wix/Product.wxs b/assets/wix/Product.wxs index 8dc2d3a3f16..3a8977e83fb 100644 --- a/assets/wix/Product.wxs +++ b/assets/wix/Product.wxs @@ -1,6 +1,4 @@ - - = 601" ?> @@ -135,8 +133,11 @@ LAUNCHAPPONEXIT=1 - - + + 1 OR VersionNT >= 603 ]]> + + + = 602 ]]> From 046c8d49178a6685600269d38fe391a6c9b95fb3 Mon Sep 17 00:00:00 2001 From: Ilya Date: Tue, 10 Jan 2023 07:38:16 +0500 Subject: [PATCH 285/779] Fix regression in RemoveNulls (#18881) --- .../host/msh/ConsoleHostUserInterface.cs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs index f399aa07b7e..1ab19d41c36 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs @@ -1910,22 +1910,24 @@ private char GetCharacterUnderCursor(Coordinates cursorPosition) #endif /// - /// Strip nulls from a string... + /// Strip nulls from a string. /// /// The string to process. - /// The string with any \0 characters removed... + /// The string with any '\0' characters removed. private static string RemoveNulls(string input) { - if (input.Contains('\0')) + if (!input.Contains('\0')) { return input; } - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(input.Length); foreach (char c in input) { if (c != '\0') + { sb.Append(c); + } } return sb.ToString(); From 31af38c22ac5039ddfd1c0319cac8c4c28fc8bea Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Tue, 10 Jan 2023 04:07:00 +0100 Subject: [PATCH 286/779] Create test to check if WebCmdlets decompress brotli-encoded data (#18905) --- .spelling | 1 + .../WebCmdlets.Tests.ps1 | 4 +++ test/tools/WebListener/BrotliFilter.cs | 33 +++++++++++++++++++ .../Controllers/CompressionController.cs | 8 +++++ test/tools/WebListener/README.md | 21 ++++++++++++ .../tools/WebListener/Views/Home/Index.cshtml | 1 + 6 files changed, 68 insertions(+) create mode 100644 test/tools/WebListener/BrotliFilter.cs diff --git a/.spelling b/.spelling index 3afd5ed7ada..eee58d26366 100644 --- a/.spelling +++ b/.spelling @@ -106,6 +106,7 @@ brcrista breakpoint brianbunke britishben +brotli brucepay bugfix build.json diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 index 0a84f60cd76..ef2d32746ed 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 @@ -584,11 +584,13 @@ Describe "Invoke-WebRequest tests" -Tags "Feature", "RequireAdminOnWindows" { # Perform the following operation for Invoke-WebRequest # gzip Returns gzip-encoded data. # deflate Returns deflate-encoded data. + # brotli Returns brotli-encoded data. # $dataEncodings = @("Chunked", "Compress", "Deflate", "GZip", "Identity") # Note: These are the supported options, but we do not have a web service to test them all. It "Invoke-WebRequest supports request that returns -encoded data." -TestCases @( @{ DataEncoding = "gzip" } @{ DataEncoding = "deflate" } + @{ DataEncoding = "brotli" } ) { param($dataEncoding) $uri = Get-WebListenerUrl -Test 'Compression' -TestValue $dataEncoding @@ -2228,11 +2230,13 @@ Describe "Invoke-RestMethod tests" -Tags "Feature", "RequireAdminOnWindows" { # Perform the following operation for Invoke-RestMethod # gzip Returns gzip-encoded data. # deflate Returns deflate-encoded data. + # brotli Returns brotli-encoded data. # $dataEncodings = @("Chunked", "Compress", "Deflate", "GZip", "Identity") # Note: These are the supported options, but we do not have a web service to test them all. It "Invoke-RestMethod supports request that returns -encoded data." -TestCases @( @{ DataEncoding = "gzip" } @{ DataEncoding = "deflate" } + @{ DataEncoding = "brotli" } ) { param($dataEncoding) $uri = Get-WebListenerUrl -Test 'Compression' -TestValue $dataEncoding diff --git a/test/tools/WebListener/BrotliFilter.cs b/test/tools/WebListener/BrotliFilter.cs new file mode 100644 index 00000000000..510bd1da2e3 --- /dev/null +++ b/test/tools/WebListener/BrotliFilter.cs @@ -0,0 +1,33 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.IO; +using System.IO.Compression; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Mvc.Filters; + +namespace mvc.Controllers +{ + internal sealed class BrotliFilter : ResultFilterAttribute + { + public override async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next) + { + var httpContext = context.HttpContext; + using (var memoryStream = new MemoryStream()) + { + var responseStream = httpContext.Response.Body; + httpContext.Response.Body = memoryStream; + + await next(); + + using (var compressedStream = new BrotliStream(responseStream, CompressionLevel.Fastest)) + { + httpContext.Response.Headers.Add("Content-Encoding", new[] { "br" }); + memoryStream.Seek(0, SeekOrigin.Begin); + await memoryStream.CopyToAsync(compressedStream); + } + } + } + } +} diff --git a/test/tools/WebListener/Controllers/CompressionController.cs b/test/tools/WebListener/Controllers/CompressionController.cs index f8fcd0c4d80..4043c774b79 100644 --- a/test/tools/WebListener/Controllers/CompressionController.cs +++ b/test/tools/WebListener/Controllers/CompressionController.cs @@ -37,6 +37,14 @@ public JsonResult Deflate() return getController.Index(); } + [BrotliFilter] + public JsonResult Brotli() + { + var getController = new GetController(); + getController.ControllerContext = this.ControllerContext; + return getController.Index(); + } + public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); diff --git a/test/tools/WebListener/README.md b/test/tools/WebListener/README.md index f4d84c3bb18..111a3b86240 100644 --- a/test/tools/WebListener/README.md +++ b/test/tools/WebListener/README.md @@ -143,6 +143,27 @@ Response when certificate is not provided in request: } ``` +### /Compression/Brotli/ + +Returns the same results as the Get test with brotli compression. + +```powershell +$uri = Get-WebListenerUrl -Test 'Compression' -TestValue 'Brotli' +Invoke-RestMethod -Uri $uri +``` + +```json +{ + "args": {}, + "origin": "127.0.0.1", + "headers": { + "User-Agent": "Mozilla/5.0 (Windows NT; Microsoft Windows 10.0.15063 ; en-US) PowerShell/6.0.0", + "Host": "localhost:8083" + }, + "url": "http://localhost:8083/Compression/Brotli" +} +``` + ### /Compression/Deflate/ Returns the same results as the Get test with deflate compression. diff --git a/test/tools/WebListener/Views/Home/Index.cshtml b/test/tools/WebListener/Views/Home/Index.cshtml index 78155781884..fb7e6746161 100644 --- a/test/tools/WebListener/Views/Home/Index.cshtml +++ b/test/tools/WebListener/Views/Home/Index.cshtml @@ -5,6 +5,7 @@
  • /Auth/Negotiate/ - Negotiate Authentication
  • /Auth/NTLM/ - NTLM Authentication
  • /Cert/ - Client Certificate Details
  • +
  • /Compression/Brotli/ - Returns brotli compressed response
  • /Compression/Deflate/ - Returns deflate compressed response
  • /Compression/Gzip/ - Returns gzip compressed response
  • /Delay/{seconds} - Delays response for seconds seconds.
  • From 8e14d2d7aa1d7bf3c3fbe7b2244c374d4b9f468e Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Tue, 10 Jan 2023 03:10:03 +0000 Subject: [PATCH 287/779] Enable get-help pattern tests on Unix (#18855) --- test/powershell/engine/Help/HelpSystem.Tests.ps1 | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/test/powershell/engine/Help/HelpSystem.Tests.ps1 b/test/powershell/engine/Help/HelpSystem.Tests.ps1 index 05d3d086a16..06e4e4ae22b 100644 --- a/test/powershell/engine/Help/HelpSystem.Tests.ps1 +++ b/test/powershell/engine/Help/HelpSystem.Tests.ps1 @@ -312,10 +312,6 @@ Describe "Get-Help should find help info within help files" -Tags @('CI') { Describe "Get-Help should find pattern help files" -Tags "CI" { - # There is a bug specific to Travis CI that suspends the test if "get-help" is used to search pattern string. This doesn't repro locally. - # This occurs even if Unix system just returns "Directory.GetFiles(path, pattern);" as the windows' code does. - # Since there's currently no way to get the vm from Travis CI and the test PASSES locally on both Ubuntu and MacOS, excluding pattern test under Unix system. - BeforeAll { $helpFile1 = "about_testCase1.help.txt" $helpFile2 = "about_testCase.2.help.txt" @@ -349,7 +345,7 @@ Describe "Get-Help should find pattern help files" -Tags "CI" { @{command = {Get-Help about_testCas?.2*}; testname = "test ?, * pattern with dot"; result = "about_test2"} ) - It "Get-Help should find pattern help files - " -TestCases $testcases -Pending: (-not $IsWindows) { + It "Get-Help should find pattern help files - " -TestCases $testcases { param ( $command, $result From 4481d14e1abf5f2ed27c496c00340ad7cbef4e1c Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 10 Jan 2023 09:46:56 -0800 Subject: [PATCH 288/779] Bump Microsoft.PowerShell.Native from 7.4.0-preview.1 to 7.4.0-preview.2 (#18910) --- .../System.Management.Automation.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/System.Management.Automation/System.Management.Automation.csproj b/src/System.Management.Automation/System.Management.Automation.csproj index 48fc97827f1..5a35c1c3f4e 100644 --- a/src/System.Management.Automation/System.Management.Automation.csproj +++ b/src/System.Management.Automation/System.Management.Automation.csproj @@ -46,7 +46,7 @@ - + From 465165fd972405fa0537ec13de78efd1f713714d Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Wed, 11 Jan 2023 17:39:04 +0100 Subject: [PATCH 289/779] Invoke-RestMethod -FollowRelLink fix links containing commas (#18829) --- .../WebCmdlet/Common/WebRequestPSCmdlet.Common.cs | 6 +++--- .../Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 | 10 ++++++++++ 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index e82bd7e5772..155e6f8e967 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -1799,7 +1799,7 @@ internal void ParseLinkHeader(HttpResponseMessage response, System.Uri requestUr _relationLink.Clear(); } - // we only support the URL in angle brackets and `rel`, other attributes are ignored + // We only support the URL in angle brackets and `rel`, other attributes are ignored // user can still parse it themselves via the Headers property const string pattern = "<(?.*?)>;\\s*rel=(?\")?(?(?(quoted).*?|[^,;]*))(?(quoted)\")"; IEnumerable links; @@ -1807,9 +1807,9 @@ internal void ParseLinkHeader(HttpResponseMessage response, System.Uri requestUr { foreach (string linkHeader in links) { - foreach (string link in linkHeader.Split(',')) + MatchCollection matchCollection = Regex.Matches(linkHeader, pattern); + foreach (Match match in matchCollection) { - Match match = Regex.Match(link, pattern); if (match.Success) { string url = match.Groups["url"].Value; diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 index ef2d32746ed..c2b3f110655 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 @@ -2442,6 +2442,16 @@ Describe "Invoke-RestMethod tests" -Tags "Feature", "RequireAdminOnWindows" { 1..3 | ForEach-Object { $result.Output[$_ - 1].linknumber | Should -BeExactly $_ } } + It "Validate Invoke-RestMethod -FollowRelLink correctly manages commas" { + $maxLinks = 5 + $uri = Get-WebListenerUrl -Test 'Link' -Query @{maxlinks = $maxLinks; type = "with,comma"} + $command = "Invoke-RestMethod -Uri '$uri' -FollowRelLink" + $result = ExecuteWebCommand -command $command + + $result.Output.Count | Should -BeExactly $maxLinks + 1..$maxLinks | ForEach-Object { $result.Output[$_ - 1].linknumber | Should -BeExactly $_ } + } + It "Verify Invoke-RestMethod supresses terminating errors with -SkipHttpErrorCheck" { $uri = Get-WebListenerUrl -Test 'Response' -Query $NotFoundQuery $command = "Invoke-RestMethod -SkipHttpErrorCheck -Uri '$uri'" From 66a2371b6edbe3ba7a033fb6280a04e80b517e26 Mon Sep 17 00:00:00 2001 From: Ikko Eltociear Ashimine Date: Thu, 12 Jan 2023 16:00:47 +0900 Subject: [PATCH 290/779] Fix typo in ModuleCmdletBase.cs (#18933) Implict -> Implicit --- .../engine/Modules/ModuleCmdletBase.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs index 117c19c9b1e..7c81939fe02 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs @@ -5723,7 +5723,7 @@ internal PSModuleInfo LoadModule(PSModuleInfo parentModule, string fileName, str if (!module.SessionState.Internal.UseExportList) { // For cross language boundaries don't implicitly export all functions, unless they are allowed nested modules. - // Implict function export is allowed when any of the following is true: + // Implicit function export is allowed when any of the following is true: // - Nested modules are allowed by module manifest // - The import context language mode is FullLanguage // - This script module not running as trusted (FullLanguage) From 292323c2100df4a80de21d965fc0fdfcbdf3ac92 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Thu, 12 Jan 2023 11:45:54 +0100 Subject: [PATCH 291/779] Simplification of GetHttpMethod and httpMethod in WebCmdlets (#18846) --- .../Common/InvokeRestMethodCommand.Common.cs | 2 +- .../Common/WebRequestPSCmdlet.Common.cs | 117 ++++++------------ 2 files changed, 41 insertions(+), 78 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs index a2418efbb86..59cc69c8346 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs @@ -48,7 +48,7 @@ public override string CustomMethod { get => base.CustomMethod; - set => base.CustomMethod = value; + set => base.CustomMethod = value.ToUpperInvariant(); } /// diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index 155e6f8e967..79362e5c5d6 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -271,7 +271,14 @@ public abstract partial class WebRequestPSCmdlet : PSCmdlet [Parameter(Mandatory = true, ParameterSetName = "CustomMethodNoProxy")] [Alias("CM")] [ValidateNotNullOrEmpty] - public virtual string CustomMethod { get; set; } + public virtual string CustomMethod + { + get => _custommethod; + + set => _custommethod = value.ToUpperInvariant(); + } + + private string _custommethod; #endregion @@ -388,7 +395,7 @@ public abstract partial class WebRequestPSCmdlet : PSCmdlet internal virtual void ValidateParameters() { - // sessions + // Sessions if (WebSession is not null && SessionVariable is not null) { ErrorRecord error = GetValidationError(WebCmdletStrings.SessionConflict, "WebCmdletSessionConflictException"); @@ -432,7 +439,7 @@ internal virtual void ValidateParameters() ThrowTerminatingError(error); } - // credentials + // Credentials if (UseDefaultCredentials && Credential is not null) { ErrorRecord error = GetValidationError(WebCmdletStrings.CredentialConflict, "WebCmdletCredentialConflictException"); @@ -451,7 +458,7 @@ internal virtual void ValidateParameters() ThrowTerminatingError(error); } - // request body content + // Request body content if (Body is not null && InFile is not null) { ErrorRecord error = GetValidationError(WebCmdletStrings.BodyConflict, "WebCmdletBodyConflictException"); @@ -470,7 +477,7 @@ internal virtual void ValidateParameters() ThrowTerminatingError(error); } - // validate InFile path + // Validate InFile path if (InFile is not null) { ProviderInfo provider = null; @@ -525,7 +532,7 @@ internal virtual void ValidateParameters() } } - // output ?? + // Output ?? if (PassThru && OutFile is null) { ErrorRecord error = GetValidationError(WebCmdletStrings.OutFileMissing, "WebCmdletOutFileMissingException", nameof(PassThru)); @@ -679,9 +686,7 @@ private Uri PrepareUri(Uri uri) // preprocess Body if content is a dictionary and method is GET (set as query) IDictionary bodyAsDictionary; LanguagePrimitives.TryConvertTo(Body, out bodyAsDictionary); - if (bodyAsDictionary is not null - && ((IsStandardMethodSet() && (Method == WebRequestMethod.Default || Method == WebRequestMethod.Get)) - || (IsCustomMethodSet() && CustomMethod.ToUpperInvariant() == "GET"))) + if (bodyAsDictionary is not null && (Method == WebRequestMethod.Default || Method == WebRequestMethod.Get || CustomMethod == "GET")) { UriBuilder uriBuilder = new(uri); if (uriBuilder.Query is not null && uriBuilder.Query.Length > 1) @@ -762,16 +767,6 @@ private ErrorRecord GetValidationError(string msg, string errorId, params object return error; } - private bool IsStandardMethodSet() - { - return (ParameterSetName == "StandardMethod" || ParameterSetName == "StandardMethodNoProxy"); - } - - private bool IsCustomMethodSet() - { - return (ParameterSetName == "CustomMethod" || ParameterSetName == "CustomMethodNoProxy"); - } - private string GetBasicAuthorizationHeader() { var password = new NetworkCredential(null, Credential.Password).Password; @@ -901,30 +896,18 @@ public abstract partial class WebRequestPSCmdlet : PSCmdlet /// private long _resumeFileSize = 0; - private HttpMethod GetHttpMethod(WebRequestMethod method) + private static HttpMethod GetHttpMethod(WebRequestMethod method) => method switch { - switch (Method) - { - case WebRequestMethod.Default: - case WebRequestMethod.Get: - return HttpMethod.Get; - case WebRequestMethod.Head: - return HttpMethod.Head; - case WebRequestMethod.Post: - return HttpMethod.Post; - case WebRequestMethod.Put: - return HttpMethod.Put; - case WebRequestMethod.Delete: - return HttpMethod.Delete; - case WebRequestMethod.Trace: - return HttpMethod.Trace; - case WebRequestMethod.Options: - return HttpMethod.Options; - default: - // Merge and Patch - return new HttpMethod(Method.ToString().ToUpperInvariant()); - } - } + WebRequestMethod.Default or WebRequestMethod.Get => HttpMethod.Get, + WebRequestMethod.Delete => HttpMethod.Delete, + WebRequestMethod.Head => HttpMethod.Head, + WebRequestMethod.Patch => HttpMethod.Patch, + WebRequestMethod.Post => HttpMethod.Post, + WebRequestMethod.Put => HttpMethod.Put, + WebRequestMethod.Options => HttpMethod.Options, + WebRequestMethod.Trace => HttpMethod.Trace, + _ => new HttpMethod(method.ToString().ToUpperInvariant()) + }; #region Virtual Methods @@ -1005,27 +988,7 @@ internal virtual HttpClient GetHttpClient(bool handleRedirect) internal virtual HttpRequestMessage GetRequest(Uri uri) { Uri requestUri = PrepareUri(uri); - HttpMethod httpMethod = null; - - switch (ParameterSetName) - { - case "StandardMethodNoProxy": - goto case "StandardMethod"; - case "StandardMethod": - // set the method if the parameter was provided - httpMethod = GetHttpMethod(Method); - break; - case "CustomMethodNoProxy": - goto case "CustomMethod"; - case "CustomMethod": - if (!string.IsNullOrEmpty(CustomMethod)) - { - // set the method if the parameter was provided - httpMethod = new HttpMethod(CustomMethod.ToUpperInvariant()); - } - - break; - } + HttpMethod httpMethod = string.IsNullOrEmpty(CustomMethod) ? GetHttpMethod(Method) : new HttpMethod(CustomMethod); // create the base WebRequest object var request = new HttpRequestMessage(httpMethod, requestUri); @@ -1130,7 +1093,7 @@ internal virtual void FillRequestStream(HttpRequestMessage request) // request } // ContentType is null - else if (Method == WebRequestMethod.Post || (IsCustomMethodSet() && CustomMethod.ToUpperInvariant() == "POST")) + else if (request.Method == HttpMethod.Post) { // Win8:545310 Invoke-WebRequest does not properly set MIME type for POST string contentType = null; @@ -1221,7 +1184,7 @@ internal virtual void FillRequestStream(HttpRequestMessage request) if (request.Content is null) { // If this is a Get request and there is no content, then don't fill in the content as empty content gets rejected by some web services per RFC7230 - if ((IsStandardMethodSet() && request.Method == HttpMethod.Get && ContentType is null) || (IsCustomMethodSet() && CustomMethod.ToUpperInvariant() == "GET")) + if (request.Method == HttpMethod.Get && ContentType is null) { return; } @@ -1344,10 +1307,10 @@ internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestM // Request again without the Range header because the server indicated the range was not satisfiable. // This happens when the local file is larger than the remote file. // If the size of the remote file is the same as the local file, there is nothing to resume. - if (Resume.IsPresent && - response.StatusCode == HttpStatusCode.RequestedRangeNotSatisfiable && - (response.Content.Headers.ContentRange.HasLength && - response.Content.Headers.ContentRange.Length != _resumeFileSize)) + if (Resume.IsPresent + && response.StatusCode == HttpStatusCode.RequestedRangeNotSatisfiable + && (response.Content.Headers.ContentRange.HasLength + && response.Content.Headers.ContentRange.Length != _resumeFileSize)) { _cancelToken.Cancel(); @@ -1451,10 +1414,10 @@ protected override void ProcessRecord() // if the request contains an authorization header and PreserveAuthorizationOnRedirect is not set, // it needs to be stripped on the first redirect. - bool keepAuthorization = WebSession is not null && - WebSession.Headers is not null && - PreserveAuthorizationOnRedirect.IsPresent && - WebSession.Headers.ContainsKey(HttpKnownHeaderNames.Authorization); + bool keepAuthorization = WebSession is not null + && WebSession.Headers is not null + && PreserveAuthorizationOnRedirect.IsPresent + && WebSession.Headers.ContainsKey(HttpKnownHeaderNames.Authorization); using (HttpClient client = GetHttpClient(keepAuthorization)) { @@ -1505,10 +1468,10 @@ WebSession.Headers is not null && // Check if the Resume range was not satisfiable because the file already completed downloading. // This happens when the local file is the same size as the remote file. - if (Resume.IsPresent && - response.StatusCode == HttpStatusCode.RequestedRangeNotSatisfiable && - response.Content.Headers.ContentRange.HasLength && - response.Content.Headers.ContentRange.Length == _resumeFileSize) + if (Resume.IsPresent + && response.StatusCode == HttpStatusCode.RequestedRangeNotSatisfiable + && response.Content.Headers.ContentRange.HasLength + && response.Content.Headers.ContentRange.Length == _resumeFileSize) { _isSuccess = true; WriteVerbose(string.Format( From ca4b6162f49aff1b89fa624a2e059794c740b6cb Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Thu, 12 Jan 2023 13:08:28 +0100 Subject: [PATCH 292/779] Add AllowInsecureRedirect switch to Web cmdlets (#18546) --- .../WebCmdlet/Common/WebRequestPSCmdlet.Common.cs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index 79362e5c5d6..e265feae33b 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -198,6 +198,12 @@ public abstract partial class WebRequestPSCmdlet : PSCmdlet [Parameter] public virtual SecureString Token { get; set; } + /// + /// Gets or sets the AllowInsecureRedirect property used to follow HTTP redirects from HTTPS. + /// + [Parameter] + public virtual SwitchParameter AllowInsecureRedirect { get; set; } + #endregion #region Headers @@ -951,7 +957,7 @@ internal virtual HttpClient GetHttpClient(bool handleRedirect) } // This indicates GetResponse will handle redirects. - if (handleRedirect) + if (handleRedirect || AllowInsecureRedirect) { handler.AllowAutoRedirect = false; } @@ -1276,7 +1282,7 @@ internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestM _cancelToken = new CancellationTokenSource(); response = client.SendAsync(req, HttpCompletionOption.ResponseHeadersRead, _cancelToken.Token).GetAwaiter().GetResult(); - if (keepAuthorization && IsRedirectCode(response.StatusCode) && response.Headers.Location is not null) + if ((keepAuthorization || (AllowInsecureRedirect && (WebSession.MaximumRedirection > 0 || WebSession.MaximumRedirection == -1))) && IsRedirectCode(response.StatusCode) && response.Headers.Location != null) { _cancelToken.Cancel(); _cancelToken = null; From f018beedffa4df3ac8c5947a8e15b19018c159a1 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Fri, 13 Jan 2023 13:37:55 +0100 Subject: [PATCH 293/779] Add tests for Allowinsecureredirect parameter in Web cmdlets (#18939) --- .../WebCmdlets.Tests.ps1 | 75 +++++++++++++++++++ .../Controllers/RedirectController.cs | 8 +- 2 files changed, 82 insertions(+), 1 deletion(-) diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 index c2b3f110655..b930c27d7d9 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 @@ -514,6 +514,26 @@ Describe "Invoke-WebRequest tests" -Tags "Feature", "RequireAdminOnWindows" { $result.Error.FullyQualifiedErrorId | Should -Be "WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand" } + It "Validate Invoke-WebRequest redirect with -Query destination Http" { + $httpUri = Get-WebListenerUrl -Test 'Get' + $uri = Get-WebListenerUrl -Test 'Redirect' -Query @{destination = $httpUri} + $command = "Invoke-WebRequest -Uri '$uri'" + + $result = ExecuteWebCommand -command $command + $jsonContent = $result.Output.Content | ConvertFrom-Json + $jsonContent.headers.Host | Should -Match $httpUri.Authority + } + + It "Validate Invoke-WebRequest redirect with -Query destination Https" { + $httpsUri = Get-WebListenerUrl -Test 'Get' -Https + $uri = Get-WebListenerUrl -Test 'Redirect' -Https -Query @{destination = $httpsUri} + $command = "Invoke-WebRequest -Uri '$uri' -SkipCertificateCheck" + + $result = ExecuteWebCommand -command $command + $jsonContent = $result.Output.Content | ConvertFrom-Json + $jsonContent.headers.Host | Should -Match $httpsUri.Authority + } + It "Invoke-WebRequest supports request that returns page containing UTF-8 data." { $uri = Get-WebListenerUrl -Test 'Encoding' -TestValue 'Utf8' $command = "Invoke-WebRequest -Uri '$uri'" @@ -937,6 +957,25 @@ Describe "Invoke-WebRequest tests" -Tags "Feature", "RequireAdminOnWindows" { $response.Error.Exception.Response.StatusCode | Should -Be $StatusCode $response.Error.Exception.Response.Headers.Location | Should -BeNullOrEmpty } + + It "Validate Invoke-WebRequest Https to Http redirect with -AllowInsecureRedirect" { + $httpUri = Get-WebListenerUrl -Test 'Get' + $uri = Get-WebListenerUrl -Test 'Redirect' -Https -Query @{destination = $httpUri} + $command = "Invoke-WebRequest -Uri '$uri' -SkipCertificateCheck -AllowInsecureRedirect" + + $result = ExecuteWebCommand -command $command + $jsonContent = $result.Output.Content | ConvertFrom-Json + $jsonContent.headers.Host | Should -Match $httpUri.Authority + } + + It "Validate Invoke-WebRequest Https to Http redirect without -AllowInsecureRedirect" { + $httpUri = Get-WebListenerUrl -Test 'Get' + $uri = Get-WebListenerUrl -Test 'Redirect' -Https -Query @{destination = $httpUri} + $command = "Invoke-WebRequest -Uri '$uri' -SkipCertificateCheck" + + $result = ExecuteWebCommand -command $command + $result.Error.FullyQualifiedErrorId | Should -Be "WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand" + } } @@ -2170,6 +2209,24 @@ Describe "Invoke-RestMethod tests" -Tags "Feature", "RequireAdminOnWindows" { $result.Error.FullyQualifiedErrorId | Should -Be "WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand" } + It "Validate Invoke-RestMethod redirect with -Query destination Http" { + $httpUri = Get-WebListenerUrl -Test 'Get' + $uri = Get-WebListenerUrl -Test 'Redirect' -Query @{destination = $httpUri} + $command = "Invoke-RestMethod -Uri '$uri'" + + $result = ExecuteWebCommand -command $command + $result.Output.Headers.Host | Should -Be $httpUri.Authority + } + + It "Validate Invoke-RestMethod redirect with -Query destination Https" { + $httpsUri = Get-WebListenerUrl -Test 'Get' -Https + $uri = Get-WebListenerUrl -Test 'Redirect' -Https -Query @{destination = $httpsUri} + $command = "Invoke-RestMethod -Uri '$uri' -SkipCertificateCheck" + + $result = ExecuteWebCommand -command $command + $result.Output.Headers.Host | Should -Be $httpsUri.Authority + } + It "Invoke-RestMethod supports request that returns page containing UTF-8 data." { $uri = Get-WebListenerUrl -Test 'Encoding' -TestValue 'Utf8' $command = "Invoke-RestMethod -Uri '$uri'" @@ -2595,6 +2652,24 @@ Describe "Invoke-RestMethod tests" -Tags "Feature", "RequireAdminOnWindows" { $response.Error.Exception.Response.Headers.Location | Should -BeNullOrEmpty } + It "Validate Invoke-RestMethod Https to Http redirect with -AllowInsecureRedirect" { + $httpUri = Get-WebListenerUrl -Test 'Get' + $uri = Get-WebListenerUrl -Test 'Redirect' -Https -Query @{destination = $httpUri} + $command = "Invoke-RestMethod -Uri '$uri' -SkipCertificateCheck -AllowInsecureRedirect" + + $result = ExecuteWebCommand -command $command + $result.Output.Headers.Host | Should -Be $httpUri.Authority + } + + It "Validate Invoke-RestMethod Https to Http redirect without -AllowInsecureRedirect" { + $httpUri = Get-WebListenerUrl -Test 'Get' + $uri = Get-WebListenerUrl -Test 'Redirect' -Https -Query @{destination = $httpUri} + $command = "Invoke-RestMethod -Uri '$uri' -SkipCertificateCheck" + + $result = ExecuteWebCommand -command $command + $result.Error.FullyQualifiedErrorId | Should -Be "WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand" + } + #endregion Redirect tests Context "Invoke-RestMethod SkipHeaderVerification Tests" { diff --git a/test/tools/WebListener/Controllers/RedirectController.cs b/test/tools/WebListener/Controllers/RedirectController.cs index 1b7df04f3b3..551db38055d 100644 --- a/test/tools/WebListener/Controllers/RedirectController.cs +++ b/test/tools/WebListener/Controllers/RedirectController.cs @@ -21,9 +21,10 @@ public class RedirectController : Controller public IActionResult Index(int count) { string url = Regex.Replace(input: Request.GetDisplayUrl(), pattern: "\\/Redirect.*", replacement: string.Empty, options: RegexOptions.IgnoreCase); + var destinationIsPresent = Request.Query.TryGetValue("destination", out StringValues destination); if (count <= 1) { - url = $"{url}/Get/"; + url = destinationIsPresent ? destination.FirstOrDefault() : $"{url}/Get/"; } else { @@ -44,6 +45,11 @@ public IActionResult Index(int count) url = new Uri($"{url}?type={type.FirstOrDefault()}").PathAndQuery; Response.Redirect(url, false); } + else if (destinationIsPresent) + { + Response.StatusCode = 302; + Response.Headers.Add("Location", url); + } else { Response.Redirect(url, false); From 2baeb1a7f0e6b61b4d237bcce57d60a803ea821f Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Fri, 13 Jan 2023 05:00:20 -0800 Subject: [PATCH 294/779] Fix `Get-Error` to work with strict mode (#18895) --- .../DefaultFormatters/PowerShellCore_format_ps1xml.cs | 8 +++----- .../Microsoft.PowerShell.Utility/Get-Error.Tests.ps1 | 5 +++++ 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs index 549a4e6d4b7..c490f9e7a64 100644 --- a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs +++ b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs @@ -1016,10 +1016,11 @@ private static IEnumerable ViewsOf_System_Management_Autom CustomControl.Create(outOfBand: true) .StartEntry() .AddScriptBlockExpressionBinding(@" + $errorColor = '' + $commandPrefix = '' if (@('NativeCommandErrorMessage','NativeCommandError') -notcontains $_.FullyQualifiedErrorId -and @('CategoryView','ConciseView','DetailedView') -notcontains $ErrorView) { $myinv = $_.InvocationInfo - $errorColor = '' if ($Host.UI.SupportsVirtualTerminal) { $errorColor = $PSStyle.Formatting.Error } @@ -1070,10 +1071,7 @@ private static IEnumerable ViewsOf_System_Management_Autom } } - if ($commandPrefix) - { - $errorColor + $commandPrefix - } + $errorColor + $commandPrefix ") .AddScriptBlockExpressionBinding(@" Set-StrictMode -Off diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-Error.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-Error.Tests.ps1 index 624649fdfc4..1d89bf6c1fa 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-Error.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-Error.Tests.ps1 @@ -145,4 +145,9 @@ Describe 'Get-Error tests' -Tag CI { } } } + + It 'Get-Error works with strict mode' { + $out = pwsh -noprofile -command 'Set-StrictMode -Version Latest; $PSStyle.OutputRendering = "PlainText"; 1/0; Get-Error' | Out-String + $out | Should -Match "Message : Attempted to divide by zero." + } } From b1d87fed49c057f3af9376eb4d6b635b0d1090af Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 13 Jan 2023 13:03:22 +0000 Subject: [PATCH 295/779] Bump Microsoft.Extensions.ObjectPool from 7.0.1 to 7.0.2 (#18925) Bumps [Microsoft.Extensions.ObjectPool](https://github.com/dotnet/aspnetcore) from 7.0.1 to 7.0.2. - [Release notes](https://github.com/dotnet/aspnetcore/releases) - [Changelog](https://github.com/dotnet/aspnetcore/blob/main/docs/ReleasePlanning.md) - [Commits](https://github.com/dotnet/aspnetcore/compare/v7.0.1...v7.0.2) --- updated-dependencies: - dependency-name: Microsoft.Extensions.ObjectPool dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj b/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj index 1f5b182935c..1b75056dd93 100644 --- a/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj +++ b/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj @@ -17,7 +17,7 @@ - + From 282fc5fc0887135d336ceb76a6cb5b6ff553ebac Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Fri, 13 Jan 2023 14:31:03 +0100 Subject: [PATCH 296/779] Fix bug with managing redirection and keepAuthorization in Web cmdlets (#18902) --- .../Common/WebRequestPSCmdlet.Common.cs | 40 +++++++++---------- .../WebCmdlets.Tests.ps1 | 20 +++++++++- 2 files changed, 36 insertions(+), 24 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index e265feae33b..3dcf289761a 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -957,20 +957,13 @@ internal virtual HttpClient GetHttpClient(bool handleRedirect) } // This indicates GetResponse will handle redirects. - if (handleRedirect || AllowInsecureRedirect) + if (handleRedirect || WebSession.MaximumRedirection == 0) { handler.AllowAutoRedirect = false; } - else if (WebSession.MaximumRedirection > -1) + else if (WebSession.MaximumRedirection > 0) { - if (WebSession.MaximumRedirection == 0) - { - handler.AllowAutoRedirect = false; - } - else - { - handler.MaxAutomaticRedirections = WebSession.MaximumRedirection; - } + handler.MaxAutomaticRedirections = WebSession.MaximumRedirection; } handler.SslProtocols = (SslProtocols)SslProtocol; @@ -1263,7 +1256,7 @@ private bool ShouldRetry(HttpStatusCode code) ); } - internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestMessage request, bool keepAuthorization) + internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestMessage request, bool handleRedirect) { ArgumentNullException.ThrowIfNull(client); @@ -1282,7 +1275,10 @@ internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestM _cancelToken = new CancellationTokenSource(); response = client.SendAsync(req, HttpCompletionOption.ResponseHeadersRead, _cancelToken.Token).GetAwaiter().GetResult(); - if ((keepAuthorization || (AllowInsecureRedirect && (WebSession.MaximumRedirection > 0 || WebSession.MaximumRedirection == -1))) && IsRedirectCode(response.StatusCode) && response.Headers.Location != null) + if (handleRedirect + && WebSession.MaximumRedirection is not 0 + && IsRedirectCode(response.StatusCode) + && response.Headers.Location is not null) { _cancelToken.Cancel(); _cancelToken = null; @@ -1303,10 +1299,10 @@ internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestM currentUri = new Uri(request.RequestUri, response.Headers.Location); // Continue to handle redirection - using (client = GetHttpClient(handleRedirect: true)) + using (client = GetHttpClient(handleRedirect)) using (HttpRequestMessage redirectRequest = GetRequest(currentUri)) { - response = GetResponse(client, redirectRequest, keepAuthorization); + response = GetResponse(client, redirectRequest, handleRedirect); } } @@ -1344,7 +1340,7 @@ internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestM WriteVerbose(reqVerboseMsg); - return GetResponse(client, requestWithoutRange, keepAuthorization); + return GetResponse(client, requestWithoutRange, handleRedirect); } } @@ -1418,14 +1414,14 @@ protected override void ProcessRecord() ValidateParameters(); PrepareSession(); - // if the request contains an authorization header and PreserveAuthorizationOnRedirect is not set, + // If the request contains an authorization header and PreserveAuthorizationOnRedirect is not set, // it needs to be stripped on the first redirect. - bool keepAuthorization = WebSession is not null - && WebSession.Headers is not null - && PreserveAuthorizationOnRedirect.IsPresent - && WebSession.Headers.ContainsKey(HttpKnownHeaderNames.Authorization); + bool keepAuthorizationOnRedirect = PreserveAuthorizationOnRedirect.IsPresent + && WebSession.Headers.ContainsKey(HttpKnownHeaderNames.Authorization); + + bool handleRedirect = keepAuthorizationOnRedirect || AllowInsecureRedirect; - using (HttpClient client = GetHttpClient(keepAuthorization)) + using (HttpClient client = GetHttpClient(handleRedirect)) { int followedRelLink = 0; Uri uri = Uri; @@ -1459,7 +1455,7 @@ protected override void ProcessRecord() WriteVerbose(reqVerboseMsg); - HttpResponseMessage response = GetResponse(client, request, keepAuthorization); + HttpResponseMessage response = GetResponse(client, request, handleRedirect); string contentType = ContentHelper.GetContentType(response); string respVerboseMsg = string.Format( diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 index b930c27d7d9..285be044eb4 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 @@ -133,14 +133,22 @@ function ExecuteRedirectRequest { $Method = 'GET', [switch] - $PreserveAuthorizationOnRedirect + $PreserveAuthorizationOnRedirect, + + [ValidateRange(0, [int]::MaxValue)] + [int] + $MaximumRedirection ) $result = [PSObject]@{Output = $null; Error = $null; Content = $null} try { $headers = @{"Authorization" = "test"} if ($Cmdlet -eq 'Invoke-WebRequest') { - $result.Output = Invoke-WebRequest -Uri $uri -Headers $headers -PreserveAuthorizationOnRedirect:$PreserveAuthorizationOnRedirect.IsPresent -Method $Method + if ($MaximumRedirection -gt 0) { + $result.Output = Invoke-WebRequest -Uri $uri -Headers $headers -PreserveAuthorizationOnRedirect:$PreserveAuthorizationOnRedirect.IsPresent -Method $Method -MaximumRedirection:$MaximumRedirection + } else { + $result.Output = Invoke-WebRequest -Uri $uri -Headers $headers -PreserveAuthorizationOnRedirect:$PreserveAuthorizationOnRedirect.IsPresent -Method $Method + } $result.Content = $result.Output.Content | ConvertFrom-Json } else { $result.Output = Invoke-RestMethod -Uri $uri -Headers $headers -PreserveAuthorizationOnRedirect:$PreserveAuthorizationOnRedirect.IsPresent -Method $Method @@ -885,6 +893,14 @@ Describe "Invoke-WebRequest tests" -Tags "Feature", "RequireAdminOnWindows" { $response.Error | Should -BeNullOrEmpty $response.Content.Headers."Authorization" | Should -BeExactly "test" } + + It "Validates Invoke-WebRequest with -PreserveAuthorizationOnRedirect respects -MaximumRedirection on redirect: " -TestCases $redirectTests { + param($redirectType, $redirectedMethod) + $uri = Get-WebListenerUrl -Test 'Redirect' -TestValue '3' -Query @{type = $redirectType} + $response = ExecuteRedirectRequest -Uri $uri -PreserveAuthorizationOnRedirect -MaximumRedirection 2 + + $response.Error.FullyQualifiedErrorId | Should -Be "WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand" + } It "Validates Invoke-WebRequest preserves the authorization header on multiple redirects: " -TestCases $redirectTests { param($redirectType) From 1d34ad8b65ef8b0f595297204f9d0a7ac285483a Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Sat, 14 Jan 2023 00:45:05 +0000 Subject: [PATCH 297/779] Bump `BenchmarkDotNet` to `0.13.3` (#18878) --- .../BenchmarkDotNet.Extensions.csproj | 4 ++-- test/perf/dotnet-tools/ResultsComparer/ResultsComparer.csproj | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/BenchmarkDotNet.Extensions.csproj b/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/BenchmarkDotNet.Extensions.csproj index 02a372fa115..614d453b930 100644 --- a/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/BenchmarkDotNet.Extensions.csproj +++ b/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/BenchmarkDotNet.Extensions.csproj @@ -6,8 +6,8 @@ - - + + diff --git a/test/perf/dotnet-tools/ResultsComparer/ResultsComparer.csproj b/test/perf/dotnet-tools/ResultsComparer/ResultsComparer.csproj index c40f05d7b77..c1028433f4c 100644 --- a/test/perf/dotnet-tools/ResultsComparer/ResultsComparer.csproj +++ b/test/perf/dotnet-tools/ResultsComparer/ResultsComparer.csproj @@ -9,7 +9,7 @@ - + From 9ffa9a22766fa2c0e55f22d642d3ac8b18158922 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Mon, 16 Jan 2023 12:08:52 +0100 Subject: [PATCH 298/779] HttpKnownHeaderNames update headers list (#18947) --- .../WebCmdlet/CoreCLR/HttpKnownHeaderNames.cs | 27 +++++++++++++++---- 1 file changed, 22 insertions(+), 5 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/HttpKnownHeaderNames.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/HttpKnownHeaderNames.cs index 0acd7c33567..e0a9b3760ef 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/HttpKnownHeaderNames.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/HttpKnownHeaderNames.cs @@ -11,14 +11,22 @@ internal static class HttpKnownHeaderNames #region Known_HTTP_Header_Names // Known HTTP Header Names. - // List comes from corefx/System/Net/HttpKnownHeaderNames.cs + // List comes from https://github.com/dotnet/runtime/blob/51a8dd5323721b363e61069575511f783e7ea6d3/src/libraries/Common/src/System/Net/HttpKnownHeaderNames.cs public const string Accept = "Accept"; public const string AcceptCharset = "Accept-Charset"; public const string AcceptEncoding = "Accept-Encoding"; public const string AcceptLanguage = "Accept-Language"; + public const string AcceptPatch = "Accept-Patch"; public const string AcceptRanges = "Accept-Ranges"; + public const string AccessControlAllowCredentials = "Access-Control-Allow-Credentials"; + public const string AccessControlAllowHeaders = "Access-Control-Allow-Headers"; + public const string AccessControlAllowMethods = "Access-Control-Allow-Methods"; + public const string AccessControlAllowOrigin = "Access-Control-Allow-Origin"; + public const string AccessControlExposeHeaders = "Access-Control-Expose-Headers"; + public const string AccessControlMaxAge = "Access-Control-Max-Age"; public const string Age = "Age"; public const string Allow = "Allow"; + public const string AltSvc = "Alt-Svc"; public const string Authorization = "Authorization"; public const string CacheControl = "Cache-Control"; public const string Connection = "Connection"; @@ -29,6 +37,7 @@ internal static class HttpKnownHeaderNames public const string ContentLocation = "Content-Location"; public const string ContentMD5 = "Content-MD5"; public const string ContentRange = "Content-Range"; + public const string ContentSecurityPolicy = "Content-Security-Policy"; public const string ContentType = "Content-Type"; public const string Cookie = "Cookie"; public const string Cookie2 = "Cookie2"; @@ -45,6 +54,7 @@ internal static class HttpKnownHeaderNames public const string IfUnmodifiedSince = "If-Unmodified-Since"; public const string KeepAlive = "Keep-Alive"; public const string LastModified = "Last-Modified"; + public const string Link = "Link"; public const string Location = "Location"; public const string MaxForwards = "Max-Forwards"; public const string Origin = "Origin"; @@ -53,6 +63,7 @@ internal static class HttpKnownHeaderNames public const string ProxyAuthenticate = "Proxy-Authenticate"; public const string ProxyAuthorization = "Proxy-Authorization"; public const string ProxyConnection = "Proxy-Connection"; + public const string PublicKeyPins = "Public-Key-Pins"; public const string Range = "Range"; public const string Referer = "Referer"; // NB: The spelling-mistake "Referer" for "Referrer" must be matched. public const string RetryAfter = "Retry-After"; @@ -64,17 +75,26 @@ internal static class HttpKnownHeaderNames public const string Server = "Server"; public const string SetCookie = "Set-Cookie"; public const string SetCookie2 = "Set-Cookie2"; + public const string StrictTransportSecurity = "Strict-Transport-Security"; public const string TE = "TE"; + public const string TSV = "TSV"; public const string Trailer = "Trailer"; public const string TransferEncoding = "Transfer-Encoding"; public const string Upgrade = "Upgrade"; + public const string UpgradeInsecureRequests = "Upgrade-Insecure-Requests"; public const string UserAgent = "User-Agent"; public const string Vary = "Vary"; public const string Via = "Via"; public const string WWWAuthenticate = "WWW-Authenticate"; public const string Warning = "Warning"; public const string XAspNetVersion = "X-AspNet-Version"; + public const string XContentDuration = "X-Content-Duration"; + public const string XContentTypeOptions = "X-Content-Type-Options"; + public const string XFrameOptions = "X-Frame-Options"; + public const string XMSEdgeRef = "X-MSEdge-Ref"; public const string XPoweredBy = "X-Powered-By"; + public const string XRequestID = "X-Request-ID"; + public const string XUACompatible = "X-UA-Compatible"; #endregion Known_HTTP_Header_Names @@ -98,9 +118,6 @@ static HttpKnownHeaderNames() s_contentHeaderSet.Add(HttpKnownHeaderNames.LastModified); } - internal static HashSet ContentHeaders - { - get => s_contentHeaderSet; - } + internal static HashSet ContentHeaders => s_contentHeaderSet; } } From 2df06f2e2052642a8b5929a0b556633ed0736a19 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Mon, 16 Jan 2023 12:29:27 +0100 Subject: [PATCH 299/779] Small cleanup common code of webcmdlets (#18946) --- .../BasicHtmlWebResponseObject.Common.cs | 7 +- .../WebCmdlet/Common/ContentHelper.Common.cs | 28 +++-- .../Common/InvokeRestMethodCommand.Common.cs | 9 +- .../Common/WebRequestPSCmdlet.Common.cs | 13 +- .../utility/WebCmdlet/CoreCLR/WebProxy.cs | 24 +--- .../CoreCLR/WebResponseHelper.CoreClr.cs | 27 +--- .../WebResponseObjectFactory.CoreClr.cs | 2 +- .../utility/WebCmdlet/FormObjectCollection.cs | 2 +- .../commands/utility/WebCmdlet/PSUserAgent.cs | 115 +++--------------- .../WebCmdlet/WebCmdletElementCollection.cs | 21 +--- 10 files changed, 57 insertions(+), 191 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/BasicHtmlWebResponseObject.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/BasicHtmlWebResponseObject.Common.cs index 7c922af0898..de624276a2a 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/BasicHtmlWebResponseObject.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/BasicHtmlWebResponseObject.Common.cs @@ -33,9 +33,7 @@ public class BasicHtmlWebResponseObject : WebResponseObject /// Initializes a new instance of the class. ///
    /// - public BasicHtmlWebResponseObject(HttpResponseMessage response) - : this(response, null) - { } + public BasicHtmlWebResponseObject(HttpResponseMessage response) : this(response, null) { } /// /// Initializes a new instance of the class @@ -43,8 +41,7 @@ public BasicHtmlWebResponseObject(HttpResponseMessage response) /// /// /// - public BasicHtmlWebResponseObject(HttpResponseMessage response, Stream contentStream) - : base(response, contentStream) + public BasicHtmlWebResponseObject(HttpResponseMessage response, Stream contentStream) : base(response, contentStream) { EnsureHtmlParser(); InitializeContent(); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs index 657f527ab0b..bf4693c1e3e 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs @@ -21,11 +21,7 @@ internal static string GetContentType(HttpResponseMessage response) return response.Content.Headers.ContentType?.MediaType; } - internal static Encoding GetDefaultEncoding() - { - Encoding encoding = Encoding.UTF8; - return encoding; - } + internal static Encoding GetDefaultEncoding() => Encoding.UTF8; internal static StringBuilder GetRawContentHeader(HttpResponseMessage response) { @@ -95,12 +91,14 @@ internal static bool IsXml(string contentType) private static bool CheckIsJson(string contentType) { if (string.IsNullOrEmpty(contentType)) + { return false; + } - // the correct type for JSON content, as specified in RFC 4627 + // The correct type for JSON content, as specified in RFC 4627 bool isJson = contentType.Equals("application/json", StringComparison.OrdinalIgnoreCase); - // add in these other "javascript" related types that + // Add in these other "javascript" related types that // sometimes get sent down as the mime type for JSON content isJson |= contentType.Equals("text/json", StringComparison.OrdinalIgnoreCase) || contentType.Equals("application/x-javascript", StringComparison.OrdinalIgnoreCase) @@ -108,15 +106,17 @@ private static bool CheckIsJson(string contentType) || contentType.Equals("application/javascript", StringComparison.OrdinalIgnoreCase) || contentType.Equals("text/javascript", StringComparison.OrdinalIgnoreCase); - return (isJson); + return isJson; } private static bool CheckIsText(string contentType) { if (string.IsNullOrEmpty(contentType)) + { return false; + } - // any text, xml or json types are text + // Any text, xml or json types are text bool isText = contentType.StartsWith("text/", StringComparison.OrdinalIgnoreCase) || CheckIsXml(contentType) || CheckIsJson(contentType); @@ -145,13 +145,15 @@ private static bool CheckIsText(string contentType) } } - return (isText); + return isText; } private static bool CheckIsXml(string contentType) { if (string.IsNullOrEmpty(contentType)) + { return false; + } // RFC 3023: Media types with the suffix "+xml" are XML bool isXml = (contentType.Equals("application/xml", StringComparison.OrdinalIgnoreCase) @@ -159,16 +161,18 @@ private static bool CheckIsXml(string contentType) || contentType.Equals("application/xml-dtd", StringComparison.OrdinalIgnoreCase)); isXml |= contentType.EndsWith("+xml", StringComparison.OrdinalIgnoreCase); - return (isXml); + return isXml; } private static string GetContentTypeSignature(string contentType) { if (string.IsNullOrEmpty(contentType)) + { return null; + } string sig = contentType.Split(';', 2)[0].ToUpperInvariant(); - return (sig); + return sig; } #endregion Private Helper Methods diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs index 59cc69c8346..7ff2095b24b 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs @@ -142,7 +142,7 @@ internal override void ProcessResponse(HttpResponseMessage response) } // NOTE: Tests use this verbose output to verify the encoding. - WriteVerbose(string.Format(System.Globalization.CultureInfo.InvariantCulture, "Content encoding: {0}", encodingVerboseName)); + WriteVerbose(string.Format(System.Globalization.CultureInfo.InvariantCulture, $"Content encoding: {encodingVerboseName}")); bool convertSuccess = false; @@ -331,12 +331,7 @@ private static bool TryConvertToJson(string json, out object obj, ref Exception converted = true; } } - catch (ArgumentException ex) - { - exRef = ex; - obj = null; - } - catch (InvalidOperationException ex) + catch (Exception ex) when (ex is ArgumentException || ex is InvalidOperationException) { exRef = ex; obj = null; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index 3dcf289761a..5dfb4f7e877 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -776,14 +776,14 @@ private ErrorRecord GetValidationError(string msg, string errorId, params object private string GetBasicAuthorizationHeader() { var password = new NetworkCredential(null, Credential.Password).Password; - string unencoded = string.Format("{0}:{1}", Credential.UserName, password); + string unencoded = string.Format($"{Credential.UserName}:{password}"); byte[] bytes = Encoding.UTF8.GetBytes(unencoded); - return string.Format("Basic {0}", Convert.ToBase64String(bytes)); + return string.Format($"Basic {Convert.ToBase64String(bytes)}"); } private string GetBearerAuthorizationHeader() { - return string.Format("Bearer {0}", new NetworkCredential(string.Empty, Token).Password); + return string.Format($"Bearer {new NetworkCredential(string.Empty, Token).Password}"); } private void ProcessAuthentication() @@ -798,7 +798,7 @@ private void ProcessAuthentication() } else { - Diagnostics.Assert(false, string.Format("Unrecognized Authentication value: {0}", Authentication)); + Diagnostics.Assert(false, string.Format($"Unrecognized Authentication value: {Authentication}")); } } @@ -1170,10 +1170,7 @@ internal virtual void FillRequestStream(HttpRequestMessage request) } catch (UnauthorizedAccessException) { - string msg = string.Format( - CultureInfo.InvariantCulture, - WebCmdletStrings.AccessDenied, - _originalFilePath); + string msg = string.Format(CultureInfo.InvariantCulture, WebCmdletStrings.AccessDenied, _originalFilePath); throw new UnauthorizedAccessException(msg); } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebProxy.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebProxy.cs index ddba7af774e..29e9da1f28d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebProxy.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebProxy.cs @@ -20,27 +20,18 @@ internal WebProxy(Uri address) public ICredentials Credentials { - get { return _credentials; } + get => _credentials; - set { _credentials = value; } + set => _credentials = value; } - internal bool BypassProxyOnLocal - { - get; set; - } + internal bool BypassProxyOnLocal { get; set; } internal bool UseDefaultCredentials { - get - { - return _credentials == CredentialCache.DefaultCredentials; - } + get => _credentials == CredentialCache.DefaultCredentials; - set - { - _credentials = value ? CredentialCache.DefaultCredentials : null; - } + set => _credentials = value ? CredentialCache.DefaultCredentials : null; } public Uri GetProxy(Uri destination) @@ -55,9 +46,6 @@ public Uri GetProxy(Uri destination) return _proxyAddress; } - public bool IsBypassed(Uri host) - { - return host.IsLoopback; - } + public bool IsBypassed(Uri host) => host.IsLoopback; } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseHelper.CoreClr.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseHelper.CoreClr.cs index dc2f734d6bd..43dee2fa029 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseHelper.CoreClr.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseHelper.CoreClr.cs @@ -10,11 +10,7 @@ namespace Microsoft.PowerShell.Commands { internal static class WebResponseHelper { - internal static string GetCharacterSet(HttpResponseMessage response) - { - string characterSet = response.Content.Headers.ContentType.CharSet; - return characterSet; - } + internal static string GetCharacterSet(HttpResponseMessage response) => response.Content.Headers.ContentType.CharSet; internal static Dictionary> GetHeadersDictionary(HttpResponseMessage response) { @@ -27,7 +23,7 @@ internal static Dictionary> GetHeadersDictionary(Htt // HttpResponseMessage.Content.Headers. The remaining headers are in HttpResponseMessage.Headers. // The keys in both should be unique with no duplicates between them. // Added for backwards compatibility with PowerShell 5.1 and earlier. - if (response.Content != null) + if (response.Content is not null) { foreach (var entry in response.Content.Headers) { @@ -38,24 +34,11 @@ internal static Dictionary> GetHeadersDictionary(Htt return headers; } - internal static string GetProtocol(HttpResponseMessage response) - { - string protocol = string.Format(CultureInfo.InvariantCulture, - "HTTP/{0}", response.Version); - return protocol; - } + internal static string GetProtocol(HttpResponseMessage response) => string.Format(CultureInfo.InvariantCulture, $"HTTP/{response.Version}"); - internal static int GetStatusCode(HttpResponseMessage response) - { - int statusCode = (int)response.StatusCode; - return statusCode; - } + internal static int GetStatusCode(HttpResponseMessage response) => (int)response.StatusCode; - internal static string GetStatusDescription(HttpResponseMessage response) - { - string statusDescription = response.StatusCode.ToString(); - return statusDescription; - } + internal static string GetStatusDescription(HttpResponseMessage response) => response.StatusCode.ToString(); internal static bool IsText(HttpResponseMessage response) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseObjectFactory.CoreClr.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseObjectFactory.CoreClr.cs index c4371515fe7..7dade00b4f6 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseObjectFactory.CoreClr.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseObjectFactory.CoreClr.cs @@ -21,7 +21,7 @@ internal static WebResponseObject GetResponseObject(HttpResponseMessage response output = new WebResponseObject(response, responseStream); } - return (output); + return output; } } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObjectCollection.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObjectCollection.cs index 9072e431cae..f435b92e484 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObjectCollection.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObjectCollection.cs @@ -30,7 +30,7 @@ public FormObject this[string key] } } - return (form); + return form; } } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/PSUserAgent.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/PSUserAgent.cs index 2ea29e73fa3..9ccd7e624ce 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/PSUserAgent.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/PSUserAgent.cs @@ -16,110 +16,37 @@ public static class PSUserAgent { private static string s_windowsUserAgent; - internal static string UserAgent - { - get - { - // format the user-agent string from the various component parts - string userAgent = string.Format(CultureInfo.InvariantCulture, - "{0} ({1}; {2}; {3}) {4}", - Compatibility, PlatformName, OS, Culture, App); - return (userAgent); - } - } + // Format the user-agent string from the various component parts + internal static string UserAgent => string.Format(CultureInfo.InvariantCulture, $"{Compatibility} ({PlatformName}; {OS}; {Culture}) {App}"); /// /// Useragent string for InternetExplorer (9.0). /// - public static string InternetExplorer - { - get - { - // format the user-agent string from the various component parts - string userAgent = string.Format(CultureInfo.InvariantCulture, - "{0} (compatible; MSIE 9.0; {1}; {2}; {3})", - Compatibility, PlatformName, OS, Culture); - return (userAgent); - } - } + public static string InternetExplorer => string.Format(CultureInfo.InvariantCulture, $"{Compatibility} (compatible; MSIE 9.0; {PlatformName}; {OS}; {Culture})"); /// /// Useragent string for Firefox (4.0). /// - public static string FireFox - { - get - { - // format the user-agent string from the various component parts - string userAgent = string.Format(CultureInfo.InvariantCulture, - "{0} ({1}; {2}; {3}) Gecko/20100401 Firefox/4.0", - Compatibility, PlatformName, OS, Culture); - return (userAgent); - } - } + public static string FireFox => string.Format(CultureInfo.InvariantCulture, $"{Compatibility} ({PlatformName}; {OS}; {Culture}) Gecko/20100401 Firefox/4.0"); /// /// Useragent string for Chrome (7.0). /// - public static string Chrome - { - get - { - // format the user-agent string from the various component parts - string userAgent = string.Format(CultureInfo.InvariantCulture, - "{0} ({1}; {2}; {3}) AppleWebKit/534.6 (KHTML, like Gecko) Chrome/7.0.500.0 Safari/534.6", - Compatibility, PlatformName, OS, Culture); - return (userAgent); - } - } + public static string Chrome => string.Format(CultureInfo.InvariantCulture, $"{Compatibility} ({PlatformName}; {OS}; {Culture}) AppleWebKit/534.6 (KHTML, like Gecko) Chrome/7.0.500.0 Safari/534.6"); /// /// Useragent string for Opera (9.0). /// - public static string Opera - { - get - { - // format the user-agent string from the various component parts - string userAgent = string.Format(CultureInfo.InvariantCulture, - "Opera/9.70 ({0}; {1}; {2}) Presto/2.2.1", - PlatformName, OS, Culture); - return (userAgent); - } - } + public static string Opera => string.Format(CultureInfo.InvariantCulture, $"Opera/9.70 ({PlatformName}; {OS}; {Culture}) Presto/2.2.1"); /// /// Useragent string for Safari (5.0). /// - public static string Safari - { - get - { - // format the user-agent string from the various component parts - string userAgent = string.Format(CultureInfo.InvariantCulture, - "{0} ({1}; {2}; {3}) AppleWebKit/533.16 (KHTML, like Gecko) Version/5.0 Safari/533.16", - Compatibility, PlatformName, OS, Culture); - return (userAgent); - } - } + public static string Safari => string.Format(CultureInfo.InvariantCulture, $"{Compatibility} ({PlatformName}; {OS}; {Culture}) AppleWebKit/533.16 (KHTML, like Gecko) Version/5.0 Safari/533.16"); - internal static string Compatibility - { - get - { - return ("Mozilla/5.0"); - } - } + internal static string Compatibility => "Mozilla/5.0"; - internal static string App - { - get - { - string app = string.Format(CultureInfo.InvariantCulture, - "PowerShell/{0}", PSVersionInfo.PSVersion); - return (app); - } - } + internal static string App => string.Format(CultureInfo.InvariantCulture, $"PowerShell/{PSVersionInfo.PSVersion}"); internal static string PlatformName { @@ -127,10 +54,10 @@ internal static string PlatformName { if (Platform.IsWindows) { - // only generate the windows user agent once - if (s_windowsUserAgent == null) + // Only generate the windows user agent once + if (s_windowsUserAgent is null) { - // find the version in the windows operating system description + // Find the version in the windows operating system description Regex pattern = new(@"\d+(\.\d+)+"); string versionText = pattern.Match(OS).Value; Version windowsPlatformversion = new(versionText); @@ -149,27 +76,15 @@ internal static string PlatformName } else { - // unknown/unsupported platform + // Unknown/unsupported platform Diagnostics.Assert(false, "Unable to determine Operating System Platform"); return string.Empty; } } } - internal static string OS - { - get - { - return RuntimeInformation.OSDescription.Trim(); - } - } + internal static string OS => RuntimeInformation.OSDescription.Trim(); - internal static string Culture - { - get - { - return (CultureInfo.CurrentCulture.Name); - } - } + internal static string Culture => CultureInfo.CurrentCulture.Name; } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebCmdletElementCollection.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebCmdletElementCollection.cs index fada385d4ac..8336249efb5 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebCmdletElementCollection.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebCmdletElementCollection.cs @@ -12,8 +12,7 @@ namespace Microsoft.PowerShell.Commands ///
    public class WebCmdletElementCollection : ReadOnlyCollection { - internal WebCmdletElementCollection(IList list) - : base(list) + internal WebCmdletElementCollection(IList list) : base(list) { } @@ -22,33 +21,21 @@ internal WebCmdletElementCollection(IList list) ///
    /// /// Found element as PSObject. - public PSObject Find(string nameOrId) - { - // try Id first - PSObject result = FindById(nameOrId) ?? FindByName(nameOrId); - - return (result); - } + public PSObject Find(string nameOrId) => FindById(nameOrId) ?? FindByName(nameOrId); /// /// Finds the element by id. /// /// /// Found element as PSObject. - public PSObject FindById(string id) - { - return Find(id, true); - } + public PSObject FindById(string id) => Find(id, findById: true); /// /// Finds the element by name. /// /// /// Found element as PSObject. - public PSObject FindByName(string name) - { - return Find(name, false); - } + public PSObject FindByName(string name) => Find(name, findById: false); private PSObject Find(string nameOrId, bool findById) { From 3fb4bb277b0968298783fbc23f22bd4c4cbb26ae Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Tue, 17 Jan 2023 11:59:52 +0100 Subject: [PATCH 300/779] Cleanup StreamHelper.cs, WebRequestPSCmdlet.Common.cs and InvokeRestMethodCommand.Common.cs (#18950) --- .../Common/InvokeRestMethodCommand.Common.cs | 26 ------- .../Common/WebRequestPSCmdlet.Common.cs | 56 ++++---------- .../utility/WebCmdlet/StreamHelper.cs | 75 +++++-------------- 3 files changed, 34 insertions(+), 123 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs index 7ff2095b24b..d128800af64 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs @@ -25,32 +25,6 @@ public class InvokeRestMethodCommand : WebRequestPSCmdlet { #region Parameters - /// - /// Gets or sets the parameter Method. - /// - [Parameter(ParameterSetName = "StandardMethod")] - [Parameter(ParameterSetName = "StandardMethodNoProxy")] - public override WebRequestMethod Method - { - get => base.Method; - - set => base.Method = value; - } - - /// - /// Gets or sets the parameter CustomMethod. - /// - [Parameter(Mandatory = true, ParameterSetName = "CustomMethod")] - [Parameter(Mandatory = true, ParameterSetName = "CustomMethodNoProxy")] - [Alias("CM")] - [ValidateNotNullOrEmpty] - public override string CustomMethod - { - get => base.CustomMethod; - - set => base.CustomMethod = value.ToUpperInvariant(); - } - /// /// Enable automatic following of rel links. /// diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index 5dfb4f7e877..73eb34013a5 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -60,7 +60,7 @@ public enum WebSslProtocol /// /// No SSL protocol will be set and the system defaults will be used. /// - Default = 0, + Default = SslProtocols.None, /// /// Specifies the TLS 1.0 is obsolete. Using this value now defaults to TLS 1.2. @@ -433,13 +433,7 @@ internal virtual void ValidateParameters() ThrowTerminatingError(error); } - if (!AllowUnencryptedAuthentication && Authentication != WebAuthenticationType.None && Uri.Scheme != "https") - { - ErrorRecord error = GetValidationError(WebCmdletStrings.AllowUnencryptedAuthenticationRequired, "WebCmdletAllowUnencryptedAuthenticationRequiredException"); - ThrowTerminatingError(error); - } - - if (!AllowUnencryptedAuthentication && (Credential is not null || UseDefaultCredentials) && Uri.Scheme != "https") + if (!AllowUnencryptedAuthentication && (Authentication != WebAuthenticationType.None || Credential is not null || UseDefaultCredentials) && Uri.Scheme != "https") { ErrorRecord error = GetValidationError(WebCmdletStrings.AllowUnencryptedAuthenticationRequired, "WebCmdletAllowUnencryptedAuthenticationRequiredException"); ThrowTerminatingError(error); @@ -486,12 +480,11 @@ internal virtual void ValidateParameters() // Validate InFile path if (InFile is not null) { - ProviderInfo provider = null; ErrorRecord errorRecord = null; try { - Collection providerPaths = GetResolvedProviderPathFromPSPath(InFile, out provider); + Collection providerPaths = GetResolvedProviderPathFromPSPath(InFile, out ProviderInfo provider); if (!provider.Name.Equals(FileSystemProvider.ProviderName, StringComparison.OrdinalIgnoreCase)) { @@ -688,10 +681,9 @@ private Uri PrepareUri(Uri uri) { uri = CheckProtocol(uri); - // before creating the web request, + // Before creating the web request, // preprocess Body if content is a dictionary and method is GET (set as query) - IDictionary bodyAsDictionary; - LanguagePrimitives.TryConvertTo(Body, out bodyAsDictionary); + LanguagePrimitives.TryConvertTo(Body, out IDictionary bodyAsDictionary); if (bodyAsDictionary is not null && (Method == WebRequestMethod.Default || Method == WebRequestMethod.Get || CustomMethod == "GET")) { UriBuilder uriBuilder = new(uri); @@ -970,16 +962,8 @@ internal virtual HttpClient GetHttpClient(bool handleRedirect) HttpClient httpClient = new(handler); - // check timeout setting (in seconds instead of milliseconds as in HttpWebRequest) - if (TimeoutSec == 0) - { - // A zero timeout means infinite - httpClient.Timeout = TimeSpan.FromMilliseconds(Timeout.Infinite); - } - else if (TimeoutSec > 0) - { - httpClient.Timeout = new TimeSpan(0, 0, TimeoutSec); - } + // Check timeout setting (in seconds instead of milliseconds as in HttpWebRequest) + httpClient.Timeout = TimeoutSec is 0 ? TimeSpan.FromMilliseconds(Timeout.Infinite) : new TimeSpan(0, 0, TimeoutSec); return httpClient; } @@ -1028,8 +1012,7 @@ internal virtual HttpRequestMessage GetRequest(Uri uri) } // Set 'User-Agent' if WebSession.Headers doesn't already contain it - string userAgent = null; - if (WebSession.Headers.TryGetValue(HttpKnownHeaderNames.UserAgent, out userAgent)) + if (WebSession.Headers.TryGetValue(HttpKnownHeaderNames.UserAgent, out string userAgent)) { WebSession.UserAgent = userAgent; } @@ -1095,8 +1078,7 @@ internal virtual void FillRequestStream(HttpRequestMessage request) else if (request.Method == HttpMethod.Post) { // Win8:545310 Invoke-WebRequest does not properly set MIME type for POST - string contentType = null; - WebSession.ContentHeaders.TryGetValue(HttpKnownHeaderNames.ContentType, out contentType); + WebSession.ContentHeaders.TryGetValue(HttpKnownHeaderNames.ContentType, out string contentType); if (string.IsNullOrEmpty(contentType)) { WebSession.ContentHeaders[HttpKnownHeaderNames.ContentType] = "application/x-www-form-urlencoded"; @@ -1280,7 +1262,7 @@ internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestM _cancelToken.Cancel(); _cancelToken = null; - // if explicit count was provided, reduce it for this redirection. + // If explicit count was provided, reduce it for this redirection. if (WebSession.MaximumRedirection > 0) { WebSession.MaximumRedirection--; @@ -1441,7 +1423,9 @@ protected override void ProcessRecord() { long requestContentLength = 0; if (request.Content is not null) + { requestContentLength = request.Content.Headers.ContentLength.Value; + } string reqVerboseMsg = string.Format( CultureInfo.CurrentCulture, @@ -1641,16 +1625,7 @@ internal long SetRequestContent(HttpRequestMessage request, string content) encoding = Encoding.GetEncoding(mediaTypeHeaderValue.CharSet); } } - catch (FormatException ex) - { - if (!SkipHeaderValidation) - { - var outerEx = new ValidationMetadataException(WebCmdletStrings.ContentTypeException, ex); - ErrorRecord er = new(outerEx, "WebCmdletContentTypeException", ErrorCategory.InvalidArgument, ContentType); - ThrowTerminatingError(er); - } - } - catch (ArgumentException ex) + catch (Exception ex) when (ex is FormatException || ex is ArgumentException) { if (!SkipHeaderValidation) { @@ -1687,7 +1662,7 @@ internal long SetRequestContent(HttpRequestMessage request, XmlNode xmlNode) } else { - bytes = StreamHelper.EncodeToBytes(xmlNode.OuterXml); + bytes = StreamHelper.EncodeToBytes(xmlNode.OuterXml, encoding: null); } var byteArrayContent = new ByteArrayContent(bytes); @@ -1764,8 +1739,7 @@ internal void ParseLinkHeader(HttpResponseMessage response, System.Uri requestUr // We only support the URL in angle brackets and `rel`, other attributes are ignored // user can still parse it themselves via the Headers property const string pattern = "<(?.*?)>;\\s*rel=(?\")?(?(?(quoted).*?|[^,;]*))(?(quoted)\")"; - IEnumerable links; - if (response.Headers.TryGetValues("Link", out links)) + if (response.Headers.TryGetValues("Link", out IEnumerable links)) { foreach (string linkHeader in links) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs index afa17912244..9d0f4a93797 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs @@ -38,8 +38,7 @@ internal class WebResponseContentMemoryStream : MemoryStream /// /// Owner cmdlet if any. /// Expected download size in Bytes. - internal WebResponseContentMemoryStream(Stream stream, int initialCapacity, Cmdlet cmdlet, long? contentLength) - : base(initialCapacity) + internal WebResponseContentMemoryStream(Stream stream, int initialCapacity, Cmdlet cmdlet, long? contentLength) : base(initialCapacity) { this._contentLength = contentLength; _originalStreamToProxy = stream; @@ -49,43 +48,15 @@ internal WebResponseContentMemoryStream(Stream stream, int initialCapacity, Cmdl /// /// - public override bool CanRead - { - get - { - return true; - } - } - - /// - /// - public override bool CanSeek - { - get - { - return true; - } - } + public override bool CanRead => true; /// /// - public override bool CanTimeout - { - get - { - return base.CanTimeout; - } - } + public override bool CanSeek => true; /// /// - public override bool CanWrite - { - get - { - return true; - } - } + public override bool CanWrite => true; /// /// @@ -215,7 +186,10 @@ protected override void Dispose(bool disposing) /// private void Initialize() { - if (_isInitialized) { return; } + if (_isInitialized) + { + return; + } _isInitialized = true; try @@ -226,7 +200,7 @@ private void Initialize() string totalDownloadSize = _contentLength is null ? "???" : Utils.DisplayHumanReadableFileSize((long)_contentLength); for (int read = 1; read > 0; totalRead += read) { - if (_ownerCmdlet != null) + if (_ownerCmdlet is not null) { record.StatusDescription = StringUtil.Format( WebCmdletStrings.ReadResponseProgressStatus, @@ -254,14 +228,14 @@ private void Initialize() } } - if (_ownerCmdlet != null) + if (_ownerCmdlet is not null) { record.StatusDescription = StringUtil.Format(WebCmdletStrings.ReadResponseComplete, totalRead); record.RecordType = ProgressRecordType.Completed; _ownerCmdlet.WriteProgress(record); } - // make sure the length is set appropriately + // Make sure the length is set appropriately base.SetLength(totalRead); base.Seek(0, SeekOrigin.Begin); } @@ -281,7 +255,7 @@ internal static class StreamHelper internal const int ChunkSize = 10000; - // just picked a random number + // Just picked a random number internal const int ActivityId = 174593042; #endregion Constants @@ -377,8 +351,6 @@ private static string StreamToString(Stream stream, Encoding encoding) bool completed = false; int byteIndex = 0; - int bytesUsed; - int charsUsed; while (!completed) { @@ -386,7 +358,7 @@ private static string StreamToString(Stream stream, Encoding encoding) bool flush = (bytesRead == 0); decoder.Convert(bytes, byteIndex, bytesRead - byteIndex, chars, 0, useBufferSize, flush, - out bytesUsed, out charsUsed, out completed); + out int bytesUsed, out int charsUsed, out completed); // The conversion produced the number of characters indicated by charsUsed. Write that number // of characters to our result buffer @@ -447,7 +419,7 @@ internal static bool TryGetEncoding(string characterSet, out Encoding encoding) internal static string DecodeStream(Stream stream, ref Encoding encoding) { bool isDefaultEncoding = false; - if (encoding == null) + if (encoding is null) { // Use the default encoding if one wasn't provided encoding = ContentHelper.GetDefaultEncoding(); @@ -459,7 +431,7 @@ internal static string DecodeStream(Stream stream, ref Encoding encoding) { do { - // check for a charset attribute on the meta element to override the default + // Check for a charset attribute on the meta element to override the default // we only look within the first 1k characters as the meta tag is in the head // tag which is at the start of the document Match match = s_metaexp.Match(content.Substring(0, Math.Min(content.Length, 1024))); @@ -472,7 +444,8 @@ internal static string DecodeStream(Stream stream, ref Encoding encoding) { stream.Seek(0, SeekOrigin.Begin); content = StreamToString(stream, localEncoding); - // report the encoding used. + + // Report the encoding used. encoding = localEncoding; } } @@ -484,23 +457,13 @@ internal static string DecodeStream(Stream stream, ref Encoding encoding) internal static byte[] EncodeToBytes(string str, Encoding encoding) { - // just use the default encoding if one wasn't provided + // Just use the default encoding if one wasn't provided encoding ??= ContentHelper.GetDefaultEncoding(); return encoding.GetBytes(str); } - internal static byte[] EncodeToBytes(string str) - { - return EncodeToBytes(str, null); - } - - internal static Stream GetResponseStream(HttpResponseMessage response) - { - Stream responseStream = response.Content.ReadAsStreamAsync().GetAwaiter().GetResult(); - - return responseStream; - } + internal static Stream GetResponseStream(HttpResponseMessage response) => response.Content.ReadAsStreamAsync().GetAwaiter().GetResult(); #endregion Static Methods } From 5f8f15a24c7789585c3780878006c8d0bcb7b25d Mon Sep 17 00:00:00 2001 From: Paul Higinbotham Date: Wed, 18 Jan 2023 14:24:34 -0800 Subject: [PATCH 301/779] Allow system lock down test debug hook to work with new wldp API (fixes system lock down tests) (#18962) --- .../security/wldpNativeMethods.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/System.Management.Automation/security/wldpNativeMethods.cs b/src/System.Management.Automation/security/wldpNativeMethods.cs index 730db922a00..a2be725da73 100644 --- a/src/System.Management.Automation/security/wldpNativeMethods.cs +++ b/src/System.Management.Automation/security/wldpNativeMethods.cs @@ -110,9 +110,9 @@ public static SystemScriptFileEnforcement GetFilePolicyEnforcement( { SafeHandle fileHandle = fileStream.SafeFileHandle; - // First check latest WDAC APIs if available. + // First check latest WDAC APIs if available. Also revert to legacy APIs if debug hook is in effect. Exception errorException = null; - if (s_wldpCanExecuteAvailable) + if (s_wldpCanExecuteAvailable && !s_allowDebugOverridePolicy) { try { From 94610307572edc7656e22bc3f5d45d57751e9f13 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 19 Jan 2023 13:00:07 +0500 Subject: [PATCH 302/779] Bump Microsoft.CodeAnalysis.Analyzers from 3.3.3 to 3.3.4 (#18975) Bumps [Microsoft.CodeAnalysis.Analyzers](https://github.com/dotnet/roslyn-analyzers) from 3.3.3 to 3.3.4. - [Release notes](https://github.com/dotnet/roslyn-analyzers/releases) - [Changelog](https://github.com/dotnet/roslyn-analyzers/blob/main/PostReleaseActivities.md) - [Commits](https://github.com/dotnet/roslyn-analyzers/compare/v3.3.3...v3.3.4) --- updated-dependencies: - dependency-name: Microsoft.CodeAnalysis.Analyzers dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .../PSVersionInfoGenerator/PSVersionInfoGenerator.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/System.Management.Automation/SourceGenerators/PSVersionInfoGenerator/PSVersionInfoGenerator.csproj b/src/System.Management.Automation/SourceGenerators/PSVersionInfoGenerator/PSVersionInfoGenerator.csproj index 56fa17a6f25..8ebdc3a61ac 100644 --- a/src/System.Management.Automation/SourceGenerators/PSVersionInfoGenerator/PSVersionInfoGenerator.csproj +++ b/src/System.Management.Automation/SourceGenerators/PSVersionInfoGenerator/PSVersionInfoGenerator.csproj @@ -13,6 +13,6 @@ - + From a01fb37243e8c662d104e8d69b81ab8a4234e90e Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Fri, 20 Jan 2023 05:50:51 +0100 Subject: [PATCH 303/779] Use interpolated strings 8 (#18988) --- .../host/msh/ConsoleHostUserInterfacePrompt.cs | 6 ++---- .../ConsoleHostUserInterfacePromptForChoice.cs | 3 +-- .../common/DisplayDatabase/XmlLoaderBase.cs | 3 +-- .../engine/MshMemberInfo.cs | 3 +-- .../hostifaces/InternalHostUserInterface.cs | 3 +-- .../engine/parser/token.cs | 12 ++++-------- .../engine/remoting/client/Job.cs | 3 +-- .../remoting/fanin/WSManTransportManager.cs | 15 +++------------ .../engine/runtime/Binding/Binders.cs | 3 +-- .../help/AliasHelpInfo.cs | 3 +-- .../help/BaseCommandHelpInfo.cs | 3 +-- .../help/CommandHelpProvider.cs | 6 ++---- .../help/HelpCommands.cs | 3 +-- .../help/ProviderHelpProvider.cs | 6 ++---- 14 files changed, 22 insertions(+), 50 deletions(-) diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs index 6d7caefec36..49ed23a2a69 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs @@ -190,8 +190,7 @@ public override { string msg = StringUtil.Format(ConsoleHostUserInterfaceStrings.RankZeroArrayErrorTemplate, desc.Name); ArgumentException innerException = PSTraceSource.NewArgumentException( - string.Format(CultureInfo.InvariantCulture, - "descriptions[{0}].AssemblyFullName", descIndex)); + string.Create(CultureInfo.InvariantCulture, $"descriptions[{descIndex}].AssemblyFullName")); PromptingException e = new PromptingException(msg, innerException, "ZeroRankArray", ErrorCategory.InvalidOperation); throw e; } @@ -203,8 +202,7 @@ public override while (true) { - fieldPromptList.Append( - string.Format(CultureInfo.InvariantCulture, "{0}]: ", inputList.Count)); + fieldPromptList.AppendFormat(CultureInfo.InvariantCulture, $"{inputList.Count}]: "); bool endListInput = false; object convertedObj = null; _ = PromptForSingleItem( diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePromptForChoice.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePromptForChoice.cs index 872aaa19a9c..e900a0fc2f7 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePromptForChoice.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePromptForChoice.cs @@ -345,8 +345,7 @@ private void WriteChoicePrompt(string[,] hotkeysAndPlainLabels, defaultStr = hotkeysAndPlainLabels[1, defaultChoice]; } - defaultChoicesBuilder.Append(string.Format(CultureInfo.InvariantCulture, - "{0}{1}", prepend, defaultStr)); + defaultChoicesBuilder.AppendFormat(CultureInfo.InvariantCulture, $"{prepend}{defaultStr}"); prepend = ","; } diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/XmlLoaderBase.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/XmlLoaderBase.cs index a7e7df0a5d7..e8fc15d5558 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/XmlLoaderBase.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/XmlLoaderBase.cs @@ -600,8 +600,7 @@ protected string ComputeCurrentXPath() path.Insert(0, "/"); if (sf.index != -1) { - path.Insert(1, string.Format(CultureInfo.InvariantCulture, - "{0}[{1}]", sf.node.Name, sf.index + 1)); + path.Insert(1, string.Create(CultureInfo.InvariantCulture, $"{sf.node.Name}[{sf.index + 1}]")); } else { diff --git a/src/System.Management.Automation/engine/MshMemberInfo.cs b/src/System.Management.Automation/engine/MshMemberInfo.cs index 4f0b4364bac..fe041212202 100644 --- a/src/System.Management.Automation/engine/MshMemberInfo.cs +++ b/src/System.Management.Automation/engine/MshMemberInfo.cs @@ -3365,8 +3365,7 @@ internal override PSMemberInfoInternalCollection InternalMembers break; default: Diagnostics.Assert(false, - string.Format(CultureInfo.InvariantCulture, - "PSInternalMemberSet cannot process {0}", name)); + string.Create(CultureInfo.InvariantCulture, $"PSInternalMemberSet cannot process {name}")); break; } } diff --git a/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs index 1e820196ca9..d398e8e006f 100644 --- a/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs @@ -927,8 +927,7 @@ private Collection EmulatePromptForMultipleChoice(string caption, defaultStr = hotkeysAndPlainLabels[1, defaultChoice]; } - defaultChoicesBuilder.Append(string.Format(Globalization.CultureInfo.InvariantCulture, - "{0}{1}", prepend, defaultStr)); + defaultChoicesBuilder.AppendFormat(Globalization.CultureInfo.InvariantCulture, $"{prepend}{defaultStr}"); prepend = ","; } diff --git a/src/System.Management.Automation/engine/parser/token.cs b/src/System.Management.Automation/engine/parser/token.cs index 43a3e86ebb7..73fccd41e9e 100644 --- a/src/System.Management.Automation/engine/parser/token.cs +++ b/src/System.Management.Automation/engine/parser/token.cs @@ -1290,8 +1290,7 @@ internal NumberToken(InternalScriptExtent scriptExtent, object value, TokenFlags internal override string ToDebugString(int indent) { - return string.Format(CultureInfo.InvariantCulture, - "{0}{1}: <{2}> Value:<{3}> Type:<{4}>", StringUtil.Padding(indent), Kind, Text, _value, _value.GetType().Name); + return string.Create(CultureInfo.InvariantCulture, $"{StringUtil.Padding(indent)}{Kind}: <{Text}> Value:<{_value}> Type:<{_value.GetType().Name}>"); } /// @@ -1332,8 +1331,7 @@ internal ParameterToken(InternalScriptExtent scriptExtent, string parameterName, internal override string ToDebugString(int indent) { - return string.Format(CultureInfo.InvariantCulture, - "{0}{1}: <-{2}{3}>", StringUtil.Padding(indent), Kind, _parameterName, _usedColon ? ":" : string.Empty); + return string.Create(CultureInfo.InvariantCulture, $"{StringUtil.Padding(indent)}{Kind}: <-{_parameterName}{(_usedColon ? ":" : string.Empty)}>"); } } @@ -1360,8 +1358,7 @@ internal VariableToken(InternalScriptExtent scriptExtent, VariablePath path, Tok internal override string ToDebugString(int indent) { - return string.Format(CultureInfo.InvariantCulture, - "{0}{1}: <{2}> Name:<{3}>", StringUtil.Padding(indent), Kind, Text, Name); + return string.Create(CultureInfo.InvariantCulture, $"{StringUtil.Padding(indent)}{Kind}: <{Text}> Name:<{Name}>"); } } @@ -1383,8 +1380,7 @@ internal StringToken(InternalScriptExtent scriptExtent, TokenKind kind, TokenFla internal override string ToDebugString(int indent) { - return string.Format(CultureInfo.InvariantCulture, - "{0}{1}: <{2}> Value:<{3}>", StringUtil.Padding(indent), Kind, Text, Value); + return string.Create(CultureInfo.InvariantCulture, $"{StringUtil.Padding(indent)}{Kind}: <{Text}> Value:<{Value}>"); } } diff --git a/src/System.Management.Automation/engine/remoting/client/Job.cs b/src/System.Management.Automation/engine/remoting/client/Job.cs index 74bd83c1faf..4c2bf10d462 100644 --- a/src/System.Management.Automation/engine/remoting/client/Job.cs +++ b/src/System.Management.Automation/engine/remoting/client/Job.cs @@ -3307,8 +3307,7 @@ protected void ProcessJobFailure(ExecutionCmdletHelper helper, out Exception fai errorId = "InvalidSessionState"; if (!string.IsNullOrEmpty(failureException.Source)) { - errorId = string.Format(System.Globalization.CultureInfo.InvariantCulture, - "{0},{1}", errorId, failureException.Source); + errorId = string.Create(System.Globalization.CultureInfo.InvariantCulture, $"{errorId},{failureException.Source}"); } } diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManTransportManager.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManTransportManager.cs index bc8244673b2..6c7eb62d181 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManTransportManager.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManTransportManager.cs @@ -202,8 +202,7 @@ internal static string ParseEscapeWSManErrorMessage(string errorMessage) Collection tokens = PSParser.Tokenize(errorMessage, out parserErrors); if (parserErrors.Count > 0) { - tracer.WriteLine(string.Format(CultureInfo.InvariantCulture, - "There were errors parsing string '{0}'", errorMessage); + tracer.WriteLine(string.Create(CultureInfo.InvariantCulture, $"There were errors parsing string '{errorMessage}'"); return errorMessage; } @@ -1399,25 +1398,17 @@ private void Initialize(Uri connectionUri, WSManConnectionInfo connectionInfo) if (string.IsNullOrEmpty(connectionUri.Query)) { // if there is no query string already, create one..see RFC 3986 - connectionStr = string.Format(CultureInfo.InvariantCulture, - "{0}?PSVersion={1}{2}", + connectionStr = string.Create(CultureInfo.InvariantCulture, $"{connectionStr.TrimEnd('/')}?PSVersion={PSVersionInfo.PSVersion}{additionalUriSuffixString}"); // Trimming the last '/' as this will allow WSMan to // properly apply URLPrefix. // Ex: http://localhost?PSVersion=2.0 will be converted // to http://localhost:/?PSVersion=2.0 // by WSMan - connectionStr.TrimEnd('/'), - PSVersionInfo.PSVersion, - additionalUriSuffixString); } else { // if there is already a query string, append using & .. see RFC 3986 - connectionStr = string.Format(CultureInfo.InvariantCulture, - "{0};PSVersion={1}{2}", - connectionStr, - PSVersionInfo.PSVersion, - additionalUriSuffixString); + connectionStr = string.Create(CultureInfo.InvariantCulture, $"{connectionStr};PSVersion={PSVersionInfo.PSVersion}{additionalUriSuffixString}"); } WSManNativeApi.BaseWSManAuthenticationCredentials authCredentials; diff --git a/src/System.Management.Automation/engine/runtime/Binding/Binders.cs b/src/System.Management.Automation/engine/runtime/Binding/Binders.cs index 76bc2bfd696..8912c95590e 100644 --- a/src/System.Management.Automation/engine/runtime/Binding/Binders.cs +++ b/src/System.Management.Automation/engine/runtime/Binding/Binders.cs @@ -7577,8 +7577,7 @@ internal PSCreateInstanceBinder(CallInfo callInfo, PSMethodInvocationConstraints public override string ToString() { - return string.Format(CultureInfo.InvariantCulture, - "PSCreateInstanceBinder: ver:{0} args:{1} constraints:<{2}>", _version, _callInfo.ArgumentCount, _constraints != null ? _constraints.ToString() : string.Empty); + return string.Create(CultureInfo.InvariantCulture, $"PSCreateInstanceBinder: ver:{_version} args:{_callInfo.ArgumentCount} constraints:<{(_constraints != null ? _constraints : string.Empty)}>"); } public override DynamicMetaObject FallbackCreateInstance(DynamicMetaObject target, DynamicMetaObject[] args, DynamicMetaObject errorSuggestion) diff --git a/src/System.Management.Automation/help/AliasHelpInfo.cs b/src/System.Management.Automation/help/AliasHelpInfo.cs index 8ac441e4e60..5d02e754397 100644 --- a/src/System.Management.Automation/help/AliasHelpInfo.cs +++ b/src/System.Management.Automation/help/AliasHelpInfo.cs @@ -40,8 +40,7 @@ private AliasHelpInfo(AliasInfo aliasInfo) } _fullHelpObject.TypeNames.Clear(); - _fullHelpObject.TypeNames.Add(string.Format(Globalization.CultureInfo.InvariantCulture, - "AliasHelpInfo#{0}", Name)); + _fullHelpObject.TypeNames.Add(string.Create(Globalization.CultureInfo.InvariantCulture, $"AliasHelpInfo#{Name}")); _fullHelpObject.TypeNames.Add("AliasHelpInfo"); _fullHelpObject.TypeNames.Add("HelpInfo"); } diff --git a/src/System.Management.Automation/help/BaseCommandHelpInfo.cs b/src/System.Management.Automation/help/BaseCommandHelpInfo.cs index 8a5969e7b35..c24e45ee788 100644 --- a/src/System.Management.Automation/help/BaseCommandHelpInfo.cs +++ b/src/System.Management.Automation/help/BaseCommandHelpInfo.cs @@ -214,8 +214,7 @@ internal Uri LookupUriFromCommandInfo() string commandToSearch = commandName; if (!string.IsNullOrEmpty(moduleName)) { - commandToSearch = string.Format(CultureInfo.InvariantCulture, - "{0}\\{1}", moduleName, commandName); + commandToSearch = string.Create(CultureInfo.InvariantCulture, $"{moduleName}\\{commandName}"); } ExecutionContext context = LocalPipeline.GetExecutionContextFromTLS(); diff --git a/src/System.Management.Automation/help/CommandHelpProvider.cs b/src/System.Management.Automation/help/CommandHelpProvider.cs index e32d1c86354..12e603e1aa9 100644 --- a/src/System.Management.Automation/help/CommandHelpProvider.cs +++ b/src/System.Management.Automation/help/CommandHelpProvider.cs @@ -950,15 +950,13 @@ private void AddToCommandCache(string mshSnapInId, string cmdletName, MamlComman // Add snapin qualified type name for this command at the top.. // this will enable customizations of the help object. - helpInfo.FullHelp.TypeNames.Insert(0, string.Format(CultureInfo.InvariantCulture, - "MamlCommandHelpInfo#{0}#{1}", mshSnapInId, cmdletName)); + helpInfo.FullHelp.TypeNames.Insert(0, string.Create(CultureInfo.InvariantCulture, $"MamlCommandHelpInfo#{mshSnapInId}#{cmdletName}")); if (!string.IsNullOrEmpty(mshSnapInId)) { key = mshSnapInId + "\\" + key; // Add snapin name to the typenames of this object - helpInfo.FullHelp.TypeNames.Insert(1, string.Format(CultureInfo.InvariantCulture, - "MamlCommandHelpInfo#{0}", mshSnapInId)); + helpInfo.FullHelp.TypeNames.Insert(1, string.Create(CultureInfo.InvariantCulture, $"MamlCommandHelpInfo#{mshSnapInId}")); } AddCache(key, helpInfo); diff --git a/src/System.Management.Automation/help/HelpCommands.cs b/src/System.Management.Automation/help/HelpCommands.cs index 5bde9be118f..0b91e24784a 100644 --- a/src/System.Management.Automation/help/HelpCommands.cs +++ b/src/System.Management.Automation/help/HelpCommands.cs @@ -821,8 +821,7 @@ public static string GetHelpUri(PSObject commandInfoPSObject) string cmdName = cmdInfo.Name; if (!string.IsNullOrEmpty(cmdInfo.ModuleName)) { - cmdName = string.Format(CultureInfo.InvariantCulture, - "{0}\\{1}", cmdInfo.ModuleName, cmdInfo.Name); + cmdName = string.Create(CultureInfo.InvariantCulture, $"{cmdInfo.ModuleName}\\{cmdInfo.Name}"); } if (DoesCurrentRunspaceIncludeCoreHelpCmdlet()) diff --git a/src/System.Management.Automation/help/ProviderHelpProvider.cs b/src/System.Management.Automation/help/ProviderHelpProvider.cs index b28dcf86398..65fb3e9dfbd 100644 --- a/src/System.Management.Automation/help/ProviderHelpProvider.cs +++ b/src/System.Management.Automation/help/ProviderHelpProvider.cs @@ -236,14 +236,12 @@ private void LoadHelpFile(ProviderInfo providerInfo) this.HelpSystem.TraceErrors(helpInfo.Errors); // Add snapin qualified type name for this command.. // this will enable customizations of the help object. - helpInfo.FullHelp.TypeNames.Insert(0, string.Format(CultureInfo.InvariantCulture, - "ProviderHelpInfo#{0}#{1}", providerInfo.PSSnapInName, helpInfo.Name)); + helpInfo.FullHelp.TypeNames.Insert(0, string.Create(CultureInfo.InvariantCulture, $"ProviderHelpInfo#{providerInfo.PSSnapInName}#{helpInfo.Name}")); if (!string.IsNullOrEmpty(providerInfo.PSSnapInName)) { helpInfo.FullHelp.Properties.Add(new PSNoteProperty("PSSnapIn", providerInfo.PSSnapIn)); - helpInfo.FullHelp.TypeNames.Insert(1, string.Format(CultureInfo.InvariantCulture, - "ProviderHelpInfo#{0}", providerInfo.PSSnapInName)); + helpInfo.FullHelp.TypeNames.Insert(1, string.Create(CultureInfo.InvariantCulture, $"ProviderHelpInfo#{providerInfo.PSSnapInName}")); } AddCache(providerInfo.PSSnapInName + "\\" + helpInfo.Name, helpInfo); From f5627538e14cf0a97915068caec42f825a18fdd9 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Fri, 20 Jan 2023 08:21:19 +0100 Subject: [PATCH 304/779] Use interpolated strings 7 (#18985) --- .../ScheduledJobStore.cs | 25 ++++++---------- src/Microsoft.WSMan.Management/WsManHelper.cs | 2 +- .../DscSupport/CimDSCParser.cs | 30 +++++++++---------- .../common/DisplayDatabase/FormatTable.cs | 4 +-- .../common/DisplayDatabase/typeDataQuery.cs | 6 ++-- .../cimSupport/cmdletization/ScriptWriter.cs | 2 +- ...lets-over-objects.xmlSerializer.autogen.cs | 6 ++-- 7 files changed, 33 insertions(+), 42 deletions(-) diff --git a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobStore.cs b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobStore.cs index 0938d9829b9..063176feae8 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobStore.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobStore.cs @@ -109,8 +109,7 @@ public static FileStream GetFileForJobDefinition( throw new PSArgumentException("definitionPath"); } - string filePathName = string.Format(CultureInfo.InvariantCulture, @"{0}\{1}\{2}.xml", - definitionPath, definitionName, DefinitionFileName); + string filePathName = string.Create(CultureInfo.InvariantCulture, $@"{definitionPath}\{definitionName}\{DefinitionFileName}.xml"); return File.Open(filePathName, fileMode, fileAccess, fileShare); } @@ -483,7 +482,7 @@ private static string CreateFilePathName(string definitionName, string fileName) Directory.CreateDirectory(filePath); Directory.CreateDirectory(outputPath); - return string.Format(CultureInfo.InstalledUICulture, @"{0}\{1}.xml", filePath, fileName); + return string.Create(CultureInfo.InstalledUICulture, $@"{filePath}\{fileName}.xml"); } /// @@ -495,7 +494,7 @@ private static string CreateFilePathName(string definitionName, string fileName) private static string GetFilePathName(string definitionName, string fileName) { string filePath = GetJobDefinitionPath(definitionName); - return string.Format(CultureInfo.InvariantCulture, @"{0}\{1}.xml", filePath, fileName); + return string.Create(CultureInfo.InvariantCulture, $@"{filePath}\{fileName}.xml"); } /// @@ -525,8 +524,7 @@ private static string GetRunDirectory( DateTime runStart) { string directoryPath = GetJobRunOutputDirectory(definitionName); - return string.Format(CultureInfo.InvariantCulture, @"{0}\{1}", directoryPath, - ConvertDateTimeToJobRunName(runStart)); + return string.reate(CultureInfo.InvariantCulture, $@"{directoryPath}\{ConvertDateTimeToJobRunName(runStart)}"); } /// @@ -540,8 +538,7 @@ private static string GetRunDirectoryFromPath( string definitionOutputPath, DateTime runStart) { - return string.Format(CultureInfo.InvariantCulture, @"{0}\{1}", - definitionOutputPath, ConvertDateTimeToJobRunName(runStart)); + return string.Create(CultureInfo.InvariantCulture, $@"{definitionOutputPath}\{ConvertDateTimeToJobRunName(runStart)}"); } /// @@ -558,11 +555,9 @@ private static string GetRunFilePathName( DateTime runStart) { string directoryPath = GetJobRunOutputDirectory(definitionName); - string jobRunPath = string.Format(CultureInfo.InvariantCulture, @"{0}\{1}", - directoryPath, ConvertDateTimeToJobRunName(runStart)); + string jobRunPath = string.Create(CultureInfo.InvariantCulture, $@"{directoryPath}\{ConvertDateTimeToJobRunName(runStart)}"); - return string.Format(CultureInfo.InvariantCulture, @"{0}\{1}.xml", jobRunPath, - runItem.ToString()); + return string.Create(CultureInfo.InvariantCulture, $@"{jobRunPath}\{runItem}.xml"); } /// @@ -579,8 +574,7 @@ private static string GetRunFilePathNameFromPath( JobRunItem runItem, DateTime runStart) { - string jobRunPath = string.Format(CultureInfo.InvariantCulture, @"{0}\{1}", - outputPath, ConvertDateTimeToJobRunName(runStart)); + string jobRunPath = string.Create(CultureInfo.InvariantCulture, $@"{outputPath}\{ConvertDateTimeToJobRunName(runStart)}"); if (!Directory.Exists(jobRunPath)) { @@ -588,8 +582,7 @@ private static string GetRunFilePathNameFromPath( Directory.CreateDirectory(jobRunPath); } - return string.Format(CultureInfo.InvariantCulture, @"{0}\{1}.xml", jobRunPath, - runItem.ToString()); + return string.Create(CultureInfo.InvariantCulture, $@"{jobRunPath}\{runItem}.xml"); } private static void AddFullAccessToDirectory( diff --git a/src/Microsoft.WSMan.Management/WsManHelper.cs b/src/Microsoft.WSMan.Management/WsManHelper.cs index 71672f3232f..1450f32a675 100644 --- a/src/Microsoft.WSMan.Management/WsManHelper.cs +++ b/src/Microsoft.WSMan.Management/WsManHelper.cs @@ -1070,7 +1070,7 @@ internal static void LoadResourceData() #if CORECLR "0409" /* TODO: don't assume it is always English on CSS? */ #else - string.Concat("0", string.Format(CultureInfo.CurrentCulture, "{0:x2}", checked((uint)CultureInfo.CurrentUICulture.LCID))) + string.Concat("0", string.Create(CultureInfo.CurrentCulture, $"{checked((uint)CultureInfo.CurrentUICulture.LCID):x2}")) #endif + "\\" + "winrm.ini"; if (File.Exists(filepath)) diff --git a/src/System.Management.Automation/DscSupport/CimDSCParser.cs b/src/System.Management.Automation/DscSupport/CimDSCParser.cs index cd9f5d423de..1347ac2c55c 100644 --- a/src/System.Management.Automation/DscSupport/CimDSCParser.cs +++ b/src/System.Management.Automation/DscSupport/CimDSCParser.cs @@ -1086,7 +1086,7 @@ public static void ClearCache() /// private static string GetModuleQualifiedResourceName(string moduleName, string moduleVersion, string className, string resourceName) { - return string.Format(CultureInfo.InvariantCulture, "{0}\\{1}\\{2}\\{3}", moduleName, moduleVersion, className, resourceName); + return string.Create(CultureInfo.InvariantCulture, $"{moduleName}\\{moduleVersion}\\{className}\\{resourceName}"); } /// @@ -1125,7 +1125,7 @@ private static List GetCachedClasses() public static List GetCachedClassesForModule(PSModuleInfo module) { List cachedClasses = new(); - var moduleQualifiedName = string.Format(CultureInfo.InvariantCulture, "{0}\\{1}", module.Name, module.Version.ToString()); + var moduleQualifiedName = string.Create(CultureInfo.InvariantCulture, $"{module.Name}\\{module.Version}"); foreach (var dscClassCacheEntry in ClassCache) { if (dscClassCacheEntry.Key.StartsWith(moduleQualifiedName, StringComparison.OrdinalIgnoreCase)) @@ -2019,7 +2019,7 @@ public static void LoadResourcesFromModule(IScriptExtent scriptExtent, { string moduleString = moduleToImport.Version == null ? moduleToImport.Name - : string.Format(CultureInfo.CurrentCulture, "<{0}, {1}>", moduleToImport.Name, moduleToImport.Version); + : string.Create(CultureInfo.CurrentCulture, $"<{moduleToImport.Name}, {moduleToImport.Version}>"); errorList.Add(new ParseError(scriptExtent, "ModuleNotFoundDuringParse", string.Format(CultureInfo.CurrentCulture, ParserStrings.ModuleNotFoundDuringParse, moduleString))); @@ -2339,7 +2339,7 @@ internal static string MapTypeNameToMofType(ITypeName typeName, string memberNam private static void GenerateMofForAst(TypeDefinitionAst typeAst, StringBuilder sb, List embeddedInstanceTypes) { var className = typeAst.Name; - sb.AppendFormat(CultureInfo.InvariantCulture, "[ClassVersion(\"1.0.0\"), FriendlyName(\"{0}\")]\nclass {0}", className); + sb.AppendFormat(CultureInfo.InvariantCulture, $"[ClassVersion(\"1.0.0\"), FriendlyName(\"{className}\")]\nclass {className}"); if (typeAst.Attributes.Any(static a => a.TypeName.GetReflectionAttributeType() == typeof(DscResourceAttribute))) { @@ -2912,19 +2912,19 @@ private static string MapAttributesToMof(string[] enumNames, IEnumerable { if (dscProperty.Key) { - sb.AppendFormat(CultureInfo.InvariantCulture, "{0}key", needComma ? ", " : string.Empty); + sb.AppendFormat(CultureInfo.InvariantCulture, $"{(needComma ? ", " : string.Empty)}key"); needComma = true; } if (dscProperty.Mandatory) { - sb.AppendFormat(CultureInfo.InvariantCulture, "{0}required", needComma ? ", " : string.Empty); + sb.AppendFormat(CultureInfo.InvariantCulture, $"{(needComma ? ", " : string.Empty)}required"); needComma = true; } if (dscProperty.NotConfigurable) { - sb.AppendFormat(CultureInfo.InvariantCulture, "{0}read", needComma ? ", " : string.Empty); + sb.AppendFormat(CultureInfo.InvariantCulture, $"{(needComma ? ", " : string.Empty)}read"); needComma = true; } @@ -2936,13 +2936,13 @@ private static string MapAttributesToMof(string[] enumNames, IEnumerable { bool valueMapComma = false; StringBuilder sbValues = new(", Values{"); - sb.AppendFormat(CultureInfo.InvariantCulture, "{0}ValueMap{{", needComma ? ", " : string.Empty); + sb.AppendFormat(CultureInfo.InvariantCulture, $"{(needComma ? ", " : string.Empty)}ValueMap{{"); needComma = true; foreach (var value in validateSet.ValidValues) { - sb.AppendFormat(CultureInfo.InvariantCulture, "{0}\"{1}\"", valueMapComma ? ", " : string.Empty, value); - sbValues.AppendFormat(CultureInfo.InvariantCulture, "{0}\"{1}\"", valueMapComma ? ", " : string.Empty, value); + sb.AppendFormat(CultureInfo.InvariantCulture, $"{(valueMapComma ? ", " : string.Empty)}\"{value}\""); + sbValues.AppendFormat(CultureInfo.InvariantCulture, $"{(valueMapComma ? ", " : string.Empty)}\"{value}\""); valueMapComma = true; } @@ -2961,11 +2961,11 @@ private static string MapAttributesToMof(string[] enumNames, IEnumerable if (enumNames != null) { - sb.AppendFormat(CultureInfo.InvariantCulture, "{0}ValueMap{{", needComma ? ", " : string.Empty); + sb.AppendFormat(CultureInfo.InvariantCulture, $"{(needComma ? ", " : string.Empty)}ValueMap{{"); needComma = false; foreach (var name in enumNames) { - sb.AppendFormat(CultureInfo.InvariantCulture, "{0}\"{1}\"", needComma ? ", " : string.Empty, name); + sb.AppendFormat(CultureInfo.InvariantCulture, $"{(needComma ? ", " : string.Empty)}\"{name}\""); needComma = true; } @@ -2973,7 +2973,7 @@ private static string MapAttributesToMof(string[] enumNames, IEnumerable needComma = false; foreach (var name in enumNames) { - sb.AppendFormat(CultureInfo.InvariantCulture, "{0}\"{1}\"", needComma ? ", " : string.Empty, name); + sb.AppendFormat(CultureInfo.InvariantCulture, $"{(needComma ? ", " : string.Empty)}\"{name}\""); needComma = true; } @@ -2981,7 +2981,7 @@ private static string MapAttributesToMof(string[] enumNames, IEnumerable } else if (embeddedInstanceType != null) { - sb.AppendFormat(CultureInfo.InvariantCulture, "{0}EmbeddedInstance(\"{1}\")", needComma ? ", " : string.Empty, embeddedInstanceType); + sb.AppendFormat(CultureInfo.InvariantCulture, $"{(needComma ? ", " : string.Empty)}EmbeddedInstance(\"{embeddedInstanceType}\")"); } sb.Append(']'); @@ -3047,7 +3047,7 @@ private static void GenerateMofForType(Type type, StringBuilder sb, List { var className = type.Name; // Friendly name is required by module validator to verify resource instance against the exclusive resource name list. - sb.AppendFormat(CultureInfo.InvariantCulture, "[ClassVersion(\"1.0.0\"), FriendlyName(\"{0}\")]\nclass {0}", className); + sb.AppendFormat(CultureInfo.InvariantCulture, $"[ClassVersion(\"1.0.0\"), FriendlyName(\"{className}\")]\nclass {className}"); if (type.GetCustomAttributes().Any()) { diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/FormatTable.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/FormatTable.cs index 91d0fabf44c..a3959a14cd3 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/FormatTable.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/FormatTable.cs @@ -98,7 +98,7 @@ protected FormatTableLoadException(SerializationInfo info, StreamingContext cont _errors = new Collection(); for (int index = 0; index < errorCount; index++) { - string key = string.Format(CultureInfo.InvariantCulture, "Error{0}", index); + string key = string.Create(CultureInfo.InvariantCulture, $"Error{index}"); _errors.Add(info.GetString(key)); } } @@ -127,7 +127,7 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont for (int index = 0; index < errorCount; index++) { - string key = string.Format(CultureInfo.InvariantCulture, "Error{0}", index); + string key = string.Create(CultureInfo.InvariantCulture, $"Error{index}"); info.AddValue(key, _errors[index]); } } diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs index 60953d22c26..0352db182fb 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs @@ -490,14 +490,12 @@ private static void TraceHelper(ViewDefinition vd, bool isMatched) sb.Append(isMatched ? "MATCH FOUND" : "NOT MATCH"); if (tr != null) { - sb.AppendFormat(CultureInfo.InvariantCulture, " {0} NAME: {1} TYPE: {2}", - ControlBase.GetControlShapeName(vd.mainControl), vd.name, tr.name); + sb.AppendFormat(CultureInfo.InvariantCulture, $" {ControlBase.GetControlShapeName(vd.mainControl)} NAME: {vd.name} TYPE: {tr.name}"); } else { TypeGroupReference tgr = togr as TypeGroupReference; - sb.AppendFormat(CultureInfo.InvariantCulture, " {0} NAME: {1} GROUP: {2}", - ControlBase.GetControlShapeName(vd.mainControl), vd.name, tgr.name); + sb.AppendFormat(CultureInfo.InvariantCulture, $" {ControlBase.GetControlShapeName(vd.mainControl)} NAME: {vd.name} GROUP: {tgr.name}"); } ActiveTracer.WriteLine(sb.ToString()); diff --git a/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs b/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs index 46484a35d06..fb5e2d6656b 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs @@ -249,7 +249,7 @@ private static string GetCmdletAttributes(CommonCmdletMetadata cmdletMetadata) ? ("'" + CodeGeneration.EscapeSingleQuotedStringContent(cmdletMetadata.Obsolete.Message) + "'") : string.Empty; string newline = (attributes.Length > 0) ? Environment.NewLine : string.Empty; - attributes.AppendFormat(CultureInfo.InvariantCulture, "{0}[Obsolete({1})]", newline, obsoleteMsg); + attributes.AppendFormat(CultureInfo.InvariantCulture, $"{newline}[Obsolete({obsoleteMsg})]"); } return attributes.ToString(); diff --git a/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.xmlSerializer.autogen.cs b/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.xmlSerializer.autogen.cs index 3d46fbf28c2..b0ad8956b38 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.xmlSerializer.autogen.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.xmlSerializer.autogen.cs @@ -289,12 +289,12 @@ protected Exception CreateUnknownNodeException() protected Exception CreateUnknownTypeException(XmlQualifiedName type) { - return new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "XmlUnknownType. Name: {0}, Namespace {1}, CurrentTag: {2}", type.Name, type.Namespace, CurrentTag())); + return new InvalidOperationException(string.Create(CultureInfo.CurrentCulture, $"XmlUnknownType. Name: {type.Name}, Namespace {type.Namespace}, CurrentTag: {CurrentTag()}")); } protected Exception CreateUnknownConstantException(string value, Type enumType) { - return new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "XmlUnknownConstant. Value: {0}, EnumType: {1}", value, enumType.Name)); + return new InvalidOperationException(string.Create(CultureInfo.CurrentCulture, $"XmlUnknownConstant. Value: {value}, EnumType: {enumType.Name}")); } protected Array ShrinkArray(Array a, int length, Type elementType, bool isNullable) @@ -426,7 +426,7 @@ internal XmlQualifiedName ToXmlQualifiedName(string value, bool decodeName) if (ns == null) { // Namespace prefix '{0}' is not defined. - throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "XmlUndefinedAlias. Prefix: {0}", prefix)); + throw new InvalidOperationException(string.Create(CultureInfo.CurrentCulture, $"XmlUndefinedAlias. Prefix: {prefix}")); } return new XmlQualifiedName(_r.NameTable.Add(localName), ns); From 64d82f812d8bc3ce0ef4a435e56cfab73ff8cf33 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Fri, 20 Jan 2023 11:26:43 +0100 Subject: [PATCH 305/779] Use interpolated strings 9 (#18993) --- .../ScheduledJobStore.cs | 2 +- .../DscSupport/CimDSCParser.cs | 24 +++++++++---------- .../common/DisplayDatabase/typeDataQuery.cs | 4 ++-- .../cimSupport/cmdletization/ScriptWriter.cs | 2 +- 4 files changed, 16 insertions(+), 16 deletions(-) diff --git a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobStore.cs b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobStore.cs index 063176feae8..e6bcd1c3b8d 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobStore.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobStore.cs @@ -524,7 +524,7 @@ private static string GetRunDirectory( DateTime runStart) { string directoryPath = GetJobRunOutputDirectory(definitionName); - return string.reate(CultureInfo.InvariantCulture, $@"{directoryPath}\{ConvertDateTimeToJobRunName(runStart)}"); + return string.Create(CultureInfo.InvariantCulture, $@"{directoryPath}\{ConvertDateTimeToJobRunName(runStart)}"); } /// diff --git a/src/System.Management.Automation/DscSupport/CimDSCParser.cs b/src/System.Management.Automation/DscSupport/CimDSCParser.cs index 1347ac2c55c..904103f451d 100644 --- a/src/System.Management.Automation/DscSupport/CimDSCParser.cs +++ b/src/System.Management.Automation/DscSupport/CimDSCParser.cs @@ -2339,7 +2339,7 @@ internal static string MapTypeNameToMofType(ITypeName typeName, string memberNam private static void GenerateMofForAst(TypeDefinitionAst typeAst, StringBuilder sb, List embeddedInstanceTypes) { var className = typeAst.Name; - sb.AppendFormat(CultureInfo.InvariantCulture, $"[ClassVersion(\"1.0.0\"), FriendlyName(\"{className}\")]\nclass {className}"); + sb.Append(CultureInfo.InvariantCulture, $"[ClassVersion(\"1.0.0\"), FriendlyName(\"{className}\")]\nclass {className}"); if (typeAst.Attributes.Any(static a => a.TypeName.GetReflectionAttributeType() == typeof(DscResourceAttribute))) { @@ -2912,19 +2912,19 @@ private static string MapAttributesToMof(string[] enumNames, IEnumerable { if (dscProperty.Key) { - sb.AppendFormat(CultureInfo.InvariantCulture, $"{(needComma ? ", " : string.Empty)}key"); + sb.Append(CultureInfo.InvariantCulture, $"{(needComma ? ", " : string.Empty)}key"); needComma = true; } if (dscProperty.Mandatory) { - sb.AppendFormat(CultureInfo.InvariantCulture, $"{(needComma ? ", " : string.Empty)}required"); + sb.Append(CultureInfo.InvariantCulture, $"{(needComma ? ", " : string.Empty)}required"); needComma = true; } if (dscProperty.NotConfigurable) { - sb.AppendFormat(CultureInfo.InvariantCulture, $"{(needComma ? ", " : string.Empty)}read"); + sb.Append(CultureInfo.InvariantCulture, $"{(needComma ? ", " : string.Empty)}read"); needComma = true; } @@ -2936,13 +2936,13 @@ private static string MapAttributesToMof(string[] enumNames, IEnumerable { bool valueMapComma = false; StringBuilder sbValues = new(", Values{"); - sb.AppendFormat(CultureInfo.InvariantCulture, $"{(needComma ? ", " : string.Empty)}ValueMap{{"); + sb.Append(CultureInfo.InvariantCulture, $"{(needComma ? ", " : string.Empty)}ValueMap{{"); needComma = true; foreach (var value in validateSet.ValidValues) { - sb.AppendFormat(CultureInfo.InvariantCulture, $"{(valueMapComma ? ", " : string.Empty)}\"{value}\""); - sbValues.AppendFormat(CultureInfo.InvariantCulture, $"{(valueMapComma ? ", " : string.Empty)}\"{value}\""); + sb.Append(CultureInfo.InvariantCulture, $"{(valueMapComma ? ", " : string.Empty)}\"{value}\""); + sbValues.Append(CultureInfo.InvariantCulture, $"{(valueMapComma ? ", " : string.Empty)}\"{value}\""); valueMapComma = true; } @@ -2961,11 +2961,11 @@ private static string MapAttributesToMof(string[] enumNames, IEnumerable if (enumNames != null) { - sb.AppendFormat(CultureInfo.InvariantCulture, $"{(needComma ? ", " : string.Empty)}ValueMap{{"); + sb.Append(CultureInfo.InvariantCulture, $"{(needComma ? ", " : string.Empty)}ValueMap{{"); needComma = false; foreach (var name in enumNames) { - sb.AppendFormat(CultureInfo.InvariantCulture, $"{(needComma ? ", " : string.Empty)}\"{name}\""); + sb.Append(CultureInfo.InvariantCulture, $"{(needComma ? ", " : string.Empty)}\"{name}\""); needComma = true; } @@ -2973,7 +2973,7 @@ private static string MapAttributesToMof(string[] enumNames, IEnumerable needComma = false; foreach (var name in enumNames) { - sb.AppendFormat(CultureInfo.InvariantCulture, $"{(needComma ? ", " : string.Empty)}\"{name}\""); + sb.Append(CultureInfo.InvariantCulture, $"{(needComma ? ", " : string.Empty)}\"{name}\""); needComma = true; } @@ -2981,7 +2981,7 @@ private static string MapAttributesToMof(string[] enumNames, IEnumerable } else if (embeddedInstanceType != null) { - sb.AppendFormat(CultureInfo.InvariantCulture, $"{(needComma ? ", " : string.Empty)}EmbeddedInstance(\"{embeddedInstanceType}\")"); + sb.Append(CultureInfo.InvariantCulture, $"{(needComma ? ", " : string.Empty)}EmbeddedInstance(\"{embeddedInstanceType}\")"); } sb.Append(']'); @@ -3047,7 +3047,7 @@ private static void GenerateMofForType(Type type, StringBuilder sb, List { var className = type.Name; // Friendly name is required by module validator to verify resource instance against the exclusive resource name list. - sb.AppendFormat(CultureInfo.InvariantCulture, $"[ClassVersion(\"1.0.0\"), FriendlyName(\"{className}\")]\nclass {className}"); + sb.Append(CultureInfo.InvariantCulture, $"[ClassVersion(\"1.0.0\"), FriendlyName(\"{className}\")]\nclass {className}"); if (type.GetCustomAttributes().Any()) { diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs index 0352db182fb..2ae6a181f87 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs @@ -490,12 +490,12 @@ private static void TraceHelper(ViewDefinition vd, bool isMatched) sb.Append(isMatched ? "MATCH FOUND" : "NOT MATCH"); if (tr != null) { - sb.AppendFormat(CultureInfo.InvariantCulture, $" {ControlBase.GetControlShapeName(vd.mainControl)} NAME: {vd.name} TYPE: {tr.name}"); + sb.Append(CultureInfo.InvariantCulture, $" {ControlBase.GetControlShapeName(vd.mainControl)} NAME: {vd.name} TYPE: {tr.name}"); } else { TypeGroupReference tgr = togr as TypeGroupReference; - sb.AppendFormat(CultureInfo.InvariantCulture, $" {ControlBase.GetControlShapeName(vd.mainControl)} NAME: {vd.name} GROUP: {tgr.name}"); + sb.Append(CultureInfo.InvariantCulture, $" {ControlBase.GetControlShapeName(vd.mainControl)} NAME: {vd.name} GROUP: {tgr.name}"); } ActiveTracer.WriteLine(sb.ToString()); diff --git a/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs b/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs index fb5e2d6656b..a0e09694705 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs @@ -249,7 +249,7 @@ private static string GetCmdletAttributes(CommonCmdletMetadata cmdletMetadata) ? ("'" + CodeGeneration.EscapeSingleQuotedStringContent(cmdletMetadata.Obsolete.Message) + "'") : string.Empty; string newline = (attributes.Length > 0) ? Environment.NewLine : string.Empty; - attributes.AppendFormat(CultureInfo.InvariantCulture, $"{newline}[Obsolete({obsoleteMsg})]"); + attributes.Append(CultureInfo.InvariantCulture, $"{newline}[Obsolete({obsoleteMsg})]"); } return attributes.ToString(); From 740c62a5bf4040a070a6d8d8b9c9e1893668e631 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Fri, 20 Jan 2023 11:38:20 +0100 Subject: [PATCH 306/779] Use interpolated strings 10 (#18992) --- .../host/msh/ConsoleHostUserInterfacePrompt.cs | 2 +- .../host/msh/ConsoleHostUserInterfacePromptForChoice.cs | 2 +- .../engine/hostifaces/InternalHostUserInterface.cs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs index 49ed23a2a69..58cd171cd2f 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs @@ -202,7 +202,7 @@ public override while (true) { - fieldPromptList.AppendFormat(CultureInfo.InvariantCulture, $"{inputList.Count}]: "); + fieldPromptList.Append(CultureInfo.InvariantCulture, $"{inputList.Count}]: "); bool endListInput = false; object convertedObj = null; _ = PromptForSingleItem( diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePromptForChoice.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePromptForChoice.cs index e900a0fc2f7..fa470b245a2 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePromptForChoice.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePromptForChoice.cs @@ -345,7 +345,7 @@ private void WriteChoicePrompt(string[,] hotkeysAndPlainLabels, defaultStr = hotkeysAndPlainLabels[1, defaultChoice]; } - defaultChoicesBuilder.AppendFormat(CultureInfo.InvariantCulture, $"{prepend}{defaultStr}"); + defaultChoicesBuilder.Append(CultureInfo.InvariantCulture, $"{prepend}{defaultStr}"); prepend = ","; } diff --git a/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs index d398e8e006f..48066da71fa 100644 --- a/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs @@ -927,7 +927,7 @@ private Collection EmulatePromptForMultipleChoice(string caption, defaultStr = hotkeysAndPlainLabels[1, defaultChoice]; } - defaultChoicesBuilder.AppendFormat(Globalization.CultureInfo.InvariantCulture, $"{prepend}{defaultStr}"); + defaultChoicesBuilder.Append(Globalization.CultureInfo.InvariantCulture, $"{prepend}{defaultStr}"); prepend = ","; } From e815e5760126f96bde81c605ceb69260477cb1fa Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Fri, 20 Jan 2023 12:59:55 +0100 Subject: [PATCH 307/779] Use interpolated strings 6 (#18983) --- .../engine/CmdletParameterBinderController.cs | 2 +- .../engine/ComInterop/ComTypeEnumDesc.cs | 5 +- .../engine/ComInterop/ComTypeLibDesc.cs | 5 +- .../engine/ComInterop/DispCallable.cs | 5 +- .../engine/ComInterop/IDispatchComObject.cs | 6 +- .../engine/ComInterop/Variant.Extended.cs | 5 +- .../CommandCompletion/CompletionCompleters.cs | 4 +- .../engine/CommandMetadata.cs | 73 +++++++------------ .../engine/CoreAdapter.cs | 4 +- .../engine/GetCommandCommand.cs | 14 +--- .../engine/InternalCommands.cs | 8 +- .../engine/ManagementObjectAdapter.cs | 5 +- .../engine/MshCommandRuntime.cs | 20 ++--- .../engine/ParameterBinderController.cs | 2 +- .../engine/ParameterSetInfo.cs | 31 ++++++-- .../engine/TypeTable.cs | 4 +- .../engine/cmdlet.cs | 26 +++---- 17 files changed, 97 insertions(+), 122 deletions(-) diff --git a/src/System.Management.Automation/engine/CmdletParameterBinderController.cs b/src/System.Management.Automation/engine/CmdletParameterBinderController.cs index ee2fec058cf..83d5e98e954 100644 --- a/src/System.Management.Automation/engine/CmdletParameterBinderController.cs +++ b/src/System.Management.Automation/engine/CmdletParameterBinderController.cs @@ -2983,7 +2983,7 @@ internal static string BuildMissingParamsString(Collection", TypeName); - } + public override string ToString() => $""; internal ComTypeEnumDesc(ComTypes.ITypeInfo typeInfo, ComTypeLibDesc typeLibDesc) : base(typeInfo, typeLibDesc) { diff --git a/src/System.Management.Automation/engine/ComInterop/ComTypeLibDesc.cs b/src/System.Management.Automation/engine/ComInterop/ComTypeLibDesc.cs index 2b81c76b6eb..8f373e52a72 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComTypeLibDesc.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComTypeLibDesc.cs @@ -32,10 +32,7 @@ private ComTypeLibDesc() _classes = new LinkedList(); } - public override string ToString() - { - return string.Format(CultureInfo.CurrentCulture, "", Name); - } + public override string ToString() => $""; public string Documentation { diff --git a/src/System.Management.Automation/engine/ComInterop/DispCallable.cs b/src/System.Management.Automation/engine/ComInterop/DispCallable.cs index df0f54009ac..e99bdd3741f 100644 --- a/src/System.Management.Automation/engine/ComInterop/DispCallable.cs +++ b/src/System.Management.Automation/engine/ComInterop/DispCallable.cs @@ -19,10 +19,7 @@ internal DispCallable(IDispatchComObject dispatch, string memberName, int dispId DispId = dispId; } - public override string ToString() - { - return string.Format(CultureInfo.CurrentCulture, "", MemberName); - } + public override string ToString() => $""; public IDispatchComObject DispatchComObject { get; } diff --git a/src/System.Management.Automation/engine/ComInterop/IDispatchComObject.cs b/src/System.Management.Automation/engine/ComInterop/IDispatchComObject.cs index 5335a18c6de..6ce86476566 100644 --- a/src/System.Management.Automation/engine/ComInterop/IDispatchComObject.cs +++ b/src/System.Management.Automation/engine/ComInterop/IDispatchComObject.cs @@ -99,7 +99,7 @@ public override string ToString() typeName = "IDispatch"; } - return string.Format(CultureInfo.CurrentCulture, "{0} ({1})", RuntimeCallableWrapper.ToString(), typeName); + return $"{RuntimeCallableWrapper} ({typeName})"; } public ComTypeDesc ComTypeDesc @@ -222,7 +222,7 @@ internal bool TryGetMemberMethodExplicit(string name, out ComMethodDesc method) return false; } - throw Error.CouldNotGetDispId(name, string.Format(CultureInfo.InvariantCulture, "0x{0:X})", hresult)); + throw Error.CouldNotGetDispId(name, string.Create(CultureInfo.InvariantCulture, $"0x{hresult:X})")); } internal bool TryGetPropertySetterExplicit(string name, out ComMethodDesc method, Type limitType, bool holdsNull) @@ -258,7 +258,7 @@ internal bool TryGetPropertySetterExplicit(string name, out ComMethodDesc method return false; } - throw Error.CouldNotGetDispId(name, string.Format(CultureInfo.InvariantCulture, "0x{0:X})", hresult)); + throw Error.CouldNotGetDispId(name, string.Create(CultureInfo.InvariantCulture, $"0x{hresult:X})")); } internal override IList GetMemberNames(bool dataOnly) diff --git a/src/System.Management.Automation/engine/ComInterop/Variant.Extended.cs b/src/System.Management.Automation/engine/ComInterop/Variant.Extended.cs index 3a47dbd2ba4..9cab38d0773 100644 --- a/src/System.Management.Automation/engine/ComInterop/Variant.Extended.cs +++ b/src/System.Management.Automation/engine/ComInterop/Variant.Extended.cs @@ -282,10 +282,7 @@ internal static System.Reflection.MethodInfo GetByrefSetter(VarEnum varType) } } - public override string ToString() - { - return string.Format(CultureInfo.CurrentCulture, "Variant ({0})", VariantType); - } + public override string ToString() => $"Variant ({VariantType})"; public void SetAsIConvertible(IConvertible value) { diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs index d8dda81d2ba..ca4cc4ec1db 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs @@ -2701,7 +2701,7 @@ private static void NativeCompletionCimAssociationResultClassName( WildcardPattern resultClassNamePattern = WildcardPattern.Get(context.WordToComplete + "*", WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant); result.AddRange(resultClassNames .Where(resultClassNamePattern.IsMatch) - .Select(x => new CompletionResult(x, x, CompletionResultType.Type, string.Format(CultureInfo.InvariantCulture, "{0} -> {1}", pseudoboundClassName, x)))); + .Select(x => new CompletionResult(x, x, CompletionResultType.Type, string.Create(CultureInfo.InvariantCulture, $"{pseudoboundClassName} -> {x}")))); } private static void NativeCompletionCimMethodName( @@ -6511,7 +6511,7 @@ internal override CompletionResult GetCompletionResult(string keyMatched, string if (i != 0) tooltip.Append(", "); tooltip.Append(GenericArgumentCount == 1 ? "T" - : string.Format(CultureInfo.InvariantCulture, "T{0}", i + 1)); + : string.Create(CultureInfo.InvariantCulture, $"T{i + 1}")); } tooltip.Append(']'); diff --git a/src/System.Management.Automation/engine/CommandMetadata.cs b/src/System.Management.Automation/engine/CommandMetadata.cs index f7e74f00cb8..aba83a1632d 100644 --- a/src/System.Management.Automation/engine/CommandMetadata.cs +++ b/src/System.Management.Automation/engine/CommandMetadata.cs @@ -847,49 +847,40 @@ internal string GetProxyCommand(string helpComment, bool generateDynamicParamete { if (string.IsNullOrEmpty(helpComment)) { - helpComment = string.Format(CultureInfo.InvariantCulture, @" -.ForwardHelpTargetName {0} -.ForwardHelpCategory {1} -", - _wrappedCommand, _wrappedCommandType); + helpComment = string.Create(CultureInfo.InvariantCulture, $@" +.ForwardHelpTargetName {_wrappedCommand} +.ForwardHelpCategory {_wrappedCommandType} +"); } string dynamicParamblock = string.Empty; if (generateDynamicParameters && this.ImplementsDynamicParameters) { - dynamicParamblock = string.Format(CultureInfo.InvariantCulture, @" + dynamicParamblock = string.Create(CultureInfo.InvariantCulture, $@" dynamicparam -{{{0}}} +{{{GetDynamicParamBlock()}}} -", GetDynamicParamBlock()); +"); } - string result = string.Format(CultureInfo.InvariantCulture, @"{0} -param({1}) + string result = string.Create(CultureInfo.InvariantCulture, $@"{GetDecl()} +param({GetParamBlock()}) -{2}begin -{{{3}}} +{dynamicParamblock}begin +{{{GetBeginBlock()}}} process -{{{4}}} +{{{GetProcessBlock()}}} end -{{{5}}} +{{{GetEndBlock()}}} clean -{{{6}}} +{{{GetCleanBlock()}}} <# -{7} +{CodeGeneration.EscapeBlockCommentContent(helpComment)} #> -", - GetDecl(), - GetParamBlock(), - dynamicParamblock, - GetBeginBlock(), - GetProcessBlock(), - GetEndBlock(), - GetCleanBlock(), - CodeGeneration.EscapeBlockCommentContent(helpComment)); +"); return result; } @@ -1020,7 +1011,7 @@ internal string GetBeginBlock() if (_wrappedAnyCmdlet) { - result = string.Format(CultureInfo.InvariantCulture, @" + result = string.Create(CultureInfo.InvariantCulture, $@" try {{ $outBuffer = $null if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) @@ -1028,38 +1019,30 @@ internal string GetBeginBlock() $PSBoundParameters['OutBuffer'] = 1 }} - $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('{0}', [System.Management.Automation.CommandTypes]::{1}) + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('{CodeGeneration.EscapeSingleQuotedStringContent(_wrappedCommand)}', [System.Management.Automation.CommandTypes]::{_wrappedCommandType}) $scriptCmd = {{& $wrappedCmd @PSBoundParameters }} - $steppablePipeline = $scriptCmd.GetSteppablePipeline({2}) + $steppablePipeline = $scriptCmd.GetSteppablePipeline({commandOrigin}) $steppablePipeline.Begin($PSCmdlet) }} catch {{ throw }} -", - CodeGeneration.EscapeSingleQuotedStringContent(_wrappedCommand), - _wrappedCommandType, - commandOrigin - ); +"); } else { - result = string.Format(CultureInfo.InvariantCulture, @" + result = string.Create(CultureInfo.InvariantCulture, $@" try {{ - $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('{0}', [System.Management.Automation.CommandTypes]::{1}) + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('{CodeGeneration.EscapeSingleQuotedStringContent(_wrappedCommand)}', [System.Management.Automation.CommandTypes]::{_wrappedCommandType}) $PSBoundParameters.Add('$args', $args) $scriptCmd = {{& $wrappedCmd @PSBoundParameters }} - $steppablePipeline = $scriptCmd.GetSteppablePipeline({2}) + $steppablePipeline = $scriptCmd.GetSteppablePipeline({commandOrigin}) $steppablePipeline.Begin($myInvocation.ExpectingInput, $ExecutionContext) }} catch {{ throw }} -", - CodeGeneration.EscapeSingleQuotedStringContent(_wrappedCommand), - _wrappedCommandType, - commandOrigin - ); +"); } return result; @@ -1083,9 +1066,9 @@ internal string GetProcessBlock() internal string GetDynamicParamBlock() { - return string.Format(CultureInfo.InvariantCulture, @" + return string.Create(CultureInfo.InvariantCulture, $@" try {{ - $targetCmd = $ExecutionContext.InvokeCommand.GetCommand('{0}', [System.Management.Automation.CommandTypes]::{1}, $PSBoundParameters) + $targetCmd = $ExecutionContext.InvokeCommand.GetCommand('{CodeGeneration.EscapeSingleQuotedStringContent(_wrappedCommand)}', [System.Management.Automation.CommandTypes]::{_wrappedCommandType}, $PSBoundParameters) $dynamicParams = @($targetCmd.Parameters.GetEnumerator() | Microsoft.PowerShell.Core\Where-Object {{ $_.Value.IsDynamic }}) if ($dynamicParams.Length -gt 0) {{ @@ -1106,9 +1089,7 @@ internal string GetDynamicParamBlock() }} catch {{ throw }} -", - CodeGeneration.EscapeSingleQuotedStringContent(_wrappedCommand), - _wrappedCommandType); +"); } internal string GetEndBlock() diff --git a/src/System.Management.Automation/engine/CoreAdapter.cs b/src/System.Management.Automation/engine/CoreAdapter.cs index 17ddb9eb1e2..beb220495a6 100644 --- a/src/System.Management.Automation/engine/CoreAdapter.cs +++ b/src/System.Management.Automation/engine/CoreAdapter.cs @@ -3887,11 +3887,11 @@ private static string GetDefaultValueStringRepresentation(ParameterInfo paramete if (parameterType.IsEnum) { - return string.Format(CultureInfo.InvariantCulture, "{0}.{1}", parameterType.ToString(), parameterDefaultValue.ToString()); + return string.Create(CultureInfo.InvariantCulture, $"{parameterType}.{parameterDefaultValue}"); } return (parameterDefaultValue is string) - ? string.Format(CultureInfo.InvariantCulture, "\"{0}\"", parameterDefaultValue.ToString()) + ? string.Create(CultureInfo.InvariantCulture, $"\"{parameterDefaultValue}\"") : parameterDefaultValue.ToString(); } diff --git a/src/System.Management.Automation/engine/GetCommandCommand.cs b/src/System.Management.Automation/engine/GetCommandCommand.cs index 81675d7b663..a3263799cda 100644 --- a/src/System.Management.Automation/engine/GetCommandCommand.cs +++ b/src/System.Management.Automation/engine/GetCommandCommand.cs @@ -614,12 +614,7 @@ private PSObject GetSyntaxObject(CommandInfo command) switch (command) { case ExternalScriptInfo externalScript: - replacedSyntax = string.Format( - "{0} (alias) -> {1}{2}{3}", - aliasName, - string.Format("{0}{1}", externalScript.Path, Environment.NewLine), - Environment.NewLine, - command.Syntax.Replace(command.Name, aliasName)); + replacedSyntax = string.Create(CultureInfo.InvariantCulture, $"{aliasName} (alias) -> {externalScript.Path}{Environment.NewLine}{Environment.NewLine}{command.Syntax.Replace(command.Name, aliasName)}"); break; case ApplicationInfo app: replacedSyntax = app.Path; @@ -631,12 +626,7 @@ private PSObject GetSyntaxObject(CommandInfo command) } else { - replacedSyntax = string.Format( - "{0} (alias) -> {1}{2}{3}", - aliasName, - command.Name, - Environment.NewLine, - command.Syntax.Replace(command.Name, aliasName)); + replacedSyntax = string.Create(CultureInfo.InvariantCulture, $"{aliasName} (alias) -> {command.Name}{Environment.NewLine}{command.Syntax.Replace(command.Name, aliasName)}"); } break; diff --git a/src/System.Management.Automation/engine/InternalCommands.cs b/src/System.Management.Automation/engine/InternalCommands.cs index 8ef6976c446..0edc1a21a61 100644 --- a/src/System.Management.Automation/engine/InternalCommands.cs +++ b/src/System.Management.Automation/engine/InternalCommands.cs @@ -701,7 +701,7 @@ private void ProcessPropertyAndMethodParameterSet() StringBuilder possibleMatches = new StringBuilder(); foreach (PSMemberInfo item in members) { - possibleMatches.AppendFormat(CultureInfo.InvariantCulture, " {0}", item.Name); + possibleMatches.Append(CultureInfo.InvariantCulture, $" {item.Name}"); } WriteError(GenerateNameParameterError("Name", InternalCommandStrings.AmbiguousPropertyOrMethodName, @@ -1019,7 +1019,7 @@ private void MethodCallWithArguments() StringBuilder possibleMatches = new StringBuilder(); foreach (PSMemberInfo item in methods) { - possibleMatches.AppendFormat(CultureInfo.InvariantCulture, " {0}", item.Name); + possibleMatches.Append(CultureInfo.InvariantCulture, $" {item.Name}"); } WriteError(GenerateNameParameterError( @@ -1049,7 +1049,7 @@ private void MethodCallWithArguments() StringBuilder arglist = new StringBuilder(GetStringRepresentation(_arguments[0])); for (int i = 1; i < _arguments.Length; i++) { - arglist.AppendFormat(CultureInfo.InvariantCulture, ", {0}", GetStringRepresentation(_arguments[i])); + arglist.Append(CultureInfo.InvariantCulture, $", {GetStringRepresentation(_arguments[i])}"); } string methodAction = string.Format(CultureInfo.InvariantCulture, @@ -2355,7 +2355,7 @@ private object GetValue(ref bool error) StringBuilder possibleMatches = new StringBuilder(); foreach (PSMemberInfo item in members) { - possibleMatches.AppendFormat(CultureInfo.InvariantCulture, " {0}", item.Name); + possibleMatches.Append(CultureInfo.InvariantCulture, $" {item.Name}"); } WriteError( diff --git a/src/System.Management.Automation/engine/ManagementObjectAdapter.cs b/src/System.Management.Automation/engine/ManagementObjectAdapter.cs index c591a6963ec..707d8314dce 100644 --- a/src/System.Management.Automation/engine/ManagementObjectAdapter.cs +++ b/src/System.Management.Automation/engine/ManagementObjectAdapter.cs @@ -454,7 +454,7 @@ protected static CacheTable GetInstanceMethodTable(ManagementBaseObject wmiObjec // unique identifier for identifying this ManagementObject's type ManagementPath classPath = wmiObject.ClassPath; - string key = string.Format(CultureInfo.InvariantCulture, "{0}#{1}", classPath.Path, staticBinding.ToString()); + string key = string.Create(CultureInfo.InvariantCulture, $"{classPath.Path}#{staticBinding}"); typeTable = (CacheTable)s_instanceMethodCacheTable[key]; if (typeTable != null) @@ -577,8 +577,7 @@ protected static string GetEmbeddedObjectTypeName(PropertyData pData) try { string cimType = (string)pData.Qualifiers["cimtype"].Value; - result = string.Format(CultureInfo.InvariantCulture, "{0}#{1}", - typeof(ManagementObject).FullName, cimType.Replace("object:", string.Empty)); + result = string.Create(CultureInfo.InvariantCulture, $"{typeof(ManagementObject).FullName}#{cimType.Replace("object:", string.Empty)}"); } catch (ManagementException) { diff --git a/src/System.Management.Automation/engine/MshCommandRuntime.cs b/src/System.Management.Automation/engine/MshCommandRuntime.cs index d8bb95b59e6..d1d0561957b 100644 --- a/src/System.Management.Automation/engine/MshCommandRuntime.cs +++ b/src/System.Management.Automation/engine/MshCommandRuntime.cs @@ -1295,8 +1295,8 @@ public bool ShouldProcess(string target, string action) /// public override void ProcessRecord() /// { /// if (ShouldProcess( - /// string.Format("Deleting file {0}",filename), - /// string.Format("Are you sure you want to delete file {0}?", filename), + /// string.Format($"Deleting file {filename}"), + /// string.Format($"Are you sure you want to delete file {filename}?"), /// "Delete file")) /// { /// // delete the object @@ -1411,8 +1411,8 @@ public bool ShouldProcess( /// { /// ShouldProcessReason shouldProcessReason; /// if (ShouldProcess( - /// string.Format("Deleting file {0}",filename), - /// string.Format("Are you sure you want to delete file {0}?", filename), + /// string.Format($"Deleting file {filename}"), + /// string.Format($"Are you sure you want to delete file {filename}?"), /// "Delete file", /// out shouldProcessReason)) /// { @@ -1724,14 +1724,14 @@ internal ShouldProcessPossibleOptimization CalculatePossibleShouldProcessOptimiz /// public override void ProcessRecord() /// { /// if (ShouldProcess( - /// string.Format("Deleting file {0}",filename), - /// string.Format("Are you sure you want to delete file {0}", filename), + /// string.Format($"Deleting file {filename}"), + /// string.Format($"Are you sure you want to delete file {filename}"), /// "Delete file")) /// { /// if (IsReadOnly(filename)) /// { /// if (!Force && !ShouldContinue( - /// string.Format("File {0} is read-only. Are you sure you want to delete read-only file {0}?", filename), + /// string.Format($"File {filename} is read-only. Are you sure you want to delete read-only file {filename}?"), /// "Delete file")) /// ) /// { @@ -1909,14 +1909,14 @@ public bool ShouldContinue( /// public override void ProcessRecord() /// { /// if (ShouldProcess( - /// string.Format("Deleting file {0}",filename), - /// string.Format("Are you sure you want to delete file {0}", filename), + /// string.Format($"Deleting file {filename}"), + /// string.Format($"Are you sure you want to delete file {filename}"), /// "Delete file")) /// { /// if (IsReadOnly(filename)) /// { /// if (!Force && !ShouldContinue( - /// string.Format("File {0} is read-only. Are you sure you want to delete read-only file {0}?", filename), + /// string.Format($"File {filename} is read-only. Are you sure you want to delete read-only file {filename}?"), /// "Delete file"), /// ref yesToAll, /// ref noToAll diff --git a/src/System.Management.Automation/engine/ParameterBinderController.cs b/src/System.Management.Automation/engine/ParameterBinderController.cs index e6a7153a879..931dc24d554 100644 --- a/src/System.Management.Automation/engine/ParameterBinderController.cs +++ b/src/System.Management.Automation/engine/ParameterBinderController.cs @@ -1029,7 +1029,7 @@ protected void ThrowElaboratedBindingException(ParameterBindingException pbex) StringBuilder defaultParamsGetBound = new StringBuilder(); foreach (string paramName in BoundDefaultParameters) { - defaultParamsGetBound.AppendFormat(CultureInfo.InvariantCulture, " -{0}", paramName); + defaultParamsGetBound.Append(CultureInfo.InvariantCulture, $" -{paramName}"); } string resourceString = ParameterBinderStrings.DefaultBindingErrorElaborationSingle; diff --git a/src/System.Management.Automation/engine/ParameterSetInfo.cs b/src/System.Management.Automation/engine/ParameterSetInfo.cs index a2bbd69b7d1..2574c086b53 100644 --- a/src/System.Management.Automation/engine/ParameterSetInfo.cs +++ b/src/System.Management.Automation/engine/ParameterSetInfo.cs @@ -238,7 +238,14 @@ private static void AppendFormatCommandParameterInfo(CommandParameterInfo parame if (parameter.ParameterType == typeof(SwitchParameter)) { - result.AppendFormat(CultureInfo.InvariantCulture, parameter.IsMandatory ? "-{0}" : "[-{0}]", parameter.Name); + if (parameter.IsMandatory) + { + result.Append($"-{parameter.Name}"); + } + else + { + result.Append($"[-{parameter.Name}]"); + } } else { @@ -246,15 +253,25 @@ private static void AppendFormatCommandParameterInfo(CommandParameterInfo parame if (parameter.IsMandatory) { - result.AppendFormat(CultureInfo.InvariantCulture, - parameter.Position != int.MinValue ? "[-{0}] <{1}>" : "-{0} <{1}>", - parameter.Name, parameterTypeString); + if (parameter.Position != int.MinValue) + { + result.Append($"[-{parameter.Name}] <{parameterTypeString}>"); + } + else + { + result.Append($"-{parameter.Name} <{parameterTypeString}>"); + } } else { - result.AppendFormat(CultureInfo.InvariantCulture, - parameter.Position != int.MinValue ? "[[-{0}] <{1}>]" : "[-{0} <{1}>]", - parameter.Name, parameterTypeString); + if (parameter.Position != int.MinValue) + { + result.Append($"[[-{parameter.Name}] <{parameterTypeString}>]"); + } + else + { + result.Append($"[-{parameter.Name} <{parameterTypeString}>]"); + } } } } diff --git a/src/System.Management.Automation/engine/TypeTable.cs b/src/System.Management.Automation/engine/TypeTable.cs index a752f9b62df..042d0ddf72d 100644 --- a/src/System.Management.Automation/engine/TypeTable.cs +++ b/src/System.Management.Automation/engine/TypeTable.cs @@ -1819,7 +1819,7 @@ protected TypeTableLoadException(SerializationInfo info, StreamingContext contex _errors = new Collection(); for (int index = 0; index < errorCount; index++) { - string key = string.Format(CultureInfo.InvariantCulture, "Error{0}", index); + string key = string.Create(CultureInfo.InvariantCulture, $"Error{index}"); _errors.Add(info.GetString(key)); } } @@ -1849,7 +1849,7 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont for (int index = 0; index < errorCount; index++) { - string key = string.Format(CultureInfo.InvariantCulture, "Error{0}", index); + string key = string.Create(CultureInfo.InvariantCulture, $"Error{index}"); info.AddValue(key, _errors[index]); } } diff --git a/src/System.Management.Automation/engine/cmdlet.cs b/src/System.Management.Automation/engine/cmdlet.cs index 9a02adc4c60..2f60c95ee47 100644 --- a/src/System.Management.Automation/engine/cmdlet.cs +++ b/src/System.Management.Automation/engine/cmdlet.cs @@ -1018,8 +1018,8 @@ public bool ShouldProcess(string target, string action) /// public override void ProcessRecord() /// { /// if (ShouldProcess( - /// string.Format("Deleting file {0}",filename), - /// string.Format("Are you sure you want to delete file {0}?", filename), + /// string.Format($"Deleting file {filename}"), + /// string.Format($"Are you sure you want to delete file {filename}?"), /// "Delete file")) /// { /// // delete the object @@ -1135,8 +1135,8 @@ public bool ShouldProcess( /// { /// ShouldProcessReason shouldProcessReason; /// if (ShouldProcess( - /// string.Format("Deleting file {0}",filename), - /// string.Format("Are you sure you want to delete file {0}?", filename), + /// string.Format($"Deleting file {filename}"), + /// string.Format($"Are you sure you want to delete file {filename}?"), /// "Delete file", /// out shouldProcessReason)) /// { @@ -1258,14 +1258,14 @@ public bool ShouldProcess( /// public override void ProcessRecord() /// { /// if (ShouldProcess( - /// string.Format("Deleting file {0}",filename), - /// string.Format("Are you sure you want to delete file {0}", filename), + /// string.Format($"Deleting file {filename}"), + /// string.Format($"Are you sure you want to delete file {filename}"), /// "Delete file")) /// { /// if (IsReadOnly(filename)) /// { /// if (!Force && !ShouldContinue( - /// string.Format("File {0} is read-only. Are you sure you want to delete read-only file {0}?", filename), + /// string.Format($"File {filename} is read-only. Are you sure you want to delete read-only file {filename}?"), /// "Delete file")) /// ) /// { @@ -1390,14 +1390,14 @@ public bool ShouldContinue(string query, string caption) /// public override void ProcessRecord() /// { /// if (ShouldProcess( - /// string.Format("Deleting file {0}",filename), - /// string.Format("Are you sure you want to delete file {0}", filename), + /// string.Format($"Deleting file {filename}"), + /// string.Format($"Are you sure you want to delete file {filename}"), /// "Delete file")) /// { /// if (IsReadOnly(filename)) /// { /// if (!Force && !ShouldContinue( - /// string.Format("File {0} is read-only. Are you sure you want to delete read-only file {0}?", filename), + /// string.Format($"File {filename} is read-only. Are you sure you want to delete read-only file {filename}?"), /// "Delete file"), /// ref yesToAll, /// ref noToAll @@ -1530,14 +1530,14 @@ public bool ShouldContinue( /// public override void ProcessRecord() /// { /// if (ShouldProcess( - /// string.Format("Deleting file {0}",filename), - /// string.Format("Are you sure you want to delete file {0}", filename), + /// string.Format($"Deleting file {filename}"), + /// string.Format($"Are you sure you want to delete file {filename}"), /// "Delete file")) /// { /// if (IsReadOnly(filename)) /// { /// if (!Force && !ShouldContinue( - /// string.Format("File {0} is read-only. Are you sure you want to delete read-only file {0}?", filename), + /// string.Format($"File {filename} is read-only. Are you sure you want to delete read-only file {filename}?"), /// "Delete file"), /// ref yesToAll, /// ref noToAll From b85fe99f5aa3bed704da0669a5f44140854e7f75 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Fri, 20 Jan 2023 18:22:10 +0100 Subject: [PATCH 308/779] Use interpolated strings 2 (#18978) --- .../GetCounterCommand.cs | 2 +- .../GetEventCommand.cs | 10 ++--- .../ImportCounterCommand.cs | 2 +- .../management/GetComputerInfoCommand.cs | 2 +- .../commands/management/Navigation.cs | 2 +- .../commands/utility/CsvCommands.cs | 2 +- .../FormatAndOutput/format-hex/Format-Hex.cs | 2 +- .../commands/utility/Group-Object.cs | 4 +- .../utility/ImplicitRemotingCommands.cs | 37 ++++++------------- .../commands/utility/UtilityCommon.cs | 2 +- .../WebCmdlet/Common/ContentHelper.Common.cs | 2 +- .../Common/InvokeRestMethodCommand.Common.cs | 2 +- .../Common/WebRequestPSCmdlet.Common.cs | 10 ++--- .../CoreCLR/WebResponseHelper.CoreClr.cs | 2 +- .../commands/utility/WebCmdlet/PSUserAgent.cs | 14 +++---- .../commands/utility/XmlCommands.cs | 2 +- .../host/msh/ConsoleControl.cs | 30 +++++++-------- .../host/msh/ConsoleHostRawUserInterface.cs | 7 ++-- .../msh/ConsoleHostUserInterfacePrompt.cs | 6 +-- ...ConsoleHostUserInterfacePromptForChoice.cs | 2 +- .../host/msh/UpdatesNotification.cs | 2 +- 21 files changed, 62 insertions(+), 82 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/GetCounterCommand.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/GetCounterCommand.cs index f04c8ceff0f..0122ad1941f 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/GetCounterCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/GetCounterCommand.cs @@ -248,7 +248,7 @@ protected override void ProcessRecord() break; default: - Debug.Fail(string.Format(CultureInfo.InvariantCulture, "Invalid parameter set name: {0}", ParameterSetName)); + Debug.Fail(string.Create(CultureInfo.InvariantCulture, $"Invalid parameter set name: {ParameterSetName}")); break; } } diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs index 587a63683ab..8f7e42dd9ae 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs @@ -396,7 +396,7 @@ protected override void ProcessRecord() break; default: - WriteDebug(string.Format(CultureInfo.InvariantCulture, "Invalid parameter set name: {0}", ParameterSetName)); + WriteDebug(string.Create(CultureInfo.InvariantCulture, $"Invalid parameter set name: {ParameterSetName}")); break; } } @@ -492,7 +492,7 @@ private void ProcessGetProvider() foreach (string log in _providersByLogMap.Keys) { logQuery = new EventLogQuery(log, PathType.LogName, AddProviderPredicatesToFilter(_providersByLogMap[log])); - WriteVerbose(string.Format(CultureInfo.InvariantCulture, "Log {0} will be queried", log)); + WriteVerbose(string.Create(CultureInfo.InvariantCulture, $"Log {log} will be queried")); } } @@ -680,7 +680,7 @@ private void ProcessFile() foreach (string resolvedPath in resolvedPaths) { _resolvedPaths.Add(resolvedPath); - WriteVerbose(string.Format(CultureInfo.InvariantCulture, "Found file {0}", resolvedPath)); + WriteVerbose(string.Create(CultureInfo.InvariantCulture, $"Found file {resolvedPath}")); } } @@ -908,7 +908,7 @@ private string BuildStructuredQuery(EventLogSession eventLogSession) break; default: - WriteDebug(string.Format(CultureInfo.InvariantCulture, "Invalid parameter set name: {0}", ParameterSetName)); + WriteDebug(string.Create(CultureInfo.InvariantCulture, $"Invalid parameter set name: {ParameterSetName}")); break; } @@ -2047,7 +2047,7 @@ private void FindProvidersByLogForWildcardPatterns(EventLogSession eventLogSessi || (wildProvPattern.IsMatch(provName))) { - WriteVerbose(string.Format(CultureInfo.InvariantCulture, "Found matching provider: {0}", provName)); + WriteVerbose(string.Create(CultureInfo.InvariantCulture, $"Found matching provider: {provName}")); AddLogsForProviderToInternalMap(eventLogSession, provName); bMatched = true; } diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/ImportCounterCommand.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/ImportCounterCommand.cs index d571df34084..ed4cdb51ff9 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/ImportCounterCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/ImportCounterCommand.cs @@ -240,7 +240,7 @@ protected override void EndProcessing() break; default: - Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Invalid parameter set name: {0}", ParameterSetName)); + Debug.Assert(false, $"Invalid parameter set name: {ParameterSetName}"); break; } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs index 7f69d6defd7..47569282929 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs @@ -248,7 +248,7 @@ private static string GetHalVersion(CimSession session, string systemDirectory) try { var halPath = CIMHelper.EscapePath(System.IO.Path.Combine(systemDirectory, "hal.dll")); - var query = string.Format("SELECT * FROM CIM_DataFile Where Name='{0}'", halPath); + var query = string.Create(CultureInfo.InvariantCulture, $"SELECT * FROM CIM_DataFile Where Name='{halPath}'"); var instance = session.QueryFirstInstance(query); if (instance != null) diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Navigation.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Navigation.cs index 9e81db105be..66995217311 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Navigation.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Navigation.cs @@ -618,7 +618,7 @@ protected override void ProcessRecord() break; default: - Dbg.Diagnostics.Assert(false, string.Format(System.Globalization.CultureInfo.InvariantCulture, "One of the predefined parameter sets should have been specified, instead we got: {0}", ParameterSetName)); + Dbg.Diagnostics.Assert(false, string.Create(System.Globalization.CultureInfo.InvariantCulture, $"One of the predefined parameter sets should have been specified, instead we got: {ParameterSetName}")); break; } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs index 3557946b24d..a447a8983bb 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs @@ -1151,7 +1151,7 @@ internal static string GetTypeString(PSObject source) temp = temp.Substring(4); } - type = string.Format(System.Globalization.CultureInfo.InvariantCulture, "#TYPE {0}", temp); + type = string.Create(System.Globalization.CultureInfo.InvariantCulture, $"#TYPE {temp}"); } return type; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-hex/Format-Hex.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-hex/Format-Hex.cs index de73b2155a6..b6a6d024396 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-hex/Format-Hex.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-hex/Format-Hex.cs @@ -296,7 +296,7 @@ private void ProcessString(string originalString) private static readonly Random _idGenerator = new(); private static string GetGroupLabel(Type inputType) - => string.Format("{0} ({1}) <{2:X8}>", inputType.Name, inputType.FullName, _idGenerator.Next()); + => string.Create(System.Globalization.CultureInfo.InvariantCulture, $"{inputType.Name} ({inputType.FullName}) <{_idGenerator.Next():X8}>"); private void FlushInputBuffer() { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Group-Object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Group-Object.cs index 379865e850e..51f8f0a6011 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Group-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Group-Object.cs @@ -153,7 +153,7 @@ private static string BuildName(List propValues) foreach (object item in propertyValueItems) { - sb.AppendFormat(CultureInfo.InvariantCulture, "{0}, ", item.ToString()); + sb.Append(CultureInfo.InvariantCulture, $"{item}, "); } sb = sb.Length > length ? sb.Remove(sb.Length - 2, 2) : sb; @@ -161,7 +161,7 @@ private static string BuildName(List propValues) } else { - sb.AppendFormat(CultureInfo.InvariantCulture, "{0}, ", propValuePropertyValue.ToString()); + sb.Append(CultureInfo.InvariantCulture, $"{propValuePropertyValue}, "); } } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs index c6197a4b7bf..ed21408c92f 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs @@ -2247,13 +2247,13 @@ private string GenerateNewPSSessionOption() RunspaceConnectionInfo runspaceConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as RunspaceConnectionInfo; if (runspaceConnectionInfo != null) { - result.AppendFormat(null, "-Culture '{0}' ", CodeGeneration.EscapeSingleQuotedStringContent(runspaceConnectionInfo.Culture.ToString())); - result.AppendFormat(null, "-UICulture '{0}' ", CodeGeneration.EscapeSingleQuotedStringContent(runspaceConnectionInfo.UICulture.ToString())); + result.Append(null, $"-Culture '{CodeGeneration.EscapeSingleQuotedStringContent(runspaceConnectionInfo.Culture.ToString())}' "); + result.Append(null, $"-UICulture '{CodeGeneration.EscapeSingleQuotedStringContent(runspaceConnectionInfo.UICulture.ToString())}' "); - result.AppendFormat(null, "-CancelTimeOut {0} ", runspaceConnectionInfo.CancelTimeout); - result.AppendFormat(null, "-IdleTimeOut {0} ", runspaceConnectionInfo.IdleTimeout); - result.AppendFormat(null, "-OpenTimeOut {0} ", runspaceConnectionInfo.OpenTimeout); - result.AppendFormat(null, "-OperationTimeOut {0} ", runspaceConnectionInfo.OperationTimeout); + result.Append(null, $"-CancelTimeOut {runspaceConnectionInfo.CancelTimeout} "); + result.Append(null, $"-IdleTimeOut {runspaceConnectionInfo.IdleTimeout} "); + result.Append(null, $"-OpenTimeOut {runspaceConnectionInfo.OpenTimeout} "); + result.Append(null, $"-OperationTimeOut {runspaceConnectionInfo.OperationTimeout} "); } WSManConnectionInfo wsmanConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as WSManConnectionInfo; @@ -2275,33 +2275,18 @@ private string GenerateNewPSSessionOption() if (wsmanConnectionInfo.MaximumReceivedDataSizePerCommand.HasValue) { - result.AppendFormat( - CultureInfo.InvariantCulture, - "-MaximumReceivedDataSizePerCommand {0} ", - wsmanConnectionInfo.MaximumReceivedDataSizePerCommand.Value); + result.Append(CultureInfo.InvariantCulture, $"-MaximumReceivedDataSizePerCommand {wsmanConnectionInfo.MaximumReceivedDataSizePerCommand.Value} "); } if (wsmanConnectionInfo.MaximumReceivedObjectSize.HasValue) { - result.AppendFormat( - CultureInfo.InvariantCulture, - "-MaximumReceivedObjectSize {0} ", - wsmanConnectionInfo.MaximumReceivedObjectSize.Value); + result.Append(CultureInfo.InvariantCulture, $"-MaximumReceivedObjectSize {wsmanConnectionInfo.MaximumReceivedObjectSize.Value} "); } - result.AppendFormat( - CultureInfo.InvariantCulture, - "-MaximumRedirection {0} ", - wsmanConnectionInfo.MaximumConnectionRedirectionCount); + result.Append(CultureInfo.InvariantCulture, $"-MaximumRedirection {wsmanConnectionInfo.MaximumConnectionRedirectionCount} "); - result.AppendFormat( - CultureInfo.InvariantCulture, - "-ProxyAccessType {0} ", - wsmanConnectionInfo.ProxyAccessType.ToString()); - result.AppendFormat( - CultureInfo.InvariantCulture, - "-ProxyAuthentication {0} ", - wsmanConnectionInfo.ProxyAuthentication.ToString()); + result.Append(CultureInfo.InvariantCulture, $"-ProxyAccessType {wsmanConnectionInfo.ProxyAccessType} "); + result.Append(CultureInfo.InvariantCulture, $"-ProxyAuthentication {wsmanConnectionInfo.ProxyAuthentication} "); result.Append(this.GenerateProxyCredentialParameter(wsmanConnectionInfo)); } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UtilityCommon.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UtilityCommon.cs index 327e6f19c54..1e3cc038750 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UtilityCommon.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UtilityCommon.cs @@ -215,7 +215,7 @@ private set /// /// Gets the hexadecimal representation of the value. /// - public string HexOffset { get => string.Format(CultureInfo.CurrentCulture, "{0:X16}", Offset64); } + public string HexOffset => string.Create(CultureInfo.CurrentCulture, $"{Offset64:X16}"); /// /// Gets the type of the input objects used to create the . diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs index bf4693c1e3e..d44828acd32 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs @@ -32,7 +32,7 @@ internal static StringBuilder GetRawContentHeader(HttpResponseMessage response) { int statusCode = WebResponseHelper.GetStatusCode(response); string statusDescription = WebResponseHelper.GetStatusDescription(response); - raw.AppendFormat("{0} {1} {2}", protocol, statusCode, statusDescription); + raw.Append($"{protocol} {statusCode} {statusDescription}"); raw.AppendLine(); } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs index d128800af64..242f380d94e 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs @@ -116,7 +116,7 @@ internal override void ProcessResponse(HttpResponseMessage response) } // NOTE: Tests use this verbose output to verify the encoding. - WriteVerbose(string.Format(System.Globalization.CultureInfo.InvariantCulture, $"Content encoding: {encodingVerboseName}")); + WriteVerbose(string.Create(System.Globalization.CultureInfo.InvariantCulture, $"Content encoding: {encodingVerboseName}")); bool convertSuccess = false; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index 73eb34013a5..beb9ad93e7e 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -744,7 +744,7 @@ private static string FormatDictionary(IDictionary content) encodedValue = WebUtility.UrlEncode(value.ToString()); } - bodyBuilder.AppendFormat("{0}={1}", encodedKey, encodedValue); + bodyBuilder.Append($"{encodedKey}={encodedValue}"); } return bodyBuilder.ToString(); @@ -768,14 +768,14 @@ private ErrorRecord GetValidationError(string msg, string errorId, params object private string GetBasicAuthorizationHeader() { var password = new NetworkCredential(null, Credential.Password).Password; - string unencoded = string.Format($"{Credential.UserName}:{password}"); + string unencoded = string.Create(CultureInfo.InvariantCulture, $"{Credential.UserName}:{password}"); byte[] bytes = Encoding.UTF8.GetBytes(unencoded); - return string.Format($"Basic {Convert.ToBase64String(bytes)}"); + return string.Create(CultureInfo.InvariantCulture, $"Basic {Convert.ToBase64String(bytes)}"); } private string GetBearerAuthorizationHeader() { - return string.Format($"Bearer {new NetworkCredential(string.Empty, Token).Password}"); + return string.Create(CultureInfo.InvariantCulture, $"Bearer {new NetworkCredential(string.Empty, Token).Password}"); } private void ProcessAuthentication() @@ -790,7 +790,7 @@ private void ProcessAuthentication() } else { - Diagnostics.Assert(false, string.Format($"Unrecognized Authentication value: {Authentication}")); + Diagnostics.Assert(false, string.Create(CultureInfo.InvariantCulture, $"Unrecognized Authentication value: {Authentication}")); } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseHelper.CoreClr.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseHelper.CoreClr.cs index 43dee2fa029..9de4311e430 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseHelper.CoreClr.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseHelper.CoreClr.cs @@ -34,7 +34,7 @@ internal static Dictionary> GetHeadersDictionary(Htt return headers; } - internal static string GetProtocol(HttpResponseMessage response) => string.Format(CultureInfo.InvariantCulture, $"HTTP/{response.Version}"); + internal static string GetProtocol(HttpResponseMessage response) => string.Create(CultureInfo.InvariantCulture, $"HTTP/{response.Version}"); internal static int GetStatusCode(HttpResponseMessage response) => (int)response.StatusCode; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/PSUserAgent.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/PSUserAgent.cs index 9ccd7e624ce..e4312e74975 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/PSUserAgent.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/PSUserAgent.cs @@ -17,36 +17,36 @@ public static class PSUserAgent private static string s_windowsUserAgent; // Format the user-agent string from the various component parts - internal static string UserAgent => string.Format(CultureInfo.InvariantCulture, $"{Compatibility} ({PlatformName}; {OS}; {Culture}) {App}"); + internal static string UserAgent => string.Create(CultureInfo.InvariantCulture, $"{Compatibility} ({PlatformName}; {OS}; {Culture}) {App}"); /// /// Useragent string for InternetExplorer (9.0). /// - public static string InternetExplorer => string.Format(CultureInfo.InvariantCulture, $"{Compatibility} (compatible; MSIE 9.0; {PlatformName}; {OS}; {Culture})"); + public static string InternetExplorer => string.Create(CultureInfo.InvariantCulture, $"{Compatibility} (compatible; MSIE 9.0; {PlatformName}; {OS}; {Culture})"); /// /// Useragent string for Firefox (4.0). /// - public static string FireFox => string.Format(CultureInfo.InvariantCulture, $"{Compatibility} ({PlatformName}; {OS}; {Culture}) Gecko/20100401 Firefox/4.0"); + public static string FireFox => string.Create(CultureInfo.InvariantCulture, $"{Compatibility} ({PlatformName}; {OS}; {Culture}) Gecko/20100401 Firefox/4.0"); /// /// Useragent string for Chrome (7.0). /// - public static string Chrome => string.Format(CultureInfo.InvariantCulture, $"{Compatibility} ({PlatformName}; {OS}; {Culture}) AppleWebKit/534.6 (KHTML, like Gecko) Chrome/7.0.500.0 Safari/534.6"); + public static string Chrome => string.Create(CultureInfo.InvariantCulture, $"{Compatibility} ({PlatformName}; {OS}; {Culture}) AppleWebKit/534.6 (KHTML, like Gecko) Chrome/7.0.500.0 Safari/534.6"); /// /// Useragent string for Opera (9.0). /// - public static string Opera => string.Format(CultureInfo.InvariantCulture, $"Opera/9.70 ({PlatformName}; {OS}; {Culture}) Presto/2.2.1"); + public static string Opera => string.Create(CultureInfo.InvariantCulture, $"Opera/9.70 ({PlatformName}; {OS}; {Culture}) Presto/2.2.1"); /// /// Useragent string for Safari (5.0). /// - public static string Safari => string.Format(CultureInfo.InvariantCulture, $"{Compatibility} ({PlatformName}; {OS}; {Culture}) AppleWebKit/533.16 (KHTML, like Gecko) Version/5.0 Safari/533.16"); + public static string Safari => string.Create(CultureInfo.InvariantCulture, $"{Compatibility} ({PlatformName}; {OS}; {Culture}) AppleWebKit/533.16 (KHTML, like Gecko) Version/5.0 Safari/533.16"); internal static string Compatibility => "Mozilla/5.0"; - internal static string App => string.Format(CultureInfo.InvariantCulture, $"PowerShell/{PSVersionInfo.PSVersion}"); + internal static string App => string.Create(CultureInfo.InvariantCulture, $"PowerShell/{PSVersionInfo.PSVersion}"); internal static string PlatformName { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs index f39242e1010..8873676c61d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs @@ -439,7 +439,7 @@ protected override void BeginProcessing() } else { - WriteObject(string.Format(CultureInfo.InvariantCulture, "", Encoding.UTF8.WebName)); + WriteObject(string.Create(CultureInfo.InvariantCulture, $"")); WriteObject(""); } } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs index e5197d77ae9..43eb27b86e6 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs @@ -109,7 +109,7 @@ internal struct COORD public override string ToString() { - return string.Format(CultureInfo.InvariantCulture, "{0},{1}", X, Y); + return string.Create(CultureInfo.InvariantCulture, $"{X},{Y}"); } } @@ -161,7 +161,7 @@ internal struct SMALL_RECT public override string ToString() { - return string.Format(CultureInfo.InvariantCulture, "{0},{1},{2},{3}", Left, Top, Right, Bottom); + return string.Create(CultureInfo.InvariantCulture, $"{Left},{Top},{Right},{Bottom}"); } } @@ -192,7 +192,7 @@ internal struct CONSOLE_CURSOR_INFO public override string ToString() { - return string.Format(CultureInfo.InvariantCulture, "Size: {0}, Visible: {1}", Size, Visible); + return string.Create(CultureInfo.InvariantCulture, $"Size: {Size}, Visible: {Visible}"); } } @@ -1249,8 +1249,7 @@ internal static void CheckWriteEdges( { if (firstLeftTrailingRow >= 0) { - throw PSTraceSource.NewArgumentException(string.Format(CultureInfo.InvariantCulture, "contents[{0}, {1}]", - firstLeftTrailingRow, contentsRegion.Left)); + throw PSTraceSource.NewArgumentException(string.Create(CultureInfo.InvariantCulture, $"contents[{firstLeftTrailingRow}, {contentsRegion.Left}]")); } } else @@ -1265,8 +1264,7 @@ internal static void CheckWriteEdges( if (leftExisting[r, 0].BufferCellType == BufferCellType.Leading ^ contents[r, contentsRegion.Left].BufferCellType == BufferCellType.Trailing) { - throw PSTraceSource.NewArgumentException(string.Format(CultureInfo.InvariantCulture, "contents[{0}, {1}]", - r, contentsRegion.Left)); + throw PSTraceSource.NewArgumentException(string.Create(CultureInfo.InvariantCulture, $"contents[{r}, {contentsRegion.Left}]")); } } } @@ -1275,8 +1273,7 @@ internal static void CheckWriteEdges( { if (firstRightLeadingRow >= 0) { - throw PSTraceSource.NewArgumentException(string.Format(CultureInfo.InvariantCulture, "contents[{0}, {1}]", - firstRightLeadingRow, contentsRegion.Right)); + throw PSTraceSource.NewArgumentException(string.Create(CultureInfo.InvariantCulture, $"contents[{firstRightLeadingRow}, {contentsRegion.Right}]")); } } else @@ -1291,8 +1288,7 @@ internal static void CheckWriteEdges( if (rightExisting[r, 0].BufferCellType == BufferCellType.Leading ^ contents[r, contentsRegion.Right].BufferCellType == BufferCellType.Leading) { - throw PSTraceSource.NewArgumentException(string.Format(CultureInfo.InvariantCulture, "contents[{0}, {1}]", - r, contentsRegion.Right)); + throw PSTraceSource.NewArgumentException(string.Create(CultureInfo.InvariantCulture, $"contents[{r}, {contentsRegion.Right}]")); } } } @@ -1312,7 +1308,7 @@ private static void CheckWriteConsoleOutputContents(BufferCell[,] contents, Rect contents[r, c].Character != 0) { // trailing character is not 0 - throw PSTraceSource.NewArgumentException(string.Format(CultureInfo.InvariantCulture, "contents[{0}, {1}]", r, c)); + throw PSTraceSource.NewArgumentException(string.Create(CultureInfo.InvariantCulture, $"contents[{r}, {c}]")); } if (contents[r, c].BufferCellType == BufferCellType.Leading) @@ -1327,7 +1323,7 @@ private static void CheckWriteConsoleOutputContents(BufferCell[,] contents, Rect { // for a 2 cell character, either there is no trailing BufferCell or // the trailing BufferCell's character is not 0 - throw PSTraceSource.NewArgumentException(string.Format(CultureInfo.InvariantCulture, "contents[{0}, {1}]", r, c)); + throw PSTraceSource.NewArgumentException(string.Create(CultureInfo.InvariantCulture, $"contents[{r}, {c}]")); } } } @@ -1522,7 +1518,7 @@ private static void WriteConsoleOutputCJK(ConsoleHandle consoleHandle, Coordinat // to write is larger than bufferLimit. In that case, the algorithm writes one row // at a time => bufferSize.Y == 1. Then, we can safely leave bufferSize.Y unchanged // to retry with a smaller bufferSize.X. - Dbg.Assert(bufferSize.Y == 1, string.Format(CultureInfo.InvariantCulture, "bufferSize.Y should be 1, but is {0}", bufferSize.Y)); + Dbg.Assert(bufferSize.Y == 1, string.Create(CultureInfo.InvariantCulture, $"bufferSize.Y should be 1, but is {bufferSize.Y}")); bufferSize.X = (short)Math.Min(colsRemaining, bufferLimit); continue; } @@ -1650,7 +1646,7 @@ private static void WriteConsoleOutputPlain(ConsoleHandle consoleHandle, Coordin // to write is larger than bufferLimit. In that case, the algorithm writes one row // at a time => bufferSize.Y == 1. Then, we can safely leave bufferSize.Y unchanged // to retry with a smaller bufferSize.X. - Dbg.Assert(bufferSize.Y == 1, string.Format(CultureInfo.InvariantCulture, "bufferSize.Y should be 1, but is {0}", bufferSize.Y)); + Dbg.Assert(bufferSize.Y == 1, string.Create(CultureInfo.InvariantCulture, $"bufferSize.Y should be 1, but is {bufferSize.Y}")); bufferSize.X = (short)Math.Min(colsRemaining, bufferLimit); continue; } @@ -1975,7 +1971,7 @@ internal static void ReadConsoleOutputCJK // to write is larger than bufferLimit. In that case, the algorithm reads one row // at a time => bufferSize.Y == 1. Then, we can safely leave bufferSize.Y unchanged // to retry with a smaller bufferSize.X. - Dbg.Assert(bufferSize.Y == 1, string.Format(CultureInfo.InvariantCulture, "bufferSize.Y should be 1, but is {0}", bufferSize.Y)); + Dbg.Assert(bufferSize.Y == 1, string.Create(CultureInfo.InvariantCulture, $"bufferSize.Y should be 1, but is {bufferSize.Y}")); bufferSize.X = (short)Math.Min(colsRemaining, bufferLimit); continue; } @@ -2145,7 +2141,7 @@ private static void ReadConsoleOutputPlain // to write is larger than bufferLimit. In that case, the algorithm reads one row // at a time => bufferSize.Y == 1. Then, we can safely leave bufferSize.Y unchanged // to retry with a smaller bufferSize.X. - Dbg.Assert(bufferSize.Y == 1, string.Format(CultureInfo.InvariantCulture, "bufferSize.Y should be 1, but is {0}", bufferSize.Y)); + Dbg.Assert(bufferSize.Y == 1, string.Create(CultureInfo.InvariantCulture, $"bufferSize.Y should be 1, but is {bufferSize.Y}")); bufferSize.X = (short)Math.Min(colsRemaining, bufferLimit); continue; } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs index f5937d21e0f..a0d654759b7 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs @@ -639,8 +639,7 @@ public override { int actualNumberOfInput = ConsoleControl.ReadConsoleInput(handle, ref inputRecords); Dbg.Assert(actualNumberOfInput == 1, - string.Format(CultureInfo.InvariantCulture, "ReadConsoleInput returns {0} number of input event records", - actualNumberOfInput)); + string.Create(CultureInfo.InvariantCulture, $"ReadConsoleInput returns {actualNumberOfInput} number of input event records")); if (actualNumberOfInput == 1) { if (((ConsoleControl.InputRecordEventTypes)inputRecords[0].EventType) == @@ -1532,7 +1531,7 @@ internal struct COORD public override string ToString() { - return string.Format(CultureInfo.InvariantCulture, "{0},{1}", X, Y); + return string.Create(CultureInfo.InvariantCulture, $"{X},{Y}"); } } @@ -1548,7 +1547,7 @@ internal struct SMALL_RECT public override string ToString() { - return string.Format(CultureInfo.InvariantCulture, "{0},{1},{2},{3}", Left, Top, Right, Bottom); + return string.Create(CultureInfo.InvariantCulture, $"{Left},{Top},{Right},{Bottom}"); } } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs index 58cd171cd2f..7b81bb8a97a 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs @@ -140,7 +140,7 @@ public override { throw PSTraceSource.NewArgumentException(nameof(descriptions), ConsoleHostUserInterfaceStrings.NullErrorTemplate, - string.Format(CultureInfo.InvariantCulture, "descriptions[{0}]", descIndex)); + string.Create(CultureInfo.InvariantCulture, $"descriptions[{descIndex}]")); } PSObject inputPSObject = null; @@ -152,7 +152,7 @@ public override if (string.IsNullOrEmpty(desc.ParameterAssemblyFullName)) { string paramName = - string.Format(CultureInfo.InvariantCulture, "descriptions[{0}].AssemblyFullName", descIndex); + string.Create(CultureInfo.InvariantCulture, $"descriptions[{descIndex}].AssemblyFullName"); throw PSTraceSource.NewArgumentException(paramName, ConsoleHostUserInterfaceStrings.NullOrEmptyErrorTemplate, paramName); } @@ -493,7 +493,7 @@ private PromptCommonInputErrors PromptTryConvertTo(Type fieldType, bool isFromRe private string PromptCommandMode(string input, FieldDescription desc, out bool inputDone) { Dbg.Assert(input != null && input.StartsWith(PromptCommandPrefix, StringComparison.OrdinalIgnoreCase), - string.Format(CultureInfo.InvariantCulture, "input should start with {0}", PromptCommandPrefix)); + string.Create(CultureInfo.InvariantCulture, $"input should start with {PromptCommandPrefix}")); Dbg.Assert(desc != null, "desc should never be null when PromptCommandMode is called"); string command = input.Substring(1); diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePromptForChoice.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePromptForChoice.cs index fa470b245a2..7e3dcfd70e0 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePromptForChoice.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePromptForChoice.cs @@ -426,7 +426,7 @@ private void ShowChoiceHelp(Collection choices, string[,] hot WriteLineToConsole( WrapToCurrentWindowWidth( - string.Format(CultureInfo.InvariantCulture, "{0} - {1}", s, choices[i].HelpMessage))); + string.Create(CultureInfo.InvariantCulture, $"{s} - {choices[i].HelpMessage}"))); } } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/UpdatesNotification.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/UpdatesNotification.cs index 455efe84d11..28cd31473dd 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/UpdatesNotification.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/UpdatesNotification.cs @@ -353,7 +353,7 @@ private static async Task QueryNewReleaseAsync(SemanticVersion baseline using var client = new HttpClient(); - string userAgent = string.Format(CultureInfo.InvariantCulture, "PowerShell {0}", PSVersionInfo.GitCommitId); + string userAgent = string.Create(CultureInfo.InvariantCulture, $"PowerShell {PSVersionInfo.GitCommitId}"); client.DefaultRequestHeaders.Add("User-Agent", userAgent); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); From 9cab34b7a70e0bf3ef042d5587d4940c079a0a65 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Sat, 21 Jan 2023 13:49:12 +0100 Subject: [PATCH 309/779] Use interpolated strings 5c (#18997) --- .../engine/Modules/AnalysisCache.cs | 4 ++-- .../engine/Modules/ImportModuleCommand.cs | 2 +- .../engine/Modules/ModuleCmdletBase.cs | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/System.Management.Automation/engine/Modules/AnalysisCache.cs b/src/System.Management.Automation/engine/Modules/AnalysisCache.cs index bb2cf74495e..a701b0745c8 100644 --- a/src/System.Management.Automation/engine/Modules/AnalysisCache.cs +++ b/src/System.Management.Automation/engine/Modules/AnalysisCache.cs @@ -1092,7 +1092,7 @@ static AnalysisCacheData() // When multiple copies of pwsh are on the system, they should use their own copy of the cache. // Append hash of `$PSHOME` to cacheFileName. string hashString = CRC32Hash.ComputeHash(Utils.DefaultPowerShellAppBase); - cacheFileName = string.Format(CultureInfo.InvariantCulture, "{0}-{1}", cacheFileName, hashString); + cacheFileName = string.Create(CultureInfo.InvariantCulture, $"{cacheFileName}-{hashString}"); if (ExperimentalFeature.EnabledExperimentalFeatureNames.Count > 0) { @@ -1118,7 +1118,7 @@ static AnalysisCacheData() // Use CRC32 because it's faster. // It's very unlikely to get collision from hashing the combinations of enabled features names. hashString = CRC32Hash.ComputeHash(allNames); - cacheFileName = string.Format(CultureInfo.InvariantCulture, "{0}-{1}", cacheFileName, hashString); + cacheFileName = string.Create(CultureInfo.InvariantCulture, $"{cacheFileName}-{hashString}"); } s_cacheStoreLocation = Path.Combine(Platform.CacheDirectory, cacheFileName); diff --git a/src/System.Management.Automation/engine/Modules/ImportModuleCommand.cs b/src/System.Management.Automation/engine/Modules/ImportModuleCommand.cs index 48836d6cc96..dbbbf7286ae 100644 --- a/src/System.Management.Automation/engine/Modules/ImportModuleCommand.cs +++ b/src/System.Management.Automation/engine/Modules/ImportModuleCommand.cs @@ -995,7 +995,7 @@ private IList ImportModule_RemotelyViaPsrpSession( string errorMessageTemplate = string.Format( CultureInfo.InvariantCulture, Modules.RemoteDiscoveryRemotePsrpCommandFailed, - string.Format(CultureInfo.InvariantCulture, "Import-Module -Name '{0}'", moduleName)); + string.Create(CultureInfo.InvariantCulture, $"Import-Module -Name '{moduleName}'")); remotelyImportedModules = RemoteDiscoveryHelper.InvokePowerShell( powerShell, this, diff --git a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs index 7c81939fe02..275b87902b7 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs @@ -4939,7 +4939,7 @@ internal static void SyncCurrentLocationHandler(object sender, LocationChangedEv using var ps = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace); ps.AddCommand(new CmdletInfo("Invoke-Command", typeof(InvokeCommandCommand))); ps.AddParameter("Session", compatSession); - ps.AddParameter("ScriptBlock", ScriptBlock.Create(string.Format("Set-Location -Path '{0}'", args.NewPath.Path))); + ps.AddParameter("ScriptBlock", ScriptBlock.Create(string.Create(CultureInfo.InvariantCulture, $"Set-Location -Path '{args.NewPath.Path}'"))); ps.Invoke(); } } From 0ee317a1573a7ea7caa96536944fcee0dcd057c6 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Sat, 21 Jan 2023 13:56:57 +0100 Subject: [PATCH 310/779] Use interpolated strings 3 (#18979) --- .../help/DefaultCommandHelpObjectBuilder.cs | 36 +++++++++---------- .../help/HelpCommands.cs | 4 +-- .../namespaces/FileSystemProvider.cs | 2 +- .../namespaces/LocationGlobber.cs | 4 +-- .../namespaces/RegistryProvider.cs | 4 +-- .../security/wldpNativeMethods.cs | 2 +- .../singleshell/config/MshSnapinInfo.cs | 7 ++-- .../utils/perfCounters/PSPerfCountersMgr.cs | 2 +- .../utils/tracing/PSEtwLog.cs | 2 +- .../utils/tracing/SysLogProvider.cs | 2 +- test/Test.Common.props | 2 +- test/perf/benchmarks/Engine.Compiler.cs | 2 +- .../CommandLineOptions.cs | 4 +-- 13 files changed, 36 insertions(+), 37 deletions(-) diff --git a/src/System.Management.Automation/help/DefaultCommandHelpObjectBuilder.cs b/src/System.Management.Automation/help/DefaultCommandHelpObjectBuilder.cs index 34b1bd84cef..d553f242c16 100644 --- a/src/System.Management.Automation/help/DefaultCommandHelpObjectBuilder.cs +++ b/src/System.Management.Automation/help/DefaultCommandHelpObjectBuilder.cs @@ -57,8 +57,8 @@ internal static PSObject GetPSObjectFromCmdletInfo(CommandInfo input) PSObject obj = new PSObject(); obj.TypeNames.Clear(); - obj.TypeNames.Add(string.Format(CultureInfo.InvariantCulture, "{0}#{1}#command", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp, commandInfo.ModuleName)); - obj.TypeNames.Add(string.Format(CultureInfo.InvariantCulture, "{0}#{1}", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp, commandInfo.ModuleName)); + obj.TypeNames.Add(string.Create(CultureInfo.InvariantCulture, $"{DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp}#{commandInfo.ModuleName}#command")); + obj.TypeNames.Add(string.Create(CultureInfo.InvariantCulture, $"{DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp}#{commandInfo.ModuleName}")); obj.TypeNames.Add(DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp); obj.TypeNames.Add("CmdletHelpInfo"); obj.TypeNames.Add("HelpInfo"); @@ -160,7 +160,7 @@ internal static void AddDetailsProperties(PSObject obj, string name, string noun PSObject mshObject = new PSObject(); mshObject.TypeNames.Clear(); - mshObject.TypeNames.Add(string.Format(CultureInfo.InvariantCulture, "{0}#details", typeNameForHelp)); + mshObject.TypeNames.Add(string.Create(CultureInfo.InvariantCulture, $"{typeNameForHelp}#details")); mshObject.Properties.Add(new PSNoteProperty("name", name)); mshObject.Properties.Add(new PSNoteProperty("noun", noun)); @@ -192,7 +192,7 @@ internal static void AddSyntaxProperties(PSObject obj, string cmdletName, ReadOn PSObject mshObject = new PSObject(); mshObject.TypeNames.Clear(); - mshObject.TypeNames.Add(string.Format(CultureInfo.InvariantCulture, "{0}#syntax", typeNameForHelp)); + mshObject.TypeNames.Add(string.Create(CultureInfo.InvariantCulture, $"{typeNameForHelp}#syntax")); AddSyntaxItemProperties(mshObject, cmdletName, parameterSets, common, typeNameForHelp); @@ -216,7 +216,7 @@ private static void AddSyntaxItemProperties(PSObject obj, string cmdletName, Rea PSObject mshObject = new PSObject(); mshObject.TypeNames.Clear(); - mshObject.TypeNames.Add(string.Format(CultureInfo.InvariantCulture, "{0}#syntaxItem", typeNameForHelp)); + mshObject.TypeNames.Add(string.Create(CultureInfo.InvariantCulture, $"{typeNameForHelp}#syntaxItem")); mshObject.Properties.Add(new PSNoteProperty("name", cmdletName)); mshObject.Properties.Add(new PSNoteProperty("CommonParameters", common)); @@ -263,7 +263,7 @@ private static void AddSyntaxParametersProperties(PSObject obj, IEnumerable attributes = new Collection(parameter.Attributes); @@ -339,7 +339,7 @@ private static void AddParameterValueGroupProperties(PSObject obj, string[] valu PSObject paramValueGroup = new PSObject(); paramValueGroup.TypeNames.Clear(); - paramValueGroup.TypeNames.Add(string.Format(CultureInfo.InvariantCulture, "{0}#parameterValueGroup", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp)); + paramValueGroup.TypeNames.Add(string.Create(CultureInfo.InvariantCulture, $"{DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp}#parameterValueGroup")); ArrayList paramValue = new ArrayList(values); @@ -359,7 +359,7 @@ internal static void AddParametersProperties(PSObject obj, Dictionary(c) Microsoft Corporation. net7.0 - 9.0 + 11.0 true true diff --git a/test/perf/benchmarks/Engine.Compiler.cs b/test/perf/benchmarks/Engine.Compiler.cs index 10e0054a01c..5869bc9ef07 100644 --- a/test/perf/benchmarks/Engine.Compiler.cs +++ b/test/perf/benchmarks/Engine.Compiler.cs @@ -23,7 +23,7 @@ public class Compiler static Compiler() { - string pattern = string.Format("{0}test{0}perf{0}benchmarks", Path.DirectorySeparatorChar); + string pattern = string.Create($"{Path.DirectorySeparatorChar}test{Path.DirectorySeparatorChar}perf{Path.DirectorySeparatorChar}benchmarks"); string location = typeof(Compiler).Assembly.Location; string testFilePath = null; diff --git a/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/CommandLineOptions.cs b/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/CommandLineOptions.cs index 3c8b343fc57..e3c2d2a82a7 100644 --- a/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/CommandLineOptions.cs +++ b/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/CommandLineOptions.cs @@ -23,7 +23,7 @@ public static List ParseAndRemoveIntParameter(List argsList, str } else { - throw new ArgumentException(String.Format("{0} must be followed by an integer", parameter)); + throw new ArgumentException(String.Create($"{parameter} must be followed by an integer")); } } @@ -94,4 +94,4 @@ public static void ValidatePartitionParameters(int? count, int? index) } } } -} \ No newline at end of file +} From ebed59772511d13a78b2e9f5546bb1fea6061199 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Sat, 21 Jan 2023 13:59:18 +0100 Subject: [PATCH 311/779] Use interpolated strings 5b (#18996) --- .../engine/debugger/debugger.cs | 4 ++-- .../engine/hostifaces/HostUtilities.cs | 4 ++-- .../engine/hostifaces/InternalHostUserInterface.cs | 3 +-- .../engine/hostifaces/MshHostRawUserInterface.cs | 10 +++++----- .../engine/hostifaces/MshHostUserInterface.cs | 2 +- .../engine/hostifaces/PSTask.cs | 2 +- .../engine/interpreter/BranchLabel.cs | 2 +- .../engine/interpreter/LabelInfo.cs | 4 ++-- .../engine/interpreter/LightCompiler.cs | 10 +++------- .../engine/interpreter/LocalVariables.cs | 2 +- .../engine/interpreter/StackOperations.cs | 2 +- 11 files changed, 20 insertions(+), 25 deletions(-) diff --git a/src/System.Management.Automation/engine/debugger/debugger.cs b/src/System.Management.Automation/engine/debugger/debugger.cs index 149fca2a632..c7b116a4d5f 100644 --- a/src/System.Management.Automation/engine/debugger/debugger.cs +++ b/src/System.Management.Automation/engine/debugger/debugger.cs @@ -5302,9 +5302,9 @@ private void DisplayScript(PSHost host, IList output, InvocationInfo i { WriteLine( lineNumber == invocationInfo.ScriptLineNumber ? - string.Format(CultureInfo.CurrentCulture, "{0,5}:* {1}", lineNumber, _lines[lineNumber - 1]) + string.Create(CultureInfo.CurrentCulture, $"{lineNumber,5}:* { _lines[lineNumber - 1]}") : - string.Format(CultureInfo.CurrentCulture, "{0,5}: {1}", lineNumber, _lines[lineNumber - 1]), + string.Create(CultureInfo.CurrentCulture, $"{lineNumber,5}: { _lines[lineNumber - 1]}"), host, output); diff --git a/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs b/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs index c543ad11f13..63ea2e9dc4b 100644 --- a/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs +++ b/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs @@ -639,10 +639,10 @@ runspace.ConnectionInfo is VMConnectionInfo || !string.IsNullOrEmpty(sshConnectionInfo.UserName) && !System.Environment.UserName.Equals(sshConnectionInfo.UserName, StringComparison.Ordinal)) { - return string.Format(CultureInfo.InvariantCulture, "[{0}@{1}]: {2}", sshConnectionInfo.UserName, sshConnectionInfo.ComputerName, basePrompt); + return string.Create(CultureInfo.InvariantCulture, $"[{sshConnectionInfo.UserName}@{sshConnectionInfo.ComputerName}]: {basePrompt}"); } - return string.Format(CultureInfo.InvariantCulture, "[{0}]: {1}", runspace.ConnectionInfo.ComputerName, basePrompt); + return string.Create(CultureInfo.InvariantCulture, $"[{runspace.ConnectionInfo.ComputerName}]: {basePrompt}"); } /// diff --git a/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs index 48066da71fa..b9c1f5df8bc 100644 --- a/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs @@ -935,8 +935,7 @@ private Collection EmulatePromptForMultipleChoice(string caption, if (defaultChoiceKeys.Count == 1) { - defaultPrompt = StringUtil.Format(InternalHostUserInterfaceStrings.DefaultChoice, - defaultChoicesStr); + defaultPrompt = StringUtil.Format(InternalHostUserInterfaceStrings.DefaultChoice, defaultChoicesStr); } else { diff --git a/src/System.Management.Automation/engine/hostifaces/MshHostRawUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/MshHostRawUserInterface.cs index f0435baec3a..c7e1b2ce849 100644 --- a/src/System.Management.Automation/engine/hostifaces/MshHostRawUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/MshHostRawUserInterface.cs @@ -71,7 +71,7 @@ public override string ToString() { - return string.Format(CultureInfo.InvariantCulture, "{0},{1}", X, Y); + return string.Create(CultureInfo.InvariantCulture, $"{X},{Y}"); } /// @@ -257,7 +257,7 @@ public override string ToString() { - return string.Format(CultureInfo.InvariantCulture, "{0},{1}", Width, Height); + return string.Create(CultureInfo.InvariantCulture, $"{Width},{Height}"); } /// @@ -566,7 +566,7 @@ public override string ToString() { - return string.Format(CultureInfo.InvariantCulture, "{0},{1},{2},{3}", VirtualKeyCode, Character, ControlKeyState, KeyDown); + return string.Create(CultureInfo.InvariantCulture, $"{VirtualKeyCode},{Character},{ControlKeyState},{KeyDown}"); } /// /// Overrides @@ -796,7 +796,7 @@ public override string ToString() { - return string.Format(CultureInfo.InvariantCulture, "{0},{1} ; {2},{3}", Left, Top, Right, Bottom); + return string.Create(CultureInfo.InvariantCulture, $"{Left},{Top} ; {Right},{Bottom}"); } /// @@ -1024,7 +1024,7 @@ public override string ToString() { - return string.Format(CultureInfo.InvariantCulture, "'{0}' {1} {2} {3}", Character, ForegroundColor, BackgroundColor, BufferCellType); + return string.Create(CultureInfo.InvariantCulture, $"'{Character}' {ForegroundColor} {BackgroundColor} {BufferCellType}"); } /// diff --git a/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs index 440252f7611..057439f4731 100644 --- a/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs @@ -1413,7 +1413,7 @@ internal static void BuildHotkeysAndPlainLabels(Collection ch if (string.Equals(hotkeysAndPlainLabels[0, i], "?", StringComparison.Ordinal)) { Exception e = PSTraceSource.NewArgumentException( - string.Format(Globalization.CultureInfo.InvariantCulture, "choices[{0}].Label", i), + string.Create(Globalization.CultureInfo.InvariantCulture, $"choices[{i}].Label"), InternalHostUserInterfaceStrings.InvalidChoiceHotKeyError); throw e; } diff --git a/src/System.Management.Automation/engine/hostifaces/PSTask.cs b/src/System.Management.Automation/engine/hostifaces/PSTask.cs index fb492706ad1..5a1cef70602 100644 --- a/src/System.Management.Automation/engine/hostifaces/PSTask.cs +++ b/src/System.Management.Automation/engine/hostifaces/PSTask.cs @@ -912,7 +912,7 @@ private void CheckForComplete() private Runspace GetRunspace(int taskId) { - var runspaceName = string.Format(CultureInfo.InvariantCulture, "{0}:{1}", PSTask.RunspaceName, taskId); + var runspaceName = string.Create(CultureInfo.InvariantCulture, $"{PSTask.RunspaceName}:{taskId}"); if (_useRunspacePool && _runspacePool.TryDequeue(out Runspace runspace)) { diff --git a/src/System.Management.Automation/engine/interpreter/BranchLabel.cs b/src/System.Management.Automation/engine/interpreter/BranchLabel.cs index 1bae16783a9..d8999084232 100644 --- a/src/System.Management.Automation/engine/interpreter/BranchLabel.cs +++ b/src/System.Management.Automation/engine/interpreter/BranchLabel.cs @@ -34,7 +34,7 @@ public RuntimeLabel(int index, int continuationStackDepth, int stackDepth) public override string ToString() { - return string.Format(CultureInfo.InvariantCulture, "->{0} C({1}) S({2})", Index, ContinuationStackDepth, StackDepth); + return string.Create(CultureInfo.InvariantCulture, $"->{Index} C({ContinuationStackDepth}) S({StackDepth})"); } } diff --git a/src/System.Management.Automation/engine/interpreter/LabelInfo.cs b/src/System.Management.Automation/engine/interpreter/LabelInfo.cs index 80e5ca25157..8d501987c3d 100644 --- a/src/System.Management.Automation/engine/interpreter/LabelInfo.cs +++ b/src/System.Management.Automation/engine/interpreter/LabelInfo.cs @@ -80,7 +80,7 @@ internal void Define(LabelScopeInfo block) { if (j.ContainsTarget(_node)) { - throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Label target already defined: {0}", _node.Name)); + throw new InvalidOperationException(string.Create(CultureInfo.InvariantCulture, $"Label target already defined: {_node.Name}")); } } @@ -132,7 +132,7 @@ private void ValidateJump(LabelScopeInfo reference) if (HasMultipleDefinitions) { - throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Ambiguous jump {0}", _node.Name)); + throw new InvalidOperationException(string.Create(CultureInfo.InvariantCulture, $"Ambiguous jump {_node.Name}")); } // We didn't find an outward jump. Look for a jump across blocks diff --git a/src/System.Management.Automation/engine/interpreter/LightCompiler.cs b/src/System.Management.Automation/engine/interpreter/LightCompiler.cs index e88606fc2fe..1243b1b6e3e 100644 --- a/src/System.Management.Automation/engine/interpreter/LightCompiler.cs +++ b/src/System.Management.Automation/engine/interpreter/LightCompiler.cs @@ -92,11 +92,7 @@ internal bool IsInsideFinallyBlock(int index) public override string ToString() { - return string.Format(CultureInfo.InvariantCulture, "{0} [{1}-{2}] [{3}->{4}]", - (IsFault ? "fault" : "catch(" + ExceptionType.Name + ")"), - StartIndex, EndIndex, - HandlerStartIndex, HandlerEndIndex - ); + return string.Create(CultureInfo.InvariantCulture, $"{(IsFault ? "fault" : "catch(" + ExceptionType.Name + ")")} [{StartIndex}-{EndIndex}] [{HandlerStartIndex}->{HandlerEndIndex}]"); } } @@ -231,11 +227,11 @@ public override string ToString() { if (IsClear) { - return string.Format(CultureInfo.InvariantCulture, "{0}: clear", Index); + return string.Create(CultureInfo.InvariantCulture, $"{Index}: clear"); } else { - return string.Format(CultureInfo.InvariantCulture, "{0}: [{1}-{2}] '{3}'", Index, StartLine, EndLine, FileName); + return string.Create(CultureInfo.InvariantCulture, $"{Index}: [{StartLine}-{EndLine}] '{FileName}'"); } } } diff --git a/src/System.Management.Automation/engine/interpreter/LocalVariables.cs b/src/System.Management.Automation/engine/interpreter/LocalVariables.cs index 0c1f6416741..af916482260 100644 --- a/src/System.Management.Automation/engine/interpreter/LocalVariables.cs +++ b/src/System.Management.Automation/engine/interpreter/LocalVariables.cs @@ -77,7 +77,7 @@ internal Expression LoadFromArray(Expression frameData, Expression closure) public override string ToString() { - return string.Format(CultureInfo.InvariantCulture, "{0}: {1} {2}", Index, IsBoxed ? "boxed" : null, InClosure ? "in closure" : null); + return string.Create(CultureInfo.InvariantCulture, $"{Index}: {(IsBoxed ? "boxed" : null)} {(InClosure ? "in closure" : null)}"); } } diff --git a/src/System.Management.Automation/engine/interpreter/StackOperations.cs b/src/System.Management.Automation/engine/interpreter/StackOperations.cs index 51a5f03348c..74f926a37a3 100644 --- a/src/System.Management.Automation/engine/interpreter/StackOperations.cs +++ b/src/System.Management.Automation/engine/interpreter/StackOperations.cs @@ -60,7 +60,7 @@ public override int Run(InterpretedFrame frame) public override string ToDebugString(int instructionIndex, object cookie, Func labelIndexer, IList objects) { - return string.Format(CultureInfo.InvariantCulture, "LoadCached({0}: {1})", _index, objects[(int)_index]); + return string.Create(CultureInfo.InvariantCulture, $"LoadCached({_index}: {objects[(int)_index]})"); } public override string ToString() From c156c9cadbab132a08293c9c545f9110dbc99f7a Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Sat, 21 Jan 2023 17:27:21 +0100 Subject: [PATCH 312/779] Use interpolated strings 4 (#18980) --- .../engine/parser/Compiler.cs | 2 +- .../engine/parser/DebugViewWriter.cs | 16 ++++++---------- .../engine/parser/PSType.cs | 6 +++--- .../engine/parser/Parser.cs | 2 +- .../engine/parser/Position.cs | 4 +--- .../engine/parser/SymbolResolver.cs | 2 +- .../engine/parser/ast.cs | 4 ++-- .../engine/parser/token.cs | 2 +- .../client/RemoteRunspacePoolInternal.cs | 2 +- .../commands/NewPSSessionConfigurationFile.cs | 8 +++----- .../remoting/common/RunspaceConnectionInfo.cs | 12 ++++++------ .../remoting/fanin/BaseTransportManager.cs | 5 +---- .../remoting/fanin/WSManTransportManager.cs | 10 ++-------- .../engine/runtime/Binding/Binders.cs | 16 +++++++--------- .../engine/runtime/MutableTuple.cs | 6 +++--- .../engine/runtime/Operations/MiscOps.cs | 8 ++------ .../engine/runtime/ScriptBlockToPowerShell.cs | 2 +- 17 files changed, 42 insertions(+), 65 deletions(-) diff --git a/src/System.Management.Automation/engine/parser/Compiler.cs b/src/System.Management.Automation/engine/parser/Compiler.cs index 676ed06fcd0..cfe4c60dea7 100644 --- a/src/System.Management.Automation/engine/parser/Compiler.cs +++ b/src/System.Management.Automation/engine/parser/Compiler.cs @@ -1149,7 +1149,7 @@ private Expression UpdatePosition(Ast ast) internal ParameterExpression NewTemp(Type type, string name) { - return Expression.Variable(type, string.Format(CultureInfo.InvariantCulture, "{0}{1}", name, _tempCounter++)); + return Expression.Variable(type, string.Create(CultureInfo.InvariantCulture, $"{name}{_tempCounter++}")); } internal static Type GetTypeConstraintForMethodResolution(ExpressionAst expr) diff --git a/src/System.Management.Automation/engine/parser/DebugViewWriter.cs b/src/System.Management.Automation/engine/parser/DebugViewWriter.cs index 69e8aae634b..cb280bdaf61 100644 --- a/src/System.Management.Automation/engine/parser/DebugViewWriter.cs +++ b/src/System.Management.Automation/engine/parser/DebugViewWriter.cs @@ -985,7 +985,7 @@ protected override Expression VisitBlock(BlockExpression node) { // Display if the type of the BlockExpression is different from the // last expression's type in the block. if (node.Type != node.Expressions[node.Expressions.Count - 1].Type) { - Out(string.Format(CultureInfo.CurrentCulture, "<{0}>", node.Type.ToString())); + Out(string.Create(CultureInfo.CurrentCulture, $"<{node.Type}>")); } VisitDeclarations(node.Variables); @@ -1124,7 +1124,7 @@ protected override Expression VisitIndex(IndexExpression node) { } protected override Expression VisitExtension(Expression node) { - Out(string.Format(CultureInfo.CurrentCulture, ".Extension<{0}>", node.GetType().ToString())); + Out(string.Create(CultureInfo.CurrentCulture, $".Extension<{node.GetType()}>")); if (node.CanReduce) { Out(Flow.Space, "{", Flow.NewLine); @@ -1151,13 +1151,13 @@ protected override Expression VisitDebugInfo(DebugInfoExpression node) { } private void DumpLabel(LabelTarget target) { - Out(string.Format(CultureInfo.CurrentCulture, ".LabelTarget {0}:", GetLabelTargetName(target))); + Out(string.Create(CultureInfo.CurrentCulture, $".LabelTarget {GetLabelTargetName(target)}:")); } private string GetLabelTargetName(LabelTarget target) { if (string.IsNullOrEmpty(target.Name)) { // Create the label target name as #Label1, #Label2, etc. - return string.Format(CultureInfo.CurrentCulture, "#Label{0}", GetLabelTargetId(target)); + return string.Create(CultureInfo.CurrentCulture, $"#Label{GetLabelTargetId(target)}"); } else { return GetDisplayName(target.Name); } @@ -1165,11 +1165,7 @@ private string GetLabelTargetName(LabelTarget target) { private void WriteLambda(LambdaExpression lambda) { Out( - string.Format( - CultureInfo.CurrentCulture, - ".Lambda {0}<{1}>", - GetLambdaName(lambda), - lambda.Type.ToString()) + string.Create(CultureInfo.CurrentCulture, $".Lambda {GetLambdaName(lambda)}<{lambda.Type}>") ); VisitDeclarations(lambda.Parameters); @@ -1205,7 +1201,7 @@ private static bool ContainsWhiteSpace(string name) { } private static string QuoteName(string name) { - return string.Format(CultureInfo.CurrentCulture, "'{0}'", name); + return string.Create(CultureInfo.CurrentCulture, $"'{name}'"); } private static string GetDisplayName(string name) { diff --git a/src/System.Management.Automation/engine/parser/PSType.cs b/src/System.Management.Automation/engine/parser/PSType.cs index f7dcdfb4265..d01a22c305d 100644 --- a/src/System.Management.Automation/engine/parser/PSType.cs +++ b/src/System.Management.Automation/engine/parser/PSType.cs @@ -296,7 +296,7 @@ public DefineTypeHelper(Parser parser, ModuleBuilder module, TypeDefinitionAst t var baseClass = this.GetBaseTypes(parser, typeDefinitionAst, out interfaces); _typeBuilder = module.DefineType(typeName, Reflection.TypeAttributes.Class | Reflection.TypeAttributes.Public, baseClass, interfaces.ToArray()); - _staticHelpersTypeBuilder = module.DefineType(string.Format(CultureInfo.InvariantCulture, "{0}_", typeName), Reflection.TypeAttributes.Class); + _staticHelpersTypeBuilder = module.DefineType(string.Create(CultureInfo.InvariantCulture, $"{typeName}_"), Reflection.TypeAttributes.Class); DefineCustomAttributes(_typeBuilder, typeDefinitionAst.Attributes, _parser, AttributeTargets.Class); _typeDefinitionAst.Type = _typeBuilder; @@ -629,7 +629,7 @@ private PropertyBuilder EmitPropertyIl(PropertyMemberAst propertyMemberAst, Type getSetAttributes |= Reflection.MethodAttributes.Static; } // C# naming convention for backing fields. - string backingFieldName = string.Format(CultureInfo.InvariantCulture, "<{0}>k__BackingField", propertyMemberAst.Name); + string backingFieldName = string.Create(CultureInfo.InvariantCulture, $"<{propertyMemberAst.Name}>k__BackingField"); var backingField = _typeBuilder.DefineField(backingFieldName, type, backingFieldAttributes); bool hasValidateAttributes = false; @@ -937,7 +937,7 @@ private void DefineMethodBody( Type returnType, Action parameterNameSetter) { - var wrapperFieldName = string.Format(CultureInfo.InvariantCulture, "<{0}>", metadataToken); + var wrapperFieldName = string.Create(CultureInfo.InvariantCulture, $"<{metadataToken}>"); var scriptBlockWrapperField = _staticHelpersTypeBuilder.DefineField(wrapperFieldName, typeof(ScriptBlockMemberMethodWrapper), FieldAttributes.Assembly | FieldAttributes.Static); diff --git a/src/System.Management.Automation/engine/parser/Parser.cs b/src/System.Management.Automation/engine/parser/Parser.cs index c0bdd25740a..b8afb42472b 100644 --- a/src/System.Management.Automation/engine/parser/Parser.cs +++ b/src/System.Management.Automation/engine/parser/Parser.cs @@ -8044,7 +8044,7 @@ private static void AssertErrorIdCorrespondsToMsgString(string errorId, string e } } - Diagnostics.Assert(msgCorrespondsToString, string.Format("Parser error ID \"{0}\" must correspond to the error message \"{1}\"", errorId, errorMsg)); + Diagnostics.Assert(msgCorrespondsToString, string.Create(CultureInfo.InvariantCulture, $"Parser error ID \"{errorId}\" must correspond to the error message \"{errorMsg}\"")); } private static object[] arrayOfOneArg diff --git a/src/System.Management.Automation/engine/parser/Position.cs b/src/System.Management.Automation/engine/parser/Position.cs index 3c4281e5446..bc2aab73d9d 100644 --- a/src/System.Management.Automation/engine/parser/Position.cs +++ b/src/System.Management.Automation/engine/parser/Position.cs @@ -766,9 +766,7 @@ public string Text _endPosition.ColumnNumber - _startPosition.ColumnNumber); } - return string.Format(CultureInfo.InvariantCulture, "{0}...{1}", - _startPosition.Line.Substring(_startPosition.ColumnNumber), - _endPosition.Line.Substring(0, _endPosition.ColumnNumber)); + return string.Create(CultureInfo.InvariantCulture, $"{_startPosition.Line.AsSpan(_startPosition.ColumnNumber)}...{ _endPosition.Line.AsSpan(0, _endPosition.ColumnNumber)}"); } else { diff --git a/src/System.Management.Automation/engine/parser/SymbolResolver.cs b/src/System.Management.Automation/engine/parser/SymbolResolver.cs index 18f694bf727..097bcabac3b 100644 --- a/src/System.Management.Automation/engine/parser/SymbolResolver.cs +++ b/src/System.Management.Automation/engine/parser/SymbolResolver.cs @@ -404,7 +404,7 @@ public override AstVisitAction VisitAssignmentStatement(AssignmentStatementAst a var typeAst = _symbolTable.GetCurrentTypeDefinitionAst(); Diagnostics.Assert(typeAst != null, "Method scopes can exist only inside type definitions."); - string typeString = string.Format(CultureInfo.InvariantCulture, "[{0}]::", typeAst.Name); + string typeString = string.Create(CultureInfo.InvariantCulture, $"[{typeAst.Name}]::"); _parser.ReportError(variableExpressionAst.Extent, nameof(ParserStrings.MissingTypeInStaticPropertyAssignment), ParserStrings.MissingTypeInStaticPropertyAssignment, diff --git a/src/System.Management.Automation/engine/parser/ast.cs b/src/System.Management.Automation/engine/parser/ast.cs index 7a2c27939fb..72906ebb72d 100644 --- a/src/System.Management.Automation/engine/parser/ast.cs +++ b/src/System.Management.Automation/engine/parser/ast.cs @@ -8898,7 +8898,7 @@ internal Type GetGenericType(Type generic) if (!TypeName.FullName.Contains('`')) { var newTypeName = new TypeName(Extent, - string.Format(CultureInfo.InvariantCulture, "{0}`{1}", TypeName.FullName, GenericArguments.Count)); + string.Create(CultureInfo.InvariantCulture, $"{TypeName.FullName}`{GenericArguments.Count}")); generic = newTypeName.GetReflectionType(); } } @@ -8925,7 +8925,7 @@ public Type GetReflectionAttributeType() if (!TypeName.FullName.Contains('`')) { var newTypeName = new TypeName(Extent, - string.Format(CultureInfo.InvariantCulture, "{0}Attribute`{1}", TypeName.FullName, GenericArguments.Count)); + string.Create(CultureInfo.InvariantCulture, $"{TypeName.FullName}Attribute`{GenericArguments.Count}")); generic = newTypeName.GetReflectionType(); } } diff --git a/src/System.Management.Automation/engine/parser/token.cs b/src/System.Management.Automation/engine/parser/token.cs index 73fccd41e9e..85862c01395 100644 --- a/src/System.Management.Automation/engine/parser/token.cs +++ b/src/System.Management.Automation/engine/parser/token.cs @@ -1271,7 +1271,7 @@ public override string ToString() internal virtual string ToDebugString(int indent) { - return string.Format(CultureInfo.InvariantCulture, "{0}{1}: <{2}>", StringUtil.Padding(indent), _kind, Text); + return string.Create(CultureInfo.InvariantCulture, $"{StringUtil.Padding(indent)}{_kind}: <{Text}>"); } } diff --git a/src/System.Management.Automation/engine/remoting/client/RemoteRunspacePoolInternal.cs b/src/System.Management.Automation/engine/remoting/client/RemoteRunspacePoolInternal.cs index dd365106ced..e7a3a41104a 100644 --- a/src/System.Management.Automation/engine/remoting/client/RemoteRunspacePoolInternal.cs +++ b/src/System.Management.Automation/engine/remoting/client/RemoteRunspacePoolInternal.cs @@ -2033,7 +2033,7 @@ internal static Collection GetRemoteCommands(Guid shellId, WSManConnec powerShell.AddCommand("Get-WSManInstance"); // Add parameters to enumerate commands. - string filterStr = string.Format(CultureInfo.InvariantCulture, "ShellId='{0}'", shellId.ToString().ToUpperInvariant()); + string filterStr = string.Create(CultureInfo.InvariantCulture, $"ShellId='{shellId.ToString().ToUpperInvariant()}'"); powerShell.AddParameter("ResourceURI", @"Shell/Command"); powerShell.AddParameter("Enumerate", true); powerShell.AddParameter("Dialect", "Selector"); diff --git a/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationFile.cs b/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationFile.cs index d6b6c261d6d..2699c6cbcbf 100644 --- a/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationFile.cs +++ b/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationFile.cs @@ -1866,12 +1866,10 @@ internal static string ConfigFragment(string key, string resourceString, string if (isExample) { - return string.Format(CultureInfo.InvariantCulture, "# {0}{1}# {2:19} = {3}{4}{5}", - resourceString, nl, key, value, nl, nl); + return string.Format(CultureInfo.InvariantCulture, "# {0}{1}# {2:19} = {3}{4}{5}", resourceString, nl, key, value, nl, nl); } - - return string.Format(CultureInfo.InvariantCulture, "# {0}{1}{2:19} = {3}{4}{5}", - resourceString, nl, key, value, nl, nl); + + return string.Format(CultureInfo.InvariantCulture, "# {0}{1}{2:19} = {3}{4}{5}", resourceString, nl, key, value, nl, nl); } /// diff --git a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs index 571d494c4d7..dac98f99449 100644 --- a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs +++ b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs @@ -2239,7 +2239,7 @@ internal int StartSSHProcess( StringUtil.Format(RemotingErrorIdStrings.KeyFileNotFound, this.KeyFilePath)); } - startInfo.ArgumentList.Add(string.Format(CultureInfo.InvariantCulture, @"-i ""{0}""", this.KeyFilePath)); + startInfo.ArgumentList.Add(string.Create(CultureInfo.InvariantCulture, $@"-i ""{this.KeyFilePath}""")); } // pass "-l login_name" command line argument to ssh if UserName is set @@ -2252,11 +2252,11 @@ internal int StartSSHProcess( // convert DOMAIN\user to user@DOMAIN var domainName = parts[0]; var userName = parts[1]; - startInfo.ArgumentList.Add(string.Format(CultureInfo.InvariantCulture, @"-l {0}@{1}", userName, domainName)); + startInfo.ArgumentList.Add(string.Create(CultureInfo.InvariantCulture, $@"-l {userName}@{domainName}")); } else { - startInfo.ArgumentList.Add(string.Format(CultureInfo.InvariantCulture, @"-l {0}", this.UserName)); + startInfo.ArgumentList.Add(string.Create(CultureInfo.InvariantCulture, $@"-l {this.UserName}")); } } @@ -2264,7 +2264,7 @@ internal int StartSSHProcess( // if Port is not set, then ssh will use Port from ssh_config if defined else 22 by default if (this.Port != 0) { - startInfo.ArgumentList.Add(string.Format(CultureInfo.InvariantCulture, @"-p {0}", this.Port)); + startInfo.ArgumentList.Add(string.Create(CultureInfo.InvariantCulture, $@"-p {this.Port}")); } // pass "-o option=value" command line argument to ssh if options are provided @@ -2272,13 +2272,13 @@ internal int StartSSHProcess( { foreach (DictionaryEntry pair in this.Options) { - startInfo.ArgumentList.Add(string.Format(CultureInfo.InvariantCulture, @"-o {0}={1}", pair.Key, pair.Value)); + startInfo.ArgumentList.Add(string.Create(CultureInfo.InvariantCulture, $@"-o {pair.Key}={pair.Value}")); } } // pass "-s destination command" command line arguments to ssh where command is the subsystem to invoke on the destination // note that ssh expects IPv6 addresses to not be enclosed in square brackets so trim them if present - startInfo.ArgumentList.Add(string.Format(CultureInfo.InvariantCulture, @"-s {0} {1}", this.ComputerName.TrimStart('[').TrimEnd(']'), this.Subsystem)); + startInfo.ArgumentList.Add(string.Create(CultureInfo.InvariantCulture, $@"-s {this.ComputerName.TrimStart('[').TrimEnd(']')} {this.Subsystem}")); startInfo.WorkingDirectory = System.IO.Path.GetDirectoryName(filePath); startInfo.CreateNoWindow = true; diff --git a/src/System.Management.Automation/engine/remoting/fanin/BaseTransportManager.cs b/src/System.Management.Automation/engine/remoting/fanin/BaseTransportManager.cs index 57268568165..af13d2fab46 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/BaseTransportManager.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/BaseTransportManager.cs @@ -364,10 +364,7 @@ internal void ProcessRawData(byte[] data, { // we dont support this stream..so ignore the data Dbg.Assert(false, - string.Format(CultureInfo.InvariantCulture, "Data should be from one of the streams : {0} or {1} or {2}", - WSManNativeApi.WSMAN_STREAM_ID_STDIN, - WSManNativeApi.WSMAN_STREAM_ID_STDOUT, - WSManNativeApi.WSMAN_STREAM_ID_PROMPTRESPONSE)); + string.Create(CultureInfo.InvariantCulture, $"Data should be from one of the streams : {WSManNativeApi.WSMAN_STREAM_ID_STDIN} or {WSManNativeApi.WSMAN_STREAM_ID_STDOUT} or {WSManNativeApi.WSMAN_STREAM_ID_PROMPTRESPONSE}")); s_baseTracer.WriteLine("{0} is not a valid stream", stream); } // process data diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManTransportManager.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManTransportManager.cs index 6c7eb62d181..b8e417da547 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManTransportManager.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManTransportManager.cs @@ -925,10 +925,7 @@ internal override void ConnectAsync() { // WSMan expects the data to be in XML format (which is text + xml tags) // so convert byte[] into base64 encoded format - string base64EncodedDataInXml = string.Format(CultureInfo.InvariantCulture, "<{0} xmlns=\"{1}\">{2}", - WSManNativeApi.PS_CONNECT_XML_TAG, - WSManNativeApi.PS_XML_NAMESPACE, - Convert.ToBase64String(additionalData)); + string base64EncodedDataInXml = string.Create(CultureInfo.InvariantCulture, $"<{WSManNativeApi.PS_CONNECT_XML_TAG} xmlns=\"{WSManNativeApi.PS_XML_NAMESPACE}\">{Convert.ToBase64String(additionalData)}"); _openContent = new WSManNativeApi.WSManData_ManToUn(base64EncodedDataInXml); } @@ -1096,10 +1093,7 @@ public override void CreateAsync() { // WSMan expects the data to be in XML format (which is text + xml tags) // so convert byte[] into base64 encoded format - string base64EncodedDataInXml = string.Format(CultureInfo.InvariantCulture, "<{0} xmlns=\"{1}\">{2}", - WSManNativeApi.PS_CREATION_XML_TAG, - WSManNativeApi.PS_XML_NAMESPACE, - Convert.ToBase64String(additionalData)); + string base64EncodedDataInXml = string.Create(CultureInfo.InvariantCulture, $"<{WSManNativeApi.PS_CREATION_XML_TAG} xmlns=\"{WSManNativeApi.PS_XML_NAMESPACE}\">{Convert.ToBase64String(additionalData)}"); _openContent = new WSManNativeApi.WSManData_ManToUn(base64EncodedDataInXml); } } diff --git a/src/System.Management.Automation/engine/runtime/Binding/Binders.cs b/src/System.Management.Automation/engine/runtime/Binding/Binders.cs index 8912c95590e..13eb426dfdc 100644 --- a/src/System.Management.Automation/engine/runtime/Binding/Binders.cs +++ b/src/System.Management.Automation/engine/runtime/Binding/Binders.cs @@ -955,7 +955,7 @@ private PSArrayAssignmentRHSBinder(int elements) public override string ToString() { - return string.Format(CultureInfo.InvariantCulture, "MultiAssignRHSBinder {0}", _elements); + return string.Create(CultureInfo.InvariantCulture, $"MultiAssignRHSBinder {_elements}"); } public override Type ReturnType { get { return typeof(IList); } } @@ -2239,7 +2239,7 @@ public override DynamicMetaObject FallbackBinaryOperation(DynamicMetaObject targ public override string ToString() { - return string.Format(CultureInfo.InvariantCulture, "PSBinaryOperationBinder {0}{1} ver:{2}", GetOperatorText(), _scalarCompare ? " scalarOnly" : string.Empty, _version); + return string.Create(CultureInfo.InvariantCulture, $"PSBinaryOperationBinder {GetOperatorText()}{(_scalarCompare ? " scalarOnly" : string.Empty)} ver:{_version}"); } internal static void InvalidateCache() @@ -3488,7 +3488,7 @@ public override DynamicMetaObject FallbackUnaryOperation(DynamicMetaObject targe public override string ToString() { - return string.Format(CultureInfo.InvariantCulture, "PSUnaryOperationBinder {0}", this.Operation); + return string.Create(CultureInfo.InvariantCulture, $"PSUnaryOperationBinder {this.Operation}"); } internal DynamicMetaObject Not(DynamicMetaObject target, DynamicMetaObject errorSuggestion) @@ -3790,7 +3790,7 @@ public override DynamicMetaObject FallbackConvert(DynamicMetaObject target, Dyna public override string ToString() { - return string.Format(CultureInfo.InvariantCulture, "PSConvertBinder [{0}] ver:{1}", Microsoft.PowerShell.ToStringCodeMethods.Type(this.Type, true), _version); + return string.Create(CultureInfo.InvariantCulture, $"PSConvertBinder [{Microsoft.PowerShell.ToStringCodeMethods.Type(this.Type, true)}] ver:{_version}"); } internal static void InvalidateCache() @@ -4548,8 +4548,7 @@ private PSSetIndexBinder(Tuple tuple) public override string ToString() { - return string.Format(CultureInfo.InvariantCulture, "PSSetIndexBinder indexCnt={0}{1} ver:{2}", - CallInfo.ArgumentCount, _constraints == null ? string.Empty : " constraints: " + _constraints, _version); + return string.Create(CultureInfo.InvariantCulture, $"PSSetIndexBinder indexCnt={CallInfo.ArgumentCount}{(_constraints == null ? string.Empty : " constraints: " + _constraints)} ver:{_version}"); } internal static void InvalidateCache() @@ -5144,8 +5143,7 @@ private PSGetMemberBinder(string name, Type classScope, bool ignoreCase, bool @s public override string ToString() { - return string.Format(CultureInfo.InvariantCulture, "GetMember: {0}{1}{2} ver:{3}", - Name, _static ? " static" : string.Empty, _nonEnumerating ? " nonEnumerating" : string.Empty, _version); + return string.Create(CultureInfo.InvariantCulture, $"GetMember: {Name}{(_static ? " static" : string.Empty)}{(_nonEnumerating ? " nonEnumerating" : string.Empty)} ver:{_version}"); } public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, DynamicMetaObject errorSuggestion) @@ -5977,7 +5975,7 @@ public PSSetMemberBinder(string name, bool ignoreCase, bool @static, Type classS public override string ToString() { - return string.Format(CultureInfo.InvariantCulture, "SetMember: {0}{1} ver:{2}", _static ? "static " : string.Empty, Name, _getMemberBinder._version); + return string.Create(CultureInfo.InvariantCulture, $"SetMember: {(_static ? "static " : string.Empty)}{Name} ver:{_getMemberBinder._version}"); } private static Expression GetTransformedExpression(IEnumerable transformationAttributes, Expression originalExpression) diff --git a/src/System.Management.Automation/engine/runtime/MutableTuple.cs b/src/System.Management.Automation/engine/runtime/MutableTuple.cs index 49c5eadc4aa..480e8e111b8 100644 --- a/src/System.Management.Automation/engine/runtime/MutableTuple.cs +++ b/src/System.Management.Automation/engine/runtime/MutableTuple.cs @@ -369,7 +369,7 @@ internal static IEnumerable GetAccessProperties(Type tupleType, in foreach (int curIndex in GetAccessPath(size, index)) { - PropertyInfo pi = tupleType.GetProperty("Item" + string.Format(CultureInfo.InvariantCulture, "{0:D3}", curIndex)); + PropertyInfo pi = tupleType.GetProperty("Item" + string.Create(CultureInfo.InvariantCulture, $"{curIndex:D3}")); Diagnostics.Assert(pi != null, "reflection should always find Item"); yield return pi; tupleType = pi.PropertyType; @@ -440,7 +440,7 @@ private static MutableTuple MakeTuple(Func creator, Type tupleType for (int i = 0; i < size; i++) { - PropertyInfo pi = tupleType.GetProperty("Item" + string.Format(CultureInfo.InvariantCulture, "{0:D3}", i)); + PropertyInfo pi = tupleType.GetProperty("Item" + string.Create(CultureInfo.InvariantCulture, $"{i:D3}")); res.SetValueImpl(i, MakeTuple(pi.PropertyType, null, null)); } } @@ -540,7 +540,7 @@ internal static Expression CreateNew(Type tupleType, int start, int end, Express int newStart = start + (i * multiplier); int newEnd = System.Math.Min(end, start + ((i + 1) * multiplier)); - PropertyInfo pi = tupleType.GetProperty("Item" + string.Format(CultureInfo.InvariantCulture, "{0:D3}", i)); + PropertyInfo pi = tupleType.GetProperty("Item" + string.Create(CultureInfo.InvariantCulture, $"{i:D3}")); newValues[i] = CreateNew(pi.PropertyType, newStart, newEnd, values); } diff --git a/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs b/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs index 42d78e8a930..a9c402f3e24 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs @@ -922,7 +922,7 @@ public override string ToString() { return FromStream == RedirectionStream.All ? "*>&1" - : string.Format(CultureInfo.InvariantCulture, "{0}>&1", (int)FromStream); + : string.Create(CultureInfo.InvariantCulture, $"{(int)FromStream}>&1"); } // private RedirectionStream ToStream { get; set; } @@ -1031,11 +1031,7 @@ internal FileRedirection(RedirectionStream from, bool appending, string file) public override string ToString() { - return string.Format(CultureInfo.InvariantCulture, "{0}> {1}", - FromStream == RedirectionStream.All - ? "*" - : ((int)FromStream).ToString(CultureInfo.InvariantCulture), - File); + return string.Create(CultureInfo.InvariantCulture, $"{(FromStream == RedirectionStream.All ? "*" : ((int)FromStream).ToString(CultureInfo.InvariantCulture))}> {File}"); } internal string File { get; } diff --git a/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs b/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs index a3185149ecd..b0017080571 100644 --- a/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs +++ b/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs @@ -946,7 +946,7 @@ private void AddParameter(CommandParameterAst commandParameterAst, bool isTruste // first character in parameter name must be a dash _powershell.AddParameter( - string.Format(CultureInfo.InvariantCulture, "-{0}{1}", commandParameterAst.ParameterName, nameSuffix), + string.Create(CultureInfo.InvariantCulture, $"-{commandParameterAst.ParameterName}{nameSuffix}"), argument); } } From 1b3b359bcbab32b9a3e7cd7ecb26642487cbb374 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Sat, 21 Jan 2023 17:32:26 +0100 Subject: [PATCH 313/779] Use interpolated strings 1 (#18977) --- .../CimSessionOperations.cs | 2 +- .../CimSessionProxy.cs | 10 +++++----- .../RegisterCimIndicationCommand.cs | 2 +- .../Utils.cs | 8 +++----- .../HelpWindow/HelpParagraphBuilder.cs | 12 ++++++------ .../FilterCore/ValidatingSelectorValue.cs | 2 +- .../FilterCore/ValidatingValueBase.cs | 2 +- .../FilterProviders/SearchTextParser.cs | 4 ++-- .../ManagementList/ManagementList/Innerlist.cs | 2 +- .../ManagementList/ViewGroupToStringConverter.cs | 2 +- .../Controls/MultipleSelectionControl.xaml.cs | 2 +- .../Controls/ParameterSetControl.xaml.cs | 13 +++++-------- .../ShowCommand/ViewModel/CommandViewModel.cs | 2 +- .../ShowCommand/ViewModel/ParameterSetViewModel.cs | 4 ++-- .../ShowCommand/ViewModel/ParameterViewModel.cs | 2 +- .../PSVersionInfoGenerator.csproj | 1 + 16 files changed, 33 insertions(+), 37 deletions(-) diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionOperations.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionOperations.cs index c22db2087e4..f31e7035202 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionOperations.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionOperations.cs @@ -951,7 +951,7 @@ internal void AddSessionToCache(CimSession cimSession, XOperationContextBase con CimTestCimSessionContext testCimSessionContext = context as CimTestCimSessionContext; uint sessionId = this.sessionState.GenerateSessionId(); string originalSessionName = testCimSessionContext.CimSessionWrapper.Name; - string sessionName = originalSessionName ?? string.Format(CultureInfo.CurrentUICulture, @"{0}{1}", CimSessionState.CimSessionClassName, sessionId); + string sessionName = originalSessionName ?? string.Create(CultureInfo.CurrentUICulture, $"{CimSessionState.CimSessionClassName}{sessionId}"); // detach CimSession from the proxy object CimSession createdCimSession = testCimSessionContext.Proxy.Detach(); diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs index bc69a4f5ce7..64f5634f970 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs @@ -875,7 +875,7 @@ internal void WriteOperationStartMessage(string operation, Hashtable parameterLi parameters.Append(','); } - parameters.Append(string.Format(CultureInfo.CurrentUICulture, @"'{0}' = {1}", key, parameterList[key])); + parameters.Append(CultureInfo.CurrentUICulture, $@"'{key}' = {parameterList[key]}"); } } @@ -1232,7 +1232,7 @@ public void EnumerateInstancesAsync(string namespaceName, string className) this.operationParameters.Add(@"className", className); this.WriteOperationStartMessage(this.operationName, this.operationParameters); CimAsyncMultipleResults asyncResult = this.CimSession.EnumerateInstancesAsync(namespaceName, className, this.OperationOptions); - string errorSource = string.Format(CultureInfo.CurrentUICulture, "{0}:{1}", namespaceName, className); + string errorSource = string.Create(CultureInfo.CurrentUICulture, $"{namespaceName}:{className}"); ConsumeCimInstanceAsync(asyncResult, new CimResultContext(errorSource)); } @@ -1314,7 +1314,7 @@ public void EnumerateClassesAsync(string namespaceName, string className) this.operationParameters.Add(@"className", className); this.WriteOperationStartMessage(this.operationName, this.operationParameters); CimAsyncMultipleResults asyncResult = this.CimSession.EnumerateClassesAsync(namespaceName, className, this.OperationOptions); - string errorSource = string.Format(CultureInfo.CurrentUICulture, "{0}:{1}", namespaceName, className); + string errorSource = string.Create(CultureInfo.CurrentUICulture, $"{namespaceName}:{className}"); ConsumeCimClassAsync(asyncResult, new CimResultContext(errorSource)); } @@ -1334,7 +1334,7 @@ public void GetClassAsync(string namespaceName, string className) this.operationParameters.Add(@"className", className); this.WriteOperationStartMessage(this.operationName, this.operationParameters); CimAsyncResult asyncResult = this.CimSession.GetClassAsync(namespaceName, className, this.OperationOptions); - string errorSource = string.Format(CultureInfo.CurrentUICulture, "{0}:{1}", namespaceName, className); + string errorSource = string.Create(CultureInfo.CurrentUICulture, $"{namespaceName}:{className}"); ConsumeCimClassAsync(asyncResult, new CimResultContext(errorSource)); } @@ -1388,7 +1388,7 @@ public void InvokeMethodAsync( this.operationParameters.Add(@"methodName", methodName); this.WriteOperationStartMessage(this.operationName, this.operationParameters); CimAsyncMultipleResults asyncResult = this.CimSession.InvokeMethodAsync(namespaceName, className, methodName, methodParameters, this.OperationOptions); - string errorSource = string.Format(CultureInfo.CurrentUICulture, "{0}:{1}", namespaceName, className); + string errorSource = string.Create(CultureInfo.CurrentUICulture, $"{namespaceName}:{className}"); ConsumeCimInvokeMethodResultAsync(asyncResult, className, methodName, new CimResultContext(errorSource)); } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/RegisterCimIndicationCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/RegisterCimIndicationCommand.cs index d5dc44a31d4..b314691e41f 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/RegisterCimIndicationCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/RegisterCimIndicationCommand.cs @@ -205,7 +205,7 @@ protected override object GetSourceObject() case CimBaseCommand.ClassNameComputerSet: // validate the classname this.CheckArgument(); - tempQueryExpression = string.Format(CultureInfo.CurrentCulture, "Select * from {0}", this.ClassName); + tempQueryExpression = string.Create(CultureInfo.CurrentCulture, $"Select * from {this.ClassName}"); break; } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/Utils.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/Utils.cs index 61afc00a676..be517c9864c 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/Utils.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/Utils.cs @@ -201,16 +201,14 @@ internal static string GetSourceCodeInformation(bool withFileName, int depth) StackFrame frame = trace.GetFrame(depth); // if (withFileName) // { - // return string.Format(CultureInfo.CurrentUICulture, "{0}#{1}:{2}:", frame.GetFileName()., frame.GetFileLineNumber(), frame.GetMethod().Name); + // return string.Create(CultureInfo.CurrentUICulture, $"{frame.GetFileName().}#{frame.GetFileLineNumber()}:{frame.GetMethod().Name}:"); // } // else // { - // return string.Format(CultureInfo.CurrentUICulture, "{0}:", frame.GetMethod()); + // return string.Create(CultureInfo.CurrentUICulture, $"{frame.GetMethod()}:"); // } - return string.Format(CultureInfo.CurrentUICulture, "{0}::{1} ", - frame.GetMethod().DeclaringType.Name, - frame.GetMethod().Name); + return string.Create(CultureInfo.CurrentUICulture, $"{frame.GetMethod().DeclaringType.Name}::{frame.GetMethod().Name} "); } #endregion diff --git a/src/Microsoft.Management.UI.Internal/HelpWindow/HelpParagraphBuilder.cs b/src/Microsoft.Management.UI.Internal/HelpWindow/HelpParagraphBuilder.cs index a0f2cf950bd..107ff67dd04 100644 --- a/src/Microsoft.Management.UI.Internal/HelpWindow/HelpParagraphBuilder.cs +++ b/src/Microsoft.Management.UI.Internal/HelpWindow/HelpParagraphBuilder.cs @@ -276,7 +276,7 @@ private static string AddIndent(string str, string indentString) foreach (string line in lines) { // Indentation is not localized - returnValue.AppendFormat("{0}{1}\r\n", indentString, line); + returnValue.Append($"{indentString}{line}\r\n"); } if (returnValue.Length > 2) @@ -369,7 +369,7 @@ private void AddSyntax(bool setting, string sectionTitle) continue; } - string commandStart = string.Format(CultureInfo.CurrentCulture, "{0} ", commandName); + string commandStart = string.Create(CultureInfo.CurrentCulture, $"{commandName} "); this.AddText(HelpParagraphBuilder.AddIndent(commandStart), false); foreach (object parameterObj in parameterObjs) @@ -389,7 +389,7 @@ private void AddSyntax(bool setting, string sectionTitle) continue; } - string parameterType = parameterValue == null ? string.Empty : string.Format(CultureInfo.CurrentCulture, "<{0}>", parameterValue); + string parameterType = parameterValue == null ? string.Empty : string.Create(CultureInfo.CurrentCulture, $"<{parameterValue}>"); string parameterOptionalOpenBrace, parameterOptionalCloseBrace; @@ -607,7 +607,7 @@ private void AddMembers(bool setting, string sectionTitle) description = GetPropertyString(propertyTypeObject, "description"); } - memberText = string.Format(CultureInfo.CurrentCulture, " [{0}] {1}\r\n", propertyType, name); + memberText = string.Create(CultureInfo.CurrentCulture, $" [{propertyType}] {name}\r\n"); } } else if (string.Equals("method", type, StringComparison.OrdinalIgnoreCase)) @@ -697,7 +697,7 @@ private static void FormatMethodData(PSObject member, string name, out string me } } - string paramString = string.Format(CultureInfo.CurrentCulture, "[{0}] ${1},", parameterType, parameterName); + string paramString = string.Create(CultureInfo.CurrentCulture, $"[{parameterType}] ${parameterName},"); parameterText.Append(paramString); } @@ -709,7 +709,7 @@ private static void FormatMethodData(PSObject member, string name, out string me } } - memberText = string.Format(CultureInfo.CurrentCulture, " [{0}] {1}({2})\r\n", returnType, name, parameterText); + memberText = string.Create(CultureInfo.CurrentCulture, $" [{returnType}] {name}({parameterText})\r\n"); } /// diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingSelectorValue.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingSelectorValue.cs index e86f2020ecc..9b72d5848ec 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingSelectorValue.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingSelectorValue.cs @@ -188,7 +188,7 @@ protected override DataErrorInfoValidationResult Validate(string columnName) { if (!columnName.Equals(SelectedIndexPropertyName, StringComparison.CurrentCulture)) { - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "{0} is not a valid column name.", columnName), "columnName"); + throw new ArgumentException(string.Create(CultureInfo.CurrentCulture, $"{columnName} is not a valid column name."), "columnName"); } if (!this.IsIndexWithinBounds(this.SelectedIndex)) diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValueBase.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValueBase.cs index f33862846a9..3a072180278 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValueBase.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValueBase.cs @@ -218,7 +218,7 @@ internal DataErrorInfoValidationResult EvaluateValidationRules(object value, Sys DataErrorInfoValidationResult result = rule.Validate(value, cultureInfo); if (result == null) { - throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "DataErrorInfoValidationResult not returned by ValidationRule: {0}", rule.ToString())); + throw new InvalidOperationException(string.Create(CultureInfo.CurrentCulture, $"DataErrorInfoValidationResult not returned by ValidationRule: {rule}")); } if (!result.IsValid) diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchTextParser.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchTextParser.cs index c64683c7301..8900964fba2 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchTextParser.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchTextParser.cs @@ -121,7 +121,7 @@ protected virtual string GetPattern() patterns.Add(rule.Pattern); } - patterns.Add(string.Format(CultureInfo.InvariantCulture, "(?<{0}>){1}", FullTextRuleGroupName, ValuePattern)); + patterns.Add(string.Create(CultureInfo.InvariantCulture, $"(?<{FullTextRuleGroupName}>){ValuePattern}")); return string.Join("|", patterns.ToArray()); } @@ -199,7 +199,7 @@ public SearchableRule(string uniqueId, SelectorFilterRule selectorFilterRule, Te this.UniqueId = uniqueId; this.selectorFilterRule = selectorFilterRule; this.childRule = childRule; - this.Pattern = string.Format(CultureInfo.InvariantCulture, "(?<{0}>){1}\\s*:\\s*{2}", uniqueId, Regex.Escape(selectorFilterRule.DisplayName), SearchTextParser.ValuePattern); + this.Pattern = string.Create(CultureInfo.InvariantCulture, $"(?<{uniqueId}>){Regex.Escape(selectorFilterRule.DisplayName)}\\s*:\\s*{SearchTextParser.ValuePattern}"); } /// diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/Innerlist.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/Innerlist.cs index fe9e0fdcd1e..a970a5290e5 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/Innerlist.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/Innerlist.cs @@ -596,7 +596,7 @@ private string GetClipboardTextLineForSelectedItem(object value) propertyValue = string.Empty; } - entryText.AppendFormat(CultureInfo.CurrentCulture, "{0}\t", propertyValue); + entryText.Append(CultureInfo.CurrentCulture, $"{propertyValue}\t"); } return entryText.ToString(); diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ViewGroupToStringConverter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ViewGroupToStringConverter.cs index c69cd8e0c08..22741a7031b 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ViewGroupToStringConverter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ViewGroupToStringConverter.cs @@ -35,7 +35,7 @@ public object Convert(object value, Type targetType, object parameter, System.Gl } string name = (!string.IsNullOrEmpty(cvg.Name.ToString())) ? cvg.Name.ToString() : UICultureResources.GroupTitleNone; - string display = string.Format(CultureInfo.CurrentCulture, "{0} ({1})", name, cvg.ItemCount); + string display = string.Create(CultureInfo.CurrentCulture, $"{name} ({cvg.ItemCount})"); return display; } diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/MultipleSelectionControl.xaml.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/MultipleSelectionControl.xaml.cs index 54dcf1896ff..f57d5dfda51 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/MultipleSelectionControl.xaml.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/MultipleSelectionControl.xaml.cs @@ -43,7 +43,7 @@ private void ButtonBrowse_Click(object sender, RoutedEventArgs e) foreach (object selectedItem in multipleSelectionDialog.listboxParameter.SelectedItems) { - newComboText.AppendFormat(CultureInfo.InvariantCulture, "{0},", selectedItem.ToString()); + newComboText.Append(CultureInfo.InvariantCulture, $"{selectedItem},"); } if (newComboText.Length > 1) diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ParameterSetControl.xaml.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ParameterSetControl.xaml.cs index 08f9df29337..907c743f6bf 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ParameterSetControl.xaml.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ParameterSetControl.xaml.cs @@ -94,7 +94,7 @@ private static CheckBox CreateCheckBox(ParameterViewModel parameterViewModel, in //// Add AutomationProperties.AutomationId for Ui Automation test. checkBox.SetValue( System.Windows.Automation.AutomationProperties.AutomationIdProperty, - string.Format(CultureInfo.CurrentCulture, "chk{0}", parameterViewModel.Name)); + string.Create(CultureInfo.CurrentCulture, $"chk{parameterViewModel.Name}")); checkBox.SetValue( System.Windows.Automation.AutomationProperties.NameProperty, @@ -124,10 +124,7 @@ private static ComboBox CreateComboBoxControl(ParameterViewModel parameterViewMo Binding selectedItemBinding = new Binding("Value"); comboBox.SetBinding(ComboBox.SelectedItemProperty, selectedItemBinding); - string automationId = string.Format( - CultureInfo.CurrentCulture, - "combox{0}", - parameterViewModel.Name); + string automationId = string.Create(CultureInfo.CurrentCulture, $"combox{parameterViewModel.Name}"); //// Add AutomationProperties.AutomationId for Ui Automation test. comboBox.SetValue( @@ -164,7 +161,7 @@ private static MultipleSelectionControl CreateMultiSelectComboControl(ParameterV multiControls.comboxParameter.SetBinding(ComboBox.TextProperty, valueBinding); // Add AutomationProperties.AutomationId for Ui Automation test. - multiControls.SetValue(System.Windows.Automation.AutomationProperties.AutomationIdProperty, string.Format("combox{0}", parameterViewModel.Name)); + multiControls.SetValue(System.Windows.Automation.AutomationProperties.AutomationIdProperty, string.Create(CultureInfo.CurrentCulture, $"combox{parameterViewModel.Name}")); multiControls.comboxParameter.SetValue( System.Windows.Automation.AutomationProperties.NameProperty, @@ -206,7 +203,7 @@ private static TextBox CreateTextBoxControl(ParameterViewModel parameterViewMode //// Add AutomationProperties.AutomationId for UI Automation test. textBox.SetValue( System.Windows.Automation.AutomationProperties.AutomationIdProperty, - string.Format(CultureInfo.CurrentCulture, "txt{0}", parameterViewModel.Name)); + string.Create(CultureInfo.CurrentCulture, $"txt{parameterViewModel.Name}")); textBox.SetValue( System.Windows.Automation.AutomationProperties.NameProperty, @@ -397,7 +394,7 @@ private Label CreateLabel(ParameterViewModel parameterViewModel, int rowNumber) //// Add AutomationProperties.AutomationId for Ui Automation test. label.SetValue( System.Windows.Automation.AutomationProperties.AutomationIdProperty, - string.Format(CultureInfo.CurrentCulture, "lbl{0}", parameterViewModel.Name)); + string.Create(CultureInfo.CurrentCulture, $"lbl{parameterViewModel.Name}")); return label; } diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/CommandViewModel.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/CommandViewModel.cs index 367b5d08131..835ae6d3c9d 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/CommandViewModel.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/CommandViewModel.cs @@ -431,7 +431,7 @@ public string GetScript() if (commandName.Contains(' ')) { - builder.AppendFormat("& \"{0}\"", commandName); + builder.Append($"& \"{commandName}\""); } else { diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterSetViewModel.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterSetViewModel.cs index 9d59ca3dc1d..2b70deff7d8 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterSetViewModel.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterSetViewModel.cs @@ -138,7 +138,7 @@ public string GetScript() { if (((bool?)parameter.Value) == true) { - builder.AppendFormat("-{0} ", parameter.Name); + builder.Append($"-{parameter.Name} "); } continue; @@ -166,7 +166,7 @@ public string GetScript() parameterValueString = ParameterSetViewModel.GetDelimitedParameter(parameterValueString, "(", ")"); } - builder.AppendFormat("-{0} {1} ", parameter.Name, parameterValueString); + builder.Append($"-{parameter.Name} {parameterValueString} "); } return builder.ToString().Trim(); diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterViewModel.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterViewModel.cs index 32eb8271938..fd5b14fff12 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterViewModel.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterViewModel.cs @@ -159,7 +159,7 @@ public string NameCheckLabel string returnValue = this.Parameter.Name; if (this.Parameter.IsMandatory) { - returnValue = string.Format(CultureInfo.CurrentUICulture, "{0}{1}", returnValue, ShowCommandResources.MandatoryLabelSegment); + returnValue = string.Create(CultureInfo.CurrentUICulture, $"{returnValue}{ShowCommandResources.MandatoryLabelSegment}"); } return returnValue; diff --git a/src/System.Management.Automation/SourceGenerators/PSVersionInfoGenerator/PSVersionInfoGenerator.csproj b/src/System.Management.Automation/SourceGenerators/PSVersionInfoGenerator/PSVersionInfoGenerator.csproj index 8ebdc3a61ac..c312121359d 100644 --- a/src/System.Management.Automation/SourceGenerators/PSVersionInfoGenerator/PSVersionInfoGenerator.csproj +++ b/src/System.Management.Automation/SourceGenerators/PSVersionInfoGenerator/PSVersionInfoGenerator.csproj @@ -9,6 +9,7 @@ netstandard2.0 10.0 true + true From 099cbc1727952ce43c23933f3f4dac77145dc29f Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Sat, 21 Jan 2023 18:26:39 +0100 Subject: [PATCH 314/779] WebCmdlets parse XML declaration to get encoding value, if present. (#18748) --- .../utility/WebCmdlet/StreamHelper.cs | 53 +++++++++++-------- 1 file changed, 31 insertions(+), 22 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs index 9d0f4a93797..0e219e591b9 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs @@ -28,7 +28,7 @@ internal class WebResponseContentMemoryStream : MemoryStream private bool _isInitialized = false; private readonly Cmdlet _ownerCmdlet; - #endregion + #endregion Data #region Constructors /// @@ -44,7 +44,7 @@ internal WebResponseContentMemoryStream(Stream stream, int initialCapacity, Cmdl _originalStreamToProxy = stream; _ownerCmdlet = cmdlet; } - #endregion + #endregion Constructors /// /// @@ -411,10 +411,15 @@ internal static bool TryGetEncoding(string characterSet, out Encoding encoding) return result; } - private static readonly Regex s_metaexp = new( + private static readonly Regex s_metaRegex = new( @"<]*charset\s*=\s*[""'\n]?(?[A-Za-z].[^\s""'\n<>]*)[\s""'\n>]", - RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.ExplicitCapture | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase + RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.ExplicitCapture | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase | RegexOptions.NonBacktracking ); + + private static readonly Regex s_xmlRegex = new( + @"<\?xml\s.*[^.><]*encoding\s*=\s*[""'\n]?(?[A-Za-z].[^\s""'\n<>]*)[\s""'\n>]", + RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.ExplicitCapture | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase | RegexOptions.NonBacktracking + ); internal static string DecodeStream(Stream stream, ref Encoding encoding) { @@ -429,27 +434,31 @@ internal static string DecodeStream(Stream stream, ref Encoding encoding) string content = StreamToString(stream, encoding); if (isDefaultEncoding) { - do + // We only look within the first 1k characters as the meta element and + // the xml declaration are at the start of the document + string substring = content.Substring(0, Math.Min(content.Length, 1024)); + + // Check for a charset attribute on the meta element to override the default + Match match = s_metaRegex.Match(substring); + + // Check for a encoding attribute on the xml declaration to override the default + if (!match.Success) { - // Check for a charset attribute on the meta element to override the default - // we only look within the first 1k characters as the meta tag is in the head - // tag which is at the start of the document - Match match = s_metaexp.Match(content.Substring(0, Math.Min(content.Length, 1024))); - if (match.Success) - { - Encoding localEncoding = null; - string characterSet = match.Groups["charset"].Value; - - if (TryGetEncoding(characterSet, out localEncoding)) - { - stream.Seek(0, SeekOrigin.Begin); - content = StreamToString(stream, localEncoding); + match = s_xmlRegex.Match(substring); + } + + if (match.Success) + { + Encoding localEncoding = null; + string characterSet = match.Groups["charset"].Value; - // Report the encoding used. - encoding = localEncoding; - } + if (TryGetEncoding(characterSet, out localEncoding)) + { + stream.Seek(0, SeekOrigin.Begin); + content = StreamToString(stream, localEncoding); + encoding = localEncoding; } - } while (false); + } } return content; From 33ba57387d697fcb4f83896456fb5730ffbfc6da Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Mon, 23 Jan 2023 18:35:20 +0100 Subject: [PATCH 315/779] Use interpolated strings 12 (#19003) --- .../engine/Modules/NewModuleManifestCommand.cs | 6 ++---- .../commands/NewPSSessionConfigurationFile.cs | 5 ++++- .../engine/runtime/Binding/Binders.cs | 11 ++--------- 3 files changed, 8 insertions(+), 14 deletions(-) diff --git a/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs b/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs index 65739b03c8c..9346e7caa97 100644 --- a/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs +++ b/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs @@ -886,14 +886,12 @@ private List TryResolveFilePath(string filePath) /// private string ManifestFragment(string key, string resourceString, string value, StreamWriter streamWriter) { - return string.Format(CultureInfo.InvariantCulture, "{0}# {1}{2}{0}{3:19} = {4}{2}{2}", - _indent, resourceString, streamWriter.NewLine, key, value); + return string.Format(CultureInfo.InvariantCulture, "{0}# {1}{2}{0}{3:19} = {4}{2}{2}", _indent, resourceString, streamWriter.NewLine, key, value); } private string ManifestFragmentForNonSpecifiedManifestMember(string key, string resourceString, string value, StreamWriter streamWriter) { - return string.Format(CultureInfo.InvariantCulture, "{0}# {1}{2}{0}# {3:19} = {4}{2}{2}", - _indent, resourceString, streamWriter.NewLine, key, value); + return string.Format(CultureInfo.InvariantCulture, "{0}# {1}{2}{0}# {3:19} = {4}{2}{2}", _indent, resourceString, streamWriter.NewLine, key, value); } private static string ManifestComment(string insert, StreamWriter streamWriter) diff --git a/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationFile.cs b/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationFile.cs index 2699c6cbcbf..07258e80a90 100644 --- a/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationFile.cs +++ b/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationFile.cs @@ -1868,7 +1868,7 @@ internal static string ConfigFragment(string key, string resourceString, string { return string.Format(CultureInfo.InvariantCulture, "# {0}{1}# {2:19} = {3}{4}{5}", resourceString, nl, key, value, nl, nl); } - + return string.Format(CultureInfo.InvariantCulture, "# {0}{1}{2:19} = {3}{4}{5}", resourceString, nl, key, value, nl, nl); } @@ -1880,7 +1880,10 @@ internal static string ConfigFragment(string key, string resourceString, string internal static string QuoteName(object name) { if (name == null) + { return "''"; + } + return "'" + System.Management.Automation.Language.CodeGeneration.EscapeSingleQuotedStringContent(name.ToString()) + "'"; } diff --git a/src/System.Management.Automation/engine/runtime/Binding/Binders.cs b/src/System.Management.Automation/engine/runtime/Binding/Binders.cs index 13eb426dfdc..79e5fb4c2f9 100644 --- a/src/System.Management.Automation/engine/runtime/Binding/Binders.cs +++ b/src/System.Management.Automation/engine/runtime/Binding/Binders.cs @@ -3959,12 +3959,7 @@ private PSGetIndexBinder(Tuple tu public override string ToString() { - return string.Format(CultureInfo.InvariantCulture, - "PSGetIndexBinder indexCount={0}{1}{2} ver:{3}", - this.CallInfo.ArgumentCount, - _allowSlicing ? string.Empty : " slicing disallowed", - _constraints == null ? string.Empty : " constraints: " + _constraints, - _version); + return string.Create(CultureInfo.InvariantCulture, $"PSGetIndexBinder indexCount={this.CallInfo.ArgumentCount}{(_allowSlicing ? string.Empty : " slicing disallowed")}{(_constraints == null ? string.Empty : " constraints: " + _constraints)} ver:{_version}"); } internal static void InvalidateCache() @@ -6579,9 +6574,7 @@ private PSInvokeMemberBinder(string name, public override string ToString() { - return string.Format(CultureInfo.InvariantCulture, - "PSInvokeMember: {0}{1}{2} ver:{3} args:{4} constraints:<{5}>", _static ? "static " : string.Empty, _propertySetter ? "propset " : string.Empty, - Name, _getMemberBinder._version, CallInfo.ArgumentCount, _invocationConstraints != null ? _invocationConstraints.ToString() : string.Empty); + return string.Create(CultureInfo.InvariantCulture, $"PSInvokeMember: {(_static ? "static " : string.Empty)}{(_propertySetter ? "propset " : string.Empty)}{Name} ver:{_getMemberBinder._version} args:{CallInfo.ArgumentCount} constraints:<{(_invocationConstraints != null ? _invocationConstraints.ToString() : string.Empty)}>"); } public override DynamicMetaObject FallbackInvokeMember(DynamicMetaObject target, DynamicMetaObject[] args, DynamicMetaObject errorSuggestion) From 4c586a7a86515869a4732532b5c8c29c9e58fa70 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Mon, 23 Jan 2023 18:36:26 +0100 Subject: [PATCH 316/779] Use interpolated strings 11 (#19002) --- .../commands/utility/ImplicitRemotingCommands.cs | 7 ++----- src/Microsoft.WSMan.Management/CredSSP.cs | 10 ++++------ .../DscSupport/CimDSCParser.cs | 14 ++------------ .../common/DisplayDatabase/typeDataXmlLoader.cs | 5 +---- .../DisplayDatabase/typeDataXmlLoader_Views.cs | 5 +---- .../cimSupport/other/ciminstancetypeadapter.cs | 9 ++------- .../engine/ManagementObjectAdapter.cs | 4 +--- .../engine/parser/DebugViewWriter.cs | 7 +------ .../remoting/commands/CustomShellCommands.cs | 4 +--- .../remoting/fanin/OutOfProcTransportManager.cs | 15 ++------------- .../remoting/fanin/WSManPluginShellSession.cs | 6 +----- .../help/HelpCommentsParser.cs | 4 +--- .../utils/tracing/SysLogProvider.cs | 14 +++----------- src/TypeCatalogGen/TypeCatalogGen.cs | 4 +--- 14 files changed, 23 insertions(+), 85 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs index ed21408c92f..6d51d972916 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs @@ -2589,15 +2589,12 @@ private string GenerateConnectionStringForNewRunspace() CodeGeneration.EscapeSingleQuotedStringContent(connectionInfo.AppName), connectionInfo.UseDefaultWSManPort ? string.Empty : - string.Format(CultureInfo.InvariantCulture, - "-Port {0} ", connectionInfo.Port), + string.Create(CultureInfo.InvariantCulture, $"-Port {connectionInfo.Port} "), isSSLSpecified ? "-useSSL" : string.Empty); } else { - return string.Format(CultureInfo.InvariantCulture, - "-connectionUri '{0}'", - CodeGeneration.EscapeSingleQuotedStringContent(GetConnectionString())); + return string.Create(CultureInfo.InvariantCulture, $"-connectionUri '{CodeGeneration.EscapeSingleQuotedStringContent(GetConnectionString())}'"); } } diff --git a/src/Microsoft.WSMan.Management/CredSSP.cs b/src/Microsoft.WSMan.Management/CredSSP.cs index 2470a6fc3c4..13e99c04f1f 100644 --- a/src/Microsoft.WSMan.Management/CredSSP.cs +++ b/src/Microsoft.WSMan.Management/CredSSP.cs @@ -200,9 +200,7 @@ private void DisableServerSideSettings() return; } - string inputXml = string.Format(CultureInfo.InvariantCulture, - @"false", - helper.Service_CredSSP_XMLNmsp); + string inputXml = string.Create(CultureInfo.InvariantCulture, $@"false"); m_SessionObj.Put(helper.Service_CredSSP_Uri, inputXml, 0); } @@ -513,6 +511,7 @@ private void EnableClientSideSettings() try { XmlDocument xmldoc = new XmlDocument(); + // push the xml string with credssp enabled xmldoc.LoadXml(m_SessionObj.Put(helper.CredSSP_RUri, newxmlcontent, 0)); @@ -592,9 +591,8 @@ private void EnableServerSideSettings() try { XmlDocument xmldoc = new XmlDocument(); - string newxmlcontent = string.Format(CultureInfo.InvariantCulture, - @"true", - helper.Service_CredSSP_XMLNmsp); + string newxmlcontent = string.Create(CultureInfo.InvariantCulture, $@"true"); + // push the xml string with credssp enabled xmldoc.LoadXml(m_SessionObj.Put(helper.Service_CredSSP_Uri, newxmlcontent, 0)); WriteObject(xmldoc.FirstChild); diff --git a/src/System.Management.Automation/DscSupport/CimDSCParser.cs b/src/System.Management.Automation/DscSupport/CimDSCParser.cs index 904103f451d..ab7536b7e4f 100644 --- a/src/System.Management.Automation/DscSupport/CimDSCParser.cs +++ b/src/System.Management.Automation/DscSupport/CimDSCParser.cs @@ -2534,12 +2534,7 @@ private static void ProcessMembers(StringBuilder sb, List embeddedInstan string arrayAffix = isArrayType ? "[]" : string.Empty; - sb.AppendFormat(CultureInfo.InvariantCulture, - " {0}{1} {2}{3};\n", - MapAttributesToMof(enumNames, attributes, embeddedInstanceType), - mofType, - member.Name, - arrayAffix); + sb.Append(CultureInfo.InvariantCulture, $" {MapAttributesToMof(enumNames, attributes, embeddedInstanceType)}{mofType} {member.Name}{arrayAffix};\n"); } } @@ -3096,12 +3091,7 @@ private static void ProcessMembers(Type type, StringBuilder sb, List emb var enumNames = memberType.IsEnum ? Enum.GetNames(memberType) : null; - sb.AppendFormat(CultureInfo.InvariantCulture, - " {0}{1} {2}{3};\n", - MapAttributesToMof(enumNames, member.GetCustomAttributes(true), embeddedInstanceType), - mofType, - member.Name, - arrayAffix); + sb.Append(CultureInfo.InvariantCulture, $" {MapAttributesToMof(enumNames, member.GetCustomAttributes(true), embeddedInstanceType)}{mofType} {member.Name}{arrayAffix};\n"); } } diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs index 8c1c251f149..d13177af484 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs @@ -436,10 +436,7 @@ private void LoadData(ExtendedTypeDefinition typeDefinition, TypeInfoDataBase db ViewDefinition view = LoadViewFromObjectModel(typeDefinition.TypeNames, formatView, viewIndex++); if (view != null) { - ReportTrace(string.Format(CultureInfo.InvariantCulture, - "{0} view {1} is loaded from the 'FormatViewDefinition' at index {2} in 'ExtendedTypeDefinition' with type name {3}", - ControlBase.GetControlShapeName(view.mainControl), - view.name, viewIndex - 1, typeDefinition.TypeName)); + ReportTrace(string.Create(CultureInfo.InvariantCulture, $"{ControlBase.GetControlShapeName(view.mainControl)} view {view.name} is loaded from the 'FormatViewDefinition' at index {viewIndex - 1} in 'ExtendedTypeDefinition' with type name {typeDefinition.TypeName}")); // we are fine, add the view to the list db.viewDefinitionsSection.viewDefinitionList.Add(view); diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Views.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Views.cs index 505c766b9d1..a92f7a6b105 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Views.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Views.cs @@ -27,10 +27,7 @@ private void LoadViewDefinitions(TypeInfoDataBase db, XmlNode viewDefinitionsNod ViewDefinition view = LoadView(n, index++); if (view != null) { - ReportTrace(string.Format(CultureInfo.InvariantCulture, - "{0} view {1} is loaded from file {2}", - ControlBase.GetControlShapeName(view.mainControl), - view.name, view.loadingInfo.filePath)); + ReportTrace(string.Create(CultureInfo.InvariantCulture, $"{ControlBase.GetControlShapeName(view.mainControl)} view {view.name} is loaded from file {view.loadingInfo.filePath}")); // we are fine, add the view to the list db.viewDefinitionsSection.viewDefinitionList.Add(view); } diff --git a/src/System.Management.Automation/cimSupport/other/ciminstancetypeadapter.cs b/src/System.Management.Automation/cimSupport/other/ciminstancetypeadapter.cs index 6b1b85c125d..1761fac8235 100644 --- a/src/System.Management.Automation/cimSupport/other/ciminstancetypeadapter.cs +++ b/src/System.Management.Automation/cimSupport/other/ciminstancetypeadapter.cs @@ -238,16 +238,11 @@ private static void AddTypeNameHierarchy(IList typeNamesWithNamespace, I { if (!string.IsNullOrEmpty(namespaceName)) { - string fullTypeName = string.Format(CultureInfo.InvariantCulture, - "Microsoft.Management.Infrastructure.CimInstance#{0}/{1}", - namespaceName, - className); + string fullTypeName = string.Create(CultureInfo.InvariantCulture, $"Microsoft.Management.Infrastructure.CimInstance#{namespaceName}/{className}"); typeNamesWithNamespace.Add(fullTypeName); } - typeNamesWithoutNamespace.Add(string.Format(CultureInfo.InvariantCulture, - "Microsoft.Management.Infrastructure.CimInstance#{0}", - className)); + typeNamesWithoutNamespace.Add(string.Create(CultureInfo.InvariantCulture, $"Microsoft.Management.Infrastructure.CimInstance#{className}")); } private static List GetInheritanceChain(CimInstance cimInstance) diff --git a/src/System.Management.Automation/engine/ManagementObjectAdapter.cs b/src/System.Management.Automation/engine/ManagementObjectAdapter.cs index 707d8314dce..cfe7ce32ee4 100644 --- a/src/System.Management.Automation/engine/ManagementObjectAdapter.cs +++ b/src/System.Management.Automation/engine/ManagementObjectAdapter.cs @@ -1161,9 +1161,7 @@ protected override PSProperty DoGetProperty(ManagementBaseObject wmiObject, stri PSLevel.Informational, PSTask.None, PSKeyword.UseAlwaysOperational, - string.Format(CultureInfo.InvariantCulture, - "ManagementBaseObjectAdapter::DoGetProperty::PropertyName:{0}, Exception:{1}, StackTrace:{2}", - propertyName, e.Message, e.StackTrace), + string.Create(CultureInfo.InvariantCulture, $"ManagementBaseObjectAdapter::DoGetProperty::PropertyName:{propertyName}, Exception:{e.Message}, StackTrace:{e.StackTrace}"), string.Empty, string.Empty); // ignore the exception. diff --git a/src/System.Management.Automation/engine/parser/DebugViewWriter.cs b/src/System.Management.Automation/engine/parser/DebugViewWriter.cs index cb280bdaf61..091ded80e19 100644 --- a/src/System.Management.Automation/engine/parser/DebugViewWriter.cs +++ b/src/System.Management.Automation/engine/parser/DebugViewWriter.cs @@ -447,12 +447,7 @@ protected override Expression VisitParameter(ParameterExpression node) { protected override Expression VisitLambda(Expression node) { Out( - string.Format(CultureInfo.CurrentCulture, - "{0} {1}<{2}>", - ".Lambda", - GetLambdaName(node), - node.Type.ToString() - ) + string.Create(CultureInfo.CurrentCulture, $".Lambda {GetLambdaName(node)}<{node.Type}>") ); if (_lambdas == null) { diff --git a/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs b/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs index d08f8662b06..811707a3b54 100644 --- a/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs +++ b/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs @@ -544,9 +544,7 @@ protected override void ProcessRecord() string restartServiceTarget = StringUtil.Format(RemotingErrorIdStrings.RestartWSManServiceTarget, "WinRM"); string restartWSManRequiredForUI = StringUtil.Format(RemotingErrorIdStrings.RestartWSManRequiredShowUI, - string.Format(CultureInfo.InvariantCulture, - "Set-PSSessionConfiguration {0} -ShowSecurityDescriptorUI", - shellName)); + string.Create(CultureInfo.InvariantCulture, $"Set-PSSessionConfiguration {shellName} -ShowSecurityDescriptorUI")); // gather -WhatIf, -Confirm parameter data and pass it to the script block bool whatIf = false; diff --git a/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs b/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs index 9b8b7b3af3b..0759f7bcb70 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs @@ -75,14 +75,7 @@ static OutOfProcessUtils() internal static string CreateDataPacket(byte[] data, DataPriorityType streamType, Guid psGuid) { - string result = string.Format(CultureInfo.InvariantCulture, - "<{0} {1}='{2}' {3}='{4}'>{5}", - PS_OUT_OF_PROC_DATA_TAG, - PS_OUT_OF_PROC_STREAM_ATTRIBUTE, - streamType.ToString(), - PS_OUT_OF_PROC_PSGUID_ATTRIBUTE, - psGuid.ToString(), - Convert.ToBase64String(data)); + string result = string.Create(CultureInfo.InvariantCulture, $"<{PS_OUT_OF_PROC_DATA_TAG} {PS_OUT_OF_PROC_STREAM_ATTRIBUTE}='{streamType}' {PS_OUT_OF_PROC_PSGUID_ATTRIBUTE}='{psGuid}'>{Convert.ToBase64String(data)}"); return result; } @@ -131,11 +124,7 @@ internal static string CreateSignalAckPacket(Guid psGuid) /// private static string CreatePSGuidPacket(string element, Guid psGuid) { - string result = string.Format(CultureInfo.InvariantCulture, - "<{0} {1}='{2}' />", - element, - PS_OUT_OF_PROC_PSGUID_ATTRIBUTE, - psGuid.ToString()); + string result = string.Create(CultureInfo.InvariantCulture, $"<{element} {PS_OUT_OF_PROC_PSGUID_ATTRIBUTE}='{psGuid}' />"); return result; } diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginShellSession.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginShellSession.cs index 51635922e0b..4f0af020ea4 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginShellSession.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginShellSession.cs @@ -468,11 +468,7 @@ internal override void ExecuteConnect( _remoteSession.ExecuteConnect(inputData, out outputData); // construct Xml to send back - string responseData = string.Format(System.Globalization.CultureInfo.InvariantCulture, - "<{0} xmlns=\"{1}\">{2}", - WSManNativeApi.PS_CONNECTRESPONSE_XML_TAG, - WSManNativeApi.PS_XML_NAMESPACE, - Convert.ToBase64String(outputData)); + string responseData = string.Create(System.Globalization.CultureInfo.InvariantCulture, $"<{WSManNativeApi.PS_CONNECTRESPONSE_XML_TAG} xmlns=\"{WSManNativeApi.PS_XML_NAMESPACE}\">{Convert.ToBase64String(outputData)}"); // TODO: currently using OperationComplete to report back the responseXml. This will need to change to use WSManReportObject // that is currently internal. diff --git a/src/System.Management.Automation/help/HelpCommentsParser.cs b/src/System.Management.Automation/help/HelpCommentsParser.cs index 36d0cb6450e..87da494dfcf 100644 --- a/src/System.Management.Automation/help/HelpCommentsParser.cs +++ b/src/System.Management.Automation/help/HelpCommentsParser.cs @@ -361,9 +361,7 @@ internal XmlDocument BuildXmlFromComments() // The title is automatically generated XmlElement title = _doc.CreateElement("maml:title", mamlURI); - string titleStr = string.Format(CultureInfo.InvariantCulture, - "\t\t\t\t-------------------------- {0} {1} --------------------------", - HelpDisplayStrings.ExampleUpperCase, count++); + string titleStr = string.Create(CultureInfo.InvariantCulture, $"\t\t\t\t-------------------------- {HelpDisplayStrings.ExampleUpperCase} {count++} --------------------------"); XmlText title_text = _doc.CreateTextNode(titleStr); example_node.AppendChild(title).AppendChild(title_text); diff --git a/src/System.Management.Automation/utils/tracing/SysLogProvider.cs b/src/System.Management.Automation/utils/tracing/SysLogProvider.cs index f3ee184485e..e1dec75ab16 100755 --- a/src/System.Management.Automation/utils/tracing/SysLogProvider.cs +++ b/src/System.Management.Automation/utils/tracing/SysLogProvider.cs @@ -288,11 +288,7 @@ public void LogTransfer(Guid parentActivityId) { // NOTE: always log int threadId = Environment.CurrentManagedThreadId; - string message = string.Format(CultureInfo.InvariantCulture, - "({0}:{1:X}:{2:X}) [Transfer]:{3} {4}", - PSVersionInfo.GitCommitId, threadId, PSChannel.Operational, - parentActivityId.ToString("B"), - Activity.ToString("B")); + string message = string.Create(CultureInfo.InvariantCulture, $"({PSVersionInfo.GitCommitId}:{threadId:X}:{PSChannel.Operational:X}) [Transfer]:{parentActivityId.ToString("B")} {Activity.ToString("B")}"); NativeMethods.SysLog(NativeMethods.SysLogPriority.Info, message); } @@ -307,9 +303,7 @@ public void SetActivity(Guid activity) Activity = activity; // NOTE: always log - string message = string.Format(CultureInfo.InvariantCulture, - "({0:X}:{1:X}:{2:X}) [Activity] {3}", - PSVersionInfo.GitCommitId, threadId, PSChannel.Operational, activity.ToString("B")); + string message = string.Create(CultureInfo.InvariantCulture, $"({PSVersionInfo.GitCommitId:X}:{threadId:X}:{PSChannel.Operational:X}) [Activity] {activity.ToString("B")}"); NativeMethods.SysLog(NativeMethods.SysLogPriority.Info, message); } @@ -333,9 +327,7 @@ public void Log(PSEventId eventId, PSChannel channel, PSTask task, PSOpcode opco sb.Clear(); // add the message preamble - sb.AppendFormat(CultureInfo.InvariantCulture, - "({0}:{1:X}:{2:X}) [{3:G}:{4:G}.{5:G}.{6:G}] ", - PSVersionInfo.GitCommitId, threadId, channel, eventId, task, opcode, level); + sb.Append(CultureInfo.InvariantCulture, $"({PSVersionInfo.GitCommitId}:{threadId:X}:{channel:X}) [{eventId:G}:{task:G}.{opcode:G}.{level:G}] "); // add the message GetEventMessage(sb, eventId, args); diff --git a/src/TypeCatalogGen/TypeCatalogGen.cs b/src/TypeCatalogGen/TypeCatalogGen.cs index 8749c19814b..aff32f6f82f 100644 --- a/src/TypeCatalogGen/TypeCatalogGen.cs +++ b/src/TypeCatalogGen/TypeCatalogGen.cs @@ -257,9 +257,7 @@ private static string GetAssemblyStrongName(MetadataReader metadataReader) // Convert bytes to hex format strings in lower case. string publicKeyTokenString = BitConverter.ToString(publicKeyTokenBytes).Replace("-", string.Empty).ToLowerInvariant(); - string strongAssemblyName = string.Format(CultureInfo.InvariantCulture, - "{0}, Version={1}, Culture={2}, PublicKeyToken={3}", - asmName, asmVersion, asmCulture, publicKeyTokenString); + string strongAssemblyName = string.Create(CultureInfo.InvariantCulture, $"{asmName}, Version={asmVersion}, Culture={asmCulture}, PublicKeyToken={publicKeyTokenString}"); return strongAssemblyName; } From 4919014484af3f1e4ca0abee246c5e13e04fb833 Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Tue, 24 Jan 2023 14:26:17 -0800 Subject: [PATCH 317/779] Update metadata and readme for next releases (#19014) --- README.md | 54 ++++++++++++++++++++++----------------------- tools/metadata.json | 6 ++--- 2 files changed, 30 insertions(+), 30 deletions(-) diff --git a/README.md b/README.md index ba40324d7b7..f054e00cd54 100644 --- a/README.md +++ b/README.md @@ -64,33 +64,33 @@ You can also download the PowerShell binary archives for Windows, macOS and Linu | Windows (Arm) | [64-bit][rl-winarm64] (preview) | [64-bit][pv-winarm64] | [Instructions][in-arm] | | Raspbian (Arm) | [32-bit][rl-arm32]/[64-bit][rl-arm64] | [32-bit][pv-arm32]/[64-bit][pv-arm64] | [Instructions][in-raspbian] | -[lts-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.8/PowerShell-7.2.8-win-x86.msi -[lts-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.8/PowerShell-7.2.8-win-x64.msi -[lts-deb]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.8/powershell-lts_7.2.8-1.deb_amd64.deb -[lts-rh]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.8/powershell-lts-7.2.8-1.rh.x86_64.rpm -[lts-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.8/powershell-lts-7.2.8-osx-x64.pkg -[lts-macos-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.8/powershell-lts-7.2.8-osx-arm64.pkg - -[rl-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.1/PowerShell-7.3.1-win-x64.msi -[rl-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.1/PowerShell-7.3.1-win-x86.msi -[rl-ubuntu20]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.1/powershell_7.3.1-1.deb_amd64.deb -[rl-ubuntu18]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.1/powershell_7.3.1-1.deb_amd64.deb -[rl-ubuntu16]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.1/powershell_7.3.1-1.deb_amd64.deb -[rl-debian9]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.1/powershell_7.3.1-1.deb_amd64.deb -[rl-debian10]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.1/powershell_7.3.1-1.deb_amd64.deb -[rl-debian11]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.1/powershell_7.3.1-1.deb_amd64.deb -[rl-centos]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.1/powershell-7.3.1-1.rh.x86_64.rpm -[rl-centos8]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.1/powershell-7.3.1-1.rh.x86_64.rpm -[rl-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.1/powershell-7.3.1-osx-x64.pkg -[rl-macos-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.1/powershell-7.3.1-osx-arm64.pkg -[rl-winarm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.1/PowerShell-7.3.1-win-arm64.zip -[rl-winx86-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.1/PowerShell-7.3.1-win-x86.zip -[rl-winx64-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.1/PowerShell-7.3.1-win-x64.zip -[rl-macos-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.1/powershell-7.3.1-osx-x64.tar.gz -[rl-macos-tar-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.1/powershell-7.3.1-osx-arm64.tar.gz -[rl-linux-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.1/powershell-7.3.1-linux-x64.tar.gz -[rl-arm32]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.1/powershell-7.3.1-linux-arm32.tar.gz -[rl-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.1/powershell-7.3.1-linux-arm64.tar.gz +[lts-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.9/PowerShell-7.2.9-win-x86.msi +[lts-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.9/PowerShell-7.2.9-win-x64.msi +[lts-deb]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.9/powershell-lts_7.2.9-1.deb_amd64.deb +[lts-rh]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.9/powershell-lts-7.2.9-1.rh.x86_64.rpm +[lts-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.9/powershell-lts-7.2.9-osx-x64.pkg +[lts-macos-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.9/powershell-lts-7.2.9-osx-arm64.pkg + +[rl-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.2/PowerShell-7.3.2-win-x64.msi +[rl-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.2/PowerShell-7.3.2-win-x86.msi +[rl-ubuntu20]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.2/powershell_7.3.2-1.deb_amd64.deb +[rl-ubuntu18]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.2/powershell_7.3.2-1.deb_amd64.deb +[rl-ubuntu16]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.2/powershell_7.3.2-1.deb_amd64.deb +[rl-debian9]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.2/powershell_7.3.2-1.deb_amd64.deb +[rl-debian10]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.2/powershell_7.3.2-1.deb_amd64.deb +[rl-debian11]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.2/powershell_7.3.2-1.deb_amd64.deb +[rl-centos]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.2/powershell-7.3.2-1.rh.x86_64.rpm +[rl-centos8]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.2/powershell-7.3.2-1.rh.x86_64.rpm +[rl-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.2/powershell-7.3.2-osx-x64.pkg +[rl-macos-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.2/powershell-7.3.2-osx-arm64.pkg +[rl-winarm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.2/PowerShell-7.3.2-win-arm64.zip +[rl-winx86-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.2/PowerShell-7.3.2-win-x86.zip +[rl-winx64-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.2/PowerShell-7.3.2-win-x64.zip +[rl-macos-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.2/powershell-7.3.2-osx-x64.tar.gz +[rl-macos-tar-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.2/powershell-7.3.2-osx-arm64.tar.gz +[rl-linux-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.2/powershell-7.3.2-linux-x64.tar.gz +[rl-arm32]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.2/powershell-7.3.2-linux-arm32.tar.gz +[rl-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.2/powershell-7.3.2-linux-arm64.tar.gz [rl-snap]: https://snapcraft.io/powershell [pv-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.1/PowerShell-7.4.0-preview.1-win-x64.msi diff --git a/tools/metadata.json b/tools/metadata.json index 31599f72322..94b577cd999 100644 --- a/tools/metadata.json +++ b/tools/metadata.json @@ -1,9 +1,9 @@ { - "StableReleaseTag": "v7.3.1", + "StableReleaseTag": "v7.3.2", "PreviewReleaseTag": "v7.4.0-preview.1", "ServicingReleaseTag": "v7.0.13", - "ReleaseTag": "v7.3.1", - "LTSReleaseTag" : ["v7.2.8", "v7.0.13"], + "ReleaseTag": "v7.3.2", + "LTSReleaseTag" : ["v7.2.9"], "NextReleaseTag": "v7.4.0-preview.2", "LTSRelease": { "Latest": false, "Package": false }, "StableRelease": { "Latest": false, "Package": false } From 44f2792a36a9884c4bfd823b3cd9444e14c81fc8 Mon Sep 17 00:00:00 2001 From: spaette <111918424+spaette@users.noreply.github.com> Date: Tue, 24 Jan 2023 22:09:54 -0600 Subject: [PATCH 318/779] Fix typo in dotnet-tools/README.md (#19021) --- test/perf/dotnet-tools/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/perf/dotnet-tools/README.md b/test/perf/dotnet-tools/README.md index 745130f9d6c..fa3ce3b2a78 100644 --- a/test/perf/dotnet-tools/README.md +++ b/test/perf/dotnet-tools/README.md @@ -4,8 +4,8 @@ The tools here are copied from [dotnet/performance](https://github.com/dotnet/pe the performance testing repository for the .NET runtime and framework libraries. - [BenchmarkDotNet.Extensions](https://github.com/dotnet/performance/tree/main/src/harness/BenchmarkDotNet.Extensions) - - It provides the needed extensions for running benckmarks, - such as the `RecommendedConfig` which defines the set of recommended configurations for running the dotnet benckmarks. + - It provides the needed extensions for running benchmarks, + such as the `RecommendedConfig` which defines the set of recommended configurations for running the dotnet benchmarks. - [Reporting](https://github.com/dotnet/performance/tree/main/src/tools/Reporting) - It provides additional result reporting support which may be useful to us when running our benchmarks in lab. From 1c27a0ceac21b2a76c2fc729266bdeb7ebb7a4bc Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Wed, 25 Jan 2023 03:34:44 -0800 Subject: [PATCH 319/779] Add progress to `Copy-Item` (#18735) --- .../host/msh/ProgressNode.cs | 2 +- .../namespaces/FileSystemProvider.cs | 85 +++++++++++++++++++ .../resources/FileSystemProviderStrings.resx | 6 ++ test/xUnit/csharp/test_Prediction.cs | 2 +- 4 files changed, 93 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressNode.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressNode.cs index c8f542052a1..4f51820524c 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressNode.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressNode.cs @@ -424,7 +424,7 @@ internal static bool IsMinimalProgressRenderingEnabled() sb.Append(secRemain); - if (PercentComplete > 0 && PercentComplete < 100 && barWidth > 0) + if (PercentComplete >= 0 && PercentComplete < 100 && barWidth > 0) { int barLength = PercentComplete * barWidth / 100; if (barLength >= barWidth) diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index 353aa3e918e..60631f7478b 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -6,6 +6,7 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; +using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; @@ -18,6 +19,7 @@ using System.Security; using System.Security.AccessControl; using System.Text; +using System.Threading.Tasks; using System.Xml; using System.Xml.XPath; @@ -58,6 +60,8 @@ public sealed partial class FileSystemProvider : NavigationCmdletProvider, // copy script will accommodate the new value. private const int FILETRANSFERSIZE = 4 * 1024 * 1024; + private const int COPY_FILE_ACTIVITY_ID = 0; + // The name of the key in an exception's Data dictionary when attempting // to copy an item onto itself. private const string SelfCopyDataKey = "SelfCopy"; @@ -3548,7 +3552,25 @@ protected override void CopyItem( } else // Copy-Item local { + if (Context != null && Context.ExecutionContext.SessionState.PSVariable.Get(SpecialVariables.ProgressPreferenceVarPath.UserPath).Value is ActionPreference progressPreference && progressPreference == ActionPreference.Continue) + { + { + Task.Run(() => + { + GetTotalFiles(path, recurse); + }); + _copyStopwatch.Start(); + } + } + CopyItemLocalOrToSession(path, destinationPath, recurse, Force, null); + if (_totalFiles > 0) + { + _copyStopwatch.Stop(); + var progress = new ProgressRecord(COPY_FILE_ACTIVITY_ID, " ", " "); + progress.RecordType = ProgressRecordType.Completed; + WriteProgress(progress); + } } } @@ -3556,6 +3578,47 @@ protected override void CopyItem( _excludeMatcher = null; } + private void GetTotalFiles(string path, bool recurse) + { + bool isContainer = IsItemContainer(path); + + try + { + if (isContainer) + { + var enumOptions = new EnumerationOptions() + { + IgnoreInaccessible = true, + AttributesToSkip = 0, + RecurseSubdirectories = recurse + }; + + var directory = new DirectoryInfo(path); + foreach (var file in directory.EnumerateFiles("*", enumOptions)) + { + if (!SessionStateUtilities.MatchesAnyWildcardPattern(file.Name, _excludeMatcher, defaultValue: false)) + { + _totalFiles++; + _totalBytes += file.Length; + } + } + } + else + { + var file = new FileInfo(path); + if (!SessionStateUtilities.MatchesAnyWildcardPattern(file.Name, _excludeMatcher, defaultValue: false)) + { + _totalFiles++; + _totalBytes += file.Length; + } + } + } + catch + { + // ignore exception + } + } + private void CopyItemFromRemoteSession(string path, string destinationPath, bool recurse, bool force, PSSession fromSession) { using (System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create()) @@ -3864,6 +3927,22 @@ private void CopyFileInfoItem(FileInfo file, string destinationPath, bool force, FileInfo result = new FileInfo(destinationPath); WriteItemObject(result, destinationPath, false); + + if (_totalFiles > 0) + { + _copiedFiles++; + _copiedBytes += file.Length; + double speed = (double)(_copiedBytes / 1024 / 1024) / _copyStopwatch.Elapsed.TotalSeconds; + var progress = new ProgressRecord( + COPY_FILE_ACTIVITY_ID, + StringUtil.Format(FileSystemProviderStrings.CopyingLocalFileActivity, _copiedFiles, _totalFiles), + StringUtil.Format(FileSystemProviderStrings.CopyingLocalBytesStatus, Utils.DisplayHumanReadableFileSize(_copiedBytes), Utils.DisplayHumanReadableFileSize(_totalBytes), speed) + ); + var percentComplete = (int)Math.Min(_copiedBytes * 100 / _totalBytes, 100); + progress.PercentComplete = percentComplete; + progress.RecordType = ProgressRecordType.Processing; + WriteProgress(progress); + } } else { @@ -4788,6 +4867,12 @@ private bool PathIsReservedDeviceName(string destinationPath, string errorId) return pathIsReservedDeviceName; } + private long _totalFiles; + private long _totalBytes; + private long _copiedFiles; + private long _copiedBytes; + private readonly Stopwatch _copyStopwatch = new Stopwatch(); + #endregion CopyItem #endregion ContainerCmdletProvider members diff --git a/src/System.Management.Automation/resources/FileSystemProviderStrings.resx b/src/System.Management.Automation/resources/FileSystemProviderStrings.resx index 436e03df32e..6ffbce6b884 100644 --- a/src/System.Management.Automation/resources/FileSystemProviderStrings.resx +++ b/src/System.Management.Automation/resources/FileSystemProviderStrings.resx @@ -339,4 +339,10 @@ The target and path cannot be the same. + + Copied {0} of {1} files + + + {0} of {1} ({2:0.0} MB/s) + diff --git a/test/xUnit/csharp/test_Prediction.cs b/test/xUnit/csharp/test_Prediction.cs index e69f5b21a9d..6c78cf3a58f 100644 --- a/test/xUnit/csharp/test_Prediction.cs +++ b/test/xUnit/csharp/test_Prediction.cs @@ -79,7 +79,7 @@ public SuggestionPackage GetSuggestion(PredictionClient client, PredictionContex { // The delay is exaggerated to make the test reliable. // xUnit must spin up a lot tasks, which makes the test unreliable when the time difference between 'delay' and 'timeout' is small. - Thread.Sleep(2000); + Thread.Sleep(3000); } // You can get the user input from the AST. From b195088c5a7af53ca61aa246c1a48628d32df48d Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Wed, 25 Jan 2023 09:46:47 -0800 Subject: [PATCH 320/779] Revert some of the interpolated string changes (#19018) --- .../Utils.cs | 8 --- .../FilterProviders/SearchTextParser.cs | 9 ++- .../FormatAndOutput/format-hex/Format-Hex.cs | 2 +- .../utility/ImplicitRemotingCommands.cs | 3 +- src/Microsoft.WSMan.Management/CredSSP.cs | 12 +++- .../DscSupport/CimDSCParser.cs | 24 +++++--- .../DisplayDatabase/typeDataXmlLoader.cs | 8 ++- .../typeDataXmlLoader_Views.cs | 7 ++- .../engine/CommandMetadata.cs | 8 ++- .../engine/GetCommandCommand.cs | 14 ++++- .../engine/ManagementObjectAdapter.cs | 6 +- .../engine/ParameterSetInfo.cs | 35 ++++------- .../engine/debugger/debugger.cs | 7 +-- .../engine/hostifaces/HostUtilities.cs | 13 +++- .../engine/interpreter/BranchLabel.cs | 2 +- .../engine/interpreter/LightCompiler.cs | 13 +++- .../engine/interpreter/LocalVariables.cs | 2 +- .../engine/interpreter/StackOperations.cs | 2 +- .../engine/parser/DebugViewWriter.cs | 7 ++- .../engine/parser/Parser.cs | 2 +- .../engine/parser/Position.cs | 4 +- .../engine/parser/token.cs | 33 ++++++++-- .../remoting/fanin/BaseTransportManager.cs | 8 ++- .../fanin/OutOfProcTransportManager.cs | 17 +++++- .../remoting/fanin/WSManPluginShellSession.cs | 7 ++- .../remoting/fanin/WSManTransportManager.cs | 28 +++++++-- .../engine/runtime/Binding/Binders.cs | 60 ++++++++++++++++--- .../engine/runtime/Operations/MiscOps.cs | 8 ++- .../help/CommandHelpProvider.cs | 12 +++- .../help/HelpCommentsParser.cs | 4 +- .../help/ProviderHelpProvider.cs | 12 +++- .../singleshell/config/MshSnapinInfo.cs | 8 ++- .../utils/tracing/SysLogProvider.cs | 14 ++++- test/perf/benchmarks/Engine.Compiler.cs | 2 +- .../CommandLineOptions.cs | 2 +- 35 files changed, 300 insertions(+), 103 deletions(-) diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/Utils.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/Utils.cs index be517c9864c..adcab254231 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/Utils.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/Utils.cs @@ -199,14 +199,6 @@ internal static string GetSourceCodeInformation(bool withFileName, int depth) { StackTrace trace = new(); StackFrame frame = trace.GetFrame(depth); - // if (withFileName) - // { - // return string.Create(CultureInfo.CurrentUICulture, $"{frame.GetFileName().}#{frame.GetFileLineNumber()}:{frame.GetMethod().Name}:"); - // } - // else - // { - // return string.Create(CultureInfo.CurrentUICulture, $"{frame.GetMethod()}:"); - // } return string.Create(CultureInfo.CurrentUICulture, $"{frame.GetMethod().DeclaringType.Name}::{frame.GetMethod().Name} "); } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchTextParser.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchTextParser.cs index 8900964fba2..2e0ac74e076 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchTextParser.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchTextParser.cs @@ -121,7 +121,7 @@ protected virtual string GetPattern() patterns.Add(rule.Pattern); } - patterns.Add(string.Create(CultureInfo.InvariantCulture, $"(?<{FullTextRuleGroupName}>){ValuePattern}")); + patterns.Add(string.Format(CultureInfo.InvariantCulture, "(?<{0}>){1}", FullTextRuleGroupName, ValuePattern)); return string.Join("|", patterns.ToArray()); } @@ -199,7 +199,12 @@ public SearchableRule(string uniqueId, SelectorFilterRule selectorFilterRule, Te this.UniqueId = uniqueId; this.selectorFilterRule = selectorFilterRule; this.childRule = childRule; - this.Pattern = string.Create(CultureInfo.InvariantCulture, $"(?<{uniqueId}>){Regex.Escape(selectorFilterRule.DisplayName)}\\s*:\\s*{SearchTextParser.ValuePattern}"); + this.Pattern = string.Format( + CultureInfo.InvariantCulture, + "(?<{0}>){1}\\s*:\\s*{2}", + uniqueId, + Regex.Escape(selectorFilterRule.DisplayName), + SearchTextParser.ValuePattern); } /// diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-hex/Format-Hex.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-hex/Format-Hex.cs index b6a6d024396..de73b2155a6 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-hex/Format-Hex.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-hex/Format-Hex.cs @@ -296,7 +296,7 @@ private void ProcessString(string originalString) private static readonly Random _idGenerator = new(); private static string GetGroupLabel(Type inputType) - => string.Create(System.Globalization.CultureInfo.InvariantCulture, $"{inputType.Name} ({inputType.FullName}) <{_idGenerator.Next():X8}>"); + => string.Format("{0} ({1}) <{2:X8}>", inputType.Name, inputType.FullName, _idGenerator.Next()); private void FlushInputBuffer() { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs index 6d51d972916..2e2e5acbfe3 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs @@ -2594,7 +2594,8 @@ private string GenerateConnectionStringForNewRunspace() } else { - return string.Create(CultureInfo.InvariantCulture, $"-connectionUri '{CodeGeneration.EscapeSingleQuotedStringContent(GetConnectionString())}'"); + string connectionString = CodeGeneration.EscapeSingleQuotedStringContent(GetConnectionString()); + return string.Create(CultureInfo.InvariantCulture, $"-connectionUri '{connectionString}'"); } } diff --git a/src/Microsoft.WSMan.Management/CredSSP.cs b/src/Microsoft.WSMan.Management/CredSSP.cs index 13e99c04f1f..c59daa39bfc 100644 --- a/src/Microsoft.WSMan.Management/CredSSP.cs +++ b/src/Microsoft.WSMan.Management/CredSSP.cs @@ -200,7 +200,10 @@ private void DisableServerSideSettings() return; } - string inputXml = string.Create(CultureInfo.InvariantCulture, $@"false"); + string inputXml = string.Format( + CultureInfo.InvariantCulture, + @"false", + helper.Service_CredSSP_XMLNmsp); m_SessionObj.Put(helper.Service_CredSSP_Uri, inputXml, 0); } @@ -591,8 +594,11 @@ private void EnableServerSideSettings() try { XmlDocument xmldoc = new XmlDocument(); - string newxmlcontent = string.Create(CultureInfo.InvariantCulture, $@"true"); - + string newxmlcontent = string.Format( + CultureInfo.InvariantCulture, + @"true", + helper.Service_CredSSP_XMLNmsp); + // push the xml string with credssp enabled xmldoc.LoadXml(m_SessionObj.Put(helper.Service_CredSSP_Uri, newxmlcontent, 0)); WriteObject(xmldoc.FirstChild); diff --git a/src/System.Management.Automation/DscSupport/CimDSCParser.cs b/src/System.Management.Automation/DscSupport/CimDSCParser.cs index ab7536b7e4f..fb903557655 100644 --- a/src/System.Management.Automation/DscSupport/CimDSCParser.cs +++ b/src/System.Management.Automation/DscSupport/CimDSCParser.cs @@ -2532,9 +2532,12 @@ private static void ProcessMembers(StringBuilder sb, List embeddedInstan out embeddedInstanceType, embeddedInstanceTypes, ref enumNames); } + string mofAttr = MapAttributesToMof(enumNames, attributes, embeddedInstanceType); string arrayAffix = isArrayType ? "[]" : string.Empty; - sb.Append(CultureInfo.InvariantCulture, $" {MapAttributesToMof(enumNames, attributes, embeddedInstanceType)}{mofType} {member.Name}{arrayAffix};\n"); + sb.Append( + CultureInfo.InvariantCulture, + $" {mofAttr}{mofType} {member.Name}{arrayAffix};\n"); } } @@ -3082,16 +3085,21 @@ private static void ProcessMembers(Type type, StringBuilder sb, List emb } // TODO - validate type and name - bool isArrayType; - string embeddedInstanceType; - string mofType = MapTypeToMofType(memberType, member.Name, className, out isArrayType, out embeddedInstanceType, + string mofType = MapTypeToMofType( + memberType, + member.Name, + className, + out bool isArrayType, + out string embeddedInstanceType, embeddedInstanceTypes); + + var enumNames = memberType.IsEnum ? Enum.GetNames(memberType) : null; + string mofAttr = MapAttributesToMof(enumNames, member.GetCustomAttributes(true), embeddedInstanceType); string arrayAffix = isArrayType ? "[]" : string.Empty; - var enumNames = memberType.IsEnum - ? Enum.GetNames(memberType) - : null; - sb.Append(CultureInfo.InvariantCulture, $" {MapAttributesToMof(enumNames, member.GetCustomAttributes(true), embeddedInstanceType)}{mofType} {member.Name}{arrayAffix};\n"); + sb.Append( + CultureInfo.InvariantCulture, + $" {mofAttr}{mofType} {member.Name}{arrayAffix};\n"); } } diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs index d13177af484..5a241d0fed1 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs @@ -436,7 +436,13 @@ private void LoadData(ExtendedTypeDefinition typeDefinition, TypeInfoDataBase db ViewDefinition view = LoadViewFromObjectModel(typeDefinition.TypeNames, formatView, viewIndex++); if (view != null) { - ReportTrace(string.Create(CultureInfo.InvariantCulture, $"{ControlBase.GetControlShapeName(view.mainControl)} view {view.name} is loaded from the 'FormatViewDefinition' at index {viewIndex - 1} in 'ExtendedTypeDefinition' with type name {typeDefinition.TypeName}")); + ReportTrace(string.Format( + CultureInfo.InvariantCulture, + "{0} view {1} is loaded from the 'FormatViewDefinition' at index {2} in 'ExtendedTypeDefinition' with type name {3}", + ControlBase.GetControlShapeName(view.mainControl), + view.name, + viewIndex - 1, + typeDefinition.TypeName)); // we are fine, add the view to the list db.viewDefinitionsSection.viewDefinitionList.Add(view); diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Views.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Views.cs index a92f7a6b105..c6d191284e6 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Views.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Views.cs @@ -27,7 +27,12 @@ private void LoadViewDefinitions(TypeInfoDataBase db, XmlNode viewDefinitionsNod ViewDefinition view = LoadView(n, index++); if (view != null) { - ReportTrace(string.Create(CultureInfo.InvariantCulture, $"{ControlBase.GetControlShapeName(view.mainControl)} view {view.name} is loaded from file {view.loadingInfo.filePath}")); + ReportTrace(string.Format( + CultureInfo.InvariantCulture, + "{0} view {1} is loaded from file {2}", + ControlBase.GetControlShapeName(view.mainControl), + view.name, + view.loadingInfo.filePath)); // we are fine, add the view to the list db.viewDefinitionsSection.viewDefinitionList.Add(view); } diff --git a/src/System.Management.Automation/engine/CommandMetadata.cs b/src/System.Management.Automation/engine/CommandMetadata.cs index aba83a1632d..df767f714b0 100644 --- a/src/System.Management.Automation/engine/CommandMetadata.cs +++ b/src/System.Management.Automation/engine/CommandMetadata.cs @@ -1009,6 +1009,7 @@ internal string GetBeginBlock() commandOrigin = string.Empty; } + string wrappedCommand = CodeGeneration.EscapeSingleQuotedStringContent(_wrappedCommand); if (_wrappedAnyCmdlet) { result = string.Create(CultureInfo.InvariantCulture, $@" @@ -1019,7 +1020,7 @@ internal string GetBeginBlock() $PSBoundParameters['OutBuffer'] = 1 }} - $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('{CodeGeneration.EscapeSingleQuotedStringContent(_wrappedCommand)}', [System.Management.Automation.CommandTypes]::{_wrappedCommandType}) + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('{wrappedCommand}', [System.Management.Automation.CommandTypes]::{_wrappedCommandType}) $scriptCmd = {{& $wrappedCmd @PSBoundParameters }} $steppablePipeline = $scriptCmd.GetSteppablePipeline({commandOrigin}) @@ -1033,7 +1034,7 @@ internal string GetBeginBlock() { result = string.Create(CultureInfo.InvariantCulture, $@" try {{ - $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('{CodeGeneration.EscapeSingleQuotedStringContent(_wrappedCommand)}', [System.Management.Automation.CommandTypes]::{_wrappedCommandType}) + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('{wrappedCommand}', [System.Management.Automation.CommandTypes]::{_wrappedCommandType}) $PSBoundParameters.Add('$args', $args) $scriptCmd = {{& $wrappedCmd @PSBoundParameters }} @@ -1066,9 +1067,10 @@ internal string GetProcessBlock() internal string GetDynamicParamBlock() { + string wrappedCommand = CodeGeneration.EscapeSingleQuotedStringContent(_wrappedCommand); return string.Create(CultureInfo.InvariantCulture, $@" try {{ - $targetCmd = $ExecutionContext.InvokeCommand.GetCommand('{CodeGeneration.EscapeSingleQuotedStringContent(_wrappedCommand)}', [System.Management.Automation.CommandTypes]::{_wrappedCommandType}, $PSBoundParameters) + $targetCmd = $ExecutionContext.InvokeCommand.GetCommand('{wrappedCommand}', [System.Management.Automation.CommandTypes]::{_wrappedCommandType}, $PSBoundParameters) $dynamicParams = @($targetCmd.Parameters.GetEnumerator() | Microsoft.PowerShell.Core\Where-Object {{ $_.Value.IsDynamic }}) if ($dynamicParams.Length -gt 0) {{ diff --git a/src/System.Management.Automation/engine/GetCommandCommand.cs b/src/System.Management.Automation/engine/GetCommandCommand.cs index a3263799cda..81675d7b663 100644 --- a/src/System.Management.Automation/engine/GetCommandCommand.cs +++ b/src/System.Management.Automation/engine/GetCommandCommand.cs @@ -614,7 +614,12 @@ private PSObject GetSyntaxObject(CommandInfo command) switch (command) { case ExternalScriptInfo externalScript: - replacedSyntax = string.Create(CultureInfo.InvariantCulture, $"{aliasName} (alias) -> {externalScript.Path}{Environment.NewLine}{Environment.NewLine}{command.Syntax.Replace(command.Name, aliasName)}"); + replacedSyntax = string.Format( + "{0} (alias) -> {1}{2}{3}", + aliasName, + string.Format("{0}{1}", externalScript.Path, Environment.NewLine), + Environment.NewLine, + command.Syntax.Replace(command.Name, aliasName)); break; case ApplicationInfo app: replacedSyntax = app.Path; @@ -626,7 +631,12 @@ private PSObject GetSyntaxObject(CommandInfo command) } else { - replacedSyntax = string.Create(CultureInfo.InvariantCulture, $"{aliasName} (alias) -> {command.Name}{Environment.NewLine}{command.Syntax.Replace(command.Name, aliasName)}"); + replacedSyntax = string.Format( + "{0} (alias) -> {1}{2}{3}", + aliasName, + command.Name, + Environment.NewLine, + command.Syntax.Replace(command.Name, aliasName)); } break; diff --git a/src/System.Management.Automation/engine/ManagementObjectAdapter.cs b/src/System.Management.Automation/engine/ManagementObjectAdapter.cs index cfe7ce32ee4..aa1c151e0e3 100644 --- a/src/System.Management.Automation/engine/ManagementObjectAdapter.cs +++ b/src/System.Management.Automation/engine/ManagementObjectAdapter.cs @@ -577,7 +577,11 @@ protected static string GetEmbeddedObjectTypeName(PropertyData pData) try { string cimType = (string)pData.Qualifiers["cimtype"].Value; - result = string.Create(CultureInfo.InvariantCulture, $"{typeof(ManagementObject).FullName}#{cimType.Replace("object:", string.Empty)}"); + result = string.Format( + CultureInfo.InvariantCulture, + "{0}#{1}", + typeof(ManagementObject).FullName, + cimType.Replace("object:", string.Empty)); } catch (ManagementException) { diff --git a/src/System.Management.Automation/engine/ParameterSetInfo.cs b/src/System.Management.Automation/engine/ParameterSetInfo.cs index 2574c086b53..5d81b8553cf 100644 --- a/src/System.Management.Automation/engine/ParameterSetInfo.cs +++ b/src/System.Management.Automation/engine/ParameterSetInfo.cs @@ -238,14 +238,7 @@ private static void AppendFormatCommandParameterInfo(CommandParameterInfo parame if (parameter.ParameterType == typeof(SwitchParameter)) { - if (parameter.IsMandatory) - { - result.Append($"-{parameter.Name}"); - } - else - { - result.Append($"[-{parameter.Name}]"); - } + result.AppendFormat(CultureInfo.InvariantCulture, parameter.IsMandatory ? "-{0}" : "[-{0}]", parameter.Name); } else { @@ -253,25 +246,19 @@ private static void AppendFormatCommandParameterInfo(CommandParameterInfo parame if (parameter.IsMandatory) { - if (parameter.Position != int.MinValue) - { - result.Append($"[-{parameter.Name}] <{parameterTypeString}>"); - } - else - { - result.Append($"-{parameter.Name} <{parameterTypeString}>"); - } + result.AppendFormat( + CultureInfo.InvariantCulture, + parameter.Position != int.MinValue ? "[-{0}] <{1}>" : "-{0} <{1}>", + parameter.Name, + parameterTypeString); } else { - if (parameter.Position != int.MinValue) - { - result.Append($"[[-{parameter.Name}] <{parameterTypeString}>]"); - } - else - { - result.Append($"[-{parameter.Name} <{parameterTypeString}>]"); - } + result.AppendFormat( + CultureInfo.InvariantCulture, + parameter.Position != int.MinValue ? "[[-{0}] <{1}>]" : "[-{0} <{1}>]", + parameter.Name, + parameterTypeString); } } } diff --git a/src/System.Management.Automation/engine/debugger/debugger.cs b/src/System.Management.Automation/engine/debugger/debugger.cs index c7b116a4d5f..059c68643ab 100644 --- a/src/System.Management.Automation/engine/debugger/debugger.cs +++ b/src/System.Management.Automation/engine/debugger/debugger.cs @@ -5301,10 +5301,9 @@ private void DisplayScript(PSHost host, IList output, InvocationInfo i for (int lineNumber = start; lineNumber <= _lines.Length && lineNumber < start + count; lineNumber++) { WriteLine( - lineNumber == invocationInfo.ScriptLineNumber ? - string.Create(CultureInfo.CurrentCulture, $"{lineNumber,5}:* { _lines[lineNumber - 1]}") - : - string.Create(CultureInfo.CurrentCulture, $"{lineNumber,5}: { _lines[lineNumber - 1]}"), + lineNumber == invocationInfo.ScriptLineNumber + ? string.Format(CultureInfo.CurrentCulture, "{0,5}:* {1}", lineNumber, _lines[lineNumber - 1]) + : string.Format(CultureInfo.CurrentCulture, "{0,5}: {1}", lineNumber, _lines[lineNumber - 1]), host, output); diff --git a/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs b/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs index 63ea2e9dc4b..1f88f48eaf5 100644 --- a/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs +++ b/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs @@ -639,10 +639,19 @@ runspace.ConnectionInfo is VMConnectionInfo || !string.IsNullOrEmpty(sshConnectionInfo.UserName) && !System.Environment.UserName.Equals(sshConnectionInfo.UserName, StringComparison.Ordinal)) { - return string.Create(CultureInfo.InvariantCulture, $"[{sshConnectionInfo.UserName}@{sshConnectionInfo.ComputerName}]: {basePrompt}"); + return string.Format( + CultureInfo.InvariantCulture, + "[{0}@{1}]: {2}", + sshConnectionInfo.UserName, + sshConnectionInfo.ComputerName, + basePrompt); } - return string.Create(CultureInfo.InvariantCulture, $"[{runspace.ConnectionInfo.ComputerName}]: {basePrompt}"); + return string.Format( + CultureInfo.InvariantCulture, + "[{0}]: {1}", + runspace.ConnectionInfo.ComputerName, + basePrompt); } /// diff --git a/src/System.Management.Automation/engine/interpreter/BranchLabel.cs b/src/System.Management.Automation/engine/interpreter/BranchLabel.cs index d8999084232..1bae16783a9 100644 --- a/src/System.Management.Automation/engine/interpreter/BranchLabel.cs +++ b/src/System.Management.Automation/engine/interpreter/BranchLabel.cs @@ -34,7 +34,7 @@ public RuntimeLabel(int index, int continuationStackDepth, int stackDepth) public override string ToString() { - return string.Create(CultureInfo.InvariantCulture, $"->{Index} C({ContinuationStackDepth}) S({StackDepth})"); + return string.Format(CultureInfo.InvariantCulture, "->{0} C({1}) S({2})", Index, ContinuationStackDepth, StackDepth); } } diff --git a/src/System.Management.Automation/engine/interpreter/LightCompiler.cs b/src/System.Management.Automation/engine/interpreter/LightCompiler.cs index 1243b1b6e3e..700850fb394 100644 --- a/src/System.Management.Automation/engine/interpreter/LightCompiler.cs +++ b/src/System.Management.Automation/engine/interpreter/LightCompiler.cs @@ -92,7 +92,14 @@ internal bool IsInsideFinallyBlock(int index) public override string ToString() { - return string.Create(CultureInfo.InvariantCulture, $"{(IsFault ? "fault" : "catch(" + ExceptionType.Name + ")")} [{StartIndex}-{EndIndex}] [{HandlerStartIndex}->{HandlerEndIndex}]"); + return string.Format( + CultureInfo.InvariantCulture, + "{0} [{1}-{2}] [{3}->{4}]", + IsFault ? "fault" : "catch(" + ExceptionType.Name + ")", + StartIndex, + EndIndex, + HandlerStartIndex, + HandlerEndIndex); } } @@ -227,11 +234,11 @@ public override string ToString() { if (IsClear) { - return string.Create(CultureInfo.InvariantCulture, $"{Index}: clear"); + return string.Format(CultureInfo.InvariantCulture, "{0}: clear", Index); } else { - return string.Create(CultureInfo.InvariantCulture, $"{Index}: [{StartLine}-{EndLine}] '{FileName}'"); + return string.Format(CultureInfo.InvariantCulture, "{0}: [{1}-{2}] '{3}'", Index, StartLine, EndLine, FileName); } } } diff --git a/src/System.Management.Automation/engine/interpreter/LocalVariables.cs b/src/System.Management.Automation/engine/interpreter/LocalVariables.cs index af916482260..0c1f6416741 100644 --- a/src/System.Management.Automation/engine/interpreter/LocalVariables.cs +++ b/src/System.Management.Automation/engine/interpreter/LocalVariables.cs @@ -77,7 +77,7 @@ internal Expression LoadFromArray(Expression frameData, Expression closure) public override string ToString() { - return string.Create(CultureInfo.InvariantCulture, $"{Index}: {(IsBoxed ? "boxed" : null)} {(InClosure ? "in closure" : null)}"); + return string.Format(CultureInfo.InvariantCulture, "{0}: {1} {2}", Index, IsBoxed ? "boxed" : null, InClosure ? "in closure" : null); } } diff --git a/src/System.Management.Automation/engine/interpreter/StackOperations.cs b/src/System.Management.Automation/engine/interpreter/StackOperations.cs index 74f926a37a3..51a5f03348c 100644 --- a/src/System.Management.Automation/engine/interpreter/StackOperations.cs +++ b/src/System.Management.Automation/engine/interpreter/StackOperations.cs @@ -60,7 +60,7 @@ public override int Run(InterpretedFrame frame) public override string ToDebugString(int instructionIndex, object cookie, Func labelIndexer, IList objects) { - return string.Create(CultureInfo.InvariantCulture, $"LoadCached({_index}: {objects[(int)_index]})"); + return string.Format(CultureInfo.InvariantCulture, "LoadCached({0}: {1})", _index, objects[(int)_index]); } public override string ToString() diff --git a/src/System.Management.Automation/engine/parser/DebugViewWriter.cs b/src/System.Management.Automation/engine/parser/DebugViewWriter.cs index 091ded80e19..cb280bdaf61 100644 --- a/src/System.Management.Automation/engine/parser/DebugViewWriter.cs +++ b/src/System.Management.Automation/engine/parser/DebugViewWriter.cs @@ -447,7 +447,12 @@ protected override Expression VisitParameter(ParameterExpression node) { protected override Expression VisitLambda(Expression node) { Out( - string.Create(CultureInfo.CurrentCulture, $".Lambda {GetLambdaName(node)}<{node.Type}>") + string.Format(CultureInfo.CurrentCulture, + "{0} {1}<{2}>", + ".Lambda", + GetLambdaName(node), + node.Type.ToString() + ) ); if (_lambdas == null) { diff --git a/src/System.Management.Automation/engine/parser/Parser.cs b/src/System.Management.Automation/engine/parser/Parser.cs index b8afb42472b..f110845afdf 100644 --- a/src/System.Management.Automation/engine/parser/Parser.cs +++ b/src/System.Management.Automation/engine/parser/Parser.cs @@ -8044,7 +8044,7 @@ private static void AssertErrorIdCorrespondsToMsgString(string errorId, string e } } - Diagnostics.Assert(msgCorrespondsToString, string.Create(CultureInfo.InvariantCulture, $"Parser error ID \"{errorId}\" must correspond to the error message \"{errorMsg}\"")); + Diagnostics.Assert(msgCorrespondsToString, $"Parser error ID \"{errorId}\" must correspond to the error message \"{errorMsg}\""); } private static object[] arrayOfOneArg diff --git a/src/System.Management.Automation/engine/parser/Position.cs b/src/System.Management.Automation/engine/parser/Position.cs index bc2aab73d9d..571a0c587f4 100644 --- a/src/System.Management.Automation/engine/parser/Position.cs +++ b/src/System.Management.Automation/engine/parser/Position.cs @@ -766,7 +766,9 @@ public string Text _endPosition.ColumnNumber - _startPosition.ColumnNumber); } - return string.Create(CultureInfo.InvariantCulture, $"{_startPosition.Line.AsSpan(_startPosition.ColumnNumber)}...{ _endPosition.Line.AsSpan(0, _endPosition.ColumnNumber)}"); + var start = _startPosition.Line.AsSpan(_startPosition.ColumnNumber); + var end = _endPosition.Line.AsSpan(0, _endPosition.ColumnNumber); + return string.Create(CultureInfo.InvariantCulture, $"{start}...{end}"); } else { diff --git a/src/System.Management.Automation/engine/parser/token.cs b/src/System.Management.Automation/engine/parser/token.cs index 85862c01395..11d0a632cb5 100644 --- a/src/System.Management.Automation/engine/parser/token.cs +++ b/src/System.Management.Automation/engine/parser/token.cs @@ -1290,7 +1290,14 @@ internal NumberToken(InternalScriptExtent scriptExtent, object value, TokenFlags internal override string ToDebugString(int indent) { - return string.Create(CultureInfo.InvariantCulture, $"{StringUtil.Padding(indent)}{Kind}: <{Text}> Value:<{_value}> Type:<{_value.GetType().Name}>"); + return string.Format( + CultureInfo.InvariantCulture, + "{0}{1}: <{2}> Value:<{3}> Type:<{4}>", + StringUtil.Padding(indent), + Kind, + Text, + _value, + _value.GetType().Name); } /// @@ -1331,7 +1338,13 @@ internal ParameterToken(InternalScriptExtent scriptExtent, string parameterName, internal override string ToDebugString(int indent) { - return string.Create(CultureInfo.InvariantCulture, $"{StringUtil.Padding(indent)}{Kind}: <-{_parameterName}{(_usedColon ? ":" : string.Empty)}>"); + return string.Format( + CultureInfo.InvariantCulture, + "{0}{1}: <-{2}{3}>", + StringUtil.Padding(indent), + Kind, + _parameterName, + _usedColon ? ":" : string.Empty); } } @@ -1358,7 +1371,13 @@ internal VariableToken(InternalScriptExtent scriptExtent, VariablePath path, Tok internal override string ToDebugString(int indent) { - return string.Create(CultureInfo.InvariantCulture, $"{StringUtil.Padding(indent)}{Kind}: <{Text}> Name:<{Name}>"); + return string.Format( + CultureInfo.InvariantCulture, + "{0}{1}: <{2}> Name:<{3}>", + StringUtil.Padding(indent), + Kind, + Text, + Name); } } @@ -1380,7 +1399,13 @@ internal StringToken(InternalScriptExtent scriptExtent, TokenKind kind, TokenFla internal override string ToDebugString(int indent) { - return string.Create(CultureInfo.InvariantCulture, $"{StringUtil.Padding(indent)}{Kind}: <{Text}> Value:<{Value}>"); + return string.Format( + CultureInfo.InvariantCulture, + "{0}{1}: <{2}> Value:<{3}>", + StringUtil.Padding(indent), + Kind, + Text, + Value); } } diff --git a/src/System.Management.Automation/engine/remoting/fanin/BaseTransportManager.cs b/src/System.Management.Automation/engine/remoting/fanin/BaseTransportManager.cs index af13d2fab46..2a9d68bd55f 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/BaseTransportManager.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/BaseTransportManager.cs @@ -363,8 +363,12 @@ internal void ProcessRawData(byte[] data, if (!shouldProcess) { // we dont support this stream..so ignore the data - Dbg.Assert(false, - string.Create(CultureInfo.InvariantCulture, $"Data should be from one of the streams : {WSManNativeApi.WSMAN_STREAM_ID_STDIN} or {WSManNativeApi.WSMAN_STREAM_ID_STDOUT} or {WSManNativeApi.WSMAN_STREAM_ID_PROMPTRESPONSE}")); + Dbg.Assert(false, string.Format( + CultureInfo.InvariantCulture, + "Data should be from one of the streams : {0} or {1} or {2}", + WSManNativeApi.WSMAN_STREAM_ID_STDIN, + WSManNativeApi.WSMAN_STREAM_ID_STDOUT, + WSManNativeApi.WSMAN_STREAM_ID_PROMPTRESPONSE)); s_baseTracer.WriteLine("{0} is not a valid stream", stream); } // process data diff --git a/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs b/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs index 0759f7bcb70..96a8b833885 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs @@ -75,7 +75,15 @@ static OutOfProcessUtils() internal static string CreateDataPacket(byte[] data, DataPriorityType streamType, Guid psGuid) { - string result = string.Create(CultureInfo.InvariantCulture, $"<{PS_OUT_OF_PROC_DATA_TAG} {PS_OUT_OF_PROC_STREAM_ATTRIBUTE}='{streamType}' {PS_OUT_OF_PROC_PSGUID_ATTRIBUTE}='{psGuid}'>{Convert.ToBase64String(data)}"); + string result = string.Format( + CultureInfo.InvariantCulture, + "<{0} {1}='{2}' {3}='{4}'>{5}", + PS_OUT_OF_PROC_DATA_TAG, + PS_OUT_OF_PROC_STREAM_ATTRIBUTE, + streamType.ToString(), + PS_OUT_OF_PROC_PSGUID_ATTRIBUTE, + psGuid.ToString(), + Convert.ToBase64String(data)); return result; } @@ -124,7 +132,12 @@ internal static string CreateSignalAckPacket(Guid psGuid) /// private static string CreatePSGuidPacket(string element, Guid psGuid) { - string result = string.Create(CultureInfo.InvariantCulture, $"<{element} {PS_OUT_OF_PROC_PSGUID_ATTRIBUTE}='{psGuid}' />"); + string result = string.Format( + CultureInfo.InvariantCulture, + "<{0} {1}='{2}' />", + element, + PS_OUT_OF_PROC_PSGUID_ATTRIBUTE, + psGuid.ToString()); return result; } diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginShellSession.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginShellSession.cs index 4f0af020ea4..c7bf908d56b 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginShellSession.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginShellSession.cs @@ -468,7 +468,12 @@ internal override void ExecuteConnect( _remoteSession.ExecuteConnect(inputData, out outputData); // construct Xml to send back - string responseData = string.Create(System.Globalization.CultureInfo.InvariantCulture, $"<{WSManNativeApi.PS_CONNECTRESPONSE_XML_TAG} xmlns=\"{WSManNativeApi.PS_XML_NAMESPACE}\">{Convert.ToBase64String(outputData)}"); + string responseData = string.Format( + System.Globalization.CultureInfo.InvariantCulture, + "<{0} xmlns=\"{1}\">{2}", + WSManNativeApi.PS_CONNECTRESPONSE_XML_TAG, + WSManNativeApi.PS_XML_NAMESPACE, + Convert.ToBase64String(outputData)); // TODO: currently using OperationComplete to report back the responseXml. This will need to change to use WSManReportObject // that is currently internal. diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManTransportManager.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManTransportManager.cs index b8e417da547..d344e5c386e 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManTransportManager.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManTransportManager.cs @@ -925,7 +925,12 @@ internal override void ConnectAsync() { // WSMan expects the data to be in XML format (which is text + xml tags) // so convert byte[] into base64 encoded format - string base64EncodedDataInXml = string.Create(CultureInfo.InvariantCulture, $"<{WSManNativeApi.PS_CONNECT_XML_TAG} xmlns=\"{WSManNativeApi.PS_XML_NAMESPACE}\">{Convert.ToBase64String(additionalData)}"); + string base64EncodedDataInXml = string.Format( + CultureInfo.InvariantCulture, + "<{0} xmlns=\"{1}\">{2}", + WSManNativeApi.PS_CONNECT_XML_TAG, + WSManNativeApi.PS_XML_NAMESPACE, + Convert.ToBase64String(additionalData)); _openContent = new WSManNativeApi.WSManData_ManToUn(base64EncodedDataInXml); } @@ -1093,7 +1098,12 @@ public override void CreateAsync() { // WSMan expects the data to be in XML format (which is text + xml tags) // so convert byte[] into base64 encoded format - string base64EncodedDataInXml = string.Create(CultureInfo.InvariantCulture, $"<{WSManNativeApi.PS_CREATION_XML_TAG} xmlns=\"{WSManNativeApi.PS_XML_NAMESPACE}\">{Convert.ToBase64String(additionalData)}"); + string base64EncodedDataInXml = string.Format( + CultureInfo.InvariantCulture, + "<{0} xmlns=\"{1}\">{2}", + WSManNativeApi.PS_CREATION_XML_TAG, + WSManNativeApi.PS_XML_NAMESPACE, + Convert.ToBase64String(additionalData)); _openContent = new WSManNativeApi.WSManData_ManToUn(base64EncodedDataInXml); } } @@ -1392,17 +1402,27 @@ private void Initialize(Uri connectionUri, WSManConnectionInfo connectionInfo) if (string.IsNullOrEmpty(connectionUri.Query)) { // if there is no query string already, create one..see RFC 3986 - connectionStr = string.Create(CultureInfo.InvariantCulture, $"{connectionStr.TrimEnd('/')}?PSVersion={PSVersionInfo.PSVersion}{additionalUriSuffixString}"); + connectionStr = string.Format( + CultureInfo.InvariantCulture, + "{0}?PSVersion={1}{2}", // Trimming the last '/' as this will allow WSMan to // properly apply URLPrefix. // Ex: http://localhost?PSVersion=2.0 will be converted // to http://localhost:/?PSVersion=2.0 // by WSMan + connectionStr.TrimEnd('/'), + PSVersionInfo.PSVersion, + additionalUriSuffixString); } else { // if there is already a query string, append using & .. see RFC 3986 - connectionStr = string.Create(CultureInfo.InvariantCulture, $"{connectionStr};PSVersion={PSVersionInfo.PSVersion}{additionalUriSuffixString}"); + connectionStr = string.Format( + CultureInfo.InvariantCulture, + "{0};PSVersion={1}{2}", + connectionStr, + PSVersionInfo.PSVersion, + additionalUriSuffixString); } WSManNativeApi.BaseWSManAuthenticationCredentials authCredentials; diff --git a/src/System.Management.Automation/engine/runtime/Binding/Binders.cs b/src/System.Management.Automation/engine/runtime/Binding/Binders.cs index 79e5fb4c2f9..ca27ecaccae 100644 --- a/src/System.Management.Automation/engine/runtime/Binding/Binders.cs +++ b/src/System.Management.Automation/engine/runtime/Binding/Binders.cs @@ -2239,7 +2239,12 @@ public override DynamicMetaObject FallbackBinaryOperation(DynamicMetaObject targ public override string ToString() { - return string.Create(CultureInfo.InvariantCulture, $"PSBinaryOperationBinder {GetOperatorText()}{(_scalarCompare ? " scalarOnly" : string.Empty)} ver:{_version}"); + return string.Format( + CultureInfo.InvariantCulture, + "PSBinaryOperationBinder {0}{1} ver:{2}", + GetOperatorText(), + _scalarCompare ? " scalarOnly" : string.Empty, + _version); } internal static void InvalidateCache() @@ -3790,7 +3795,11 @@ public override DynamicMetaObject FallbackConvert(DynamicMetaObject target, Dyna public override string ToString() { - return string.Create(CultureInfo.InvariantCulture, $"PSConvertBinder [{Microsoft.PowerShell.ToStringCodeMethods.Type(this.Type, true)}] ver:{_version}"); + return string.Format( + CultureInfo.InvariantCulture, + "PSConvertBinder [{0}] ver:{1}", + Microsoft.PowerShell.ToStringCodeMethods.Type(this.Type, true), + _version); } internal static void InvalidateCache() @@ -3959,7 +3968,13 @@ private PSGetIndexBinder(Tuple tu public override string ToString() { - return string.Create(CultureInfo.InvariantCulture, $"PSGetIndexBinder indexCount={this.CallInfo.ArgumentCount}{(_allowSlicing ? string.Empty : " slicing disallowed")}{(_constraints == null ? string.Empty : " constraints: " + _constraints)} ver:{_version}"); + return string.Format( + CultureInfo.InvariantCulture, + "PSGetIndexBinder indexCount={0}{1}{2} ver:{3}", + this.CallInfo.ArgumentCount, + _allowSlicing ? string.Empty : " slicing disallowed", + _constraints == null ? string.Empty : " constraints: " + _constraints, + _version); } internal static void InvalidateCache() @@ -4543,7 +4558,12 @@ private PSSetIndexBinder(Tuple tuple) public override string ToString() { - return string.Create(CultureInfo.InvariantCulture, $"PSSetIndexBinder indexCnt={CallInfo.ArgumentCount}{(_constraints == null ? string.Empty : " constraints: " + _constraints)} ver:{_version}"); + return string.Format( + CultureInfo.InvariantCulture, + "PSSetIndexBinder indexCnt={0}{1} ver:{2}", + CallInfo.ArgumentCount, + _constraints == null ? string.Empty : " constraints: " + _constraints, + _version); } internal static void InvalidateCache() @@ -5138,7 +5158,13 @@ private PSGetMemberBinder(string name, Type classScope, bool ignoreCase, bool @s public override string ToString() { - return string.Create(CultureInfo.InvariantCulture, $"GetMember: {Name}{(_static ? " static" : string.Empty)}{(_nonEnumerating ? " nonEnumerating" : string.Empty)} ver:{_version}"); + return string.Format( + CultureInfo.InvariantCulture, + "GetMember: {0}{1}{2} ver:{3}", + Name, + _static ? " static" : string.Empty, + _nonEnumerating ? " nonEnumerating" : string.Empty, + _version); } public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, DynamicMetaObject errorSuggestion) @@ -5970,7 +5996,12 @@ public PSSetMemberBinder(string name, bool ignoreCase, bool @static, Type classS public override string ToString() { - return string.Create(CultureInfo.InvariantCulture, $"SetMember: {(_static ? "static " : string.Empty)}{Name} ver:{_getMemberBinder._version}"); + return string.Format( + CultureInfo.InvariantCulture, + "SetMember: {0}{1} ver:{2}", + _static ? "static " : string.Empty, + Name, + _getMemberBinder._version); } private static Expression GetTransformedExpression(IEnumerable transformationAttributes, Expression originalExpression) @@ -6574,7 +6605,15 @@ private PSInvokeMemberBinder(string name, public override string ToString() { - return string.Create(CultureInfo.InvariantCulture, $"PSInvokeMember: {(_static ? "static " : string.Empty)}{(_propertySetter ? "propset " : string.Empty)}{Name} ver:{_getMemberBinder._version} args:{CallInfo.ArgumentCount} constraints:<{(_invocationConstraints != null ? _invocationConstraints.ToString() : string.Empty)}>"); + return string.Format( + CultureInfo.InvariantCulture, + "PSInvokeMember: {0}{1}{2} ver:{3} args:{4} constraints:<{5}>", + _static ? "static " : string.Empty, + _propertySetter ? "propset " : string.Empty, + Name, + _getMemberBinder._version, + CallInfo.ArgumentCount, + _invocationConstraints != null ? _invocationConstraints.ToString() : string.Empty); } public override DynamicMetaObject FallbackInvokeMember(DynamicMetaObject target, DynamicMetaObject[] args, DynamicMetaObject errorSuggestion) @@ -7568,7 +7607,12 @@ internal PSCreateInstanceBinder(CallInfo callInfo, PSMethodInvocationConstraints public override string ToString() { - return string.Create(CultureInfo.InvariantCulture, $"PSCreateInstanceBinder: ver:{_version} args:{_callInfo.ArgumentCount} constraints:<{(_constraints != null ? _constraints : string.Empty)}>"); + return string.Format( + CultureInfo.InvariantCulture, + "PSCreateInstanceBinder: ver:{0} args:{1} constraints:<{2}>", + _version, + _callInfo.ArgumentCount, + _constraints != null ? _constraints.ToString() : string.Empty); } public override DynamicMetaObject FallbackCreateInstance(DynamicMetaObject target, DynamicMetaObject[] args, DynamicMetaObject errorSuggestion) diff --git a/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs b/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs index a9c402f3e24..907c07e5916 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs @@ -1031,7 +1031,13 @@ internal FileRedirection(RedirectionStream from, bool appending, string file) public override string ToString() { - return string.Create(CultureInfo.InvariantCulture, $"{(FromStream == RedirectionStream.All ? "*" : ((int)FromStream).ToString(CultureInfo.InvariantCulture))}> {File}"); + return string.Format( + CultureInfo.InvariantCulture, + "{0}> {1}", + FromStream == RedirectionStream.All + ? "*" + : ((int)FromStream).ToString(CultureInfo.InvariantCulture), + File); } internal string File { get; } diff --git a/src/System.Management.Automation/help/CommandHelpProvider.cs b/src/System.Management.Automation/help/CommandHelpProvider.cs index 12e603e1aa9..0cbb42b821d 100644 --- a/src/System.Management.Automation/help/CommandHelpProvider.cs +++ b/src/System.Management.Automation/help/CommandHelpProvider.cs @@ -950,13 +950,21 @@ private void AddToCommandCache(string mshSnapInId, string cmdletName, MamlComman // Add snapin qualified type name for this command at the top.. // this will enable customizations of the help object. - helpInfo.FullHelp.TypeNames.Insert(0, string.Create(CultureInfo.InvariantCulture, $"MamlCommandHelpInfo#{mshSnapInId}#{cmdletName}")); + helpInfo.FullHelp.TypeNames.Insert( + index: 0, + string.Create( + CultureInfo.InvariantCulture, + $"MamlCommandHelpInfo#{mshSnapInId}#{cmdletName}")); if (!string.IsNullOrEmpty(mshSnapInId)) { key = mshSnapInId + "\\" + key; // Add snapin name to the typenames of this object - helpInfo.FullHelp.TypeNames.Insert(1, string.Create(CultureInfo.InvariantCulture, $"MamlCommandHelpInfo#{mshSnapInId}")); + helpInfo.FullHelp.TypeNames.Insert( + index: 1, + string.Create( + CultureInfo.InvariantCulture, + $"MamlCommandHelpInfo#{mshSnapInId}")); } AddCache(key, helpInfo); diff --git a/src/System.Management.Automation/help/HelpCommentsParser.cs b/src/System.Management.Automation/help/HelpCommentsParser.cs index 87da494dfcf..36d0cb6450e 100644 --- a/src/System.Management.Automation/help/HelpCommentsParser.cs +++ b/src/System.Management.Automation/help/HelpCommentsParser.cs @@ -361,7 +361,9 @@ internal XmlDocument BuildXmlFromComments() // The title is automatically generated XmlElement title = _doc.CreateElement("maml:title", mamlURI); - string titleStr = string.Create(CultureInfo.InvariantCulture, $"\t\t\t\t-------------------------- {HelpDisplayStrings.ExampleUpperCase} {count++} --------------------------"); + string titleStr = string.Format(CultureInfo.InvariantCulture, + "\t\t\t\t-------------------------- {0} {1} --------------------------", + HelpDisplayStrings.ExampleUpperCase, count++); XmlText title_text = _doc.CreateTextNode(titleStr); example_node.AppendChild(title).AppendChild(title_text); diff --git a/src/System.Management.Automation/help/ProviderHelpProvider.cs b/src/System.Management.Automation/help/ProviderHelpProvider.cs index 65fb3e9dfbd..afc0c71c6c2 100644 --- a/src/System.Management.Automation/help/ProviderHelpProvider.cs +++ b/src/System.Management.Automation/help/ProviderHelpProvider.cs @@ -236,12 +236,20 @@ private void LoadHelpFile(ProviderInfo providerInfo) this.HelpSystem.TraceErrors(helpInfo.Errors); // Add snapin qualified type name for this command.. // this will enable customizations of the help object. - helpInfo.FullHelp.TypeNames.Insert(0, string.Create(CultureInfo.InvariantCulture, $"ProviderHelpInfo#{providerInfo.PSSnapInName}#{helpInfo.Name}")); + helpInfo.FullHelp.TypeNames.Insert( + index: 0, + string.Create( + CultureInfo.InvariantCulture, + $"ProviderHelpInfo#{providerInfo.PSSnapInName}#{helpInfo.Name}")); if (!string.IsNullOrEmpty(providerInfo.PSSnapInName)) { helpInfo.FullHelp.Properties.Add(new PSNoteProperty("PSSnapIn", providerInfo.PSSnapIn)); - helpInfo.FullHelp.TypeNames.Insert(1, string.Create(CultureInfo.InvariantCulture, $"ProviderHelpInfo#{providerInfo.PSSnapInName}")); + helpInfo.FullHelp.TypeNames.Insert( + index: 1, + string.Create( + CultureInfo.InvariantCulture, + $"ProviderHelpInfo#{providerInfo.PSSnapInName}")); } AddCache(providerInfo.PSSnapInName + "\\" + helpInfo.Name, helpInfo); diff --git a/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs b/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs index 687a41588f4..17804d0360e 100644 --- a/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs +++ b/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs @@ -939,7 +939,13 @@ internal static PSSnapInInfo ReadCoreEngineSnapIn() "Help.format.ps1xml", "HelpV3.format.ps1xml", "PowerShellCore.format.ps1xml", "PowerShellTrace.format.ps1xml", "Registry.format.ps1xml"}); - string strongName = string.Create(CultureInfo.InvariantCulture, $"{s_coreSnapin.AssemblyName}, Version={assemblyVersion}, Culture={culture}, PublicKeyToken={publicKeyToken}"); + string strongName = string.Format( + CultureInfo.InvariantCulture, + "{0}, Version={1}, Culture={2}, PublicKeyToken={3}", + s_coreSnapin.AssemblyName, + assemblyVersion, + culture, + publicKeyToken); string moduleName = Path.Combine(applicationBase, s_coreSnapin.AssemblyName + ".dll"); diff --git a/src/System.Management.Automation/utils/tracing/SysLogProvider.cs b/src/System.Management.Automation/utils/tracing/SysLogProvider.cs index e1dec75ab16..f3ee184485e 100755 --- a/src/System.Management.Automation/utils/tracing/SysLogProvider.cs +++ b/src/System.Management.Automation/utils/tracing/SysLogProvider.cs @@ -288,7 +288,11 @@ public void LogTransfer(Guid parentActivityId) { // NOTE: always log int threadId = Environment.CurrentManagedThreadId; - string message = string.Create(CultureInfo.InvariantCulture, $"({PSVersionInfo.GitCommitId}:{threadId:X}:{PSChannel.Operational:X}) [Transfer]:{parentActivityId.ToString("B")} {Activity.ToString("B")}"); + string message = string.Format(CultureInfo.InvariantCulture, + "({0}:{1:X}:{2:X}) [Transfer]:{3} {4}", + PSVersionInfo.GitCommitId, threadId, PSChannel.Operational, + parentActivityId.ToString("B"), + Activity.ToString("B")); NativeMethods.SysLog(NativeMethods.SysLogPriority.Info, message); } @@ -303,7 +307,9 @@ public void SetActivity(Guid activity) Activity = activity; // NOTE: always log - string message = string.Create(CultureInfo.InvariantCulture, $"({PSVersionInfo.GitCommitId:X}:{threadId:X}:{PSChannel.Operational:X}) [Activity] {activity.ToString("B")}"); + string message = string.Format(CultureInfo.InvariantCulture, + "({0:X}:{1:X}:{2:X}) [Activity] {3}", + PSVersionInfo.GitCommitId, threadId, PSChannel.Operational, activity.ToString("B")); NativeMethods.SysLog(NativeMethods.SysLogPriority.Info, message); } @@ -327,7 +333,9 @@ public void Log(PSEventId eventId, PSChannel channel, PSTask task, PSOpcode opco sb.Clear(); // add the message preamble - sb.Append(CultureInfo.InvariantCulture, $"({PSVersionInfo.GitCommitId}:{threadId:X}:{channel:X}) [{eventId:G}:{task:G}.{opcode:G}.{level:G}] "); + sb.AppendFormat(CultureInfo.InvariantCulture, + "({0}:{1:X}:{2:X}) [{3:G}:{4:G}.{5:G}.{6:G}] ", + PSVersionInfo.GitCommitId, threadId, channel, eventId, task, opcode, level); // add the message GetEventMessage(sb, eventId, args); diff --git a/test/perf/benchmarks/Engine.Compiler.cs b/test/perf/benchmarks/Engine.Compiler.cs index 5869bc9ef07..10e0054a01c 100644 --- a/test/perf/benchmarks/Engine.Compiler.cs +++ b/test/perf/benchmarks/Engine.Compiler.cs @@ -23,7 +23,7 @@ public class Compiler static Compiler() { - string pattern = string.Create($"{Path.DirectorySeparatorChar}test{Path.DirectorySeparatorChar}perf{Path.DirectorySeparatorChar}benchmarks"); + string pattern = string.Format("{0}test{0}perf{0}benchmarks", Path.DirectorySeparatorChar); string location = typeof(Compiler).Assembly.Location; string testFilePath = null; diff --git a/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/CommandLineOptions.cs b/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/CommandLineOptions.cs index e3c2d2a82a7..aa60c7cc2e6 100644 --- a/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/CommandLineOptions.cs +++ b/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/CommandLineOptions.cs @@ -23,7 +23,7 @@ public static List ParseAndRemoveIntParameter(List argsList, str } else { - throw new ArgumentException(String.Create($"{parameter} must be followed by an integer")); + throw new ArgumentException($"{parameter} must be followed by an integer"); } } From 3a17d0230fe611312e00f5fc5c3ef1708e6be346 Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Wed, 25 Jan 2023 13:39:21 -0800 Subject: [PATCH 321/779] Update additional interpolated string changes (#19029) --- src/Microsoft.WSMan.Management/WsManHelper.cs | 11 ++++------ .../DscSupport/CimDSCParser.cs | 20 +++++++++---------- .../common/DisplayDatabase/typeDataQuery.cs | 14 +++++++++++-- ...lets-over-objects.xmlSerializer.autogen.cs | 2 +- 4 files changed, 27 insertions(+), 20 deletions(-) diff --git a/src/Microsoft.WSMan.Management/WsManHelper.cs b/src/Microsoft.WSMan.Management/WsManHelper.cs index 1450f32a675..ce76f35af6c 100644 --- a/src/Microsoft.WSMan.Management/WsManHelper.cs +++ b/src/Microsoft.WSMan.Management/WsManHelper.cs @@ -1066,13 +1066,10 @@ internal static void LoadResourceData() { try { - string filepath = System.Environment.ExpandEnvironmentVariables("%Windir%") + "\\System32\\Winrm\\" + -#if CORECLR - "0409" /* TODO: don't assume it is always English on CSS? */ -#else - string.Concat("0", string.Create(CultureInfo.CurrentCulture, $"{checked((uint)CultureInfo.CurrentUICulture.LCID):x2}")) -#endif - + "\\" + "winrm.ini"; + string winDir = System.Environment.ExpandEnvironmentVariables("%Windir%"); + uint lcid = checked((uint)CultureInfo.CurrentUICulture.LCID); + string filepath = string.Create(CultureInfo.CurrentCulture, $@"{winDir}\System32\Winrm\0{lcid:x2}\winrm.ini"); + if (File.Exists(filepath)) { FileStream _fs = new FileStream(filepath, FileMode.Open, FileAccess.Read); diff --git a/src/System.Management.Automation/DscSupport/CimDSCParser.cs b/src/System.Management.Automation/DscSupport/CimDSCParser.cs index fb903557655..a3c80e577fa 100644 --- a/src/System.Management.Automation/DscSupport/CimDSCParser.cs +++ b/src/System.Management.Automation/DscSupport/CimDSCParser.cs @@ -2910,19 +2910,19 @@ private static string MapAttributesToMof(string[] enumNames, IEnumerable { if (dscProperty.Key) { - sb.Append(CultureInfo.InvariantCulture, $"{(needComma ? ", " : string.Empty)}key"); + sb.AppendFormat(CultureInfo.InvariantCulture, "{0}key", needComma ? ", " : string.Empty); needComma = true; } if (dscProperty.Mandatory) { - sb.Append(CultureInfo.InvariantCulture, $"{(needComma ? ", " : string.Empty)}required"); + sb.AppendFormat(CultureInfo.InvariantCulture, "{0}required", needComma ? ", " : string.Empty); needComma = true; } if (dscProperty.NotConfigurable) { - sb.Append(CultureInfo.InvariantCulture, $"{(needComma ? ", " : string.Empty)}read"); + sb.AppendFormat(CultureInfo.InvariantCulture, "{0}read", needComma ? ", " : string.Empty); needComma = true; } @@ -2934,13 +2934,13 @@ private static string MapAttributesToMof(string[] enumNames, IEnumerable { bool valueMapComma = false; StringBuilder sbValues = new(", Values{"); - sb.Append(CultureInfo.InvariantCulture, $"{(needComma ? ", " : string.Empty)}ValueMap{{"); + sb.AppendFormat(CultureInfo.InvariantCulture, "{0}ValueMap{{", needComma ? ", " : string.Empty); needComma = true; foreach (var value in validateSet.ValidValues) { - sb.Append(CultureInfo.InvariantCulture, $"{(valueMapComma ? ", " : string.Empty)}\"{value}\""); - sbValues.Append(CultureInfo.InvariantCulture, $"{(valueMapComma ? ", " : string.Empty)}\"{value}\""); + sb.AppendFormat(CultureInfo.InvariantCulture, "{0}\"{1}\"", valueMapComma ? ", " : string.Empty, value); + sbValues.AppendFormat(CultureInfo.InvariantCulture, "{0}\"{1}\"", valueMapComma ? ", " : string.Empty, value); valueMapComma = true; } @@ -2959,11 +2959,11 @@ private static string MapAttributesToMof(string[] enumNames, IEnumerable if (enumNames != null) { - sb.Append(CultureInfo.InvariantCulture, $"{(needComma ? ", " : string.Empty)}ValueMap{{"); + sb.AppendFormat(CultureInfo.InvariantCulture, "{0}ValueMap{{", needComma ? ", " : string.Empty); needComma = false; foreach (var name in enumNames) { - sb.Append(CultureInfo.InvariantCulture, $"{(needComma ? ", " : string.Empty)}\"{name}\""); + sb.AppendFormat(CultureInfo.InvariantCulture, "{0}\"{1}\"", needComma ? ", " : string.Empty, name); needComma = true; } @@ -2971,7 +2971,7 @@ private static string MapAttributesToMof(string[] enumNames, IEnumerable needComma = false; foreach (var name in enumNames) { - sb.Append(CultureInfo.InvariantCulture, $"{(needComma ? ", " : string.Empty)}\"{name}\""); + sb.AppendFormat(CultureInfo.InvariantCulture, "{0}\"{1}\"", needComma ? ", " : string.Empty, name); needComma = true; } @@ -2979,7 +2979,7 @@ private static string MapAttributesToMof(string[] enumNames, IEnumerable } else if (embeddedInstanceType != null) { - sb.Append(CultureInfo.InvariantCulture, $"{(needComma ? ", " : string.Empty)}EmbeddedInstance(\"{embeddedInstanceType}\")"); + sb.AppendFormat(CultureInfo.InvariantCulture, "{0}EmbeddedInstance(\"{1}\")", needComma ? ", " : string.Empty, embeddedInstanceType); } sb.Append(']'); diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs index 2ae6a181f87..78aef16483b 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs @@ -490,12 +490,22 @@ private static void TraceHelper(ViewDefinition vd, bool isMatched) sb.Append(isMatched ? "MATCH FOUND" : "NOT MATCH"); if (tr != null) { - sb.Append(CultureInfo.InvariantCulture, $" {ControlBase.GetControlShapeName(vd.mainControl)} NAME: {vd.name} TYPE: {tr.name}"); + sb.AppendFormat( + CultureInfo.InvariantCulture, + " {0} NAME: {1} TYPE: {2}", + ControlBase.GetControlShapeName(vd.mainControl), + vd.name, + tr.name); } else { TypeGroupReference tgr = togr as TypeGroupReference; - sb.Append(CultureInfo.InvariantCulture, $" {ControlBase.GetControlShapeName(vd.mainControl)} NAME: {vd.name} GROUP: {tgr.name}"); + sb.AppendFormat( + CultureInfo.InvariantCulture, + " {0} NAME: {1} GROUP: {2}", + ControlBase.GetControlShapeName(vd.mainControl), + vd.name, + tgr.name); } ActiveTracer.WriteLine(sb.ToString()); diff --git a/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.xmlSerializer.autogen.cs b/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.xmlSerializer.autogen.cs index b0ad8956b38..6cfed8ebe2d 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.xmlSerializer.autogen.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.xmlSerializer.autogen.cs @@ -289,7 +289,7 @@ protected Exception CreateUnknownNodeException() protected Exception CreateUnknownTypeException(XmlQualifiedName type) { - return new InvalidOperationException(string.Create(CultureInfo.CurrentCulture, $"XmlUnknownType. Name: {type.Name}, Namespace {type.Namespace}, CurrentTag: {CurrentTag()}")); + return new InvalidOperationException(string.Create(CultureInfo.CurrentCulture, $"XmlUnknownType. Name: {type.Name}, Namespace: {type.Namespace}, CurrentTag: {CurrentTag()}")); } protected Exception CreateUnknownConstantException(string value, Type enumType) From 5f3100cd955eec7172d255b83902684736f94a84 Mon Sep 17 00:00:00 2001 From: "James Truher [MSFT]" Date: Wed, 25 Jan 2023 18:02:20 -0800 Subject: [PATCH 322/779] Change test so output does not include newline. (#19026) --- test/powershell/engine/Api/PSCommand.Tests.ps1 | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/test/powershell/engine/Api/PSCommand.Tests.ps1 b/test/powershell/engine/Api/PSCommand.Tests.ps1 index 373951cd29e..0b0be2280f8 100644 --- a/test/powershell/engine/Api/PSCommand.Tests.ps1 +++ b/test/powershell/engine/Api/PSCommand.Tests.ps1 @@ -54,14 +54,13 @@ Describe "PSCommand API tests" -Tag "CI" { # We manually create a CmdletInfo here (with an unresolable command) to verify that CmdletInfo's are cloned. $cmdlet = [System.Management.Automation.CmdletInfo]::new('un-resolvable', [Microsoft.PowerShell.Commands.OutStringCommand]) - $null = $otherShell.AddCommand($cmdlet).AddParameter("InputObject", 'test') + $null = $otherShell.AddCommand($cmdlet).AddParameter("InputObject", 'test').AddParameter("Stream") # Setter for "Commands" calls PSCommand.Clone() $shell.Commands = $otherShell.Commands $result = $shell.Invoke() - $result | Should -Be "test -" + $result | Should -Be "test" } finally { $otherShell.Dispose() From f8cbf90ccb7930e23c7f938256c3f361b3384ad5 Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Fri, 27 Jan 2023 10:03:19 -0800 Subject: [PATCH 323/779] Fix progress calculation divide by zero in Copy-Item (#19038) --- .../namespaces/FileSystemProvider.cs | 2 +- .../Microsoft.PowerShell.Management/FileSystem.Tests.ps1 | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index 60631f7478b..ddd738def75 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -3938,7 +3938,7 @@ private void CopyFileInfoItem(FileInfo file, string destinationPath, bool force, StringUtil.Format(FileSystemProviderStrings.CopyingLocalFileActivity, _copiedFiles, _totalFiles), StringUtil.Format(FileSystemProviderStrings.CopyingLocalBytesStatus, Utils.DisplayHumanReadableFileSize(_copiedBytes), Utils.DisplayHumanReadableFileSize(_totalBytes), speed) ); - var percentComplete = (int)Math.Min(_copiedBytes * 100 / _totalBytes, 100); + var percentComplete = _totalBytes != 0 ? (int)Math.Min(_copiedBytes * 100 / _totalBytes, 100) : 100; progress.PercentComplete = percentComplete; progress.RecordType = ProgressRecordType.Processing; WriteProgress(progress); diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/FileSystem.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/FileSystem.Tests.ps1 index 5e55630c06c..8f13cb48662 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/FileSystem.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/FileSystem.Tests.ps1 @@ -317,6 +317,12 @@ Describe "Basic FileSystem Provider Tests" -Tags "CI" { Remove-Item -Path $testPath -Recurse -Force -ErrorAction SilentlyContinue } } + + It "Copy-Item can copy 0 byte length file" { + $zeroLengthFile = New-Item -Path (Join-Path $TestDrive "zeroLengthFile.txt") -ItemType File -Force + Copy-Item -Path $zeroLengthFile -Destination "$TestDrive\zeroLengthFile2.txt" -Force + "$TestDrive\zeroLengthFile2.txt" | Should -Exist + } } Context "Validate behavior when access is denied" { From d29f34b5c278956ccc6e152d0b8104ed898f3511 Mon Sep 17 00:00:00 2001 From: spaette <111918424+spaette@users.noreply.github.com> Date: Mon, 30 Jan 2023 11:48:00 -0600 Subject: [PATCH 324/779] typos (#19058) --- .../HelpWindow/HelpParagraphBuilder.cs | 2 +- .../HelpWindow/HelpViewModel.cs | 2 +- .../HelpWindow/ParagraphBuilder.cs | 14 +++++++------- .../HelpWindow/ParagraphSearcher.cs | 4 ++-- .../ManagementList/Common/DataRoutedEventArgs.cs | 2 +- .../Common/DismissiblePopup.Generated.cs | 2 +- .../Controls/ParameterSetControl.xaml.cs | 2 +- .../ShowCommand/ViewModel/CommandViewModel.cs | 2 +- .../ShowCommand/ViewModel/ParameterSetViewModel.cs | 4 ++-- .../commandHelpers/HelpWindowHelper.cs | 2 +- .../commandHelpers/ShowCommandHelper.cs | 4 ++-- .../commands/management/GetComputerInfoCommand.cs | 2 +- .../FormatAndOutput/format-hex/Format-Hex.cs | 4 ++-- .../LocalAccounts/StringUtil.cs | 2 +- .../CoreCLR/CorePsAssemblyLoadContext.cs | 2 +- .../CoreCLR/CorePsPlatform.cs | 2 +- .../out-console/ConsoleLineOutput.cs | 4 ++-- .../engine/ComInterop/ComInvokeBinder.cs | 2 +- .../engine/ComInterop/ExcepInfo.cs | 2 +- .../engine/ComInterop/VarEnumSelector.cs | 4 ++-- .../engine/CommandCompletion/CommandCompletion.cs | 2 +- .../engine/CommandDiscovery.cs | 2 +- .../engine/CommandProcessor.cs | 2 +- .../engine/CoreAdapter.cs | 6 +++--- .../engine/InitialSessionState.cs | 2 +- .../engine/Modules/ModuleCmdletBase.cs | 2 +- .../engine/Modules/ModuleIntrinsics.cs | 4 ++-- .../engine/MshCmdlet.cs | 8 ++++---- .../engine/MshCommandRuntime.cs | 2 +- .../engine/Subsystem/SubsystemManager.cs | 2 +- .../engine/TypeTable.cs | 2 +- .../engine/debugger/debugger.cs | 6 +++--- .../engine/hostifaces/History.cs | 2 +- .../engine/hostifaces/LocalPipeline.cs | 4 ++-- .../engine/hostifaces/pipelinebase.cs | 10 +++++----- .../engine/parser/token.cs | 2 +- .../engine/remoting/client/RemotingProtocol2.cs | 2 +- .../engine/remoting/client/remotepipeline.cs | 6 +++--- .../client/remotingprotocolimplementation.cs | 2 +- .../engine/remoting/commands/ConnectPSSession.cs | 2 +- .../remoting/commands/InvokeCommandCommand.cs | 2 +- .../engine/remoting/commands/PSRemotingCmdlet.cs | 2 +- .../engine/remoting/commands/ReceivePSSession.cs | 2 +- .../engine/remoting/commands/getrunspacecommand.cs | 2 +- .../engine/remoting/commands/newrunspacecommand.cs | 2 +- .../remoting/common/RunspaceConnectionInfo.cs | 2 +- .../engine/remoting/fanin/WSManNativeAPI.cs | 8 ++++---- .../remoting/fanin/WSManPluginShellSession.cs | 2 +- .../remoting/server/ServerRemotingProtocol2.cs | 4 ++-- .../engine/runtime/CompiledScriptBlock.cs | 2 +- .../engine/serialization.cs | 6 +++--- .../help/CommandHelpProvider.cs | 2 +- .../help/HelpCommands.cs | 2 +- .../utils/PlatformInvokes.cs | 2 +- src/System.Management.Automation/utils/Verbs.cs | 2 +- 55 files changed, 88 insertions(+), 88 deletions(-) diff --git a/src/Microsoft.Management.UI.Internal/HelpWindow/HelpParagraphBuilder.cs b/src/Microsoft.Management.UI.Internal/HelpWindow/HelpParagraphBuilder.cs index 107ff67dd04..fdb81a6d416 100644 --- a/src/Microsoft.Management.UI.Internal/HelpWindow/HelpParagraphBuilder.cs +++ b/src/Microsoft.Management.UI.Internal/HelpWindow/HelpParagraphBuilder.cs @@ -147,7 +147,7 @@ private static PSPropertyInfo GetProperty(PSObject psObj, string propertyName) /// /// PSObject that contains another PSObject as a property. /// Property name that contains the PSObject. - /// Property name in thye inner PSObject. + /// Property name in the inner PSObject. /// The string from the inner psObject property or null if it could not be retrieved. private static string GetInnerPSObjectPropertyString(PSObject psObj, string psObjectName, string propertyName) { diff --git a/src/Microsoft.Management.UI.Internal/HelpWindow/HelpViewModel.cs b/src/Microsoft.Management.UI.Internal/HelpWindow/HelpViewModel.cs index 7cbe4b0c74e..7ab8681fef4 100644 --- a/src/Microsoft.Management.UI.Internal/HelpWindow/HelpViewModel.cs +++ b/src/Microsoft.Management.UI.Internal/HelpWindow/HelpViewModel.cs @@ -268,7 +268,7 @@ private void SetMatchesLabel() } /// - /// Called internally to notify when a proiperty changed. + /// Called internally to notify when a property changed. /// /// Property name. private void OnNotifyPropertyChanged(string propertyName) diff --git a/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphBuilder.cs b/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphBuilder.cs index 5878e5f029e..92c0de12cde 100644 --- a/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphBuilder.cs +++ b/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphBuilder.cs @@ -77,12 +77,12 @@ internal Paragraph Paragraph /// /// Called after all the AddText calls have been made to build the paragraph /// based on the current text. - /// This method goes over 3 collections simultaneouslly: + /// This method goes over 3 collections simultaneously: /// 1) characters in this.textBuilder /// 2) spans in this.boldSpans /// 3) spans in this.highlightedSpans /// And adds the minimal number of Inlines to the paragraph so that all - /// characters that should be bold and/or highlighed are. + /// characters that should be bold and/or highlighted are. /// internal void BuildParagraph() { @@ -234,11 +234,11 @@ private static void AddInline(Paragraph currentParagraph, bool currentBold, bool } /// - /// This is an auxiliar method in BuildParagraph to move the current bold or highlighed spans + /// This is an auxiliar method in BuildParagraph to move the current bold or highlighted spans /// according to the - /// The current bold and higlighed span should be ending ahead of the current position. + /// The current bold and highlighted span should be ending ahead of the current position. /// Moves and to the - /// propper span in according to the + /// proper span in according to the /// This is an auxiliar method in BuildParagraph. /// /// Current index within . @@ -290,7 +290,7 @@ private void AddHighlight(int start, int length) } /// - /// Called internally to notify when a proiperty changed. + /// Called internally to notify when a property changed. /// /// Property name. private void OnNotifyPropertyChanged(string propertyName) @@ -303,7 +303,7 @@ private void OnNotifyPropertyChanged(string propertyName) } /// - /// A text span used to mark bold and highlighed segments. + /// A text span used to mark bold and highlighted segments. /// internal struct TextSpan { diff --git a/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphSearcher.cs b/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphSearcher.cs index 6c42047b1b7..9ba8f158a2f 100644 --- a/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphSearcher.cs +++ b/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphSearcher.cs @@ -202,10 +202,10 @@ private static Paragraph GetParagraph(Run run) } /// - /// Returns true if the run is the fiorst run of the paragraph. + /// Returns true if the run is the first run of the paragraph. /// /// Run to check. - /// True if the run is the fiorst run of the paragraph. + /// True if the run is the first run of the paragraph. private static bool IsFirstRun(Run run) { Paragraph paragraph = GetParagraph(run); diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/DataRoutedEventArgs.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/DataRoutedEventArgs.cs index cf65462c3b4..f75555b1da4 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/DataRoutedEventArgs.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/DataRoutedEventArgs.cs @@ -11,7 +11,7 @@ namespace Microsoft.Management.UI.Internal { /// /// Routed event args which provide the ability to attach an - /// arbitrary peice of data. + /// arbitrary piece of data. /// /// There are no restrictions on type T. [SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/DismissiblePopup.Generated.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/DismissiblePopup.Generated.cs index 76e3206f1f5..3a2768b17b0 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/DismissiblePopup.Generated.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/DismissiblePopup.Generated.cs @@ -11,7 +11,7 @@ namespace Microsoft.Management.UI.Internal { /// - /// A popup which child controls can signal to be dimissed. + /// A popup which child controls can signal to be dismissed. /// /// /// If a control wants to dismiss the popup then they should execute the DismissPopupCommand on a target in the popup window. diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ParameterSetControl.xaml.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ParameterSetControl.xaml.cs index 907c743f6bf..6efef65eec6 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ParameterSetControl.xaml.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ParameterSetControl.xaml.cs @@ -363,7 +363,7 @@ private void AddControlToMainGrid(UIElement uiControl) } /// - /// Creates a Lable control and add it to MainGrid. + /// Creates a Label control and add it to MainGrid. /// /// DataContext object. /// Row number. diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/CommandViewModel.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/CommandViewModel.cs index 835ae6d3c9d..425accfaea9 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/CommandViewModel.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/CommandViewModel.cs @@ -457,7 +457,7 @@ public string GetScript() } /// - /// Showing help information for current actived cmdlet. + /// Showing help information for current active cmdlet. /// public void OpenHelpWindow() { diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterSetViewModel.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterSetViewModel.cs index 2b70deff7d8..89428ecf58d 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterSetViewModel.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterSetViewModel.cs @@ -226,12 +226,12 @@ internal static int Compare(ParameterViewModel source, ParameterViewModel target #endregion /// - /// Gets the delimited poarameter if it needs delimitation and is not delimited. + /// Gets the delimited parameter if it needs delimitation and is not delimited. /// /// Value needing delimitation. /// Open delimitation. /// Close delimitation. - /// The delimited poarameter if it needs delimitation and is not delimited. + /// The delimited parameter if it needs delimitation and is not delimited. private static string GetDelimitedParameter(string parameterValue, string openDelimiter, string closeDelimiter) { string parameterValueTrimmed = parameterValue.Trim(); diff --git a/src/Microsoft.Management.UI.Internal/commandHelpers/HelpWindowHelper.cs b/src/Microsoft.Management.UI.Internal/commandHelpers/HelpWindowHelper.cs index ddb9ab191ae..e0b036a93d0 100644 --- a/src/Microsoft.Management.UI.Internal/commandHelpers/HelpWindowHelper.cs +++ b/src/Microsoft.Management.UI.Internal/commandHelpers/HelpWindowHelper.cs @@ -13,7 +13,7 @@ namespace Microsoft.PowerShell.Commands.Internal { /// - /// Implements thw WPF window part of the ShowWindow option of get-help. + /// Implements the WPF window part of the ShowWindow option of get-help. /// internal static class HelpWindowHelper { diff --git a/src/Microsoft.Management.UI.Internal/commandHelpers/ShowCommandHelper.cs b/src/Microsoft.Management.UI.Internal/commandHelpers/ShowCommandHelper.cs index 2268edb99f5..13dfe839b9d 100644 --- a/src/Microsoft.Management.UI.Internal/commandHelpers/ShowCommandHelper.cs +++ b/src/Microsoft.Management.UI.Internal/commandHelpers/ShowCommandHelper.cs @@ -21,7 +21,7 @@ namespace Microsoft.PowerShell.Commands.ShowCommandInternal { /// - /// Implements thw WPF window part of the show-command cmdlet. + /// Implements the WPF window part of the show-command cmdlet. /// internal class ShowCommandHelper : IDisposable { @@ -672,7 +672,7 @@ internal static AllModulesViewModel GetNewAllModulesViewModel(AllModulesViewMode /// /// Gets an error message to be displayed when failed to import a module. /// - /// Command belongiong to the module to import. + /// Command belonging to the module to import. /// Module to import. /// Error importing the module. /// An error message to be displayed when failed to import a module. diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs index 47569282929..02f13f1dd88 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs @@ -3055,7 +3055,7 @@ public class ComputerInfo public ulong? OsFreeSpaceInPagingFiles { get; internal set; } /// - /// Array of fiel paths to the operating system's paging files. + /// Array of file paths to the operating system's paging files. /// [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] OsPagingFiles { get; internal set; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-hex/Format-Hex.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-hex/Format-Hex.cs index de73b2155a6..48cc45a48d0 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-hex/Format-Hex.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-hex/Format-Hex.cs @@ -24,7 +24,7 @@ public sealed class FormatHex : PSCmdlet private const int BUFFERSIZE = 16; /// - /// For cases where a homogenous collection of bytes or other items are directly piped in, we collect all the + /// For cases where a homogeneous collection of bytes or other items are directly piped in, we collect all the /// bytes in a List<byte> and then output the formatted result all at once in EndProcessing(). /// private readonly List _inputBuffer = new(); @@ -37,7 +37,7 @@ public sealed class FormatHex : PSCmdlet private bool _groupInput = true; /// - /// Keep track of prior input types to determine if we're given a heterogenous collection. + /// Keep track of prior input types to determine if we're given a heterogeneous collection. /// private Type _lastInputType; diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/StringUtil.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/StringUtil.cs index 3534b34cc49..25bbeb49329 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/StringUtil.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/StringUtil.cs @@ -12,7 +12,7 @@ namespace System.Management.Automation.SecurityAccountsManager internal class StringUtil { /// - /// Private constructor to precent auto-generation of a default constructor with greater accessability. + /// Private constructor to present auto-generation of a default constructor with greater accessibility. /// private StringUtil() { diff --git a/src/System.Management.Automation/CoreCLR/CorePsAssemblyLoadContext.cs b/src/System.Management.Automation/CoreCLR/CorePsAssemblyLoadContext.cs index 5cd38cec25b..6a9462f37d4 100644 --- a/src/System.Management.Automation/CoreCLR/CorePsAssemblyLoadContext.cs +++ b/src/System.Management.Automation/CoreCLR/CorePsAssemblyLoadContext.cs @@ -589,7 +589,7 @@ public static void SetPowerShellAssemblyLoadContext([MarshalAs(UnmanagedType.LPW } /// - /// Provides helper functions to faciliate calling managed code from a native PowerShell host. + /// Provides helper functions to facilitate calling managed code from a native PowerShell host. /// public static unsafe class PowerShellUnsafeAssemblyLoad { diff --git a/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs b/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs index 1790cc72b52..78b355ab3fe 100644 --- a/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs +++ b/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs @@ -213,7 +213,7 @@ internal static class CommonEnvVariableNames private static string s_tempHome = null; /// - /// Get the 'HOME' environment variable or create a temporary home diretory if the environment variable is not set. + /// Get the 'HOME' environment variable or create a temporary home directory if the environment variable is not set. /// private static string GetHomeOrCreateTempHome() { diff --git a/src/System.Management.Automation/FormatAndOutput/out-console/ConsoleLineOutput.cs b/src/System.Management.Automation/FormatAndOutput/out-console/ConsoleLineOutput.cs index e8379d3f321..f828b673de0 100644 --- a/src/System.Management.Automation/FormatAndOutput/out-console/ConsoleLineOutput.cs +++ b/src/System.Management.Automation/FormatAndOutput/out-console/ConsoleLineOutput.cs @@ -520,7 +520,7 @@ internal PromptResponse PromptUser(PSHostUserInterface console) private readonly PromptHandler _prompt = null; /// - /// Conter for the # of lines written when prompting is on. + /// Counter for the # of lines written when prompting is on. /// private long _linesWritten = 0; @@ -530,7 +530,7 @@ internal PromptResponse PromptUser(PSHostUserInterface console) private bool _disableLineWrittenEvent = false; /// - /// Refecence to the PSHostUserInterface interface we use. + /// Reference to the PSHostUserInterface interface we use. /// private readonly PSHostUserInterface _console = null; diff --git a/src/System.Management.Automation/engine/ComInterop/ComInvokeBinder.cs b/src/System.Management.Automation/engine/ComInterop/ComInvokeBinder.cs index 88e4114cd58..f657f62e405 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComInvokeBinder.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComInvokeBinder.cs @@ -392,7 +392,7 @@ private Expression GenerateFinallyBlock() } /// - /// Create a stub for the target of the optimized lopop. + /// Create a stub for the target of the optimized loop. /// /// private Expression MakeIDispatchInvokeTarget() diff --git a/src/System.Management.Automation/engine/ComInterop/ExcepInfo.cs b/src/System.Management.Automation/engine/ComInterop/ExcepInfo.cs index 4f829b6241d..74314850a59 100644 --- a/src/System.Management.Automation/engine/ComInterop/ExcepInfo.cs +++ b/src/System.Management.Automation/engine/ComInterop/ExcepInfo.cs @@ -10,7 +10,7 @@ namespace System.Management.Automation.ComInterop { /// - /// This is similar to ComTypes.EXCEPINFO, but lets us do our own custom marshaling. + /// This is similar to ComTypes.EXCEPINFO, but lets us do our own custom marshalling. /// [StructLayout(LayoutKind.Sequential)] internal struct ExcepInfo diff --git a/src/System.Management.Automation/engine/ComInterop/VarEnumSelector.cs b/src/System.Management.Automation/engine/ComInterop/VarEnumSelector.cs index 275f75f4bb2..942a6364435 100644 --- a/src/System.Management.Automation/engine/ComInterop/VarEnumSelector.cs +++ b/src/System.Management.Automation/engine/ComInterop/VarEnumSelector.cs @@ -98,7 +98,7 @@ internal static Type GetTypeForVarEnum(VarEnum vt) } /// - /// Gets the managed type that an object needs to be coverted to in order for it to be able + /// Gets the managed type that an object needs to be converted to in order for it to be able /// to be represented as a Variant. /// /// In general, there is a many-to-many mapping between Type and VarEnum. However, this method @@ -429,7 +429,7 @@ private VarEnum GetComType(ref Type argumentType) } /// - /// Get the COM Variant type that argument should be marshaled as for a call to COM. + /// Get the COM Variant type that argument should be marshalled as for a call to COM. /// private VariantBuilder GetVariantBuilder(Type argumentType) { diff --git a/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs b/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs index d0d248fa50a..21b4832a363 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs @@ -1153,7 +1153,7 @@ private LastWordFinder(string sentence) } /// - /// Locates the last "word" in a string of text. A word is a conguous sequence of characters that are not + /// Locates the last "word" in a string of text. A word is a congruous sequence of characters that are not /// whitespace, or a contiguous set grouped by single or double quotes. Can be called by at most 1 thread at a time /// per LastWordFinder instance. /// diff --git a/src/System.Management.Automation/engine/CommandDiscovery.cs b/src/System.Management.Automation/engine/CommandDiscovery.cs index 0dca804e648..8efaff4d0a9 100644 --- a/src/System.Management.Automation/engine/CommandDiscovery.cs +++ b/src/System.Management.Automation/engine/CommandDiscovery.cs @@ -55,7 +55,7 @@ internal CommandLookupEventArgs(string commandName, CommandOrigin commandOrigin, public bool StopSearch { get; set; } /// - /// The CommandInfo obejct for the command that was found. + /// The CommandInfo object for the command that was found. /// public CommandInfo Command { get; set; } diff --git a/src/System.Management.Automation/engine/CommandProcessor.cs b/src/System.Management.Automation/engine/CommandProcessor.cs index 62eebe5d937..53c0b688570 100644 --- a/src/System.Management.Automation/engine/CommandProcessor.cs +++ b/src/System.Management.Automation/engine/CommandProcessor.cs @@ -686,7 +686,7 @@ private static Cmdlet ConstructInstance(Type type) /// If the constructor for the cmdlet threw an exception. /// /// - /// The type referenced by refered to an + /// The type referenced by referred to an /// abstract type or them member was invoked via a late-binding mechanism. /// /// diff --git a/src/System.Management.Automation/engine/CoreAdapter.cs b/src/System.Management.Automation/engine/CoreAdapter.cs index beb220495a6..0bda9ee906f 100644 --- a/src/System.Management.Automation/engine/CoreAdapter.cs +++ b/src/System.Management.Automation/engine/CoreAdapter.cs @@ -38,7 +38,7 @@ namespace System.Management.Automation internal abstract class Adapter { /// - /// Tracer for this and derivate classes. + /// Tracer for this and derivative classes. /// [TraceSource("ETS", "Extended Type System")] protected static PSTraceSource tracer = PSTraceSource.GetTracer("ETS", "Extended Type System"); @@ -1826,7 +1826,7 @@ internal static object[] GetMethodArgumentsBase(string methodName, } // We are going to put all the remaining arguments into an array - // and convert them to the propper type, if necessary to be the + // and convert them to the proper type, if necessary to be the // one argument for this last parameter int remainingArgumentCount = arguments.Length - parametersLength + 1; if (remainingArgumentCount == 1 && arguments[arguments.Length - 1] == null) @@ -1878,7 +1878,7 @@ internal static object[] GetMethodArgumentsBase(string methodName, } /// - /// Auxiliary method in MethodInvoke to set newArguments[index] with the propper value. + /// Auxiliary method in MethodInvoke to set newArguments[index] with the proper value. /// /// Used for the MethodException that might be thrown. /// The complete array of arguments. diff --git a/src/System.Management.Automation/engine/InitialSessionState.cs b/src/System.Management.Automation/engine/InitialSessionState.cs index e041b0d7006..c26e3def06c 100644 --- a/src/System.Management.Automation/engine/InitialSessionState.cs +++ b/src/System.Management.Automation/engine/InitialSessionState.cs @@ -4477,7 +4477,7 @@ static InitialSessionState() internal static readonly SessionStateVariableEntry[] BuiltInVariables; /// - /// Returns a new array of alias entries everytime it's called. This + /// Returns a new array of alias entries every time it's called. This /// can't be static because the elements may be mutated in different session /// state objects so each session state must have a copy of the entry. /// diff --git a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs index 275b87902b7..1b4b5204302 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs @@ -4608,7 +4608,7 @@ private string FixFileName(string moduleName, string moduleBase, string fileName /// A utility routine to fix up a file name so it's rooted and has an extension. /// /// - /// When fixing up an assembly file, this method loads the resovled assembly if it's in the process of actually loading a module. + /// When fixing up an assembly file, this method loads the resolved assembly if it's in the process of actually loading a module. /// Read the comments in the method for the detailed information. /// /// Name of the module that we are processing, used for caching purpose when we need to load an assembly. diff --git a/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs b/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs index 796ce35943d..50170b63422 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs @@ -1248,7 +1248,7 @@ internal static string GetModulePath() #if !UNIX /// - /// Returns a PSModulePath suiteable for Windows PowerShell by removing PowerShell's specific + /// Returns a PSModulePath suitable for Windows PowerShell by removing PowerShell's specific /// paths from current PSModulePath. /// /// @@ -1711,7 +1711,7 @@ internal enum ModuleMatchFailure /// Module version was greater than the maximum version. MaximumVersion, - /// The module specifcation passed in was null. + /// The module specification passed in was null. NullModuleSpecification, } diff --git a/src/System.Management.Automation/engine/MshCmdlet.cs b/src/System.Management.Automation/engine/MshCmdlet.cs index 9711b64f8b0..40095ad1472 100644 --- a/src/System.Management.Automation/engine/MshCmdlet.cs +++ b/src/System.Management.Automation/engine/MshCmdlet.cs @@ -116,7 +116,7 @@ public bool ToBool() /// Construct a SwitchParameter instance with a particular value. /// /// - /// If true, it indicates that the switch is present, flase otherwise. + /// If true, it indicates that the switch is present, false otherwise. /// public SwitchParameter(bool isPresent) { @@ -362,7 +362,7 @@ public CommandInfo GetCommand(string commandName, CommandTypes type, object[] ar public System.EventHandler PostCommandLookupAction { get; set; } /// - /// Gets or sets the action that is invoked everytime the runspace location (cwd) is changed. + /// Gets or sets the action that is invoked every time the runspace location (cwd) is changed. /// public System.EventHandler LocationChangedAction { get; set; } @@ -702,7 +702,7 @@ public Collection InvokeScript(string script, params object[] args) } /// - /// Executes a given scriptblock synchonously in the given session state. + /// Executes a given scriptblock synchronously in the given session state. /// The scriptblock will be executed in the calling scope (dot-sourced) rather than in a new child scope. /// /// The session state in which to execute the scriptblock. @@ -746,7 +746,7 @@ public Collection InvokeScript( /// /// If true, executes the scriptblock in a new child scope, otherwise the scriptblock is dot-sourced into the calling scope. /// The scriptblock to execute. - /// Optionall input to the command. + /// Optional input to the command. /// Arguments to pass to the scriptblock. /// /// A collection of the PSObjects generated by executing the script. Never null, but may be empty. diff --git a/src/System.Management.Automation/engine/MshCommandRuntime.cs b/src/System.Management.Automation/engine/MshCommandRuntime.cs index d1d0561957b..427929c3e8b 100644 --- a/src/System.Management.Automation/engine/MshCommandRuntime.cs +++ b/src/System.Management.Automation/engine/MshCommandRuntime.cs @@ -3226,7 +3226,7 @@ internal SwitchParameter UseTransaction private bool _debugFlag = false; /// - /// Debug tell the command system to provide Programmer/Support type messages to understand what is really occuring + /// Debug tell the command system to provide Programmer/Support type messages to understand what is really occurring /// and give the user the opportunity to stop or debug the situation. /// /// diff --git a/src/System.Management.Automation/engine/Subsystem/SubsystemManager.cs b/src/System.Management.Automation/engine/Subsystem/SubsystemManager.cs index 022c163a16c..e389040899e 100644 --- a/src/System.Management.Automation/engine/Subsystem/SubsystemManager.cs +++ b/src/System.Management.Automation/engine/Subsystem/SubsystemManager.cs @@ -67,7 +67,7 @@ static SubsystemManager() /// /// /// Design point: - /// The implemnentation proxy object is not supposed to expose to users. + /// The implementation proxy object is not supposed to expose to users. /// Users shouldn't depend on a implementation proxy object directly, but instead should depend on PowerShell APIs. /// /// Example: if a user want to use prediction functionality, he/she should use the PowerShell prediction API instead of diff --git a/src/System.Management.Automation/engine/TypeTable.cs b/src/System.Management.Automation/engine/TypeTable.cs index 042d0ddf72d..502258485c0 100644 --- a/src/System.Management.Automation/engine/TypeTable.cs +++ b/src/System.Management.Automation/engine/TypeTable.cs @@ -3036,7 +3036,7 @@ private static bool GetCheckMemberType(ConcurrentBag errors, string type /// /// Issue appropriate errors and remove members as necessary if: /// - The serialization settings do not fall into one of the combinations of the table below - /// - If the serialization settings notes' values cannot be converted to the propper type + /// - If the serialization settings notes' values cannot be converted to the proper type /// - If serialization settings members are of the wrong member type /// - DefaultDisplayPropertySet is not an PSPropertySet /// - DefaultDisplayProperty is not an PSPropertyInfo diff --git a/src/System.Management.Automation/engine/debugger/debugger.cs b/src/System.Management.Automation/engine/debugger/debugger.cs index 059c68643ab..c84d6a48293 100644 --- a/src/System.Management.Automation/engine/debugger/debugger.cs +++ b/src/System.Management.Automation/engine/debugger/debugger.cs @@ -4490,7 +4490,7 @@ protected virtual bool HandleListCommand(PSDataCollection output) /// /// Attempts to fix up the debugger stop invocation information so that /// the correct stack and source can be displayed in the debugger, for - /// cases where the debugged runspace is called inside a parent sccript, + /// cases where the debugged runspace is called inside a parent script, /// such as with script Invoke-Command cases. /// /// @@ -4761,7 +4761,7 @@ protected override bool HandleListCommand(PSDataCollection output) /// /// Attempts to fix up the debugger stop invocation information so that /// the correct stack and source can be displayed in the debugger, for - /// cases where the debugged runspace is called inside a parent sccript, + /// cases where the debugged runspace is called inside a parent script, /// such as with script Invoke-Command cases. /// /// Invocation information from debugger stop. @@ -5646,7 +5646,7 @@ public static void StartMonitoringRunspace(Debugger debugger, PSMonitorRunspaceI } /// - /// End monitoring a runspace on the target degbugger. + /// End monitoring a runspace on the target debugger. /// /// Target debugger. /// PSMonitorRunspaceInfo. diff --git a/src/System.Management.Automation/engine/hostifaces/History.cs b/src/System.Management.Automation/engine/hostifaces/History.cs index 162cf033315..a061078f63c 100644 --- a/src/System.Management.Automation/engine/hostifaces/History.cs +++ b/src/System.Management.Automation/engine/hostifaces/History.cs @@ -510,7 +510,7 @@ internal HistoryInfo[] GetEntries(WildcardPattern wildcardpattern, long count, S long id = _countEntriesAdded; for (long i = 0; i <= count - 1;) { - // if buffersize is changed,we have to loop from max entry to min entry thats not cleared + // if buffersize is changed,we have to loop from max entry to min entry that's not cleared if (_capacity != DefaultHistorySize) { if (_countEntriesAdded > _capacity) diff --git a/src/System.Management.Automation/engine/hostifaces/LocalPipeline.cs b/src/System.Management.Automation/engine/hostifaces/LocalPipeline.cs index 44e3f3047b2..93cb65f3f07 100644 --- a/src/System.Management.Automation/engine/hostifaces/LocalPipeline.cs +++ b/src/System.Management.Automation/engine/hostifaces/LocalPipeline.cs @@ -730,7 +730,7 @@ private void InvokeThreadProc() /// /// Stop the running pipeline. /// - /// If true pipeline is stoped synchronously + /// If true pipeline is stopped synchronously /// else asynchronously. protected override void ImplementStop(bool syncCall) { @@ -969,7 +969,7 @@ private void InitStreams() } /// - /// This method sets streams to their orignal states from execution context. + /// This method sets streams to their original states from execution context. /// This is done when Pipeline is completed/failed/stopped ie., termination state. /// private void ClearStreams() diff --git a/src/System.Management.Automation/engine/hostifaces/pipelinebase.cs b/src/System.Management.Automation/engine/hostifaces/pipelinebase.cs index b4efa770880..f144ff7f506 100644 --- a/src/System.Management.Automation/engine/hostifaces/pipelinebase.cs +++ b/src/System.Management.Automation/engine/hostifaces/pipelinebase.cs @@ -282,7 +282,7 @@ public override void StopAsync() /// /// Stop the running pipeline. /// - /// If true pipeline is stoped synchronously + /// If true pipeline is stopped synchronously /// else asynchronously. private void CoreStop(bool syncCall) { @@ -298,7 +298,7 @@ private void CoreStop(bool syncCall) break; // If pipeline execution has failed or completed or - // stoped, return silently. + // stopped, return silently. case PipelineState.Stopped: case PipelineState.Completed: case PipelineState.Failed: @@ -331,7 +331,7 @@ private void CoreStop(bool syncCall) // Raise the event outside the lock RaisePipelineStateEvents(); - // A pipeline can be stoped before it is started. See NotStarted + // A pipeline can be stopped before it is started. See NotStarted // case in above switch statement. This is done to allow stoping a pipeline // in another thread before it has been started. lock (SyncRoot) @@ -515,7 +515,7 @@ private void CoreInvoke(IEnumerable input, bool syncCall) SyncInvokeCall = syncCall; // Create event which will be signalled when pipeline execution - // is completed/failed/stoped. + // is completed/failed/stopped. // Note:Runspace.Close waits for all the running pipeline // to finish. This Event must be created before pipeline is // added to list of running pipelines. This avoids the race condition @@ -891,7 +891,7 @@ protected void RaisePipelineStateEvents() /// /// ManualResetEvent which is signaled when pipeline execution is - /// completed/failed/stoped. + /// completed/failed/stopped. /// internal ManualResetEvent PipelineFinishedEvent { get; private set; } diff --git a/src/System.Management.Automation/engine/parser/token.cs b/src/System.Management.Automation/engine/parser/token.cs index 11d0a632cb5..2d71602fca0 100644 --- a/src/System.Management.Automation/engine/parser/token.cs +++ b/src/System.Management.Automation/engine/parser/token.cs @@ -200,7 +200,7 @@ public enum TokenKind /// The addition operator '+'. Plus = 40, - /// The substraction operator '-'. + /// The subtraction operator '-'. Minus = 41, /// The assignment operator '='. diff --git a/src/System.Management.Automation/engine/remoting/client/RemotingProtocol2.cs b/src/System.Management.Automation/engine/remoting/client/RemotingProtocol2.cs index ecc3d6cfd9f..ed01bc7ad1b 100644 --- a/src/System.Management.Automation/engine/remoting/client/RemotingProtocol2.cs +++ b/src/System.Management.Automation/engine/remoting/client/RemotingProtocol2.cs @@ -1430,7 +1430,7 @@ internal void ProcessDisconnect(RunspacePoolStateInfo rsStateInfo) /// /// This does not ensure that the corresponding session/runspacepool is in connected stated - /// Its the caller responsiblity to ensure that this is the case + /// It's the caller responsibility to ensure that this is the case /// At the protocols layers, this logic is delegated to the transport layer. /// WSMan transport ensures that WinRS commands cannot be reconnected when the parent shell is not in connected state. /// diff --git a/src/System.Management.Automation/engine/remoting/client/remotepipeline.cs b/src/System.Management.Automation/engine/remoting/client/remotepipeline.cs index 67e4b7153f3..cf476cec226 100644 --- a/src/System.Management.Automation/engine/remoting/client/remotepipeline.cs +++ b/src/System.Management.Automation/engine/remoting/client/remotepipeline.cs @@ -95,7 +95,7 @@ private RemotePipeline(RemoteRunspace runspace, bool addToHistory, bool isNested SetCommandCollection(_commands); // Create event which will be signalled when pipeline execution - // is completed/failed/stoped. + // is completed/failed/stopped. // Note:Runspace.Close waits for all the running pipeline // to finish. This Event must be created before pipeline is // added to list of running pipelines. This avoids the race condition @@ -599,7 +599,7 @@ private bool CanStopPipeline(out bool isAlreadyStopping) break; // If pipeline execution has failed or completed or - // stoped, return silently. + // stopped, return silently. case PipelineState.Stopped: case PipelineState.Completed: case PipelineState.Failed: @@ -1018,7 +1018,7 @@ private void Cleanup() /// /// ManualResetEvent which is signaled when pipeline execution is - /// completed/failed/stoped. + /// completed/failed/stopped. /// internal ManualResetEvent PipelineFinishedEvent { get; } diff --git a/src/System.Management.Automation/engine/remoting/client/remotingprotocolimplementation.cs b/src/System.Management.Automation/engine/remoting/client/remotingprotocolimplementation.cs index d8800311127..71720f6cacd 100644 --- a/src/System.Management.Automation/engine/remoting/client/remotingprotocolimplementation.cs +++ b/src/System.Management.Automation/engine/remoting/client/remotingprotocolimplementation.cs @@ -329,7 +329,7 @@ private void HandleStateChanged(object sender, RemoteSessionStateEventArgs arg) } /// - /// Clubing negotiation packet + runspace creation and then doing transportManager.ConnectAsync(). + /// Clubbing negotiation packet + runspace creation and then doing transportManager.ConnectAsync(). /// This will save us 2 network calls by doing all the work in one network call. /// private void HandleNegotiationSendingStateChange() diff --git a/src/System.Management.Automation/engine/remoting/commands/ConnectPSSession.cs b/src/System.Management.Automation/engine/remoting/commands/ConnectPSSession.cs index b84b36e727e..a1d993a6545 100644 --- a/src/System.Management.Automation/engine/remoting/commands/ConnectPSSession.cs +++ b/src/System.Management.Automation/engine/remoting/commands/ConnectPSSession.cs @@ -83,7 +83,7 @@ public class ConnectPSSessionCommand : PSRunspaceCmdlet, IDisposable /// /// This parameters specifies the appname which identifies the connection /// end point on the remote machine. If this parameter is not specified - /// then the value specified in DEFAULTREMOTEAPPNAME will be used. If thats + /// then the value specified in DEFAULTREMOTEAPPNAME will be used. If that's /// not specified as well, then "WSMAN" will be used. /// [Parameter(ValueFromPipelineByPropertyName = true, diff --git a/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs b/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs index a2a2397cb7a..0942c305979 100644 --- a/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs @@ -308,7 +308,7 @@ public override string ConfigurationName /// /// This parameters specifies the appname which identifies the connection /// end point on the remote machine. If this parameter is not specified - /// then the value specified in DEFAULTREMOTEAPPNAME will be used. If thats + /// then the value specified in DEFAULTREMOTEAPPNAME will be used. If that's /// not specified as well, then "WSMAN" will be used. /// [Parameter(ValueFromPipelineByPropertyName = true, diff --git a/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs b/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs index a24163f66c7..ff86e894e82 100644 --- a/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs +++ b/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs @@ -592,7 +592,7 @@ public virtual PSCredential Credential /// /// This parameters specifies the appname which identifies the connection /// end point on the remote machine. If this parameter is not specified - /// then the value specified in DEFAULTREMOTEAPPNAME will be used. If thats + /// then the value specified in DEFAULTREMOTEAPPNAME will be used. If that's /// not specified as well, then "WSMAN" will be used. /// [Parameter(ValueFromPipelineByPropertyName = true, diff --git a/src/System.Management.Automation/engine/remoting/commands/ReceivePSSession.cs b/src/System.Management.Automation/engine/remoting/commands/ReceivePSSession.cs index 9704216e053..798cf82d9fa 100644 --- a/src/System.Management.Automation/engine/remoting/commands/ReceivePSSession.cs +++ b/src/System.Management.Automation/engine/remoting/commands/ReceivePSSession.cs @@ -116,7 +116,7 @@ public class ReceivePSSessionCommand : PSRemotingCmdlet /// /// This parameters specifies the appname which identifies the connection /// end point on the remote machine. If this parameter is not specified - /// then the value specified in DEFAULTREMOTEAPPNAME will be used. If thats + /// then the value specified in DEFAULTREMOTEAPPNAME will be used. If that's /// not specified as well, then "WSMAN" will be used. /// [Parameter(ValueFromPipelineByPropertyName = true, diff --git a/src/System.Management.Automation/engine/remoting/commands/getrunspacecommand.cs b/src/System.Management.Automation/engine/remoting/commands/getrunspacecommand.cs index 080c05c9d63..1312c5f5c4a 100644 --- a/src/System.Management.Automation/engine/remoting/commands/getrunspacecommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/getrunspacecommand.cs @@ -69,7 +69,7 @@ public class GetPSSessionCommand : PSRunspaceCmdlet, IDisposable /// /// This parameters specifies the appname which identifies the connection /// end point on the remote machine. If this parameter is not specified - /// then the value specified in DEFAULTREMOTEAPPNAME will be used. If thats + /// then the value specified in DEFAULTREMOTEAPPNAME will be used. If that's /// not specified as well, then "WSMAN" will be used. /// [Parameter(ValueFromPipelineByPropertyName = true, diff --git a/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs b/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs index 3ea381d6a1c..bb858169f2d 100644 --- a/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs @@ -1385,7 +1385,7 @@ internal override event EventHandler OperationComplete /// /// There are two problems that need to be handled. /// 1) We need to make sure that the ThrottleManager StartComplete and StopComplete - /// operation events are called or the ThrottleManager will never end (will stop reponding). + /// operation events are called or the ThrottleManager will never end (will stop responding). /// 2) The HandleRunspaceStateChanged event handler remains in the Runspace /// StateChanged event call chain until this object is disposed. We have to /// disallow the HandleRunspaceStateChanged event from running and throwing diff --git a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs index dac98f99449..15d2b1470b1 100644 --- a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs +++ b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs @@ -1375,7 +1375,7 @@ private void UpdateUri(Uri uri) private string _appName = s_defaultAppName; private Uri _connectionUri = new Uri(LocalHostUriString); // uri of this connection private PSCredential _credential; // credentials to be used for this connection - private string _shellUri = DefaultShellUri; // shell thats specified by the user + private string _shellUri = DefaultShellUri; // shell that's specified by the user private string _thumbPrint; private AuthenticationMechanism _proxyAuthentication; private PSCredential _proxyCredential; diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManNativeAPI.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManNativeAPI.cs index 6dd3614a62f..289f88c576f 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManNativeAPI.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManNativeAPI.cs @@ -1404,7 +1404,7 @@ internal struct WSManShellStartupInfoStruct /// /// Managed to unmanaged representation of WSMAN_SHELL_STARTUP_INFO. /// It converts managed values into an unmanaged compatible WSManShellStartupInfoStruct that - /// is marshaled into unmanaged memory. + /// is marshalled into unmanaged memory. /// internal struct WSManShellStartupInfo_ManToUn : IDisposable { @@ -2006,13 +2006,13 @@ private struct WSManBinaryDataInternal internal class WSManPluginRequest { /// - /// Unmarshaled WSMAN_SENDER_DETAILS struct. + /// Unmarshalled WSMAN_SENDER_DETAILS struct. /// internal WSManSenderDetails senderDetails; internal string locale; internal string resourceUri; /// - /// Unmarshaled WSMAN_OPERATION_INFO struct. + /// Unmarshalled WSMAN_OPERATION_INFO struct. /// internal WSManOperationInfo operationInfo; @@ -2100,7 +2100,7 @@ internal class WSManSenderDetails internal string senderName; internal string authenticationMechanism; internal WSManCertificateDetails certificateDetails; - internal IntPtr clientToken; // TODO: How should this be marshaled????? + internal IntPtr clientToken; // TODO: How should this be marshalled????? internal string httpUrl; /// diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginShellSession.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginShellSession.cs index c7bf908d56b..54a7b66d0c1 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginShellSession.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginShellSession.cs @@ -770,7 +770,7 @@ internal bool ProcessArguments( internal void Stop( WSManNativeApi.WSManPluginRequest requestDetails) { - // stop the command..command will be stoped if we raise ClosingEvent on + // stop the command..command will be stopped if we raise ClosingEvent on // transport manager. transportMgr.PerformStop(); WSManPluginInstance.ReportWSManOperationComplete(requestDetails, null); diff --git a/src/System.Management.Automation/engine/remoting/server/ServerRemotingProtocol2.cs b/src/System.Management.Automation/engine/remoting/server/ServerRemotingProtocol2.cs index f45a67583a9..11761c25af8 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerRemotingProtocol2.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerRemotingProtocol2.cs @@ -348,7 +348,7 @@ internal TypeTable TypeTable /// /// Data to send. /// This overload takes a RemoteDataObject and should - /// be the one thats used to send data from within this + /// be the one that's used to send data from within this /// data structure handler class private void SendDataAsync(RemoteDataObject data) { @@ -785,7 +785,7 @@ internal Runspace RunspaceUsedToInvokePowerShell /// /// Data to send. /// This overload takes a RemoteDataObject and should - /// be the one thats used to send data from within this + /// be the one that's used to send data from within this /// data structure handler class private void SendDataAsync(RemoteDataObject data) { diff --git a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs index f6b78c884df..17793d78aa9 100644 --- a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs +++ b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs @@ -1968,7 +1968,7 @@ private static string LookupHash(uint h) /// /// If a hash matches, we ignore the possibility of a /// collision. If the hash is acceptable, collisions will - /// be infrequent and we'll just log an occasionaly script + /// be infrequent and we'll just log an occasional script /// that isn't really suspicious. /// /// The string matching the hash, or null. diff --git a/src/System.Management.Automation/engine/serialization.cs b/src/System.Management.Automation/engine/serialization.cs index d85b56b4470..0a78c4ee26c 100644 --- a/src/System.Management.Automation/engine/serialization.cs +++ b/src/System.Management.Automation/engine/serialization.cs @@ -733,7 +733,7 @@ internal static string MaskDeserializationPrefix(string typeName) /// /// Gets a new collection of typenames without "Deserialization." prefix - /// in the typename. This will allow to map type info/format info of the orignal type + /// in the typename. This will allow to map type info/format info of the original type /// for deserialized objects. /// /// @@ -3988,7 +3988,7 @@ private object ReadListContainer(ContainerType ct) } /// - /// Utilitily class for ReadDictionary(), supporting ordered or non-ordered Dictionaty methods. + /// Utility class for ReadDictionary(), supporting ordered or non-ordered Dictionary methods. /// private class PSDictionary { @@ -6523,7 +6523,7 @@ public void Add(string key, PSPrimitiveDictionary[] value) /// /// If originalHash contains PSVersionTable, then just returns the Cloned copy of - /// the original hash. Othewise, creates a clone copy and add PSVersionInfo.GetPSVersionTable + /// the original hash. Otherwise, creates a clone copy and add PSVersionInfo.GetPSVersionTable /// to the clone and returns. /// /// diff --git a/src/System.Management.Automation/help/CommandHelpProvider.cs b/src/System.Management.Automation/help/CommandHelpProvider.cs index 0cbb42b821d..f55b345e45b 100644 --- a/src/System.Management.Automation/help/CommandHelpProvider.cs +++ b/src/System.Management.Automation/help/CommandHelpProvider.cs @@ -879,7 +879,7 @@ private HelpInfo GetFromCommandCacheOrCmdletInfo(CmdletInfo cmdletInfo) /// /// Used to retrieve helpinfo by removing the prefix from the noun portion of a command name. /// Import-Module and Import-PSSession supports changing the name of a command - /// by suppling a custom prefix. In those cases, the help content is stored by using the + /// by supplying a custom prefix. In those cases, the help content is stored by using the /// original command name (without prefix) as the key. /// /// This method retrieves the help content by suppressing the prefix and then making a copy diff --git a/src/System.Management.Automation/help/HelpCommands.cs b/src/System.Management.Automation/help/HelpCommands.cs index c8debb12851..af79758dcb3 100644 --- a/src/System.Management.Automation/help/HelpCommands.cs +++ b/src/System.Management.Automation/help/HelpCommands.cs @@ -508,7 +508,7 @@ private void GetAndWriteParameterInfo(HelpInfo helpInfo) /// /// Category specified by the user. /// - /// If the request cant be serviced. + /// If the request can't be serviced. /// private void ValidateAndThrowIfError(HelpCategory cat) { diff --git a/src/System.Management.Automation/utils/PlatformInvokes.cs b/src/System.Management.Automation/utils/PlatformInvokes.cs index 109eef919d6..4405f2f6910 100644 --- a/src/System.Management.Automation/utils/PlatformInvokes.cs +++ b/src/System.Management.Automation/utils/PlatformInvokes.cs @@ -487,7 +487,7 @@ internal struct PRIVILEGE_SET /// /// Retrieves the current process token. - /// This function exists just for backward compatibility. It is prefered to use the other override that takes 'SafeHandle' as parameter. + /// This function exists just for backward compatibility. It is preferred to use the other override that takes 'SafeHandle' as parameter. /// /// Process handle. /// Token access. diff --git a/src/System.Management.Automation/utils/Verbs.cs b/src/System.Management.Automation/utils/Verbs.cs index 21ef9cbad22..e234609359a 100644 --- a/src/System.Management.Automation/utils/Verbs.cs +++ b/src/System.Management.Automation/utils/Verbs.cs @@ -348,7 +348,7 @@ public static class VerbsLifecycle public const string Build = "Build"; /// - /// Finalize an interruptable activity. Makes pending changes permanent. + /// Finalize an interruptible activity. Makes pending changes permanent. /// public const string Complete = "Complete"; From 4e80e7611f27a758b70b7356759c65bd57eb2b11 Mon Sep 17 00:00:00 2001 From: Staffan Gustafsson Date: Tue, 31 Jan 2023 06:13:55 +0100 Subject: [PATCH 325/779] Adding missing guard for telemetry optout to avoid NRE when importing modules (#18949) --- src/System.Management.Automation/utils/Telemetry.cs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/System.Management.Automation/utils/Telemetry.cs b/src/System.Management.Automation/utils/Telemetry.cs index 3d9f3c9e1f7..6ae1a93d6de 100644 --- a/src/System.Management.Automation/utils/Telemetry.cs +++ b/src/System.Management.Automation/utils/Telemetry.cs @@ -661,6 +661,11 @@ private static bool GetEnvironmentVariableAsBool(string name, bool defaultValue) /// The module version to report. The default value is the anonymous version '0.0.0.0'. internal static void SendModuleTelemetryMetric(TelemetryType telemetryType, string moduleName, string moduleVersion = AnonymousVersion) { + if (!CanSendTelemetry) + { + return; + } + try { string allowedModuleName = GetModuleName(moduleName); From f3485228f7a422be14d086c17379f50c0e222e70 Mon Sep 17 00:00:00 2001 From: Paul Higinbotham Date: Tue, 31 Jan 2023 08:23:44 -0800 Subject: [PATCH 326/779] Ignore expected error for file systems not supporting alternate streams (#19065) --- .../namespaces/FileSystemProvider.cs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index ddd738def75..4d7acd99d32 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -8098,7 +8098,10 @@ internal static List GetStreams(string path) // Directories don't normally have alternate streams, so this is not an exceptional state. // If a directory has no alternate data streams, FindFirstStreamW returns ERROR_HANDLE_EOF. - if (error == NativeMethods.ERROR_HANDLE_EOF) + // If the file system (such as FAT32) does not support alternate streams, then + // ERROR_INVALID_PARAMETER is returned by FindFirstStreamW. See documentation: + // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-findfirststreamw + if (error == NativeMethods.ERROR_HANDLE_EOF || error == NativeMethods.ERROR_INVALID_PARAMETER) { return alternateStreams; } @@ -8135,7 +8138,9 @@ internal static List GetStreams(string path) int lastError = Marshal.GetLastWin32Error(); if (lastError != NativeMethods.ERROR_HANDLE_EOF) + { throw new Win32Exception(lastError); + } } finally { handle.Dispose(); } From 794d93cdf8008c244c0eed6a9096bc574d12037e Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Tue, 31 Jan 2023 11:19:39 -0800 Subject: [PATCH 327/779] Update the cgmanifest (#18814) Co-authored-by: adityapatwardhan --- tools/cgmanifest.json | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tools/cgmanifest.json b/tools/cgmanifest.json index ce5b8f243a1..d38c15ae461 100644 --- a/tools/cgmanifest.json +++ b/tools/cgmanifest.json @@ -1,5 +1,4 @@ { - "$schema": "https://json.schemastore.org/component-detection-manifest.json", "Registrations": [ { "Component": { @@ -106,7 +105,7 @@ "Type": "nuget", "Nuget": { "Name": "Microsoft.Extensions.ObjectPool", - "Version": "7.0.1" + "Version": "7.0.2" } }, "DevelopmentDependency": false @@ -176,7 +175,7 @@ "Type": "nuget", "Nuget": { "Name": "Microsoft.PowerShell.Native", - "Version": "7.3.1" + "Version": "7.3.2" } }, "DevelopmentDependency": false @@ -1401,5 +1400,6 @@ }, "DevelopmentDependency": false } - ] + ], + "$schema": "https://json.schemastore.org/component-detection-manifest.json" } From 337c865dd3b7684e8dc6ac7026450071455afa26 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 31 Jan 2023 11:31:44 -0800 Subject: [PATCH 328/779] Bump XunitXml.TestLogger from 3.0.70 to 3.0.78 (#19066) Bumps [XunitXml.TestLogger](https://github.com/spekt/xunit.testlogger) from 3.0.70 to 3.0.78. - [Release notes](https://github.com/spekt/xunit.testlogger/releases) - [Changelog](https://github.com/spekt/xunit.testlogger/blob/master/CHANGELOG.md) - [Commits](https://github.com/spekt/xunit.testlogger/compare/v3.0.70...v3.0.78) --- updated-dependencies: - dependency-name: XunitXml.TestLogger dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- test/xUnit/xUnit.tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/xUnit/xUnit.tests.csproj b/test/xUnit/xUnit.tests.csproj index 6f78ed96964..14bf2b5f4d4 100644 --- a/test/xUnit/xUnit.tests.csproj +++ b/test/xUnit/xUnit.tests.csproj @@ -26,7 +26,7 @@ - + From 9ae7d68947851d388a309bf39675bd6e44c71065 Mon Sep 17 00:00:00 2001 From: spaette <111918424+spaette@users.noreply.github.com> Date: Tue, 31 Jan 2023 13:35:32 -0600 Subject: [PATCH 329/779] Correct spelling of custom in event (#19059) --- .../PowerShell.Core.Instrumentation.man | 2 +- src/System.Management.Automation/resources/EventResource.resx | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/PowerShell.Core.Instrumentation/PowerShell.Core.Instrumentation.man b/src/PowerShell.Core.Instrumentation/PowerShell.Core.Instrumentation.man index 8979ad8ebe0..fb221cfe964 100644 --- a/src/PowerShell.Core.Instrumentation/PowerShell.Core.Instrumentation.man +++ b/src/PowerShell.Core.Instrumentation/PowerShell.Core.Instrumentation.man @@ -4869,7 +4869,7 @@ /> Runspace Id: {0} Pipeline Id: {1}. Server is sending data of size {2} to client. DataType: {3} TargetInterface: {4} - Request {0}. Creating a server remote session. UserName: {1} Custome Shell Id: {2} + Request {0}. Creating a server remote session. UserName: {1} Custom Shell Id: {2} Reporting context for request: {0} Context Reported: {0} From b2c4888ebb64a524f0816111bc2d999aa64a2c5f Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Tue, 31 Jan 2023 12:06:29 -0800 Subject: [PATCH 330/779] Add Windows ARM64 CI (#19040) * Add CI for win-arm64 * Add common function to test for windows arm64 * Update because string where items need investigation --------- Co-authored-by: Aditya Patwardhan --- .vsts-ci/templates/ci-build.yml | 45 ++++++++- .vsts-ci/templates/windows-test.yml | 24 ++++- .vsts-ci/windows-arm64.yml | 95 +++++++++++++++++++ .vsts-ci/windows.yml | 1 + build.psm1 | 11 ++- test/powershell/Host/ConsoleHost.Tests.ps1 | 8 ++ test/powershell/Host/ScreenReader.Tests.ps1 | 6 +- .../TabCompletion/TabCompletion.Tests.ps1 | 8 ++ .../NativeCommandProcessor.Tests.ps1 | 4 + .../NativeExecution/NativeStreams.Tests.ps1 | 6 +- .../PSSessionConfiguration.Tests.ps1 | 9 +- .../FileSystem.Tests.ps1 | 7 ++ .../Get-HotFix.Tests.ps1 | 6 ++ .../Get-Process.Tests.ps1 | 4 + .../Environment-Variables.Tests.ps1 | 4 + .../Format-Table.Tests.ps1 | 11 ++- .../Invoke-Item.Tests.ps1 | 4 + .../Set-Date.Tests.ps1 | 4 + .../Write-Debug.Tests.ps1 | 8 +- .../Write-Error.Tests.ps1 | 8 +- .../Write-Progress.Tests.ps1 | 7 +- .../Write-Verbose.Tests.ps1 | 8 +- .../CredSSP.Tests.ps1 | 4 + .../Basic/GroupPolicySettings.Tests.ps1 | 12 ++- .../powershell/engine/COM/COM.Basic.Tests.ps1 | 4 + .../Get-ExperimentalFeature.Tests.ps1 | 4 + .../engine/Help/HelpSystem.Tests.ps1 | 16 ++++ .../InvokeCommandRemoteDebug.Tests.ps1 | 6 ++ .../Modules/HelpersCommon/HelpersCommon.psd1 | 9 +- .../Modules/HelpersCommon/HelpersCommon.psm1 | 4 + tools/ci.psm1 | 9 +- 31 files changed, 331 insertions(+), 25 deletions(-) create mode 100644 .vsts-ci/windows-arm64.yml diff --git a/.vsts-ci/templates/ci-build.yml b/.vsts-ci/templates/ci-build.yml index e64ab4967a2..c502a9a3d46 100644 --- a/.vsts-ci/templates/ci-build.yml +++ b/.vsts-ci/templates/ci-build.yml @@ -1,16 +1,50 @@ parameters: - pool: 'windows-latest' - jobName: 'win_build' - displayName: Windows Build + - name: pool + default: 'windows-latest' + - name: imageName + default: 'PSWindows11-ARM64' + - name: jobName + default: 'win_build' + - name: displayName + default: Windows Build + - name: PoolType + default: AzDoHosted + type: string + values: + - AzDoHosted + - 1esHosted jobs: - job: ${{ parameters.jobName }} pool: - vmImage: ${{ parameters.pool }} + ${{ if eq( parameters.PoolType, 'AzDoHosted') }}: + vmImage: ${{ parameters.pool }} + ${{ else }}: + name: ${{ parameters.pool }} + demands: + - ImageOverride -equals ${{ parameters.imageName }} displayName: ${{ parameters.displayName }} steps: + - powershell: | + [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12 + $pwsh = Get-Command pwsh -ErrorAction SilentlyContinue -CommandType Application + + if ($null -eq $pwsh) { + $powerShellPath = Join-Path -Path $env:AGENT_TEMPDIRECTORY -ChildPath 'powershell' + Invoke-WebRequest -Uri https://raw.githubusercontent.com/PowerShell/PowerShell/master/tools/install-powershell.ps1 -outfile ./install-powershell.ps1 + ./install-powershell.ps1 -Destination $powerShellPath + $vstsCommandString = "vso[task.setvariable variable=PATH]$powerShellPath;$env:PATH" + Write-Host "sending " + $vstsCommandString + Write-Host "##$vstsCommandString" + } + + displayName: Install PowerShell + + - checkout: self + fetchDepth: 1000 + - pwsh: | Get-ChildItem -Path env: displayName: Capture Environment @@ -26,6 +60,9 @@ jobs: - pwsh: | Import-Module .\tools\ci.psm1 Invoke-CIInstall -SkipUser + Write-Verbose -Verbose "Start Sync-PSTags" + Sync-PSTags -AddRemoteIfMissing + Write-Verbose -Verbose "End Sync-PSTags" displayName: Bootstrap condition: succeeded() diff --git a/.vsts-ci/templates/windows-test.yml b/.vsts-ci/templates/windows-test.yml index 2e5d5b67e24..50ff67a32a8 100644 --- a/.vsts-ci/templates/windows-test.yml +++ b/.vsts-ci/templates/windows-test.yml @@ -1,5 +1,6 @@ parameters: pool: 'windows-2019' + imageName: 'PSWindows11-ARM64' parentJobs: [] purpose: '' tagSet: 'CI' @@ -9,11 +10,32 @@ jobs: dependsOn: ${{ parameters.parentJobs }} pool: - vmImage: ${{ parameters.pool }} + ${{ if startsWith( parameters.pool, 'windows-') }}: + vmImage: ${{ parameters.pool }} + ${{ else }}: + name: ${{ parameters.pool }} + demands: + - ImageOverride -equals ${{ parameters.imageName }} displayName: Windows Test - ${{ parameters.purpose }} - ${{ parameters.tagSet }} steps: + - powershell: | + [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12 + $pwsh = Get-Command pwsh -ErrorAction SilentlyContinue -CommandType Application + + if ($null -eq $pwsh) { + $powerShellPath = Join-Path -Path $env:AGENT_TEMPDIRECTORY -ChildPath 'powershell' + Invoke-WebRequest -Uri https://raw.githubusercontent.com/PowerShell/PowerShell/master/tools/install-powershell.ps1 -outfile ./install-powershell.ps1 + ./install-powershell.ps1 -Destination $powerShellPath + $vstsCommandString = "vso[task.setvariable variable=PATH]$powerShellPath;$env:PATH" + Write-Host "sending " + $vstsCommandString + Write-Host "##$vstsCommandString" + } + + displayName: Install PowerShell if missing + condition: ne('${{ parameters.pool }}', 'windows-2019') + - pwsh: | Get-ChildItem -Path env: displayName: Capture Environment diff --git a/.vsts-ci/windows-arm64.yml b/.vsts-ci/windows-arm64.yml new file mode 100644 index 00000000000..be4cfcbaf4c --- /dev/null +++ b/.vsts-ci/windows-arm64.yml @@ -0,0 +1,95 @@ +name: PR-$(System.PullRequest.PullRequestNumber)-$(Date:yyyyMMdd)$(Rev:.rr) +trigger: + # Batch merge builds together while a merge build is running + batch: true + branches: + include: + - master + - release* + - feature* + paths: + include: + - '*' + exclude: + - .vsts-ci/misc-analysis.yml + - .github/ISSUE_TEMPLATE/* + - .dependabot/config.yml + - test/perf/* +pr: + branches: + include: + - master + - release* + - feature* + paths: + include: + - '*' + exclude: + - .dependabot/config.yml + - .github/ISSUE_TEMPLATE/* + - .vsts-ci/misc-analysis.yml + - tools/cgmanifest.json + - LICENSE.txt + - test/common/markdown/* + - test/perf/* + - tools/packaging/* + - tools/releaseBuild/* + - tools/releaseBuild/azureDevOps/templates/* + - README.md + - .spelling + +variables: + - name: GIT_CONFIG_PARAMETERS + value: "'core.autocrlf=false'" + - name: DOTNET_CLI_TELEMETRY_OPTOUT + value: 1 + - name: POWERSHELL_TELEMETRY_OPTOUT + value: 1 + # Avoid expensive initialization of dotnet cli, see: https://donovanbrown.com/post/Stop-wasting-time-during-NET-Core-builds + - name: DOTNET_SKIP_FIRST_TIME_EXPERIENCE + value: 1 + - name: __SuppressAnsiEscapeSequences + value: 1 + - group: PoolNames + +resources: +- repo: self + clean: true + +stages: +- stage: BuildWin + displayName: Build for Windows + jobs: + - template: templates/ci-build.yml + parameters: + pool: $(armPool) + PoolType: 1esHosted + +- stage: TestWin + displayName: Test for Windows + jobs: + - template: templates/windows-test.yml + parameters: + purpose: UnelevatedPesterTests + tagSet: CI + pool: $(armPool) + + - template: templates/windows-test.yml + parameters: + purpose: ElevatedPesterTests + tagSet: CI + pool: $(armPool) + + - template: templates/windows-test.yml + parameters: + purpose: UnelevatedPesterTests + tagSet: Others + pool: $(armPool) + + - template: templates/windows-test.yml + parameters: + purpose: ElevatedPesterTests + tagSet: Others + pool: $(armPool) + + - template: templates/verify-xunit.yml diff --git a/.vsts-ci/windows.yml b/.vsts-ci/windows.yml index f886d2bd337..ef6241800e4 100644 --- a/.vsts-ci/windows.yml +++ b/.vsts-ci/windows.yml @@ -45,6 +45,7 @@ variables: # Avoid expensive initialization of dotnet cli, see: https://donovanbrown.com/post/Stop-wasting-time-during-NET-Core-builds DOTNET_SKIP_FIRST_TIME_EXPERIENCE: 1 __SuppressAnsiEscapeSequences: 1 + NugetSecurityAnalysisWarningLevel: none resources: - repo: self diff --git a/build.psm1 b/build.psm1 index fd2858ba288..3b808c562cf 100644 --- a/build.psm1 +++ b/build.psm1 @@ -19,7 +19,7 @@ $script:Options = $null $dotnetMetadata = Get-Content $PSScriptRoot/DotnetRuntimeMetadata.json | ConvertFrom-Json $dotnetCLIChannel = $dotnetMetadata.Sdk.Channel $dotnetCLIQuality = $dotnetMetadata.Sdk.Quality -$dotnetAzureFeed = $env:__DONET_RUNTIME_FEED ?? $dotnetMetadata.Sdk.azureFeed +$dotnetAzureFeed = if (-not $env:__DONET_RUNTIME_FEED ) { $dotnetMetadata.Sdk.azureFeed } $dotnetAzureFeedSecret = $env:__DONET_RUNTIME_FEED_KEY $dotnetSDKVersionOveride = $dotnetMetadata.Sdk.sdkImageOverride $dotnetCLIRequiredVersion = $(Get-Content $PSScriptRoot/global.json | ConvertFrom-Json).Sdk.Version @@ -138,6 +138,7 @@ function Get-EnvironmentInformation { $environment += @{'IsAdmin' = (New-Object Security.Principal.WindowsPrincipal ([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)} $environment += @{'nugetPackagesRoot' = "${env:USERPROFILE}\.nuget\packages", "${env:NUGET_PACKAGES}"} + $environment += @{ 'OSArchitecture' = [System.Runtime.InteropServices.RuntimeInformation]::ProcessArchitecture } } else { @@ -1343,7 +1344,7 @@ function Start-PSPester { $command += " *> $outputBufferFilePath; '__UNELEVATED_TESTS_THE_END__' >> $outputBufferFilePath" } - Write-Verbose $command + Write-Verbose $command -Verbose $script:nonewline = $true $script:inerror = $false @@ -1600,11 +1601,17 @@ function script:Start-UnelevatedProcess [string]$process, [string[]]$arguments ) + if (-not $environment.IsWindows) { throw "Start-UnelevatedProcess is currently not supported on non-Windows platforms" } + if (-not $environment.OSArchitecture -eq 'arm64') + { + throw "Start-UnelevatedProcess is currently not supported on arm64 platforms" + } + runas.exe /trustlevel:0x20000 "$process $arguments" } diff --git a/test/powershell/Host/ConsoleHost.Tests.ps1 b/test/powershell/Host/ConsoleHost.Tests.ps1 index 7ee7fd07a46..e821df9b457 100644 --- a/test/powershell/Host/ConsoleHost.Tests.ps1 +++ b/test/powershell/Host/ConsoleHost.Tests.ps1 @@ -93,6 +93,10 @@ Describe "ConsoleHost unit tests" -tags "Feature" { } It "Clear-Host does not injects data into PowerShell output stream" { + if (Test-IsWindowsArm64) { + Set-ItResult -Pending -Because "ARM64 runs in non-interactively mode and Clear-Host does not work." + } + & { Clear-Host; 'hi' } | Should -BeExactly 'hi' } @@ -997,6 +1001,10 @@ public enum ShowWindowCommands : int ) { param ($WindowStyle) + if (Test-IsWindowsArm64) { + Set-ItResult -Pending -Because "All windows are showing up as hidden or ARM64" + } + try { $ps = Start-Process $powershell -ArgumentList "-WindowStyle $WindowStyle -noexit -interactive" -PassThru $startTime = Get-Date diff --git a/test/powershell/Host/ScreenReader.Tests.ps1 b/test/powershell/Host/ScreenReader.Tests.ps1 index 35f86459861..1b11a0e3ffa 100644 --- a/test/powershell/Host/ScreenReader.Tests.ps1 +++ b/test/powershell/Host/ScreenReader.Tests.ps1 @@ -44,8 +44,12 @@ Describe "Validate start of console host" -Tag CI { } It "PSReadLine should not be auto-loaded when screen reader status is active" -Skip:(-not $IsWindows) { + if (Test-IsWindowsArm64) { + Set-ItResult -Pending -Because "Needs investigation, PSReadline loads on ARM64" + } + $output = & "$PSHOME/pwsh" -noprofile -noexit -c "Get-Module PSReadLine; exit" - $output.Length | Should -BeExactly 2 + $output.Length | Should -BeExactly 2 -Because "There should be two lines of output but we got: $output" ## The warning message about screen reader should be returned, but the PSReadLine module should not be loaded. $output[0] | Should -BeLike "Warning:*'Import-Module PSReadLine'." diff --git a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 index 982085ff268..3ed99228d7a 100644 --- a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 +++ b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 @@ -1213,6 +1213,9 @@ Verb-Noun -Param1 Hello ^ } It "Tab completion UNC path" -Skip:(!$IsWindows) { + if (!$env:HOMEDRIVE) { + Set-ItResult -Skipped -Because "Homerdrive is not set" + } $homeDrive = $env:HOMEDRIVE.Replace(":", "$") $beforeTab = "\\localhost\$homeDrive\wind" $afterTab = "& '\\localhost\$homeDrive\Windows'" @@ -1995,6 +1998,11 @@ dir -Recurse ` It "Input '' should successfully complete" -TestCases $testCases -Skip:(!$IsWindows) { param($inputStr, $expected) + if (Test-IsWindowsArm64) { + Set-ItResult -Pending -Because "TBD" + } + + $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length $res.CompletionMatches.Count | Should -BeGreaterThan 0 $res.CompletionMatches[0].CompletionText | Should -BeExactly $expected diff --git a/test/powershell/Language/Scripting/NativeExecution/NativeCommandProcessor.Tests.ps1 b/test/powershell/Language/Scripting/NativeExecution/NativeCommandProcessor.Tests.ps1 index d62230bb45a..d736d4b3945 100644 --- a/test/powershell/Language/Scripting/NativeExecution/NativeCommandProcessor.Tests.ps1 +++ b/test/powershell/Language/Scripting/NativeExecution/NativeCommandProcessor.Tests.ps1 @@ -145,6 +145,10 @@ Describe "Native Command Processor" -tags "Feature" { } It "Should not block running Windows executables" -Skip:(!$IsWindows -or !(Get-Command notepad.exe)) { + if (Test-IsWindowsArm64) { + Set-ItResult -Pending -Because "Needs investigation" + } + function FindNewNotepad { Get-Process -Name notepad -ErrorAction Ignore | Where-Object { $_.Id -NotIn $dontKill } diff --git a/test/powershell/Language/Scripting/NativeExecution/NativeStreams.Tests.ps1 b/test/powershell/Language/Scripting/NativeExecution/NativeStreams.Tests.ps1 index 755ea27f794..53ed45fe4da 100644 --- a/test/powershell/Language/Scripting/NativeExecution/NativeStreams.Tests.ps1 +++ b/test/powershell/Language/Scripting/NativeExecution/NativeStreams.Tests.ps1 @@ -53,7 +53,11 @@ Describe "Native streams behavior with PowerShell" -Tags 'CI' { ($out | Out-String).Replace("`r", '') | Should -BeExactly "foo`n`nbar`n`nbazmiddlefoo`n`nbar`n`nbaz`n" } - It 'does not get truncated or split when redirected' { + It 'Does not get truncated or split when redirected' { + if (Test-IsWindowsArm64) { + Set-ItResult -Pending -Because "IOException: The handle is invalid." + } + $longtext = "0123456789" while ($longtext.Length -lt [console]::WindowWidth) { $longtext += $longtext diff --git a/test/powershell/Modules/Microsoft.PowerShell.Core/PSSessionConfiguration.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Core/PSSessionConfiguration.Tests.ps1 index a4e9e1e5116..8ab4047c279 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Core/PSSessionConfiguration.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Core/PSSessionConfiguration.Tests.ps1 @@ -10,7 +10,8 @@ try $originalWarningPreference = $WarningPreference $WarningPreference = "SilentlyContinue" # Skip all tests if can't write to $PSHOME as Register-PSSessionConfiguration writes to $PSHOME - $IsNotSkipped = ($IsWindows -and $IsCoreCLR -and (Test-IsElevated) -and (Test-CanWriteToPsHome)) + # or if the processor architecture is Arm64 + $IsNotSkipped = ($IsWindows -and $IsCoreCLR -and (Test-IsElevated) -and (Test-CanWriteToPsHome) -and [System.Runtime.InteropServices.RuntimeInformation]::ProcessArchitecture -ne [System.Runtime.InteropServices.Architecture]::Arm64) $PSDefaultParameterValues["it:skip"] = !$IsNotSkipped # @@ -830,6 +831,12 @@ namespace PowershellTestConfigNamespace Describe "Validate Enable-PSSession Cmdlet" -Tags @("Feature", 'RequireAdminOnWindows') { BeforeAll { + if (Test-IsWindowsArm64) { + Write-Verbose "remoting is not setup on ARM64, skipping tests" -Verbose + $PSDefaultParameterValues["it:skip"] = $true + return + } + if ($IsNotSkipped) { Enable-PSRemoting } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/FileSystem.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/FileSystem.Tests.ps1 index 8f13cb48662..0f5222b3db5 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/FileSystem.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/FileSystem.Tests.ps1 @@ -355,6 +355,10 @@ Describe "Basic FileSystem Provider Tests" -Tags "CI" { ) { param ($cmdline, $expectedError) + if (Test-IsElevated) { + Set-ItResult -Skipped -Because "Process must NOT be elevated" + } + $scriptBlock = [scriptblock]::Create($cmdline) $scriptBlock | Should -Throw -ErrorId $expectedError } @@ -1557,6 +1561,9 @@ Describe "Remove-Item UnAuthorized Access" -Tags "CI", "RequireAdminOnWindows" { } It "Access-denied test for removing a folder" -Skip:(-not $IsWindows) { + if (Test-IsWindowsArm64) { + Set-ItResult -Pending -Because "runas.exe /trustlevel:0x20000 is not supported on ARM64" + } # The expected error is returned when there is a empty directory with the user does not have authorization to is deleted. # It cannot have 'System. 'Hidden' or 'ReadOnly' attribute as well as -Force should not be used. diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Get-HotFix.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Get-HotFix.Tests.ps1 index 02f6bbf9c4f..b3539df487b 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Get-HotFix.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Get-HotFix.Tests.ps1 @@ -9,6 +9,12 @@ Describe "Get-HotFix Tests" -Tag CI { if (!$IsWindows) { $skip = $true } + elseif (Test-IsWindowsArm64) { + # Win32Exception: Failed to load required native library 'C:\Windows\Microsoft.NET\Framework64\v4.0.30319\wminet_utils.dll'. + Write-Verbose "needed provider not on ARM64, skipping tests" -Verbose + $PSDefaultParameterValues["it:skip"] = $true + return + } else { # skip the tests if there are no hotfixes returned $qfe = Get-CimInstance Win32_QuickFixEngineering diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Process.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Process.Tests.ps1 index 4cde8baefee..90e20a2c479 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Process.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Process.Tests.ps1 @@ -79,6 +79,10 @@ Describe "Get-Process" -Tags "CI" { } It "Should fail to run Get-Process with -IncludeUserName without admin" -Skip:(!$IsWindows) { + if (Test-IsElevated) { + Set-ItResult -Skipped -Because "must NOT be run as admin" + } + { Get-Process -IncludeUserName } | Should -Throw -ErrorId "IncludeUserNameRequiresElevation,Microsoft.PowerShell.Commands.GetProcessCommand" } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Environment-Variables.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Environment-Variables.Tests.ps1 index 4c2b839259b..cdc9a5fe584 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Environment-Variables.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Environment-Variables.Tests.ps1 @@ -20,6 +20,10 @@ Describe "Environment-Variables" -Tags "CI" { It "Should have the correct HOME" { if ($IsWindows) { + if (!$ENV:HOMEPATH) { + Set-ItResult -Skipped -Because "Homepath is not set" + } + # \Windows\System32 is found as $env:HOMEPATH for temporary profiles $expected = "\Users", "\Windows" Split-Path $ENV:HOMEPATH -Parent | Should -BeIn $expected diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Format-Table.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Format-Table.Tests.ps1 index f5bbae4b0b5..6f93c3903e9 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Format-Table.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Format-Table.Tests.ps1 @@ -6,6 +6,13 @@ Describe "Format-Table" -Tags "CI" { $outputRendering = $PSStyle.OutputRendering $PSStyle.OutputRendering = 'plaintext' } + $noConsole = $true + try { + if ([Console]::WindowHeight -ne 0) { + $noConsole = $false + } + } catch { + } } AfterAll { @@ -805,7 +812,7 @@ A Name B } } - It "-RepeatHeader should output the header at every screen full" -Skip:([Console]::WindowHeight -eq 0) { + It "-RepeatHeader should output the header at every screen full" -Skip:$noConsole { $numHeaders = 4 $numObjects = [Console]::WindowHeight * $numHeaders $out = 1..$numObjects | ForEach-Object { @{foo=$_} } | Format-Table -RepeatHeader | Out-String @@ -813,7 +820,7 @@ A Name B ($lines | Select-String "Name\s*Value").Count | Should -Be ($numHeaders + 1) } - It "-RepeatHeader should output the header at every screen full for custom table" -Skip:([Console]::WindowHeight -eq 0) { + It "-RepeatHeader should output the header at every screen full for custom table" -Skip:$noConsole { $numHeaders = 4 $numObjects = [Console]::WindowHeight * $numHeaders $out = 1..$numObjects | ForEach-Object { [pscustomobject]@{foo=$_;bar=$_;hello=$_;world=$_} } | Format-Table -Property hello, world -RepeatHeader | Out-String diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Invoke-Item.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Invoke-Item.Tests.ps1 index 72ab978b69f..64ee47b3ecb 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Invoke-Item.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Invoke-Item.Tests.ps1 @@ -214,6 +214,10 @@ Categories=Application; It "Should invoke a folder without error" -Skip:(!$supportedEnvironment) { if ($IsWindows) { + if (Test-IsWindowsArm64) { + Set-ItResult -Pending -Because "Shell.Application errors with COMException: The server process could not be started because the configured identity is incorrect. Check the username and password." + } + $shell = New-Object -ComObject "Shell.Application" $windows = $shell.Windows() diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Set-Date.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Set-Date.Tests.ps1 index f382c6fa214..f189879d35b 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Set-Date.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Set-Date.Tests.ps1 @@ -32,6 +32,10 @@ Describe "Set-Date for admin" -Tag @('CI', 'RequireAdminOnWindows', 'RequireSudo Describe "Set-Date" -Tag 'CI' { It "Set-Date should produce an error in a non-elevated context" { + if (Test-IsElevated) { + Set-ItResult -Skipped -Because "must NOT be run as admin" + } + { Get-Date | Set-Date } | Should -Throw -ErrorId "System.ComponentModel.Win32Exception,Microsoft.PowerShell.Commands.SetDateCommand" } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Write-Debug.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Write-Debug.Tests.ps1 index 5dfc696b150..f93027cc578 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Write-Debug.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Write-Debug.Tests.ps1 @@ -3,8 +3,12 @@ Describe "Write-Debug tests" -Tags "CI" { It "Should not have added line breaks" { $text = "0123456789" - while ($text.Length -lt [Console]::WindowWidth) { - $text += $text + try { + while ($text.Length -lt [Console]::WindowWidth) { + $text += $text + } + } catch { + # Ignore errors if the console doesn't support WindowWidth } $origDebugPref = $DebugPreference $DebugPreference = "Continue" diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Write-Error.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Write-Error.Tests.ps1 index 45ff1614d42..47886aab0f3 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Write-Error.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Write-Error.Tests.ps1 @@ -98,8 +98,12 @@ Describe "Write-Error Tests" -Tags "CI" { It "ErrorRecord should not be truncated or have inserted newlines when redirected from another process" { $longtext = "0123456789" - while ($longtext.Length -lt [console]::WindowWidth) { - $longtext += $longtext + try{ + while ($longtext.Length -lt [console]::WindowWidth) { + $longtext += $longtext + } + } catch { + # Ignore if the console is doesn't support WindowWidth } $PSNativeCommandUseErrorActionPreference = $false $result = & "$PSHOME/pwsh" -noprofile -command "`$ErrorView = 'NormalView'; Write-Error -Message '$longtext'" 2>&1 diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Write-Progress.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Write-Progress.Tests.ps1 index 0f62cbcb6a6..97fd19da1b8 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Write-Progress.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Write-Progress.Tests.ps1 @@ -24,7 +24,12 @@ Describe "Write-Progress DRT Unit Tests" -Tags "CI" { } It 'Activity longer than console width works' { - $activity = 'a' * ([console]::WindowWidth + 1) + try { + $activity = 'a' * ([console]::WindowWidth + 1) + } catch { + Set-ItResult -Skipped -Because 'Console width is not supported' + } + { Write-Progress -Activity $activity -Status ('b' * ([console]::WindowWidth + 1)) -Id 1 } | Should -Not -Throw Write-Progress -Activity $activity -Id 1 -Completed } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Write-Verbose.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Write-Verbose.Tests.ps1 index 3630ef0cf3e..f12086206db 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Write-Verbose.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Write-Verbose.Tests.ps1 @@ -31,8 +31,12 @@ Describe "Write-Verbose" -Tags "CI" { It "Should not have added line breaks" { $text = "0123456789" - while ($text.Length -lt [Console]::WindowWidth) { - $text += $text + try { + while ($text.Length -lt [Console]::WindowWidth) { + $text += $text + } + } catch { + # Ignore errors if the console doesn't support WindowWidth } $origVerbosePref = $VerbosePreference $VerbosePreference = "continue" diff --git a/test/powershell/Modules/Microsoft.WSMan.Management/CredSSP.Tests.ps1 b/test/powershell/Modules/Microsoft.WSMan.Management/CredSSP.Tests.ps1 index 0f13e8e6aad..224064541d5 100644 --- a/test/powershell/Modules/Microsoft.WSMan.Management/CredSSP.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.WSMan.Management/CredSSP.Tests.ps1 @@ -113,6 +113,10 @@ Describe "CredSSP cmdlet error cases tests" -Tags 'Feature' { ) { param ($cmdline, $cmd) + if (Test-IsWindowsArm64) { + Set-ItResult -Pending -Because "WSManCredSSP results in InvalidOperationException on ARM64." + } + $scriptBlock = [scriptblock]::Create($cmdline) $scriptBlock | Should -Throw -ErrorId "System.InvalidOperationException,Microsoft.WSMan.Management.$cmd" } diff --git a/test/powershell/engine/Basic/GroupPolicySettings.Tests.ps1 b/test/powershell/engine/Basic/GroupPolicySettings.Tests.ps1 index 44080453e90..9c6765f0e17 100644 --- a/test/powershell/engine/Basic/GroupPolicySettings.Tests.ps1 +++ b/test/powershell/engine/Basic/GroupPolicySettings.Tests.ps1 @@ -57,6 +57,10 @@ Describe 'Group policy settings tests' -Tag CI,RequireAdminOnWindows { } It 'Module logging policy test' { + if (Test-IsWindowsArm64) { + Set-ItResult -Pending -Because "There is no PowerShellCore event provider on ARM64 until we have an MSI" + } + function TestFeature { param([string]$KeyPath) @@ -85,7 +89,9 @@ Describe 'Group policy settings tests' -Tag CI,RequireAdminOnWindows { Remove-Item $ModuleNamesKeyPath -Recurse -Force # usually event becomes visible in the log after ~500 ms # set timeout for 5 seconds - Wait-UntilTrue -sb { Get-WinEvent -FilterHashtable @{ ProviderName="PowerShellCore"; Id = 4103 } -MaxEvents 5 | ? {$_.Message.Contains($RareCommand)} } -TimeoutInMilliseconds (5*1000) -IntervalInMilliseconds 100 | Should -BeTrue + Wait-UntilTrue -sb { Get-WinEvent -FilterHashtable @{ ProviderName="PowerShellCore"; Id = 4103 } -MaxEvents 5 | + Where-Object {$_.Message.Contains($RareCommand)} } -TimeoutInMilliseconds (5*1000) -IntervalInMilliseconds 100 | + Should -BeTrue } $KeyPath = Join-Path $KeyRoot 'ModuleLogging' @@ -101,6 +107,10 @@ Describe 'Group policy settings tests' -Tag CI,RequireAdminOnWindows { } It 'ScriptBlock logging policy test' { + if (Test-IsWindowsArm64) { + Set-ItResult -Pending -Because "There is no PowerShellCore event provider on ARM64 until we have an MSI" + } + function TestFeature { param([string]$KeyPath) diff --git a/test/powershell/engine/COM/COM.Basic.Tests.ps1 b/test/powershell/engine/COM/COM.Basic.Tests.ps1 index 28974e15420..5265a256256 100644 --- a/test/powershell/engine/COM/COM.Basic.Tests.ps1 +++ b/test/powershell/engine/COM/COM.Basic.Tests.ps1 @@ -106,6 +106,10 @@ Describe 'Basic COM Tests' -Tags "CI" { } It "InvokeMember binder should differentiate PSObject that wraps COM object from other PSObjects" { + if (Test-IsWindowsArm64) { + Set-ItResult -Pending -Because "COMException: The server process could not be started because the configured identity is incorrect. Check the username and password." + } + ## InvokeMember on the member name 'Windows' $shell | ForEach-Object { $_.Windows() } > $null diff --git a/test/powershell/engine/ExperimentalFeature/Get-ExperimentalFeature.Tests.ps1 b/test/powershell/engine/ExperimentalFeature/Get-ExperimentalFeature.Tests.ps1 index 02c4ad856b7..802531ab39e 100644 --- a/test/powershell/engine/ExperimentalFeature/Get-ExperimentalFeature.Tests.ps1 +++ b/test/powershell/engine/ExperimentalFeature/Get-ExperimentalFeature.Tests.ps1 @@ -180,6 +180,10 @@ Describe "Default enablement of Experimental Features" -Tags CI { } It "On preview builds, Experimental Features are enabled" -Skip:(!$isPreview) { + if (Test-IsWindowsArm64) { + Set-ItResult -Pending -Because "Needs investigation" + } + (Join-Path -Path $PSHOME -ChildPath 'powershell.config.json') | Should -Exist foreach ($expFeature in Get-ExperimentalFeature) diff --git a/test/powershell/engine/Help/HelpSystem.Tests.ps1 b/test/powershell/engine/Help/HelpSystem.Tests.ps1 index 06e4e4ae22b..2786e64ee0e 100644 --- a/test/powershell/engine/Help/HelpSystem.Tests.ps1 +++ b/test/powershell/engine/Help/HelpSystem.Tests.ps1 @@ -69,6 +69,10 @@ Describe "Validate that //default.help.txt is present" -Tags @( Describe "Validate that the Help function can Run in strict mode" -Tags @('CI') { It "Help doesn't fail when strict mode is on" { + if (Test-IsWindowsArm64) { + Set-ItResult -Pending -Because "IOException: The handle is invalid." + } + $help = & { # run in nested scope to keep strict mode from affecting other tests @@ -404,16 +408,28 @@ Describe "Get-Help should find pattern alias" -Tags "CI" { Describe "help function uses full view by default" -Tags "CI" { It "help should return full view without -Full switch" { + if (Test-IsWindowsArm64) { + Set-ItResult -Pending -Because "IOException: The handle is invalid." + } + $gpsHelp = (help Microsoft.PowerShell.Management\Get-Process) $gpsHelp | Where-Object {$_ -cmatch '^PARAMETERS'} | Should -Not -BeNullOrEmpty } It "help should return full view even with -Full switch" { + if (Test-IsWindowsArm64) { + Set-ItResult -Pending -Because "IOException: The handle is invalid." + } + $gpsHelp = (help Microsoft.PowerShell.Management\Get-Process -Full) $gpsHelp | Where-Object {$_ -cmatch '^PARAMETERS'} | Should -Not -BeNullOrEmpty } It "help should not append -Full when not using AllUsersView parameter set" { + if (Test-IsWindowsArm64) { + Set-ItResult -Pending -Because "IOException: The handle is invalid." + } + $gpsHelp = (help Microsoft.PowerShell.Management\Get-Process -Parameter Name) $gpsHelp | Where-Object {$_ -cmatch '^PARAMETERS'} | Should -BeNullOrEmpty } diff --git a/test/powershell/engine/Remoting/InvokeCommandRemoteDebug.Tests.ps1 b/test/powershell/engine/Remoting/InvokeCommandRemoteDebug.Tests.ps1 index fef7da0e75e..886bceb363d 100644 --- a/test/powershell/engine/Remoting/InvokeCommandRemoteDebug.Tests.ps1 +++ b/test/powershell/engine/Remoting/InvokeCommandRemoteDebug.Tests.ps1 @@ -126,6 +126,12 @@ Describe "Invoke-Command remote debugging tests" -Tags 'Feature','RequireAdminOn $PSDefaultParameterValues["it:skip"] = $true return } + elseif (Test-IsWindowsArm64) { + Write-Verbose "remoting is not setup on ARM64, skipping tests" -Verbose + $PSDefaultParameterValues["it:skip"] = $true + return + } + $sb = [scriptblock]::Create('"Hello!"') diff --git a/test/tools/Modules/HelpersCommon/HelpersCommon.psd1 b/test/tools/Modules/HelpersCommon/HelpersCommon.psd1 index 43d2ada88cc..8facd270576 100644 --- a/test/tools/Modules/HelpersCommon/HelpersCommon.psd1 +++ b/test/tools/Modules/HelpersCommon/HelpersCommon.psd1 @@ -18,24 +18,25 @@ Description = 'Temporary module contains functions for using in tests' FunctionsToExport = @( 'Add-TestDynamicType' - 'Test-CanWriteToPsHome' 'Disable-Testhook' 'Enable-Testhook' + 'Get-PlatformInfo' 'Get-RandomFileName' - 'New-RandomHexString' + 'Get-WSManSupport' 'New-ComplexPassword' + 'New-RandomHexString' 'Send-VstsLogFile' 'Set-TesthookResult' 'Start-NativeExecution' + 'Test-CanWriteToPsHome' 'Test-IsElevated' 'Test-IsRoot' 'Test-IsVstsLinux' 'Test-IsVstsWindows' + 'Test-IsWindowsArm64' 'Test-TesthookIsSet' 'Wait-FileToBePresent' 'Wait-UntilTrue' - 'Get-PlatformInfo' - 'Get-WSManSupport' ) CmdletsToExport= @() diff --git a/test/tools/Modules/HelpersCommon/HelpersCommon.psm1 b/test/tools/Modules/HelpersCommon/HelpersCommon.psm1 index f0706650bb9..ef0683a6abe 100644 --- a/test/tools/Modules/HelpersCommon/HelpersCommon.psm1 +++ b/test/tools/Modules/HelpersCommon/HelpersCommon.psm1 @@ -396,3 +396,7 @@ function Get-WsManSupport { } return $false } + +function Test-IsWindowsArm64 { + return $IsWindows -and [System.Runtime.InteropServices.RuntimeInformation]::ProcessArchitecture -eq [System.Runtime.InteropServices.Architecture]::Arm64 +} diff --git a/tools/ci.psm1 b/tools/ci.psm1 index e2feca60dd3..731ab4eaebf 100644 --- a/tools/ci.psm1 +++ b/tools/ci.psm1 @@ -263,10 +263,17 @@ function Invoke-CITest $ExperimentalFeatureTests = Get-ExperimentalFeatureTests if ($Purpose -eq 'UnelevatedPesterTests') { + $unelevate = $true + $environment = Get-EnvironmentInformation + if ($environment.OSArchitecture -eq 'arm64') { + Write-Verbose -Verbose "running on arm64, running unelevated tests as elevated" + $unelevate = $false + } + $arguments = @{ Bindir = $env:CoreOutput OutputFile = $testResultsNonAdminFile - Unelevate = $true + Unelevate = $unelevate Terse = $true Tag = @() ExcludeTag = $ExcludeTag + 'RequireAdminOnWindows' From 3622ee53b427954c4badf5f097a114f8d4dbd693 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 31 Jan 2023 12:22:48 -0800 Subject: [PATCH 331/779] Bump Microsoft.NET.Test.Sdk from 17.4.0 to 17.4.1 (#18823) Bumps [Microsoft.NET.Test.Sdk](https://github.com/microsoft/vstest) from 17.4.0 to 17.4.1. - [Release notes](https://github.com/microsoft/vstest/releases) - [Changelog](https://github.com/microsoft/vstest/blob/main/docs/releases.md) - [Commits](https://github.com/microsoft/vstest/compare/v17.4.0...v17.4.1) --- updated-dependencies: - dependency-name: Microsoft.NET.Test.Sdk dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- test/xUnit/xUnit.tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/xUnit/xUnit.tests.csproj b/test/xUnit/xUnit.tests.csproj index 14bf2b5f4d4..0f1d2038d38 100644 --- a/test/xUnit/xUnit.tests.csproj +++ b/test/xUnit/xUnit.tests.csproj @@ -27,7 +27,7 @@ - + From ce343421762de653c7979d372ffbac2353343de1 Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Tue, 31 Jan 2023 12:55:29 -0800 Subject: [PATCH 332/779] Add 7.2 and 7.3 change logs (#19025) --- .spelling | 6 ++++ CHANGELOG/7.2.md | 62 +++++++++++++++++++++++++++++++++++++++ CHANGELOG/7.3.md | 76 ++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 144 insertions(+) diff --git a/.spelling b/.spelling index eee58d26366..38ca53d6073 100644 --- a/.spelling +++ b/.spelling @@ -1281,6 +1281,12 @@ CommonCommandParameters.cs preview.6.22352.1 v2.2.6 ResultsComparer +pre-defined +System.Runtime.CompilerServices.Unsafe +TabExpansion +PSv2 +System.Data.SqlClient +Microsoft.CSharp - CHANGELOG.md aavdberg asrosent diff --git a/CHANGELOG/7.2.md b/CHANGELOG/7.2.md index fd1ee4af54f..4e8cc516f79 100644 --- a/CHANGELOG/7.2.md +++ b/CHANGELOG/7.2.md @@ -1,5 +1,67 @@ # 7.2 Changelog +## [7.2.9] - 2023-01-24 + +### Engine Updates and Fixes + +- Fix for JEA session leaking functions (Internal 23821 & 23819) + +### General Cmdlet Updates and Fixes + +- Correct incorrect cmdlet name in script (#18919) + +### Build and Packaging Improvements + +
    + + + +

    Bump .NET version to 6.0.13

    + +
    + +
      +
    • Create test artifacts for windows arm64 (#18932)
    • +
    • Update dependencies for .NET release (Internal 23816)
    • +
    • Don't install based on build-id for RPM (#18921)
    • +
    • Apply expected file permissions to linux files after authenticode signing (#18922)
    • +
    • Add authenticode signing for assemblies on linux builds (#18920)
    • +
    + +
    + +[7.2.9]: https://github.com/PowerShell/PowerShell/compare/v7.2.8...v7.2.9 + +## [7.2.8] - 2022-12-13 + +### Engine Updates and Fixes + +- Remove TabExpansion for PSv2 from remote session configuration (Internal 23294) + +### Build and Packaging Improvements + +
    + + + +

    Bump .NET SDK to 6.0.403

    + +
    + +
      +
    • Update CGManifest and ThirdPartyNotices
    • +
    • Update Microsoft.CSharp from 4.3.0 to 4.7.0
    • +
    • Update to latest SDK (#18610)
    • +
    • Allow two-digit revisions in vPack package validation pattern (#18569)
    • +
    • Update outdated dependencies (#18576)
    • +
    • Work around args parsing issue (#18606)
    • +
    • Bump System.Data.SqlClient from 4.8.4 to 4.8.5 (#18515)
    • +
    + +
    + +[7.2.8]: https://github.com/PowerShell/PowerShell/compare/v7.2.7...v7.2.8 + ## [7.2.7] - 2022-10-20 ### Engine Updates and Fixes diff --git a/CHANGELOG/7.3.md b/CHANGELOG/7.3.md index 66516873ae3..e513c444d5a 100644 --- a/CHANGELOG/7.3.md +++ b/CHANGELOG/7.3.md @@ -1,5 +1,81 @@ # 7.3 Changelog +## [7.3.2] - 2023-01-24 + +### Engine Updates and Fixes + +- Fix `SuspiciousContentChecker.Match` to detect a pre-defined string when the text starts with it (#18916) +- Fix for JEA session leaking functions (Internal 23820) + +### General Cmdlet Updates and Fixes + +- Fix `Start-Job` to check the existence of working directory using the PowerShell way (#18917) +- Fix `Switch-Process` error to include the command that is not found (#18650) + +### Tests + +- Allow system lock down test debug hook to work with new `WLDP` API (fixes system lock down tests) (#18962) + +### Build and Packaging Improvements + +
    + + + +

    Bump to use .NET 7.0.2

    + +
    + +
      +
    • Update dependencies for .NET release (Internal 23818)
    • +
    • Remove unnecessary reference to System.Runtime.CompilerServices.Unsafe (#18918)
    • +
    • Add bootstrap after SBOM task to re-install .NET (#18891)
    • +
    + +
    + +[7.3.2]: https://github.com/PowerShell/PowerShell/compare/v7.3.1...v7.3.2 + +## [7.3.1] - 2022-12-13 + +### Engine Updates and Fixes + +- Remove TabExpansion for PSv2 from remote session configuration (Internal 23331) +- Add `sqlcmd` to list to use legacy argument passing (#18645 #18646) +- Change `exec` from alias to function to handle arbitrary args (#18644) +- Fix `Switch-Process` to copy the current env to the new process (#18632) +- Fix issue when completing the first command in a script with an empty array expression (#18355) +- Fix `Switch-Process` to set `termios` appropriate for child process (#18572) +- Fix native access violation (#18571) + +### Tests + +- Backport CI fixed from #18508 (#18626) +- Mark charset test as pending (#18609) + +### Build and Packaging Improvements + +
    + + + +

    We thank the following contributors!

    + +
    + +
      +
    • Update packages (Internal 23330)
    • +
    • Apply expected file permissions to linux files after authenticode signing (#18647)
    • +
    • Bump System.Data.SqlClient (#18573)
    • +
    • Don't install based on build-id for RPM (#18570)
    • +
    • Work around args parsing issue (#18607)
    • +
    • Fix package download in vPack job
    • +
    + +
    + +[7.3.1]: https://github.com/PowerShell/PowerShell/compare/v7.3.0...v7.3.1 + ## [7.3.0] - 2022-11-08 ### General Cmdlet Updates and Fixes From 049a1f29d599d2b95469a6139a4b3d0a2fcec10c Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Tue, 31 Jan 2023 12:58:15 -0800 Subject: [PATCH 333/779] Add tool to trigger license information gathering for NuGet modules (#18827) --- .spelling | 2 + tools/clearlyDefined/ClearlyDefined.ps1 | 47 ++++++ tools/clearlyDefined/readme.md | 30 ++++ .../src/ClearlyDefined/ClearlyDefined.psm1 | 137 ++++++++++++++++++ 4 files changed, 216 insertions(+) create mode 100644 tools/clearlyDefined/ClearlyDefined.ps1 create mode 100644 tools/clearlyDefined/readme.md create mode 100644 tools/clearlyDefined/src/ClearlyDefined/ClearlyDefined.psm1 diff --git a/.spelling b/.spelling index 38ca53d6073..958114e0359 100644 --- a/.spelling +++ b/.spelling @@ -1671,3 +1671,5 @@ centos-7 Security.types.ps1xml - ADOPTERS.md MicrosoftPowerBIMgmt + - tools/clearlyDefined/readme.md +ClearlyDefined diff --git a/tools/clearlyDefined/ClearlyDefined.ps1 b/tools/clearlyDefined/ClearlyDefined.ps1 new file mode 100644 index 00000000000..ded0b229938 --- /dev/null +++ b/tools/clearlyDefined/ClearlyDefined.ps1 @@ -0,0 +1,47 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +param( + [parameter(Mandatory = $true, ParameterSetName='Harvest')] + [switch] + $Harvest, + [parameter(Mandatory = $true, ParameterSetName='Test')] + [switch] + $Test, + [switch] + $ForceModuleReload +) + +$extraParams = @{} +if ($ForceModuleReload) { + $extraParams['Force'] = $true +} + +Import-Module -Name "$PSScriptRoot/src/ClearlyDefined" @extraParams + +$cgManfest = Get-Content "$PSScriptRoot/../cgmanifest.json" | ConvertFrom-Json +$fullCgList = $cgManfest.Registrations.Component | + ForEach-Object { + [Pscustomobject]@{ + type = $_.Type + Name = $_.Nuget.Name + PackageVersion = $_.Nuget.Version + } + } + +$fullList = $fullCgList | Get-ClearlyDefinedData + +$needHarvest = $fullList | Where-Object { !$_.harvested } + +Write-Verbose "Full List count: $($fullList.Count)" -Verbose +Write-Verbose "Need harvest: $($needHarvest.Count)" -Verbose + +if ($Harvest) { + $needHarvest | select-object -ExpandProperty coordinates | Start-ClearlyDefinedHarvest +} elseif ($Test) { + if($needHarvest.Count -gt 0) { + $needHarvest | Format-List | Out-String -Width 9999 | Write-Verbose -Verbose + throw "There are $($needHarvest.Count) packages that need to be harvested" + } else { + Write-Verbose "All packages have been harvested" -Verbose + } +} diff --git a/tools/clearlyDefined/readme.md b/tools/clearlyDefined/readme.md new file mode 100644 index 00000000000..839fc7019aa --- /dev/null +++ b/tools/clearlyDefined/readme.md @@ -0,0 +1,30 @@ +# ClearlyDefined + +## Purpose + +This tool is intended to test if all the license data in [ClearlyDefined](https://clearlydefined.io) is present to generate the PowerShell license. +If the data is not present, it can request that ClearlyDefined gather (called Harvest in their terminology) the data. + +## Use + +### Testing + +Run `./ClearlyDefined.ps1 -test`. + +If there is any missing data, the script should write verbose messages about the missing data and throw. +If there is no missing data, the script should not throw. + +### Harvesting + +Run `./ClearlyDefined.ps1 -Harvest`. +The script will trigger the harvest and output the result from ClearlyDefined. +**Give ClearlyDefined 24 hours to harvest the data.** +You can use the `-Test` switch without the `-Harvest` switch to test if Harvesting is done. + +## Caching + +If you run in the same PowerShell session, the script will be faster due to caching. + +The module will cache any results from ClearlyDefined that indicate the package is Harvested for 60 minutes. +No caching is done for packages that are not yet harvested. +To clear the cache, run with the `-ForceModuleReload` switch. diff --git a/tools/clearlyDefined/src/ClearlyDefined/ClearlyDefined.psm1 b/tools/clearlyDefined/src/ClearlyDefined/ClearlyDefined.psm1 new file mode 100644 index 00000000000..2a9434c9cbe --- /dev/null +++ b/tools/clearlyDefined/src/ClearlyDefined/ClearlyDefined.psm1 @@ -0,0 +1,137 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +# Start the collection (known as harvest) of ClearlyDefined data for a package +function Start-ClearlyDefinedHarvest { + [CmdletBinding()] + param( + [Parameter(ValueFromPipelineByPropertyName=$true)] + [Alias('Type')] + [validateset('nuget')] + [string] + $PackageType = 'nuget', + + [parameter(mandatory = $true, ValueFromPipelineByPropertyName=$true)] + [Alias('Name')] + [string] + $PackageName, + + [parameter(mandatory = $true, ValueFromPipelineByPropertyName=$true)] + [Alias('Version')] + [Alias('Revision')] + [string] + $PackageVersion + ) + + Process { + $coordinates = Get-ClearlyDefinedCoordinates @PSBoundParameters + $body = @{tool='package';coordinates=$coordinates} | convertto-json + Write-Verbose $body -Verbose + (Invoke-WebRequest -Method Post -Uri 'https://api.clearlydefined.io/harvest' -Body $body -ContentType 'application/json').Content + } +} + +function ConvertFrom-ClearlyDefinedCoordinates { + [CmdletBinding()] + param( + [parameter(mandatory = $true, ValueFromPipeline = $true)] + [string] + $Coordinates + ) + + Begin {} + Process { + $parts = $Coordinates.Split('/') + [PSCustomObject]@{ + type = $parts[0] + provider = $parts[1] + namespace = $parts[2] + name = $parts[3] + revision = $parts[4] + } + } + End {} +} + +# Get the coordinate string for a package +Function Get-ClearlyDefinedCoordinates { + [CmdletBinding()] + param( + [validateset('nuget')] + [string] + $PackageType = 'nuget', + [parameter(mandatory = $true)] + [string] + $PackageName, + [parameter(mandatory = $true)] + [string] + $PackageVersion + ) + + return "$PackageType/$PackageType/-/$PackageName/$PackageVersion" +} + +# Cache of ClearlyDefined data +$cdCache = @{} + +# Get the ClearlyDefined data for a package +Function Get-ClearlyDefinedData { + [CmdletBinding()] + param( + [Parameter(ValueFromPipelineByPropertyName=$true)] + [Alias('Type')] + [validateset('nuget')] + [string] + $PackageType = 'nuget', + + [parameter(mandatory = $true, ValueFromPipelineByPropertyName=$true)] + [Alias('Name')] + [string] + $PackageName, + + [parameter(mandatory = $true, ValueFromPipelineByPropertyName=$true)] + [Alias('Revision')] + [string] + $PackageVersion + ) + + Begin { + $cacheMinutes = 60 + $cacheCutoff = (get-date).AddMinutes(-$cacheMinutes) + $coordinateList = @() + } + + Process { + $coordinateList += Get-ClearlyDefinedCoordinates @PSBoundParameters + } + + end { + $total = $coordinateList.Count + $completed = 0 + foreach($coordinates in $coordinateList) { + Write-Progress -Activity "Getting ClearlyDefined data" -Status "Getting data for $coordinates" -PercentComplete (($completed / $total) * 100) + $containsKey = $cdCache.ContainsKey($coordinates) + if ($containsKey -and $cdCache[$coordinates].cachedTime -gt $cacheCutoff) { + Write-Verbose "Returning cached data for $coordinates" + Write-Output $cdCache[$coordinates] + continue + } + + Invoke-RestMethod -Uri "https://api.clearlydefined.io/definitions/$coordinates" | ForEach-Object { + [bool] $harvested = if ($_.licensed.declared) { $true } else { $false } + Add-Member -NotePropertyName cachedTime -NotePropertyValue (get-date) -InputObject $_ -PassThru | Add-Member -NotePropertyName harvested -NotePropertyValue $harvested -PassThru + if ($_.harvested) { + Write-Verbose "Caching data for $coordinates" + $cdCache[$coordinates] = $_ + } + } + $completed++ + } + } +} + +Export-ModuleMember -Function @( + 'Start-ClearlyDefinedHarvest' + 'Get-ClearlyDefinedData' + 'ConvertFrom-ClearlyDefinedCoordinates' +) From 3e74bd0ea1292dbd2b7803b566a6cbb57d0ec0f6 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Wed, 1 Feb 2023 17:42:37 +0100 Subject: [PATCH 334/779] Small cleanup WebCmdlets (#19030) --- .../WebCmdlet/Common/ContentHelper.Common.cs | 39 ++++----- .../Common/WebRequestPSCmdlet.Common.cs | 82 +++++++++---------- .../CoreCLR/WebResponseHelper.CoreClr.cs | 2 +- .../WebResponseObjectFactory.CoreClr.cs | 10 +-- 4 files changed, 59 insertions(+), 74 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs index d44828acd32..41af8ebc6dc 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs @@ -15,11 +15,8 @@ internal static class ContentHelper { #region Internal Methods - internal static string GetContentType(HttpResponseMessage response) - { - // ContentType may not exist in response header. Return null if not. - return response.Content.Headers.ContentType?.MediaType; - } + // ContentType may not exist in response header. Return null if not. + internal static string GetContentType(HttpResponseMessage response) => response.Content.Headers.ContentType?.MediaType; internal static Encoding GetDefaultEncoding() => Encoding.UTF8; @@ -32,8 +29,7 @@ internal static StringBuilder GetRawContentHeader(HttpResponseMessage response) { int statusCode = WebResponseHelper.GetStatusCode(response); string statusDescription = WebResponseHelper.GetStatusDescription(response); - raw.Append($"{protocol} {statusCode} {statusDescription}"); - raw.AppendLine(); + raw.AppendLine($"{protocol} {statusCode} {statusDescription}"); } HttpHeaders[] headerCollections = @@ -52,12 +48,9 @@ internal static StringBuilder GetRawContentHeader(HttpResponseMessage response) foreach (var header in headerCollection) { // Headers may have multiple entries with different values - foreach (var headerValue in header.Value) + foreach (string headerValue in header.Value) { - raw.Append(header.Key); - raw.Append(": "); - raw.Append(headerValue); - raw.AppendLine(); + raw.AppendLine($"{header.Key}: {headerValue}"); } } } @@ -101,10 +94,10 @@ private static bool CheckIsJson(string contentType) // Add in these other "javascript" related types that // sometimes get sent down as the mime type for JSON content isJson |= contentType.Equals("text/json", StringComparison.OrdinalIgnoreCase) - || contentType.Equals("application/x-javascript", StringComparison.OrdinalIgnoreCase) - || contentType.Equals("text/x-javascript", StringComparison.OrdinalIgnoreCase) - || contentType.Equals("application/javascript", StringComparison.OrdinalIgnoreCase) - || contentType.Equals("text/javascript", StringComparison.OrdinalIgnoreCase); + || contentType.Equals("application/x-javascript", StringComparison.OrdinalIgnoreCase) + || contentType.Equals("text/x-javascript", StringComparison.OrdinalIgnoreCase) + || contentType.Equals("application/javascript", StringComparison.OrdinalIgnoreCase) + || contentType.Equals("text/javascript", StringComparison.OrdinalIgnoreCase); return isJson; } @@ -118,8 +111,8 @@ private static bool CheckIsText(string contentType) // Any text, xml or json types are text bool isText = contentType.StartsWith("text/", StringComparison.OrdinalIgnoreCase) - || CheckIsXml(contentType) - || CheckIsJson(contentType); + || CheckIsXml(contentType) + || CheckIsJson(contentType); // Further content type analysis is available on Windows if (Platform.IsWindows && !isText) @@ -156,11 +149,11 @@ private static bool CheckIsXml(string contentType) } // RFC 3023: Media types with the suffix "+xml" are XML - bool isXml = (contentType.Equals("application/xml", StringComparison.OrdinalIgnoreCase) - || contentType.Equals("application/xml-external-parsed-entity", StringComparison.OrdinalIgnoreCase) - || contentType.Equals("application/xml-dtd", StringComparison.OrdinalIgnoreCase)); - - isXml |= contentType.EndsWith("+xml", StringComparison.OrdinalIgnoreCase); + bool isXml = contentType.Equals("application/xml", StringComparison.OrdinalIgnoreCase) + || contentType.Equals("application/xml-external-parsed-entity", StringComparison.OrdinalIgnoreCase) + || contentType.Equals("application/xml-dtd", StringComparison.OrdinalIgnoreCase) + || contentType.EndsWith("+xml", StringComparison.OrdinalIgnoreCase); + return isXml; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index beb9ad93e7e..befa819504a 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -105,7 +105,7 @@ public abstract partial class WebRequestPSCmdlet : PSCmdlet [ValidateNotNullOrEmpty] public virtual Uri Uri { get; set; } - #endregion + #endregion URI #region HTTP Version @@ -117,7 +117,7 @@ public abstract partial class WebRequestPSCmdlet : PSCmdlet [HttpVersionCompletions] public virtual Version HttpVersion { get; set; } - #endregion + #endregion HTTP Version #region Session /// @@ -133,7 +133,7 @@ public abstract partial class WebRequestPSCmdlet : PSCmdlet [Alias("SV")] public virtual string SessionVariable { get; set; } - #endregion + #endregion Session #region Authorization and Credentials @@ -198,13 +198,7 @@ public abstract partial class WebRequestPSCmdlet : PSCmdlet [Parameter] public virtual SecureString Token { get; set; } - /// - /// Gets or sets the AllowInsecureRedirect property used to follow HTTP redirects from HTTPS. - /// - [Parameter] - public virtual SwitchParameter AllowInsecureRedirect { get; set; } - - #endregion + #endregion Authorization and Credentials #region Headers @@ -234,10 +228,25 @@ public abstract partial class WebRequestPSCmdlet : PSCmdlet [Parameter] public virtual IDictionary Headers { get; set; } - #endregion + /// + /// Gets or sets the SkipHeaderValidation property. + /// + /// + /// This property adds headers to the request's header collection without validation. + /// + [Parameter] + public virtual SwitchParameter SkipHeaderValidation { get; set; } + + #endregion Headers #region Redirect + /// + /// Gets or sets the AllowInsecureRedirect property used to follow HTTP redirects from HTTPS. + /// + [Parameter] + public virtual SwitchParameter AllowInsecureRedirect { get; set; } + /// /// Gets or sets the RedirectMax property. /// @@ -252,6 +261,21 @@ public abstract partial class WebRequestPSCmdlet : PSCmdlet [ValidateRange(0, int.MaxValue)] public virtual int MaximumRetryCount { get; set; } + /// + /// Gets or sets the PreserveAuthorizationOnRedirect property. + /// + /// + /// This property overrides compatibility with web requests on Windows. + /// On FullCLR (WebRequest), authorization headers are stripped during redirect. + /// CoreCLR (HTTPClient) does not have this behavior so web requests that work on + /// PowerShell/FullCLR can fail with PowerShell/CoreCLR. To provide compatibility, + /// we'll detect requests with an Authorization header and automatically strip + /// the header when the first redirect occurs. This switch turns off this logic for + /// edge cases where the authorization header needs to be preserved across redirects. + /// + [Parameter] + public virtual SwitchParameter PreserveAuthorizationOnRedirect { get; set; } + /// /// Gets or sets the RetryIntervalSec property, which determines the number seconds between retries. /// @@ -259,7 +283,7 @@ public abstract partial class WebRequestPSCmdlet : PSCmdlet [ValidateRange(1, int.MaxValue)] public virtual int RetryIntervalSec { get; set; } = 5; - #endregion + #endregion Redirect #region Method @@ -286,7 +310,7 @@ public virtual string CustomMethod private string _custommethod; - #endregion + #endregion Method #region NoProxy @@ -297,7 +321,7 @@ public virtual string CustomMethod [Parameter(Mandatory = true, ParameterSetName = "StandardMethodNoProxy")] public virtual SwitchParameter NoProxy { get; set; } - #endregion + #endregion NoProxy #region Proxy @@ -323,7 +347,7 @@ public virtual string CustomMethod [Parameter(ParameterSetName = "CustomMethod")] public virtual SwitchParameter ProxyUseDefaultCredentials { get; set; } - #endregion + #endregion Proxy #region Input @@ -365,7 +389,7 @@ public virtual string CustomMethod /// private string _originalFilePath; - #endregion + #endregion Input #region Output @@ -393,7 +417,7 @@ public virtual string CustomMethod [Parameter] public virtual SwitchParameter SkipHttpErrorCheck { get; set; } - #endregion + #endregion Output #endregion Virtual Properties @@ -825,30 +849,6 @@ public HttpResponseException(string message, HttpResponseMessage response) : bas /// public abstract partial class WebRequestPSCmdlet : PSCmdlet { - /// - /// Gets or sets the PreserveAuthorizationOnRedirect property. - /// - /// - /// This property overrides compatibility with web requests on Windows. - /// On FullCLR (WebRequest), authorization headers are stripped during redirect. - /// CoreCLR (HTTPClient) does not have this behavior so web requests that work on - /// PowerShell/FullCLR can fail with PowerShell/CoreCLR. To provide compatibility, - /// we'll detect requests with an Authorization header and automatically strip - /// the header when the first redirect occurs. This switch turns off this logic for - /// edge cases where the authorization header needs to be preserved across redirects. - /// - [Parameter] - public virtual SwitchParameter PreserveAuthorizationOnRedirect { get; set; } - - /// - /// Gets or sets the SkipHeaderValidation property. - /// - /// - /// This property adds headers to the request's header collection without validation. - /// - [Parameter] - public virtual SwitchParameter SkipHeaderValidation { get; set; } - #region Abstract Methods /// diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseHelper.CoreClr.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseHelper.CoreClr.cs index 9de4311e430..aaf921c7f0d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseHelper.CoreClr.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseHelper.CoreClr.cs @@ -43,7 +43,7 @@ internal static Dictionary> GetHeadersDictionary(Htt internal static bool IsText(HttpResponseMessage response) { // ContentType may not exist in response header. - string contentType = response.Content.Headers.ContentType?.MediaType; + string contentType = ContentHelper.GetContentType(response); return ContentHelper.IsText(contentType); } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseObjectFactory.CoreClr.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseObjectFactory.CoreClr.cs index 7dade00b4f6..4c8f1c40321 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseObjectFactory.CoreClr.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseObjectFactory.CoreClr.cs @@ -11,15 +11,7 @@ internal static class WebResponseObjectFactory { internal static WebResponseObject GetResponseObject(HttpResponseMessage response, Stream responseStream, ExecutionContext executionContext) { - WebResponseObject output; - if (WebResponseHelper.IsText(response)) - { - output = new BasicHtmlWebResponseObject(response, responseStream); - } - else - { - output = new WebResponseObject(response, responseStream); - } + WebResponseObject output = WebResponseHelper.IsText(response) ? new BasicHtmlWebResponseObject(response, responseStream) : new WebResponseObject(response, responseStream); return output; } From dd406b512ab0721943b7fc9c851ea5cc034cedf4 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Wed, 1 Feb 2023 17:45:09 +0100 Subject: [PATCH 335/779] Add ValidateNotNullOrEmpty to OutFile and InFile parameters of WebCmdlets (#19044) --- .../Common/WebRequestPSCmdlet.Common.cs | 2 + .../WebCmdlets.Tests.ps1 | 58 ++++++++++++++++--- 2 files changed, 53 insertions(+), 7 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index befa819504a..f75de9b0078 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -382,6 +382,7 @@ public virtual string CustomMethod /// Gets or sets the InFile property. /// [Parameter] + [ValidateNotNullOrEmpty] public virtual string InFile { get; set; } /// @@ -397,6 +398,7 @@ public virtual string CustomMethod /// Gets or sets the OutFile property. /// [Parameter] + [ValidateNotNullOrEmpty] public virtual string OutFile { get; set; } /// diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 index 285be044eb4..43363edb6eb 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 @@ -704,6 +704,16 @@ Describe "Invoke-WebRequest tests" -Tags "Feature", "RequireAdminOnWindows" { $jsonContent.headers.Host | Should -Be $uri.Authority } + It "Invoke-WebRequest should fail if -OutFile is ." -TestCases @( + @{ Name = "empty"; Value = [string]::Empty } + @{ Name = "null"; Value = $null } + ) { + param ($value) + $uri = Get-WebListenerUrl -Test 'Get' + $errorId = "ParameterArgumentValidationError,Microsoft.PowerShell.Commands.InvokeWebRequestCommand" + { Invoke-WebRequest -Uri $uri -OutFile $value} | Should -Throw -ErrorId $errorId + } + It "Validate Invoke-WebRequest handles missing Content-Type in response header" { #Validate that exception is not thrown when response headers are missing Content-Type. $uri = Get-WebListenerUrl -Test 'ResponseHeaders' -Query @{'Content-Type' = ''} @@ -893,7 +903,7 @@ Describe "Invoke-WebRequest tests" -Tags "Feature", "RequireAdminOnWindows" { $response.Error | Should -BeNullOrEmpty $response.Content.Headers."Authorization" | Should -BeExactly "test" } - + It "Validates Invoke-WebRequest with -PreserveAuthorizationOnRedirect respects -MaximumRedirection on redirect: " -TestCases $redirectTests { param($redirectType, $redirectedMethod) $uri = Get-WebListenerUrl -Test 'Redirect' -TestValue '3' -Query @{type = $redirectType} @@ -2390,6 +2400,16 @@ Describe "Invoke-RestMethod tests" -Tags "Feature", "RequireAdminOnWindows" { $jsonContent.headers.Host | Should -Be $uri.Authority } + It "Invoke-RestMethod should fail if -OutFile is ." -TestCases @( + @{ Name = "empty"; Value = [string]::Empty } + @{ Name = "null"; Value = $null } + ) { + param ($value) + $uri = Get-WebListenerUrl -Test 'Get' + $errorId = "ParameterArgumentValidationError,Microsoft.PowerShell.Commands.InvokeRestMethodCommand" + { Invoke-RestMethod -Uri $uri -OutFile $value} | Should -Throw -ErrorId $errorId + } + It "Validate Invoke-RestMethod handles missing Content-Type in response header" { #Validate that exception is not thrown when response headers are missing Content-Type. $uri = Get-WebListenerUrl -Test 'ResponseHeaders' -Query @{'Content-Type' = ''} @@ -3629,10 +3649,16 @@ Describe "Validate Invoke-WebRequest and Invoke-RestMethod -InFile" -Tags "Featu $uri = Get-WebListenerUrl -Test 'Post' $testCases = @( #region INVOKE-WEBREQUEST + @{ + Name = 'Validate error for Invoke-WebRequest -InFile null' + ScriptBlock = {Invoke-WebRequest -Uri $uri -Method Post -InFile $null} + ExpectedFullyQualifiedErrorId = 'ParameterArgumentValidationError,Microsoft.PowerShell.Commands.InvokeWebRequestCommand' + } + @{ Name = 'Validate error for Invoke-WebRequest -InFile ""' ScriptBlock = {Invoke-WebRequest -Uri $uri -Method Post -InFile ""} - ExpectedFullyQualifiedErrorId = 'WebCmdletInFileNotFilePathException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand' + ExpectedFullyQualifiedErrorId = 'ParameterArgumentValidationError,Microsoft.PowerShell.Commands.InvokeWebRequestCommand' } @{ @@ -3642,30 +3668,48 @@ Describe "Validate Invoke-WebRequest and Invoke-RestMethod -InFile" -Tags "Featu } @{ - Name = "Validate error for Invoke-WebRequest -InFile $TestDrive\content.txt" - ScriptBlock = {Invoke-WebRequest -Uri $uri -Method Post -InFile $TestDrive\content.txt} + Name = "Validate error for Invoke-WebRequest -InFile $TestDrive\content.txt" + ScriptBlock = {Invoke-WebRequest -Uri $uri -Method Post -InFile $TestDrive\content.txt} ExpectedFullyQualifiedErrorId = 'PathNotFound,Microsoft.PowerShell.Commands.InvokeWebRequestCommand' } + + @{ + Name = "Validate error for Invoke-WebRequest -InFile $TestDrive" + ScriptBlock = {Invoke-WebRequest -Uri $uri -Method Post -InFile $TestDrive} + ExpectedFullyQualifiedErrorId = 'WebCmdletInFileNotFilePathException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand' + } #endregion #region INVOKE-RESTMETHOD + @{ + Name = "Validate error for Invoke-RestMethod -InFile null" + ScriptBlock = {Invoke-RestMethod -Uri $uri -Method Post -InFile $null} + ExpectedFullyQualifiedErrorId = 'ParameterArgumentValidationError,Microsoft.PowerShell.Commands.InvokeRestMethodCommand' + } + @{ Name = "Validate error for Invoke-RestMethod -InFile ''" ScriptBlock = {Invoke-RestMethod -Uri $uri -Method Post -InFile ''} - ExpectedFullyQualifiedErrorId = 'WebCmdletInFileNotFilePathException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand' + ExpectedFullyQualifiedErrorId = 'ParameterArgumentValidationError,Microsoft.PowerShell.Commands.InvokeRestMethodCommand' } @{ - Name = "Validate error for Invoke-RestMethod -InFile " + Name = "Validate error for Invoke-RestMethod -InFile" ScriptBlock = {Invoke-RestMethod -Uri $uri -Method Post -InFile} ExpectedFullyQualifiedErrorId = 'MissingArgument,Microsoft.PowerShell.Commands.InvokeRestMethodCommand' } @{ - Name = "Validate error for Invoke-RestMethod -InFile $TestDrive\content.txt" + Name = "Validate error for Invoke-RestMethod -InFile $TestDrive\content.txt" ScriptBlock = {Invoke-RestMethod -Uri $uri -Method Post -InFile $TestDrive\content.txt} ExpectedFullyQualifiedErrorId = 'PathNotFound,Microsoft.PowerShell.Commands.InvokeRestMethodCommand' } + + @{ + Name = "Validate error for Invoke-RestMethod -InFile $TestDrive" + ScriptBlock = {Invoke-RestMethod -Uri $uri -Method Post -InFile $TestDrive} + ExpectedFullyQualifiedErrorId = 'WebCmdletInFileNotFilePathException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand' + } #endregion ) } From c87f2a48fd8ba2a3a1c54d9a82d6937dc57f44c2 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Wed, 1 Feb 2023 17:56:49 +0100 Subject: [PATCH 336/779] Rework SetRequestContent in WebCmdlets (#18964) --- .../Common/WebRequestPSCmdlet.Common.cs | 129 +++++++----------- 1 file changed, 47 insertions(+), 82 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index f75de9b0078..c267ad81f8d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -1089,9 +1089,6 @@ internal virtual void FillRequestStream(HttpRequestMessage request) if (Form is not null) { - // Content headers will be set by MultipartFormDataContent which will throw unless we clear them first - WebSession.ContentHeaders.Clear(); - var formData = new MultipartFormDataContent(); foreach (DictionaryEntry formEntry in Form) { @@ -1101,55 +1098,48 @@ internal virtual void FillRequestStream(HttpRequestMessage request) SetRequestContent(request, formData); } - // coerce body into a usable form else if (Body is not null) { + // Coerce body into a usable form object content = Body; - // make sure we're using the base object of the body, not the PSObject wrapper - PSObject psBody = Body as PSObject; - if (psBody is not null) + // Make sure we're using the base object of the body, not the PSObject wrapper + if (Body is PSObject psBody) { content = psBody.BaseObject; } - if (content is FormObject form) - { - SetRequestContent(request, form.Fields); - } - else if (content is IDictionary dictionary && request.Method != HttpMethod.Get) - { - SetRequestContent(request, dictionary); - } - else if (content is XmlNode xmlNode) - { - SetRequestContent(request, xmlNode); - } - else if (content is Stream stream) - { - SetRequestContent(request, stream); - } - else if (content is byte[] bytes) - { - SetRequestContent(request, bytes); - } - else if (content is MultipartFormDataContent multipartFormDataContent) + switch (content) { - WebSession.ContentHeaders.Clear(); - SetRequestContent(request, multipartFormDataContent); - } - else - { - SetRequestContent( - request, - (string)LanguagePrimitives.ConvertTo(content, typeof(string), CultureInfo.InvariantCulture)); + case FormObject form: + SetRequestContent(request, form.Fields); + break; + case IDictionary dictionary when request.Method != HttpMethod.Get: + SetRequestContent(request, dictionary); + break; + case XmlNode xmlNode: + SetRequestContent(request, xmlNode); + break; + case Stream stream: + SetRequestContent(request, stream); + break; + case byte[] bytes: + SetRequestContent(request, bytes); + break; + case MultipartFormDataContent multipartFormDataContent: + SetRequestContent(request, multipartFormDataContent); + break; + default: + SetRequestContent(request, (string)LanguagePrimitives.ConvertTo(content, typeof(string), CultureInfo.InvariantCulture)); + break; } } - else if (InFile is not null) // copy InFile data + else if (InFile is not null) { + // Copy InFile data try { - // open the input file + // Open the input file SetRequestContent(request, new FileStream(InFile, FileMode.Open, FileAccess.Read, FileShare.Read)); } catch (UnauthorizedAccessException) @@ -1574,24 +1564,17 @@ protected override void ProcessRecord() /// /// The WebRequest who's content is to be set. /// A byte array containing the content data. - /// The number of bytes written to the requests RequestStream (and the new value of the request's ContentLength property. /// /// Because this function sets the request's ContentLength property and writes content data into the requests's stream, /// it should be called one time maximum on a given request. /// - internal long SetRequestContent(HttpRequestMessage request, byte[] content) + internal void SetRequestContent(HttpRequestMessage request, byte[] content) { ArgumentNullException.ThrowIfNull(request); + ArgumentNullException.ThrowIfNull(content); - if (content is null) - { - return 0; - } - - var byteArrayContent = new ByteArrayContent(content); + ByteArrayContent byteArrayContent = new(content); request.Content = byteArrayContent; - - return byteArrayContent.Headers.ContentLength.Value; } /// @@ -1599,19 +1582,14 @@ internal long SetRequestContent(HttpRequestMessage request, byte[] content) /// /// The WebRequest who's content is to be set. /// A String object containing the content data. - /// The number of bytes written to the requests RequestStream (and the new value of the request's ContentLength property. /// /// Because this function sets the request's ContentLength property and writes content data into the requests's stream, /// it should be called one time maximum on a given request. /// - internal long SetRequestContent(HttpRequestMessage request, string content) + internal void SetRequestContent(HttpRequestMessage request, string content) { ArgumentNullException.ThrowIfNull(request); - - if (content is null) - { - return 0; - } + ArgumentNullException.ThrowIfNull(content); Encoding encoding = null; if (ContentType is not null) @@ -1631,7 +1609,7 @@ internal long SetRequestContent(HttpRequestMessage request, string content) { if (!SkipHeaderValidation) { - var outerEx = new ValidationMetadataException(WebCmdletStrings.ContentTypeException, ex); + ValidationMetadataException outerEx = new(WebCmdletStrings.ContentTypeException, ex); ErrorRecord er = new(outerEx, "WebCmdletContentTypeException", ErrorCategory.InvalidArgument, ContentType); ThrowTerminatingError(er); } @@ -1639,20 +1617,14 @@ internal long SetRequestContent(HttpRequestMessage request, string content) } byte[] bytes = StreamHelper.EncodeToBytes(content, encoding); - var byteArrayContent = new ByteArrayContent(bytes); + ByteArrayContent byteArrayContent = new(bytes); request.Content = byteArrayContent; - - return byteArrayContent.Headers.ContentLength.Value; } - internal long SetRequestContent(HttpRequestMessage request, XmlNode xmlNode) + internal void SetRequestContent(HttpRequestMessage request, XmlNode xmlNode) { ArgumentNullException.ThrowIfNull(request); - - if (xmlNode is null) - { - return 0; - } + ArgumentNullException.ThrowIfNull(xmlNode); byte[] bytes = null; XmlDocument doc = xmlNode as XmlDocument; @@ -1667,10 +1639,9 @@ internal long SetRequestContent(HttpRequestMessage request, XmlNode xmlNode) bytes = StreamHelper.EncodeToBytes(xmlNode.OuterXml, encoding: null); } - var byteArrayContent = new ByteArrayContent(bytes); - request.Content = byteArrayContent; + ByteArrayContent byteArrayContent = new(bytes); - return byteArrayContent.Headers.ContentLength.Value; + request.Content = byteArrayContent; } /// @@ -1678,21 +1649,17 @@ internal long SetRequestContent(HttpRequestMessage request, XmlNode xmlNode) /// /// The WebRequest who's content is to be set. /// A Stream object containing the content data. - /// The number of bytes written to the requests RequestStream (and the new value of the request's ContentLength property. /// /// Because this function sets the request's ContentLength property and writes content data into the requests's stream, /// it should be called one time maximum on a given request. /// - internal long SetRequestContent(HttpRequestMessage request, Stream contentStream) + internal void SetRequestContent(HttpRequestMessage request, Stream contentStream) { ArgumentNullException.ThrowIfNull(request); - ArgumentNullException.ThrowIfNull(contentStream); - var streamContent = new StreamContent(contentStream); + StreamContent streamContent = new(contentStream); request.Content = streamContent; - - return streamContent.Headers.ContentLength.Value; } /// @@ -1700,30 +1667,28 @@ internal long SetRequestContent(HttpRequestMessage request, Stream contentStream /// /// The WebRequest who's content is to be set. /// A MultipartFormDataContent object containing multipart/form-data content. - /// The number of bytes written to the requests RequestStream (and the new value of the request's ContentLength property. /// /// Because this function sets the request's ContentLength property and writes content data into the requests's stream, /// it should be called one time maximum on a given request. /// - internal long SetRequestContent(HttpRequestMessage request, MultipartFormDataContent multipartContent) + internal void SetRequestContent(HttpRequestMessage request, MultipartFormDataContent multipartContent) { ArgumentNullException.ThrowIfNull(request); - ArgumentNullException.ThrowIfNull(multipartContent); + + // Content headers will be set by MultipartFormDataContent which will throw unless we clear them first + WebSession.ContentHeaders.Clear(); request.Content = multipartContent; - - return multipartContent.Headers.ContentLength.Value; } - internal long SetRequestContent(HttpRequestMessage request, IDictionary content) + internal void SetRequestContent(HttpRequestMessage request, IDictionary content) { ArgumentNullException.ThrowIfNull(request); - ArgumentNullException.ThrowIfNull(content); string body = FormatDictionary(content); - return SetRequestContent(request, body); + SetRequestContent(request, body); } internal void ParseLinkHeader(HttpResponseMessage response, System.Uri requestUri) From 137b4d788b591535135a0dee7ecdcf76c6ece4e3 Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Wed, 1 Feb 2023 16:19:51 -0800 Subject: [PATCH 337/779] Fix for JEA session leaking functions (#19024) --- .../engine/InitialSessionState.cs | 83 +++++++++-- .../engine/Modules/ModuleCmdletBase.cs | 3 + .../engine/SessionStateScope.cs | 134 +++++++++--------- 3 files changed, 147 insertions(+), 73 deletions(-) diff --git a/src/System.Management.Automation/engine/InitialSessionState.cs b/src/System.Management.Automation/engine/InitialSessionState.cs index c26e3def06c..78f6c0af988 100644 --- a/src/System.Management.Automation/engine/InitialSessionState.cs +++ b/src/System.Management.Automation/engine/InitialSessionState.cs @@ -2966,13 +2966,20 @@ private RunspaceOpenModuleLoadException ProcessModulesToImport( HashSet unresolvedCmdsToExpose) { RunspaceOpenModuleLoadException exceptionToReturn = null; + List processedModules = new List(); foreach (object module in moduleList) { string moduleName = module as string; if (moduleName != null) { - exceptionToReturn = ProcessOneModule(initializedRunspace, moduleName, null, path, publicCommands); + exceptionToReturn = ProcessOneModule( + initializedRunspace: initializedRunspace, + name: moduleName, + moduleInfoToLoad: null, + path: path, + publicCommands: publicCommands, + processedModules: processedModules); } else { @@ -2983,7 +2990,13 @@ private RunspaceOpenModuleLoadException ProcessModulesToImport( { // if only name is specified in the module spec, just try import the module // ie., don't take the performance overhead of calling GetModule. - exceptionToReturn = ProcessOneModule(initializedRunspace, moduleSpecification.Name, null, path, publicCommands); + exceptionToReturn = ProcessOneModule( + initializedRunspace: initializedRunspace, + name: moduleSpecification.Name, + moduleInfoToLoad: null, + path: path, + publicCommands: publicCommands, + processedModules: processedModules); } else { @@ -2991,7 +3004,13 @@ private RunspaceOpenModuleLoadException ProcessModulesToImport( if (moduleInfos != null && moduleInfos.Count > 0) { - exceptionToReturn = ProcessOneModule(initializedRunspace, moduleSpecification.Name, moduleInfos[0], path, publicCommands); + exceptionToReturn = ProcessOneModule( + initializedRunspace: initializedRunspace, + name: moduleSpecification.Name, + moduleInfoToLoad: moduleInfos[0], + path: path, + publicCommands: publicCommands, + processedModules: processedModules); } else { @@ -3040,7 +3059,11 @@ private RunspaceOpenModuleLoadException ProcessModulesToImport( string commandToMakeVisible = Utils.ParseCommandName(unresolvedCommand, out moduleName); bool found = false; - foreach (CommandInfo cmd in LookupCommands(commandToMakeVisible, moduleName, initializedRunspace.ExecutionContext)) + foreach (CommandInfo cmd in LookupCommands( + commandPattern: commandToMakeVisible, + moduleName: moduleName, + context: initializedRunspace.ExecutionContext, + processedModules: processedModules)) { if (!found) { @@ -3091,11 +3114,13 @@ private RunspaceOpenModuleLoadException ProcessModulesToImport( /// /// /// + /// /// private static IEnumerable LookupCommands( string commandPattern, string moduleName, - ExecutionContext context) + ExecutionContext context, + List processedModules) { bool isWildCardPattern = WildcardPattern.ContainsWildcardCharacters(commandPattern); var searchOptions = isWildCardPattern ? @@ -3109,7 +3134,11 @@ private static IEnumerable LookupCommands( CommandOrigin cmdOrigin = CommandOrigin.Runspace; while (true) { - foreach (CommandInfo commandInfo in context.SessionState.InvokeCommand.GetCommands(commandPattern, CommandTypes.All, searchOptions, cmdOrigin)) + foreach (CommandInfo commandInfo in context.SessionState.InvokeCommand.GetCommands( + name: commandPattern, + commandTypes: CommandTypes.All, + options: searchOptions, + commandOrigin: cmdOrigin)) { // If module name is provided then use it to restrict returned results. if (haveModuleName && !moduleName.Equals(commandInfo.ModuleName, StringComparison.OrdinalIgnoreCase)) @@ -3139,13 +3168,43 @@ private static IEnumerable LookupCommands( // Next try internal search. cmdOrigin = CommandOrigin.Internal; } + + // If the command is associated with a module, try finding the command in the imported module list. + // The SessionState function table holds only one command name, and if two or more modules contain + // a command with the same name, only one of them will appear in the function table search above. + if (!found && haveModuleName) + { + var pattern = new WildcardPattern(commandPattern); + + foreach (PSModuleInfo moduleInfo in processedModules) + { + if (moduleInfo.Name.Equals(moduleName, StringComparison.OrdinalIgnoreCase)) + { + foreach (var cmd in moduleInfo.ExportedCommands.Values) + { + if (pattern.IsMatch(cmd.Name)) + { + yield return cmd; + } + } + + break; + } + } + } } /// /// If is null, import module using . Otherwise, /// import module using /// - private RunspaceOpenModuleLoadException ProcessOneModule(Runspace initializedRunspace, string name, PSModuleInfo moduleInfoToLoad, string path, HashSet publicCommands) + private RunspaceOpenModuleLoadException ProcessOneModule( + Runspace initializedRunspace, + string name, + PSModuleInfo moduleInfoToLoad, + string path, + HashSet publicCommands, + List processedModules) { using (PowerShell pse = PowerShell.Create()) { @@ -3182,6 +3241,11 @@ private RunspaceOpenModuleLoadException ProcessOneModule(Runspace initializedRun c = new CmdletInfo("Out-Default", typeof(OutDefaultCommand), null, null, initializedRunspace.ExecutionContext); pse.AddCommand(new Command(c)); } + else + { + // For runspace init module processing, pass back the PSModuleInfo to the output pipeline. + cmd.Parameters.Add("PassThru"); + } pse.Runspace = initializedRunspace; // Module import should be run in FullLanguage mode since it is running in @@ -3190,7 +3254,10 @@ private RunspaceOpenModuleLoadException ProcessOneModule(Runspace initializedRun pse.Runspace.ExecutionContext.LanguageMode = PSLanguageMode.FullLanguage; try { - pse.Invoke(); + // For runspace init module processing, collect the imported PSModuleInfo returned in the output pipeline. + // In other cases, this collection will be empty. + Collection moduleInfos = pse.Invoke(); + processedModules.AddRange(moduleInfos); } finally { diff --git a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs index 1b4b5204302..b17d3628aa4 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs @@ -7192,6 +7192,9 @@ private static void ImportFunctions(FunctionInfo func, SessionStateInternal targ CommandOrigin.Internal, targetSessionState.ExecutionContext); + // Note that the module 'func' and the function table 'functionInfo' instances are now linked + // together (see 'CopiedCommand' in CommandInfo class), so setting visibility on one also + // sets it on the other. SetCommandVisibility(isImportModulePrivate, functionInfo); functionInfo.Module = sourceModule; diff --git a/src/System.Management.Automation/engine/SessionStateScope.cs b/src/System.Management.Automation/engine/SessionStateScope.cs index 57c4c6388ba..080aebb2b0a 100644 --- a/src/System.Management.Automation/engine/SessionStateScope.cs +++ b/src/System.Management.Automation/engine/SessionStateScope.cs @@ -1245,11 +1245,18 @@ internal FunctionInfo SetFunction( name != null, "The caller should verify the name"); - var functionInfos = GetFunctions(); - FunctionInfo existingValue; + Dictionary functionInfos = GetFunctions(); FunctionInfo result; - if (!functionInfos.TryGetValue(name, out existingValue)) + + // Functions are equal only if they have the same name and if they come from the same module (if any). + // If the function is not associated with a module then the info 'ModuleName' property is set to empty string. + // If the new function has the same name of an existing function, but different module names, then the + // existing table function is replaced with the new function. + if (!functionInfos.TryGetValue(name, out FunctionInfo existingValue) || + (originalFunction != null && + !existingValue.ModuleName.Equals(originalFunction.ModuleName, StringComparison.OrdinalIgnoreCase))) { + // Add new function info to function table and return. result = functionFactory(name, function, originalFunction, options, context, helpFile); functionInfos[name] = result; @@ -1257,81 +1264,78 @@ internal FunctionInfo SetFunction( { GetAllScopeFunctions()[name] = result; } - } - else - { - // Make sure the function isn't constant or readonly - - SessionState.ThrowIfNotVisible(origin, existingValue); - if (IsFunctionOptionSet(existingValue, ScopedItemOptions.Constant) || - (!force && IsFunctionOptionSet(existingValue, ScopedItemOptions.ReadOnly))) - { - SessionStateUnauthorizedAccessException e = - new SessionStateUnauthorizedAccessException( - name, - SessionStateCategory.Function, - "FunctionNotWritable", - SessionStateStrings.FunctionNotWritable); + return result; + } - throw e; - } + // Update the existing function. - // Ensure we are not trying to set the function to constant as this can only be - // done at creation time. + // Make sure the function isn't constant or readonly. + SessionState.ThrowIfNotVisible(origin, existingValue); - if ((options & ScopedItemOptions.Constant) != 0) - { - SessionStateUnauthorizedAccessException e = - new SessionStateUnauthorizedAccessException( - name, - SessionStateCategory.Function, - "FunctionCannotBeMadeConstant", - SessionStateStrings.FunctionCannotBeMadeConstant); + if (IsFunctionOptionSet(existingValue, ScopedItemOptions.Constant) || + (!force && IsFunctionOptionSet(existingValue, ScopedItemOptions.ReadOnly))) + { + SessionStateUnauthorizedAccessException e = + new SessionStateUnauthorizedAccessException( + name, + SessionStateCategory.Function, + "FunctionNotWritable", + SessionStateStrings.FunctionNotWritable); - throw e; - } + throw e; + } - // Ensure we are not trying to remove the AllScope option + // Ensure we are not trying to set the function to constant as this can only be + // done at creation time. + if ((options & ScopedItemOptions.Constant) != 0) + { + SessionStateUnauthorizedAccessException e = + new SessionStateUnauthorizedAccessException( + name, + SessionStateCategory.Function, + "FunctionCannotBeMadeConstant", + SessionStateStrings.FunctionCannotBeMadeConstant); - if ((options & ScopedItemOptions.AllScope) == 0 && - IsFunctionOptionSet(existingValue, ScopedItemOptions.AllScope)) - { - SessionStateUnauthorizedAccessException e = - new SessionStateUnauthorizedAccessException( - name, - SessionStateCategory.Function, - "FunctionAllScopeOptionCannotBeRemoved", - SessionStateStrings.FunctionAllScopeOptionCannotBeRemoved); + throw e; + } - throw e; - } + // Ensure we are not trying to remove the AllScope option. + if ((options & ScopedItemOptions.AllScope) == 0 && + IsFunctionOptionSet(existingValue, ScopedItemOptions.AllScope)) + { + SessionStateUnauthorizedAccessException e = + new SessionStateUnauthorizedAccessException( + name, + SessionStateCategory.Function, + "FunctionAllScopeOptionCannotBeRemoved", + SessionStateStrings.FunctionAllScopeOptionCannotBeRemoved); - FunctionInfo existingFunction = existingValue; - FunctionInfo newValue = null; + throw e; + } - // If the function type changes (i.e.: function to workflow or back) - // then we need to blast what was there - newValue = functionFactory(name, function, originalFunction, options, context, helpFile); + FunctionInfo existingFunction = existingValue; - bool changesFunctionType = existingFunction.GetType() != newValue.GetType(); + // If the function type changes (i.e.: function to workflow or back) + // then we need to replace what was there. + FunctionInfo newValue = functionFactory(name, function, originalFunction, options, context, helpFile); - // Since the options are set after the script block, we have to - // forcefully apply the script block if the options will be - // set to not being ReadOnly - if (changesFunctionType || - ((existingFunction.Options & ScopedItemOptions.ReadOnly) != 0 && force)) - { - result = newValue; - functionInfos[name] = newValue; - } - else - { - bool applyForce = force || (options & ScopedItemOptions.ReadOnly) == 0; + bool changesFunctionType = existingFunction.GetType() != newValue.GetType(); - existingFunction.Update(newValue, applyForce, options, helpFile); - result = existingFunction; - } + // Since the options are set after the script block, we have to + // forcefully apply the script block if the options will be + // set to not being ReadOnly. + if (changesFunctionType || + ((existingFunction.Options & ScopedItemOptions.ReadOnly) != 0 && force)) + { + result = newValue; + functionInfos[name] = newValue; + } + else + { + bool applyForce = force || (options & ScopedItemOptions.ReadOnly) == 0; + existingFunction.Update(newValue, applyForce, options, helpFile); + result = existingFunction; } return result; From 9d8cc0c62d096567789768e03f164fa45d54cb7b Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Thu, 2 Feb 2023 00:29:01 +0000 Subject: [PATCH 338/779] Update to the latest NOTICES file (#19077) Co-authored-by: adityapatwardhan --- ThirdPartyNotices.txt | 202 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 197 insertions(+), 5 deletions(-) diff --git a/ThirdPartyNotices.txt b/ThirdPartyNotices.txt index 4afffa8931f..04ab0a7a4f4 100644 --- a/ThirdPartyNotices.txt +++ b/ThirdPartyNotices.txt @@ -134,7 +134,7 @@ SOFTWARE. --------------------------------------------------------- -Microsoft.CodeAnalysis.Common 4.3.1 - MIT +Microsoft.CodeAnalysis.Common 4.4.0 - MIT (c) Microsoft Corporation @@ -154,7 +154,7 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI --------------------------------------------------------- -Microsoft.CodeAnalysis.CSharp 4.3.1 - MIT +Microsoft.CodeAnalysis.CSharp 4.4.0 - MIT (c) Microsoft Corporation @@ -176,7 +176,7 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI --------------------------------------------------------- -Microsoft.Extensions.ObjectPool 7.0.0 - MIT +Microsoft.Extensions.ObjectPool 7.0.1 - MIT (c) Microsoft Corporation @@ -265,7 +265,7 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI --------------------------------------------------------- -Microsoft.PowerShell.Native 7.3.0 - MIT +Microsoft.PowerShell.Native 7.3.1 - MIT (c) Microsoft Corporation @@ -537,6 +537,54 @@ SOFTWARE. Microsoft.Windows.Compatibility 7.0.0 - MIT +(c) Microsoft Corporation +Copyright (c) Andrew Arnott +Copyright 2019 LLVM Project +Copyright 2018 Daniel Lemire +Copyright (c) .NET Foundation +Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson +Copyright (c) 1998 Microsoft. To +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2005-2020 Rich Felker +Copyright (c) Microsoft Corporation +Copyright (c) 2007 James Newton-King +Copyright (c) 2012-2014, Yann Collet +Copyright (c) 1991-2022 Unicode, Inc. +Copyright (c) 2013-2017, Alfred Klomp +Copyright 2012 the V8 project authors +Copyright (c) 1999 Lucent Technologies +Copyright (c) 2008-2016, Wojciech Mula +Copyright (c) 2011-2020 Microsoft Corp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2021 csFastFloat authors +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors +Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 +Portions (c) International Organization +Copyright (c) 2004-2006 Intel Corporation +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) +Copyright (c) .NET Foundation Contributors +Copyright (c) 2020 Mara Bos +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2008-2020 Advanced Micro Devices, Inc. +Copyright (c) 2019 Microsoft Corporation, Daan Leijen +Copyright (c) 2011 Novell, Inc (http://www.novell.com) +Copyright (c) 1995-2022 Jean-loup Gailly and Mark Adler +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors +Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright (c) 1980, 1986, 1993 The Regents of the University of California +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass. To The MIT License (MIT) @@ -585,7 +633,7 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI --------------------------------------------------------- -Newtonsoft.Json 13.0.1 - MIT +Newtonsoft.Json 13.0.2 - MIT Copyright James Newton-King 2008 @@ -1657,6 +1705,54 @@ SOFTWARE. System.Data.OleDb 7.0.0 - MIT +(c) Microsoft Corporation +Copyright (c) Andrew Arnott +Copyright 2019 LLVM Project +Copyright 2018 Daniel Lemire +Copyright (c) .NET Foundation +Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson +Copyright (c) 1998 Microsoft. To +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2005-2020 Rich Felker +Copyright (c) Microsoft Corporation +Copyright (c) 2007 James Newton-King +Copyright (c) 2012-2014, Yann Collet +Copyright (c) 1991-2022 Unicode, Inc. +Copyright (c) 2013-2017, Alfred Klomp +Copyright 2012 the V8 project authors +Copyright (c) 1999 Lucent Technologies +Copyright (c) 2008-2016, Wojciech Mula +Copyright (c) 2011-2020 Microsoft Corp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2021 csFastFloat authors +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors +Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 +Portions (c) International Organization +Copyright (c) 2004-2006 Intel Corporation +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) +Copyright (c) .NET Foundation Contributors +Copyright (c) 2020 Mara Bos +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2008-2020 Advanced Micro Devices, Inc. +Copyright (c) 2019 Microsoft Corporation, Daan Leijen +Copyright (c) 2011 Novell, Inc (http://www.novell.com) +Copyright (c) 1995-2022 Jean-loup Gailly and Mark Adler +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors +Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright (c) 1980, 1986, 1993 The Regents of the University of California +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass. To The MIT License (MIT) @@ -2310,6 +2406,54 @@ SOFTWARE. System.Formats.Asn1 7.0.0 - MIT +(c) Microsoft Corporation +Copyright (c) Andrew Arnott +Copyright 2019 LLVM Project +Copyright 2018 Daniel Lemire +Copyright (c) .NET Foundation +Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson +Copyright (c) 1998 Microsoft. To +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2005-2020 Rich Felker +Copyright (c) Microsoft Corporation +Copyright (c) 2007 James Newton-King +Copyright (c) 2012-2014, Yann Collet +Copyright (c) 1991-2022 Unicode, Inc. +Copyright (c) 2013-2017, Alfred Klomp +Copyright 2012 the V8 project authors +Copyright (c) 1999 Lucent Technologies +Copyright (c) 2008-2016, Wojciech Mula +Copyright (c) 2011-2020 Microsoft Corp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2021 csFastFloat authors +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors +Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 +Portions (c) International Organization +Copyright (c) 2004-2006 Intel Corporation +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) +Copyright (c) .NET Foundation Contributors +Copyright (c) 2020 Mara Bos +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2008-2020 Advanced Micro Devices, Inc. +Copyright (c) 2019 Microsoft Corporation, Daan Leijen +Copyright (c) 2011 Novell, Inc (http://www.novell.com) +Copyright (c) 1995-2022 Jean-loup Gailly and Mark Adler +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors +Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright (c) 1980, 1986, 1993 The Regents of the University of California +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass. To The MIT License (MIT) @@ -4101,6 +4245,54 @@ SOFTWARE. System.Text.Encodings.Web 7.0.0 - MIT +(c) Microsoft Corporation +Copyright (c) Andrew Arnott +Copyright 2019 LLVM Project +Copyright 2018 Daniel Lemire +Copyright (c) .NET Foundation +Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson +Copyright (c) 1998 Microsoft. To +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2005-2020 Rich Felker +Copyright (c) Microsoft Corporation +Copyright (c) 2007 James Newton-King +Copyright (c) 2012-2014, Yann Collet +Copyright (c) 1991-2022 Unicode, Inc. +Copyright (c) 2013-2017, Alfred Klomp +Copyright 2012 the V8 project authors +Copyright (c) 1999 Lucent Technologies +Copyright (c) 2008-2016, Wojciech Mula +Copyright (c) 2011-2020 Microsoft Corp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2021 csFastFloat authors +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors +Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 +Portions (c) International Organization +Copyright (c) 2004-2006 Intel Corporation +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) +Copyright (c) .NET Foundation Contributors +Copyright (c) 2020 Mara Bos +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2008-2020 Advanced Micro Devices, Inc. +Copyright (c) 2019 Microsoft Corporation, Daan Leijen +Copyright (c) 2011 Novell, Inc (http://www.novell.com) +Copyright (c) 1995-2022 Jean-loup Gailly and Mark Adler +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors +Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright (c) 1980, 1986, 1993 The Regents of the University of California +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass. To The MIT License (MIT) From 7fe5cb3e354eb775778944e5419cfbcb8fede735 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Thu, 2 Feb 2023 16:15:53 -0800 Subject: [PATCH 339/779] Fix `Start-Process -Credential -Wait` to work on Windows (#19082) * address Ilya's feedback, simplify to just WaitForExit() when cred is used * Update src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs Co-authored-by: Ilya --------- Co-authored-by: Ilya --- .../commands/management/Process.cs | 32 ++++++++++++------- 1 file changed, 20 insertions(+), 12 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs index 2bdb5fcc2b6..70596e263da 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs @@ -2039,21 +2039,29 @@ protected override void BeginProcessing() #if UNIX process.WaitForExit(); #else - _waithandle = new ManualResetEvent(false); - - // Create and start the job object - ProcessCollection jobObject = new(); - if (jobObject.AssignProcessToJobObject(process)) + if (_credential is not null) { - // Wait for the job object to finish - jobObject.WaitOne(_waithandle); + // If we are running as a different user, we cannot use a job object, so just wait on the process + process.WaitForExit(); } - else if (!process.HasExited) + else { - // WinBlue: 27537 Start-Process -Wait doesn't work in a remote session on Windows 7 or lower. - process.Exited += myProcess_Exited; - process.EnableRaisingEvents = true; - process.WaitForExit(); + _waithandle = new ManualResetEvent(false); + + // Create and start the job object + ProcessCollection jobObject = new(); + if (jobObject.AssignProcessToJobObject(process)) + { + // Wait for the job object to finish + jobObject.WaitOne(_waithandle); + } + else if (!process.HasExited) + { + // WinBlue: 27537 Start-Process -Wait doesn't work in a remote session on Windows 7 or lower. + process.Exited += myProcess_Exited; + process.EnableRaisingEvents = true; + process.WaitForExit(); + } } #endif } From ec0eb220626c5d30e8feeb1e9519d028fe67e906 Mon Sep 17 00:00:00 2001 From: spaette <111918424+spaette@users.noreply.github.com> Date: Thu, 2 Feb 2023 23:40:43 -0600 Subject: [PATCH 340/779] Fix typos in comments (#19064) --- assets/wix/Product.wxs | 2 +- .../HelpWindow/ParagraphBuilder.cs | 6 +++--- .../HelpWindow/ParagraphSearcher.cs | 12 ++++++------ .../ViewModel/AllModulesViewModel.cs | 2 +- .../management/GetComputerInfoCommand.cs | 2 +- .../Common/WebRequestPSCmdlet.Common.cs | 10 +++++----- .../host/msh/ConsoleControl.cs | 2 +- .../host/msh/PendingProgress.cs | 2 +- src/Microsoft.WSMan.Management/WsManHelper.cs | 4 ++-- .../resources/WsManResources.resx | 2 +- .../resources/WsManResources.txt | 2 +- .../CoreCLR/CorePsPlatform.cs | 2 +- .../common/FormatViewGenerator.cs | 4 ++-- .../common/FormatViewGenerator_Complex.cs | 2 +- .../common/FormattingObjects.cs | 2 +- .../FormatAndOutput/common/ILineOutput.cs | 2 +- .../engine/ComInterop/IDispatchComObject.cs | 2 +- .../engine/ComInterop/VarEnumSelector.cs | 2 +- .../CommandCompletion/CompletionCompleters.cs | 4 ++-- .../engine/CoreAdapter.cs | 2 +- .../engine/ExtendedTypeSystemException.cs | 18 +++++++++--------- .../engine/GetCommandCommand.cs | 2 +- .../engine/InitialSessionState.cs | 4 ++-- .../engine/Interop/Windows/QueryDosDevice.cs | 2 +- .../engine/Modules/ModuleCmdletBase.cs | 2 +- .../engine/Modules/ModuleIntrinsics.cs | 2 +- .../engine/Modules/ModuleSpecification.cs | 2 +- .../engine/NativeCommandParameterBinder.cs | 2 +- .../engine/ParameterBinderBase.cs | 2 +- .../engine/ParameterBinderController.cs | 2 +- .../engine/SessionStateContainer.cs | 2 +- .../engine/debugger/debugger.cs | 4 ++-- .../engine/hostifaces/ConnectionBase.cs | 2 +- .../hostifaces/InternalHostUserInterface.cs | 2 +- .../engine/hostifaces/LocalConnection.cs | 2 +- .../engine/lang/scriptblock.cs | 2 +- .../engine/parser/Compiler.cs | 4 ++-- .../engine/parser/Parser.cs | 2 +- .../engine/parser/tokenizer.cs | 2 +- .../engine/pipeline.cs | 2 +- .../remoting/commands/CustomShellCommands.cs | 16 ++++++++-------- .../remoting/commands/remotingcommandutil.cs | 2 +- .../fanin/InitialSessionStateProvider.cs | 2 +- .../engine/runtime/Binding/Binders.cs | 4 ++-- .../engine/runtime/Operations/MiscOps.cs | 2 +- .../help/AliasHelpProvider.cs | 4 ++-- .../help/ProviderContext.cs | 2 +- .../help/UpdatableHelpSystem.cs | 14 +++++++------- .../namespaces/FileSystemContentStream.cs | 2 +- .../namespaces/FileSystemProvider.cs | 2 +- .../namespaces/FileSystemSecurity.cs | 2 +- .../namespaces/RegistryProvider.cs | 4 ++-- .../security/CatalogHelper.cs | 4 ++-- .../security/SecurityManager.cs | 2 +- .../utils/MetadataExceptions.cs | 8 ++++---- .../utils/tracing/PSEtwLogProvider.cs | 2 +- src/TypeCatalogGen/TypeCatalogGen.cs | 2 +- test/hosting/test_HostingBasic.cs | 2 +- test/perf/benchmarks/Engine.Compiler.cs | 2 +- test/perf/benchmarks/Engine.ScriptBlock.cs | 2 +- .../PerfLabExporter.cs | 2 +- .../RecommendedConfig.cs | 2 +- .../TooManyTestCasesValidator.cs | 2 +- 63 files changed, 108 insertions(+), 108 deletions(-) diff --git a/assets/wix/Product.wxs b/assets/wix/Product.wxs index 3a8977e83fb..54979ecb51c 100644 --- a/assets/wix/Product.wxs +++ b/assets/wix/Product.wxs @@ -222,7 +222,7 @@ - ADD_EXPLORER_CONTEXT_MENU_OPENPOWERSHELL diff --git a/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphBuilder.cs b/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphBuilder.cs index 92c0de12cde..79c53d04ced 100644 --- a/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphBuilder.cs +++ b/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphBuilder.cs @@ -12,8 +12,8 @@ namespace Microsoft.Management.UI.Internal { /// /// Builds a paragraph based on Text + Bold + Highlight information. - /// Bold are the segments of thexct that should be bold, and Highlight are - /// the segments of thext that should be highlighted (like search results). + /// Bold are the segments of the text that should be bold, and Highlight are + /// the segments of the text that should be highlighted (like search results). /// internal class ParagraphBuilder : INotifyPropertyChanged { @@ -264,7 +264,7 @@ private static void MoveSpanToPosition(ref int currentSpanIndex, ref TextSpan? c } // there is no span ending ahead of current position, so - // we set the current span to null to prevent unecessary comparisons against the currentSpan + // we set the current span to null to prevent unnecessary comparisons against the currentSpan currentSpan = null; } diff --git a/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphSearcher.cs b/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphSearcher.cs index 9ba8f158a2f..c8b9907751d 100644 --- a/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphSearcher.cs +++ b/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphSearcher.cs @@ -43,8 +43,8 @@ internal ParagraphSearcher() /// The next highlight starting at the . internal Run MoveAndHighlightNextNextMatch(bool forward, TextPointer caretPosition) { - Debug.Assert(caretPosition != null, "a caret position is allways valid"); - Debug.Assert(caretPosition.Parent != null && caretPosition.Parent is Run, "a caret PArent is allways a valid Run"); + Debug.Assert(caretPosition != null, "a caret position is always valid"); + Debug.Assert(caretPosition.Parent != null && caretPosition.Parent is Run, "a caret Parent is always a valid Run"); Run caretRun = (Run)caretPosition.Parent; Run currentRun; @@ -59,7 +59,7 @@ internal Run MoveAndHighlightNextNextMatch(bool forward, TextPointer caretPositi // It has to be in the end because if there is a match at the beginning of the file // and the caret has not been touched (so it is in the beginning of the file too) // we want to highlight this first match. - // Considering the caller allways set the caret to the end of the highlight + // Considering the caller always set the caret to the end of the highlight // The condition below works well for successive searchs // We also need to move to the adjacent run if the caret is at the first run and we // are moving backwards so that a search backwards when the first run is highlighted @@ -78,7 +78,7 @@ internal Run MoveAndHighlightNextNextMatch(bool forward, TextPointer caretPositi if (currentRun == null) { - // if we could not find a next highlight wrap arround + // if we could not find a next highlight wraparound currentRun = ParagraphSearcher.GetFirstOrLastRun(caretRun, forward); currentRun = ParagraphSearcher.GetNextMatch(currentRun, forward); } @@ -86,7 +86,7 @@ internal Run MoveAndHighlightNextNextMatch(bool forward, TextPointer caretPositi this.currentHighlightedMatch = currentRun; if (this.currentHighlightedMatch != null) { - // restore the curent highligthed background to current highlighted + // restore the curent highlighted background to current highlighted this.currentHighlightedMatch.Background = ParagraphSearcher.CurrentHighlightBrush; } @@ -221,7 +221,7 @@ private static bool IsFirstRun(Run run) /// The first or last run in the paragraph containing . private static Run GetFirstOrLastRun(Run caretRun, bool forward) { - Debug.Assert(caretRun != null, "a caret run is allways valid"); + Debug.Assert(caretRun != null, "a caret run is always valid"); Paragraph paragraph = GetParagraph(caretRun); diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/AllModulesViewModel.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/AllModulesViewModel.cs index d2899b994d6..04fc95e4223 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/AllModulesViewModel.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/AllModulesViewModel.cs @@ -529,7 +529,7 @@ private void Initialization(Dictionary importedMo return; } - // If there are more modules, create an additional module to agregate all commands + // If there are more modules, create an additional module to aggregate all commands ModuleViewModel allCommandsModule = new ModuleViewModel(ShowCommandResources.All, null); this.modules.Add(allCommandsModule); allCommandsModule.SetAllModules(this); diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs index 02f13f1dd88..3de7c723745 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs @@ -1190,7 +1190,7 @@ internal static class EnumConverter where T : struct, IConvertible /// /// /// A Nullable enum object. If the value - /// is convertable to a valid enum value, the returned object's + /// is convertible to a valid enum value, the returned object's /// value will contain the converted value, otherwise the returned /// object will be null. /// diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index c267ad81f8d..7e991eece0a 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -1565,7 +1565,7 @@ protected override void ProcessRecord() /// The WebRequest who's content is to be set. /// A byte array containing the content data. /// - /// Because this function sets the request's ContentLength property and writes content data into the requests's stream, + /// Because this function sets the request's ContentLength property and writes content data into the request's stream, /// it should be called one time maximum on a given request. /// internal void SetRequestContent(HttpRequestMessage request, byte[] content) @@ -1583,7 +1583,7 @@ internal void SetRequestContent(HttpRequestMessage request, byte[] content) /// The WebRequest who's content is to be set. /// A String object containing the content data. /// - /// Because this function sets the request's ContentLength property and writes content data into the requests's stream, + /// Because this function sets the request's ContentLength property and writes content data into the request's stream, /// it should be called one time maximum on a given request. /// internal void SetRequestContent(HttpRequestMessage request, string content) @@ -1650,7 +1650,7 @@ internal void SetRequestContent(HttpRequestMessage request, XmlNode xmlNode) /// The WebRequest who's content is to be set. /// A Stream object containing the content data. /// - /// Because this function sets the request's ContentLength property and writes content data into the requests's stream, + /// Because this function sets the request's ContentLength property and writes content data into the request's stream, /// it should be called one time maximum on a given request. /// internal void SetRequestContent(HttpRequestMessage request, Stream contentStream) @@ -1668,7 +1668,7 @@ internal void SetRequestContent(HttpRequestMessage request, Stream contentStream /// The WebRequest who's content is to be set. /// A MultipartFormDataContent object containing multipart/form-data content. /// - /// Because this function sets the request's ContentLength property and writes content data into the requests's stream, + /// Because this function sets the request's ContentLength property and writes content data into the request's stream, /// it should be called one time maximum on a given request. /// internal void SetRequestContent(HttpRequestMessage request, MultipartFormDataContent multipartContent) @@ -1775,7 +1775,7 @@ private void AddMultipartContent(object fieldName, object fieldValue, MultipartF { foreach (var item in items) { - // Recruse, but do not enumerate the next level. IEnumerables will be treated as single values. + // Recurse, but do not enumerate the next level. IEnumerables will be treated as single values. AddMultipartContent(fieldName: fieldName, fieldValue: item, formData: formData, enumerate: false); } } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs index 43eb27b86e6..8857c64fa50 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs @@ -2799,7 +2799,7 @@ internal static int LengthInBufferCells(char c) ((uint)(c - 0xffe0) <= (0xffe6 - 0xffe0))); // We can ignore these ranges because .Net strings use surrogate pairs - // for this range and we do not handle surrogage pairs. + // for this range and we do not handle surrogate pairs. // (c >= 0x20000 && c <= 0x2fffd) || // (c >= 0x30000 && c <= 0x3fffd) return 1 + (isWide ? 1 : 0); diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs index 8453ad65072..7f1a5ad7e11 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs @@ -573,7 +573,7 @@ internal override int invisible = 0; if (TallyHeight(rawUI, maxHeight, maxWidth) > maxHeight) { - // This will smash down nodes until the tree will fit into the alloted number of lines. If in the + // This will smash down nodes until the tree will fit into the allotted number of lines. If in the // process some nodes were made invisible, we will add a line to the display to say so. invisible = CompressToFit(rawUI, maxHeight, maxWidth); diff --git a/src/Microsoft.WSMan.Management/WsManHelper.cs b/src/Microsoft.WSMan.Management/WsManHelper.cs index ce76f35af6c..83b1f0a72a3 100644 --- a/src/Microsoft.WSMan.Management/WsManHelper.cs +++ b/src/Microsoft.WSMan.Management/WsManHelper.cs @@ -615,7 +615,7 @@ internal static void ValidateSpecifiedAuthentication(AuthenticationMechanism aut if ((credential != null) && (certificateThumbprint != null)) { string message = FormatResourceMsgFromResourcetextS( - "AmbiguosAuthentication", + "AmbiguousAuthentication", "CertificateThumbPrint", "credential"); throw new InvalidOperationException(message); @@ -626,7 +626,7 @@ internal static void ValidateSpecifiedAuthentication(AuthenticationMechanism aut (certificateThumbprint != null)) { string message = FormatResourceMsgFromResourcetextS( - "AmbiguosAuthentication", + "AmbiguousAuthentication", "CertificateThumbPrint", authentication.ToString()); throw new InvalidOperationException(message); diff --git a/src/Microsoft.WSMan.Management/resources/WsManResources.resx b/src/Microsoft.WSMan.Management/resources/WsManResources.resx index c55aab1132f..a25f6c4801f 100644 --- a/src/Microsoft.WSMan.Management/resources/WsManResources.resx +++ b/src/Microsoft.WSMan.Management/resources/WsManResources.resx @@ -191,7 +191,7 @@ Do you want to enable CredSSP authentication? This command cannot be used because the parameter matches a non-text property on the ResourceURI.Check the input parameters and run your command. - + A {0} cannot be specified when {1} is specified. diff --git a/src/Microsoft.WSMan.Management/resources/WsManResources.txt b/src/Microsoft.WSMan.Management/resources/WsManResources.txt index 50cf1bf1fe5..10702e5ccea 100644 --- a/src/Microsoft.WSMan.Management/resources/WsManResources.txt +++ b/src/Microsoft.WSMan.Management/resources/WsManResources.txt @@ -56,7 +56,7 @@ CredSSPServiceConfigured=This computer is configured to receive credentials from CredSSPServiceNotConfigured=This computer is not configured to receive credentials from a remote client computer. QuickConfigContinueCaption=WinRM Quick Configuration QuickConfigContinueQuery=Running the Set-WSManQuickConfig command has significant security implications, as it enables remote management through the WinRM service on this computer.\nThis command:\n 1. Checks whether the WinRM service is running. If the WinRM service is not running, the service is started.\n 2. Sets the WinRM service startup type to automatic.\n 3. Creates a listener to accept requests on any IP address. By default, the transport is HTTP.\n 4. Enables a firewall exception for WS-Management traffic.\n 5. Enables Kerberos and Negotiate service authentication.\nDo you want to enable remote management through the WinRM service on this computer? -AmbiguosAuthentication=A {0} cannot be specified when {1} is specified. +AmbiguousAuthentication=A {0} cannot be specified when {1} is specified. CmdletNotAvailable=This PowerShell cmdlet is not available on for Windows XP and Windows Server 2003. InvalidValueType=This command cannot be used because the parameter value type is invalid. {0} configuration expects a value of Type {1}. Verify that the value is correct and try again. ClearItemOnRunAsPassword=The RunAsPassword value cannot be removed. Remove the values for RunAsUser and RunAsPassword in PowerShell by calling the Clear-Item cmdlet with the value for -Path attribute equal to the value of RunAsUser. diff --git a/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs b/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs index 78b355ab3fe..81b0e624ddf 100644 --- a/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs +++ b/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs @@ -898,7 +898,7 @@ internal static partial class NativeMethods private const string psLib = "libpsl-native"; // Ansi is a misnomer, it is hardcoded to UTF-8 on Linux and macOS - // C bools are 1 byte and so must be marshaled as I1 + // C bools are 1 byte and so must be marshalled as I1 [LibraryImport(psLib)] internal static partial int GetErrorCategory(int errno); diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator.cs index f29033e3c8d..41c4dafe85c 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator.cs @@ -219,7 +219,7 @@ internal GroupStartData GenerateGroupStartData(PSObject firstObjectInGroup, int if (formatErrorObject != null && formatErrorObject.exception != null) { - // if we did no thave any errors in the expression evaluation + // if we did not have any errors in the expression evaluation // we might have errors in the formatting, if present _errorManager.LogStringFormatError(formatErrorObject); if (_errorManager.DisplayFormatErrorString) @@ -387,7 +387,7 @@ protected string GetExpressionDisplayValue(PSObject so, int enumerationLimit, PS } else if (formatErrorObject != null && formatErrorObject.exception != null) { - // if we did no thave any errors in the expression evaluation + // if we did not have any errors in the expression evaluation // we might have errors in the formatting, if present _errorManager.LogStringFormatError(formatErrorObject); if (_errorManager.DisplayErrorStrings) diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Complex.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Complex.cs index cae35b7b28c..5573c28f78b 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Complex.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Complex.cs @@ -491,7 +491,7 @@ private void DisplayRawObject(PSObject so, List formatValueList) if (formatErrorObject != null && formatErrorObject.exception != null) { - // if we did no thave any errors in the expression evaluation + // if we did not have any errors in the expression evaluation // we might have errors in the formatting, if present _errorManager.LogStringFormatError(formatErrorObject); if (_errorManager.DisplayFormatErrorString) diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormattingObjects.cs b/src/System.Management.Automation/FormatAndOutput/common/FormattingObjects.cs index 6c999ae33ec..4af1ee54d81 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormattingObjects.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormattingObjects.cs @@ -18,7 +18,7 @@ // representation that mig have been introduced by serialization. // // There is also the need to preserve type information across serialization -// boundaries, therefore the objects provide a GUID based machanism to +// boundaries, therefore the objects provide a GUID based mechanism to // preserve the information. // diff --git a/src/System.Management.Automation/FormatAndOutput/common/ILineOutput.cs b/src/System.Management.Automation/FormatAndOutput/common/ILineOutput.cs index 3c200664636..7bca25ea828 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/ILineOutput.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/ILineOutput.cs @@ -137,7 +137,7 @@ protected static int CharLengthInBufferCells(char c) ((uint)(c - 0xffe0) <= (0xffe6 - 0xffe0))); // We can ignore these ranges because .Net strings use surrogate pairs - // for this range and we do not handle surrogage pairs. + // for this range and we do not handle surrogate pairs. // (c >= 0x20000 && c <= 0x2fffd) || // (c >= 0x30000 && c <= 0x3fffd) return 1 + (isWide ? 1 : 0); diff --git a/src/System.Management.Automation/engine/ComInterop/IDispatchComObject.cs b/src/System.Management.Automation/engine/ComInterop/IDispatchComObject.cs index 6ce86476566..7c2a3c106a7 100644 --- a/src/System.Management.Automation/engine/ComInterop/IDispatchComObject.cs +++ b/src/System.Management.Automation/engine/ComInterop/IDispatchComObject.cs @@ -22,7 +22,7 @@ namespace System.Management.Automation.ComInterop /// default arguments?). So obj.foo() is ambiguous as it could mean invoking method foo, /// or it could mean invoking the function pointer returned by property foo. /// We are attempting to find whether we need to call a method or a property by examining - /// the ITypeInfo associated with the IDispatch. ITypeInfo tell's use what parameters the method + /// the ITypeInfo associated with the IDispatch. ITypeInfo tells us what parameters the method /// expects, is it a method or a property, what is the default property of the object, how to /// create an enumerator for collections etc. /// diff --git a/src/System.Management.Automation/engine/ComInterop/VarEnumSelector.cs b/src/System.Management.Automation/engine/ComInterop/VarEnumSelector.cs index 942a6364435..bbe65d0a6ef 100644 --- a/src/System.Management.Automation/engine/ComInterop/VarEnumSelector.cs +++ b/src/System.Management.Automation/engine/ComInterop/VarEnumSelector.cs @@ -455,7 +455,7 @@ private VariantBuilder GetVariantBuilder(Type argumentType) if (elementType == typeof(object) || elementType == typeof(DBNull)) { //no meaningful value to pass ByRef. - //perhaps the calee will replace it with something. + //perhaps the callee will replace it with something. //need to pass as a variant reference elementVarEnum = VarEnum.VT_VARIANT; } diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs index ca4cc4ec1db..9b10aa31eab 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs @@ -2028,7 +2028,7 @@ private static void NativeCommandArgumentCompletion( string parameterName = parameter.Name; // Fall back to the commandAst command name if a command name is not found. This can be caused by a script block or AST with the matching function definition being passed to CompleteInput - // This allows for editors and other tools using CompleteInput with Script/AST definations to get values from RegisteredArgumentCompleters to better match the console experience. + // This allows for editors and other tools using CompleteInput with Script/AST definitions to get values from RegisteredArgumentCompleters to better match the console experience. // See issue https://github.com/PowerShell/PowerShell/issues/10567 string actualCommandName = string.IsNullOrEmpty(commandName) ? commandAst.GetCommandName() @@ -4618,7 +4618,7 @@ internal static IEnumerable CompleteFilename(CompletionContext } catch (Exception) { - // The object at the specified path is not accessable, such as c:\hiberfil.sys (for hibernation) or c:\pagefile.sys (for paging) + // The object at the specified path is not accessible, such as c:\hiberfil.sys (for hibernation) or c:\pagefile.sys (for paging) // We ignore those files continue; } diff --git a/src/System.Management.Automation/engine/CoreAdapter.cs b/src/System.Management.Automation/engine/CoreAdapter.cs index 0bda9ee906f..55486c674ab 100644 --- a/src/System.Management.Automation/engine/CoreAdapter.cs +++ b/src/System.Management.Automation/engine/CoreAdapter.cs @@ -2230,7 +2230,7 @@ internal object Invoke(object target, object[] arguments) // be thrown when converting arguments to the ByRef-like parameter types. // // So when reaching here, we only care about (1) if the method return type is - // BeRef-like; (2) if it's a constrcutor of a ByRef-like type. + // BeRef-like; (2) if it's a constructor of a ByRef-like type. if (method is ConstructorInfo ctor) { diff --git a/src/System.Management.Automation/engine/ExtendedTypeSystemException.cs b/src/System.Management.Automation/engine/ExtendedTypeSystemException.cs index 9ed85accb4f..854482e3f6f 100644 --- a/src/System.Management.Automation/engine/ExtendedTypeSystemException.cs +++ b/src/System.Management.Automation/engine/ExtendedTypeSystemException.cs @@ -36,7 +36,7 @@ public ExtendedTypeSystemException(string message) /// Initializes a new instance of ExtendedTypeSystemException setting the message and innerException. /// /// The exception's message. - /// The exceptions's inner exception. + /// The exception's inner exception. public ExtendedTypeSystemException(string message, Exception innerException) : base(message, innerException) { @@ -112,7 +112,7 @@ public MethodException(string message) /// Initializes a new instance of MethodException setting the message and innerException. /// /// The exception's message. - /// The exceptions's inner exception. + /// The exception's inner exception. public MethodException(string message, Exception innerException) : base(message, innerException) { @@ -183,7 +183,7 @@ public MethodInvocationException(string message) /// Initializes a new instance of MethodInvocationException setting the message and innerException. /// /// The exception's message. - /// The exceptions's inner exception. + /// The exception's inner exception. public MethodInvocationException(string message, Exception innerException) : base(message, innerException) { @@ -252,7 +252,7 @@ public GetValueException(string message) /// Initializes a new instance of GetValueException setting the message and innerException. /// /// The exception's message. - /// The exceptions's inner exception. + /// The exception's inner exception. public GetValueException(string message, Exception innerException) : base(message, innerException) { @@ -319,7 +319,7 @@ public PropertyNotFoundException(string message) /// Initializes a new instance of GetValueException setting the message and innerException. /// /// The exception's message. - /// The exceptions's inner exception. + /// The exception's inner exception. public PropertyNotFoundException(string message, Exception innerException) : base(message, innerException) { @@ -388,7 +388,7 @@ public GetValueInvocationException(string message) /// Initializes a new instance of GetValueInvocationException setting the message and innerException. /// /// The exception's message. - /// The exceptions's inner exception. + /// The exception's inner exception. public GetValueInvocationException(string message, Exception innerException) : base(message, innerException) { @@ -455,7 +455,7 @@ public SetValueException(string message) /// Initializes a new instance of SetValueException setting the message and innerException. /// /// The exception's message. - /// The exceptions's inner exception. + /// The exception's inner exception. public SetValueException(string message, Exception innerException) : base(message, innerException) { @@ -522,7 +522,7 @@ public SetValueInvocationException(string message) /// Initializes a new instance of SetValueInvocationException setting the message and innerException. /// /// The exception's message. - /// The exceptions's inner exception. + /// The exception's inner exception. public SetValueInvocationException(string message, Exception innerException) : base(message, innerException) { @@ -617,7 +617,7 @@ public PSInvalidCastException(string message) /// Initializes a new instance of PSInvalidCastException setting the message and innerException. /// /// The exception's message. - /// The exceptions's inner exception. + /// The exception's inner exception. public PSInvalidCastException(string message, Exception innerException) : base(message, innerException) { diff --git a/src/System.Management.Automation/engine/GetCommandCommand.cs b/src/System.Management.Automation/engine/GetCommandCommand.cs index 81675d7b663..9784cdc9ea8 100644 --- a/src/System.Management.Automation/engine/GetCommandCommand.cs +++ b/src/System.Management.Automation/engine/GetCommandCommand.cs @@ -564,7 +564,7 @@ private void OutputResultsHelper(IEnumerable results) // No telemetry here - capturing the name of a command which we are not familiar with // may be confidential customer information - // We want telementry on commands people look for but don't exist - this should give us an idea + // We want telemetry on commands people look for but don't exist - this should give us an idea // what sort of commands people expect but either don't exist, or maybe should be installed by default. // The StartsWith is to avoid logging telemetry when suggestion mode checks the // current directory for scripts/exes in the current directory and '.' is not in the path. diff --git a/src/System.Management.Automation/engine/InitialSessionState.cs b/src/System.Management.Automation/engine/InitialSessionState.cs index 78f6c0af988..31b8f549b4f 100644 --- a/src/System.Management.Automation/engine/InitialSessionState.cs +++ b/src/System.Management.Automation/engine/InitialSessionState.cs @@ -2434,7 +2434,7 @@ private void Bind_LoadAssemblies(ExecutionContext context) } // Specify the source only if this is for module loading. - // The source is used for porper cleaning of the assembly cache when a module is unloaded. + // The source is used for proper cleaning of the assembly cache when a module is unloaded. Assembly asm = context.AddAssembly(ssae.Module?.Name, ssae.Name, ssae.FileName, out Exception error); if (asm == null || error != null) @@ -4753,7 +4753,7 @@ internal static SessionStateAliasEntry[] BuiltInAliases SessionStateFunctionEntry.GetDelayParsedFunctionEntry("cd..", "Set-Location ..", isProductCode: true, languageMode: systemLanguageMode), SessionStateFunctionEntry.GetDelayParsedFunctionEntry("cd\\", "Set-Location \\", isProductCode: true, languageMode: systemLanguageMode), SessionStateFunctionEntry.GetDelayParsedFunctionEntry("cd~", "Set-Location ~", isProductCode: true, languageMode: systemLanguageMode), - // Win8: 320909. Retaining the original definition to ensure backward compatability. + // Win8: 320909. Retaining the original definition to ensure backward compatibility. SessionStateFunctionEntry.GetDelayParsedFunctionEntry("Pause", string.Concat("$null = Read-Host '", CodeGeneration.EscapeSingleQuotedStringContent(RunspaceInit.PauseDefinitionString), "'"), isProductCode: true, languageMode: systemLanguageMode), SessionStateFunctionEntry.GetDelayParsedFunctionEntry("help", GetHelpPagingFunctionText(), isProductCode: true, languageMode: systemLanguageMode), diff --git a/src/System.Management.Automation/engine/Interop/Windows/QueryDosDevice.cs b/src/System.Management.Automation/engine/Interop/Windows/QueryDosDevice.cs index 419a4ef127b..27907bd0135 100644 --- a/src/System.Management.Automation/engine/Interop/Windows/QueryDosDevice.cs +++ b/src/System.Management.Automation/engine/Interop/Windows/QueryDosDevice.cs @@ -41,7 +41,7 @@ internal static string GetDosDeviceForNetworkPath(char deviceName) { if (buffer.StartsWith("\\??\\")) { - // QueryDosDevice always return array of NULL-terinating strings with additional final NULL + // QueryDosDevice always return array of NULL-terminating strings with additional final NULL // so the buffer has always two NULL-s on end. // // "\\??\\UNC\\localhost\\c$\\tmp\0\0" -> "UNC\\localhost\\c$\\tmp\0\0" diff --git a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs index b17d3628aa4..f476fe6eb82 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs @@ -714,7 +714,7 @@ private PSModuleInfo LoadModuleNamedInManifest( if (string.IsNullOrEmpty(rootedPath)) { // Use the name of the parent module if it's specified, otherwise, use the current module name. - // - If the current module is a nested module, then the parent module will be specifeid. + // - If the current module is a nested module, then the parent module will be specified. // - If the current module is a root module, then the parent module will not be specified. string moduleName = parentModule?.Name ?? ModuleIntrinsics.GetModuleName(moduleSpecification.Name); rootedPath = FixFileName(moduleName, moduleBase, moduleSpecification.Name, extension: null, canLoadAssembly: importingModule); diff --git a/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs b/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs index 50170b63422..f15a567d655 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs @@ -1148,7 +1148,7 @@ private static string AddToPath(string basePath, string pathToAdd, int insertPos } else if (insertPosition > result.Length) { - // handle case where path is a singleton with no path seperator already + // handle case where path is a singleton with no path separator already result.Append(Path.PathSeparator).Append(subPathToAdd); } else // insert at the requested location (this is used by DSC ( location) and by 'user-specific location' (SpecialFolder.MyDocuments or EVT.User)) diff --git a/src/System.Management.Automation/engine/Modules/ModuleSpecification.cs b/src/System.Management.Automation/engine/Modules/ModuleSpecification.cs index b539b191909..a89837b3da2 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleSpecification.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleSpecification.cs @@ -127,7 +127,7 @@ internal static Exception ModuleSpecificationInitHelper(ModuleSpecification modu } } // catch all exceptions here, we are going to report them via return value. - // Example of catched exception: one of conversions to Version failed. + // Example of caught exception: one of conversions to Version failed. catch (Exception e) { return e; diff --git a/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs b/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs index 567a00387d5..104414f1fb8 100644 --- a/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs +++ b/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs @@ -201,7 +201,7 @@ internal NativeArgumentPassingStyle ArgumentPassingStyle } catch { - // The value is not convertable send back Legacy + // The value is not convertible send back Legacy return NativeArgumentPassingStyle.Legacy; } } diff --git a/src/System.Management.Automation/engine/ParameterBinderBase.cs b/src/System.Management.Automation/engine/ParameterBinderBase.cs index e190c4aaca3..d087d5900e3 100644 --- a/src/System.Management.Automation/engine/ParameterBinderBase.cs +++ b/src/System.Management.Automation/engine/ParameterBinderBase.cs @@ -1447,7 +1447,7 @@ private object HandleNullParameterForSpecialTypes( /// could not be created. /// [SuppressMessage("Microsoft.Maintainability", "CA1505:AvoidUnmaintainableCode")] - [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "Consider Simplyfing it")] + [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "Consider Simplifying it")] private object EncodeCollection( CommandParameterInternal argument, string parameterName, diff --git a/src/System.Management.Automation/engine/ParameterBinderController.cs b/src/System.Management.Automation/engine/ParameterBinderController.cs index 931dc24d554..f9781a99435 100644 --- a/src/System.Management.Automation/engine/ParameterBinderController.cs +++ b/src/System.Management.Automation/engine/ParameterBinderController.cs @@ -616,7 +616,7 @@ protected Collection BindNamedParameters(uint paramete { // This named parameter from splatting is also explicitly specified by the user, // which was successfully bound, so we ignore the one from splatting because it - // is superceded by the explicit one. For example: + // is superseded by the explicit one. For example: // $splat = @{ Path = $path1 } // dir @splat -Path $path2 continue; diff --git a/src/System.Management.Automation/engine/SessionStateContainer.cs b/src/System.Management.Automation/engine/SessionStateContainer.cs index 8a070caec87..1438671e1ec 100644 --- a/src/System.Management.Automation/engine/SessionStateContainer.cs +++ b/src/System.Management.Automation/engine/SessionStateContainer.cs @@ -1497,7 +1497,7 @@ internal void GetChildItems( // include and exclude filters try { - // Temeporary set literal path as false to apply filter + // Temporary set literal path as false to apply filter context.SuppressWildcardExpansion = false; ProcessPathItems(providerInstance, path, recurse, depth, context, out _, ProcessMode.Enumerate); } diff --git a/src/System.Management.Automation/engine/debugger/debugger.cs b/src/System.Management.Automation/engine/debugger/debugger.cs index c84d6a48293..2d154bec0f2 100644 --- a/src/System.Management.Automation/engine/debugger/debugger.cs +++ b/src/System.Management.Automation/engine/debugger/debugger.cs @@ -2129,7 +2129,7 @@ private bool CanDisableDebugger { get { - // The debugger can be disbled if there are no breakpoints + // The debugger can be disabled if there are no breakpoints // left and if we are not currently stepping in the debugger. return _idToBreakpoint.IsEmpty && _currentDebuggerAction != DebuggerResumeAction.StepInto && @@ -3539,7 +3539,7 @@ private DebuggerCommandResults ProcessCommandForActiveDebugger(PSCommand command else if ((command.Commands.Count > 0) && (command.Commands[0].CommandText.IndexOf(".EnterNestedPrompt()", StringComparison.OrdinalIgnoreCase) > 0)) { - // Prevent a host EnterNestedPrompt() call from occuring in an active debugger. + // Prevent a host EnterNestedPrompt() call from occurring in an active debugger. // Host nested prompt makes no sense in this case and can cause host to stop responding depending on host implementation. throw new PSNotSupportedException(); } diff --git a/src/System.Management.Automation/engine/hostifaces/ConnectionBase.cs b/src/System.Management.Automation/engine/hostifaces/ConnectionBase.cs index ca3847cc593..64ca4956e02 100644 --- a/src/System.Management.Automation/engine/hostifaces/ConnectionBase.cs +++ b/src/System.Management.Automation/engine/hostifaces/ConnectionBase.cs @@ -263,7 +263,7 @@ private void CoreOpen(bool syncCall) if (etwEnabled) RunspaceEventSource.Log.OpenRunspaceStop(); #if LEGACYTELEMETRY - // We report startup telementry when opening the runspace - because this is the first time + // We report startup telemetry when opening the runspace - because this is the first time // we are really using PowerShell. This isn't the cleanest place though, because // sometimes there are many runspaces created - the callee ensures telemetry is only // reported once. Note that if the host implements IHostProvidesTelemetryData, we rely diff --git a/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs index b9c1f5df8bc..94a25726f7b 100644 --- a/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs @@ -495,7 +495,7 @@ internal PSInformationalBuffers GetInformationalMessageBuffers() break; case 3: - // No to All means that we want to stop everytime WriteDebug is called. Since No throws an error, I + // No to All means that we want to stop every time WriteDebug is called. Since No throws an error, I // think that ordinarily, the caller will terminate. So I don't think the caller will ever get back // calling WriteDebug again, and thus "No to All" might not be a useful option to have. diff --git a/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs b/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs index e640e6f112a..476502c7e37 100644 --- a/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs +++ b/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs @@ -1512,7 +1512,7 @@ public RunspaceOpenModuleLoadException(string message) /// Initializes a new instance of ScriptBlockToPowerShellNotSupportedException setting the message and innerException. /// /// The exception's message. - /// The exceptions's inner exception. + /// The exception's inner exception. public RunspaceOpenModuleLoadException(string message, Exception innerException) : base(message, innerException) { diff --git a/src/System.Management.Automation/engine/lang/scriptblock.cs b/src/System.Management.Automation/engine/lang/scriptblock.cs index cc2f8ef9138..c00fb9d6e37 100644 --- a/src/System.Management.Automation/engine/lang/scriptblock.cs +++ b/src/System.Management.Automation/engine/lang/scriptblock.cs @@ -1359,7 +1359,7 @@ public ScriptBlockToPowerShellNotSupportedException(string message) /// Initializes a new instance of ScriptBlockToPowerShellNotSupportedException setting the message and innerException. /// /// The exception's message. - /// The exceptions's inner exception. + /// The exception's inner exception. public ScriptBlockToPowerShellNotSupportedException(string message, Exception innerException) : base(message, innerException) { diff --git a/src/System.Management.Automation/engine/parser/Compiler.cs b/src/System.Management.Automation/engine/parser/Compiler.cs index cfe4c60dea7..a262ec520a0 100644 --- a/src/System.Management.Automation/engine/parser/Compiler.cs +++ b/src/System.Management.Automation/engine/parser/Compiler.cs @@ -435,8 +435,8 @@ internal static class CachedReflectionInfo internal static readonly MethodInfo PSInvokeMemberBinder_IsHeterogeneousArray = typeof(PSInvokeMemberBinder).GetMethod(nameof(PSInvokeMemberBinder.IsHeterogeneousArray), StaticFlags); - internal static readonly MethodInfo PSInvokeMemberBinder_IsHomogenousArray = - typeof(PSInvokeMemberBinder).GetMethod(nameof(PSInvokeMemberBinder.IsHomogenousArray), StaticFlags); + internal static readonly MethodInfo PSInvokeMemberBinder_IsHomogeneousArray = + typeof(PSInvokeMemberBinder).GetMethod(nameof(PSInvokeMemberBinder.IsHomogeneousArray), StaticFlags); internal static readonly MethodInfo PSInvokeMemberBinder_TryGetInstanceMethod = typeof(PSInvokeMemberBinder).GetMethod(nameof(PSInvokeMemberBinder.TryGetInstanceMethod), StaticFlags); diff --git a/src/System.Management.Automation/engine/parser/Parser.cs b/src/System.Management.Automation/engine/parser/Parser.cs index f110845afdf..e1788d5996f 100644 --- a/src/System.Management.Automation/engine/parser/Parser.cs +++ b/src/System.Management.Automation/engine/parser/Parser.cs @@ -5750,7 +5750,7 @@ private PipelineBaseAst PipelineChainRule() // just look for pipelines as before. RuntimeHelpers.EnsureSufficientExecutionStack(); - // First look for assignment, since PipelineRule once handled that and this supercedes that. + // First look for assignment, since PipelineRule once handled that and this supersedes that. // We may end up with an expression here as a result, // in which case we hang on to it to pass it into the first pipeline rule call. Token assignToken = null; diff --git a/src/System.Management.Automation/engine/parser/tokenizer.cs b/src/System.Management.Automation/engine/parser/tokenizer.cs index 9e133016e85..c0c150cdd42 100644 --- a/src/System.Management.Automation/engine/parser/tokenizer.cs +++ b/src/System.Management.Automation/engine/parser/tokenizer.cs @@ -2563,7 +2563,7 @@ private bool ScanDollarInStringExpandable(StringBuilder sb, StringBuilder format // Make sure we didn't consume anything because we didn't find // any nested tokens (no variable or subexpression.) - Diagnostics.Assert(PeekChar() == c1, "We accidently consumed a character we shouldn't have."); + Diagnostics.Assert(PeekChar() == c1, "We accidentally consumed a character we shouldn't have."); return false; } diff --git a/src/System.Management.Automation/engine/pipeline.cs b/src/System.Management.Automation/engine/pipeline.cs index 3373b5e56f0..dba038f91b4 100644 --- a/src/System.Management.Automation/engine/pipeline.cs +++ b/src/System.Management.Automation/engine/pipeline.cs @@ -1040,7 +1040,7 @@ private void Start(bool incomingStream) } // We want the value of PSDefaultParameterValues before possibly changing to the commands scopes. - // This ensures we use the value from the callers scope, not the callees scope. + // This ensures we use the value from the caller's scope, not the callee's scope. IDictionary psDefaultParameterValues = firstcommandProcessor.Context.GetVariableValue(SpecialVariables.PSDefaultParameterValuesVarPath, false) as IDictionary; diff --git a/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs b/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs index 811707a3b54..e4424fd8c9a 100644 --- a/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs +++ b/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs @@ -348,7 +348,7 @@ static RegisterPSSessionConfigurationCommand() string localSDDL = GetLocalSddl(); // compile the script block statically and reuse the same instance - // everytime the command is run..This will save on parsing time. + // every time the command is run..This will save on parsing time. string newPluginSbString = string.Format(CultureInfo.InvariantCulture, newPluginSbFormat, WSManNativeApi.ResourceURIPrefix, localSDDL, RemoteManagementUsersSID, InteractiveUsersSID); @@ -2618,7 +2618,7 @@ static UnregisterPSSessionConfigurationCommand() removePluginSbFormat, RemotingConstants.PSPluginDLLName); // compile the script block statically and reuse the same instance - // everytime the command is run..This will save on parsing time. + // every time the command is run..This will save on parsing time. s_removePluginSb = ScriptBlock.Create(removePluginScript); s_removePluginSb.LanguageMode = PSLanguageMode.FullLanguage; } @@ -2834,7 +2834,7 @@ static GetPSSessionConfigurationCommand() PSSessionConfigurationCommandUtilities.PSCustomShellTypeName, RemotingConstants.PSPluginDLLName); // compile the script block statically and reuse the same instance - // everytime the command is run..This will save on parsing time. + // every time the command is run..This will save on parsing time. s_getPluginSb = ScriptBlock.Create(scriptToRun); s_getPluginSb.LanguageMode = PSLanguageMode.FullLanguage; } @@ -3258,7 +3258,7 @@ static SetPSSessionConfigurationCommand() RemotingConstants.PSPluginDLLName, localSDDL, RemoteManagementUsersSID, InteractiveUsersSID); // compile the script block statically and reuse the same instance - // everytime the command is run..This will save on parsing time. + // every time the command is run..This will save on parsing time. s_setPluginSb = ScriptBlock.Create(setPluginScript); s_setPluginSb.LanguageMode = PSLanguageMode.FullLanguage; } @@ -4208,7 +4208,7 @@ static EnablePSSessionConfigurationCommand() enablePluginSbFormat, setWSManConfigCommand, PSSessionConfigurationCommandBase.RemoteManagementUsersSID, PSSessionConfigurationCommandBase.InteractiveUsersSID); // compile the script block statically and reuse the same instance - // everytime the command is run..This will save on parsing time. + // every time the command is run..This will save on parsing time. s_enablePluginSb = ScriptBlock.Create(enablePluginScript); s_enablePluginSb.LanguageMode = PSLanguageMode.FullLanguage; } @@ -4495,7 +4495,7 @@ static DisablePSSessionConfigurationCommand() disablePluginSbFormat); // compile the script block statically and reuse the same instance - // everytime the command is run..This will save on parsing time. + // every time the command is run..This will save on parsing time. s_disablePluginSb = ScriptBlock.Create(disablePluginScript); s_disablePluginSb.LanguageMode = PSLanguageMode.FullLanguage; } @@ -4902,7 +4902,7 @@ static EnablePSRemotingCommand() RemotingConstants.MaxIdleTimeoutMS, RemotingConstants.PSPluginDLLName); // compile the script block statically and reuse the same instance - // everytime the command is run..This will save on parsing time. + // every time the command is run..This will save on parsing time. s_enableRemotingSb = ScriptBlock.Create(enableRemotingScript); s_enableRemotingSb.LanguageMode = PSLanguageMode.FullLanguage; } @@ -5126,7 +5126,7 @@ static DisablePSRemotingCommand() string disableRemotingScript = string.Format(CultureInfo.InvariantCulture, disablePSRemotingFormat, localSDDL); // compile the script block statically and reuse the same instance - // everytime the command is run..This will save on parsing time. + // every time the command is run..This will save on parsing time. s_disableRemotingSb = ScriptBlock.Create(disableRemotingScript); s_disableRemotingSb.LanguageMode = PSLanguageMode.FullLanguage; } diff --git a/src/System.Management.Automation/engine/remoting/commands/remotingcommandutil.cs b/src/System.Management.Automation/engine/remoting/commands/remotingcommandutil.cs index f30e4ba5109..3e2603a36fe 100644 --- a/src/System.Management.Automation/engine/remoting/commands/remotingcommandutil.cs +++ b/src/System.Management.Automation/engine/remoting/commands/remotingcommandutil.cs @@ -93,7 +93,7 @@ internal static void CheckRemotingCmdletPrerequisites() try { - // the following registry key defines WSMan compatability + // the following registry key defines WSMan compatibility // HKLM\Software\Microsoft\Windows\CurrentVersion\WSMAN\ServiceStackVersion string wsManStackValue = null; RegistryKey wsManKey = Registry.LocalMachine.OpenSubKey(WSManKeyPath); diff --git a/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs b/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs index ffcb9a80672..600614ca764 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs @@ -2983,7 +2983,7 @@ internal static class DISCFileValidation #endif // These are configuration options for WSMan (WinRM) endpoint configurations, that - // appearand in .pssc files, but are not part of PowerShell InitialSessionState. + // appear in .pssc files, but are not part of PowerShell InitialSessionState. private static readonly HashSet UnsupportedConfigOptions = new HashSet(StringComparer.OrdinalIgnoreCase) { "GroupManagedServiceAccount", diff --git a/src/System.Management.Automation/engine/runtime/Binding/Binders.cs b/src/System.Management.Automation/engine/runtime/Binding/Binders.cs index ca27ecaccae..d5517443a62 100644 --- a/src/System.Management.Automation/engine/runtime/Binding/Binders.cs +++ b/src/System.Management.Automation/engine/runtime/Binding/Binders.cs @@ -94,7 +94,7 @@ internal static BindingRestrictions PSGetMethodArgumentRestriction(this DynamicM { var effectiveArgType = Adapter.EffectiveArgumentType(obj.Value); var methodInfo = effectiveArgType != typeof(object[]) - ? CachedReflectionInfo.PSInvokeMemberBinder_IsHomogenousArray.MakeGenericMethod(effectiveArgType.GetElementType()) + ? CachedReflectionInfo.PSInvokeMemberBinder_IsHomogeneousArray.MakeGenericMethod(effectiveArgType.GetElementType()) : CachedReflectionInfo.PSInvokeMemberBinder_IsHeterogeneousArray; BindingRestrictions restrictions; @@ -7372,7 +7372,7 @@ private DynamicMetaObject InvokeForEachOnCollection(DynamicMetaObject targetEnum #region Runtime helpers - internal static bool IsHomogenousArray(object[] args) + internal static bool IsHomogeneousArray(object[] args) { if (args.Length == 0) { diff --git a/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs b/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs index 907c07e5916..e6efdace4c5 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs @@ -1478,7 +1478,7 @@ internal static int FindMatchingHandler(MutableTuple tuple, RuntimeException rte do { - // Always assume no need to repeat the search for another interation + // Always assume no need to repeat the search for another iteration continueToSearch = false; // The 'ErrorRecord' of the current RuntimeException would be passed to $_ ErrorRecord errorRecordToPass = rte.ErrorRecord; diff --git a/src/System.Management.Automation/help/AliasHelpProvider.cs b/src/System.Management.Automation/help/AliasHelpProvider.cs index f14f815891a..d93aa76b2f3 100644 --- a/src/System.Management.Automation/help/AliasHelpProvider.cs +++ b/src/System.Management.Automation/help/AliasHelpProvider.cs @@ -161,7 +161,7 @@ internal override IEnumerable SearchHelp(HelpRequest helpRequest, bool foreach (HelpInfo helpInfo in ExactMatchHelp(exactMatchHelpRequest)) { // Component/Role/Functionality match is done only for SearchHelp - // as "get-help * -category alias" should not forwad help to + // as "get-help * -category alias" should not forward help to // CommandHelpProvider..(ExactMatchHelp does forward help to // CommandHelpProvider) if (!Match(helpInfo, helpRequest)) @@ -208,7 +208,7 @@ internal override IEnumerable SearchHelp(HelpRequest helpRequest, bool foreach (HelpInfo helpInfo in ExactMatchHelp(exactMatchHelpRequest)) { // Component/Role/Functionality match is done only for SearchHelp - // as "get-help * -category alias" should not forwad help to + // as "get-help * -category alias" should not forward help to // CommandHelpProvider..(ExactMatchHelp does forward help to // CommandHelpProvider) if (!Match(helpInfo, helpRequest)) diff --git a/src/System.Management.Automation/help/ProviderContext.cs b/src/System.Management.Automation/help/ProviderContext.cs index cb24ece0593..817e2b3f0e6 100644 --- a/src/System.Management.Automation/help/ProviderContext.cs +++ b/src/System.Management.Automation/help/ProviderContext.cs @@ -141,7 +141,7 @@ Runspaces.SessionStateProviderEntry sessionStateProvider in } } - // ok we have path and valid provider that supplys content..initialize the provider + // ok we have path and valid provider that supplies content..initialize the provider // and get the help content for the path. cmdletProvider.Start(providerInfo, cmdletProviderContext); // There should be exactly one resolved path. diff --git a/src/System.Management.Automation/help/UpdatableHelpSystem.cs b/src/System.Management.Automation/help/UpdatableHelpSystem.cs index 31fe5362d77..c909556adef 100644 --- a/src/System.Management.Automation/help/UpdatableHelpSystem.cs +++ b/src/System.Management.Automation/help/UpdatableHelpSystem.cs @@ -1097,14 +1097,14 @@ internal void InstallHelpContent(UpdatableHelpCommandType commandType, Execution #if UNIX private static bool ExpandArchive(string source, string destination) { - bool sucessfulDecompression = false; + bool successfulDecompression = false; try { using (ZipArchive zipArchive = ZipFile.Open(source, ZipArchiveMode.Read)) { zipArchive.ExtractToDirectory(destination); - sucessfulDecompression = true; + successfulDecompression = true; } } catch (ArgumentException) { } @@ -1116,7 +1116,7 @@ private static bool ExpandArchive(string source, string destination) catch (UnauthorizedAccessException) { } catch (ObjectDisposedException) { } - return sucessfulDecompression; + return successfulDecompression; } #endif @@ -1137,9 +1137,9 @@ private static void UnzipHelpContent(ExecutionContext context, string srcPath, s } string sourceDirectory = Path.GetDirectoryName(srcPath); - bool sucessfulDecompression = false; + bool successfulDecompression = false; #if UNIX - sucessfulDecompression = ExpandArchive(Path.Combine(sourceDirectory, Path.GetFileName(srcPath)), destPath); + successfulDecompression = ExpandArchive(Path.Combine(sourceDirectory, Path.GetFileName(srcPath)), destPath); #else // Cabinet API doesn't handle the trailing back slash if (!sourceDirectory.EndsWith('\\')) @@ -1152,9 +1152,9 @@ private static void UnzipHelpContent(ExecutionContext context, string srcPath, s destPath += "\\"; } - sucessfulDecompression = CabinetExtractorFactory.GetCabinetExtractor().Extract(Path.GetFileName(srcPath), sourceDirectory, destPath); + successfulDecompression = CabinetExtractorFactory.GetCabinetExtractor().Extract(Path.GetFileName(srcPath), sourceDirectory, destPath); #endif - if (!sucessfulDecompression) + if (!successfulDecompression) { throw new UpdatableHelpSystemException("UnableToExtract", StringUtil.Format(HelpDisplayStrings.UnzipFailure), ErrorCategory.InvalidOperation, null, null); diff --git a/src/System.Management.Automation/namespaces/FileSystemContentStream.cs b/src/System.Management.Automation/namespaces/FileSystemContentStream.cs index f9af5222a5f..5aa81ccd680 100644 --- a/src/System.Management.Automation/namespaces/FileSystemContentStream.cs +++ b/src/System.Management.Automation/namespaces/FileSystemContentStream.cs @@ -709,7 +709,7 @@ private bool ReadDelimited(bool waitChanges, List blocks, bool readBackw // We've reached the end of file or end of line. if (_currentLineContent.Length > 0) { - // Add the block read to the ouptut array list, trimming a trailing delimiter, if present. + // Add the block read to the output array list, trimming a trailing delimiter, if present. // Note: If -Tail was specified, we get here in the course of 2 distinct passes: // - Once while reading backward simply to determine the appropriate *start position* for later forward reading, ignoring the content of the blocks read (in reverse). // - Then again during forward reading, for regular output processing; it is only then that trimming the delimiter is necessary. diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index 4d7acd99d32..5c2ff6d89c4 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -5101,7 +5101,7 @@ protected override string NormalizeRelativePath( #if UNIX // We don't use the Directory.EnumerateFiles() for Unix because the path // may contain additional globbing patterns such as '[ab]' - // which Directory.EnumerateFiles() processes, giving undesireable + // which Directory.EnumerateFiles() processes, giving undesirable // results in this context. if (!File.Exists(result) && !Directory.Exists(result)) { diff --git a/src/System.Management.Automation/namespaces/FileSystemSecurity.cs b/src/System.Management.Automation/namespaces/FileSystemSecurity.cs index c886bbd0a0b..31e996e9b63 100644 --- a/src/System.Management.Automation/namespaces/FileSystemSecurity.cs +++ b/src/System.Management.Automation/namespaces/FileSystemSecurity.cs @@ -141,7 +141,7 @@ public void SetSecurityDescriptor( // the solution is to: // // - First attempt to copy the entire security descriptor as we did in V1. - // This ensures backward compatability for administrator scripts that currently + // This ensures backward compatibility for administrator scripts that currently // work. // - If the attempt fails due to a PrivilegeNotHeld exception, try again with // an estimate of the minimum required subset. This is an estimate, since the diff --git a/src/System.Management.Automation/namespaces/RegistryProvider.cs b/src/System.Management.Automation/namespaces/RegistryProvider.cs index fff328fba29..ecf36bec4ca 100644 --- a/src/System.Management.Automation/namespaces/RegistryProvider.cs +++ b/src/System.Management.Automation/namespaces/RegistryProvider.cs @@ -801,7 +801,7 @@ private static string EscapeSpecialChars(string path) // should not be done. if (textElement.Contains(charactersThatNeedEscaping)) { - // This text element needs espacing + // This text element needs escaping result.Append('`'); } @@ -850,7 +850,7 @@ private static string EscapeChildName(string name) // should not be done. if (textElement.Contains(charactersThatNeedEscaping)) { - // This text element needs espacing + // This text element needs escaping result.Append('`'); } diff --git a/src/System.Management.Automation/security/CatalogHelper.cs b/src/System.Management.Automation/security/CatalogHelper.cs index 5f71d1f86be..8347423f305 100644 --- a/src/System.Management.Automation/security/CatalogHelper.cs +++ b/src/System.Management.Automation/security/CatalogHelper.cs @@ -689,8 +689,8 @@ internal static bool CompareDictionaries(Dictionary catalogItems List relativePathsFromFolder = pathItems.Keys.ToList(); List relativePathsFromCatalog = catalogItems.Keys.ToList(); - // Find entires those are not in both list lists. These should be empty lists for success - // Hashes in Catalog should be exact similar to the ones from folder + // Find entries that are not in both lists. These should be empty lists for success + // Hashes in Catalog should be exactly similar to the ones from folder List relativePathsNotInFolder = relativePathsFromFolder.Except(relativePathsFromCatalog, StringComparer.CurrentCultureIgnoreCase).ToList(); List relativePathsNotInCatalog = relativePathsFromCatalog.Except(relativePathsFromFolder, StringComparer.CurrentCultureIgnoreCase).ToList(); diff --git a/src/System.Management.Automation/security/SecurityManager.cs b/src/System.Management.Automation/security/SecurityManager.cs index 2baf1560a38..e7874ec3524 100644 --- a/src/System.Management.Automation/security/SecurityManager.cs +++ b/src/System.Management.Automation/security/SecurityManager.cs @@ -180,7 +180,7 @@ private bool CheckPolicy(ExternalScriptInfo script, PSHost host, out Exception r } } - // WLDP and Applocker takes priority over powershell exeuction policy. + // WLDP and Applocker takes priority over powershell execution policy. // See if they want to bypass the authorization manager if (_executionPolicy == ExecutionPolicy.Bypass) { diff --git a/src/System.Management.Automation/utils/MetadataExceptions.cs b/src/System.Management.Automation/utils/MetadataExceptions.cs index 53f2328fc3d..21e499ce5e4 100644 --- a/src/System.Management.Automation/utils/MetadataExceptions.cs +++ b/src/System.Management.Automation/utils/MetadataExceptions.cs @@ -48,7 +48,7 @@ public MetadataException(string message) : base(message) /// Initializes a new instance of MetadataException setting the message and innerException. /// /// The exception's message. - /// The exceptions's inner exception. + /// The exception's inner exception. public MetadataException(string message, Exception innerException) : base(message, innerException) { SetErrorCategory(ErrorCategory.MetadataError); @@ -124,7 +124,7 @@ public ValidationMetadataException(string message) : this(message, false) { } /// Initializes a new instance of ValidationMetadataException setting the message and innerException. /// /// The exception's message. - /// The exceptions's inner exception. + /// The exception's inner exception. public ValidationMetadataException(string message, Exception innerException) : base(message, innerException) { } internal ValidationMetadataException( @@ -198,7 +198,7 @@ public ArgumentTransformationMetadataException(string message) /// Initializes a new instance of ArgumentTransformationMetadataException setting the message and innerException. /// /// The exception's message. - /// The exceptions's inner exception. + /// The exception's inner exception. public ArgumentTransformationMetadataException(string message, Exception innerException) : base(message, innerException) { } @@ -246,7 +246,7 @@ public ParsingMetadataException(string message) /// Initializes a new instance of ParsingMetadataException setting the message and innerException. /// /// The exception's message. - /// The exceptions's inner exception. + /// The exception's inner exception. public ParsingMetadataException(string message, Exception innerException) : base(message, innerException) { } diff --git a/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs b/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs index 9b56da1ae72..586082a0d43 100755 --- a/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs +++ b/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs @@ -127,7 +127,7 @@ internal override void LogCommandLifecycleEvent(Func getLogContext, if (newState == CommandState.Stopped || newState == CommandState.Terminated) { - // When state is stopped or termianted only log the CommandName + // When state is stopped or terminated only log the CommandName payload.AppendLine(StringUtil.Format(EtwLoggingStrings.CommandStateChange, logContext, newState.ToString())); } else diff --git a/src/TypeCatalogGen/TypeCatalogGen.cs b/src/TypeCatalogGen/TypeCatalogGen.cs index aff32f6f82f..4bf5605fb0a 100644 --- a/src/TypeCatalogGen/TypeCatalogGen.cs +++ b/src/TypeCatalogGen/TypeCatalogGen.cs @@ -97,7 +97,7 @@ public static void Main(string[] args) // We only care about public types TypeDefinition typeDefinition = metadataReader.GetTypeDefinition(typeHandle); // The visibility mask is used to mask out the bits that contain the visibility. - // The visibilities are not combineable, e.g. you can't be both public and private, which is why these aren't independent powers of two. + // The visibilities are not combinable, e.g. you can't be both public and private, which is why these aren't independent powers of two. TypeAttributes visibilityBits = typeDefinition.Attributes & TypeAttributes.VisibilityMask; if (visibilityBits != TypeAttributes.Public && visibilityBits != TypeAttributes.NestedPublic) { diff --git a/test/hosting/test_HostingBasic.cs b/test/hosting/test_HostingBasic.cs index e29b14e38c0..1b4a67707e2 100644 --- a/test/hosting/test_HostingBasic.cs +++ b/test/hosting/test_HostingBasic.cs @@ -183,7 +183,7 @@ public static void TestConsoleShellScenario() Assert.Equal(42, ret); } - /* Test disabled because CommandLineParser is static and can only be intialized once (above in TestConsoleShellScenario) + /* Test disabled because CommandLineParser is static and can only be initialized once (above in TestConsoleShellScenario) /// /// ConsoleShell cannot start with both InitialSessionState and -ConfigurationFile argument configurations specified. /// diff --git a/test/perf/benchmarks/Engine.Compiler.cs b/test/perf/benchmarks/Engine.Compiler.cs index 10e0054a01c..4f9dbab88a9 100644 --- a/test/perf/benchmarks/Engine.Compiler.cs +++ b/test/perf/benchmarks/Engine.Compiler.cs @@ -58,7 +58,7 @@ public void GlobalSetup() // Run it once to get the C# code jitted. // The first call to this takes relatively too long, which makes the BDN's heuristic incorrectly - // believe that there is no need to run many ops in each interation. However, the subsequent runs + // believe that there is no need to run many ops in each iteration. However, the subsequent runs // of this method is much faster than the first run, and this causes 'MinIterationTime' warnings // to our benchmarks and make the benchmark results not reliable. // Calling this method once in 'GlobalSetup' is a workaround. diff --git a/test/perf/benchmarks/Engine.ScriptBlock.cs b/test/perf/benchmarks/Engine.ScriptBlock.cs index 1f9ac989428..dfd7beb865f 100644 --- a/test/perf/benchmarks/Engine.ScriptBlock.cs +++ b/test/perf/benchmarks/Engine.ScriptBlock.cs @@ -51,7 +51,7 @@ public void GlobalSetup() // Run it once to get the C# code jitted and the script compiled. // The first call to this takes relatively too long, which makes the BDN's heuristic incorrectly - // believe that there is no need to run many ops in each interation. However, the subsequent runs + // believe that there is no need to run many ops in each iteration. However, the subsequent runs // of this method is much faster than the first run, and this causes 'MinIterationTime' warnings // to our benchmarks and make the benchmark results not reliable. // Calling this method once in 'GlobalSetup' is a workaround. diff --git a/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/PerfLabExporter.cs b/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/PerfLabExporter.cs index b50e408af0b..86306da342a 100644 --- a/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/PerfLabExporter.cs +++ b/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/PerfLabExporter.cs @@ -25,7 +25,7 @@ public override void ExportToLog(Summary summary, ILogger logger) var reporter = Reporter.CreateReporter(); DisassemblyDiagnoser disassemblyDiagnoser = summary.Reports - .FirstOrDefault()? // dissasembler was either enabled for all or none of them (so we use the first one) + .FirstOrDefault()? // disassembler was either enabled for all or none of them (so we use the first one) .BenchmarkCase.Config.GetDiagnosers().OfType().FirstOrDefault(); foreach (var report in summary.Reports) diff --git a/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/RecommendedConfig.cs b/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/RecommendedConfig.cs index 40aa5f87fbe..a8aac9700b0 100644 --- a/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/RecommendedConfig.cs +++ b/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/RecommendedConfig.cs @@ -31,7 +31,7 @@ public static IConfig Create( { job = Job.Default .WithWarmupCount(1) // 1 warmup is enough for our purpose - .WithIterationTime(TimeInterval.FromMilliseconds(250)) // the default is 0.5s per iteration, which is slighlty too much for us + .WithIterationTime(TimeInterval.FromMilliseconds(250)) // the default is 0.5s per iteration, which is slightly too much for us .WithMinIterationCount(15) .WithMaxIterationCount(20) // we don't want to run more that 20 iterations .DontEnforcePowerPlan(); // make sure BDN does not try to enforce High Performance power plan on Windows diff --git a/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/TooManyTestCasesValidator.cs b/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/TooManyTestCasesValidator.cs index 36c8b41f9c7..b001f603dcb 100644 --- a/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/TooManyTestCasesValidator.cs +++ b/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/TooManyTestCasesValidator.cs @@ -26,7 +26,7 @@ public IEnumerable Validate(ValidationParameters validationPara return byDescriptor.Where(benchmarkCase => benchmarkCase.Count() > Limit).Select(group => new ValidationError( isCritical: true, - message: $"{group.Key.Descriptor.Type.Name}.{group.Key.Descriptor.WorkloadMethod.Name} has {group.Count()} test cases. It MUST NOT have more than {Limit} test cases. We don't have inifinite amount of time to run all the benchmarks!!", + message: $"{group.Key.Descriptor.Type.Name}.{group.Key.Descriptor.WorkloadMethod.Name} has {group.Count()} test cases. It MUST NOT have more than {Limit} test cases. We don't have infinite amount of time to run all the benchmarks!!", benchmarkCase: group.First())); } } From bfef3a4814af5527c4c6ccbd2b624151650b0c23 Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Tue, 7 Feb 2023 12:13:54 -0800 Subject: [PATCH 341/779] Update CodeQL build agent (#19113) --- .github/workflows/codeql-analysis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index 48ff5aad04c..6463ce67ff1 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -24,7 +24,7 @@ jobs: contents: read # for actions/checkout to fetch code security-events: write # for github/codeql-action/analyze to upload SARIF results name: Analyze - runs-on: ubuntu-18.04 + runs-on: ubuntu-latest strategy: fail-fast: false From 462f82574320cbb0a104ab29cff4196980935d17 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Wed, 8 Feb 2023 11:54:53 +0100 Subject: [PATCH 342/779] Small changes in Webcmdlets (#19109) --- .../Common/WebRequestPSCmdlet.Common.cs | 38 ++++++++----------- 1 file changed, 15 insertions(+), 23 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index 7e991eece0a..38b4e645ec6 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -605,7 +605,7 @@ internal virtual void PrepareSession() if (CertificateThumbprint is not null) { - X509Store store = new(StoreName.My, StoreLocation.CurrentUser); + using X509Store store = new(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly); X509Certificate2Collection collection = (X509Certificate2Collection)store.Certificates; X509Certificate2Collection tbCollection = (X509Certificate2Collection)collection.Find(X509FindType.FindByThumbprint, CertificateThumbprint, false); @@ -1230,7 +1230,6 @@ private bool ShouldRetry(HttpStatusCode code) internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestMessage request, bool handleRedirect) { ArgumentNullException.ThrowIfNull(client); - ArgumentNullException.ThrowIfNull(request); // Add 1 to account for the first request. @@ -1241,7 +1240,7 @@ internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestM do { // Track the current URI being used by various requests and re-requests. - var currentUri = req.RequestUri; + Uri currentUri = req.RequestUri; _cancelToken = new CancellationTokenSource(); response = client.SendAsync(req, HttpCompletionOption.ResponseHeadersRead, _cancelToken.Token).GetAwaiter().GetResult(); @@ -1259,6 +1258,7 @@ internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestM { WebSession.MaximumRedirection--; } + // For selected redirects that used POST, GET must be used with the // redirected Location. // Since GET is the default; POST only occurs when -Method POST is used. @@ -1269,12 +1269,10 @@ internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestM } currentUri = new Uri(request.RequestUri, response.Headers.Location); + // Continue to handle redirection - using (client = GetHttpClient(handleRedirect)) - using (HttpRequestMessage redirectRequest = GetRequest(currentUri)) - { - response = GetResponse(client, redirectRequest, handleRedirect); - } + using HttpRequestMessage redirectRequest = GetRequest(currentUri); + response = GetResponse(client, redirectRequest, handleRedirect); } // Request again without the Range header because the server indicated the range was not satisfiable. @@ -1296,11 +1294,8 @@ internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestM using (HttpRequestMessage requestWithoutRange = GetRequest(currentUri)) { FillRequestStream(requestWithoutRange); - long requestContentLength = 0; - if (requestWithoutRange.Content is not null) - { - requestContentLength = requestWithoutRange.Content.Headers.ContentLength.Value; - } + + long requestContentLength = requestWithoutRange.Content is null ? 0 : requestWithoutRange.Content.Headers.ContentLength.Value; string reqVerboseMsg = string.Format( CultureInfo.CurrentCulture, @@ -1413,11 +1408,7 @@ protected override void ProcessRecord() FillRequestStream(request); try { - long requestContentLength = 0; - if (request.Content is not null) - { - requestContentLength = request.Content.Headers.ContentLength.Value; - } + long requestContentLength = request.Content is null ? 0 : request.Content.Headers.ContentLength.Value; string reqVerboseMsg = string.Format( CultureInfo.CurrentCulture, @@ -1472,13 +1463,14 @@ protected override void ProcessRecord() StreamReader reader = null; try { - reader = new StreamReader(StreamHelper.GetResponseStream(response)); - // remove HTML tags making it easier to read + reader = new(StreamHelper.GetResponseStream(response)); + + // Remove HTML tags making it easier to read detailMsg = System.Text.RegularExpressions.Regex.Replace(reader.ReadToEnd(), "<[^>]*>", string.Empty); } - catch (Exception) + catch { - // catch all + // Catch all } finally { @@ -1551,7 +1543,7 @@ protected override void ProcessRecord() } /// - /// Implementing ^C, after start the BeginGetResponse. + /// To implement ^C. /// protected override void StopProcessing() => _cancelToken?.Cancel(); From b7e2913f6f758eea66a94ff3179dd1881ba45e10 Mon Sep 17 00:00:00 2001 From: Armaan Mcleod Date: Wed, 8 Feb 2023 23:48:04 +1100 Subject: [PATCH 343/779] Add `-NoHeader` parameter to `ConvertTo-Csv` and `Export-Csv` cmdlets (#19108) --- .../commands/utility/CsvCommands.cs | 28 +++++++++++++------ .../ConvertTo-Csv.Tests.ps1 | 5 ++++ .../Export-Csv.Tests.ps1 | 15 ++++++++++ 3 files changed, 39 insertions(+), 9 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs index a447a8983bb..2434ad836f3 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs @@ -72,6 +72,12 @@ public abstract class BaseCsvWritingCommand : PSCmdlet [Alias("UQ")] public QuoteKind UseQuotes { get; set; } = QuoteKind.Always; + /// + /// Gets or sets property that writes csv file with no headers. + /// + [Parameter] + public SwitchParameter NoHeader { get; set; } + #endregion Command Line Parameters /// @@ -301,7 +307,7 @@ protected override void ProcessRecord() } // write headers (row1: typename + row2: column names) - if (!_isActuallyAppending) + if (!_isActuallyAppending && !NoHeader.IsPresent) { if (NoTypeInformation == false) { @@ -727,16 +733,20 @@ protected override void ProcessRecord() if (_propertyNames == null) { _propertyNames = ExportCsvHelper.BuildPropertyNames(InputObject, _propertyNames); - if (NoTypeInformation == false) - { - WriteCsvLine(ExportCsvHelper.GetTypeString(InputObject)); - } - // Write property information - string properties = _helper.ConvertPropertyNamesCSV(_propertyNames); - if (!properties.Equals(string.Empty)) + if (!NoHeader.IsPresent) { - WriteCsvLine(properties); + if (NoTypeInformation == false) + { + WriteCsvLine(ExportCsvHelper.GetTypeString(InputObject)); + } + + // Write property information + string properties = _helper.ConvertPropertyNamesCSV(_propertyNames); + if (!properties.Equals(string.Empty)) + { + WriteCsvLine(properties); + } } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/ConvertTo-Csv.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/ConvertTo-Csv.Tests.ps1 index 129da4a9fde..0d484260813 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/ConvertTo-Csv.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/ConvertTo-Csv.Tests.ps1 @@ -91,6 +91,11 @@ Describe "ConvertTo-Csv" -Tags "CI" { $result | Should -Not -Match ([regex]::Escape('#TYPE')) } + It "Does not include headers with -NoHeader" { + $result = $testObject | ConvertTo-Csv -NoHeader + $result | Should -BeExactly '"Hello","World"' + } + It "Does not support -UseQuotes and -QuoteFields at the same time" { { $testObject | ConvertTo-Csv -UseQuotes Always -QuoteFields "TestFieldName" } | Should -Throw -ErrorId "CannotSpecifyQuoteFieldsAndUseQuotes,Microsoft.PowerShell.Commands.ConvertToCsvCommand" diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Export-Csv.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Export-Csv.Tests.ps1 index 962576f824e..67234f24c58 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Export-Csv.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Export-Csv.Tests.ps1 @@ -68,6 +68,21 @@ Describe "Export-Csv" -Tags "CI" { $results[0] | Should -Not -Match ([regex]::Escape("#TYPE")) } + It "Does not include headers with -NoHeader when exported and can imported with headers" { + $P1 | Export-Csv -Path $testCsv -NoHeader + $results = Get-Content -Path $testCsv + $results | Should -BeExactly '"first"' + $results = Import-Csv -Path $testCsv -Header "P1" + $results[0].P1 | Should -BeExactly "first" + } + + It "Does not include headers when imported with headers and exported using -NoHeader" { + $P1 | Export-Csv -Path $testCsv + (Import-Csv -Path $testCsv) | Export-Csv -Path $testCsv -NoHeader + $results = Get-Content -Path $testCsv + $results | Should -BeExactly '"first"' + } + It "Includes type information when -IncludeTypeInformation is supplied" { $testObject | Export-Csv -Path $testCsv -IncludeTypeInformation $results = Get-Content -Path $testCsv From 4756506d22bb84a71176a1962984d557ad37fd4a Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Wed, 8 Feb 2023 09:54:08 -0800 Subject: [PATCH 344/779] Fix error formatting to remove the unneeded leading newline for concise view (#19080) --- .../DefaultFormatters/PowerShellCore_format_ps1xml.cs | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs index c490f9e7a64..6ab8b8f2150 100644 --- a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs +++ b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs @@ -1284,7 +1284,6 @@ function Get-ConciseViewPositionMessage { return ""${errorColor}$($err.Exception.Message)${resetcolor}"" } - $myinv = $err.InvocationInfo if ($ErrorView -eq 'DetailedView') { $message = Get-Error | Out-String return ""${errorColor}${message}${resetcolor}"" @@ -1301,10 +1300,9 @@ function Get-ConciseViewPositionMessage { } elseif ($myinv -and ($myinv.MyCommand -or ($err.CategoryInfo.Category -ne 'ParserError'))) { $posmsg = $myinv.PositionMessage - } - - if ($posmsg -ne '') { - $posmsg = $newline + $posmsg + if ($posmsg -ne '') { + $posmsg = $newline + $posmsg + } } if ($err.PSMessageDetails) { From ef0af95845928c1dbab8be7de1e7390c53ce2ac6 Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Wed, 8 Feb 2023 10:18:32 -0800 Subject: [PATCH 345/779] Make the exception error in PowerShell able to associate with the right history entry (#19095) --- .../engine/AutomationEngine.cs | 16 ++- .../engine/lang/parserutils.cs | 16 +++ .../engine/runtime/Operations/MiscOps.cs | 5 +- .../utils/ParserException.cs | 4 +- .../Scripting/ErrorHistoryId.Tests.ps1 | 110 ++++++++++++++++++ 5 files changed, 144 insertions(+), 7 deletions(-) create mode 100644 test/powershell/Language/Scripting/ErrorHistoryId.Tests.ps1 diff --git a/src/System.Management.Automation/engine/AutomationEngine.cs b/src/System.Management.Automation/engine/AutomationEngine.cs index 61952f7739f..cc1ca2f5ad0 100644 --- a/src/System.Management.Automation/engine/AutomationEngine.cs +++ b/src/System.Management.Automation/engine/AutomationEngine.cs @@ -105,12 +105,22 @@ internal ScriptBlock ParseScriptBlock(string script, string fileName, bool addTo if (errors.Length > 0) { - if (errors[0].IncompleteInput) + ParseException ex = errors[0].IncompleteInput + ? new IncompleteParseException(errors[0].Message, errors[0].ErrorId) + : new ParseException(errors); + + if (addToHistory) { - throw new IncompleteParseException(errors[0].Message, errors[0].ErrorId); + // Try associating the parsing error with the history item if we can. + InvocationInfo invInfo = ex.ErrorRecord.InvocationInfo; + LocalRunspace localRunspace = Context.CurrentRunspace as LocalRunspace; + if (invInfo is not null && localRunspace?.History is not null) + { + invInfo.HistoryId = localRunspace.History.GetNextHistoryId(); + } } - throw new ParseException(errors); + throw ex; } return new ScriptBlock(ast, isFilter: false); diff --git a/src/System.Management.Automation/engine/lang/parserutils.cs b/src/System.Management.Automation/engine/lang/parserutils.cs index f159e72be43..e9970684810 100644 --- a/src/System.Management.Automation/engine/lang/parserutils.cs +++ b/src/System.Management.Automation/engine/lang/parserutils.cs @@ -1973,6 +1973,22 @@ internal static void UpdateExceptionErrorRecordPosition(Exception exception, ISc } } } + + internal static void UpdateExceptionErrorRecordHistoryId(RuntimeException exception, ExecutionContext context) + { + InvocationInfo invInfo = exception.ErrorRecord.InvocationInfo; + if (invInfo is not { HistoryId: -1 }) + { + return; + } + + if (context?.CurrentCommandProcessor is null) + { + return; + } + + invInfo.HistoryId = context.CurrentCommandProcessor.Command.MyInvocation.HistoryId; + } } #endregion InterpreterError diff --git a/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs b/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs index e6efdace4c5..6e67925ddb7 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs @@ -1266,7 +1266,7 @@ internal static void DefineFunction(ExecutionContext context, } catch (Exception exception) { - if (!(exception is RuntimeException rte)) + if (exception is not RuntimeException rte) { throw ExceptionHandlingOps.ConvertToRuntimeException(exception, functionDefinitionAst.Extent); } @@ -1623,6 +1623,9 @@ internal static void CheckActionPreference(FunctionContext funcContext, Exceptio InterpreterError.UpdateExceptionErrorRecordPosition(rte, funcContext.CurrentPosition); } + // Update the history id if needed to associate the exception with the right history item. + InterpreterError.UpdateExceptionErrorRecordHistoryId(rte, funcContext._executionContext); + var context = funcContext._executionContext; var outputPipe = funcContext._outputPipe; diff --git a/src/System.Management.Automation/utils/ParserException.cs b/src/System.Management.Automation/utils/ParserException.cs index b7056108218..9087c374b69 100644 --- a/src/System.Management.Automation/utils/ParserException.cs +++ b/src/System.Management.Automation/utils/ParserException.cs @@ -127,9 +127,7 @@ public ParseException(string message, /// Initializes a new instance of the ParseException class with a collection of error messages. /// /// The collection of error messages. - [SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", - Justification = "ErrorRecord is not overridden in classes deriving from ParseException")] - public ParseException(Language.ParseError[] errors) + public ParseException(ParseError[] errors) { ArgumentNullException.ThrowIfNull(errors); diff --git a/test/powershell/Language/Scripting/ErrorHistoryId.Tests.ps1 b/test/powershell/Language/Scripting/ErrorHistoryId.Tests.ps1 new file mode 100644 index 00000000000..3d467b66c1d --- /dev/null +++ b/test/powershell/Language/Scripting/ErrorHistoryId.Tests.ps1 @@ -0,0 +1,110 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +Describe "Error HistoryId Tests" -Tags "CI" { + + BeforeAll { + $setting = [System.Management.Automation.PSInvocationSettings]::New() + $setting.AddToHistory = $true + + function RunCommand($ps, $command) { + $ps.Commands.Clear() + $ps.AddScript($command).Invoke($null, $setting) + } + + $funcBarUseWriteErrorApi = @' +function bar { + [CmdletBinding()] + param() + + $er = [System.Management.Automation.ErrorRecord]::new( + [System.ArgumentException]::new(), + 'PSCmdlet.WriteError', + [System.Management.Automation.ErrorCategory]::InvalidOperation, + $null) + $PSCmdlet.WriteError($er) +} +'@ + $funcBarThrowTermError = @' +function bar { + [CmdletBinding()] + param() + + $er = [System.Management.Automation.ErrorRecord]::new( + [System.ArgumentException]::new(), + 'PSCmdlet.ThrowTerminatingError', + [System.Management.Automation.ErrorCategory]::InvalidOperation, + $null) + $PSCmdlet.ThrowTerminatingError($er) +} +'@ + } + + BeforeEach { + $ps = [PowerShell]::Create("NewRunspace") + } + + AfterEach { + $ps.Dispose() + } + + It "Error from has the right history Id" -TestCases @( + @{ caption = "'throw' in global scope"; cmd1 = "1+1"; cmd2 = "throw 'abc'" } + @{ caption = "'throw' in function"; cmd1 = "function bar { throw 'abc' }"; cmd2 = "bar" } + ) { + param($cmd1, $cmd2) + + try { + ## 1st in history + $null = RunCommand $ps $cmd1 + ## 2nd in history + $null = RunCommand $ps $cmd2 + } catch { + ## ignore the exception + } + + $ps.HadErrors | Should -BeTrue + $err = RunCommand $ps '$Error[0]' + $err.FullyQualifiedErrorId | Should -BeExactly 'abc' + $err.InvocationInfo.HistoryId | Should -Be 2 + } + + It "Error from has the right history Id" -TestCases @( + @{ caption = "parameter binding"; cmd1 = "1+1"; cmd2 = "Get-Verb -abc"; errId = "NamedParameterNotFound,Microsoft.PowerShell.Commands.GetVerbCommand" } + @{ caption = "'1/0' in global scope"; cmd1 = "1+1"; cmd2 = "1/0"; errId = "RuntimeException" } + @{ caption = "'1/0' in function"; cmd1 = "function bar { 1/0 }"; cmd2 = "bar"; errId = "RuntimeException" } + @{ caption = "method exception in global scope"; cmd1 = "1+1"; cmd2 = "[System.IO.Path]::GetExtension()"; errId = "MethodCountCouldNotFindBest" } + @{ caption = "method exception in function"; cmd1 = "function bar { [System.IO.Path]::GetExtension() }"; cmd2 = "bar"; errId = "MethodCountCouldNotFindBest" } + @{ caption = "'Write-Error'"; cmd1 = "function bar { Write-Error 'abc' }"; cmd2 = "bar"; errId = "Microsoft.PowerShell.Commands.WriteErrorException,bar" } + @{ caption = "'PSCmdlet.WriteError'"; cmd1 = $funcBarUseWriteErrorApi; cmd2 = "bar"; errId = "PSCmdlet.WriteError,bar" } + @{ caption = "'PSCmdlet.ThrowTerminatingError'"; cmd1 = $funcBarThrowTermError; cmd2 = "bar"; errId = "PSCmdlet.ThrowTerminatingError,bar" } + ) { + param($cmd1, $cmd2, $errId) + + ## 1st in history + $null = RunCommand $ps $cmd1 + ## 2nd in history + $null = RunCommand $ps $cmd2 + + $ps.HadErrors | Should -BeTrue + $err = RunCommand $ps '$Error[0]' + $err.FullyQualifiedErrorId | Should -BeExactly $errId + $err.InvocationInfo.HistoryId | Should -Be 2 + } + + It "ParseError has the right history Id" { + try { + ## 1st in history + $null = RunCommand $ps '1+1' + ## 2nd in history + $null = RunCommand $ps 'for (int i = 2; i < 3; i++) { foreach {} }' + } catch { + ## ignore the exception + } + + $ps.HadErrors | Should -BeTrue + $err = RunCommand $ps '$Error[0]' + $err | Should -BeOfType 'System.Management.Automation.ParseException' + $err.ErrorRecord.InvocationInfo.HistoryId | Should -Be 2 + } +} From 359f5c35f1f4c8715da5203956858198e2b1ab98 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Thu, 9 Feb 2023 09:22:04 +0100 Subject: [PATCH 346/779] Improve Invoke-WebRequest xml and json errors format (#18837) --- .../Common/WebRequestPSCmdlet.Common.cs | 62 +++++++++++++++++-- .../WebCmdlets.Tests.ps1 | 29 +++++++++ 2 files changed, 87 insertions(+), 4 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index 38b4e645ec6..c231aeac5ab 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -16,6 +16,8 @@ using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Text; +using System.Text.Json; +using System.Text.Json.Nodes; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; @@ -1463,10 +1465,8 @@ protected override void ProcessRecord() StreamReader reader = null; try { - reader = new(StreamHelper.GetResponseStream(response)); - - // Remove HTML tags making it easier to read - detailMsg = System.Text.RegularExpressions.Regex.Replace(reader.ReadToEnd(), "<[^>]*>", string.Empty); + reader = new StreamReader(StreamHelper.GetResponseStream(response)); + detailMsg = FormatErrorMessage(reader.ReadToEnd(), contentType); } catch { @@ -1821,6 +1821,60 @@ private static StreamContent GetMultipartFileContent(object fieldName, FileInfo return result; } + + private static string FormatErrorMessage(string error, string contentType) + { + string formattedError = null; + + try + { + if (ContentHelper.IsXml(contentType)) + { + XmlDocument doc = new(); + doc.LoadXml(error); + + XmlWriterSettings settings = new XmlWriterSettings { + Indent = true, + NewLineOnAttributes = true, + OmitXmlDeclaration = true + }; + + if (doc.FirstChild is XmlDeclaration) + { + XmlDeclaration decl = doc.FirstChild as XmlDeclaration; + settings.Encoding = Encoding.GetEncoding(decl.Encoding); + } + + StringBuilder stringBuilder = new(); + using XmlWriter xmlWriter = XmlWriter.Create(stringBuilder, settings); + doc.Save(xmlWriter); + string xmlString = stringBuilder.ToString(); + + formattedError = Environment.NewLine + xmlString; + } + else if (ContentHelper.IsJson(contentType)) + { + JsonNode jsonNode = JsonNode.Parse(error); + JsonSerializerOptions options = new JsonSerializerOptions { WriteIndented = true }; + string jsonString = jsonNode.ToJsonString(options); + + formattedError = Environment.NewLine + jsonString; + } + } + catch + { + // Ignore errors + } + + if (string.IsNullOrEmpty(formattedError)) + { + // Remove HTML tags making it easier to read + formattedError = System.Text.RegularExpressions.Regex.Replace(error, "<[^>]*>", string.Empty); + } + + return formattedError; + } + #endregion Helper Methods } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 index 43363edb6eb..35262d8bf41 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 @@ -785,6 +785,35 @@ Describe "Invoke-WebRequest tests" -Tags "Feature", "RequireAdminOnWindows" { $result.Error.FullyQualifiedErrorId | Should -Be "WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand" } + It "Validate Invoke-WebRequest returns errors in exception" -TestCases @( + @{ type = "XML" + query = @{ + contenttype = 'application/xml' + body = '418I am a teapot!!!' + statuscode = 418 + responsephrase = "I am a teapot" + } + expectederror = $IsWindows ? "`r`n`r`n 418`r`n I am a teapot!!!`r`n" : "`n`n 418`n I am a teapot!!!`n" + } + + @{ type = "Json" + query = @{ + contenttype = 'application/json' + body = '{"error":{"code":"418", "message":"I am a teapot!!!"}}' + statuscode = 418 + responsephrase = "I am a teapot" + } + expectederror = $IsWindows ? "`r`n{`r`n `"error`": {`r`n `"code`": `"418`",`r`n `"message`": `"I am a teapot!!!`"`r`n }`r`n}" : "`n{`n `"error`": {`n `"code`": `"418`",`n `"message`": `"I am a teapot!!!`"`n }`n}" + } + ) { + param($query, $expectederror) + $uri = Get-WebListenerUrl -Test 'Response' -Query $query + $command = "Invoke-WebRequest -Uri '$uri'" + $result = ExecuteWebCommand -command $command + + $result.Error.ErrorDetails.Message | Should -Be $expectederror + } + It "Validate Invoke-WebRequest returns empty RelationLink property if there is no Link Header" { $uri = $uri = Get-WebListenerUrl -Test 'Get' $command = "Invoke-WebRequest -Uri '$uri'" From 0f1251ebdef2a54743be1506b4e02d269ac3346f Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Thu, 9 Feb 2023 09:38:24 +0100 Subject: [PATCH 347/779] Dispose previous response in Webcmdlets (#19117) --- .../utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index c231aeac5ab..bd4e762f5a9 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -1274,6 +1274,7 @@ internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestM // Continue to handle redirection using HttpRequestMessage redirectRequest = GetRequest(currentUri); + response.Dispose(); response = GetResponse(client, redirectRequest, handleRedirect); } @@ -1308,7 +1309,8 @@ internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestM WriteVerbose(reqVerboseMsg); - return GetResponse(client, requestWithoutRange, handleRedirect); + response.Dispose(); + response = GetResponse(client, requestWithoutRange, handleRedirect); } } @@ -1421,7 +1423,7 @@ protected override void ProcessRecord() WriteVerbose(reqVerboseMsg); - HttpResponseMessage response = GetResponse(client, request, handleRedirect); + using HttpResponseMessage response = GetResponse(client, request, handleRedirect); string contentType = ContentHelper.GetContentType(response); string respVerboseMsg = string.Format( From 1ee8df5fe14b8080318d01388f132dfbe1b7f162 Mon Sep 17 00:00:00 2001 From: Armaan Mcleod Date: Thu, 9 Feb 2023 21:08:10 +1100 Subject: [PATCH 348/779] Added minor readability and refactoring fixes to Process.cs (#19123) --- .../commands/management/Process.cs | 75 +++++++++++-------- 1 file changed, 45 insertions(+), 30 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs index 70596e263da..82eccff3652 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs @@ -21,8 +21,6 @@ using Microsoft.Management.Infrastructure; using Microsoft.PowerShell.Commands.Internal; using Microsoft.Win32.SafeHandles; -using DWORD = System.UInt32; -using FileNakedHandle = System.IntPtr; namespace Microsoft.PowerShell.Commands { @@ -519,14 +517,7 @@ public override Process[] InputObject [Parameter(ParameterSetName = NameWithUserNameParameterSet, Mandatory = true)] [Parameter(ParameterSetName = IdWithUserNameParameterSet, Mandatory = true)] [Parameter(ParameterSetName = InputObjectWithUserNameParameterSet, Mandatory = true)] - public SwitchParameter IncludeUserName - { - get { return _includeUserName; } - - set { _includeUserName = value; } - } - - private bool _includeUserName = false; + public SwitchParameter IncludeUserName { get; set; } /// /// To display the modules of a process. @@ -744,7 +735,10 @@ private static string RetrieveProcessUserName(Process process) try { int error; - if (!Win32Native.OpenProcessToken(process.Handle, TOKEN_QUERY, out processTokenHandler)) { return null; } + if (!Win32Native.OpenProcessToken(process.Handle, TOKEN_QUERY, out processTokenHandler)) + { + return null; + } // Set the default length to be 256, so it will be sufficient for most cases. int tokenInfoLength = 256; @@ -757,7 +751,10 @@ private static string RetrieveProcessUserName(Process process) Marshal.FreeHGlobal(tokenUserInfo); tokenUserInfo = Marshal.AllocHGlobal(tokenInfoLength); - if (!Win32Native.GetTokenInformation(processTokenHandler, Win32Native.TOKEN_INFORMATION_CLASS.TokenUser, tokenUserInfo, tokenInfoLength, out tokenInfoLength)) { return null; } + if (!Win32Native.GetTokenInformation(processTokenHandler, Win32Native.TOKEN_INFORMATION_CLASS.TokenUser, tokenUserInfo, tokenInfoLength, out tokenInfoLength)) + { + return null; + } } else { @@ -1165,7 +1162,10 @@ protected override void ProcessRecord() SafeGetProcessName(process), SafeGetProcessId(process)); - if (!ShouldProcess(targetString)) { continue; } + if (!ShouldProcess(targetString)) + { + continue; + } try { @@ -1323,7 +1323,10 @@ private bool IsProcessOwnedByCurrentUser(Process process) } finally { - if (ph != IntPtr.Zero) { Win32Native.CloseHandle(ph); } + if (ph != IntPtr.Zero) + { + Win32Native.CloseHandle(ph); + } } return false; @@ -1483,7 +1486,10 @@ protected override void ProcessRecord() SafeGetProcessName(process), SafeGetProcessId(process)); - if (!ShouldProcess(targetMessage)) { continue; } + if (!ShouldProcess(targetMessage)) + { + continue; + } // Sometimes Idle process has processid zero,so handle that because we cannot attach debugger to it. if (process.Id == 0) @@ -1498,7 +1504,10 @@ protected override void ProcessRecord() { // If the process has exited, we skip it. If the process is from a remote // machine, then we generate a non-terminating error. - if (process.HasExited) { continue; } + if (process.HasExited) + { + continue; + } } catch (NotSupportedException ex) { @@ -1549,8 +1558,7 @@ private void AttachDebuggerToProcess(Process process) } catch (CimException e) { - string message = e.Message; - if (!string.IsNullOrEmpty(message)) { message = message.Trim(); } + string message = e.Message?.Trim(); var errorRecord = new ErrorRecord( new InvalidOperationException(StringUtil.Format(ProcessResources.DebuggerError, message)), @@ -1566,16 +1574,17 @@ private void AttachDebuggerToProcess(Process process) /// private static string MapReturnCodeToErrorMessage(int returnCode) { - string errorMessage = string.Empty; - switch (returnCode) + string errorMessage = returnCode switch { - case 2: errorMessage = ProcessResources.AttachDebuggerReturnCode2; break; - case 3: errorMessage = ProcessResources.AttachDebuggerReturnCode3; break; - case 8: errorMessage = ProcessResources.AttachDebuggerReturnCode8; break; - case 9: errorMessage = ProcessResources.AttachDebuggerReturnCode9; break; - case 21: errorMessage = ProcessResources.AttachDebuggerReturnCode21; break; - default: Diagnostics.Assert(false, "Unreachable code."); break; - } + 2 => ProcessResources.AttachDebuggerReturnCode2, + 3 => ProcessResources.AttachDebuggerReturnCode3, + 8 => ProcessResources.AttachDebuggerReturnCode8, + 9 => ProcessResources.AttachDebuggerReturnCode9, + 21 => ProcessResources.AttachDebuggerReturnCode21, + _ => string.Empty + }; + + Diagnostics.Assert(!string.IsNullOrEmpty(errorMessage), "Error message should not be null or empty."); return errorMessage; } @@ -2006,13 +2015,19 @@ protected override void BeginProcessing() } else if (ParameterSetName.Equals("UseShellExecute")) { - if (Verb != null) { startInfo.Verb = Verb; } + if (Verb != null) + { + startInfo.Verb = Verb; + } startInfo.WindowStyle = _windowstyle; } string targetMessage = StringUtil.Format(ProcessResources.StartProcessTarget, startInfo.FileName, startInfo.Arguments.Trim()); - if (!ShouldProcess(targetMessage)) { return; } + if (!ShouldProcess(targetMessage)) + { + return; + } Process process = Start(startInfo); @@ -2971,7 +2986,7 @@ public override void GetObjectData( base.GetObjectData(info, context); ArgumentNullException.ThrowIfNull(info); - + info.AddValue("ProcessName", _processName); } #endregion Serialization From c4d688d6e337f542fa3df4ca167d0b890208e0d3 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Thu, 9 Feb 2023 12:58:55 +0100 Subject: [PATCH 349/779] Cleanup WebCmdlets comments (#19124) --- .../BasicHtmlWebResponseObject.Common.cs | 9 ++--- .../Common/InvokeRestMethodCommand.Common.cs | 5 ++- .../Common/WebRequestPSCmdlet.Common.cs | 37 +++++++++---------- .../Common/WebResponseObject.Common.cs | 3 +- .../InvokeWebRequestCommand.CoreClr.cs | 2 +- .../utility/WebCmdlet/CoreCLR/WebProxy.cs | 7 +--- .../commands/utility/WebCmdlet/FormObject.cs | 11 +++--- 7 files changed, 34 insertions(+), 40 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/BasicHtmlWebResponseObject.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/BasicHtmlWebResponseObject.Common.cs index de624276a2a..86d4c4dfbba 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/BasicHtmlWebResponseObject.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/BasicHtmlWebResponseObject.Common.cs @@ -164,8 +164,7 @@ protected void InitializeContent() string contentType = ContentHelper.GetContentType(BaseResponse); if (ContentHelper.IsText(contentType)) { - Encoding encoding = null; - // fill the Content buffer + // Fill the Content buffer string characterSet = WebResponseHelper.GetCharacterSet(BaseResponse); if (string.IsNullOrEmpty(characterSet) && ContentHelper.IsJson(contentType)) @@ -173,12 +172,12 @@ protected void InitializeContent() characterSet = Encoding.UTF8.HeaderName; } - this.Content = StreamHelper.DecodeStream(RawContentStream, characterSet, out encoding); - this.Encoding = encoding; + Content = StreamHelper.DecodeStream(RawContentStream, characterSet, out Encoding encoding); + Encoding = encoding; } else { - this.Content = string.Empty; + Content = string.Empty; } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs index 242f380d94e..a27e4e70008 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs @@ -232,7 +232,10 @@ private bool TryProcessFeedStream(Stream responseStream) } } } - catch (XmlException) { } + catch (XmlException) + { + // Catch XmlException + } finally { responseStream.Seek(0, SeekOrigin.Begin); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index bd4e762f5a9..7779295c84d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -270,7 +270,7 @@ public abstract partial class WebRequestPSCmdlet : PSCmdlet /// This property overrides compatibility with web requests on Windows. /// On FullCLR (WebRequest), authorization headers are stripped during redirect. /// CoreCLR (HTTPClient) does not have this behavior so web requests that work on - /// PowerShell/FullCLR can fail with PowerShell/CoreCLR. To provide compatibility, + /// PowerShell/FullCLR can fail with PowerShell/CoreCLR. To provide compatibility, /// we'll detect requests with an Authorization header and automatically strip /// the header when the first redirect occurs. This switch turns off this logic for /// edge cases where the authorization header needs to be preserved across redirects. @@ -576,24 +576,24 @@ internal virtual void ValidateParameters() internal virtual void PrepareSession() { - // make sure we have a valid WebRequestSession object to work with + // Make sure we have a valid WebRequestSession object to work with WebSession ??= new WebRequestSession(); if (SessionVariable is not null) { - // save the session back to the PS environment if requested + // Save the session back to the PS environment if requested PSVariableIntrinsics vi = SessionState.PSVariable; vi.Set(SessionVariable, WebSession); } - // handle credentials + // Handle credentials if (Credential is not null && Authentication == WebAuthenticationType.None) { - // get the relevant NetworkCredential + // Get the relevant NetworkCredential NetworkCredential netCred = Credential.GetNetworkCredential(); WebSession.Credentials = netCred; - // supplying a credential overrides the UseDefaultCredentials setting + // Supplying a credential overrides the UseDefaultCredentials setting WebSession.UseDefaultCredentials = false; } else if ((Credential is not null || Token is not null) && Authentication != WebAuthenticationType.None) @@ -629,10 +629,10 @@ internal virtual void PrepareSession() WebSession.AddCertificate(Certificate); } - // handle the user agent + // Handle the user agent if (UserAgent is not null) { - // store the UserAgent string + // Store the UserAgent string WebSession.UserAgent = UserAgent; } @@ -659,7 +659,7 @@ internal virtual void PrepareSession() WebSession.MaximumRedirection = MaximumRedirection; } - // store the other supplied headers + // Store the other supplied headers if (Headers is not null) { foreach (string key in Headers.Keys) @@ -725,7 +725,8 @@ private Uri PrepareUri(Uri uri) } uri = uriBuilder.Uri; - // set body to null to prevent later FillRequestStream + + // Set body to null to prevent later FillRequestStream Body = null; } @@ -913,18 +914,16 @@ public abstract partial class WebRequestPSCmdlet : PSCmdlet #region Virtual Methods - // NOTE: Only pass true for handleRedirect if the original request has an authorization header - // and PreserveAuthorizationOnRedirect is NOT set. internal virtual HttpClient GetHttpClient(bool handleRedirect) { HttpClientHandler handler = new(); handler.CookieContainer = WebSession.Cookies; handler.AutomaticDecompression = DecompressionMethods.All; - // set the credentials used by this request + // Set the credentials used by this request if (WebSession.UseDefaultCredentials) { - // the UseDefaultCredentials flag overrides other supplied credentials + // The UseDefaultCredentials flag overrides other supplied credentials handler.UseDefaultCredentials = true; } else if (WebSession.Credentials is not null) @@ -977,7 +976,7 @@ internal virtual HttpRequestMessage GetRequest(Uri uri) Uri requestUri = PrepareUri(uri); HttpMethod httpMethod = string.IsNullOrEmpty(CustomMethod) ? GetHttpMethod(Method) : new HttpMethod(CustomMethod); - // create the base WebRequest object + // Create the base WebRequest object var request = new HttpRequestMessage(httpMethod, requestUri); if (HttpVersion is not null) @@ -985,7 +984,7 @@ internal virtual HttpRequestMessage GetRequest(Uri uri) request.Version = HttpVersion; } - // pull in session data + // Pull in session data if (WebSession.Headers.Count > 0) { WebSession.ContentHeaders.Clear(); @@ -1072,13 +1071,11 @@ internal virtual void FillRequestStream(HttpRequestMessage request) { ArgumentNullException.ThrowIfNull(request); - // set the content type + // Set the request content type if (ContentType is not null) { WebSession.ContentHeaders[HttpKnownHeaderNames.ContentType] = ContentType; - // request } - // ContentType is null else if (request.Method == HttpMethod.Post) { // Win8:545310 Invoke-WebRequest does not properly set MIME type for POST @@ -1499,7 +1496,7 @@ protected override void ProcessRecord() // Errors with redirection counts of greater than 0 are handled automatically by .NET, but are // impossible to detect programmatically when we hit this limit. By handling this ourselves // (and still writing out the result), users can debug actual HTTP redirect problems. - if (WebSession.MaximumRedirection == 0 && IsRedirectCode(response.StatusCode)) // Indicate "HttpClientHandler.AllowAutoRedirect is false" + if (WebSession.MaximumRedirection == 0 && IsRedirectCode(response.StatusCode)) { ErrorRecord er = new(new InvalidOperationException(), "MaximumRedirectExceeded", ErrorCategory.InvalidOperation, request); er.ErrorDetails = new ErrorDetails(WebCmdletStrings.MaximumRedirectionCountExceeded); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebResponseObject.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebResponseObject.Common.cs index 8db9064022c..5a55ccc2e73 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebResponseObject.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebResponseObject.Common.cs @@ -150,7 +150,8 @@ private void SetResponse(HttpResponseMessage response, Stream contentStream) int initialCapacity = (int)Math.Min(contentLength, StreamHelper.DefaultReadBuffer); RawContentStream = new WebResponseContentMemoryStream(st, initialCapacity, cmdlet: null, response.Content.Headers.ContentLength.GetValueOrDefault()); } - // set the position of the content stream to the beginning + + // Set the position of the content stream to the beginning RawContentStream.Position = 0; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/InvokeWebRequestCommand.CoreClr.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/InvokeWebRequestCommand.CoreClr.cs index d4490019772..e101bcc65b7 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/InvokeWebRequestCommand.CoreClr.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/InvokeWebRequestCommand.CoreClr.cs @@ -23,7 +23,7 @@ public class InvokeWebRequestCommand : WebRequestPSCmdlet /// public InvokeWebRequestCommand() : base() { - this._parseRelLink = true; + _parseRelLink = true; } /// diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebProxy.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebProxy.cs index 29e9da1f28d..0f46827bd63 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebProxy.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebProxy.cs @@ -38,12 +38,7 @@ public Uri GetProxy(Uri destination) { ArgumentNullException.ThrowIfNull(destination); - if (destination.IsLoopback) - { - return destination; - } - - return _proxyAddress; + return destination.IsLoopback ? destination : _proxyAddress; } public bool IsBypassed(Uri host) => host.IsLoopback; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObject.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObject.cs index b8f7d252711..b496a120329 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObject.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObject.cs @@ -11,22 +11,22 @@ namespace Microsoft.PowerShell.Commands public class FormObject { /// - /// Gets or private sets the Id property. + /// Gets the Id property. /// public string Id { get; } /// - /// Gets or private sets the Method property. + /// Gets the Method property. /// public string Method { get; } /// - /// Gets or private sets the Action property. + /// Gets the Action property. /// public string Action { get; } /// - /// Gets or private sets the Fields property. + /// Gets the Fields property. /// public Dictionary Fields { get; } @@ -46,8 +46,7 @@ public FormObject(string id, string method, string action) internal void AddField(string key, string value) { - string test; - if (key != null && !Fields.TryGetValue(key, out test)) + if (key is not null && !Fields.TryGetValue(key, out string test)) { Fields[key] = value; } From f13974840b6e2343c28596d89ac9f985d008400f Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Thu, 9 Feb 2023 12:15:31 -0800 Subject: [PATCH 350/779] Allow cross compiling windows (#19119) * Allow cross compiling windows * fix exp feature generation * make sure all platforms have OSArchitecture --- build.psm1 | 45 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 44 insertions(+), 1 deletion(-) diff --git a/build.psm1 b/build.psm1 index 3b808c562cf..4e1fd0f3f9a 100644 --- a/build.psm1 +++ b/build.psm1 @@ -159,6 +159,7 @@ function Get-EnvironmentInformation } if ($environment.IsLinux) { + $environment += @{ 'OSArchitecture' = [System.Runtime.InteropServices.RuntimeInformation]::ProcessArchitecture } $LinuxInfo = Get-Content /etc/os-release -Raw | ConvertFrom-StringData $lsb_release = Get-Command lsb_release -Type Application -ErrorAction Ignore | Select-Object -First 1 if ($lsb_release) { @@ -455,6 +456,9 @@ Fix steps: if ($Options.Runtime -like 'win*' -or ($Options.Runtime -like 'fxdependent*' -and $environment.IsWindows)) { $Arguments += "/property:IsWindows=true" + if(!$environment.IsWindows) { + $Arguments += "/property:EnableWindowsTargeting=true" + } } else { $Arguments += "/property:IsWindows=false" @@ -648,7 +652,7 @@ Fix steps: (Test-IsPreview $psVersion) -and -not (Test-IsReleaseCandidate $psVersion) ) { - if (-not $env:PS_RELEASE_BUILD -and -not $Runtime.Contains("arm") -and -not ($Runtime -like 'fxdependent*')) { + if ((Test-ShouldGenerateExperimentalFeatures -Runtime $Options.Runtime)) { Write-Verbose "Build experimental feature list by running 'Get-ExperimentalFeature'" -Verbose $json = & $publishPath\pwsh -noprofile -command { $expFeatures = Get-ExperimentalFeature | ForEach-Object -MemberName Name @@ -697,6 +701,45 @@ Fix steps: } } +function Test-ShouldGenerateExperimentalFeatures +{ + param( + [Parameter(Mandatory)] + $Runtime + ) + + if ($env:PS_RELEASE_BUILD) { + return $false + } + + if ($Runtime -like 'fxdependent*') { + return $false + } + + $runtimePattern = 'unknown-' + if ($environment.IsWindows) { + $runtimePattern = '^win.*-' + } + + if ($environment.IsMacOS) { + $runtimePattern = '^osx.*-' + } + + if ($environment.IsLinux) { + $runtimePattern = '^linux.*-' + } + + $runtimePattern += $environment.OSArchitecture.ToString() + Write-Verbose "runtime pattern check: $Runtime -match $runtimePattern" -Verbose + if ($Runtime -match $runtimePattern) { + Write-Verbose "Generating experimental feature list" -Verbose + return $true + } + + Write-Verbose "Skipping generating experimental feature list" -Verbose + return $false +} + function Restore-PSPackage { [CmdletBinding()] From 9b228dcc62b318e4c96e32fa08b963d39ad74240 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Fri, 10 Feb 2023 08:27:56 +0100 Subject: [PATCH 351/779] Merge partials in WebRequestPSCmdlet.Common.cs (#19126) --- .../Common/WebRequestPSCmdlet.Common.cs | 851 +++++++++--------- 1 file changed, 420 insertions(+), 431 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index 7779295c84d..a9c5934ecd3 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -88,8 +88,47 @@ public enum WebSslProtocol /// /// Base class for Invoke-RestMethod and Invoke-WebRequest commands. /// - public abstract partial class WebRequestPSCmdlet : PSCmdlet + public abstract class WebRequestPSCmdlet : PSCmdlet { + #region Fields + + /// + /// Cancellation token source. + /// + internal CancellationTokenSource _cancelToken = null; + + /// + /// Automatically follow Rel Links. + /// + internal bool _followRelLink = false; + + /// + /// Maximum number of Rel Links to follow. + /// + internal int _maximumFollowRelLink = int.MaxValue; + + /// + /// Parse Rel Links. + /// + internal bool _parseRelLink = false; + + /// + /// Automatically follow Rel Links. + /// + internal Dictionary _relationLink = null; + + /// + /// The current size of the local file being resumed. + /// + private long _resumeFileSize = 0; + + /// + /// The remote endpoint returned a 206 status code indicating successful resume. + /// + private bool _resumeSuccess = false; + + #endregion Fields + #region Virtual Properties #region URI @@ -425,6 +464,213 @@ public virtual string CustomMethod #endregion Virtual Properties + #region Helper Properties + + internal string QualifiedOutFile => QualifyFilePath(OutFile); + + internal bool ShouldCheckHttpStatus => !SkipHttpErrorCheck; + + /// + /// Determines whether writing to a file should Resume and append rather than overwrite. + /// + internal bool ShouldResume => Resume.IsPresent && _resumeSuccess; + + internal bool ShouldSaveToOutFile => !string.IsNullOrEmpty(OutFile); + + internal bool ShouldWriteToPipeline => !ShouldSaveToOutFile || PassThru; + + #endregion Helper Properties + + #region Abstract Methods + + /// + /// Read the supplied WebResponse object and push the resulting output into the pipeline. + /// + /// Instance of a WebResponse object to be processed. + internal abstract void ProcessResponse(HttpResponseMessage response); + + #endregion Abstract Methods + + #region Overrides + + /// + /// The main execution method for cmdlets derived from WebRequestPSCmdlet. + /// + protected override void ProcessRecord() + { + try + { + // Set cmdlet context for write progress + ValidateParameters(); + PrepareSession(); + + // If the request contains an authorization header and PreserveAuthorizationOnRedirect is not set, + // it needs to be stripped on the first redirect. + bool keepAuthorizationOnRedirect = PreserveAuthorizationOnRedirect.IsPresent + && WebSession.Headers.ContainsKey(HttpKnownHeaderNames.Authorization); + + bool handleRedirect = keepAuthorizationOnRedirect || AllowInsecureRedirect; + + using (HttpClient client = GetHttpClient(handleRedirect)) + { + int followedRelLink = 0; + Uri uri = Uri; + do + { + if (followedRelLink > 0) + { + string linkVerboseMsg = string.Format( + CultureInfo.CurrentCulture, + WebCmdletStrings.FollowingRelLinkVerboseMsg, + uri.AbsoluteUri); + + WriteVerbose(linkVerboseMsg); + } + + using (HttpRequestMessage request = GetRequest(uri)) + { + FillRequestStream(request); + try + { + long requestContentLength = request.Content is null ? 0 : request.Content.Headers.ContentLength.Value; + + string reqVerboseMsg = string.Format( + CultureInfo.CurrentCulture, + WebCmdletStrings.WebMethodInvocationVerboseMsg, + request.Version, + request.Method, + requestContentLength); + + WriteVerbose(reqVerboseMsg); + + using HttpResponseMessage response = GetResponse(client, request, handleRedirect); + + string contentType = ContentHelper.GetContentType(response); + string respVerboseMsg = string.Format( + CultureInfo.CurrentCulture, + WebCmdletStrings.WebResponseVerboseMsg, + response.Content.Headers.ContentLength, + contentType); + + WriteVerbose(respVerboseMsg); + + bool _isSuccess = response.IsSuccessStatusCode; + + // Check if the Resume range was not satisfiable because the file already completed downloading. + // This happens when the local file is the same size as the remote file. + if (Resume.IsPresent + && response.StatusCode == HttpStatusCode.RequestedRangeNotSatisfiable + && response.Content.Headers.ContentRange.HasLength + && response.Content.Headers.ContentRange.Length == _resumeFileSize) + { + _isSuccess = true; + WriteVerbose(string.Format( + CultureInfo.CurrentCulture, + WebCmdletStrings.OutFileWritingSkipped, + OutFile)); + + // Disable writing to the OutFile. + OutFile = null; + } + + if (ShouldCheckHttpStatus && !_isSuccess) + { + string message = string.Format( + CultureInfo.CurrentCulture, + WebCmdletStrings.ResponseStatusCodeFailure, + (int)response.StatusCode, + response.ReasonPhrase); + + HttpResponseException httpEx = new(message, response); + ErrorRecord er = new(httpEx, "WebCmdletWebResponseException", ErrorCategory.InvalidOperation, request); + string detailMsg = string.Empty; + StreamReader reader = null; + try + { + reader = new StreamReader(StreamHelper.GetResponseStream(response)); + detailMsg = FormatErrorMessage(reader.ReadToEnd(), contentType); + } + catch + { + // Catch all + } + finally + { + reader?.Dispose(); + } + + if (!string.IsNullOrEmpty(detailMsg)) + { + er.ErrorDetails = new ErrorDetails(detailMsg); + } + + ThrowTerminatingError(er); + } + + if (_parseRelLink || _followRelLink) + { + ParseLinkHeader(response, uri); + } + + ProcessResponse(response); + UpdateSession(response); + + // If we hit our maximum redirection count, generate an error. + // Errors with redirection counts of greater than 0 are handled automatically by .NET, but are + // impossible to detect programmatically when we hit this limit. By handling this ourselves + // (and still writing out the result), users can debug actual HTTP redirect problems. + if (WebSession.MaximumRedirection == 0 && IsRedirectCode(response.StatusCode)) + { + ErrorRecord er = new(new InvalidOperationException(), "MaximumRedirectExceeded", ErrorCategory.InvalidOperation, request); + er.ErrorDetails = new ErrorDetails(WebCmdletStrings.MaximumRedirectionCountExceeded); + WriteError(er); + } + } + catch (HttpRequestException ex) + { + ErrorRecord er = new(ex, "WebCmdletWebResponseException", ErrorCategory.InvalidOperation, request); + if (ex.InnerException is not null) + { + er.ErrorDetails = new ErrorDetails(ex.InnerException.Message); + } + + ThrowTerminatingError(er); + } + + if (_followRelLink) + { + if (!_relationLink.ContainsKey("next")) + { + return; + } + + uri = new Uri(_relationLink["next"]); + followedRelLink++; + } + } + } + while (_followRelLink && (followedRelLink < _maximumFollowRelLink)); + } + } + catch (CryptographicException ex) + { + ErrorRecord er = new(ex, "WebCmdletCertificateException", ErrorCategory.SecurityError, null); + ThrowTerminatingError(er); + } + catch (NotSupportedException ex) + { + ErrorRecord er = new(ex, "WebCmdletIEDomNotSupportedException", ErrorCategory.NotImplemented, null); + ThrowTerminatingError(er); + } + } + + /// + /// To implement ^C. + /// + protected override void StopProcessing() => _cancelToken?.Cancel(); + + #endregion Overrides + #region Virtual Methods internal virtual void ValidateParameters() @@ -684,241 +930,12 @@ internal virtual void PrepareSession() WebSession.RetryIntervalInSeconds = RetryIntervalSec; } } - - #endregion Virtual Methods - - #region Helper Properties - - internal string QualifiedOutFile => QualifyFilePath(OutFile); - - internal bool ShouldSaveToOutFile => !string.IsNullOrEmpty(OutFile); - - internal bool ShouldWriteToPipeline => !ShouldSaveToOutFile || PassThru; - - internal bool ShouldCheckHttpStatus => !SkipHttpErrorCheck; - - /// - /// Determines whether writing to a file should Resume and append rather than overwrite. - /// - internal bool ShouldResume => Resume.IsPresent && _resumeSuccess; - - #endregion Helper Properties - - #region Helper Methods - private Uri PrepareUri(Uri uri) - { - uri = CheckProtocol(uri); - - // Before creating the web request, - // preprocess Body if content is a dictionary and method is GET (set as query) - LanguagePrimitives.TryConvertTo(Body, out IDictionary bodyAsDictionary); - if (bodyAsDictionary is not null && (Method == WebRequestMethod.Default || Method == WebRequestMethod.Get || CustomMethod == "GET")) - { - UriBuilder uriBuilder = new(uri); - if (uriBuilder.Query is not null && uriBuilder.Query.Length > 1) - { - uriBuilder.Query = string.Concat(uriBuilder.Query.AsSpan(1), "&", FormatDictionary(bodyAsDictionary)); - } - else - { - uriBuilder.Query = FormatDictionary(bodyAsDictionary); - } - - uri = uriBuilder.Uri; - - // Set body to null to prevent later FillRequestStream - Body = null; - } - - return uri; - } - - private static Uri CheckProtocol(Uri uri) - { - ArgumentNullException.ThrowIfNull(uri); - - if (!uri.IsAbsoluteUri) - { - uri = new Uri("http://" + uri.OriginalString); - } - - return uri; - } - - private string QualifyFilePath(string path) - { - string resolvedFilePath = PathUtils.ResolveFilePath(filePath: path, command: this, isLiteralPath: true); - return resolvedFilePath; - } - - private static string FormatDictionary(IDictionary content) - { - ArgumentNullException.ThrowIfNull(content); - - StringBuilder bodyBuilder = new(); - foreach (string key in content.Keys) - { - if (bodyBuilder.Length > 0) - { - bodyBuilder.Append('&'); - } - - object value = content[key]; - - // URLEncode the key and value - string encodedKey = WebUtility.UrlEncode(key); - string encodedValue = string.Empty; - if (value is not null) - { - encodedValue = WebUtility.UrlEncode(value.ToString()); - } - - bodyBuilder.Append($"{encodedKey}={encodedValue}"); - } - - return bodyBuilder.ToString(); - } - - private ErrorRecord GetValidationError(string msg, string errorId) - { - var ex = new ValidationMetadataException(msg); - var error = new ErrorRecord(ex, errorId, ErrorCategory.InvalidArgument, this); - return error; - } - - private ErrorRecord GetValidationError(string msg, string errorId, params object[] args) - { - msg = string.Format(CultureInfo.InvariantCulture, msg, args); - var ex = new ValidationMetadataException(msg); - var error = new ErrorRecord(ex, errorId, ErrorCategory.InvalidArgument, this); - return error; - } - - private string GetBasicAuthorizationHeader() - { - var password = new NetworkCredential(null, Credential.Password).Password; - string unencoded = string.Create(CultureInfo.InvariantCulture, $"{Credential.UserName}:{password}"); - byte[] bytes = Encoding.UTF8.GetBytes(unencoded); - return string.Create(CultureInfo.InvariantCulture, $"Basic {Convert.ToBase64String(bytes)}"); - } - - private string GetBearerAuthorizationHeader() - { - return string.Create(CultureInfo.InvariantCulture, $"Bearer {new NetworkCredential(string.Empty, Token).Password}"); - } - - private void ProcessAuthentication() - { - if (Authentication == WebAuthenticationType.Basic) - { - WebSession.Headers["Authorization"] = GetBasicAuthorizationHeader(); - } - else if (Authentication == WebAuthenticationType.Bearer || Authentication == WebAuthenticationType.OAuth) - { - WebSession.Headers["Authorization"] = GetBearerAuthorizationHeader(); - } - else - { - Diagnostics.Assert(false, string.Create(CultureInfo.InvariantCulture, $"Unrecognized Authentication value: {Authentication}")); - } - } - - #endregion Helper Methods - } - - // TODO: Merge Partials - - /// - /// Exception class for webcmdlets to enable returning HTTP error response. - /// - public sealed class HttpResponseException : HttpRequestException - { - /// - /// Initializes a new instance of the class. - /// - /// Message for the exception. - /// Response from the HTTP server. - public HttpResponseException(string message, HttpResponseMessage response) : base(message, inner: null, response.StatusCode) - { - Response = response; - } - - /// - /// HTTP error response. - /// - public HttpResponseMessage Response { get; } - } - - /// - /// Base class for Invoke-RestMethod and Invoke-WebRequest commands. - /// - public abstract partial class WebRequestPSCmdlet : PSCmdlet - { - #region Abstract Methods - - /// - /// Read the supplied WebResponse object and push the resulting output into the pipeline. - /// - /// Instance of a WebResponse object to be processed. - internal abstract void ProcessResponse(HttpResponseMessage response); - - #endregion Abstract Methods - - /// - /// Cancellation token source. - /// - internal CancellationTokenSource _cancelToken = null; - - /// - /// Parse Rel Links. - /// - internal bool _parseRelLink = false; - - /// - /// Automatically follow Rel Links. - /// - internal bool _followRelLink = false; - - /// - /// Automatically follow Rel Links. - /// - internal Dictionary _relationLink = null; - - /// - /// Maximum number of Rel Links to follow. - /// - internal int _maximumFollowRelLink = int.MaxValue; - - /// - /// The remote endpoint returned a 206 status code indicating successful resume. - /// - private bool _resumeSuccess = false; - - /// - /// The current size of the local file being resumed. - /// - private long _resumeFileSize = 0; - - private static HttpMethod GetHttpMethod(WebRequestMethod method) => method switch - { - WebRequestMethod.Default or WebRequestMethod.Get => HttpMethod.Get, - WebRequestMethod.Delete => HttpMethod.Delete, - WebRequestMethod.Head => HttpMethod.Head, - WebRequestMethod.Patch => HttpMethod.Patch, - WebRequestMethod.Post => HttpMethod.Post, - WebRequestMethod.Put => HttpMethod.Put, - WebRequestMethod.Options => HttpMethod.Options, - WebRequestMethod.Trace => HttpMethod.Trace, - _ => new HttpMethod(method.ToString().ToUpperInvariant()) - }; - - #region Virtual Methods - - internal virtual HttpClient GetHttpClient(bool handleRedirect) - { - HttpClientHandler handler = new(); - handler.CookieContainer = WebSession.Cookies; - handler.AutomaticDecompression = DecompressionMethods.All; + + internal virtual HttpClient GetHttpClient(bool handleRedirect) + { + HttpClientHandler handler = new(); + handler.CookieContainer = WebSession.Cookies; + handler.AutomaticDecompression = DecompressionMethods.All; // Set the credentials used by this request if (WebSession.UseDefaultCredentials) @@ -1187,45 +1204,6 @@ internal virtual void FillRequestStream(HttpRequestMessage request) } } - // Returns true if the status code is one of the supported redirection codes. - private static bool IsRedirectCode(HttpStatusCode code) - { - int intCode = (int)code; - return - ( - (intCode >= 300 && intCode < 304) || - intCode == 307 || - intCode == 308 - ); - } - - // Returns true if the status code is a redirection code and the action requires switching from POST to GET on redirection. - // NOTE: Some of these status codes map to the same underlying value but spelling them out for completeness. - private static bool IsRedirectToGet(HttpStatusCode code) - { - return - ( - code == HttpStatusCode.Found || - code == HttpStatusCode.Moved || - code == HttpStatusCode.Redirect || - code == HttpStatusCode.RedirectMethod || - code == HttpStatusCode.SeeOther || - code == HttpStatusCode.Ambiguous || - code == HttpStatusCode.MultipleChoices - ); - } - - // Returns true if the status code shows a server or client error and MaximumRetryCount > 0 - private bool ShouldRetry(HttpStatusCode code) - { - int intCode = (int)code; - - return - ( - (intCode == 304 || (intCode >= 400 && intCode <= 599)) && WebSession.MaximumRetryCount > 0 - ); - } - internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestMessage request, bool handleRedirect) { ArgumentNullException.ThrowIfNull(client); @@ -1368,188 +1346,125 @@ internal virtual void UpdateSession(HttpResponseMessage response) #endregion Virtual Methods - #region Overrides - - /// - /// The main execution method for cmdlets derived from WebRequestPSCmdlet. - /// - protected override void ProcessRecord() + #region Helper Methods + private Uri PrepareUri(Uri uri) { - try - { - // Set cmdlet context for write progress - ValidateParameters(); - PrepareSession(); - - // If the request contains an authorization header and PreserveAuthorizationOnRedirect is not set, - // it needs to be stripped on the first redirect. - bool keepAuthorizationOnRedirect = PreserveAuthorizationOnRedirect.IsPresent - && WebSession.Headers.ContainsKey(HttpKnownHeaderNames.Authorization); - - bool handleRedirect = keepAuthorizationOnRedirect || AllowInsecureRedirect; + uri = CheckProtocol(uri); - using (HttpClient client = GetHttpClient(handleRedirect)) + // Before creating the web request, + // preprocess Body if content is a dictionary and method is GET (set as query) + LanguagePrimitives.TryConvertTo(Body, out IDictionary bodyAsDictionary); + if (bodyAsDictionary is not null && (Method == WebRequestMethod.Default || Method == WebRequestMethod.Get || CustomMethod == "GET")) + { + UriBuilder uriBuilder = new(uri); + if (uriBuilder.Query is not null && uriBuilder.Query.Length > 1) { - int followedRelLink = 0; - Uri uri = Uri; - do - { - if (followedRelLink > 0) - { - string linkVerboseMsg = string.Format( - CultureInfo.CurrentCulture, - WebCmdletStrings.FollowingRelLinkVerboseMsg, - uri.AbsoluteUri); - - WriteVerbose(linkVerboseMsg); - } - - using (HttpRequestMessage request = GetRequest(uri)) - { - FillRequestStream(request); - try - { - long requestContentLength = request.Content is null ? 0 : request.Content.Headers.ContentLength.Value; + uriBuilder.Query = string.Concat(uriBuilder.Query.AsSpan(1), "&", FormatDictionary(bodyAsDictionary)); + } + else + { + uriBuilder.Query = FormatDictionary(bodyAsDictionary); + } - string reqVerboseMsg = string.Format( - CultureInfo.CurrentCulture, - WebCmdletStrings.WebMethodInvocationVerboseMsg, - request.Version, - request.Method, - requestContentLength); + uri = uriBuilder.Uri; - WriteVerbose(reqVerboseMsg); + // Set body to null to prevent later FillRequestStream + Body = null; + } - using HttpResponseMessage response = GetResponse(client, request, handleRedirect); + return uri; + } - string contentType = ContentHelper.GetContentType(response); - string respVerboseMsg = string.Format( - CultureInfo.CurrentCulture, - WebCmdletStrings.WebResponseVerboseMsg, - response.Content.Headers.ContentLength, - contentType); + private static Uri CheckProtocol(Uri uri) + { + ArgumentNullException.ThrowIfNull(uri); - WriteVerbose(respVerboseMsg); + if (!uri.IsAbsoluteUri) + { + uri = new Uri("http://" + uri.OriginalString); + } - bool _isSuccess = response.IsSuccessStatusCode; + return uri; + } - // Check if the Resume range was not satisfiable because the file already completed downloading. - // This happens when the local file is the same size as the remote file. - if (Resume.IsPresent - && response.StatusCode == HttpStatusCode.RequestedRangeNotSatisfiable - && response.Content.Headers.ContentRange.HasLength - && response.Content.Headers.ContentRange.Length == _resumeFileSize) - { - _isSuccess = true; - WriteVerbose(string.Format( - CultureInfo.CurrentCulture, - WebCmdletStrings.OutFileWritingSkipped, - OutFile)); + private string QualifyFilePath(string path) + { + string resolvedFilePath = PathUtils.ResolveFilePath(filePath: path, command: this, isLiteralPath: true); + return resolvedFilePath; + } - // Disable writing to the OutFile. - OutFile = null; - } + private static string FormatDictionary(IDictionary content) + { + ArgumentNullException.ThrowIfNull(content); - if (ShouldCheckHttpStatus && !_isSuccess) - { - string message = string.Format( - CultureInfo.CurrentCulture, - WebCmdletStrings.ResponseStatusCodeFailure, - (int)response.StatusCode, - response.ReasonPhrase); + StringBuilder bodyBuilder = new(); + foreach (string key in content.Keys) + { + if (bodyBuilder.Length > 0) + { + bodyBuilder.Append('&'); + } - HttpResponseException httpEx = new(message, response); - ErrorRecord er = new(httpEx, "WebCmdletWebResponseException", ErrorCategory.InvalidOperation, request); - string detailMsg = string.Empty; - StreamReader reader = null; - try - { - reader = new StreamReader(StreamHelper.GetResponseStream(response)); - detailMsg = FormatErrorMessage(reader.ReadToEnd(), contentType); - } - catch - { - // Catch all - } - finally - { - reader?.Dispose(); - } + object value = content[key]; - if (!string.IsNullOrEmpty(detailMsg)) - { - er.ErrorDetails = new ErrorDetails(detailMsg); - } + // URLEncode the key and value + string encodedKey = WebUtility.UrlEncode(key); + string encodedValue = string.Empty; + if (value is not null) + { + encodedValue = WebUtility.UrlEncode(value.ToString()); + } - ThrowTerminatingError(er); - } + bodyBuilder.Append($"{encodedKey}={encodedValue}"); + } - if (_parseRelLink || _followRelLink) - { - ParseLinkHeader(response, uri); - } + return bodyBuilder.ToString(); + } - ProcessResponse(response); - UpdateSession(response); + private ErrorRecord GetValidationError(string msg, string errorId) + { + var ex = new ValidationMetadataException(msg); + var error = new ErrorRecord(ex, errorId, ErrorCategory.InvalidArgument, this); + return error; + } - // If we hit our maximum redirection count, generate an error. - // Errors with redirection counts of greater than 0 are handled automatically by .NET, but are - // impossible to detect programmatically when we hit this limit. By handling this ourselves - // (and still writing out the result), users can debug actual HTTP redirect problems. - if (WebSession.MaximumRedirection == 0 && IsRedirectCode(response.StatusCode)) - { - ErrorRecord er = new(new InvalidOperationException(), "MaximumRedirectExceeded", ErrorCategory.InvalidOperation, request); - er.ErrorDetails = new ErrorDetails(WebCmdletStrings.MaximumRedirectionCountExceeded); - WriteError(er); - } - } - catch (HttpRequestException ex) - { - ErrorRecord er = new(ex, "WebCmdletWebResponseException", ErrorCategory.InvalidOperation, request); - if (ex.InnerException is not null) - { - er.ErrorDetails = new ErrorDetails(ex.InnerException.Message); - } + private ErrorRecord GetValidationError(string msg, string errorId, params object[] args) + { + msg = string.Format(CultureInfo.InvariantCulture, msg, args); + var ex = new ValidationMetadataException(msg); + var error = new ErrorRecord(ex, errorId, ErrorCategory.InvalidArgument, this); + return error; + } - ThrowTerminatingError(er); - } + private string GetBasicAuthorizationHeader() + { + var password = new NetworkCredential(null, Credential.Password).Password; + string unencoded = string.Create(CultureInfo.InvariantCulture, $"{Credential.UserName}:{password}"); + byte[] bytes = Encoding.UTF8.GetBytes(unencoded); + return string.Create(CultureInfo.InvariantCulture, $"Basic {Convert.ToBase64String(bytes)}"); + } - if (_followRelLink) - { - if (!_relationLink.ContainsKey("next")) - { - return; - } + private string GetBearerAuthorizationHeader() + { + return string.Create(CultureInfo.InvariantCulture, $"Bearer {new NetworkCredential(string.Empty, Token).Password}"); + } - uri = new Uri(_relationLink["next"]); - followedRelLink++; - } - } - } - while (_followRelLink && (followedRelLink < _maximumFollowRelLink)); - } + private void ProcessAuthentication() + { + if (Authentication == WebAuthenticationType.Basic) + { + WebSession.Headers["Authorization"] = GetBasicAuthorizationHeader(); } - catch (CryptographicException ex) + else if (Authentication == WebAuthenticationType.Bearer || Authentication == WebAuthenticationType.OAuth) { - ErrorRecord er = new(ex, "WebCmdletCertificateException", ErrorCategory.SecurityError, null); - ThrowTerminatingError(er); + WebSession.Headers["Authorization"] = GetBearerAuthorizationHeader(); } - catch (NotSupportedException ex) + else { - ErrorRecord er = new(ex, "WebCmdletIEDomNotSupportedException", ErrorCategory.NotImplemented, null); - ThrowTerminatingError(er); + Diagnostics.Assert(false, string.Create(CultureInfo.InvariantCulture, $"Unrecognized Authentication value: {Authentication}")); } } - - /// - /// To implement ^C. - /// - protected override void StopProcessing() => _cancelToken?.Cancel(); - - #endregion Overrides - - #region Helper Methods - + /// /// Sets the ContentLength property of the request and writes the specified content to the request's RequestStream. /// @@ -1724,7 +1639,7 @@ internal void ParseLinkHeader(HttpResponseMessage response, System.Uri requestUr /// /// The Field Name to use. /// The Field Value to use. - /// The > to update. + /// The to update. /// If true, collection types in will be enumerated. If false, collections will be treated as single value. private void AddMultipartContent(object fieldName, object fieldValue, MultipartFormDataContent formData, bool enumerate) { @@ -1815,6 +1730,7 @@ private static StreamContent GetMultipartStreamContent(object fieldName, Stream private static StreamContent GetMultipartFileContent(object fieldName, FileInfo file) { var result = GetMultipartStreamContent(fieldName: fieldName, stream: new FileStream(file.FullName, FileMode.Open)); + // .NET does not enclose field names in quotes, however, modern browsers and curl do. result.Headers.ContentDisposition.FileName = "\"" + file.Name + "\""; @@ -1874,6 +1790,79 @@ private static string FormatErrorMessage(string error, string contentType) return formattedError; } + // Returns true if the status code is one of the supported redirection codes. + private static bool IsRedirectCode(HttpStatusCode code) + { + int intCode = (int)code; + return + ( + (intCode >= 300 && intCode < 304) || + intCode == 307 || + intCode == 308 + ); + } + + // Returns true if the status code is a redirection code and the action requires switching from POST to GET on redirection. + // NOTE: Some of these status codes map to the same underlying value but spelling them out for completeness. + private static bool IsRedirectToGet(HttpStatusCode code) + { + return + ( + code == HttpStatusCode.Found || + code == HttpStatusCode.Moved || + code == HttpStatusCode.Redirect || + code == HttpStatusCode.RedirectMethod || + code == HttpStatusCode.SeeOther || + code == HttpStatusCode.Ambiguous || + code == HttpStatusCode.MultipleChoices + ); + } + + // Returns true if the status code shows a server or client error and MaximumRetryCount > 0 + private bool ShouldRetry(HttpStatusCode code) + { + int intCode = (int)code; + + return + ( + (intCode == 304 || (intCode >= 400 && intCode <= 599)) && WebSession.MaximumRetryCount > 0 + ); + } + + private static HttpMethod GetHttpMethod(WebRequestMethod method) => method switch + { + WebRequestMethod.Default or WebRequestMethod.Get => HttpMethod.Get, + WebRequestMethod.Delete => HttpMethod.Delete, + WebRequestMethod.Head => HttpMethod.Head, + WebRequestMethod.Patch => HttpMethod.Patch, + WebRequestMethod.Post => HttpMethod.Post, + WebRequestMethod.Put => HttpMethod.Put, + WebRequestMethod.Options => HttpMethod.Options, + WebRequestMethod.Trace => HttpMethod.Trace, + _ => new HttpMethod(method.ToString().ToUpperInvariant()) + }; + #endregion Helper Methods } + + /// + /// Exception class for webcmdlets to enable returning HTTP error response. + /// + public sealed class HttpResponseException : HttpRequestException + { + /// + /// Initializes a new instance of the class. + /// + /// Message for the exception. + /// Response from the HTTP server. + public HttpResponseException(string message, HttpResponseMessage response) : base(message, inner: null, response.StatusCode) + { + Response = response; + } + + /// + /// HTTP error response. + /// + public HttpResponseMessage Response { get; } + } } From ed68c861d45ae4a96c6306a0f876bc6cfebf93ad Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Fri, 10 Feb 2023 12:14:29 +0100 Subject: [PATCH 352/779] Fix redirection for -CustomMethod "POST" in WebCmdlets (#19111) --- .../Common/WebRequestPSCmdlet.Common.cs | 19 ++++---- .../WebCmdlets.Tests.ps1 | 47 +++++++++++++++++-- 2 files changed, 53 insertions(+), 13 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index a9c5934ecd3..a4a924079fb 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -1211,16 +1211,16 @@ internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestM // Add 1 to account for the first request. int totalRequests = WebSession.MaximumRetryCount + 1; - HttpRequestMessage req = request; + HttpRequestMessage currentRequest = request; HttpResponseMessage response = null; do { // Track the current URI being used by various requests and re-requests. - Uri currentUri = req.RequestUri; + Uri currentUri = currentRequest.RequestUri; _cancelToken = new CancellationTokenSource(); - response = client.SendAsync(req, HttpCompletionOption.ResponseHeadersRead, _cancelToken.Token).GetAwaiter().GetResult(); + response = client.SendAsync(currentRequest, HttpCompletionOption.ResponseHeadersRead, _cancelToken.Token).GetAwaiter().GetResult(); if (handleRedirect && WebSession.MaximumRedirection is not 0 @@ -1236,13 +1236,12 @@ internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestM WebSession.MaximumRedirection--; } - // For selected redirects that used POST, GET must be used with the - // redirected Location. - // Since GET is the default; POST only occurs when -Method POST is used. - if (Method == WebRequestMethod.Post && IsRedirectToGet(response.StatusCode)) + // For selected redirects, GET must be used with the redirected Location. + if (currentRequest.Method == HttpMethod.Post && IsRedirectToGet(response.StatusCode)) { // See https://msdn.microsoft.com/library/system.net.httpstatuscode(v=vs.110).aspx Method = WebRequestMethod.Get; + CustomMethod = string.Empty; } currentUri = new Uri(request.RequestUri, response.Headers.Location); @@ -1327,9 +1326,9 @@ internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestM _cancelToken.Cancel(); _cancelToken = null; - req.Dispose(); - req = GetRequest(currentUri); - FillRequestStream(req); + currentRequest.Dispose(); + currentRequest = GetRequest(currentUri); + FillRequestStream(currentRequest); } totalRequests--; diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 index 35262d8bf41..7ff5867130e 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 @@ -132,6 +132,10 @@ function ExecuteRedirectRequest { [string] $Method = 'GET', + [ValidateSet('POST')] + [string] + $CustomMethod, + [switch] $PreserveAuthorizationOnRedirect, @@ -146,12 +150,20 @@ function ExecuteRedirectRequest { if ($Cmdlet -eq 'Invoke-WebRequest') { if ($MaximumRedirection -gt 0) { $result.Output = Invoke-WebRequest -Uri $uri -Headers $headers -PreserveAuthorizationOnRedirect:$PreserveAuthorizationOnRedirect.IsPresent -Method $Method -MaximumRedirection:$MaximumRedirection + } elseif ($CustomMethod) { + $result.Output = Invoke-WebRequest -Uri $uri -Headers $headers -PreserveAuthorizationOnRedirect:$PreserveAuthorizationOnRedirect.IsPresent -CustomMethod $CustomMethod } else { $result.Output = Invoke-WebRequest -Uri $uri -Headers $headers -PreserveAuthorizationOnRedirect:$PreserveAuthorizationOnRedirect.IsPresent -Method $Method } $result.Content = $result.Output.Content | ConvertFrom-Json } else { - $result.Output = Invoke-RestMethod -Uri $uri -Headers $headers -PreserveAuthorizationOnRedirect:$PreserveAuthorizationOnRedirect.IsPresent -Method $Method + if ($MaximumRedirection -gt 0) { + $result.Output = Invoke-RestMethod -Uri $uri -Headers $headers -PreserveAuthorizationOnRedirect:$PreserveAuthorizationOnRedirect.IsPresent -Method $Method -MaximumRedirection:$MaximumRedirection + } elseif ($CustomMethod) { + $result.Output = Invoke-RestMethod -Uri $uri -Headers $headers -PreserveAuthorizationOnRedirect:$PreserveAuthorizationOnRedirect.IsPresent -CustomMethod $CustomMethod + } else { + $result.Output = Invoke-RestMethod -Uri $uri -Headers $headers -PreserveAuthorizationOnRedirect:$PreserveAuthorizationOnRedirect.IsPresent -Method $Method + } # NOTE: $result.Output should already be a PSObject (Invoke-RestMethod converts the returned json automatically) # so simply reference $result.Output $result.Content = $result.Output @@ -986,7 +998,22 @@ Describe "Invoke-WebRequest tests" -Tags "Feature", "RequireAdminOnWindows" { $response.Error | Should -BeNullOrEmpty # ensure user-agent is present (i.e., no false positives ) $response.Content.Headers."User-Agent" | Should -Not -BeNullOrEmpty - # ensure Authorization header has been removed. + # ensure Authorization header has been preserved. + $response.Content.Headers."Authorization" | Should -BeExactly 'test' + # ensure POST was changed to GET for selected redirections and remains as POST for others. + $response.Content.Method | Should -Be $redirectedMethod + } + + It "Validates Invoke-WebRequest -PreserveAuthorizationOnRedirect -CustomMethod POST keeps the authorization header redirects and switches from POST to GET when it handles the redirect: " -TestCases $redirectTests { + param($redirectType, $redirectedMethod) + $uri = Get-WebListenerUrl -Test 'Redirect' -Query @{type = $redirectType} + + $response = ExecuteRedirectRequest -PreserveAuthorizationOnRedirect -Uri $uri -CustomMethod 'POST' + + $response.Error | Should -BeNullOrEmpty + # ensure user-agent is present (i.e., no false positives ) + $response.Content.Headers."User-Agent" | Should -Not -BeNullOrEmpty + # ensure Authorization header has been preserved. $response.Content.Headers."Authorization" | Should -BeExactly 'test' # ensure POST was changed to GET for selected redirections and remains as POST for others. $response.Content.Method | Should -Be $redirectedMethod @@ -2690,7 +2717,21 @@ Describe "Invoke-RestMethod tests" -Tags "Feature", "RequireAdminOnWindows" { $response.Error | Should -BeNullOrEmpty # ensure user-agent is present (i.e., no false positives ) $response.Content.Headers."User-Agent" | Should -Not -BeNullOrEmpty - # ensure Authorization header has been removed. + # ensure Authorization header has been preserved. + $response.Content.Headers."Authorization" | Should -BeExactly 'test' + # ensure POST was changed to GET for selected redirections and remains as POST for others. + $response.Content.Method | Should -Be $redirectedMethod + } + + It "Validates Invoke-RestMethod -PreserveAuthorizationOnRedirect -CustomMethod POST keeps the authorization header redirects and switches from POST to GET when it handles the redirect: " -TestCases $redirectTests { + param($redirectType, $redirectedMethod) + $uri = Get-WebListenerUrl -Test 'Redirect' -Query @{type = $redirectType} + $response = ExecuteRedirectRequest -PreserveAuthorizationOnRedirect -Cmdlet 'Invoke-RestMethod' -Uri $uri -CustomMethod 'POST' + + $response.Error | Should -BeNullOrEmpty + # ensure user-agent is present (i.e., no false positives ) + $response.Content.Headers."User-Agent" | Should -Not -BeNullOrEmpty + # ensure Authorization header has been preserved. $response.Content.Headers."Authorization" | Should -BeExactly 'test' # ensure POST was changed to GET for selected redirections and remains as POST for others. $response.Content.Method | Should -Be $redirectedMethod From 2f43013df380e6ea1f04ddcf32d9efdefa9ae6a3 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Fri, 10 Feb 2023 17:50:01 +0100 Subject: [PATCH 353/779] Build the relative URI for links from the response in Invoke-WebRequest (#19092) --- .../Common/WebRequestPSCmdlet.Common.cs | 9 +++++---- .../WebCmdlets.Tests.ps1 | 16 ++++++++++++---- 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index a4a924079fb..3a3c4386293 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -609,7 +609,7 @@ protected override void ProcessRecord() if (_parseRelLink || _followRelLink) { - ParseLinkHeader(response, uri); + ParseLinkHeader(response); } ProcessResponse(response); @@ -1596,8 +1596,9 @@ internal void SetRequestContent(HttpRequestMessage request, IDictionary content) SetRequestContent(request, body); } - internal void ParseLinkHeader(HttpResponseMessage response, System.Uri requestUri) + internal void ParseLinkHeader(HttpResponseMessage response) { + Uri requestUri = response.RequestMessage.RequestUri; if (_relationLink is null) { // Must ignore the case of relation links. See RFC 8288 (https://tools.ietf.org/html/rfc8288) @@ -1610,12 +1611,12 @@ internal void ParseLinkHeader(HttpResponseMessage response, System.Uri requestUr // We only support the URL in angle brackets and `rel`, other attributes are ignored // user can still parse it themselves via the Headers property - const string pattern = "<(?.*?)>;\\s*rel=(?\")?(?(?(quoted).*?|[^,;]*))(?(quoted)\")"; + const string Pattern = "<(?.*?)>;\\s*rel=(?\")?(?(?(quoted).*?|[^,;]*))(?(quoted)\")"; if (response.Headers.TryGetValues("Link", out IEnumerable links)) { foreach (string linkHeader in links) { - MatchCollection matchCollection = Regex.Matches(linkHeader, pattern); + MatchCollection matchCollection = Regex.Matches(linkHeader, Pattern); foreach (Match match in matchCollection) { if (match.Success) diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 index 7ff5867130e..2c3c3fb671a 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 @@ -834,8 +834,12 @@ Describe "Invoke-WebRequest tests" -Tags "Feature", "RequireAdminOnWindows" { $result.Output.RelationLink.Count | Should -Be 0 } - It "Validate Invoke-WebRequest returns valid RelationLink property with absolute uris if Link Header is present" { - $uri = Get-WebListenerUrl -Test 'Link' -Query @{maxlinks = 5; linknumber = 2} + It "Validate Invoke-WebRequest returns valid RelationLink property with absolute uris if Link Header is present " -TestCases @( + $originalUri = Get-WebListenerUrl -Test 'Link' -Query @{maxlinks = 5; linknumber = 2} + @{name = '(URI with scheme)'; uri = $originalUri} + @{name = '(URI without scheme)'; uri = $originalUri.OriginalString.Split("//")[1]} + ) { + param($uri) $command = "Invoke-WebRequest -Uri '$uri'" $result = ExecuteWebCommand -command $command @@ -2547,9 +2551,13 @@ Describe "Invoke-RestMethod tests" -Tags "Feature", "RequireAdminOnWindows" { $result.Output | Should -BeExactly "foo" } - It "Validate Invoke-RestMethod -FollowRelLink correctly follows all the available relation links" { + It "Validate Invoke-RestMethod -FollowRelLink correctly follows all the available relation links " -TestCases @( $maxLinks = 5 - $uri = Get-WebListenerUrl -Test 'Link' -Query @{maxlinks = $maxLinks} + $originalUri = Get-WebListenerUrl -Test 'Link' -Query @{maxlinks = $maxLinks} + @{name = '(URI with scheme)'; uri = $originalUri} + @{name = '(URI without scheme)'; uri = $originalUri.OriginalString.Split("//")[1]} + ) { + param($uri) $command = "Invoke-RestMethod -Uri '$uri' -FollowRelLink" $result = ExecuteWebCommand -command $command From 1848740cb79a207f6a60098c770ebe9557303274 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Sat, 11 Feb 2023 16:25:37 +0100 Subject: [PATCH 354/779] Small cleanup webcmdlets (#19128) --- .../Common/WebRequestPSCmdlet.Common.cs | 112 +++++++----------- 1 file changed, 43 insertions(+), 69 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index 3a3c4386293..31aea2f6894 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -859,8 +859,7 @@ internal virtual void PrepareSession() X509Certificate2Collection tbCollection = (X509Certificate2Collection)collection.Find(X509FindType.FindByThumbprint, CertificateThumbprint, false); if (tbCollection.Count == 0) { - CryptographicException ex = new(WebCmdletStrings.ThumbprintNotFound); - throw ex; + throw new CryptographicException(WebCmdletStrings.ThumbprintNotFound); } foreach (X509Certificate2 tbCert in tbCollection) @@ -910,13 +909,13 @@ internal virtual void PrepareSession() { foreach (string key in Headers.Keys) { - var value = Headers[key]; + object value = Headers[key]; // null is not valid value for header. // We silently ignore header if value is null. if (value is not null) { - // add the header value (or overwrite it if already present) + // Add the header value (or overwrite it if already present) WebSession.Headers[key] = value.ToString(); } } @@ -994,7 +993,7 @@ internal virtual HttpRequestMessage GetRequest(Uri uri) HttpMethod httpMethod = string.IsNullOrEmpty(CustomMethod) ? GetHttpMethod(Method) : new HttpMethod(CustomMethod); // Create the base WebRequest object - var request = new HttpRequestMessage(httpMethod, requestUri); + HttpRequestMessage request = new(httpMethod, requestUri); if (HttpVersion is not null) { @@ -1058,7 +1057,7 @@ internal virtual HttpRequestMessage GetRequest(Uri uri) if (TransferEncoding is not null) { request.Headers.TransferEncodingChunked = true; - var headerValue = new TransferCodingHeaderValue(TransferEncoding); + TransferCodingHeaderValue headerValue = new(TransferEncoding); if (!request.Headers.TransferEncoding.Contains(headerValue)) { request.Headers.TransferEncoding.Add(headerValue); @@ -1069,7 +1068,7 @@ internal virtual HttpRequestMessage GetRequest(Uri uri) // If not, create a Range to request the entire file. if (Resume.IsPresent) { - var fileInfo = new FileInfo(QualifiedOutFile); + FileInfo fileInfo = new(QualifiedOutFile); if (fileInfo.Exists) { request.Headers.Range = new RangeHeaderValue(fileInfo.Length, null); @@ -1105,7 +1104,7 @@ internal virtual void FillRequestStream(HttpRequestMessage request) if (Form is not null) { - var formData = new MultipartFormDataContent(); + MultipartFormDataContent formData = new(); foreach (DictionaryEntry formEntry in Form) { // AddMultipartContent will handle PSObject unwrapping, Object type determination and enumerateing top level IEnumerables. @@ -1117,13 +1116,8 @@ internal virtual void FillRequestStream(HttpRequestMessage request) else if (Body is not null) { // Coerce body into a usable form - object content = Body; - // Make sure we're using the base object of the body, not the PSObject wrapper - if (Body is PSObject psBody) - { - content = psBody.BaseObject; - } + object content = Body is PSObject psBody ? psBody.BaseObject : Body; switch (content) { @@ -1179,7 +1173,7 @@ internal virtual void FillRequestStream(HttpRequestMessage request) request.Content.Headers.Clear(); } - foreach (var entry in WebSession.ContentHeaders) + foreach (KeyValuePair entry in WebSession.ContentHeaders) { if (!string.IsNullOrWhiteSpace(entry.Value)) { @@ -1195,7 +1189,7 @@ internal virtual void FillRequestStream(HttpRequestMessage request) } catch (FormatException ex) { - var outerEx = new ValidationMetadataException(WebCmdletStrings.ContentTypeException, ex); + ValidationMetadataException outerEx = new(WebCmdletStrings.ContentTypeException, ex); ErrorRecord er = new(outerEx, "WebCmdletContentTypeException", ErrorCategory.InvalidArgument, ContentType); ThrowTerminatingError(er); } @@ -1378,20 +1372,11 @@ private static Uri CheckProtocol(Uri uri) { ArgumentNullException.ThrowIfNull(uri); - if (!uri.IsAbsoluteUri) - { - uri = new Uri("http://" + uri.OriginalString); - } - - return uri; - } - - private string QualifyFilePath(string path) - { - string resolvedFilePath = PathUtils.ResolveFilePath(filePath: path, command: this, isLiteralPath: true); - return resolvedFilePath; + return uri.IsAbsoluteUri ? uri : new Uri("http://" + uri.OriginalString); } + private string QualifyFilePath(string path) => PathUtils.ResolveFilePath(filePath: path, command: this, isLiteralPath: true); + private static string FormatDictionary(IDictionary content) { ArgumentNullException.ThrowIfNull(content); @@ -1408,11 +1393,7 @@ private static string FormatDictionary(IDictionary content) // URLEncode the key and value string encodedKey = WebUtility.UrlEncode(key); - string encodedValue = string.Empty; - if (value is not null) - { - encodedValue = WebUtility.UrlEncode(value.ToString()); - } + string encodedValue = value is null ? string.Empty : WebUtility.UrlEncode(value.ToString()); bodyBuilder.Append($"{encodedKey}={encodedValue}"); } @@ -1422,22 +1403,20 @@ private static string FormatDictionary(IDictionary content) private ErrorRecord GetValidationError(string msg, string errorId) { - var ex = new ValidationMetadataException(msg); - var error = new ErrorRecord(ex, errorId, ErrorCategory.InvalidArgument, this); - return error; + ValidationMetadataException ex = new(msg); + return new ErrorRecord(ex, errorId, ErrorCategory.InvalidArgument, this); } private ErrorRecord GetValidationError(string msg, string errorId, params object[] args) { msg = string.Format(CultureInfo.InvariantCulture, msg, args); - var ex = new ValidationMetadataException(msg); - var error = new ErrorRecord(ex, errorId, ErrorCategory.InvalidArgument, this); - return error; + ValidationMetadataException ex = new(msg); + return new ErrorRecord(ex, errorId, ErrorCategory.InvalidArgument, this); } private string GetBasicAuthorizationHeader() { - var password = new NetworkCredential(null, Credential.Password).Password; + string password = new NetworkCredential(string.Empty, Credential.Password).Password; string unencoded = string.Create(CultureInfo.InvariantCulture, $"{Credential.UserName}:{password}"); byte[] bytes = Encoding.UTF8.GetBytes(unencoded); return string.Create(CultureInfo.InvariantCulture, $"Basic {Convert.ToBase64String(bytes)}"); @@ -1463,14 +1442,14 @@ private void ProcessAuthentication() Diagnostics.Assert(false, string.Create(CultureInfo.InvariantCulture, $"Unrecognized Authentication value: {Authentication}")); } } - + /// - /// Sets the ContentLength property of the request and writes the specified content to the request's RequestStream. + /// Writes the specified content to the request's RequestStream. /// /// The WebRequest who's content is to be set. /// A byte array containing the content data. /// - /// Because this function sets the request's ContentLength property and writes content data into the request's stream, + /// Because this function writes content data into the request's stream, /// it should be called one time maximum on a given request. /// internal void SetRequestContent(HttpRequestMessage request, byte[] content) @@ -1478,17 +1457,16 @@ internal void SetRequestContent(HttpRequestMessage request, byte[] content) ArgumentNullException.ThrowIfNull(request); ArgumentNullException.ThrowIfNull(content); - ByteArrayContent byteArrayContent = new(content); - request.Content = byteArrayContent; + request.Content = new ByteArrayContent(content); } /// - /// Sets the ContentLength property of the request and writes the specified content to the request's RequestStream. + /// Writes the specified content to the request's RequestStream. /// /// The WebRequest who's content is to be set. /// A String object containing the content data. /// - /// Because this function sets the request's ContentLength property and writes content data into the request's stream, + /// Because this function writes content data into the request's stream, /// it should be called one time maximum on a given request. /// internal void SetRequestContent(HttpRequestMessage request, string content) @@ -1504,7 +1482,7 @@ internal void SetRequestContent(HttpRequestMessage request, string content) // would be used if Charset is not supplied in the Content-Type property. try { - var mediaTypeHeaderValue = MediaTypeHeaderValue.Parse(ContentType); + MediaTypeHeaderValue mediaTypeHeaderValue = MediaTypeHeaderValue.Parse(ContentType); if (!string.IsNullOrEmpty(mediaTypeHeaderValue.CharSet)) { encoding = Encoding.GetEncoding(mediaTypeHeaderValue.CharSet); @@ -1522,8 +1500,7 @@ internal void SetRequestContent(HttpRequestMessage request, string content) } byte[] bytes = StreamHelper.EncodeToBytes(content, encoding); - ByteArrayContent byteArrayContent = new(bytes); - request.Content = byteArrayContent; + request.Content = new ByteArrayContent(bytes); } internal void SetRequestContent(HttpRequestMessage request, XmlNode xmlNode) @@ -1533,9 +1510,8 @@ internal void SetRequestContent(HttpRequestMessage request, XmlNode xmlNode) byte[] bytes = null; XmlDocument doc = xmlNode as XmlDocument; - if (doc?.FirstChild is XmlDeclaration) + if (doc?.FirstChild is XmlDeclaration decl) { - XmlDeclaration decl = doc.FirstChild as XmlDeclaration; Encoding encoding = Encoding.GetEncoding(decl.Encoding); bytes = StreamHelper.EncodeToBytes(doc.OuterXml, encoding); } @@ -1544,18 +1520,16 @@ internal void SetRequestContent(HttpRequestMessage request, XmlNode xmlNode) bytes = StreamHelper.EncodeToBytes(xmlNode.OuterXml, encoding: null); } - ByteArrayContent byteArrayContent = new(bytes); - - request.Content = byteArrayContent; + request.Content = new ByteArrayContent(bytes); } /// - /// Sets the ContentLength property of the request and writes the specified content to the request's RequestStream. + /// Writes the specified content to the request's RequestStream. /// /// The WebRequest who's content is to be set. /// A Stream object containing the content data. /// - /// Because this function sets the request's ContentLength property and writes content data into the request's stream, + /// Because this function writes content data into the request's stream, /// it should be called one time maximum on a given request. /// internal void SetRequestContent(HttpRequestMessage request, Stream contentStream) @@ -1563,17 +1537,16 @@ internal void SetRequestContent(HttpRequestMessage request, Stream contentStream ArgumentNullException.ThrowIfNull(request); ArgumentNullException.ThrowIfNull(contentStream); - StreamContent streamContent = new(contentStream); - request.Content = streamContent; + request.Content = new StreamContent(contentStream); } /// - /// Sets the ContentLength property of the request and writes the specified content to the request's RequestStream. + /// Writes the specified content to the request's RequestStream. /// /// The WebRequest who's content is to be set. /// A MultipartFormDataContent object containing multipart/form-data content. /// - /// Because this function sets the request's ContentLength property and writes content data into the request's stream, + /// Because this function writes content data into the request's stream, /// it should be called one time maximum on a given request. /// internal void SetRequestContent(HttpRequestMessage request, MultipartFormDataContent multipartContent) @@ -1679,7 +1652,7 @@ private void AddMultipartContent(object fieldName, object fieldValue, MultipartF // Treat the value as a collection and enumerate it if enumeration is true if (enumerate && fieldValue is IEnumerable items) { - foreach (var item in items) + foreach (object item in items) { // Recurse, but do not enumerate the next level. IEnumerables will be treated as single values. AddMultipartContent(fieldName: fieldName, fieldValue: item, formData: formData, enumerate: false); @@ -1694,11 +1667,12 @@ private void AddMultipartContent(object fieldName, object fieldValue, MultipartF /// The Field Value to use for the private static StringContent GetMultipartStringContent(object fieldName, object fieldValue) { - var contentDisposition = new ContentDispositionHeaderValue("form-data"); + ContentDispositionHeaderValue contentDisposition = new("form-data"); + // .NET does not enclose field names in quotes, however, modern browsers and curl do. contentDisposition.Name = "\"" + LanguagePrimitives.ConvertTo(fieldName) + "\""; - var result = new StringContent(LanguagePrimitives.ConvertTo(fieldValue)); + StringContent result = new(LanguagePrimitives.ConvertTo(fieldValue)); result.Headers.ContentDisposition = contentDisposition; return result; @@ -1711,11 +1685,12 @@ private static StringContent GetMultipartStringContent(object fieldName, object /// The to use for the private static StreamContent GetMultipartStreamContent(object fieldName, Stream stream) { - var contentDisposition = new ContentDispositionHeaderValue("form-data"); + ContentDispositionHeaderValue contentDisposition = new("form-data"); + // .NET does not enclose field names in quotes, however, modern browsers and curl do. contentDisposition.Name = "\"" + LanguagePrimitives.ConvertTo(fieldName) + "\""; - var result = new StreamContent(stream); + StreamContent result = new(stream); result.Headers.ContentDisposition = contentDisposition; result.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); @@ -1729,7 +1704,7 @@ private static StreamContent GetMultipartStreamContent(object fieldName, Stream /// The file to use for the private static StreamContent GetMultipartFileContent(object fieldName, FileInfo file) { - var result = GetMultipartStreamContent(fieldName: fieldName, stream: new FileStream(file.FullName, FileMode.Open)); + StreamContent result = GetMultipartStreamContent(fieldName: fieldName, stream: new FileStream(file.FullName, FileMode.Open)); // .NET does not enclose field names in quotes, however, modern browsers and curl do. result.Headers.ContentDisposition.FileName = "\"" + file.Name + "\""; @@ -1754,9 +1729,8 @@ private static string FormatErrorMessage(string error, string contentType) OmitXmlDeclaration = true }; - if (doc.FirstChild is XmlDeclaration) + if (doc.FirstChild is XmlDeclaration decl) { - XmlDeclaration decl = doc.FirstChild as XmlDeclaration; settings.Encoding = Encoding.GetEncoding(decl.Encoding); } From 22b33c15a21b11d86f0f6fe491e0c332950159a7 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Sun, 12 Feb 2023 07:09:20 +0100 Subject: [PATCH 355/779] Revert comment changes in WebRequestPSCmdlet.Common.cs (#19136) --- .../Common/WebRequestPSCmdlet.Common.cs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index 31aea2f6894..9ccb5a7f7d5 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -1444,12 +1444,12 @@ private void ProcessAuthentication() } /// - /// Writes the specified content to the request's RequestStream. + /// Sets the ContentLength property of the request and writes the specified content to the request's RequestStream. /// /// The WebRequest who's content is to be set. /// A byte array containing the content data. /// - /// Because this function writes content data into the request's stream, + /// Because this function sets the request's ContentLength property and writes content data into the request's stream, /// it should be called one time maximum on a given request. /// internal void SetRequestContent(HttpRequestMessage request, byte[] content) @@ -1461,12 +1461,12 @@ internal void SetRequestContent(HttpRequestMessage request, byte[] content) } /// - /// Writes the specified content to the request's RequestStream. + /// Sets the ContentLength property of the request and writes the specified content to the request's RequestStream. /// /// The WebRequest who's content is to be set. /// A String object containing the content data. /// - /// Because this function writes content data into the request's stream, + /// Because this function sets the request's ContentLength property and writes content data into the request's stream, /// it should be called one time maximum on a given request. /// internal void SetRequestContent(HttpRequestMessage request, string content) @@ -1524,12 +1524,12 @@ internal void SetRequestContent(HttpRequestMessage request, XmlNode xmlNode) } /// - /// Writes the specified content to the request's RequestStream. + /// Sets the ContentLength property of the request and writes the specified content to the request's RequestStream. /// /// The WebRequest who's content is to be set. /// A Stream object containing the content data. /// - /// Because this function writes content data into the request's stream, + /// Because this function sets the request's ContentLength property and writes content data into the request's stream, /// it should be called one time maximum on a given request. /// internal void SetRequestContent(HttpRequestMessage request, Stream contentStream) @@ -1541,12 +1541,12 @@ internal void SetRequestContent(HttpRequestMessage request, Stream contentStream } /// - /// Writes the specified content to the request's RequestStream. + /// Sets the ContentLength property of the request and writes the ContentLength property of the request and writes the specified content to the request's RequestStream. /// /// The WebRequest who's content is to be set. /// A MultipartFormDataContent object containing multipart/form-data content. /// - /// Because this function writes content data into the request's stream, + /// Because this function sets the request's ContentLength property and writes content data into the request's stream, /// it should be called one time maximum on a given request. /// internal void SetRequestContent(HttpRequestMessage request, MultipartFormDataContent multipartContent) From 43abbc4517fb925800d9a2476604b8768d204721 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Mon, 13 Feb 2023 12:03:54 -0800 Subject: [PATCH 356/779] Update to the latest NOTICES file (#19086) Co-authored-by: adityapatwardhan --- ThirdPartyNotices.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ThirdPartyNotices.txt b/ThirdPartyNotices.txt index 04ab0a7a4f4..7c73d5c23a4 100644 --- a/ThirdPartyNotices.txt +++ b/ThirdPartyNotices.txt @@ -176,7 +176,7 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI --------------------------------------------------------- -Microsoft.Extensions.ObjectPool 7.0.1 - MIT +Microsoft.Extensions.ObjectPool 7.0.2 - MIT (c) Microsoft Corporation @@ -265,7 +265,7 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI --------------------------------------------------------- -Microsoft.PowerShell.Native 7.3.1 - MIT +Microsoft.PowerShell.Native 7.3.2 - MIT (c) Microsoft Corporation From 69a4d79400382c555ceac6a98d838ebde5d38721 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Tue, 14 Feb 2023 04:32:48 +0100 Subject: [PATCH 357/779] Webcmdlets display an error on https to http redirect (#18595) --- .../WebCmdlet/Common/WebRequestPSCmdlet.Common.cs | 10 +++++++++- .../resources/WebCmdletStrings.resx | 9 ++++++--- .../Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 | 4 ++-- 3 files changed, 17 insertions(+), 6 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index 9ccb5a7f7d5..fcb1eda744b 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -572,7 +572,15 @@ protected override void ProcessRecord() // Disable writing to the OutFile. OutFile = null; } - + + // Detect insecure redirection + if (!AllowInsecureRedirect && response.RequestMessage.RequestUri.Scheme == "https" && response.Headers.Location?.Scheme == "http") + { + ErrorRecord er = new(new InvalidOperationException(), "InsecureRedirection", ErrorCategory.InvalidOperation, request); + er.ErrorDetails = new ErrorDetails(WebCmdletStrings.InsecureRedirection); + ThrowTerminatingError(er); + } + if (ShouldCheckHttpStatus && !_isSuccess) { string message = string.Format( diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/WebCmdletStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/WebCmdletStrings.resx index bea0ae7d28a..a9628c647e3 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/WebCmdletStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/WebCmdletStrings.resx @@ -159,12 +159,15 @@ Cannot convert the JSON string because a dictionary that was converted from the string contains the duplicated key '{0}'. - - Cannot convert the JSON string because it contains keys with different casing. Please use the -AsHashTable switch instead. The key that was attempted to be added to the existing key '{0}' was '{1}'. - The response content cannot be parsed because the Internet Explorer engine is not available, or Internet Explorer's first-launch configuration is not complete. Specify the UseBasicParsing parameter and try again. + + Cannot follow an insecure redirection by default. Reissue the command specifying the -AllowInsecureRedirect switch. + + + Cannot convert the JSON string because it contains keys with different casing. Please use the -AsHashTable switch instead. The key that was attempted to be added to the existing key '{0}' was '{1}'. + The maximum redirection count has been exceeded. To increase the number of redirections allowed, supply a higher value to the -MaximumRedirection parameter. diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 index 2c3c3fb671a..3538a799b9b 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 @@ -1060,7 +1060,7 @@ Describe "Invoke-WebRequest tests" -Tags "Feature", "RequireAdminOnWindows" { $command = "Invoke-WebRequest -Uri '$uri' -SkipCertificateCheck" $result = ExecuteWebCommand -command $command - $result.Error.FullyQualifiedErrorId | Should -Be "WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand" + $result.Error.FullyQualifiedErrorId | Should -Be "InsecureRedirection,Microsoft.PowerShell.Commands.InvokeWebRequestCommand" } } @@ -2781,7 +2781,7 @@ Describe "Invoke-RestMethod tests" -Tags "Feature", "RequireAdminOnWindows" { $command = "Invoke-RestMethod -Uri '$uri' -SkipCertificateCheck" $result = ExecuteWebCommand -command $command - $result.Error.FullyQualifiedErrorId | Should -Be "WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand" + $result.Error.FullyQualifiedErrorId | Should -Be "InsecureRedirection,Microsoft.PowerShell.Commands.InvokeRestMethodCommand" } #endregion Redirect tests From 60b4e9704fca546f76e1128e30de4077c51a3ca2 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Tue, 14 Feb 2023 17:40:42 +0100 Subject: [PATCH 358/779] Allow to preserve the original HTTP method by adding `-PreserveHttpMethodOnRedirect` to Web cmdlets (#18894) --- .../Common/WebRequestPSCmdlet.Common.cs | 66 +++++++++---------- .../WebCmdlets.Tests.ps1 | 35 +++++++++- 2 files changed, 64 insertions(+), 37 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index fcb1eda744b..567a98ebfb9 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -351,6 +351,12 @@ public virtual string CustomMethod private string _custommethod; + /// + /// Gets or sets the PreserveHttpMethodOnRedirect property. + /// + [Parameter] + public virtual SwitchParameter PreserveHttpMethodOnRedirect { get; set; } + #endregion Method #region NoProxy @@ -509,7 +515,7 @@ protected override void ProcessRecord() bool keepAuthorizationOnRedirect = PreserveAuthorizationOnRedirect.IsPresent && WebSession.Headers.ContainsKey(HttpKnownHeaderNames.Authorization); - bool handleRedirect = keepAuthorizationOnRedirect || AllowInsecureRedirect; + bool handleRedirect = keepAuthorizationOnRedirect || AllowInsecureRedirect || PreserveHttpMethodOnRedirect; using (HttpClient client = GetHttpClient(handleRedirect)) { @@ -1239,9 +1245,8 @@ internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestM } // For selected redirects, GET must be used with the redirected Location. - if (currentRequest.Method == HttpMethod.Post && IsRedirectToGet(response.StatusCode)) + if (RequestRequiresForceGet(response.StatusCode, currentRequest.Method) && !PreserveHttpMethodOnRedirect) { - // See https://msdn.microsoft.com/library/system.net.httpstatuscode(v=vs.110).aspx Method = WebRequestMethod.Get; CustomMethod = string.Empty; } @@ -1713,7 +1718,7 @@ private static StreamContent GetMultipartStreamContent(object fieldName, Stream private static StreamContent GetMultipartFileContent(object fieldName, FileInfo file) { StreamContent result = GetMultipartStreamContent(fieldName: fieldName, stream: new FileStream(file.FullName, FileMode.Open)); - + // .NET does not enclose field names in quotes, however, modern browsers and curl do. result.Headers.ContentDisposition.FileName = "\"" + file.Name + "\""; @@ -1773,43 +1778,34 @@ private static string FormatErrorMessage(string error, string contentType) } // Returns true if the status code is one of the supported redirection codes. - private static bool IsRedirectCode(HttpStatusCode code) + private static bool IsRedirectCode(HttpStatusCode statusCode) => statusCode switch { - int intCode = (int)code; - return - ( - (intCode >= 300 && intCode < 304) || - intCode == 307 || - intCode == 308 - ); - } + HttpStatusCode.Found + or HttpStatusCode.Moved + or HttpStatusCode.MultipleChoices + or HttpStatusCode.PermanentRedirect + or HttpStatusCode.SeeOther + or HttpStatusCode.TemporaryRedirect => true, + _ => false + }; - // Returns true if the status code is a redirection code and the action requires switching from POST to GET on redirection. - // NOTE: Some of these status codes map to the same underlying value but spelling them out for completeness. - private static bool IsRedirectToGet(HttpStatusCode code) + // Returns true if the status code is a redirection code and the action requires switching to GET on redirection. + // See https://learn.microsoft.com/en-us/dotnet/api/system.net.httpstatuscode + private static bool RequestRequiresForceGet(HttpStatusCode statusCode, HttpMethod requestMethod) => statusCode switch { - return - ( - code == HttpStatusCode.Found || - code == HttpStatusCode.Moved || - code == HttpStatusCode.Redirect || - code == HttpStatusCode.RedirectMethod || - code == HttpStatusCode.SeeOther || - code == HttpStatusCode.Ambiguous || - code == HttpStatusCode.MultipleChoices - ); - } + HttpStatusCode.Found + or HttpStatusCode.Moved + or HttpStatusCode.MultipleChoices => requestMethod == HttpMethod.Post, + HttpStatusCode.SeeOther => requestMethod != HttpMethod.Get && requestMethod != HttpMethod.Head, + _ => false + }; // Returns true if the status code shows a server or client error and MaximumRetryCount > 0 - private bool ShouldRetry(HttpStatusCode code) + private static bool ShouldRetry(HttpStatusCode statusCode) => (int)statusCode switch { - int intCode = (int)code; - - return - ( - (intCode == 304 || (intCode >= 400 && intCode <= 599)) && WebSession.MaximumRetryCount > 0 - ); - } + 304 or (>= 400 and <= 599) => true, + _ => false + }; private static HttpMethod GetHttpMethod(WebRequestMethod method) => method switch { diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 index 3538a799b9b..2da345fcd3a 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 @@ -139,6 +139,9 @@ function ExecuteRedirectRequest { [switch] $PreserveAuthorizationOnRedirect, + [switch] + $PreserveHttpMethodOnRedirect, + [ValidateRange(0, [int]::MaxValue)] [int] $MaximumRedirection @@ -153,7 +156,7 @@ function ExecuteRedirectRequest { } elseif ($CustomMethod) { $result.Output = Invoke-WebRequest -Uri $uri -Headers $headers -PreserveAuthorizationOnRedirect:$PreserveAuthorizationOnRedirect.IsPresent -CustomMethod $CustomMethod } else { - $result.Output = Invoke-WebRequest -Uri $uri -Headers $headers -PreserveAuthorizationOnRedirect:$PreserveAuthorizationOnRedirect.IsPresent -Method $Method + $result.Output = Invoke-WebRequest -Uri $uri -Headers $headers -PreserveAuthorizationOnRedirect:$PreserveAuthorizationOnRedirect.IsPresent -PreserveHttpMethodOnRedirect:$PreserveHttpMethodOnRedirect.IsPresent -Method $Method } $result.Content = $result.Output.Content | ConvertFrom-Json } else { @@ -162,7 +165,7 @@ function ExecuteRedirectRequest { } elseif ($CustomMethod) { $result.Output = Invoke-RestMethod -Uri $uri -Headers $headers -PreserveAuthorizationOnRedirect:$PreserveAuthorizationOnRedirect.IsPresent -CustomMethod $CustomMethod } else { - $result.Output = Invoke-RestMethod -Uri $uri -Headers $headers -PreserveAuthorizationOnRedirect:$PreserveAuthorizationOnRedirect.IsPresent -Method $Method + $result.Output = Invoke-RestMethod -Uri $uri -Headers $headers -PreserveAuthorizationOnRedirect:$PreserveAuthorizationOnRedirect.IsPresent -PreserveHttpMethodOnRedirect:$PreserveHttpMethodOnRedirect.IsPresent -Method $Method } # NOTE: $result.Output should already be a PSObject (Invoke-RestMethod converts the returned json automatically) # so simply reference $result.Output @@ -1023,6 +1026,20 @@ Describe "Invoke-WebRequest tests" -Tags "Feature", "RequireAdminOnWindows" { $response.Content.Method | Should -Be $redirectedMethod } + It "Validates Invoke-WebRequest -PreserveHttpMethodOnRedirect keeps the authorization header redirects and do remains POST when it handles the redirect: " -TestCases $redirectTests { + param($redirectType) + $uri = Get-WebListenerUrl -Test 'Redirect' -Query @{type = $redirectType} + $response = ExecuteRedirectRequest -PreserveHttpMethodOnRedirect -Uri $uri -Method 'POST' + + $response.Error | Should -BeNullOrEmpty + # ensure user-agent is present (i.e., no false positives ) + $response.Content.Headers."User-Agent" | Should -Not -BeNullOrEmpty + # ensure Authorization header has been kept. + $response.Content.Headers."Authorization" | Should -BeExactly 'test' + # ensure POST doesn't change. + $response.Content.Method | Should -Be 'POST' + } + It "Validates Invoke-WebRequest handles responses without Location header for requests with Authorization header and redirect: " -TestCases $redirectTests { param($redirectType, $redirectedMethod) # Skip relative test as it is not a valid response type. @@ -2745,6 +2762,20 @@ Describe "Invoke-RestMethod tests" -Tags "Feature", "RequireAdminOnWindows" { $response.Content.Method | Should -Be $redirectedMethod } + It "Validates Invoke-RestMethod -PreserveHttpMethodOnRedirect keeps the authorization header redirects and remains POST when it handles the redirect: " -TestCases $redirectTests { + param($redirectType) + $uri = Get-WebListenerUrl -Test 'Redirect' -Query @{type = $redirectType} + $response = ExecuteRedirectRequest -PreserveHttpMethodOnRedirect -Cmdlet 'Invoke-RestMethod' -Uri $uri -Method 'POST' + + $response.Error | Should -BeNullOrEmpty + # ensure user-agent is present (i.e., no false positives ) + $response.Content.Headers."User-Agent" | Should -Not -BeNullOrEmpty + # ensure Authorization header has been kept. + $response.Content.Headers."Authorization" | Should -BeExactly 'test' + # ensure POST doesn't change. + $response.Content.Method | Should -Be 'POST' + } + It "Validates Invoke-RestMethod handles responses without Location header for requests with Authorization header and redirect: " -TestCases $redirectTests { param($redirectType, $redirectedMethod) # Skip relative test as it is not a valid response type. From 47f8df26b513bc798e21cbacf7957af95710281b Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Tue, 14 Feb 2023 11:33:34 -0800 Subject: [PATCH 359/779] Add verification of R2R at packaging (#19129) Co-authored-by: Aditya Patwardhan --- build.psm1 | 4 + tools/packaging/packaging.psm1 | 253 +++++++++++++++++++++++++++++++-- 2 files changed, 249 insertions(+), 8 deletions(-) diff --git a/build.psm1 b/build.psm1 index 4e1fd0f3f9a..915d4ee0d1d 100644 --- a/build.psm1 +++ b/build.psm1 @@ -795,6 +795,10 @@ function Restore-PSPackage $RestoreArguments += "quiet" } + if ($Options.Runtime -like 'win*') { + $RestoreArguments += "/property:EnableWindowsTargeting=True" + } + if ($InteractiveAuth) { $RestoreArguments += "--interactive" } diff --git a/tools/packaging/packaging.psm1 b/tools/packaging/packaging.psm1 index daa493f19eb..85336f039b3 100644 --- a/tools/packaging/packaging.psm1 +++ b/tools/packaging/packaging.psm1 @@ -20,6 +20,19 @@ $script:netCoreRuntime = 'net7.0' $script:iconFileName = "Powershell_black_64.png" $script:iconPath = Join-Path -path $PSScriptRoot -ChildPath "../../assets/$iconFileName" -Resolve +class R2RVerification { + [ValidateSet('NoR2R','R2R','SdkOnly')] + [string] + $R2RState = 'R2R' + + [System.Reflection.PortableExecutable.Machine] + $Architecture = [System.Reflection.PortableExecutable.Machine]::Amd64 + + [ValidateSet('Linux','Apple','Windows')] + [string] + $OperatingSystem = 'Windows' +} + function Start-PSPackage { [CmdletBinding(DefaultParameterSetName='Version',SupportsShouldProcess=$true)] param( @@ -42,7 +55,6 @@ function Start-PSPackage { # Generate windows downlevel package [ValidateSet("win7-x86", "win7-x64", "win-arm", "win-arm64")] - [ValidateScript({$Environment.IsWindows})] [string] $WindowsRuntime, [ValidateSet('osx-x64', 'osx-arm64')] @@ -321,6 +333,10 @@ function Start-PSPackage { switch ($Type) { "zip" { + $os, $architecture = ($Script:Options.Runtime -split '-') + $peOS = ConvertTo-PEOperatingSystem -OperatingSystem $os + $peArch = ConvertTo-PEArchitecture -Architecture $architecture + $Arguments = @{ PackageNameSuffix = $NameSuffix PackageSourcePath = $Source @@ -328,6 +344,22 @@ function Start-PSPackage { Force = $Force } + if ($architecture -in 'x86', 'x64', 'arm', 'arm64') { + $Arguments += @{ R2RVerification = [R2RVerification]@{ + R2RState = 'R2R' + OperatingSystem = $peOS + Architecture = $peArch + } + } + } else { + $Arguments += @{ R2RVerification = [R2RVerification]@{ + R2RState = 'SdkOnly' + OperatingSystem = $peOS + Architecture = $peArch + } + } + } + if ($PSCmdlet.ShouldProcess("Create Zip Package")) { New-ZipPackage @Arguments } @@ -352,6 +384,11 @@ function Start-PSPackage { PackageSourcePath = $Source PackageVersion = $Version Force = $Force + R2RVerification = [R2RVerification]@{ + R2RState = 'SdkOnly' + OperatingSystem = "Windows" + Architecture = "amd64" + } } if ($PSCmdlet.ShouldProcess("Create Zip Package")) { @@ -365,6 +402,9 @@ function Start-PSPackage { PackageNameSuffix = 'gc' Version = $Version Force = $Force + R2RVerification = [R2RVerification]@{ + R2RState = 'SdkOnly' + } } if ($PSCmdlet.ShouldProcess("Create tar.gz Package")) { @@ -379,6 +419,9 @@ function Start-PSPackage { PackageSourcePath = $Source PackageVersion = $Version Force = $Force + R2RVerification = [R2RVerification]@{ + R2RState = 'NoR2R' + } } if ($PSCmdlet.ShouldProcess("Create Zip Package")) { @@ -391,6 +434,9 @@ function Start-PSPackage { PackageNameSuffix = 'fxdependent' Version = $Version Force = $Force + R2RVerification = [R2RVerification]@{ + R2RState = 'NoR2R' + } } if ($PSCmdlet.ShouldProcess("Create tar.gz Package")) { @@ -400,8 +446,10 @@ function Start-PSPackage { } "msi" { $TargetArchitecture = "x64" + $r2rArchitecture = "amd64" if ($Runtime -match "-x86") { $TargetArchitecture = "x86" + $r2rArchitecture = "i386" } Write-Verbose "TargetArchitecture = $TargetArchitecture" -Verbose @@ -412,7 +460,7 @@ function Start-PSPackage { AssetsPath = "$RepoRoot\assets" ProductTargetArchitecture = $TargetArchitecture Force = $Force - } + } if ($PSCmdlet.ShouldProcess("Create MSI Package")) { New-MSIPackage @Arguments @@ -454,7 +502,20 @@ function Start-PSPackage { } if ($MacOSRuntime) { - $Arguments['Architecture'] = $MacOSRuntime.Split('-')[1] + $architecture = $MacOSRuntime.Split('-')[1] + $Arguments['Architecture'] = $architecture + } + + if ($Script:Options.Runtime -match '(linux|osx).*') { + $os, $architecture = ($Script:Options.Runtime -split '-') + $peOS = ConvertTo-PEOperatingSystem -OperatingSystem $os + $peArch = ConvertTo-PEArchitecture -Architecture $architecture + + $Arguments['R2RVerification'] = [R2RVerification]@{ + R2RState = "R2R" + OperatingSystem = $peOS + Architecture = $peArch + } } if ($PSCmdlet.ShouldProcess("Create tar.gz Package")) { @@ -462,6 +523,7 @@ function Start-PSPackage { } } "tar-arm" { + $peArch = ConvertTo-PEArchitecture -Architecture 'arm' $Arguments = @{ PackageSourcePath = $Source Name = $Name @@ -469,6 +531,11 @@ function Start-PSPackage { Force = $Force Architecture = "arm32" ExcludeSymbolicLinks = $true + R2RVerification = [R2RVerification]@{ + R2RState = 'R2R' + OperatingSystem = "Linux" + Architecture = $peArch + } } if ($PSCmdlet.ShouldProcess("Create tar.gz Package")) { @@ -483,6 +550,11 @@ function Start-PSPackage { Force = $Force Architecture = "arm64" ExcludeSymbolicLinks = $true + R2RVerification = [R2RVerification]@{ + R2RState = 'R2R' + OperatingSystem = "Linux" + Architecture = "arm64" + } } if ($PSCmdlet.ShouldProcess("Create tar.gz Package")) { @@ -497,6 +569,11 @@ function Start-PSPackage { Force = $Force Architecture = "alpine-x64" ExcludeSymbolicLinks = $true + R2RVerification = [R2RVerification]@{ + R2RState = 'R2R' + OperatingSystem = "Linux" + Architecture = "amd64" + } } if ($PSCmdlet.ShouldProcess("Create tar.gz Package")) { @@ -628,7 +705,9 @@ function New-TarballPackage { [switch] $ExcludeSymbolicLinks, - [string] $CurrentLocation = (Get-Location) + [string] $CurrentLocation = (Get-Location), + + [R2RVerification] $R2RVerification ) if ($PackageNameSuffix) { @@ -657,7 +736,7 @@ function New-TarballPackage { } $Staging = "$PSScriptRoot/staging" - New-StagingFolder -StagingPath $Staging -PackageSourcePath $PackageSourcePath + New-StagingFolder -StagingPath $Staging -PackageSourcePath $PackageSourcePath -R2RVerification $R2RVerification if (Get-Command -Name tar -CommandType Application -ErrorAction Ignore) { if ($Force -or $PSCmdlet.ShouldProcess("Create tarball package")) { @@ -1682,15 +1761,60 @@ function New-StagingFolder [Parameter(Mandatory)] [string] $StagingPath, + [Parameter(Mandatory)] [string] $PackageSourcePath, + [string] - $Filter = '*' + $Filter = '*', + + [R2RVerification] + $R2RVerification ) Remove-Item -Recurse -Force -ErrorAction SilentlyContinue $StagingPath Copy-Item -Recurse $PackageSourcePath $StagingPath -Filter $Filter + + $smaPath = Join-Path $StagingPath 'System.Management.Automation.dll' + if ($R2RVerification) { + $smaInfo = Get-PEInfo -File $smaPath + switch ($R2RVerification.R2RState) { + $null { + Write-Verbose "Skipping R2R verification" -Verbose + } + 'R2R' { + Write-Verbose "Verifying R2R was done..." -Verbose + if (!$smaInfo.CrossGen -or $smaInfo.Architecture -ne $R2RVerification.Architecture -or $smaInfo.OS -ne $R2RVerification.OperatingSystem) { + throw "System.Management.Automation.dll is not ReadyToRun for $($R2RVerification.OperatingSystem) $($R2RVerification.Architecture). Actually ($($smaInfo.CrossGen) $($smaInfo.OS) $($smaInfo.Architecture) )" + } + $mismatchedCrossGenedFiles = @(Get-ChildItem -Path $StagingPath -Filter '*.dll' -Recurse | + Get-PEInfo | + Where-Object { $_.CrossGen -and $_.OS -ne $R2RVerification.OperatingSystem -and $_.Architecture -ne $R2RVerification.Architecture }) + if ($mismatchedCrossGenedFiles.Count -gt 0) { + foreach ($file in $mismatchedCrossGenedFiles) { + Write-Warning "Misconfigured ReadyToRun file found. Expected $($R2RVerification.OperatingSystem) $($R2RVerification.Architecture). Actual ($($file.OS) $($file.Architecture) ) " + } + throw "Unexpected ReadyToRun files found." + } + } + 'NoR2R' { + Write-Verbose "Verifying no R2R was done..." -Verbose + $crossGenedFiles = @(Get-ChildItem -Path $StagingPath -Filter '*.dll' -Recurse | + Get-PEInfo | + Where-Object { $_.CrossGen }) + if ($crossGenedFiles.Count -gt 0) { + throw "Unexpected ReadyToRun files found: $($crossGenedFiles | ForEach-Object { $_.Path })" + } + } + 'SdkOnly' { + Write-Verbose "Verifying no R2R was done on SMA..." -Verbose + if ($smaInfo.CrossGen) { + throw "System.Management.Automation.dll should not be ReadyToRun" + } + } + } + } } # Function to create a zip file for Nano Server and xcopy deployment @@ -1718,7 +1842,9 @@ function New-ZipPackage [switch] $Force, - [string] $CurrentLocation = (Get-Location) + [string] $CurrentLocation = (Get-Location), + + [R2RVerification] $R2RVerification = [R2RVerification]::new() ) $ProductSemanticVersion = Get-PackageSemanticVersion -Version $PackageVersion @@ -1745,7 +1871,7 @@ function New-ZipPackage if ($PSCmdlet.ShouldProcess("Create zip package")) { $staging = "$PSScriptRoot/staging" - New-StagingFolder -StagingPath $staging -PackageSourcePath $PackageSourcePath + New-StagingFolder -StagingPath $staging -PackageSourcePath $PackageSourcePath -R2RVerification $R2RVerification Compress-Archive -Path $staging\* -DestinationPath $zipLocationPath } @@ -1816,6 +1942,8 @@ function New-PdbZipPackage if ($PSCmdlet.ShouldProcess("Create zip package")) { $staging = "$PSScriptRoot/staging" + + # We should NOT R2R verify the PDB zip New-StagingFolder -StagingPath $staging -PackageSourcePath $PackageSourcePath -Filter *.pdb Compress-Archive -Path $staging\* -DestinationPath $zipLocationPath @@ -4825,3 +4953,112 @@ function Test-PackageManifest { } } } + +# Get the PE information for a file +function Get-PEInfo { + [CmdletBinding()] + param([Parameter(ValueFromPipeline = $true)][string] $File) + BEGIN { + # retrieved from ILCompiler.PEWriter.MachineOSOverride + enum MachineOSOverride { + Windows = 0 + SunOS = 6546 + NetBSD = 6547 + Apple = 17988 + Linux = 31609 + FreeBSD = 44484 + } + + # The information we want + class PsPeInfo { + [string]$File + [bool]$CrossGen + [Nullable[MachineOSOverride]]$OS + [System.Reflection.PortableExecutable.Machine]$Architecture + [Nullable[System.Reflection.PortableExecutable.CorFlags]]$Flags + } + + } + PROCESS { + $filePath = (get-item $file).fullname + $CrossGenFlag = 4 + try { + $stream = [System.IO.FileStream]::new($FilePath, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read) + $peReader = [System.Reflection.PortableExecutable.PEReader]::new($stream) + $flags = $peReader.PEHeaders.CorHeader.Flags + if (-not $flags) { + Write-Warning "$filePath is not a managed assembly" + } + $machine = $peReader.PEHeaders.CoffHeader.Machine + if (-not $machine) { + throw "Null Machine" + } + } catch { + $er = [system.management.automation.errorrecord]::new(([InvalidOperationException]::new($_)), "Get-PEInfo:InvalidOperation", "InvalidOperation", $filePath) + $PSCmdlet.WriteError($er) + return + } finally { + if ($peReader) { + $peReader.Dispose() + } + } + + [ushort]$r2rOsArch = $machine + + $RealOS = $null + $realarch = "unknown" + foreach ($os in [enum]::GetValues([MachineOSOverride])) { + foreach ($architecture in [Enum]::GetValues([System.Reflection.PortableExecutable.Machine])) { + if (([ushort]$architecture -BXOR [ushort]$os) -eq [ushort]$r2rOsArch) { + $realOS = $os + $realArch = $architecture + + [PsPeInfo]@{ + File = $File + OS = $realos + Architecture = $realarch + CrossGen = [bool]($flags -band $CrossGenFlag) + Flags = $flags + } + return + } + } + } + } +} + +function ConvertTo-PEArchitecture { + [CmdletBinding()] + param( + [Parameter(ValueFromPipeline = $true)] + [string] + $Architecture + ) + + PROCESS { + switch ($Architecture) { + "x86" { "I386" } + "x64" { "AMD64" } + "arm" { "ArmThumb2" } + default { $Architecture } + } + } +} + +function ConvertTo-PEOperatingSystem { + [CmdletBinding()] + param( + [Parameter(ValueFromPipeline = $true)] + [string] + $OperatingSystem + ) + + PROCESS { + switch -regex ($OperatingSystem) { + "win.*" { "Windows" } + "Linux" { "Linux" } + "OSX" { "Apple" } + default { $OperatingSystem } + } + } +} From a66a812ca89f0f8d26700478aa975786c6a9a40d Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Tue, 14 Feb 2023 16:42:51 -0800 Subject: [PATCH 360/779] Fix a typo in `pwsh` help content (#19153) --- .../resources/ManagedEntranceStrings.resx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/ManagedEntranceStrings.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/ManagedEntranceStrings.resx index c6f96715fb0..e435f7662cc 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/resources/ManagedEntranceStrings.resx +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/ManagedEntranceStrings.resx @@ -443,7 +443,7 @@ All parameters are case-insensitive. Example: "pwsh -o XML -c Get-Date" - When called withing a PowerShell session, you get deserialized objects as + When called within a PowerShell session, you get deserialized objects as output rather plain strings. When called from other shells, the output is string data formatted as CLIXML text. From 23733de1744571887033493919c84a23c69f9e96 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 15 Feb 2023 11:17:34 -0800 Subject: [PATCH 361/779] Bump `Microsoft.Extensions.ObjectPool` from 7.0.2 to 7.0.3 (#19155) --- src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj b/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj index 1b75056dd93..ec03c9c23a7 100644 --- a/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj +++ b/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj @@ -17,7 +17,7 @@ - + From 540c9e729f2a4a8b83c2fd7785671b2afed5bd69 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Thu, 16 Feb 2023 15:13:34 -0800 Subject: [PATCH 362/779] Update the cgmanifest (#19165) Co-authored-by: adityapatwardhan --- tools/cgmanifest.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tools/cgmanifest.json b/tools/cgmanifest.json index d38c15ae461..eb29d157d4d 100644 --- a/tools/cgmanifest.json +++ b/tools/cgmanifest.json @@ -1,4 +1,5 @@ { + "$schema": "https://json.schemastore.org/component-detection-manifest.json", "Registrations": [ { "Component": { @@ -105,7 +106,7 @@ "Type": "nuget", "Nuget": { "Name": "Microsoft.Extensions.ObjectPool", - "Version": "7.0.2" + "Version": "7.0.3" } }, "DevelopmentDependency": false @@ -1400,6 +1401,5 @@ }, "DevelopmentDependency": false } - ], - "$schema": "https://json.schemastore.org/component-detection-manifest.json" + ] } From 27313be95bab73f3066ab7382240d72e2572dddb Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Thu, 16 Feb 2023 15:23:12 -0800 Subject: [PATCH 363/779] Add URL for all distributions (#19159) * Add URL for all distributions * Make url compatible --- tools/packages.microsoft.com/mapping.json | 79 ++++++++++++++++------- 1 file changed, 55 insertions(+), 24 deletions(-) diff --git a/tools/packages.microsoft.com/mapping.json b/tools/packages.microsoft.com/mapping.json index 8bb238e1e8f..9ae06c5f1b8 100644 --- a/tools/packages.microsoft.com/mapping.json +++ b/tools/packages.microsoft.com/mapping.json @@ -1,58 +1,89 @@ { - "Packages" : [ + "Packages": [ { "url": "microsoft-centos8-prod", - "distribution" : ["centos"], - "PackageFormat" : "PACKAGE_NAME-POWERSHELL_RELEASE-1.rh.x86_64.rpm" + "distribution": [ + "centos" + ], + "PackageFormat": "PACKAGE_NAME-POWERSHELL_RELEASE-1.rh.x86_64.rpm" }, { "url": "microsoft-rhel8.0-prod", - "distribution" : ["trusty"], - "PackageFormat" : "PACKAGE_NAME-POWERSHELL_RELEASE-1.rh.x86_64.rpm" + "distribution": [ + "trusty" + ], + "PackageFormat": "PACKAGE_NAME-POWERSHELL_RELEASE-1.rh.x86_64.rpm" }, { "url": "microsoft-rhel7.3-prod", - "distribution" : ["trusty"], - "PackageFormat" : "PACKAGE_NAME-POWERSHELL_RELEASE-1.rh.x86_64.rpm" + "distribution": [ + "trusty" + ], + "PackageFormat": "PACKAGE_NAME-POWERSHELL_RELEASE-1.rh.x86_64.rpm" }, { "url": "cbl-mariner-2.0-prod-Microsoft-x86_64", - "distribution" : ["bionic"], - "PackageFormat" : "PACKAGE_NAME-POWERSHELL_RELEASE-1.cm.x86_64.rpm", - "channel" : "stable" + "distribution": [ + "bionic" + ], + "PackageFormat": "PACKAGE_NAME-POWERSHELL_RELEASE-1.cm.x86_64.rpm", + "channel": "stable" }, { "url": "cbl-mariner-2.0-preview-Microsoft-x86_64", - "distribution" : ["bionic"], - "PackageFormat" : "PACKAGE_NAME-POWERSHELL_RELEASE-1.cm.x86_64.rpm", - "channel" : "preview" + "distribution": [ + "bionic" + ], + "PackageFormat": "PACKAGE_NAME-POWERSHELL_RELEASE-1.cm.x86_64.rpm", + "channel": "preview" }, { - "distribution" : ["stretch"], - "PackageFormat" : "PACKAGE_NAME_POWERSHELL_RELEASE-1.deb_amd64.deb" + "url": "microsoft-debian-stretch-prod", + "distribution": [ + "stretch" + ], + "PackageFormat": "PACKAGE_NAME_POWERSHELL_RELEASE-1.deb_amd64.deb" }, { - "distribution" : ["buster"], - "PackageFormat" : "PACKAGE_NAME_POWERSHELL_RELEASE-1.deb_amd64.deb" + "url": "microsoft-debian-buster-prod", + "distribution": [ + "buster" + ], + "PackageFormat": "PACKAGE_NAME_POWERSHELL_RELEASE-1.deb_amd64.deb" }, { - "distribution" : ["bionic"], - "PackageFormat" : "PACKAGE_NAME_POWERSHELL_RELEASE-1.deb_amd64.deb" + "url": "microsoft-ubuntu-bionic-prod", + "distribution": [ + "bionic" + ], + "PackageFormat": "PACKAGE_NAME_POWERSHELL_RELEASE-1.deb_amd64.deb" }, { - "distribution" : ["jammy"], - "PackageFormat" : "PACKAGE_NAME_POWERSHELL_RELEASE-1.deb_amd64.deb" + "url": "microsoft-ubuntu-jammy-prod", + "distribution": [ + "jammy" + ], + "PackageFormat": "PACKAGE_NAME_POWERSHELL_RELEASE-1.deb_amd64.deb" }, { - "distribution": ["focal"], + "url": "microsoft-ubuntu-focal-prod", + "distribution": [ + "focal" + ], "PackageFormat": "PACKAGE_NAME_POWERSHELL_RELEASE-1.deb_amd64.deb" }, { - "distribution": ["xenial"], + "url": "microsoft-ubuntu-xenial-prod", + "distribution": [ + "xenial" + ], "PackageFormat": "PACKAGE_NAME_POWERSHELL_RELEASE-1.deb_amd64.deb" }, { - "distribution": ["bullseye"], + "url": "microsoft-debian-bullseye-prod", + "distribution": [ + "bullseye" + ], "PackageFormat": "PACKAGE_NAME_POWERSHELL_RELEASE-1.deb_amd64.deb" } ] From 5b9a22581e365b713ab86f71851bdbc60e92a219 Mon Sep 17 00:00:00 2001 From: Ikko Eltociear Ashimine Date: Wed, 22 Feb 2023 03:03:39 +0900 Subject: [PATCH 364/779] Fix a typo in `InitialSessionState.cs` (#19177) --- src/System.Management.Automation/engine/InitialSessionState.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/System.Management.Automation/engine/InitialSessionState.cs b/src/System.Management.Automation/engine/InitialSessionState.cs index 31b8f549b4f..23383826bae 100644 --- a/src/System.Management.Automation/engine/InitialSessionState.cs +++ b/src/System.Management.Automation/engine/InitialSessionState.cs @@ -2921,7 +2921,7 @@ private Exception ProcessPowerShellCommand(PowerShell psToInvoke, Runspace initi } finally { - // Restore the langauge mode, but not if it was altered by the startup script itself. + // Restore the language mode, but not if it was altered by the startup script itself. if (initializedRunspace.SessionStateProxy.LanguageMode == PSLanguageMode.FullLanguage) { initializedRunspace.SessionStateProxy.LanguageMode = originalLanguageMode; From 0be3eeac38e3065fb4cb7dd49d1c86aee4cb04fc Mon Sep 17 00:00:00 2001 From: Armaan Mcleod Date: Wed, 22 Feb 2023 05:14:08 +1100 Subject: [PATCH 365/779] Add `-Path` and `-LiteralPath` parameters to `Test-Json` cmdlet (#19042) --- .../commands/utility/TestJsonCommand.cs | 103 ++++++++++++- .../Test-Json.Tests.ps1 | 145 +++++++++++++++++- 2 files changed, 235 insertions(+), 13 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/TestJsonCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/TestJsonCommand.cs index 9d792b91233..fc416d9772e 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/TestJsonCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/TestJsonCommand.cs @@ -16,19 +16,63 @@ namespace Microsoft.PowerShell.Commands /// /// This class implements Test-Json command. /// - [Cmdlet(VerbsDiagnostic.Test, "Json", DefaultParameterSetName = ParameterAttribute.AllParameterSets, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096609")] + [Cmdlet(VerbsDiagnostic.Test, "Json", DefaultParameterSetName = JsonStringParameterSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096609")] [OutputType(typeof(bool))] public class TestJsonCommand : PSCmdlet { - private const string SchemaFileParameterSet = "SchemaFile"; - private const string SchemaStringParameterSet = "SchemaString"; + #region Parameter Set Names + + private const string JsonStringParameterSet = "JsonString"; + private const string JsonStringWithSchemaStringParameterSet = "JsonStringWithSchemaString"; + private const string JsonStringWithSchemaFileParameterSet = "JsonStringWithSchemaFile"; + private const string JsonPathParameterSet = "JsonPath"; + private const string JsonPathWithSchemaStringParameterSet = "JsonPathWithSchemaString"; + private const string JsonPathWithSchemaFileParameterSet = "JsonPathWithSchemaFile"; + private const string JsonLiteralPathParameterSet = "JsonLiteralPath"; + private const string JsonLiteralPathWithSchemaStringParameterSet = "JsonLiteralPathWithSchemaString"; + private const string JsonLiteralPathWithSchemaFileParameterSet = "JsonLiteralPathWithSchemaFile"; + + #endregion + + #region Parameters /// /// Gets or sets JSON string to be validated. /// - [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true)] + [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ParameterSetName = JsonStringParameterSet)] + [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ParameterSetName = JsonStringWithSchemaStringParameterSet)] + [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ParameterSetName = JsonStringWithSchemaFileParameterSet)] public string Json { get; set; } + /// + /// Gets or sets JSON file path to be validated. + /// + [Parameter(Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = JsonPathParameterSet)] + [Parameter(Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = JsonPathWithSchemaStringParameterSet)] + [Parameter(Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = JsonPathWithSchemaFileParameterSet)] + public string Path { get; set; } + + /// + /// Gets or sets JSON literal file path to be validated. + /// + [Parameter(Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = JsonLiteralPathParameterSet)] + [Parameter(Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = JsonLiteralPathWithSchemaStringParameterSet)] + [Parameter(Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = JsonLiteralPathWithSchemaFileParameterSet)] + [Alias("PSPath", "LP")] + public string LiteralPath + { + get + { + return _isLiteralPath ? Path : null; + } + + set + { + _isLiteralPath = true; + Path = value; + } + } + /// /// Gets or sets schema to validate the JSON against. /// This is optional parameter. @@ -37,7 +81,9 @@ public class TestJsonCommand : PSCmdlet /// then validates the JSON against the schema. Before testing the JSON string, /// the cmdlet parses the schema doing implicitly check the schema too. /// - [Parameter(Position = 1, ParameterSetName = SchemaStringParameterSet)] + [Parameter(Position = 1, Mandatory = true, ParameterSetName = JsonStringWithSchemaStringParameterSet)] + [Parameter(Position = 1, Mandatory = true, ParameterSetName = JsonPathWithSchemaStringParameterSet)] + [Parameter(Position = 1, Mandatory = true, ParameterSetName = JsonLiteralPathWithSchemaStringParameterSet)] [ValidateNotNullOrEmpty] public string Schema { get; set; } @@ -45,10 +91,17 @@ public class TestJsonCommand : PSCmdlet /// Gets or sets path to the file containing schema to validate the JSON string against. /// This is optional parameter. /// - [Parameter(Position = 1, ParameterSetName = SchemaFileParameterSet)] + [Parameter(Position = 1, Mandatory = true, ParameterSetName = JsonStringWithSchemaFileParameterSet)] + [Parameter(Position = 1, Mandatory = true, ParameterSetName = JsonPathWithSchemaFileParameterSet)] + [Parameter(Position = 1, Mandatory = true, ParameterSetName = JsonLiteralPathWithSchemaFileParameterSet)] [ValidateNotNullOrEmpty] public string SchemaFile { get; set; } + #endregion + + #region Private Members + + private bool _isLiteralPath = false; private JsonSchema _jschema; /// @@ -72,6 +125,10 @@ private static bool UnwrapException(Exception e) return true; } + #endregion + + #region Protected Members + /// /// Prepare a JSON schema. /// @@ -137,10 +194,38 @@ e is SecurityException protected override void ProcessRecord() { bool result = true; + string jsonToParse = string.Empty; + + if (Json != null) + { + jsonToParse = Json; + } + else if (Path != null) + { + string resolvedPath = PathUtils.ResolveFilePath(Path, this, _isLiteralPath); + + if (!File.Exists(resolvedPath)) + { + ItemNotFoundException exception = new( + Path, + "PathNotFound", + SessionStateStrings.PathNotFound); + + ThrowTerminatingError(exception.ErrorRecord); + } + + jsonToParse = File.ReadAllText(resolvedPath); + } + + if (string.IsNullOrWhiteSpace(jsonToParse)) + { + WriteObject(false); + return; + } try { - var parsedJson = JToken.Parse(Json); + var parsedJson = JToken.Parse(jsonToParse); if (_jschema != null) { @@ -165,10 +250,12 @@ protected override void ProcessRecord() result = false; Exception exception = new(TestJsonCmdletStrings.InvalidJson, exc); - WriteError(new ErrorRecord(exception, "InvalidJson", ErrorCategory.InvalidData, Json)); + WriteError(new ErrorRecord(exception, "InvalidJson", ErrorCategory.InvalidData, jsonToParse)); } WriteObject(result); } + + #endregion } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Test-Json.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Test-Json.Tests.ps1 index 2ea76f5826e..9e949e0215a 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Test-Json.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Test-Json.Tests.ps1 @@ -3,11 +3,11 @@ Describe "Test-Json" -Tags "CI" { BeforeAll { - $validSchemaJsonPath = Join-Path -Path (Join-Path $PSScriptRoot -ChildPath assets) -ChildPath valid_schema_reference.json - - $invalidSchemaJsonPath = Join-Path -Path (Join-Path $PSScriptRoot -ChildPath assets) -ChildPath invalid_schema_reference.json - - $missingSchemaJsonPath = Join-Path -Path (Join-Path $PSScriptRoot -ChildPath assets) -ChildPath no_such_file.json + $assetsPath = Join-Path $PSScriptRoot -ChildPath assets + $validSchemaJsonPath = Join-Path -Path $assetsPath -ChildPath valid_schema_reference.json + $invalidSchemaJsonPath = Join-Path -Path $assetsPath -ChildPath invalid_schema_reference.json + $missingSchemaJsonPath = Join-Path -Path $assetsPath -ChildPath no_such_file.json + $missingJsonPath = Join-Path -Path $assetsPath -ChildPath no_such_file.json $validSchemaJson = @" { @@ -65,48 +65,139 @@ Describe "Test-Json" -Tags "CI" { errorNode } "@ + + $validJsonPath = Join-Path -Path $TestDrive -ChildPath 'validJson.json' + $validLiteralJsonPath = Join-Path -Path $TestDrive -ChildPath "[valid]Json.json" + $invalidNodeInJsonPath = Join-Path -Path $TestDrive -ChildPath 'invalidNodeInJson.json' + $invalidTypeInJsonPath = Join-Path -Path $TestDrive -ChildPath 'invalidTypeInJson.json' + $invalidTypeInJson2Path = Join-Path -Path $TestDrive -ChildPath 'invalidTypeInJson2.json' + $invalidEmptyJsonPath = Join-Path -Path $TestDrive -ChildPath 'emptyJson.json' + + Set-Content -Path $validJsonPath -Value $validJson + Set-Content -LiteralPath $validLiteralJsonPath -Value $validJson + Set-Content -Path $invalidNodeInJsonPath -Value $invalidNodeInJson + Set-Content -Path $invalidTypeInJsonPath -Value $invalidTypeInJson + Set-Content -Path $invalidTypeInJson2Path -Value $invalidTypeInJson2 + New-Item -Path $invalidEmptyJsonPath -ItemType File } It "Missing JSON schema file doesn't exist" { Test-Path -LiteralPath $missingSchemaJsonPath | Should -BeFalse } + It "Missing JSON file doesn't exist" { + Test-Path -LiteralPath $missingJsonPath | Should -BeFalse + } + It "Json is valid" { Test-Json -Json $validJson | Should -BeTrue + ($validJson | Test-Json) | Should -BeTrue } It "Json is valid against a valid schema from string" { Test-Json -Json $validJson -Schema $validSchemaJson | Should -BeTrue + ($validJson | Test-Json -Schema $validSchemaJson) | Should -BeTrue } It "Json is valid against a valid schema from file" { Test-Json -Json $validJson -SchemaFile $validSchemaJsonPath | Should -BeTrue + ($validJson | Test-Json -SchemaFile $validSchemaJsonPath) | Should -BeTrue + } + + It "Json file specified using -Path is valid" { + Test-Json -Path $validJsonPath | Should -BeTrue + } + + It "Json file specified using -LiteralPath is valid" { + Test-Json -LiteralPath $validLiteralJsonPath | Should -BeTrue + } + + It "Json file specified using LiteralPath aliases -PSPath and -LP is valid" { + Test-Json -PSPath $validLiteralJsonPath | Should -BeTrue + Test-Json -LP $validLiteralJsonPath | Should -BeTrue + } + + It "Json file specified using -Path from pipeline is valid" { + (Get-ChildItem -Path $validJsonPath -File | Test-Json) | Should -BeTrue + } + + It "Json file specified using -LiteralPath from pipeline is valid" { + (Get-ChildItem -LiteralPath $validLiteralJsonPath -File | Test-Json) | Should -BeTrue + } + + It "Json file is valid against a valid schema from string" { + Test-Json -Path $validJsonPath -Schema $validSchemaJson | Should -BeTrue + } + + It "Json file is valid against a valid schema from file" { + Test-Json -Path $validJsonPath -SchemaFile $validSchemaJsonPath | Should -BeTrue } It "Json is invalid" { Test-Json -Json $invalidNodeInJson -ErrorAction SilentlyContinue | Should -BeFalse + ($invalidNodeInJson | Test-Json -ErrorAction SilentlyContinue) | Should -BeFalse } It "Json is invalid against a valid schema from string" { Test-Json -Json $invalidTypeInJson2 -Schema $validSchemaJson -ErrorAction SilentlyContinue | Should -BeFalse + ($invalidTypeInJson2 | Test-Json -Schema $validSchemaJson -ErrorAction SilentlyContinue) | Should -BeFalse + Test-Json -Json $invalidNodeInJson -Schema $validSchemaJson -ErrorAction SilentlyContinue | Should -BeFalse + ($invalidNodeInJson | Test-Json -Schema $validSchemaJson -ErrorAction SilentlyContinue) | Should -BeFalse } It "Json is invalid against a valid schema from file" { Test-Json -Json $invalidTypeInJson2 -SchemaFile $validSchemaJsonPath -ErrorAction SilentlyContinue | Should -BeFalse + ($invalidTypeInJson2 | Test-Json -SchemaFile $validSchemaJsonPath -ErrorAction SilentlyContinue) | Should -BeFalse + Test-Json -Json $invalidNodeInJson -SchemaFile $validSchemaJsonPath -ErrorAction SilentlyContinue | Should -BeFalse + ($invalidNodeInJson | Test-Json -SchemaFile $validSchemaJsonPath -ErrorAction SilentlyContinue) | Should -BeFalse + } + + It "Json file is invalid against a valid schema from file" { + Test-Json -Path $invalidTypeInJson2Path -SchemaFile $validSchemaJsonPath -ErrorAction SilentlyContinue | Should -BeFalse + Test-Json -Path $invalidNodeInJsonPath -SchemaFile $validSchemaJsonPath -ErrorAction SilentlyContinue | Should -BeFalse + } + + It "Json file is invalid" { + Test-Json -Path $invalidNodeInJsonPath -ErrorAction SilentlyContinue | Should -BeFalse + } + + It "Json file is invalid against a valid schema from string" { + Test-Json -Path $invalidTypeInJson2Path -Schema $validSchemaJson -ErrorAction SilentlyContinue | Should -BeFalse + Test-Json -Path $invalidNodeInJsonPath -Schema $validSchemaJson -ErrorAction SilentlyContinue | Should -BeFalse + } + + It "Json file is invalid against an empty file" { + Test-Json -Path $invalidEmptyJsonPath -ErrorAction SilentlyContinue | Should -BeFalse } It "Test-Json throw if a schema from string is invalid" { { Test-Json -Json $validJson -Schema $invalidSchemaJson -ErrorAction Stop } | Should -Throw -ErrorId "InvalidJsonSchema,Microsoft.PowerShell.Commands.TestJsonCommand" + { Test-Json -Path $validJsonPath -Schema $invalidSchemaJson -ErrorAction Stop } | Should -Throw -ErrorId "InvalidJsonSchema,Microsoft.PowerShell.Commands.TestJsonCommand" } It "Test-Json throw if a schema from file is invalid" { { Test-Json -Json $validJson -SchemaFile $invalidSchemaJsonPath -ErrorAction Stop } | Should -Throw -ErrorId "InvalidJsonSchema,Microsoft.PowerShell.Commands.TestJsonCommand" + { Test-Json -Path $validJsonPath -SchemaFile $invalidSchemaJsonPath -ErrorAction Stop } | Should -Throw -ErrorId "InvalidJsonSchema,Microsoft.PowerShell.Commands.TestJsonCommand" } It "Test-Json throw if a path to a schema from file is invalid" { { Test-Json -Json $validJson -SchemaFile $missingSchemaJsonPath -ErrorAction Stop } | Should -Throw -ErrorId "JsonSchemaFileOpenFailure,Microsoft.PowerShell.Commands.TestJsonCommand" + { Test-Json -Path $validJsonPath -SchemaFile $missingSchemaJsonPath -ErrorAction Stop } | Should -Throw -ErrorId "JsonSchemaFileOpenFailure,Microsoft.PowerShell.Commands.TestJsonCommand" + } + + It "Test-Json throw if a path from file is invalid" { + { Test-Json -Path $missingJsonPath -ErrorAction Stop } | Should -Throw -ErrorId "PathNotFound,Microsoft.PowerShell.Commands.TestJsonCommand" + } + + It "Test-Json throw if a path from file using -Path is a literal path" { + { Test-Json -Path $validLiteralJsonPath -ErrorAction Stop } | Should -Throw -ErrorId "FileOpenFailure,Microsoft.PowerShell.Commands.TestJsonCommand" + } + + It "Json file throw if a path from file using -LiteralPath is a wildcard or regular expression" { + { Test-Json -LiteralPath (Join-Path -Path $TestDrive -ChildPath "*Json.json") -ErrorAction Stop } | Should -Throw -ErrorId "PathNotFound,Microsoft.PowerShell.Commands.TestJsonCommand" + { Test-Json -LiteralPath (Join-Path -Path $TestDrive -ChildPath "[a-z]Json.json") -ErrorAction Stop } | Should -Throw -ErrorId "PathNotFound,Microsoft.PowerShell.Commands.TestJsonCommand" } It "Test-Json write an error on invalid () Json against a valid schema from string" -TestCases @( @@ -133,6 +224,30 @@ Describe "Test-Json" -Tags "CI" { $errorVar.FullyQualifiedErrorId | Should -BeExactly $errorId } + It "Test-Json write an error on invalid () Json file against a valid schema from string" -TestCases @( + @{ name = "type"; json = $invalidTypeInJsonPath; errorId = "InvalidJsonAgainstSchema,Microsoft.PowerShell.Commands.TestJsonCommand" } + @{ name = "node"; json = $invalidNodeInJsonPath; errorId = "InvalidJson,Microsoft.PowerShell.Commands.TestJsonCommand" } + ) { + param ($json, $errorId) + + $errorVar = $null + Test-Json -Path $json -Schema $validSchemaJson -ErrorVariable errorVar -ErrorAction SilentlyContinue + + $errorVar.FullyQualifiedErrorId | Should -BeExactly $errorId + } + + It "Test-Json write an error on invalid () Json file against a valid schema from file" -TestCases @( + @{ name = "type"; json = $invalidTypeInJsonPath; errorId = "InvalidJsonAgainstSchema,Microsoft.PowerShell.Commands.TestJsonCommand" } + @{ name = "node"; json = $invalidNodeInJsonPath; errorId = "InvalidJson,Microsoft.PowerShell.Commands.TestJsonCommand" } + ) { + param ($json, $errorId) + + $errorVar = $null + Test-Json -Path $json -SchemaFile $validSchemaJsonPath -ErrorVariable errorVar -ErrorAction SilentlyContinue + + $errorVar.FullyQualifiedErrorId | Should -BeExactly $errorId + } + It "Test-Json return all errors when check invalid Json against a valid schema from string" { $errorVar = $null Test-Json -Json $invalidTypeInJson2 -Schema $validSchemaJson -ErrorVariable errorVar -ErrorAction SilentlyContinue @@ -153,6 +268,26 @@ Describe "Test-Json" -Tags "CI" { $errorVar[1].FullyQualifiedErrorId | Should -BeExactly "InvalidJsonAgainstSchema,Microsoft.PowerShell.Commands.TestJsonCommand" } + It "Test-Json return all errors when check invalid Json file against a valid schema from string" { + $errorVar = $null + Test-Json -Path $invalidTypeInJson2Path -Schema $validSchemaJson -ErrorVariable errorVar -ErrorAction SilentlyContinue + + # '$invalidTypeInJson2Path' contains two errors in property types. + $errorVar.Count | Should -Be 2 + $errorVar[0].FullyQualifiedErrorId | Should -BeExactly "InvalidJsonAgainstSchema,Microsoft.PowerShell.Commands.TestJsonCommand" + $errorVar[1].FullyQualifiedErrorId | Should -BeExactly "InvalidJsonAgainstSchema,Microsoft.PowerShell.Commands.TestJsonCommand" + } + + It "Test-Json return all errors when check invalid Json file against a valid schema from file" { + $errorVar = $null + Test-Json -Path $invalidTypeInJson2Path -SchemaFile $validSchemaJsonPath -ErrorVariable errorVar -ErrorAction SilentlyContinue + + # '$invalidTypeInJson2Path' contains two errors in property types. + $errorVar.Count | Should -Be 2 + $errorVar[0].FullyQualifiedErrorId | Should -BeExactly "InvalidJsonAgainstSchema,Microsoft.PowerShell.Commands.TestJsonCommand" + $errorVar[1].FullyQualifiedErrorId | Should -BeExactly "InvalidJsonAgainstSchema,Microsoft.PowerShell.Commands.TestJsonCommand" + } + It 'Test-Json recognizes non-object types: ' -TestCases @( @{ name = 'number'; value = 1; expected = 'number' } @{ name = '"true"'; value = '"true"'; expected = 'string' } From 91d8fb0367e302c0145b057ee62854277e4ff082 Mon Sep 17 00:00:00 2001 From: Trey <13120514+syntax-tm@users.noreply.github.com> Date: Wed, 22 Feb 2023 11:09:04 -0600 Subject: [PATCH 366/779] Corrected some minor spelling mistakes (#19176) --- .../CimSessionProxy.cs | 2 +- .../engine/DefaultCommandRuntime.cs | 2 +- .../engine/parser/tokenizer.cs | 4 ++-- .../engine/remoting/common/remotingexceptions.cs | 12 ++++++------ .../engine/Basic/ValidateAttributes.Tests.ps1 | 2 +- 5 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs index 64f5634f970..630bb34dfb1 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs @@ -1493,7 +1493,7 @@ protected virtual void PostOperationDeleteEvent(OperationEventArgs args) /// The CimSession object managed by this proxy object, /// which is either created by constructor OR passed in by caller. /// The session will be closed while disposing this proxy object - /// if it is created by constuctor. + /// if it is created by constructor. /// internal CimSession CimSession { get; private set; } diff --git a/src/System.Management.Automation/engine/DefaultCommandRuntime.cs b/src/System.Management.Automation/engine/DefaultCommandRuntime.cs index 88a2a2ee427..746d809d831 100644 --- a/src/System.Management.Automation/engine/DefaultCommandRuntime.cs +++ b/src/System.Management.Automation/engine/DefaultCommandRuntime.cs @@ -64,7 +64,7 @@ public void WriteObject(object sendToPipeline) /// /// Default implementation of the enumerated WriteObject. Either way, the - /// objects are added to the list passed to this object in the constuctor. + /// objects are added to the list passed to this object in the constructor. /// /// Object to write. /// If true, the collection is enumerated, otherwise diff --git a/src/System.Management.Automation/engine/parser/tokenizer.cs b/src/System.Management.Automation/engine/parser/tokenizer.cs index c0c150cdd42..8b19c7dc385 100644 --- a/src/System.Management.Automation/engine/parser/tokenizer.cs +++ b/src/System.Management.Automation/engine/parser/tokenizer.cs @@ -314,7 +314,7 @@ public DynamicKeyword Copy() public bool HasReservedProperties { get; set; } /// - /// A list of the properties allowed for this constuctor. + /// A list of the properties allowed for this constructor. /// public Dictionary Properties { @@ -327,7 +327,7 @@ public Dictionary Properties private Dictionary _properties; /// - /// A list of the parameters allowed for this constuctor. + /// A list of the parameters allowed for this constructor. /// public Dictionary Parameters { diff --git a/src/System.Management.Automation/engine/remoting/common/remotingexceptions.cs b/src/System.Management.Automation/engine/remoting/common/remotingexceptions.cs index 9e92c045896..fbecd29a6f0 100644 --- a/src/System.Management.Automation/engine/remoting/common/remotingexceptions.cs +++ b/src/System.Management.Automation/engine/remoting/common/remotingexceptions.cs @@ -297,7 +297,7 @@ public PSRemotingDataStructureException() } /// - /// This constuctor takes a localized string as the error message. + /// This constructor takes a localized string as the error message. /// /// /// A localized string as an error message. @@ -309,7 +309,7 @@ public PSRemotingDataStructureException(string message) } /// - /// This constuctor takes a localized string as the error message, and an inner exception. + /// This constructor takes a localized string as the error message, and an inner exception. /// /// /// A localized string as an error message. @@ -339,7 +339,7 @@ internal PSRemotingDataStructureException(string resourceString, params object[] } /// - /// This constuctor takes an inner exception and an error id. + /// This constructor takes an inner exception and an error id. /// /// /// Inner exception. @@ -445,7 +445,7 @@ internal PSRemotingTransportException(PSRemotingErrorId errorId, string resource } /// - /// This constuctor takes an inner exception and an error id. + /// This constructor takes an inner exception and an error id. /// /// /// Inner exception. @@ -588,7 +588,7 @@ public PSRemotingTransportRedirectException(string message, Exception innerExcep } /// - /// This constuctor takes an inner exception and an error id. + /// This constructor takes an inner exception and an error id. /// /// /// Inner exception. @@ -685,7 +685,7 @@ public class PSDirectException : RuntimeException #region Constructor /// - /// This constuctor takes a localized string as the error message. + /// This constructor takes a localized string as the error message. /// /// /// A localized string as an error message. diff --git a/test/powershell/engine/Basic/ValidateAttributes.Tests.ps1 b/test/powershell/engine/Basic/ValidateAttributes.Tests.ps1 index 310465a03c2..c8d56786d51 100644 --- a/test/powershell/engine/Basic/ValidateAttributes.Tests.ps1 +++ b/test/powershell/engine/Basic/ValidateAttributes.Tests.ps1 @@ -52,7 +52,7 @@ Describe 'Validate Attributes Tests' -Tags 'CI' { } } - Context "ValidateRange - ParameterConstuctors" { + Context "ValidateRange - ParameterConstructors" { BeforeAll { $testCases = @( @{ From 290fe281040b893046080b12b5c86af9d1886699 Mon Sep 17 00:00:00 2001 From: MartinGC94 <42123497+MartinGC94@users.noreply.github.com> Date: Wed, 22 Feb 2023 18:10:22 +0100 Subject: [PATCH 367/779] Fix class member completion for classes with base types (#19179) --- .../engine/parser/TypeInferenceVisitor.cs | 13 ++++++++++++- .../Host/TabCompletion/TabCompletion.Tests.ps1 | 11 +++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs index 206c0737c10..993c5a45501 100644 --- a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs +++ b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs @@ -322,7 +322,18 @@ internal void AddMembersByInferredTypeDefinitionAst( } var baseTypeDefinitionAst = baseTypeName._typeDefinitionAst; - results.AddRange(GetMembersByInferredType(new PSTypeName(baseTypeDefinitionAst), isStatic, filterToCall)); + if (baseTypeDefinitionAst is null) + { + var baseReflectionType = baseTypeName.GetReflectionType(); + if (baseReflectionType is not null) + { + results.AddRange(GetMembersByInferredType(new PSTypeName(baseReflectionType), isStatic, filterToCall)); + } + } + else + { + results.AddRange(GetMembersByInferredType(new PSTypeName(baseTypeDefinitionAst), isStatic, filterToCall)); + } } // Add stuff from our base class System.Object. diff --git a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 index 3ed99228d7a..eb51455fdc7 100644 --- a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 +++ b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 @@ -843,6 +843,17 @@ Verb-Noun -Param1 Hello ^ $res.CompletionMatches[0].CompletionText | Should -Be "Attributes" } + it 'Should complete base class members of types without type definition AST' { + $res = TabExpansion2 -inputScript @' +class InheritedClassTest : System.Attribute +{ + [void] TestMethod() + { + $this. +'@ + $res.CompletionMatches.CompletionText | Should -Contain 'TypeId' + } + Context "Script name completion" { BeforeAll { Setup -f 'install-powershell.ps1' -Content "" From ad4db8d9c613005c801a3e4089232d5cd62247d0 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Wed, 22 Feb 2023 09:26:57 -0800 Subject: [PATCH 368/779] Update to the latest `NOTICES` file (#19169) --- ThirdPartyNotices.txt | 15 +-------------- 1 file changed, 1 insertion(+), 14 deletions(-) diff --git a/ThirdPartyNotices.txt b/ThirdPartyNotices.txt index 7c73d5c23a4..99ad0e45ece 100644 --- a/ThirdPartyNotices.txt +++ b/ThirdPartyNotices.txt @@ -176,22 +176,9 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI --------------------------------------------------------- -Microsoft.Extensions.ObjectPool 7.0.2 - MIT +Microsoft.Extensions.ObjectPool 7.0.3 - MIT -(c) Microsoft Corporation -Copyright (c) Andrew Arnott -Copyright (c) 2019 David Fowler -Copyright (c) 2016 Richard Morris -Copyright (c) 2017 Yoshifumi Kawai -Copyright (c) Microsoft Corporation -Copyright (c) 2007 James Newton-King -Copyright (c) 2014-2018 Michael Daines -Copyright (c) 2013-2017, Milosz Krajewski -Copyright (c) .NET Foundation and Contributors -Copyright (c) 2019-2020 West Wind Technologies -Copyright (c) 2010-2019 Google LLC. http://angular.io/license -Copyright (c) Sindre Sorhus (https://sindresorhus.com) MIT License From 75b7bfb0343816db362a368c7702c3bc3036baba Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 22 Feb 2023 09:34:51 -0800 Subject: [PATCH 369/779] Bump `Microsoft.NET.Test.Sdk` from 17.4.1 to 17.5.0 (#19191) --- test/xUnit/xUnit.tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/xUnit/xUnit.tests.csproj b/test/xUnit/xUnit.tests.csproj index 0f1d2038d38..272f21675a8 100644 --- a/test/xUnit/xUnit.tests.csproj +++ b/test/xUnit/xUnit.tests.csproj @@ -27,7 +27,7 @@ - + From 830f050fe6278a97f6f23fdef6dcfbf65c9f9a3d Mon Sep 17 00:00:00 2001 From: "James Truher [MSFT]" Date: Wed, 22 Feb 2023 09:36:27 -0800 Subject: [PATCH 370/779] Update a broken link in the README.md (#19187) --- docs/learning-powershell/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/learning-powershell/README.md b/docs/learning-powershell/README.md index 0dbbc5b8576..17829d89df7 100644 --- a/docs/learning-powershell/README.md +++ b/docs/learning-powershell/README.md @@ -97,7 +97,7 @@ Note that all bash commands should continue working on PowerShell session. - [The Guide to Learning PowerShell][ebook-from-Idera] by Tobias Weltner - [PowerShell-related Videos][channel9-learn-powershell] on Channel 9 - [PowerShell Quick Reference Guides][quick-reference] by PowerShellMagazine.com -- [Learn PowerShell Video Library][idera-learn-powershell] from Idera +- [PowerShell Tips][idera-powershell-tips] from Idera - [PowerShell 5 How-To Videos][script-guy-how-to] by Ed Wilson - [PowerShell Documentation](https://docs.microsoft.com/powershell) - [Interactive learning with PSKoans](https://aka.ms/pskoans) @@ -121,7 +121,7 @@ Note that all bash commands should continue working on PowerShell session. [why-learn-powershell]: https://blogs.technet.microsoft.com/heyscriptingguy/2014/10/18/weekend-scripter-why-learn-powershell/ [ebook-from-Idera]:https://www.idera.com/resourcecentral/whitepapers/powershell-ebook [channel9-learn-powershell]: https://channel9.msdn.com/Search?term=powershell#ch9Search -[idera-learn-powershell]: https://community.idera.com/database-tools/powershell/video_library/ +[idera-powershell-tips]: https://blog.idera.com/database-tools/powershell/powertips/ [quick-reference]: https://www.powershellmagazine.com/2014/04/24/windows-powershell-4-0-and-other-quick-reference-guides/ [script-guy-how-to]:https://blogs.technet.microsoft.com/tommypatterson/2015/09/04/ed-wilsons-powershell5-videos-now-on-channel9-2/ [basic-cookbooks]:https://docs.microsoft.com/powershell/scripting/samples/sample-scripts-for-administration From 77fcd471bbdd1d8161750ceddb49cb67b93f597d Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Wed, 22 Feb 2023 13:31:14 -0800 Subject: [PATCH 371/779] Revert a few change to not use 'ArgumentNullException.ThrowIfNull' (#19151) --- src/System.Management.Automation/engine/Utils.cs | 9 +-------- .../engine/lang/scriptblock.cs | 7 ++++--- .../engine/parser/SafeValues.cs | 7 ++++--- .../namespaces/FileSystemProvider.cs | 1 + .../utils/ParserException.cs | 4 +--- .../utils/perfCounters/CounterSetRegistrarBase.cs | 4 +--- 6 files changed, 12 insertions(+), 20 deletions(-) diff --git a/src/System.Management.Automation/engine/Utils.cs b/src/System.Management.Automation/engine/Utils.cs index bdf85b54e5e..74e3e468246 100644 --- a/src/System.Management.Automation/engine/Utils.cs +++ b/src/System.Management.Automation/engine/Utils.cs @@ -1733,11 +1733,6 @@ internal ReadOnlyBag(HashSet hashset) /// internal static class Requires { - internal static void NotNull(object value, string paramName) - { - ArgumentNullException.ThrowIfNull(value, paramName); - } - internal static void NotNullOrEmpty(string value, string paramName) { if (string.IsNullOrEmpty(value)) @@ -1748,9 +1743,7 @@ internal static void NotNullOrEmpty(string value, string paramName) internal static void NotNullOrEmpty(ICollection value, string paramName) { - ArgumentNullException.ThrowIfNull(value, paramName); - - if (value.Count == 0) + if (value is null || value.Count == 0) { throw new ArgumentNullException(paramName); } diff --git a/src/System.Management.Automation/engine/lang/scriptblock.cs b/src/System.Management.Automation/engine/lang/scriptblock.cs index c00fb9d6e37..fdc5bcdb326 100644 --- a/src/System.Management.Automation/engine/lang/scriptblock.cs +++ b/src/System.Management.Automation/engine/lang/scriptblock.cs @@ -1138,9 +1138,10 @@ public void Begin(bool expectInput, EngineIntrinsics contextToRedirectTo) /// The command you're calling this from (i.e. instance of PSCmdlet or value of $PSCmdlet variable). public void Begin(InternalCommand command) { - ArgumentNullException.ThrowIfNull(command); - - ArgumentNullException.ThrowIfNull(command.MyInvocation, nameof(command)); + if (command is null || command.MyInvocation is null) + { + throw new ArgumentNullException(nameof(command)); + } Begin(command.MyInvocation.ExpectingInput, command.commandRuntime); } diff --git a/src/System.Management.Automation/engine/parser/SafeValues.cs b/src/System.Management.Automation/engine/parser/SafeValues.cs index f551270c372..05c87daab5b 100644 --- a/src/System.Management.Automation/engine/parser/SafeValues.cs +++ b/src/System.Management.Automation/engine/parser/SafeValues.cs @@ -530,10 +530,11 @@ public object VisitIndexExpression(IndexExpressionAst indexExpressionAst) // Get the value of the index and value and call the compiler var index = indexExpressionAst.Index.Accept(this); var target = indexExpressionAst.Target.Accept(this); - - ArgumentNullException.ThrowIfNull(index, nameof(indexExpressionAst)); - ArgumentNullException.ThrowIfNull(target, nameof(indexExpressionAst)); + if (index is null || target is null) + { + throw new ArgumentNullException(nameof(indexExpressionAst)); + } return GetIndexedValueFromTarget(target, index); } diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index 5c2ff6d89c4..30db2e27180 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -7969,6 +7969,7 @@ internal static bool CreateJunction(string path, string target) { throw new ArgumentNullException(nameof(target)); } + using (SafeHandle handle = WinOpenReparsePoint(path, FileAccess.Write)) { byte[] mountPointBytes = Encoding.Unicode.GetBytes(NonInterpretedPathPrefix + Path.GetFullPath(target)); diff --git a/src/System.Management.Automation/utils/ParserException.cs b/src/System.Management.Automation/utils/ParserException.cs index 9087c374b69..4070fa7e7f1 100644 --- a/src/System.Management.Automation/utils/ParserException.cs +++ b/src/System.Management.Automation/utils/ParserException.cs @@ -129,9 +129,7 @@ public ParseException(string message, /// The collection of error messages. public ParseException(ParseError[] errors) { - ArgumentNullException.ThrowIfNull(errors); - - if (errors.Length == 0) + if (errors is null || errors.Length == 0) { throw new ArgumentNullException(nameof(errors)); } diff --git a/src/System.Management.Automation/utils/perfCounters/CounterSetRegistrarBase.cs b/src/System.Management.Automation/utils/perfCounters/CounterSetRegistrarBase.cs index 33e03e67a47..f9a08b76a87 100644 --- a/src/System.Management.Automation/utils/perfCounters/CounterSetRegistrarBase.cs +++ b/src/System.Management.Automation/utils/perfCounters/CounterSetRegistrarBase.cs @@ -108,9 +108,7 @@ protected CounterSetRegistrarBase( CounterSetInstType = counterSetInstType; CounterSetName = counterSetName; - ArgumentNullException.ThrowIfNull(counterInfoArray); - - if (counterInfoArray.Length == 0) + if (counterInfoArray is null || counterInfoArray.Length == 0) { throw new ArgumentNullException(nameof(counterInfoArray)); } From c381d6dd8331ef2056ee6f9ddd1c87e1e1e0b254 Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Wed, 22 Feb 2023 15:56:40 -0800 Subject: [PATCH 372/779] Simplify Windows Packaging CI Trigger YAML (#19160) --- .vsts-ci/windows/windows-packaging.yml | 20 ++------------------ 1 file changed, 2 insertions(+), 18 deletions(-) diff --git a/.vsts-ci/windows/windows-packaging.yml b/.vsts-ci/windows/windows-packaging.yml index b413b7a639b..d7443ffa135 100644 --- a/.vsts-ci/windows/windows-packaging.yml +++ b/.vsts-ci/windows/windows-packaging.yml @@ -27,30 +27,14 @@ pr: - release* - feature* paths: - # file extension filters are not supported when this was written. - # This really should be /src/**/*.csproj include: - - .vsts-ci/windows/* + - .vsts-ci/windows/*.yml - assets/wix/* - build.psm1 - global.json - nuget.config - PowerShell.Common.props - - src/Microsoft.Management.Infrastructure.CimCmdlets/Microsoft.Management.Infrastructure.CimCmdlets.csproj - - src/Microsoft.Management.UI.Internal/Microsoft.PowerShell.GraphicalHost.csproj - - src/Microsoft.PowerShell.Commands.Diagnostics/Microsoft.PowerShell.Commands.Diagnostics.csproj - - src/Microsoft.PowerShell.Commands.Management/Microsoft.PowerShell.Commands.Management.csproj - - src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj - - src/Microsoft.PowerShell.ConsoleHost/Microsoft.PowerShell.ConsoleHost.csproj - - src/Microsoft.PowerShell.CoreCLR.Eventing/Microsoft.PowerShell.CoreCLR.Eventing.csproj - - src/Microsoft.PowerShell.GlobalTool.Shim/Microsoft.PowerShell.GlobalTool.Shim.csproj - - src/Microsoft.PowerShell.MarkdownRender/Microsoft.PowerShell.MarkdownRender.csproj - - src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj - - src/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.csproj - - src/Microsoft.WSMan.Management/Microsoft.WSMan.Management.csproj - - src/Microsoft.WSMan.Runtime/Microsoft.WSMan.Runtime.csproj - - src/Modules/PSGalleryModules.csproj - - src/powershell-win-core/powershell-win-core.csproj + - src/*.csproj - test/packaging/windows/* - tools/ci.psm1 - tools/packaging/* From 79b4b5c33f6048ef9cb8b6b24400a564d57c4227 Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Wed, 22 Feb 2023 16:01:18 -0800 Subject: [PATCH 373/779] Update the `FeedbackProvider` interface to return structured data (#19133) --- .../host/msh/ConsoleHost.cs | 54 +---- .../PowerShellCore_format_ps1xml.cs | 6 +- .../FormatAndOutput/common/PSStyle.cs | 24 +- .../FeedbackSubsystem/FeedbackHub.cs | 42 ++-- .../FeedbackSubsystem/IFeedbackProvider.cs | 217 ++++++++++++------ .../engine/hostifaces/HostUtilities.cs | 206 ++++++++++++++++- .../resources/SuggestionStrings.resx | 7 +- test/xUnit/csharp/test_Feedback.cs | 31 +-- test/xUnit/csharp/test_Subsystem.cs | 2 +- 9 files changed, 422 insertions(+), 167 deletions(-) diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs index e2b7bd7b8ba..577abc5c087 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs @@ -2836,61 +2836,13 @@ private void EvaluateFeedbacks(ConsoleHostUserInterface ui) // Output any training suggestions try { - List feedbacks = FeedbackHub.GetFeedback(_parent.Runspace); - if (feedbacks is null || feedbacks.Count == 0) + List feedbacks = FeedbackHub.GetFeedback(_parent.Runspace); + if (feedbacks is null || feedbacks.Count is 0) { return; } - // Feedback section starts with a new line. - ui.WriteLine(); - - const string Indentation = " "; - string nameStyle = PSStyle.Instance.Formatting.FeedbackProvider; - string textStyle = PSStyle.Instance.Formatting.FeedbackText; - string ansiReset = PSStyle.Instance.Reset; - - if (!ui.SupportsVirtualTerminal) - { - nameStyle = string.Empty; - textStyle = string.Empty; - ansiReset = string.Empty; - } - - int count = 0; - var output = new StringBuilder(); - - foreach (FeedbackEntry entry in feedbacks) - { - if (count > 0) - { - output.AppendLine(); - } - - output.Append("Suggestion [") - .Append(nameStyle) - .Append(entry.Name) - .Append(ansiReset) - .AppendLine("]:") - .Append(textStyle); - - string[] lines = entry.Text.Split('\n', StringSplitOptions.RemoveEmptyEntries); - foreach (string line in lines) - { - output.Append(Indentation) - .Append(line.AsSpan().TrimEnd()) - .AppendLine(); - } - - output.Append(ansiReset); - ui.Write(output.ToString()); - - count++; - output.Clear(); - } - - // Feedback section ends with a new line. - ui.WriteLine(); + HostUtilities.RenderFeedback(feedbacks, ui); } catch (Exception e) { diff --git a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs index 6ab8b8f2150..3d6257f36a8 100644 --- a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs +++ b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs @@ -2063,8 +2063,9 @@ private static IEnumerable ViewsOf_System_Management_Autom .AddItemScriptBlock(@"""$($_.Formatting.Debug)$($_.Formatting.Debug.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Formatting.Debug") .AddItemScriptBlock(@"""$($_.Formatting.TableHeader)$($_.Formatting.TableHeader.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Formatting.TableHeader") .AddItemScriptBlock(@"""$($_.Formatting.CustomTableHeaderLabel)$($_.Formatting.CustomTableHeaderLabel.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Formatting.CustomTableHeaderLabel") - .AddItemScriptBlock(@"""$($_.Formatting.FeedbackProvider)$($_.Formatting.FeedbackProvider.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Formatting.FeedbackProvider") + .AddItemScriptBlock(@"""$($_.Formatting.FeedbackName)$($_.Formatting.FeedbackName.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Formatting.FeedbackName") .AddItemScriptBlock(@"""$($_.Formatting.FeedbackText)$($_.Formatting.FeedbackText.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Formatting.FeedbackText") + .AddItemScriptBlock(@"""$($_.Formatting.FeedbackAction)$($_.Formatting.FeedbackAction.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Formatting.FeedbackAction") .AddItemScriptBlock(@"""$($_.Progress.Style)$($_.Progress.Style.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Progress.Style") .AddItemScriptBlock(@"""$($_.Progress.MaxWidth)""", label: "Progress.MaxWidth") .AddItemScriptBlock(@"""$($_.Progress.View)""", label: "Progress.View") @@ -2122,8 +2123,9 @@ private static IEnumerable ViewsOf_System_Management_Autom .AddItemScriptBlock(@"""$($_.Debug)$($_.Debug.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Debug") .AddItemScriptBlock(@"""$($_.TableHeader)$($_.TableHeader.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "TableHeader") .AddItemScriptBlock(@"""$($_.CustomTableHeaderLabel)$($_.CustomTableHeaderLabel.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "CustomTableHeaderLabel") - .AddItemScriptBlock(@"""$($_.FeedbackProvider)$($_.FeedbackProvider.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "FeedbackProvider") + .AddItemScriptBlock(@"""$($_.FeedbackName)$($_.FeedbackName.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "FeedbackName") .AddItemScriptBlock(@"""$($_.FeedbackText)$($_.FeedbackText.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "FeedbackText") + .AddItemScriptBlock(@"""$($_.FeedbackAction)$($_.FeedbackAction.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "FeedbackAction") .EndEntry() .EndList()); } diff --git a/src/System.Management.Automation/FormatAndOutput/common/PSStyle.cs b/src/System.Management.Automation/FormatAndOutput/common/PSStyle.cs index 930e86d4acc..3f927afd7d5 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/PSStyle.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/PSStyle.cs @@ -435,16 +435,17 @@ public string Debug /// /// Gets or sets the style for rendering feedback provider names. /// - public string FeedbackProvider + public string FeedbackName { - get => _feedbackProvider; - set => _feedbackProvider = ValidateNoContent(value); + get => _feedbackName; + set => _feedbackName = ValidateNoContent(value); } - private string _feedbackProvider = "\x1b[33m"; + // Yellow by default. + private string _feedbackName = "\x1b[33m"; /// - /// Gets or sets the style for rendering feedback text. + /// Gets or sets the style for rendering feedback message. /// public string FeedbackText { @@ -452,7 +453,20 @@ public string FeedbackText set => _feedbackText = ValidateNoContent(value); } + // BrightCyan by default. private string _feedbackText = "\x1b[96m"; + + /// + /// Gets or sets the style for rendering feedback actions. + /// + public string FeedbackAction + { + get => _feedbackAction; + set => _feedbackAction = ValidateNoContent(value); + } + + // BrightWhite by default. + private string _feedbackAction = "\x1b[97m"; } /// diff --git a/src/System.Management.Automation/engine/Subsystem/FeedbackSubsystem/FeedbackHub.cs b/src/System.Management.Automation/engine/Subsystem/FeedbackSubsystem/FeedbackHub.cs index 5755945dcd0..6818d25bcdb 100644 --- a/src/System.Management.Automation/engine/Subsystem/FeedbackSubsystem/FeedbackHub.cs +++ b/src/System.Management.Automation/engine/Subsystem/FeedbackSubsystem/FeedbackHub.cs @@ -17,7 +17,7 @@ namespace System.Management.Automation.Subsystem.Feedback /// /// The class represents a result from a feedback provider. /// - public class FeedbackEntry + public class FeedbackResult { /// /// Gets the Id of the feedback provider. @@ -30,15 +30,15 @@ public class FeedbackEntry public string Name { get; } /// - /// Gets the text of the feedback. + /// Gets the feedback item. /// - public string Text { get; } + public FeedbackItem Item { get; } - internal FeedbackEntry(Guid id, string name, string text) + internal FeedbackResult(Guid id, string name, FeedbackItem item) { Id = id; Name = name; - Text = text; + Item = item; } } @@ -50,7 +50,7 @@ public static class FeedbackHub /// /// Collect the feedback from registered feedback providers using the default timeout. /// - public static List? GetFeedback(Runspace runspace) + public static List? GetFeedback(Runspace runspace) { return GetFeedback(runspace, millisecondsTimeout: 300); } @@ -58,7 +58,7 @@ public static class FeedbackHub /// /// Collect the feedback from registered feedback providers using the specified timeout. /// - public static List? GetFeedback(Runspace runspace, int millisecondsTimeout) + public static List? GetFeedback(Runspace runspace, int millisecondsTimeout) { Requires.Condition(millisecondsTimeout > 0, nameof(millisecondsTimeout)); @@ -110,9 +110,9 @@ public static class FeedbackHub } IFeedbackProvider? generalFeedback = null; - List>? tasks = null; + List>? tasks = null; CancellationTokenSource? cancellationSource = null; - Func? callBack = null; + Func? callBack = null; for (int i = 0; i < providers.Count; i++) { @@ -126,7 +126,7 @@ public static class FeedbackHub if (tasks is null) { - tasks = new List>(capacity: count); + tasks = new List>(capacity: count); cancellationSource = new CancellationTokenSource(); callBack = GetCallBack(lastHistory.CommandLine, lastError, cancellationSource); } @@ -148,7 +148,7 @@ public static class FeedbackHub Task.Delay(millisecondsTimeout, cancellationSource!.Token)); } - List? resultList = null; + List? resultList = null; if (generalFeedback is not null) { bool changedDefault = false; @@ -162,11 +162,11 @@ public static class FeedbackHub Runspace.DefaultRunspace = localRunspace; } - string? text = generalFeedback.GetFeedback(lastHistory.CommandLine, lastError, CancellationToken.None); - if (text is not null) + FeedbackItem? item = generalFeedback.GetFeedback(lastHistory.CommandLine, lastError, CancellationToken.None); + if (item is not null) { - resultList ??= new List(count); - resultList.Add(new FeedbackEntry(generalFeedback.Id, generalFeedback.Name, text)); + resultList ??= new List(count); + resultList.Add(new FeedbackResult(generalFeedback.Id, generalFeedback.Name, item)); } } finally @@ -188,14 +188,14 @@ public static class FeedbackHub waitTask.Wait(); cancellationSource!.Cancel(); - foreach (Task task in tasks!) + foreach (Task task in tasks!) { if (task.IsCompletedSuccessfully) { - FeedbackEntry? result = task.Result; + FeedbackResult? result = task.Result; if (result is not null) { - resultList ??= new List(count); + resultList ??= new List(count); resultList.Add(result); } } @@ -212,7 +212,7 @@ public static class FeedbackHub // A local helper function to avoid creating an instance of the generated delegate helper class // when no feedback provider is registered. - private static Func GetCallBack( + private static Func GetCallBack( string commandLine, ErrorRecord lastError, CancellationTokenSource cancellationSource) @@ -220,8 +220,8 @@ public static class FeedbackHub return state => { var provider = (IFeedbackProvider)state!; - var text = provider.GetFeedback(commandLine, lastError, cancellationSource.Token); - return text is null ? null : new FeedbackEntry(provider.Id, provider.Name, text); + var item = provider.GetFeedback(commandLine, lastError, cancellationSource.Token); + return item is null ? null : new FeedbackResult(provider.Id, provider.Name, item); }; } } diff --git a/src/System.Management.Automation/engine/Subsystem/FeedbackSubsystem/IFeedbackProvider.cs b/src/System.Management.Automation/engine/Subsystem/FeedbackSubsystem/IFeedbackProvider.cs index ba6d4f8433b..52c79a46fd5 100644 --- a/src/System.Management.Automation/engine/Subsystem/FeedbackSubsystem/IFeedbackProvider.cs +++ b/src/System.Management.Automation/engine/Subsystem/FeedbackSubsystem/IFeedbackProvider.cs @@ -3,7 +3,6 @@ #nullable enable -using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; @@ -14,6 +13,91 @@ namespace System.Management.Automation.Subsystem.Feedback { + /// + /// Layout for displaying the recommended actions. + /// + public enum FeedbackDisplayLayout + { + /// + /// Display one recommended action per row. + /// + Portrait, + + /// + /// Display all recommended actions in the same row. + /// + Landscape, + } + + /// + /// The class represents a feedback item generated by the feedback provider. + /// + public sealed class FeedbackItem + { + /// + /// Gets the description message about this feedback. + /// + public string Header { get; } + + /// + /// Gets the footer message about this feedback. + /// + public string? Footer { get; } + + /// + /// Gets the recommended actions -- command lines or even code snippets to run. + /// + public List? RecommendedActions { get; } + + /// + /// Gets the layout to use for displaying the recommended actions. + /// + public FeedbackDisplayLayout Layout { get; } + + /// + /// Gets or sets the next feedback item, if there is one. + /// + public FeedbackItem? Next { get; set; } + + /// + /// Initializes a new instance of the class. + /// + /// The description message (must be not null or empty). + /// The recommended actions to take (optional). + public FeedbackItem(string header, List? actions) + : this(header, actions, footer: null, FeedbackDisplayLayout.Portrait) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The description message (must be not null or empty). + /// The recommended actions to take (optional). + /// The layout for displaying the actions. + public FeedbackItem(string header, List? actions, FeedbackDisplayLayout layout) + : this(header, actions, footer: null, layout) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The description message (must be not null or empty). + /// The recommended actions to take (optional). + /// The footer message (optional). + /// The layout for displaying the actions. + public FeedbackItem(string header, List? actions, string? footer, FeedbackDisplayLayout layout) + { + Requires.NotNullOrEmpty(header, nameof(header)); + + Header = header; + RecommendedActions = actions; + Footer = footer; + Layout = layout; + } + } + /// /// Interface for implementing a feedback provider on command failures. /// @@ -27,29 +111,29 @@ public interface IFeedbackProvider : ISubsystem /// /// Gets feedback based on the given commandline and error record. /// - /// - string? GetFeedback(string commandLine, ErrorRecord lastError, CancellationToken token); + /// The command line that was just executed. + /// The error that was triggerd by the command line. + /// The cancellation token to cancel the operation. + /// The feedback item. + FeedbackItem? GetFeedback(string commandLine, ErrorRecord lastError, CancellationToken token); } internal sealed class GeneralCommandErrorFeedback : IFeedbackProvider { private readonly Guid _guid; - private readonly object[] _args; - private ScriptBlock? _fuzzySb; internal GeneralCommandErrorFeedback() { _guid = new Guid("A3C6B07E-4A89-40C9-8BE6-2A9AAD2786A4"); - _args = new object[1]; } public Guid Id => _guid; - public string Name => "General"; + public string Name => "general"; public string Description => "The built-in general feedback source for command errors."; - public string? GetFeedback(string commandLine, ErrorRecord lastError, CancellationToken token) + public FeedbackItem? GetFeedback(string commandLine, ErrorRecord lastError, CancellationToken token) { var rsToUse = Runspace.DefaultRunspace; if (rsToUse is null) @@ -72,31 +156,31 @@ internal GeneralCommandErrorFeedback() if (command is not null) { - return StringUtil.Format( - SuggestionStrings.Suggestion_CommandExistsInCurrentDirectory, - target, - localTarget); + return new FeedbackItem( + StringUtil.Format(SuggestionStrings.Suggestion_CommandExistsInCurrentDirectory, target), + new List { localTarget }); } // Check fuzzy matching command names. if (ExperimentalFeature.IsEnabled("PSCommandNotFoundSuggestion")) { - _fuzzySb ??= ScriptBlock.CreateDelayParsedScriptBlock(@$" - param([string] $target) - $cmdNames = Get-Command $target -UseFuzzyMatching -FuzzyMinimumDistance 1 | Select-Object -First 5 -Unique -ExpandProperty Name - if ($cmdNames) {{ - [string]::Join(', ', $cmdNames) - }} - ", isProductCode: true); - - _args[0] = target; - var result = _fuzzySb.InvokeReturnAsIs(_args); - - if (result is not null && result != AutomationNull.Value) + var pwsh = PowerShell.Create(RunspaceMode.CurrentRunspace); + var results = pwsh.AddCommand("Get-Command") + .AddParameter("UseFuzzyMatching") + .AddParameter("FuzzyMinimumDistance", 1) + .AddParameter("Name", target) + .AddCommand("Select-Object") + .AddParameter("First", 5) + .AddParameter("Unique") + .AddParameter("ExpandProperty", "Name") + .Invoke(); + + if (results.Count > 0) { - return StringUtil.Format( + return new FeedbackItem( SuggestionStrings.Suggestion_CommandNotFound, - result.ToString()); + new List(results), + FeedbackDisplayLayout.Landscape); } } } @@ -108,7 +192,6 @@ internal GeneralCommandErrorFeedback() internal sealed class UnixCommandNotFound : IFeedbackProvider, ICommandPredictor { private readonly Guid _guid; - private string? _notFoundFeedback; private List? _candidates; internal UnixCommandNotFound() @@ -146,10 +229,7 @@ static bool IsFileExecutable(string path) } } - /// - /// Gets feedback based on the given commandline and error record. - /// - public string? GetFeedback(string commandLine, ErrorRecord lastError, CancellationToken token) + public FeedbackItem? GetFeedback(string commandLine, ErrorRecord lastError, CancellationToken token) { if (Platform.IsWindows || lastError.FullyQualifiedErrorId != "CommandNotFoundException") { @@ -176,15 +256,44 @@ static bool IsFileExecutable(string path) startInfo.RedirectStandardOutput = true; using var process = Process.Start(startInfo); - var stderr = process?.StandardError.ReadToEnd().Trim(); - - // The feedback contains recommended actions only if the output has multiple lines of text. - if (stderr?.IndexOf('\n') > 0) + if (process is not null) { - _notFoundFeedback = stderr; + string? header = null; + List? actions = null; - var stdout = process?.StandardOutput.ReadToEnd().Trim(); - return string.IsNullOrEmpty(stdout) ? stderr : $"{stderr}\n{stdout}"; + while (true) + { + string? line = process.StandardError.ReadLine(); + if (line is null) + { + break; + } + + if (line == string.Empty) + { + continue; + } + + if (line.StartsWith("sudo ", StringComparison.Ordinal)) + { + actions ??= new List(); + actions.Add(line.TrimEnd()); + } + else if (actions is null) + { + header = line; + } + } + + if (actions is not null && header is not null) + { + _candidates = actions; + + var footer = process.StandardOutput.ReadToEnd().Trim(); + return string.IsNullOrEmpty(footer) + ? new FeedbackItem(header, actions) + : new FeedbackItem(header, actions, footer, FeedbackDisplayLayout.Portrait); + } } } @@ -206,37 +315,6 @@ public bool CanAcceptFeedback(PredictionClient client, PredictorFeedbackKind fee public SuggestionPackage GetSuggestion(PredictionClient client, PredictionContext context, CancellationToken cancellationToken) { - if (_candidates is null && _notFoundFeedback is not null) - { - var text = _notFoundFeedback.AsSpan(); - // Set to null to avoid potential race condition. - _notFoundFeedback = null; - - // This loop searches for candidate results with almost no allocation. - while (true) - { - // The line is a candidate if it starts with "sudo ", such as "sudo apt install python3". - // 'sudo' is a command name that remains the same, so this check should work for all locales. - bool isCandidate = text.StartsWith("sudo ", StringComparison.Ordinal); - int index = text.IndexOf('\n'); - if (isCandidate) - { - var line = index != -1 ? text.Slice(0, index) : text; - _candidates ??= new List(); - _candidates.Add(new string(line.TrimEnd())); - } - - // Break out the loop if we are done with the last line. - if (index == -1 || index == text.Length - 1) - { - break; - } - - // Point to the rest of feedback text. - text = text.Slice(index + 1); - } - } - if (_candidates is not null) { string input = context.InputAst.Extent.Text; @@ -263,7 +341,6 @@ public SuggestionPackage GetSuggestion(PredictionClient client, PredictionContex public void OnCommandLineAccepted(PredictionClient client, IReadOnlyList history) { // Reset the candidate state. - _notFoundFeedback = null; _candidates = null; } diff --git a/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs b/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs index 1f88f48eaf5..e0d19c489c8 100644 --- a/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs +++ b/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs @@ -10,8 +10,8 @@ using System.Management.Automation.Internal; using System.Management.Automation.Language; using System.Management.Automation.Runspaces; +using System.Management.Automation.Subsystem.Feedback; using System.Runtime.InteropServices; -using System.Security; using System.Text; using System.Text.RegularExpressions; @@ -42,6 +42,8 @@ public static class HostUtilities { #region Internal Access + private static readonly char s_actionIndicator = HostSupportUnicode() ? '\u2b9e' : '>'; + private static readonly string s_checkForCommandInCurrentDirectoryScript = @" [System.Diagnostics.DebuggerHidden()] param() @@ -74,6 +76,25 @@ public static class HostUtilities private static readonly List s_suggestions = InitializeSuggestions(); + private static bool HostSupportUnicode() + { + // Reference: https://github.com/zkat/supports-unicode/blob/main/src/lib.rs + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + return Environment.GetEnvironmentVariable("WT_SESSION") is not null || + Environment.GetEnvironmentVariable("TERM_PROGRAM") is "vscode" || + Environment.GetEnvironmentVariable("ConEmuTask") is "{cmd:Cmder}" || + Environment.GetEnvironmentVariable("TERM") is "xterm-256color" or "alacritty"; + } + + string ctype = Environment.GetEnvironmentVariable("LC_ALL") ?? + Environment.GetEnvironmentVariable("LC_CTYPE") ?? + Environment.GetEnvironmentVariable("LANG") ?? + string.Empty; + + return ctype.EndsWith("UTF8") || ctype.EndsWith("UTF-8"); + } + private static List InitializeSuggestions() { var suggestions = new List( @@ -811,6 +832,189 @@ public static Collection InvokeOnRunspace(PSCommand command, Runspace #endregion + #region Feedback Rendering + + /// + /// Render the feedbacks to the specified host. + /// + /// The feedback results. + /// The host to render to. + public static void RenderFeedback(List feedbacks, PSHostUserInterface ui) + { + // Caption style is dimmed bright white with italic effect, used for fixed captions, such as '[' and ']'. + string captionStyle = "\x1b[97;2;3m"; + string italics = "\x1b[3m"; + string nameStyle = PSStyle.Instance.Formatting.FeedbackName; + string textStyle = PSStyle.Instance.Formatting.FeedbackText; + string actionStyle = PSStyle.Instance.Formatting.FeedbackAction; + string ansiReset = PSStyle.Instance.Reset; + + if (!ui.SupportsVirtualTerminal) + { + captionStyle = string.Empty; + italics = string.Empty; + nameStyle = string.Empty; + textStyle = string.Empty; + actionStyle = string.Empty; + ansiReset = string.Empty; + } + + var output = new StringBuilder(); + var chkset = new HashSet(); + + foreach (FeedbackResult entry in feedbacks) + { + output.AppendLine(); + output.Append($"{captionStyle}[{ansiReset}") + .Append($"{nameStyle}{italics}{entry.Name}{ansiReset}") + .Append($"{captionStyle}]{ansiReset}"); + + FeedbackItem item = entry.Item; + chkset.Add(item); + + do + { + RenderText(output, item.Header, textStyle, ansiReset, indent: 2, startOnNewLine: true); + RenderActions(output, item, textStyle, actionStyle, ansiReset); + RenderText(output, item.Footer, textStyle, ansiReset, indent: 2, startOnNewLine: true); + + // A feedback provider may return multiple feedback items, though that may be rare. + item = item.Next; + } + while (item is not null && chkset.Add(item)); + + ui.Write(output.ToString()); + output.Clear(); + chkset.Clear(); + } + + // Feedback section ends with a new line. + ui.WriteLine(); + } + + /// + /// Helper function to render feedback message. + /// + /// The output string builder to write to. + /// The text to be rendered. + /// The style to be used. + /// The ANSI code to reset. + /// The number of spaces for indentation. + /// Indicates whether to start writing from a new line. + internal static void RenderText(StringBuilder output, string text, string style, string ansiReset, int indent, bool startOnNewLine) + { + if (text is null) + { + return; + } + + if (startOnNewLine) + { + // Start writing the text on the next line. + output.AppendLine(); + } + + // Apply the style. + output.Append(style); + + int count = 0; + var trimChars = "\r\n".AsSpan(); + var span = text.AsSpan().Trim(trimChars); + + // This loop renders the text with minimal allocation. + while (true) + { + int index = span.IndexOf('\n'); + var line = index is -1 ? span : span.Slice(0, index); + + if (startOnNewLine || count > 0) + { + output.Append(' ', indent); + } + + output.Append(line.TrimEnd('\r')).AppendLine(); + + // Break out the loop if we are done with the last line. + if (index is -1) + { + break; + } + + // Point to the rest of feedback text. + span = span.Slice(index + 1); + count++; + } + + output.Append(ansiReset); + } + + /// + /// Helper function to render feedback actions. + /// + /// The output string builder to write to. + /// The feedback item to be rendered. + /// The style used for feedback messages. + /// The style used for feedback actions. + /// The ANSI code to reset. + internal static void RenderActions(StringBuilder output, FeedbackItem item, string textStyle, string actionStyle, string ansiReset) + { + if (item.RecommendedActions is null || item.RecommendedActions.Count is 0) + { + return; + } + + List actions = item.RecommendedActions; + if (item.Layout is FeedbackDisplayLayout.Landscape) + { + // Add 4-space indentation and write the indicator. + output.Append($" {textStyle}{s_actionIndicator}{ansiReset} "); + + // Then concatenate the action texts. + for (int i = 0; i < actions.Count; i++) + { + string action = actions[i]; + if (i > 0) + { + output.Append(", "); + } + + output.Append(actionStyle).Append(action).Append(ansiReset); + } + + output.AppendLine(); + } + else + { + int lastIndex = actions.Count - 1; + for (int i = 0; i < actions.Count; i++) + { + string action = actions[i]; + + // Add 4-space indentation and write the indicator, then write the action. + output.Append($" {textStyle}{s_actionIndicator}{ansiReset} "); + + if (action.Contains('\n')) + { + // If the action is a code snippet, properly render it with the right indentation. + RenderText(output, action, actionStyle, ansiReset, indent: 6, startOnNewLine: false); + + // Append an extra line unless it's the last action. + if (i != lastIndex) + { + output.AppendLine(); + } + } + else + { + output.Append(actionStyle).Append(action).Append(ansiReset) + .AppendLine(); + } + } + } + } + + #endregion + #endregion } diff --git a/src/System.Management.Automation/resources/SuggestionStrings.resx b/src/System.Management.Automation/resources/SuggestionStrings.resx index 14e9c01b275..ea249db55e7 100644 --- a/src/System.Management.Automation/resources/SuggestionStrings.resx +++ b/src/System.Management.Automation/resources/SuggestionStrings.resx @@ -118,10 +118,13 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - The command "{0}" was not found, but does exist in the current location. PowerShell does not load commands from the current location by default. If you trust this command, instead type: "{1}". See "get-help about_Command_Precedence" for more details. + The command "{0}" was not found, but does exist in the current location. +PowerShell does not load commands from the current location by default (see 'Get-Help about_Command_Precedence'). + +If you trust this command, run the following command instead: - The most similar commands are: {0}. + The most similar commands are: Rule must be a ScriptBlock for dynamic match types. diff --git a/test/xUnit/csharp/test_Feedback.cs b/test/xUnit/csharp/test_Feedback.cs index 372c9ec8cc4..b3c1fb08ecf 100644 --- a/test/xUnit/csharp/test_Feedback.cs +++ b/test/xUnit/csharp/test_Feedback.cs @@ -2,6 +2,7 @@ // Licensed under the MIT License. using System; +using System.Collections.Generic; using System.IO; using System.Management.Automation; using System.Management.Automation.Subsystem; @@ -42,7 +43,7 @@ private MyFeedback(Guid id, string name, string description, bool delay) public string Description => _description; - public string GetFeedback(string commandLine, ErrorRecord errorRecord, CancellationToken token) + public FeedbackItem GetFeedback(string commandLine, ErrorRecord errorRecord, CancellationToken token) { if (_delay) { @@ -51,7 +52,9 @@ public string GetFeedback(string commandLine, ErrorRecord errorRecord, Cancellat Thread.Sleep(2500); } - return $"{commandLine}+{errorRecord.FullyQualifiedErrorId}"; + return new FeedbackItem( + "slow-feedback-caption", + new List { $"{commandLine}+{errorRecord.FullyQualifiedErrorId}" }); } } @@ -76,40 +79,40 @@ public static void GetFeedback() .Invoke(input: null, settings); pwsh.Commands.Clear(); - // Run a command 'feedbacktest', so as to trigger the 'General' feedback. + // Run a command 'feedbacktest', so as to trigger the 'general' feedback. pwsh.AddScript("feedbacktest").Invoke(input: null, settings); pwsh.Commands.Clear(); try { // Register the slow feedback provider. - // The 'General' feedback provider is built-in and registered by default. + // The 'general' feedback provider is built-in and registered by default. SubsystemManager.RegisterSubsystem(SubsystemKind.FeedbackProvider, MyFeedback.SlowFeedback); - // Expect the result from 'General' only because the 'slow' one cannot finish before the specified timeout. + // Expect the result from 'general' only because the 'slow' one cannot finish before the specified timeout. // The specified timeout is exaggerated to make the test reliable. // xUnit must spin up a lot tasks, which makes the test unreliable when the time difference between 'delay' and 'timeout' is small. var feedbacks = FeedbackHub.GetFeedback(pwsh.Runspace, millisecondsTimeout: 1500); string expectedCmd = Path.Combine(".", "feedbacktest"); - // Test the result from the 'General' feedback provider. + // Test the result from the 'general' feedback provider. Assert.Single(feedbacks); - Assert.Equal("General", feedbacks[0].Name); - Assert.Contains(expectedCmd, feedbacks[0].Text); + Assert.Equal("general", feedbacks[0].Name); + Assert.Equal(expectedCmd, feedbacks[0].Item.RecommendedActions[0]); - // Expect the result from both 'General' and the 'slow' feedback providers. + // Expect the result from both 'general' and the 'slow' feedback providers. // Same here -- the specified timeout is exaggerated to make the test reliable. // xUnit must spin up a lot tasks, which makes the test unreliable when the time difference between 'delay' and 'timeout' is small. feedbacks = FeedbackHub.GetFeedback(pwsh.Runspace, millisecondsTimeout: 4000); Assert.Equal(2, feedbacks.Count); - FeedbackEntry entry1 = feedbacks[0]; - Assert.Equal("General", entry1.Name); - Assert.Contains(expectedCmd, entry1.Text); + FeedbackResult entry1 = feedbacks[0]; + Assert.Equal("general", entry1.Name); + Assert.Equal(expectedCmd, entry1.Item.RecommendedActions[0]); - FeedbackEntry entry2 = feedbacks[1]; + FeedbackResult entry2 = feedbacks[1]; Assert.Equal("Slow", entry2.Name); - Assert.Equal("feedbacktest+CommandNotFoundException", entry2.Text); + Assert.Equal("feedbacktest+CommandNotFoundException", entry2.Item.RecommendedActions[0]); } finally { diff --git a/test/xUnit/csharp/test_Subsystem.cs b/test/xUnit/csharp/test_Subsystem.cs index 724c8747e5a..1318f13139d 100644 --- a/test/xUnit/csharp/test_Subsystem.cs +++ b/test/xUnit/csharp/test_Subsystem.cs @@ -65,7 +65,7 @@ private MyCompositeSubsystem(Guid id) #region IFeedbackProvider - public string GetFeedback(string commandLine, ErrorRecord errorRecord, CancellationToken token) => "nothing"; + public FeedbackItem GetFeedback(string commandLine, ErrorRecord errorRecord, CancellationToken token) => new FeedbackItem("nothing", null); #endregion From 2d15e0c5b6adfad5cb815e5381d7f9e48e7ac7ed Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Wed, 22 Feb 2023 16:12:16 -0800 Subject: [PATCH 374/779] Update to .NET 8 preview 1 build (#19194) --- Analyzers.props | 1 - DotnetRuntimeMetadata.json | 4 +- PowerShell.Common.props | 4 +- assets/wix/files.wxs | 222 +++++++++++++++++- build.psm1 | 6 +- global.json | 2 +- nuget.config | 2 +- .../Microsoft.PowerShell.GraphicalHost.csproj | 2 +- ...oft.PowerShell.Commands.Diagnostics.csproj | 2 +- ...soft.PowerShell.Commands.Management.csproj | 2 +- ...crosoft.PowerShell.Commands.Utility.csproj | 6 +- ...crosoft.PowerShell.CoreCLR.Eventing.csproj | 2 +- .../Microsoft.PowerShell.SDK.csproj | 22 +- .../Microsoft.WSMan.Management.csproj | 2 +- src/Modules/PSGalleryModules.csproj | 2 +- src/ResGen/ResGen.csproj | 2 +- .../PSVersionInfoGenerator.csproj | 2 +- .../System.Management.Automation.csproj | 16 +- src/TypeCatalogGen/TypeCatalogGen.csproj | 2 +- .../powershell-win-core.csproj | 2 +- test/Test.Common.props | 2 +- .../BenchmarkDotNet.Extensions.csproj | 4 +- .../ResultsComparer/ResultsComparer.csproj | 2 +- .../Get-ExperimentalFeature.Tests.ps1 | 4 +- .../engine/Formatting/PSStyle.Tests.ps1 | 4 +- test/tools/NamedPipeConnection/build.ps1 | 4 +- ...soft.PowerShell.NamedPipeConnection.csproj | 4 +- test/tools/OpenCover/OpenCover.psm1 | 2 +- test/tools/TestService/TestService.csproj | 2 +- test/tools/WebListener/BrotliFilter.cs | 3 +- .../WebListener/Controllers/AuthController.cs | 7 +- .../WebListener/Controllers/LinkController.cs | 3 +- .../Controllers/RedirectController.cs | 5 +- test/tools/WebListener/DeflateFilter.cs | 3 +- test/tools/WebListener/GzipFilter.cs | 3 +- test/tools/WebListener/WebListener.csproj | 4 +- tools/findMissingNotices.ps1 | 6 +- tools/packaging/packaging.psm1 | 10 +- tools/packaging/packaging.strings.psd1 | 2 +- tools/packaging/projects/nuget/package.csproj | 2 +- ...crosoft.PowerShell.Commands.Utility.csproj | 2 +- .../Microsoft.PowerShell.ConsoleHost.csproj | 2 +- .../System.Management.Automation.csproj | 2 +- .../templates/release-SDKTests.yml | 2 +- 44 files changed, 299 insertions(+), 90 deletions(-) diff --git a/Analyzers.props b/Analyzers.props index 192d9433fda..6988cf57f5d 100644 --- a/Analyzers.props +++ b/Analyzers.props @@ -1,7 +1,6 @@ - diff --git a/DotnetRuntimeMetadata.json b/DotnetRuntimeMetadata.json index 89c806b629f..f2dbaaae3e2 100644 --- a/DotnetRuntimeMetadata.json +++ b/DotnetRuntimeMetadata.json @@ -1,9 +1,9 @@ { "sdk": { - "channel": "7.0.1xx", + "channel": "8.0.1xx-preview1", "quality": "daily", "qualityFallback": "preview", - "packageVersionPattern": "7.0.1", + "packageVersionPattern": "8.0.0-preview.1", "sdkImageVersion": "7.0.101", "nextChannel": "7.0.1xx-rc2", "azureFeed": "", diff --git a/PowerShell.Common.props b/PowerShell.Common.props index 8f784ede515..cf9f792f99c 100644 --- a/PowerShell.Common.props +++ b/PowerShell.Common.props @@ -138,8 +138,8 @@ Microsoft Corporation (c) Microsoft Corporation. - net7.0 - 10.0 + net8.0 + 11.0 true true diff --git a/assets/wix/files.wxs b/assets/wix/files.wxs index 46aad9fd92a..a3e5932d134 100644 --- a/assets/wix/files.wxs +++ b/assets/wix/files.wxs @@ -218,9 +218,6 @@ - - - @@ -1602,6 +1599,18 @@ + + + + + + + + + + + + @@ -1667,6 +1676,18 @@ + + + + + + + + + + + + @@ -1732,6 +1753,18 @@ + + + + + + + + + + + + @@ -1797,6 +1830,18 @@ + + + + + + + + + + + + @@ -1862,6 +1907,18 @@ + + + + + + + + + + + + @@ -1927,6 +1984,18 @@ + + + + + + + + + + + + @@ -1992,6 +2061,18 @@ + + + + + + + + + + + + @@ -2057,6 +2138,18 @@ + + + + + + + + + + + + @@ -2122,6 +2215,18 @@ + + + + + + + + + + + + @@ -2187,6 +2292,18 @@ + + + + + + + + + + + + @@ -2252,6 +2369,18 @@ + + + + + + + + + + + + @@ -2317,6 +2446,18 @@ + + + + + + + + + + + + @@ -2382,6 +2523,18 @@ + + + + + + + + + + + + @@ -2778,8 +2931,11 @@ - - + + + + + @@ -2857,7 +3013,6 @@ - @@ -3669,7 +3824,60 @@ - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/build.psm1 b/build.psm1 index 915d4ee0d1d..68f6a5ea070 100644 --- a/build.psm1 +++ b/build.psm1 @@ -877,8 +877,8 @@ function New-PSOptions { [ValidateSet('Debug', 'Release', 'CodeCoverage', 'StaticAnalysis', '')] [string]$Configuration, - [ValidateSet("net7.0")] - [string]$Framework = "net7.0", + [ValidateSet("net8.0")] + [string]$Framework = "net8.0", # These are duplicated from Start-PSBuild # We do not use ValidateScript since we want tab completion @@ -3484,7 +3484,7 @@ function Clear-NativeDependencies $filesToDeleteWinDesktop = @() $deps = Get-Content "$PublishFolder/pwsh.deps.json" -Raw | ConvertFrom-Json -Depth 20 - $targetRuntime = ".NETCoreApp,Version=v7.0/$($script:Options.Runtime)" + $targetRuntime = ".NETCoreApp,Version=v8.0/$($script:Options.Runtime)" $runtimePackNetCore = $deps.targets.${targetRuntime}.PSObject.Properties.Name -like 'runtimepack.Microsoft.NETCore.App.Runtime*' $runtimePackWinDesktop = $deps.targets.${targetRuntime}.PSObject.Properties.Name -like 'runtimepack.Microsoft.WindowsDesktop.App.Runtime*' diff --git a/global.json b/global.json index c3e71204cef..1fbc1e123a1 100644 --- a/global.json +++ b/global.json @@ -1,5 +1,5 @@ { "sdk": { - "version": "7.0.101" + "version": "8.0.100-preview.1.23115.2" } } diff --git a/nuget.config b/nuget.config index 314766a64f0..5137d0c33d6 100644 --- a/nuget.config +++ b/nuget.config @@ -2,7 +2,7 @@ - + diff --git a/src/Microsoft.Management.UI.Internal/Microsoft.PowerShell.GraphicalHost.csproj b/src/Microsoft.Management.UI.Internal/Microsoft.PowerShell.GraphicalHost.csproj index 607148b02fe..7a1b3a817f2 100644 --- a/src/Microsoft.Management.UI.Internal/Microsoft.PowerShell.GraphicalHost.csproj +++ b/src/Microsoft.Management.UI.Internal/Microsoft.PowerShell.GraphicalHost.csproj @@ -7,7 +7,7 @@ Microsoft.PowerShell.GraphicalHost True Windows - 7.0 + 8.0 false diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/Microsoft.PowerShell.Commands.Diagnostics.csproj b/src/Microsoft.PowerShell.Commands.Diagnostics/Microsoft.PowerShell.Commands.Diagnostics.csproj index 39d3e7aab92..87928d00dfb 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/Microsoft.PowerShell.Commands.Diagnostics.csproj +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/Microsoft.PowerShell.Commands.Diagnostics.csproj @@ -8,7 +8,7 @@ - + diff --git a/src/Microsoft.PowerShell.Commands.Management/Microsoft.PowerShell.Commands.Management.csproj b/src/Microsoft.PowerShell.Commands.Management/Microsoft.PowerShell.Commands.Management.csproj index 06bd7872cbe..07a067f518d 100644 --- a/src/Microsoft.PowerShell.Commands.Management/Microsoft.PowerShell.Commands.Management.csproj +++ b/src/Microsoft.PowerShell.Commands.Management/Microsoft.PowerShell.Commands.Management.csproj @@ -47,7 +47,7 @@ - + diff --git a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj index ea2280fac56..abd64ba98f2 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj +++ b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj @@ -32,9 +32,9 @@ - - - + + + diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/Microsoft.PowerShell.CoreCLR.Eventing.csproj b/src/Microsoft.PowerShell.CoreCLR.Eventing/Microsoft.PowerShell.CoreCLR.Eventing.csproj index 26376c5609f..cf29ac2442d 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/Microsoft.PowerShell.CoreCLR.Eventing.csproj +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/Microsoft.PowerShell.CoreCLR.Eventing.csproj @@ -8,7 +8,7 @@ - + diff --git a/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj b/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj index ec03c9c23a7..7a9c2a9eec1 100644 --- a/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj +++ b/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj @@ -16,25 +16,21 @@ - - - - - - - + + + - - - - - + + + + + - + diff --git a/src/Microsoft.WSMan.Management/Microsoft.WSMan.Management.csproj b/src/Microsoft.WSMan.Management/Microsoft.WSMan.Management.csproj index 94a13515348..5f9cdc385d4 100644 --- a/src/Microsoft.WSMan.Management/Microsoft.WSMan.Management.csproj +++ b/src/Microsoft.WSMan.Management/Microsoft.WSMan.Management.csproj @@ -10,7 +10,7 @@ - + diff --git a/src/Modules/PSGalleryModules.csproj b/src/Modules/PSGalleryModules.csproj index f2dfd6af95e..82a9db7e533 100644 --- a/src/Modules/PSGalleryModules.csproj +++ b/src/Modules/PSGalleryModules.csproj @@ -5,7 +5,7 @@ Microsoft Corporation (c) Microsoft Corporation. - net7.0 + net8.0 true diff --git a/src/ResGen/ResGen.csproj b/src/ResGen/ResGen.csproj index f86d5328ba8..5174826b96f 100644 --- a/src/ResGen/ResGen.csproj +++ b/src/ResGen/ResGen.csproj @@ -2,7 +2,7 @@ Generates C# typed bindings for .resx files - net7.0 + net8.0 resgen Exe true diff --git a/src/System.Management.Automation/SourceGenerators/PSVersionInfoGenerator/PSVersionInfoGenerator.csproj b/src/System.Management.Automation/SourceGenerators/PSVersionInfoGenerator/PSVersionInfoGenerator.csproj index c312121359d..200e06e885d 100644 --- a/src/System.Management.Automation/SourceGenerators/PSVersionInfoGenerator/PSVersionInfoGenerator.csproj +++ b/src/System.Management.Automation/SourceGenerators/PSVersionInfoGenerator/PSVersionInfoGenerator.csproj @@ -7,7 +7,7 @@ netstandard2.0 - 10.0 + 11.0 true true diff --git a/src/System.Management.Automation/System.Management.Automation.csproj b/src/System.Management.Automation/System.Management.Automation.csproj index 5a35c1c3f4e..38642bf4598 100644 --- a/src/System.Management.Automation/System.Management.Automation.csproj +++ b/src/System.Management.Automation/System.Management.Automation.csproj @@ -34,16 +34,16 @@ - - - - + + + + - + - - - + + + diff --git a/src/TypeCatalogGen/TypeCatalogGen.csproj b/src/TypeCatalogGen/TypeCatalogGen.csproj index 170819a6bf9..2ccfc7f45c1 100644 --- a/src/TypeCatalogGen/TypeCatalogGen.csproj +++ b/src/TypeCatalogGen/TypeCatalogGen.csproj @@ -2,7 +2,7 @@ Generates CorePsTypeCatalog.cs given powershell.inc - net7.0 + net8.0 true TypeCatalogGen Exe diff --git a/src/powershell-win-core/powershell-win-core.csproj b/src/powershell-win-core/powershell-win-core.csproj index 9879e8485b4..79d9e3fccfa 100644 --- a/src/powershell-win-core/powershell-win-core.csproj +++ b/src/powershell-win-core/powershell-win-core.csproj @@ -12,7 +12,7 @@ Microsoft.PowerShell ..\..\assets\pwsh.manifest Windows - 7.0 + 8.0 diff --git a/test/Test.Common.props b/test/Test.Common.props index f9cd72c099e..d59992b4774 100644 --- a/test/Test.Common.props +++ b/test/Test.Common.props @@ -6,7 +6,7 @@ Microsoft Corporation (c) Microsoft Corporation. - net7.0 + net8.0 11.0 true diff --git a/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/BenchmarkDotNet.Extensions.csproj b/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/BenchmarkDotNet.Extensions.csproj index 614d453b930..35a33bac75f 100644 --- a/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/BenchmarkDotNet.Extensions.csproj +++ b/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/BenchmarkDotNet.Extensions.csproj @@ -6,8 +6,8 @@ - - + + diff --git a/test/perf/dotnet-tools/ResultsComparer/ResultsComparer.csproj b/test/perf/dotnet-tools/ResultsComparer/ResultsComparer.csproj index c1028433f4c..e9a52f673f1 100644 --- a/test/perf/dotnet-tools/ResultsComparer/ResultsComparer.csproj +++ b/test/perf/dotnet-tools/ResultsComparer/ResultsComparer.csproj @@ -9,7 +9,7 @@ - + diff --git a/test/powershell/engine/ExperimentalFeature/Get-ExperimentalFeature.Tests.ps1 b/test/powershell/engine/ExperimentalFeature/Get-ExperimentalFeature.Tests.ps1 index 802531ab39e..d36fc3fddb8 100644 --- a/test/powershell/engine/ExperimentalFeature/Get-ExperimentalFeature.Tests.ps1 +++ b/test/powershell/engine/ExperimentalFeature/Get-ExperimentalFeature.Tests.ps1 @@ -167,7 +167,7 @@ Describe "Default enablement of Experimental Features" -Tags CI { It "On stable builds, Experimental Features are not enabled" -Skip:($isPreview) { foreach ($expFeature in Get-ExperimentalFeature) { - # In CI, pwsh that is running tests (with $PSHOME like D:\a\1\s\src\powershell-win-core\bin\release\net7.0\win7-x64\publish) + # In CI, pwsh that is running tests (with $PSHOME like D:\a\1\s\src\powershell-win-core\bin\release\net8.0\win7-x64\publish) # is launched from another pwsh (with $PSHOME like C:\program files\powershell\7) # resulting in combined PSModulePath which is used by Get-ExperimentalFeature to enum module-scoped exp.features from both pwsh locations. # So we need to exclude parent's modules' exp.features from verification using filtering on $PSHOME. @@ -188,7 +188,7 @@ Describe "Default enablement of Experimental Features" -Tags CI { foreach ($expFeature in Get-ExperimentalFeature) { - # In CI, pwsh that is running tests (with $PSHOME like D:\a\1\s\src\powershell-win-core\bin\release\net7.0\win7-x64\publish) + # In CI, pwsh that is running tests (with $PSHOME like D:\a\1\s\src\powershell-win-core\bin\release\net8.0\win7-x64\publish) # is launched from another pwsh (with $PSHOME like C:\program files\powershell\7) # resulting in combined PSModulePath which is used by Get-ExperimentalFeature to enum module-scoped exp.features from both pwsh locations. # So we need to exclude parent's modules' exp.features from verification using filtering on $PSHOME. diff --git a/test/powershell/engine/Formatting/PSStyle.Tests.ps1 b/test/powershell/engine/Formatting/PSStyle.Tests.ps1 index ba7910cb942..d8a124a2332 100644 --- a/test/powershell/engine/Formatting/PSStyle.Tests.ps1 +++ b/test/powershell/engine/Formatting/PSStyle.Tests.ps1 @@ -516,10 +516,10 @@ Billy Bob… Senior DevOps … 13 It "Wrapping long word with escape sequences" { $expected = @" `e[32;1mb : `e[0m`e[33mC:\repos\PowerShell\src\powershell-w`e[0m - `e[33min-core\bin\Debug\net7.0\win7-x64\pu`e[0m + `e[33min-core\bin\Debug\net8.0\win7-x64\pu`e[0m `e[33mblish\pwsh.exe`e[0m "@ - $obj = [pscustomobject] @{ b = "`e[33mC:\repos\PowerShell\src\powershell-win-core\bin\Debug\net7.0\win7-x64\publish\pwsh.exe" } + $obj = [pscustomobject] @{ b = "`e[33mC:\repos\PowerShell\src\powershell-win-core\bin\Debug\net8.0\win7-x64\publish\pwsh.exe" } $obj | Format-List | Out-String -Width 40 | Out-File $outFile $text = Get-Content $outFile -Raw diff --git a/test/tools/NamedPipeConnection/build.ps1 b/test/tools/NamedPipeConnection/build.ps1 index 1427971d633..dbb390d0962 100644 --- a/test/tools/NamedPipeConnection/build.ps1 +++ b/test/tools/NamedPipeConnection/build.ps1 @@ -36,8 +36,8 @@ param ( [ValidateSet("Debug", "Release")] [string] $BuildConfiguration = "Debug", - [ValidateSet("net7.0")] - [string] $BuildFramework = "net7.0" + [ValidateSet("net8.0")] + [string] $BuildFramework = "net8.0" ) $script:ModuleName = 'Microsoft.PowerShell.NamedPipeConnection' diff --git a/test/tools/NamedPipeConnection/src/code/Microsoft.PowerShell.NamedPipeConnection.csproj b/test/tools/NamedPipeConnection/src/code/Microsoft.PowerShell.NamedPipeConnection.csproj index b1e7f09fa6b..0182a55f3e6 100644 --- a/test/tools/NamedPipeConnection/src/code/Microsoft.PowerShell.NamedPipeConnection.csproj +++ b/test/tools/NamedPipeConnection/src/code/Microsoft.PowerShell.NamedPipeConnection.csproj @@ -8,9 +8,9 @@ 1.0.0.0 1.0.0 1.0.0 - net7.0 + net8.0 true - 9.0 + 11.0 diff --git a/test/tools/OpenCover/OpenCover.psm1 b/test/tools/OpenCover/OpenCover.psm1 index f9130df5ae9..886cc3a3d0c 100644 --- a/test/tools/OpenCover/OpenCover.psm1 +++ b/test/tools/OpenCover/OpenCover.psm1 @@ -624,7 +624,7 @@ function Invoke-OpenCover [parameter()]$OutputLog = "$HOME/Documents/OpenCover.xml", [parameter()]$TestPath = "${script:psRepoPath}/test/powershell", [parameter()]$OpenCoverPath = "$HOME/OpenCover", - [parameter()]$PowerShellExeDirectory = "${script:psRepoPath}/src/powershell-win-core/bin/CodeCoverage/net7.0/win7-x64/publish", + [parameter()]$PowerShellExeDirectory = "${script:psRepoPath}/src/powershell-win-core/bin/CodeCoverage/net8.0/win7-x64/publish", [parameter()]$PesterLogElevated = "$HOME/Documents/TestResultsElevated.xml", [parameter()]$PesterLogUnelevated = "$HOME/Documents/TestResultsUnelevated.xml", [parameter()]$PesterLogFormat = "NUnitXml", diff --git a/test/tools/TestService/TestService.csproj b/test/tools/TestService/TestService.csproj index 2ab58a57ddf..0e260e8dfa2 100644 --- a/test/tools/TestService/TestService.csproj +++ b/test/tools/TestService/TestService.csproj @@ -13,7 +13,7 @@ - + diff --git a/test/tools/WebListener/BrotliFilter.cs b/test/tools/WebListener/BrotliFilter.cs index 510bd1da2e3..a4947cd8f62 100644 --- a/test/tools/WebListener/BrotliFilter.cs +++ b/test/tools/WebListener/BrotliFilter.cs @@ -5,6 +5,7 @@ using System.IO; using System.IO.Compression; using System.Threading.Tasks; +using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.Filters; namespace mvc.Controllers @@ -23,7 +24,7 @@ public override async Task OnResultExecutionAsync(ResultExecutingContext context using (var compressedStream = new BrotliStream(responseStream, CompressionLevel.Fastest)) { - httpContext.Response.Headers.Add("Content-Encoding", new[] { "br" }); + httpContext.Response.Headers.Append("Content-Encoding", new[] { "br" }); memoryStream.Seek(0, SeekOrigin.Begin); await memoryStream.CopyToAsync(compressedStream); } diff --git a/test/tools/WebListener/Controllers/AuthController.cs b/test/tools/WebListener/Controllers/AuthController.cs index 6e8349ebe97..39da56b312b 100644 --- a/test/tools/WebListener/Controllers/AuthController.cs +++ b/test/tools/WebListener/Controllers/AuthController.cs @@ -9,6 +9,7 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Extensions; using Microsoft.Extensions.Primitives; using mvc.Models; @@ -28,7 +29,7 @@ public JsonResult Basic() } else { - Response.Headers.Add("WWW-Authenticate", "Basic realm=\"WebListener\""); + Response.Headers.Append("WWW-Authenticate", "Basic realm=\"WebListener\""); Response.StatusCode = 401; return Json("401 Unauthorized"); } @@ -45,7 +46,7 @@ public JsonResult Negotiate() } else { - Response.Headers.Add("WWW-Authenticate", "Negotiate"); + Response.Headers.Append("WWW-Authenticate", "Negotiate"); Response.StatusCode = 401; return Json("401 Unauthorized"); } @@ -62,7 +63,7 @@ public JsonResult Ntlm() } else { - Response.Headers.Add("WWW-Authenticate", "NTLM"); + Response.Headers.Append("WWW-Authenticate", "NTLM"); Response.StatusCode = 401; return Json("401 Unauthorized"); } diff --git a/test/tools/WebListener/Controllers/LinkController.cs b/test/tools/WebListener/Controllers/LinkController.cs index 75548d8ab2c..6abe9eab2dc 100644 --- a/test/tools/WebListener/Controllers/LinkController.cs +++ b/test/tools/WebListener/Controllers/LinkController.cs @@ -8,6 +8,7 @@ using System.Linq; using System.Text.RegularExpressions; using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Extensions; using Microsoft.Extensions.Primitives; using mvc.Models; @@ -90,7 +91,7 @@ public JsonResult Index() linkHeader = string.Join(',', linkList); } - Response.Headers.Add("Link", linkHeader); + Response.Headers.Append("Link", linkHeader); // Generate /Get/ result and append linknumber, maxlinks, and type var getController = new GetController(); diff --git a/test/tools/WebListener/Controllers/RedirectController.cs b/test/tools/WebListener/Controllers/RedirectController.cs index 551db38055d..807ffa24e58 100644 --- a/test/tools/WebListener/Controllers/RedirectController.cs +++ b/test/tools/WebListener/Controllers/RedirectController.cs @@ -10,6 +10,7 @@ using System.Text.RegularExpressions; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Extensions; using Microsoft.Extensions.Primitives; using mvc.Models; @@ -38,7 +39,7 @@ public IActionResult Index(int count) { Response.StatusCode = (int)status; url = $"{url}?type={type.FirstOrDefault()}"; - Response.Headers.Add("Location", url); + Response.Headers.Append("Location", url); } else if (typeIsPresent && string.Equals(type.FirstOrDefault(), "relative", StringComparison.InvariantCultureIgnoreCase)) { @@ -48,7 +49,7 @@ public IActionResult Index(int count) else if (destinationIsPresent) { Response.StatusCode = 302; - Response.Headers.Add("Location", url); + Response.Headers.Append("Location", url); } else { diff --git a/test/tools/WebListener/DeflateFilter.cs b/test/tools/WebListener/DeflateFilter.cs index 60d39c39d18..5399ae7df02 100644 --- a/test/tools/WebListener/DeflateFilter.cs +++ b/test/tools/WebListener/DeflateFilter.cs @@ -5,6 +5,7 @@ using System.IO; using System.IO.Compression; using System.Threading.Tasks; +using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.Filters; namespace mvc.Controllers @@ -23,7 +24,7 @@ public override async Task OnResultExecutionAsync(ResultExecutingContext context using (var compressedStream = new DeflateStream(responseStream, CompressionLevel.Fastest)) { - httpContext.Response.Headers.Add("Content-Encoding", new[] { "deflate" }); + httpContext.Response.Headers.Append("Content-Encoding", new[] { "deflate" }); memoryStream.Seek(0, SeekOrigin.Begin); await memoryStream.CopyToAsync(compressedStream); } diff --git a/test/tools/WebListener/GzipFilter.cs b/test/tools/WebListener/GzipFilter.cs index 9eab3627b5c..a1221ff4bd2 100644 --- a/test/tools/WebListener/GzipFilter.cs +++ b/test/tools/WebListener/GzipFilter.cs @@ -5,6 +5,7 @@ using System.IO; using System.IO.Compression; using System.Threading.Tasks; +using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.Filters; namespace mvc.Controllers @@ -23,7 +24,7 @@ public override async Task OnResultExecutionAsync(ResultExecutingContext context using (var compressedStream = new GZipStream(responseStream, CompressionLevel.Fastest)) { - httpContext.Response.Headers.Add("Content-Encoding", new[] { "gzip" }); + httpContext.Response.Headers.Append("Content-Encoding", new[] { "gzip" }); memoryStream.Seek(0, SeekOrigin.Begin); await memoryStream.CopyToAsync(compressedStream); } diff --git a/test/tools/WebListener/WebListener.csproj b/test/tools/WebListener/WebListener.csproj index 5e4803747cc..ad92dc867fb 100644 --- a/test/tools/WebListener/WebListener.csproj +++ b/test/tools/WebListener/WebListener.csproj @@ -7,8 +7,8 @@ - - + + diff --git a/tools/findMissingNotices.ps1 b/tools/findMissingNotices.ps1 index c7a6514d723..d1c43816b29 100644 --- a/tools/findMissingNotices.ps1 +++ b/tools/findMissingNotices.ps1 @@ -177,8 +177,8 @@ function Get-CGRegistrations { $registrationChanged = $false - $dotnetTargetName = 'net7.0' - $dotnetTargetNameWin7 = 'net7.0-windows7.0' + $dotnetTargetName = 'net8.0' + $dotnetTargetNameWin7 = 'net8.0-windows8.0' $unixProjectName = 'powershell-unix' $windowsProjectName = 'powershell-win-core' $actualRuntime = $Runtime @@ -276,7 +276,7 @@ $newRegistrations = $registrations.Keys | Sort-Object | ForEach-Object { $regist $count = $newRegistrations.Count $newJson = @{ - Registrations = $newRegistrations + Registrations = $newRegistrations '$schema' = "https://json.schemastore.org/component-detection-manifest.json" } | ConvertTo-Json -depth 99 diff --git a/tools/packaging/packaging.psm1 b/tools/packaging/packaging.psm1 index 85336f039b3..81bfa662b2a 100644 --- a/tools/packaging/packaging.psm1 +++ b/tools/packaging/packaging.psm1 @@ -16,7 +16,7 @@ $AllDistributions = @() $AllDistributions += $DebianDistributions $AllDistributions += $RedhatDistributions $AllDistributions += 'macOs' -$script:netCoreRuntime = 'net7.0' +$script:netCoreRuntime = 'net8.0' $script:iconFileName = "Powershell_black_64.png" $script:iconPath = Join-Path -path $PSScriptRoot -ChildPath "../../assets/$iconFileName" -Resolve @@ -1513,7 +1513,7 @@ function Get-PackageDependencies ) if($Script:Options.Runtime -like 'fx*') { $Dependencies += @( - "dotnet-runtime-7.0" + "dotnet-runtime-8.0" ) } } elseif ($Distribution -eq 'macOS') { @@ -2377,7 +2377,7 @@ function New-ILNugetPackageFromSource } <# - Copy the generated reference assemblies to the 'ref/net7.0' folder properly. + Copy the generated reference assemblies to the 'ref/net8.0' folder properly. This is a helper function used by 'New-ILNugetPackageSource'. #> function CopyReferenceAssemblies @@ -3330,7 +3330,7 @@ function New-MSIPatch # This example shows how to produce a Debug-x64 installer for development purposes. cd $RootPathOfPowerShellRepo Import-Module .\build.psm1; Import-Module .\tools\packaging\packaging.psm1 - New-MSIPackage -Verbose -ProductSourcePath '.\src\powershell-win-core\bin\Debug\net7.0\win7-x64\publish' -ProductTargetArchitecture x64 -ProductVersion '1.2.3' + New-MSIPackage -Verbose -ProductSourcePath '.\src\powershell-win-core\bin\Debug\net8.0\win7-x64\publish' -ProductTargetArchitecture x64 -ProductVersion '1.2.3' #> function New-MSIPackage { @@ -3721,7 +3721,7 @@ function Start-MsiBuild { # This example shows how to produce a Debug-x64 installer for development purposes. cd $RootPathOfPowerShellRepo Import-Module .\build.psm1; Import-Module .\tools\packaging\packaging.psm1 - New-MSIXPackage -Verbose -ProductSourcePath '.\src\powershell-win-core\bin\Debug\net7.0\win7-x64\publish' -ProductTargetArchitecture x64 -ProductVersion '1.2.3' + New-MSIXPackage -Verbose -ProductSourcePath '.\src\powershell-win-core\bin\Debug\net8.0\win7-x64\publish' -ProductTargetArchitecture x64 -ProductVersion '1.2.3' #> function New-MSIXPackage { diff --git a/tools/packaging/packaging.strings.psd1 b/tools/packaging/packaging.strings.psd1 index b0753a0a4fd..39afb75a96b 100644 --- a/tools/packaging/packaging.strings.psd1 +++ b/tools/packaging/packaging.strings.psd1 @@ -166,7 +166,7 @@ open {0} - + diff --git a/tools/packaging/projects/nuget/package.csproj b/tools/packaging/projects/nuget/package.csproj index d82205451ac..390283c5ef1 100644 --- a/tools/packaging/projects/nuget/package.csproj +++ b/tools/packaging/projects/nuget/package.csproj @@ -11,6 +11,6 @@ runtime=$(RID);version=$(SemVer);PackageName=$(PackageName) $(StagingPath) True - net7.0 + net8.0 diff --git a/tools/packaging/projects/reference/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj b/tools/packaging/projects/reference/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj index 4dfc566682c..027a802830d 100644 --- a/tools/packaging/projects/reference/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj +++ b/tools/packaging/projects/reference/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj @@ -1,6 +1,6 @@ - net7.0 + net8.0 $(RefAsmVersion) true $(SnkFile) diff --git a/tools/packaging/projects/reference/Microsoft.PowerShell.ConsoleHost/Microsoft.PowerShell.ConsoleHost.csproj b/tools/packaging/projects/reference/Microsoft.PowerShell.ConsoleHost/Microsoft.PowerShell.ConsoleHost.csproj index 4394e1148d1..1ac7e3f0b95 100644 --- a/tools/packaging/projects/reference/Microsoft.PowerShell.ConsoleHost/Microsoft.PowerShell.ConsoleHost.csproj +++ b/tools/packaging/projects/reference/Microsoft.PowerShell.ConsoleHost/Microsoft.PowerShell.ConsoleHost.csproj @@ -1,6 +1,6 @@ - net7.0 + net8.0 $(RefAsmVersion) true $(SnkFile) diff --git a/tools/packaging/projects/reference/System.Management.Automation/System.Management.Automation.csproj b/tools/packaging/projects/reference/System.Management.Automation/System.Management.Automation.csproj index 862cf1ddff8..4a5ea22ca9d 100644 --- a/tools/packaging/projects/reference/System.Management.Automation/System.Management.Automation.csproj +++ b/tools/packaging/projects/reference/System.Management.Automation/System.Management.Automation.csproj @@ -1,6 +1,6 @@ - net7.0 + net8.0 $(RefAsmVersion) true $(SnkFile) diff --git a/tools/releaseBuild/azureDevOps/templates/release-SDKTests.yml b/tools/releaseBuild/azureDevOps/templates/release-SDKTests.yml index 0efffbee99e..45f15074702 100644 --- a/tools/releaseBuild/azureDevOps/templates/release-SDKTests.yml +++ b/tools/releaseBuild/azureDevOps/templates/release-SDKTests.yml @@ -108,7 +108,7 @@ jobs: $localLocation = "$(Pipeline.Workspace)/releasePipeline/finalResults" $xmlElement = @" - + "@ From 91bbdda4ef818e99f1b55bde0586f975063ac4fc Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Thu, 23 Feb 2023 17:49:35 +0000 Subject: [PATCH 375/779] Set `LangVersion` compiler option to `11.0` (#18877) --- test/perf/dotnet-tools/ResultsComparer/ResultsComparer.csproj | 2 +- .../Microsoft.PowerShell.Commands.Utility.csproj | 2 +- .../Microsoft.PowerShell.ConsoleHost.csproj | 2 +- .../System.Management.Automation.csproj | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/test/perf/dotnet-tools/ResultsComparer/ResultsComparer.csproj b/test/perf/dotnet-tools/ResultsComparer/ResultsComparer.csproj index e9a52f673f1..2e0c00506c9 100644 --- a/test/perf/dotnet-tools/ResultsComparer/ResultsComparer.csproj +++ b/test/perf/dotnet-tools/ResultsComparer/ResultsComparer.csproj @@ -3,7 +3,7 @@ Exe $(PERFLAB_TARGET_FRAMEWORKS) net5.0 - latest + 11.0 diff --git a/tools/packaging/projects/reference/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj b/tools/packaging/projects/reference/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj index 027a802830d..97e38b81a19 100644 --- a/tools/packaging/projects/reference/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj +++ b/tools/packaging/projects/reference/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj @@ -5,7 +5,7 @@ true $(SnkFile) true - Latest + 11.0 diff --git a/tools/packaging/projects/reference/Microsoft.PowerShell.ConsoleHost/Microsoft.PowerShell.ConsoleHost.csproj b/tools/packaging/projects/reference/Microsoft.PowerShell.ConsoleHost/Microsoft.PowerShell.ConsoleHost.csproj index 1ac7e3f0b95..777d98d2fe6 100644 --- a/tools/packaging/projects/reference/Microsoft.PowerShell.ConsoleHost/Microsoft.PowerShell.ConsoleHost.csproj +++ b/tools/packaging/projects/reference/Microsoft.PowerShell.ConsoleHost/Microsoft.PowerShell.ConsoleHost.csproj @@ -5,7 +5,7 @@ true $(SnkFile) true - Latest + 11.0 diff --git a/tools/packaging/projects/reference/System.Management.Automation/System.Management.Automation.csproj b/tools/packaging/projects/reference/System.Management.Automation/System.Management.Automation.csproj index 4a5ea22ca9d..73f7932b174 100644 --- a/tools/packaging/projects/reference/System.Management.Automation/System.Management.Automation.csproj +++ b/tools/packaging/projects/reference/System.Management.Automation/System.Management.Automation.csproj @@ -5,7 +5,7 @@ true $(SnkFile) true - Latest + 11.0 From f718f9618b6acfdee83e08e3977291d263e3ae66 Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Thu, 23 Feb 2023 10:10:38 -0800 Subject: [PATCH 376/779] Split test artifact build into windows and non-windows (#19199) --- .../azureDevOps/templates/testartifacts.yml | 70 +++++++++++++++++-- 1 file changed, 63 insertions(+), 7 deletions(-) diff --git a/tools/releaseBuild/azureDevOps/templates/testartifacts.yml b/tools/releaseBuild/azureDevOps/templates/testartifacts.yml index b76ec0514be..b7080936757 100644 --- a/tools/releaseBuild/azureDevOps/templates/testartifacts.yml +++ b/tools/releaseBuild/azureDevOps/templates/testartifacts.yml @@ -1,16 +1,17 @@ jobs: -- job: build_testartifacts +- job: build_testartifacts_win variables: - name: runCodesignValidationInjection value: false - name: NugetSecurityAnalysisWarningLevel value: none - group: DotNetPrivateBuildAccess - displayName: Build test artifacts + displayName: Build windows test artifacts condition: succeeded() pool: - # testing - vmImage: ubuntu-latest + name: PowerShell1ES + demands: + - ImageOverride -equals PSMMS2019-Secure steps: - checkout: self clean: true @@ -46,6 +47,64 @@ jobs: win7-x64 { $packageName = "TestPackage-win-x64.zip" } win7-x86 { $packageName = "TestPackage-win-x86.zip" } win-arm64 { $packageName = "TestPackage-win-arm64.zip" } + } + + Rename-Item $(System.ArtifactsDirectory)/TestPackage.zip $packageName + Write-Host "##vso[artifact.upload containerfolder=testArtifacts;artifactname=testArtifacts]$(System.ArtifactsDirectory)/$packageName" + } + + BuildTestPackage -runtime win7-x64 + BuildTestPackage -runtime win7-x86 + BuildTestPackage -runtime win-arm64 + + displayName: Build test package and upload + retryCountOnTaskFailure: 1 + +- job: build_testartifacts_nonwin + variables: + - name: runCodesignValidationInjection + value: false + - name: NugetSecurityAnalysisWarningLevel + value: none + - group: DotNetPrivateBuildAccess + displayName: Build non-windows test artifacts + condition: succeeded() + pool: + name: PowerShell1ES + demands: + - ImageOverride -equals PSMMSUbuntu20.04-Secure + steps: + - checkout: self + clean: true + + - template: /tools/releaseBuild/azureDevOps/templates/insert-nuget-config-azfeed.yml + parameters: + repoRoot: $(Build.SourcesDirectory) + + - pwsh: | + Import-Module ./build.psm1 + Start-PSBootstrap + displayName: Bootstrap + env: + __DONET_RUNTIME_FEED: $(RUNTIME_SOURCEFEED) + __DONET_RUNTIME_FEED_KEY: $(RUNTIME_SOURCEFEED_KEY) + + - pwsh: | + Import-Module ./build.psm1 + + function BuildTestPackage([string] $runtime) + { + Write-Verbose -Verbose "Starting to build package for $runtime" + + New-TestPackage -Destination $(System.ArtifactsDirectory) -Runtime $runtime + + if (-not (Test-Path $(System.ArtifactsDirectory)/TestPackage.zip)) + { + throw "Test Package was not found at: $(System.ArtifactsDirectory)" + } + + switch ($runtime) + { linux-x64 { $packageName = "TestPackage-linux-x64.zip" } linux-arm { $packageName = "TestPackage-linux-arm.zip" } linux-arm64 { $packageName = "TestPackage-linux-arm64.zip" } @@ -57,9 +116,6 @@ jobs: Write-Host "##vso[artifact.upload containerfolder=testArtifacts;artifactname=testArtifacts]$(System.ArtifactsDirectory)/$packageName" } - BuildTestPackage -runtime win7-x64 - BuildTestPackage -runtime win7-x86 - BuildTestPackage -runtime win-arm64 BuildTestPackage -runtime linux-x64 BuildTestPackage -runtime linux-arm BuildTestPackage -runtime linux-arm64 From 6055a82f6b1141531d878fc628947c2f7c4d6fe9 Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Thu, 23 Feb 2023 18:21:38 +0000 Subject: [PATCH 377/779] Use `CallerArgumentExpression` on `Requires.NotNull` (#19200) --- .../engine/ComInterop/BoundDispEvent.cs | 4 +- .../engine/ComInterop/ComBinder.cs | 44 +++++++++---------- .../ComInterop/ComFallbackMetaObject.cs | 10 ++--- .../engine/ComInterop/ComMetaObject.cs | 12 ++--- .../engine/ComInterop/Helpers.cs | 5 ++- .../engine/ComInterop/IDispatchMetaObject.cs | 12 ++--- 6 files changed, 45 insertions(+), 42 deletions(-) diff --git a/src/System.Management.Automation/engine/ComInterop/BoundDispEvent.cs b/src/System.Management.Automation/engine/ComInterop/BoundDispEvent.cs index 6965fa6e3b5..e6549b39d22 100644 --- a/src/System.Management.Automation/engine/ComInterop/BoundDispEvent.cs +++ b/src/System.Management.Automation/engine/ComInterop/BoundDispEvent.cs @@ -73,7 +73,7 @@ private static void VerifyHandler(object handler) /// The original event with handler added. private object InPlaceAdd(object handler) { - Requires.NotNull(handler, nameof(handler)); + Requires.NotNull(handler); VerifyHandler(handler); ComEventsSink comEventSink = ComEventsSink.FromRuntimeCallableWrapper(_rcw, _sourceIid, true); @@ -88,7 +88,7 @@ private object InPlaceAdd(object handler) /// The original event with handler removed. private object InPlaceSubtract(object handler) { - Requires.NotNull(handler, nameof(handler)); + Requires.NotNull(handler); VerifyHandler(handler); ComEventsSink comEventSink = ComEventsSink.FromRuntimeCallableWrapper(_rcw, _sourceIid, false); diff --git a/src/System.Management.Automation/engine/ComInterop/ComBinder.cs b/src/System.Management.Automation/engine/ComInterop/ComBinder.cs index 37a52498e7f..a88abc09f1e 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComBinder.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComBinder.cs @@ -35,8 +35,8 @@ public static bool IsComObject(object value) /// True if operation was bound successfully; otherwise, false. public static bool TryBindGetMember(GetMemberBinder binder, DynamicMetaObject instance, out DynamicMetaObject result, bool delayInvocation) { - Requires.NotNull(binder, nameof(binder)); - Requires.NotNull(instance, nameof(instance)); + Requires.NotNull(binder); + Requires.NotNull(instance); if (TryGetMetaObject(ref instance)) { @@ -66,9 +66,9 @@ public static bool TryBindGetMember(GetMemberBinder binder, DynamicMetaObject in /// True if operation was bound successfully; otherwise, false. public static bool TryBindSetMember(SetMemberBinder binder, DynamicMetaObject instance, DynamicMetaObject value, out DynamicMetaObject result) { - Requires.NotNull(binder, nameof(binder)); - Requires.NotNull(instance, nameof(instance)); - Requires.NotNull(value, nameof(value)); + Requires.NotNull(binder); + Requires.NotNull(instance); + Requires.NotNull(value); if (TryGetMetaObject(ref instance)) { @@ -91,9 +91,9 @@ public static bool TryBindSetMember(SetMemberBinder binder, DynamicMetaObject in /// True if operation was bound successfully; otherwise, false. public static bool TryBindInvoke(InvokeBinder binder, DynamicMetaObject instance, DynamicMetaObject[] args, out DynamicMetaObject result) { - Requires.NotNull(binder, nameof(binder)); - Requires.NotNull(instance, nameof(instance)); - Requires.NotNull(args, nameof(args)); + Requires.NotNull(binder); + Requires.NotNull(instance); + Requires.NotNull(args); if (TryGetMetaObjectInvoke(ref instance)) { @@ -116,9 +116,9 @@ public static bool TryBindInvoke(InvokeBinder binder, DynamicMetaObject instance /// True if operation was bound successfully; otherwise, false. public static bool TryBindInvokeMember(InvokeMemberBinder binder, bool isSetProperty, DynamicMetaObject instance, DynamicMetaObject[] args, out DynamicMetaObject result) { - Requires.NotNull(binder, nameof(binder)); - Requires.NotNull(instance, nameof(instance)); - Requires.NotNull(args, nameof(args)); + Requires.NotNull(binder); + Requires.NotNull(instance); + Requires.NotNull(args); if (TryGetMetaObject(ref instance)) { @@ -158,9 +158,9 @@ public static bool TryBindInvokeMember(InvokeMemberBinder binder, bool isSetProp /// True if operation was bound successfully; otherwise, false. public static bool TryBindGetIndex(GetIndexBinder binder, DynamicMetaObject instance, DynamicMetaObject[] args, out DynamicMetaObject result) { - Requires.NotNull(binder, nameof(binder)); - Requires.NotNull(instance, nameof(instance)); - Requires.NotNull(args, nameof(args)); + Requires.NotNull(binder); + Requires.NotNull(instance); + Requires.NotNull(args); if (TryGetMetaObjectInvoke(ref instance)) { @@ -183,10 +183,10 @@ public static bool TryBindGetIndex(GetIndexBinder binder, DynamicMetaObject inst /// True if operation was bound successfully; otherwise, false. public static bool TryBindSetIndex(SetIndexBinder binder, DynamicMetaObject instance, DynamicMetaObject[] args, DynamicMetaObject value, out DynamicMetaObject result) { - Requires.NotNull(binder, nameof(binder)); - Requires.NotNull(instance, nameof(instance)); - Requires.NotNull(args, nameof(args)); - Requires.NotNull(value, nameof(value)); + Requires.NotNull(binder); + Requires.NotNull(instance); + Requires.NotNull(args); + Requires.NotNull(value); if (TryGetMetaObjectInvoke(ref instance)) { @@ -208,8 +208,8 @@ public static bool TryBindSetIndex(SetIndexBinder binder, DynamicMetaObject inst /// True if operation was bound successfully; otherwise, false. public static bool TryConvert(ConvertBinder binder, DynamicMetaObject instance, out DynamicMetaObject result) { - Requires.NotNull(binder, nameof(binder)); - Requires.NotNull(instance, nameof(instance)); + Requires.NotNull(binder); + Requires.NotNull(instance); if (IsComObject(instance.Value)) { @@ -245,7 +245,7 @@ public static bool TryConvert(ConvertBinder binder, DynamicMetaObject instance, /// The collection of member names. internal static IList GetDynamicDataMemberNames(object value) { - Requires.NotNull(value, nameof(value)); + Requires.NotNull(value); Requires.Condition(IsComObject(value), nameof(value)); return ComObject.ObjectToComObject(value).GetMemberNames(true); @@ -260,7 +260,7 @@ internal static IList GetDynamicDataMemberNames(object value) /// The collection of pairs that represent data member's names and their data. internal static IList> GetDynamicDataMembers(object value, IEnumerable names) { - Requires.NotNull(value, nameof(value)); + Requires.NotNull(value); Requires.Condition(IsComObject(value), nameof(value)); return ComObject.ObjectToComObject(value).GetMembers(names); diff --git a/src/System.Management.Automation/engine/ComInterop/ComFallbackMetaObject.cs b/src/System.Management.Automation/engine/ComInterop/ComFallbackMetaObject.cs index 758281c7ac4..8a6e81f0800 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComFallbackMetaObject.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComFallbackMetaObject.cs @@ -23,31 +23,31 @@ internal ComFallbackMetaObject(Expression expression, BindingRestrictions restri public override DynamicMetaObject BindGetIndex(GetIndexBinder binder, DynamicMetaObject[] indexes) { - Requires.NotNull(binder, nameof(binder)); + Requires.NotNull(binder); return binder.FallbackGetIndex(UnwrapSelf(), indexes); } public override DynamicMetaObject BindSetIndex(SetIndexBinder binder, DynamicMetaObject[] indexes, DynamicMetaObject value) { - Requires.NotNull(binder, nameof(binder)); + Requires.NotNull(binder); return binder.FallbackSetIndex(UnwrapSelf(), indexes, value); } public override DynamicMetaObject BindGetMember(GetMemberBinder binder) { - Requires.NotNull(binder, nameof(binder)); + Requires.NotNull(binder); return binder.FallbackGetMember(UnwrapSelf()); } public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args) { - Requires.NotNull(binder, nameof(binder)); + Requires.NotNull(binder); return binder.FallbackInvokeMember(UnwrapSelf(), args); } public override DynamicMetaObject BindSetMember(SetMemberBinder binder, DynamicMetaObject value) { - Requires.NotNull(binder, nameof(binder)); + Requires.NotNull(binder); return binder.FallbackSetMember(UnwrapSelf(), value); } diff --git a/src/System.Management.Automation/engine/ComInterop/ComMetaObject.cs b/src/System.Management.Automation/engine/ComInterop/ComMetaObject.cs index bc75f83ba0a..39c9d1dbe05 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComMetaObject.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComMetaObject.cs @@ -16,37 +16,37 @@ internal ComMetaObject(Expression expression, BindingRestrictions restrictions, public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args) { - Requires.NotNull(binder, nameof(binder)); + Requires.NotNull(binder); return binder.Defer(args.AddFirst(WrapSelf())); } public override DynamicMetaObject BindInvoke(InvokeBinder binder, DynamicMetaObject[] args) { - Requires.NotNull(binder, nameof(binder)); + Requires.NotNull(binder); return binder.Defer(args.AddFirst(WrapSelf())); } public override DynamicMetaObject BindGetMember(GetMemberBinder binder) { - Requires.NotNull(binder, nameof(binder)); + Requires.NotNull(binder); return binder.Defer(WrapSelf()); } public override DynamicMetaObject BindSetMember(SetMemberBinder binder, DynamicMetaObject value) { - Requires.NotNull(binder, nameof(binder)); + Requires.NotNull(binder); return binder.Defer(WrapSelf(), value); } public override DynamicMetaObject BindGetIndex(GetIndexBinder binder, DynamicMetaObject[] indexes) { - Requires.NotNull(binder, nameof(binder)); + Requires.NotNull(binder); return binder.Defer(WrapSelf(), indexes); } public override DynamicMetaObject BindSetIndex(SetIndexBinder binder, DynamicMetaObject[] indexes, DynamicMetaObject value) { - Requires.NotNull(binder, nameof(binder)); + Requires.NotNull(binder); return binder.Defer(WrapSelf(), indexes.AddLast(value)); } diff --git a/src/System.Management.Automation/engine/ComInterop/Helpers.cs b/src/System.Management.Automation/engine/ComInterop/Helpers.cs index 814e93825a7..a780e095e20 100644 --- a/src/System.Management.Automation/engine/ComInterop/Helpers.cs +++ b/src/System.Management.Automation/engine/ComInterop/Helpers.cs @@ -1,8 +1,11 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable + using System; using System.Linq.Expressions; +using System.Runtime.CompilerServices; namespace System.Management.Automation.ComInterop { @@ -33,7 +36,7 @@ internal static Expression Convert(Expression expression, Type type) internal static class Requires { [System.Diagnostics.Conditional("DEBUG")] - internal static void NotNull(object value, string paramName) + internal static void NotNull(object value, [CallerArgumentExpression("value")] string? paramName = null) { ArgumentNullException.ThrowIfNull(value, paramName); } diff --git a/src/System.Management.Automation/engine/ComInterop/IDispatchMetaObject.cs b/src/System.Management.Automation/engine/ComInterop/IDispatchMetaObject.cs index b340cf54967..9826ac9d467 100644 --- a/src/System.Management.Automation/engine/ComInterop/IDispatchMetaObject.cs +++ b/src/System.Management.Automation/engine/ComInterop/IDispatchMetaObject.cs @@ -23,7 +23,7 @@ internal IDispatchMetaObject(Expression expression, IDispatchComObject self) public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args) { - Requires.NotNull(binder, nameof(binder)); + Requires.NotNull(binder); ComMethodDesc method = null; @@ -63,7 +63,7 @@ public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, Dy public override DynamicMetaObject BindInvoke(InvokeBinder binder, DynamicMetaObject[] args) { - Requires.NotNull(binder, nameof(binder)); + Requires.NotNull(binder); if (_self.TryGetGetItem(out ComMethodDesc method)) { @@ -108,7 +108,7 @@ public override DynamicMetaObject BindGetMember(GetMemberBinder binder) ComBinder.ComGetMemberBinder comBinder = binder as ComBinder.ComGetMemberBinder; bool canReturnCallables = comBinder?._canReturnCallables ?? false; - Requires.NotNull(binder, nameof(binder)); + Requires.NotNull(binder); // 1. Try methods if (_self.TryGetMemberMethod(binder.Name, out ComMethodDesc method)) @@ -187,7 +187,7 @@ private DynamicMetaObject BindEvent(ComEventDesc eventDesc) public override DynamicMetaObject BindGetIndex(GetIndexBinder binder, DynamicMetaObject[] indexes) { - Requires.NotNull(binder, nameof(binder)); + Requires.NotNull(binder); if (_self.TryGetGetItem(out ComMethodDesc getItem)) { @@ -203,7 +203,7 @@ public override DynamicMetaObject BindGetIndex(GetIndexBinder binder, DynamicMet public override DynamicMetaObject BindSetIndex(SetIndexBinder binder, DynamicMetaObject[] indexes, DynamicMetaObject value) { - Requires.NotNull(binder, nameof(binder)); + Requires.NotNull(binder); if (_self.TryGetSetItem(out ComMethodDesc setItem)) { @@ -238,7 +238,7 @@ public override DynamicMetaObject BindSetIndex(SetIndexBinder binder, DynamicMet public override DynamicMetaObject BindSetMember(SetMemberBinder binder, DynamicMetaObject value) { - Requires.NotNull(binder, nameof(binder)); + Requires.NotNull(binder); return // 1. Check for simple property put From 0a11f799dcd557fa7593073f8cfca771c3061818 Mon Sep 17 00:00:00 2001 From: MartinGC94 <42123497+MartinGC94@users.noreply.github.com> Date: Thu, 23 Feb 2023 22:42:57 +0100 Subject: [PATCH 378/779] Add property assignment completion for enums (#19178) * Add property assignment completion for enums * Move method --- .../CommandCompletion/CompletionAnalysis.cs | 24 +++++++++++++++++++ .../TabCompletion/TabCompletion.Tests.ps1 | 5 ++++ 2 files changed, 29 insertions(+) diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs index cc7ba18284a..9315880138a 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs @@ -1421,6 +1421,24 @@ private static bool TryGetTypeConstraintOnVariable( return typeConstraint != null || setConstraint != null; } + private static List CompletePropertyAssignment(MemberExpressionAst memberExpression, CompletionContext context) + { + if (SafeExprEvaluator.TrySafeEval(memberExpression, context.ExecutionContext, out var evalValue)) + { + if (evalValue is null) + { + return null; + } + + Type type = evalValue.GetType(); + if (type.IsEnum) + { + return GetResultForEnum(type, context); + } + } + return null; + } + private static bool TryGetCompletionsForVariableAssignment( CompletionContext completionContext, AssignmentStatementAst assignmentAst, @@ -1452,6 +1470,12 @@ bool TryGetResultForSet(Type typeConstraint, ValidateSetAttribute setConstraint, return false; } + if (assignmentAst.Left is MemberExpressionAst member) + { + completions = CompletePropertyAssignment(member, completionContext); + return completions is not null; + } + completions = null; // Try to get the variable from the assignment, plus any type constraint on it diff --git a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 index eb51455fdc7..af35677834a 100644 --- a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 +++ b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 @@ -378,6 +378,11 @@ using ` $res.CompletionMatches[0].CompletionText | Should -BeExactly '${PSVersionTable}' } + It 'Should work for property assignment of enum type:' { + $res = TabExpansion2 -inputScript '$psstyle.Progress.View="Clas' + $res.CompletionMatches[0].CompletionText | Should -Be '"Classic"' + } + It 'Should work for variable assignment of enum type: ' -TestCases @( @{ inputStr = '$ErrorActionPreference = '; filter = ''; doubleQuotes = $false } @{ inputStr = '$ErrorActionPreference='; filter = ''; doubleQuotes = $false } From 4314e634cadde65a743d359106def376ed1c59ee Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Thu, 23 Feb 2023 22:15:24 +0000 Subject: [PATCH 379/779] Use `ArgumentOutOfRangeException.ThrowIfNegativeOrZero` when applicable (#19201) --- .../engine/Subsystem/FeedbackSubsystem/FeedbackHub.cs | 2 +- .../Subsystem/PredictionSubsystem/CommandPrediction.cs | 2 +- src/System.Management.Automation/engine/Utils.cs | 8 -------- 3 files changed, 2 insertions(+), 10 deletions(-) diff --git a/src/System.Management.Automation/engine/Subsystem/FeedbackSubsystem/FeedbackHub.cs b/src/System.Management.Automation/engine/Subsystem/FeedbackSubsystem/FeedbackHub.cs index 6818d25bcdb..fa12c0ca751 100644 --- a/src/System.Management.Automation/engine/Subsystem/FeedbackSubsystem/FeedbackHub.cs +++ b/src/System.Management.Automation/engine/Subsystem/FeedbackSubsystem/FeedbackHub.cs @@ -60,7 +60,7 @@ public static class FeedbackHub /// public static List? GetFeedback(Runspace runspace, int millisecondsTimeout) { - Requires.Condition(millisecondsTimeout > 0, nameof(millisecondsTimeout)); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(millisecondsTimeout); var localRunspace = runspace as LocalRunspace; if (localRunspace is null) diff --git a/src/System.Management.Automation/engine/Subsystem/PredictionSubsystem/CommandPrediction.cs b/src/System.Management.Automation/engine/Subsystem/PredictionSubsystem/CommandPrediction.cs index 7ed70e247a5..dcafbbc6233 100644 --- a/src/System.Management.Automation/engine/Subsystem/PredictionSubsystem/CommandPrediction.cs +++ b/src/System.Management.Automation/engine/Subsystem/PredictionSubsystem/CommandPrediction.cs @@ -74,7 +74,7 @@ public static class CommandPrediction /// A list of objects. public static async Task?> PredictInputAsync(PredictionClient client, Ast ast, Token[] astTokens, int millisecondsTimeout) { - Requires.Condition(millisecondsTimeout > 0, nameof(millisecondsTimeout)); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(millisecondsTimeout); var predictors = SubsystemManager.GetSubsystems(); if (predictors.Count == 0) diff --git a/src/System.Management.Automation/engine/Utils.cs b/src/System.Management.Automation/engine/Utils.cs index 74e3e468246..bb0a50e8bc4 100644 --- a/src/System.Management.Automation/engine/Utils.cs +++ b/src/System.Management.Automation/engine/Utils.cs @@ -1748,13 +1748,5 @@ internal static void NotNullOrEmpty(ICollection value, string paramName) throw new ArgumentNullException(paramName); } } - - internal static void Condition([DoesNotReturnIf(false)] bool precondition, string paramName) - { - if (!precondition) - { - throw new ArgumentException(paramName); - } - } } } From 744127608efdb07b800407c78b2a58434943e42b Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Fri, 24 Feb 2023 17:45:33 +0000 Subject: [PATCH 380/779] Replace `Requires.NotNullOrEmpty(string)` with `ArgumentException.ThrowIfNullOrEmpty` (#19197) --- .../Subsystem/FeedbackSubsystem/IFeedbackProvider.cs | 2 +- .../Subsystem/PredictionSubsystem/CommandPrediction.cs | 2 +- .../Subsystem/PredictionSubsystem/ICommandPredictor.cs | 4 ++-- src/System.Management.Automation/engine/Utils.cs | 8 -------- 4 files changed, 4 insertions(+), 12 deletions(-) diff --git a/src/System.Management.Automation/engine/Subsystem/FeedbackSubsystem/IFeedbackProvider.cs b/src/System.Management.Automation/engine/Subsystem/FeedbackSubsystem/IFeedbackProvider.cs index 52c79a46fd5..0e126f9f27a 100644 --- a/src/System.Management.Automation/engine/Subsystem/FeedbackSubsystem/IFeedbackProvider.cs +++ b/src/System.Management.Automation/engine/Subsystem/FeedbackSubsystem/IFeedbackProvider.cs @@ -89,7 +89,7 @@ public FeedbackItem(string header, List? actions, FeedbackDisplayLayout /// The layout for displaying the actions. public FeedbackItem(string header, List? actions, string? footer, FeedbackDisplayLayout layout) { - Requires.NotNullOrEmpty(header, nameof(header)); + ArgumentException.ThrowIfNullOrEmpty(header); Header = header; RecommendedActions = actions; diff --git a/src/System.Management.Automation/engine/Subsystem/PredictionSubsystem/CommandPrediction.cs b/src/System.Management.Automation/engine/Subsystem/PredictionSubsystem/CommandPrediction.cs index dcafbbc6233..3e06d046481 100644 --- a/src/System.Management.Automation/engine/Subsystem/PredictionSubsystem/CommandPrediction.cs +++ b/src/System.Management.Automation/engine/Subsystem/PredictionSubsystem/CommandPrediction.cs @@ -249,7 +249,7 @@ static Action GetCallBack(PredictionClient client, uint sessi /// The accepted suggestion text. public static void OnSuggestionAccepted(PredictionClient client, Guid predictorId, uint session, string suggestionText) { - Requires.NotNullOrEmpty(suggestionText, nameof(suggestionText)); + ArgumentException.ThrowIfNullOrEmpty(suggestionText); var predictors = SubsystemManager.GetSubsystems(); if (predictors.Count == 0) diff --git a/src/System.Management.Automation/engine/Subsystem/PredictionSubsystem/ICommandPredictor.cs b/src/System.Management.Automation/engine/Subsystem/PredictionSubsystem/ICommandPredictor.cs index 95e8487bbad..1c632c541c4 100644 --- a/src/System.Management.Automation/engine/Subsystem/PredictionSubsystem/ICommandPredictor.cs +++ b/src/System.Management.Automation/engine/Subsystem/PredictionSubsystem/ICommandPredictor.cs @@ -201,7 +201,7 @@ public PredictionContext(Ast inputAst, Token[] inputTokens) /// A object. public static PredictionContext Create(string input) { - Requires.NotNullOrEmpty(input, nameof(input)); + ArgumentException.ThrowIfNullOrEmpty(input); Ast ast = Parser.ParseInput(input, out Token[] tokens, out _); return new PredictionContext(ast, tokens); @@ -239,7 +239,7 @@ public PredictiveSuggestion(string suggestion) /// The tooltip of the suggestion. public PredictiveSuggestion(string suggestion, string? toolTip) { - Requires.NotNullOrEmpty(suggestion, nameof(suggestion)); + ArgumentException.ThrowIfNullOrEmpty(suggestion); SuggestionText = suggestion; ToolTip = toolTip; diff --git a/src/System.Management.Automation/engine/Utils.cs b/src/System.Management.Automation/engine/Utils.cs index bb0a50e8bc4..a6642e81c55 100644 --- a/src/System.Management.Automation/engine/Utils.cs +++ b/src/System.Management.Automation/engine/Utils.cs @@ -1733,14 +1733,6 @@ internal ReadOnlyBag(HashSet hashset) /// internal static class Requires { - internal static void NotNullOrEmpty(string value, string paramName) - { - if (string.IsNullOrEmpty(value)) - { - throw new ArgumentNullException(paramName); - } - } - internal static void NotNullOrEmpty(ICollection value, string paramName) { if (value is null || value.Count == 0) From 2d9dc8c0a49991af95fa4c3784080e0e48e62da6 Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Fri, 24 Feb 2023 11:35:06 -0800 Subject: [PATCH 381/779] Add pattern to replace for reference API generation (#19214) --- tools/packaging/packaging.psm1 | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/tools/packaging/packaging.psm1 b/tools/packaging/packaging.psm1 index 81bfa662b2a..6eae9550503 100644 --- a/tools/packaging/packaging.psm1 +++ b/tools/packaging/packaging.psm1 @@ -2757,6 +2757,11 @@ function CleanupGeneratedSourceCode Pattern = "[System.Runtime.CompilerServices.CompilerGeneratedAttribute, System.Runtime.CompilerServices.IsReadOnlyAttribute]" Replacement = "/* [System.Runtime.CompilerServices.CompilerGeneratedAttribute, System.Runtime.CompilerServices.IsReadOnlyAttribute] */ " }, + @{ + ApplyTo = @("System.Management.Automation") + Pattern = "[System.Runtime.CompilerServices.CompilerGeneratedAttribute, System.Runtime.CompilerServices.NullableContextAttribute((byte)1)]" + Replacement = "/* [System.Runtime.CompilerServices.CompilerGeneratedAttribute, System.Runtime.CompilerServices.NullableContextAttribute((byte)1)] */ " + }, @{ ApplyTo = @("System.Management.Automation", "Microsoft.PowerShell.ConsoleHost") Pattern = "[System.Runtime.CompilerServices.NullableAttribute((byte)2)]" From fe5f43cdc30ae5e353d3dc6a18747b9d632df811 Mon Sep 17 00:00:00 2001 From: Patrick Meinecke Date: Fri, 24 Feb 2023 15:16:43 -0500 Subject: [PATCH 382/779] Update tools metadata and README (#19204) * Update tools metadata for releases * Update README for release --- README.md | 54 ++++++++++++++++++++++----------------------- tools/metadata.json | 6 ++--- 2 files changed, 30 insertions(+), 30 deletions(-) diff --git a/README.md b/README.md index f054e00cd54..206cf0adee9 100644 --- a/README.md +++ b/README.md @@ -64,33 +64,33 @@ You can also download the PowerShell binary archives for Windows, macOS and Linu | Windows (Arm) | [64-bit][rl-winarm64] (preview) | [64-bit][pv-winarm64] | [Instructions][in-arm] | | Raspbian (Arm) | [32-bit][rl-arm32]/[64-bit][rl-arm64] | [32-bit][pv-arm32]/[64-bit][pv-arm64] | [Instructions][in-raspbian] | -[lts-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.9/PowerShell-7.2.9-win-x86.msi -[lts-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.9/PowerShell-7.2.9-win-x64.msi -[lts-deb]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.9/powershell-lts_7.2.9-1.deb_amd64.deb -[lts-rh]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.9/powershell-lts-7.2.9-1.rh.x86_64.rpm -[lts-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.9/powershell-lts-7.2.9-osx-x64.pkg -[lts-macos-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.9/powershell-lts-7.2.9-osx-arm64.pkg - -[rl-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.2/PowerShell-7.3.2-win-x64.msi -[rl-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.2/PowerShell-7.3.2-win-x86.msi -[rl-ubuntu20]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.2/powershell_7.3.2-1.deb_amd64.deb -[rl-ubuntu18]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.2/powershell_7.3.2-1.deb_amd64.deb -[rl-ubuntu16]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.2/powershell_7.3.2-1.deb_amd64.deb -[rl-debian9]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.2/powershell_7.3.2-1.deb_amd64.deb -[rl-debian10]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.2/powershell_7.3.2-1.deb_amd64.deb -[rl-debian11]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.2/powershell_7.3.2-1.deb_amd64.deb -[rl-centos]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.2/powershell-7.3.2-1.rh.x86_64.rpm -[rl-centos8]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.2/powershell-7.3.2-1.rh.x86_64.rpm -[rl-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.2/powershell-7.3.2-osx-x64.pkg -[rl-macos-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.2/powershell-7.3.2-osx-arm64.pkg -[rl-winarm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.2/PowerShell-7.3.2-win-arm64.zip -[rl-winx86-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.2/PowerShell-7.3.2-win-x86.zip -[rl-winx64-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.2/PowerShell-7.3.2-win-x64.zip -[rl-macos-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.2/powershell-7.3.2-osx-x64.tar.gz -[rl-macos-tar-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.2/powershell-7.3.2-osx-arm64.tar.gz -[rl-linux-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.2/powershell-7.3.2-linux-x64.tar.gz -[rl-arm32]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.2/powershell-7.3.2-linux-arm32.tar.gz -[rl-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.2/powershell-7.3.2-linux-arm64.tar.gz +[lts-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.10/PowerShell-7.2.10-win-x86.msi +[lts-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.10/PowerShell-7.2.10-win-x64.msi +[lts-deb]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.10/powershell-lts_7.2.10-1.deb_amd64.deb +[lts-rh]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.10/powershell-lts-7.2.10-1.rh.x86_64.rpm +[lts-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.10/powershell-lts-7.2.10-osx-x64.pkg +[lts-macos-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.10/powershell-lts-7.2.10-osx-arm64.pkg + +[rl-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.3/PowerShell-7.3.3-win-x64.msi +[rl-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.3/PowerShell-7.3.3-win-x86.msi +[rl-ubuntu20]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.3/powershell_7.3.3-1.deb_amd64.deb +[rl-ubuntu18]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.3/powershell_7.3.3-1.deb_amd64.deb +[rl-ubuntu16]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.3/powershell_7.3.3-1.deb_amd64.deb +[rl-debian9]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.3/powershell_7.3.3-1.deb_amd64.deb +[rl-debian10]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.3/powershell_7.3.3-1.deb_amd64.deb +[rl-debian11]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.3/powershell_7.3.3-1.deb_amd64.deb +[rl-centos]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.3/powershell-7.3.3-1.rh.x86_64.rpm +[rl-centos8]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.3/powershell-7.3.3-1.rh.x86_64.rpm +[rl-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.3/powershell-7.3.3-osx-x64.pkg +[rl-macos-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.3/powershell-7.3.3-osx-arm64.pkg +[rl-winarm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.3/PowerShell-7.3.3-win-arm64.zip +[rl-winx86-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.3/PowerShell-7.3.3-win-x86.zip +[rl-winx64-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.3/PowerShell-7.3.3-win-x64.zip +[rl-macos-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.3/powershell-7.3.3-osx-x64.tar.gz +[rl-macos-tar-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.3/powershell-7.3.3-osx-arm64.tar.gz +[rl-linux-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.3/powershell-7.3.3-linux-x64.tar.gz +[rl-arm32]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.3/powershell-7.3.3-linux-arm32.tar.gz +[rl-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.3/powershell-7.3.3-linux-arm64.tar.gz [rl-snap]: https://snapcraft.io/powershell [pv-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.1/PowerShell-7.4.0-preview.1-win-x64.msi diff --git a/tools/metadata.json b/tools/metadata.json index 94b577cd999..a49c16c0ee9 100644 --- a/tools/metadata.json +++ b/tools/metadata.json @@ -1,9 +1,9 @@ { - "StableReleaseTag": "v7.3.2", + "StableReleaseTag": "v7.3.3", "PreviewReleaseTag": "v7.4.0-preview.1", "ServicingReleaseTag": "v7.0.13", - "ReleaseTag": "v7.3.2", - "LTSReleaseTag" : ["v7.2.9"], + "ReleaseTag": "v7.3.3", + "LTSReleaseTag" : ["v7.2.10"], "NextReleaseTag": "v7.4.0-preview.2", "LTSRelease": { "Latest": false, "Package": false }, "StableRelease": { "Latest": false, "Package": false } From 7b7e4c865bc978f739918455396072cc9a6c5378 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 27 Feb 2023 13:59:10 -0800 Subject: [PATCH 383/779] Bump Markdig.Signed from 0.30.4 to 0.31.0 (#19232) --- .../Microsoft.PowerShell.Commands.Utility.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj index abd64ba98f2..cec526fb9b9 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj +++ b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj @@ -8,7 +8,7 @@ - + From 0ba89599b234acac4b3b2ccce64a6407b4c30326 Mon Sep 17 00:00:00 2001 From: Berkan Diler Date: Mon, 27 Feb 2023 23:03:54 +0100 Subject: [PATCH 384/779] Replace `BitConverter.ToString` with `Convert.ToHexString` where appropriate (#19216) --- .../commands/utility/GetHash.cs | 4 ++-- src/System.Management.Automation/security/CatalogHelper.cs | 2 +- src/System.Management.Automation/utils/PsUtils.cs | 2 +- src/System.Management.Automation/utils/tracing/PSEtwLog.cs | 4 ++-- src/TypeCatalogGen/TypeCatalogGen.cs | 2 +- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetHash.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetHash.cs index bf80ccbfffc..6f4b2f53cef 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetHash.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetHash.cs @@ -155,7 +155,7 @@ protected override void EndProcessing() { byte[] bytehash = ComputeHash(InputStream); - string hash = BitConverter.ToString(bytehash).Replace("-", string.Empty); + string hash = Convert.ToHexString(bytehash); WriteHashResult(Algorithm, hash, string.Empty); } } @@ -177,7 +177,7 @@ private bool ComputeFileHash(string path, out string hash) openfilestream = File.OpenRead(path); byte[] bytehash = ComputeHash(openfilestream); - hash = BitConverter.ToString(bytehash).Replace("-", string.Empty); + hash = Convert.ToHexString(bytehash); } catch (FileNotFoundException ex) { diff --git a/src/System.Management.Automation/security/CatalogHelper.cs b/src/System.Management.Automation/security/CatalogHelper.cs index 8347423f305..405e8baa384 100644 --- a/src/System.Management.Automation/security/CatalogHelper.cs +++ b/src/System.Management.Automation/security/CatalogHelper.cs @@ -457,7 +457,7 @@ internal static string CalculateFileHash(string filePath, string hashAlgorithm) _cmdlet.ThrowTerminatingError(errorRecord); } - hashValue = BitConverter.ToString(hashBytes).Replace("-", string.Empty); + hashValue = Convert.ToHexString(hashBytes); } return hashValue; diff --git a/src/System.Management.Automation/utils/PsUtils.cs b/src/System.Management.Automation/utils/PsUtils.cs index 80f9bf74e3b..0dde69ddf82 100644 --- a/src/System.Management.Automation/utils/PsUtils.cs +++ b/src/System.Management.Automation/utils/PsUtils.cs @@ -523,7 +523,7 @@ internal static byte[] ComputeHash(byte[] buffer) internal static string ComputeHash(string input) { byte[] hashBytes = ComputeHash(Encoding.UTF8.GetBytes(input)); - return BitConverter.ToString(hashBytes).Replace("-", string.Empty); + return Convert.ToHexString(hashBytes); } } diff --git a/src/System.Management.Automation/utils/tracing/PSEtwLog.cs b/src/System.Management.Automation/utils/tracing/PSEtwLog.cs index 208fdd86387..706073cff9a 100644 --- a/src/System.Management.Automation/utils/tracing/PSEtwLog.cs +++ b/src/System.Management.Automation/utils/tracing/PSEtwLog.cs @@ -244,8 +244,8 @@ internal static void LogAnalyticVerbose(PSEventId id, PSOpcode opcode, PSTask ta { if (provider.IsEnabled(PSLevel.Verbose, keyword)) { - string payLoadData = BitConverter.ToString(fragmentData.blob, fragmentData.offset, fragmentData.length); - payLoadData = string.Create(CultureInfo.InvariantCulture, $"0x{payLoadData.Replace("-", string.Empty)}"); + string payLoadData = Convert.ToHexString(fragmentData.blob, fragmentData.offset, fragmentData.length); + payLoadData = string.Create(CultureInfo.InvariantCulture, $"0x{payLoadData}"); provider.WriteEvent(id, PSChannel.Analytic, opcode, PSLevel.Verbose, task, keyword, objectId, fragmentId, isStartFragment, isEndFragment, fragmentLength, diff --git a/src/TypeCatalogGen/TypeCatalogGen.cs b/src/TypeCatalogGen/TypeCatalogGen.cs index 4bf5605fb0a..461757fcaf5 100644 --- a/src/TypeCatalogGen/TypeCatalogGen.cs +++ b/src/TypeCatalogGen/TypeCatalogGen.cs @@ -256,7 +256,7 @@ private static string GetAssemblyStrongName(MetadataReader metadataReader) } // Convert bytes to hex format strings in lower case. - string publicKeyTokenString = BitConverter.ToString(publicKeyTokenBytes).Replace("-", string.Empty).ToLowerInvariant(); + string publicKeyTokenString = Convert.ToHexString(publicKeyTokenBytes).ToLowerInvariant(); string strongAssemblyName = string.Create(CultureInfo.InvariantCulture, $"{asmName}, Version={asmVersion}, Culture={asmCulture}, PublicKeyToken={publicKeyTokenString}"); return strongAssemblyName; From 67972ada4b911c8a7e69bfe78c403c0ac2447e2d Mon Sep 17 00:00:00 2001 From: Patrick Meinecke Date: Mon, 27 Feb 2023 17:06:17 -0500 Subject: [PATCH 385/779] Pull in changelogs for v7.2.10 and v7.3.3 releases (#19219) --- .spelling | 3 +++ CHANGELOG/7.2.md | 28 ++++++++++++++++++++++++++++ CHANGELOG/7.3.md | 23 +++++++++++++++++++++++ 3 files changed, 54 insertions(+) diff --git a/.spelling b/.spelling index 958114e0359..d4f5d47ef4b 100644 --- a/.spelling +++ b/.spelling @@ -1287,6 +1287,9 @@ TabExpansion PSv2 System.Data.SqlClient Microsoft.CSharp +v7.2.10 +7.2.x +v7.3.3 - CHANGELOG.md aavdberg asrosent diff --git a/CHANGELOG/7.2.md b/CHANGELOG/7.2.md index 4e8cc516f79..d1f1da8ea9e 100644 --- a/CHANGELOG/7.2.md +++ b/CHANGELOG/7.2.md @@ -1,5 +1,33 @@ # 7.2 Changelog +## [7.2.10] - 2023-02-23 + +### Build and Packaging Improvements + +
    + + + +

    Bump .NET version to 6.0.14

    + +
    + +
      +
    • Fixed package names verification to support multi-digit versions (#17220)
    • +
    • Add pipeline secrets (from #17837) (Internal 24413)
    • +
    • Update to azCopy 10 (#18509)
    • +
    • Update third party notices for v7.2.10 (Internal 24346)
    • +
    • Update cgmanifest for v7.2.10 (Internal 24333)
    • +
    • Pull latest patches for 7.2.10 dependencies (Internal 24325)
    • +
    • Update SDK to 6.0.406 for v7.2.10 (Internal 24324)
    • +
    • Add test for framework dependent package in release pipeline (#18506) (#19114)
    • +
    • Mark 7.2.x releases as latest LTS but not latest stable (#19069)
    • +
    + +
    + +[7.2.10]: https://github.com/PowerShell/PowerShell/compare/v7.2.9...v7.2.10 + ## [7.2.9] - 2023-01-24 ### Engine Updates and Fixes diff --git a/CHANGELOG/7.3.md b/CHANGELOG/7.3.md index e513c444d5a..57c1e3b99f3 100644 --- a/CHANGELOG/7.3.md +++ b/CHANGELOG/7.3.md @@ -1,5 +1,28 @@ # 7.3 Changelog +## [7.3.3] - 2023-02-23 + +### Build and Packaging Improvements + +
    + + + +

    Bump to use .NET 7.0.3

    + +
    + +
      +
    • Update third party notices for v7.3.3 (Internal 24353)
    • +
    • Add tool to trigger license information gathering for NuGet modules (#18827)
    • +
    • Update global.json to 7.0.200 for v7.3.3 (Internal 24334)
    • +
    • Update cgmanifest for v7.3.3 (Internal 24338)
    • +
    + +
    + +[7.3.3]: https://github.com/PowerShell/PowerShell/compare/v7.3.2...v7.3.3 + ## [7.3.2] - 2023-01-24 ### Engine Updates and Fixes From 4284a318c059ccdb393c1a4c32b6c617e4e3bc69 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 27 Feb 2023 14:10:52 -0800 Subject: [PATCH 386/779] Bump Microsoft.CodeAnalysis.CSharp from 4.4.0 to 4.5.0 (#19233) --- .../Microsoft.PowerShell.Commands.Utility.csproj | 2 +- .../PSVersionInfoGenerator/PSVersionInfoGenerator.csproj | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj index cec526fb9b9..ac469c4fd9f 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj +++ b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj @@ -32,7 +32,7 @@
    - + diff --git a/src/System.Management.Automation/SourceGenerators/PSVersionInfoGenerator/PSVersionInfoGenerator.csproj b/src/System.Management.Automation/SourceGenerators/PSVersionInfoGenerator/PSVersionInfoGenerator.csproj index 200e06e885d..cc807a81cfd 100644 --- a/src/System.Management.Automation/SourceGenerators/PSVersionInfoGenerator/PSVersionInfoGenerator.csproj +++ b/src/System.Management.Automation/SourceGenerators/PSVersionInfoGenerator/PSVersionInfoGenerator.csproj @@ -13,7 +13,7 @@ - + From c48e5cbcca9addd6884b0b673e1241565ed68acc Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Mon, 27 Feb 2023 23:42:07 +0100 Subject: [PATCH 387/779] Use `ArgumentException.ThrowIfNullOrEmpty()` in more places (#19213) --- .../ManagementList/Common/WpfHelp.cs | 5 +-- .../PropertyValueSelectorFilterRule.cs | 11 ++---- .../FilterCore/ValidatingValueBase.cs | 5 +-- .../FilterProviders/FilterRulePanelItem.cs | 6 +--- .../commands/utility/CsvCommands.cs | 1 - .../utility/trace/TraceExpressionCommand.cs | 3 +- .../ConfigProvider.cs | 5 +-- .../CurrentConfigurations.cs | 17 ++-------- src/Microsoft.WSMan.Management/WsManHelper.cs | 6 +--- .../CoreCLR/CorePsAssemblyLoadContext.cs | 5 +-- .../cmdletization/ObjectModelWrapper.cs | 7 +--- .../engine/CommandInfo.cs | 5 +-- .../engine/Modules/ModuleSpecification.cs | 6 ++-- .../engine/Modules/PSModuleInfo.cs | 5 +-- .../engine/PSClassInfo.cs | 5 +-- .../remoting/commands/InvokeCommandCommand.cs | 5 +-- .../namespaces/FileSystemProvider.cs | 11 ++---- .../utils/MshTraceSource.cs | 34 +++++-------------- .../utils/StructuredTraceSource.cs | 8 +---- .../utils/perfCounters/PSPerfCountersMgr.cs | 14 +++----- test/xUnit/csharp/test_FileSystemProvider.cs | 2 +- 21 files changed, 36 insertions(+), 130 deletions(-) diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/WpfHelp.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/WpfHelp.cs index 4bc9ebef28d..42b8a06b845 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/WpfHelp.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/WpfHelp.cs @@ -419,10 +419,7 @@ public static T GetOptionalTemplateChild(Control templateParent, string child { ArgumentNullException.ThrowIfNull(templateParent); - if (string.IsNullOrEmpty(childName)) - { - throw new ArgumentNullException("childName"); - } + ArgumentException.ThrowIfNullOrEmpty(childName); object templatePart = templateParent.Template.FindName(childName, templateParent); T item = templatePart as T; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/PropertyValueSelectorFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/PropertyValueSelectorFilterRule.cs index f1bf8520a99..9143336aa4c 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/PropertyValueSelectorFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/PropertyValueSelectorFilterRule.cs @@ -66,15 +66,8 @@ public PropertyValueSelectorFilterRule(string propertyName, string propertyDispl /// public PropertyValueSelectorFilterRule(string propertyName, string propertyDisplayName, IEnumerable rules) { - if (string.IsNullOrEmpty(propertyName)) - { - throw new ArgumentNullException("propertyName"); - } - - if (string.IsNullOrEmpty(propertyDisplayName)) - { - throw new ArgumentNullException("propertyDisplayName"); - } + ArgumentException.ThrowIfNullOrEmpty(propertyName); + ArgumentException.ThrowIfNullOrEmpty(propertyDisplayName); ArgumentNullException.ThrowIfNull(rules); diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValueBase.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValueBase.cs index 3a072180278..fc2b331f583 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValueBase.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValueBase.cs @@ -83,10 +83,7 @@ public string this[string columnName] { get { - if (string.IsNullOrEmpty(columnName)) - { - throw new ArgumentNullException("columnName"); - } + ArgumentException.ThrowIfNullOrEmpty(columnName); this.UpdateValidationResult(columnName); return this.GetValidationResult().ErrorMessage; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanelItem.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanelItem.cs index 2378f9238d8..60ad54e6613 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanelItem.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanelItem.cs @@ -80,11 +80,7 @@ protected internal set public FilterRulePanelItem(FilterRule rule, string groupId) { ArgumentNullException.ThrowIfNull(rule); - - if (string.IsNullOrEmpty(groupId)) - { - throw new ArgumentNullException("groupId"); - } + ArgumentException.ThrowIfNullOrEmpty(groupId); this.Rule = rule; this.GroupId = groupId; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs index 2434ad836f3..b1f24414f89 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs @@ -1274,7 +1274,6 @@ internal class ImportCsvHelper internal ImportCsvHelper(PSCmdlet cmdlet, char delimiter, IList header, string typeName, StreamReader streamReader) { ArgumentNullException.ThrowIfNull(cmdlet); - ArgumentNullException.ThrowIfNull(streamReader); _cmdlet = cmdlet; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs index 4a38d14845c..d73df70a97a 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs @@ -330,8 +330,7 @@ internal TracePipelineWriter( bool writeError, Collection matchingSources) { - ArgumentNullException.ThrowIfNull(cmdlet); - + ArgumentNullException.ThrowIfNull(cmdlet); ArgumentNullException.ThrowIfNull(matchingSources); _cmdlet = cmdlet; diff --git a/src/Microsoft.WSMan.Management/ConfigProvider.cs b/src/Microsoft.WSMan.Management/ConfigProvider.cs index d40e4161188..a5d9d6a7cb0 100644 --- a/src/Microsoft.WSMan.Management/ConfigProvider.cs +++ b/src/Microsoft.WSMan.Management/ConfigProvider.cs @@ -3413,10 +3413,7 @@ private static string NormalizePath(string path, string host) /// private PSObject GetItemValue(string path) { - if (string.IsNullOrEmpty(path)) - { - throw new ArgumentNullException(path); - } + ArgumentException.ThrowIfNullOrEmpty(path); // if endswith '\', removes it. if (path.EndsWith(WSManStringLiterals.DefaultPathSeparator.ToString(), StringComparison.OrdinalIgnoreCase)) diff --git a/src/Microsoft.WSMan.Management/CurrentConfigurations.cs b/src/Microsoft.WSMan.Management/CurrentConfigurations.cs index 81d4ecfd870..f4c252c4d1d 100644 --- a/src/Microsoft.WSMan.Management/CurrentConfigurations.cs +++ b/src/Microsoft.WSMan.Management/CurrentConfigurations.cs @@ -76,10 +76,7 @@ public CurrentConfigurations(IWSManSession serverSession) /// False, if operation failed. public bool RefreshCurrentConfiguration(string responseOfGet) { - if (string.IsNullOrEmpty(responseOfGet)) - { - throw new ArgumentNullException(nameof(responseOfGet)); - } + ArgumentException.ThrowIfNullOrEmpty(responseOfGet); this.rootDocument.LoadXml(responseOfGet); this.documentElement = this.rootDocument.DocumentElement; @@ -98,10 +95,7 @@ public bool RefreshCurrentConfiguration(string responseOfGet) /// False, if operation is not successful. public void PutConfigurationOnServer(string resourceUri) { - if (string.IsNullOrEmpty(resourceUri)) - { - throw new ArgumentNullException(nameof(resourceUri)); - } + ArgumentException.ThrowIfNullOrEmpty(resourceUri); this.serverSession.Put(resourceUri, this.rootDocument.InnerXml, 0); } @@ -145,12 +139,7 @@ public void RemoveOneConfiguration(string pathToNodeFromRoot) public void UpdateOneConfiguration(string pathToNodeFromRoot, string configurationName, string configurationValue) { ArgumentNullException.ThrowIfNull(pathToNodeFromRoot); - - if (string.IsNullOrEmpty(configurationName)) - { - throw new ArgumentNullException(nameof(configurationName)); - } - + ArgumentException.ThrowIfNullOrEmpty(configurationName); ArgumentNullException.ThrowIfNull(configurationValue); XmlNode nodeToUpdate = diff --git a/src/Microsoft.WSMan.Management/WsManHelper.cs b/src/Microsoft.WSMan.Management/WsManHelper.cs index 83b1f0a72a3..482f24aa9c1 100644 --- a/src/Microsoft.WSMan.Management/WsManHelper.cs +++ b/src/Microsoft.WSMan.Management/WsManHelper.cs @@ -179,11 +179,7 @@ private static string FormatResourceMsgFromResourcetextS( object[] args) { ArgumentNullException.ThrowIfNull(resourceManager); - - if (string.IsNullOrEmpty(resourceName)) - { - throw new ArgumentNullException(nameof(resourceName)); - } + ArgumentException.ThrowIfNullOrEmpty(resourceName); string template = resourceManager.GetString(resourceName); diff --git a/src/System.Management.Automation/CoreCLR/CorePsAssemblyLoadContext.cs b/src/System.Management.Automation/CoreCLR/CorePsAssemblyLoadContext.cs index 6a9462f37d4..0aba1eddfe4 100644 --- a/src/System.Management.Automation/CoreCLR/CorePsAssemblyLoadContext.cs +++ b/src/System.Management.Automation/CoreCLR/CorePsAssemblyLoadContext.cs @@ -579,10 +579,7 @@ public static class PowerShellAssemblyLoadContextInitializer /// public static void SetPowerShellAssemblyLoadContext([MarshalAs(UnmanagedType.LPWStr)] string basePaths) { - if (string.IsNullOrEmpty(basePaths)) - { - throw new ArgumentNullException(nameof(basePaths)); - } + ArgumentException.ThrowIfNullOrEmpty(basePaths); PowerShellAssemblyLoadContext.InitializeSingleton(basePaths); } diff --git a/src/System.Management.Automation/cimSupport/cmdletization/ObjectModelWrapper.cs b/src/System.Management.Automation/cimSupport/cmdletization/ObjectModelWrapper.cs index e52582fc985..325d8c52c99 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/ObjectModelWrapper.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/ObjectModelWrapper.cs @@ -18,15 +18,10 @@ public abstract class CmdletAdapter internal void Initialize(PSCmdlet cmdlet, string className, string classVersion, IDictionary privateData) { ArgumentNullException.ThrowIfNull(cmdlet); - - if (string.IsNullOrEmpty(className)) - { - throw new ArgumentNullException(nameof(className)); - } + ArgumentException.ThrowIfNullOrEmpty(className); // possible and ok to have classVersion==string.Empty ArgumentNullException.ThrowIfNull(classVersion); - ArgumentNullException.ThrowIfNull(privateData); _cmdlet = cmdlet; diff --git a/src/System.Management.Automation/engine/CommandInfo.cs b/src/System.Management.Automation/engine/CommandInfo.cs index 7cd213a025c..6b90b1d1640 100644 --- a/src/System.Management.Automation/engine/CommandInfo.cs +++ b/src/System.Management.Automation/engine/CommandInfo.cs @@ -285,10 +285,7 @@ internal void SetCommandType(CommandTypes newType) /// internal void Rename(string newName) { - if (string.IsNullOrEmpty(newName)) - { - throw new ArgumentNullException(nameof(newName)); - } + ArgumentException.ThrowIfNullOrEmpty(newName); Name = newName; } diff --git a/src/System.Management.Automation/engine/Modules/ModuleSpecification.cs b/src/System.Management.Automation/engine/Modules/ModuleSpecification.cs index a89837b3da2..8c333ec154f 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleSpecification.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleSpecification.cs @@ -44,12 +44,10 @@ public ModuleSpecification() /// The module name. public ModuleSpecification(string moduleName) { - if (string.IsNullOrEmpty(moduleName)) - { - throw new ArgumentNullException(nameof(moduleName)); - } + ArgumentException.ThrowIfNullOrEmpty(moduleName); this.Name = moduleName; + // Alias name of miniumVersion this.Version = null; this.RequiredVersion = null; diff --git a/src/System.Management.Automation/engine/Modules/PSModuleInfo.cs b/src/System.Management.Automation/engine/Modules/PSModuleInfo.cs index d4cc2214b05..48e0cee0797 100644 --- a/src/System.Management.Automation/engine/Modules/PSModuleInfo.cs +++ b/src/System.Management.Automation/engine/Modules/PSModuleInfo.cs @@ -1302,10 +1302,7 @@ public object Invoke(ScriptBlock sb, params object[] args) /// public PSVariable GetVariableFromCallersModule(string variableName) { - if (string.IsNullOrEmpty(variableName)) - { - throw new ArgumentNullException(nameof(variableName)); - } + ArgumentException.ThrowIfNullOrEmpty(variableName); var context = LocalPipeline.GetExecutionContextFromTLS(); SessionState callersSessionState = null; diff --git a/src/System.Management.Automation/engine/PSClassInfo.cs b/src/System.Management.Automation/engine/PSClassInfo.cs index c73e9250071..10b2cf1101d 100644 --- a/src/System.Management.Automation/engine/PSClassInfo.cs +++ b/src/System.Management.Automation/engine/PSClassInfo.cs @@ -61,10 +61,7 @@ public sealed class PSClassMemberInfo /// internal PSClassMemberInfo(string name, string memberType, string defaultValue) { - if (string.IsNullOrEmpty(name)) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentException.ThrowIfNullOrEmpty(name); this.Name = name; this.TypeName = memberType; diff --git a/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs b/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs index 0942c305979..9ee5969aff1 100644 --- a/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs @@ -2167,10 +2167,7 @@ public void StartProgress( return; } - if (string.IsNullOrEmpty(computerName)) - { - throw new ArgumentNullException(nameof(computerName)); - } + ArgumentException.ThrowIfNullOrEmpty(computerName); lock (_syncObject) { diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index 30db2e27180..3d4c3e2f9da 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -7960,15 +7960,8 @@ internal static bool CreateJunction(string path, string target) #if UNIX return false; #else - if (string.IsNullOrEmpty(path)) - { - throw new ArgumentNullException(nameof(path)); - } - - if (string.IsNullOrEmpty(target)) - { - throw new ArgumentNullException(nameof(target)); - } + ArgumentException.ThrowIfNullOrEmpty(path); + ArgumentException.ThrowIfNullOrEmpty(target); using (SafeHandle handle = WinOpenReparsePoint(path, FileAccess.Write)) { diff --git a/src/System.Management.Automation/utils/MshTraceSource.cs b/src/System.Management.Automation/utils/MshTraceSource.cs index 25fcc7b940e..dd7d3214ff3 100644 --- a/src/System.Management.Automation/utils/MshTraceSource.cs +++ b/src/System.Management.Automation/utils/MshTraceSource.cs @@ -98,13 +98,7 @@ internal static PSTraceSource GetTracer( string description, bool traceHeaders) { - if (string.IsNullOrEmpty(name)) - { - // 2005/04/13-JonN In theory this should be ArgumentException, - // but I don't want to deal with loading the string in this - // low-level code. - throw new ArgumentNullException(nameof(name)); - } + ArgumentException.ThrowIfNullOrEmpty(name); lock (PSTraceSource.s_getTracerLock) { @@ -182,13 +176,9 @@ internal static PSTraceSource GetNewTraceSource( string description, bool traceHeaders) { - if (string.IsNullOrEmpty(name)) - { - // Note, all callers should have already verified the name before calling this - // API, so this exception should never be exposed to an end-user. - - throw new ArgumentException("name"); - } + // Note, all callers should have already verified the name before calling this + // API, so this exception should never be exposed to an end-user. + ArgumentException.ThrowIfNullOrEmpty(name); // Keep the fullName as it was passed, but truncate or pad // the category name to 16 characters. This allows for @@ -228,10 +218,7 @@ internal static PSTraceSource GetNewTraceSource( /// Exception instance ready to throw. internal static PSArgumentNullException NewArgumentNullException(string paramName) { - if (string.IsNullOrEmpty(paramName)) - { - throw new ArgumentNullException(nameof(paramName)); - } + ArgumentException.ThrowIfNullOrEmpty(paramName); string message = StringUtil.Format(AutomationExceptions.ArgumentNull, paramName); var e = new PSArgumentNullException(paramName, message); @@ -287,12 +274,10 @@ internal static PSArgumentNullException NewArgumentNullException( /// Exception instance ready to throw. internal static PSArgumentException NewArgumentException(string paramName) { - if (string.IsNullOrEmpty(paramName)) - { - throw new ArgumentNullException(nameof(paramName)); - } + ArgumentException.ThrowIfNullOrEmpty(paramName); string message = StringUtil.Format(AutomationExceptions.Argument, paramName); + // Note that the message param comes first var e = new PSArgumentException(message, paramName); @@ -477,10 +462,7 @@ internal static PSNotImplementedException NewNotImplementedException() /// Exception instance ready to throw. internal static PSArgumentOutOfRangeException NewArgumentOutOfRangeException(string paramName, object actualValue) { - if (string.IsNullOrEmpty(paramName)) - { - throw new ArgumentNullException(nameof(paramName)); - } + ArgumentException.ThrowIfNullOrEmpty(paramName); string message = StringUtil.Format(AutomationExceptions.ArgumentOutOfRange, paramName); var e = new PSArgumentOutOfRangeException(paramName, actualValue, message); diff --git a/src/System.Management.Automation/utils/StructuredTraceSource.cs b/src/System.Management.Automation/utils/StructuredTraceSource.cs index 8d47ac61c9d..be5f10da080 100644 --- a/src/System.Management.Automation/utils/StructuredTraceSource.cs +++ b/src/System.Management.Automation/utils/StructuredTraceSource.cs @@ -269,13 +269,7 @@ public partial class PSTraceSource /// internal PSTraceSource(string fullName, string name, string description, bool traceHeaders) { - if (string.IsNullOrEmpty(fullName)) - { - // 2005/04/13-JonN In theory this should be ArgumentException, - // but I don't want to deal with loading the string in this - // low-level code. - throw new ArgumentNullException(nameof(fullName)); - } + ArgumentException.ThrowIfNullOrEmpty(fullName); try { diff --git a/src/System.Management.Automation/utils/perfCounters/PSPerfCountersMgr.cs b/src/System.Management.Automation/utils/perfCounters/PSPerfCountersMgr.cs index 6fb3e012ef3..761de0c6360 100644 --- a/src/System.Management.Automation/utils/perfCounters/PSPerfCountersMgr.cs +++ b/src/System.Management.Automation/utils/perfCounters/PSPerfCountersMgr.cs @@ -78,7 +78,7 @@ public bool IsCounterSetRegistered(string counterSetName, out Guid counterSetId) counterSetId = new Guid(); if (counterSetName == null) { - ArgumentNullException argNullException = new ArgumentNullException("counterSetName"); + ArgumentNullException argNullException = new ArgumentNullException(nameof(counterSetName)); _tracer.TraceException(argNullException); return false; } @@ -233,8 +233,7 @@ public bool UpdateCounterByValue( { if (counterSetName == null) { - ArgumentNullException argNullException = - new ArgumentNullException("counterSetName"); + ArgumentNullException argNullException = new ArgumentNullException(nameof(counterSetName)); _tracer.TraceException(argNullException); return false; } @@ -275,8 +274,7 @@ public bool UpdateCounterByValue( Guid counterSetId; if (counterSetName == null) { - ArgumentNullException argNullException = - new ArgumentNullException("counterSetName"); + ArgumentNullException argNullException = new ArgumentNullException(nameof(counterSetName)); _tracer.TraceException(argNullException); return false; } @@ -376,8 +374,7 @@ public bool SetCounterValue( { if (counterSetName == null) { - ArgumentNullException argNullException = - new ArgumentNullException("counterSetName"); + ArgumentNullException argNullException = new ArgumentNullException(nameof(counterSetName)); _tracer.TraceException(argNullException); return false; } @@ -416,8 +413,7 @@ public bool SetCounterValue( { if (counterSetName == null) { - ArgumentNullException argNullException = - new ArgumentNullException("counterSetName"); + ArgumentNullException argNullException = new ArgumentNullException(nameof(counterSetName)); _tracer.TraceException(argNullException); return false; } diff --git a/test/xUnit/csharp/test_FileSystemProvider.cs b/test/xUnit/csharp/test_FileSystemProvider.cs index 85ab0b2eedd..1bea0f84ce4 100644 --- a/test/xUnit/csharp/test_FileSystemProvider.cs +++ b/test/xUnit/csharp/test_FileSystemProvider.cs @@ -84,7 +84,7 @@ public void TestCreateJunctionFails() } else { - Assert.Throws(delegate { InternalSymbolicLinkLinkCodeMethods.CreateJunction(string.Empty, string.Empty); }); + Assert.Throws(delegate { InternalSymbolicLinkLinkCodeMethods.CreateJunction(string.Empty, string.Empty); }); } } From 476af582d56b25913d1ff9dc8057e1a484f814a9 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Mon, 27 Feb 2023 23:43:15 +0100 Subject: [PATCH 388/779] Use `using` variable to reduce the nested level (#19229) --- .../Common/WebRequestPSCmdlet.Common.cs | 231 +++++++++--------- 1 file changed, 115 insertions(+), 116 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index 567a98ebfb9..70f03f5ddef 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -517,154 +517,153 @@ protected override void ProcessRecord() bool handleRedirect = keepAuthorizationOnRedirect || AllowInsecureRedirect || PreserveHttpMethodOnRedirect; - using (HttpClient client = GetHttpClient(handleRedirect)) + using HttpClient client = GetHttpClient(handleRedirect); + + int followedRelLink = 0; + Uri uri = Uri; + do { - int followedRelLink = 0; - Uri uri = Uri; - do + if (followedRelLink > 0) { - if (followedRelLink > 0) - { - string linkVerboseMsg = string.Format( - CultureInfo.CurrentCulture, - WebCmdletStrings.FollowingRelLinkVerboseMsg, - uri.AbsoluteUri); + string linkVerboseMsg = string.Format( + CultureInfo.CurrentCulture, + WebCmdletStrings.FollowingRelLinkVerboseMsg, + uri.AbsoluteUri); - WriteVerbose(linkVerboseMsg); - } + WriteVerbose(linkVerboseMsg); + } - using (HttpRequestMessage request = GetRequest(uri)) + using (HttpRequestMessage request = GetRequest(uri)) + { + FillRequestStream(request); + try { - FillRequestStream(request); - try - { - long requestContentLength = request.Content is null ? 0 : request.Content.Headers.ContentLength.Value; + long requestContentLength = request.Content is null ? 0 : request.Content.Headers.ContentLength.Value; - string reqVerboseMsg = string.Format( - CultureInfo.CurrentCulture, - WebCmdletStrings.WebMethodInvocationVerboseMsg, - request.Version, - request.Method, - requestContentLength); + string reqVerboseMsg = string.Format( + CultureInfo.CurrentCulture, + WebCmdletStrings.WebMethodInvocationVerboseMsg, + request.Version, + request.Method, + requestContentLength); - WriteVerbose(reqVerboseMsg); + WriteVerbose(reqVerboseMsg); - using HttpResponseMessage response = GetResponse(client, request, handleRedirect); + using HttpResponseMessage response = GetResponse(client, request, handleRedirect); - string contentType = ContentHelper.GetContentType(response); - string respVerboseMsg = string.Format( - CultureInfo.CurrentCulture, - WebCmdletStrings.WebResponseVerboseMsg, - response.Content.Headers.ContentLength, - contentType); + string contentType = ContentHelper.GetContentType(response); + string respVerboseMsg = string.Format( + CultureInfo.CurrentCulture, + WebCmdletStrings.WebResponseVerboseMsg, + response.Content.Headers.ContentLength, + contentType); - WriteVerbose(respVerboseMsg); + WriteVerbose(respVerboseMsg); - bool _isSuccess = response.IsSuccessStatusCode; + bool _isSuccess = response.IsSuccessStatusCode; - // Check if the Resume range was not satisfiable because the file already completed downloading. - // This happens when the local file is the same size as the remote file. - if (Resume.IsPresent - && response.StatusCode == HttpStatusCode.RequestedRangeNotSatisfiable - && response.Content.Headers.ContentRange.HasLength - && response.Content.Headers.ContentRange.Length == _resumeFileSize) - { - _isSuccess = true; - WriteVerbose(string.Format( - CultureInfo.CurrentCulture, - WebCmdletStrings.OutFileWritingSkipped, - OutFile)); - - // Disable writing to the OutFile. - OutFile = null; - } + // Check if the Resume range was not satisfiable because the file already completed downloading. + // This happens when the local file is the same size as the remote file. + if (Resume.IsPresent + && response.StatusCode == HttpStatusCode.RequestedRangeNotSatisfiable + && response.Content.Headers.ContentRange.HasLength + && response.Content.Headers.ContentRange.Length == _resumeFileSize) + { + _isSuccess = true; + WriteVerbose(string.Format( + CultureInfo.CurrentCulture, + WebCmdletStrings.OutFileWritingSkipped, + OutFile)); + + // Disable writing to the OutFile. + OutFile = null; + } - // Detect insecure redirection - if (!AllowInsecureRedirect && response.RequestMessage.RequestUri.Scheme == "https" && response.Headers.Location?.Scheme == "http") - { - ErrorRecord er = new(new InvalidOperationException(), "InsecureRedirection", ErrorCategory.InvalidOperation, request); - er.ErrorDetails = new ErrorDetails(WebCmdletStrings.InsecureRedirection); - ThrowTerminatingError(er); - } + // Detect insecure redirection + if (!AllowInsecureRedirect && response.RequestMessage.RequestUri.Scheme == "https" && response.Headers.Location?.Scheme == "http") + { + ErrorRecord er = new(new InvalidOperationException(), "InsecureRedirection", ErrorCategory.InvalidOperation, request); + er.ErrorDetails = new ErrorDetails(WebCmdletStrings.InsecureRedirection); + ThrowTerminatingError(er); + } - if (ShouldCheckHttpStatus && !_isSuccess) + if (ShouldCheckHttpStatus && !_isSuccess) + { + string message = string.Format( + CultureInfo.CurrentCulture, + WebCmdletStrings.ResponseStatusCodeFailure, + (int)response.StatusCode, + response.ReasonPhrase); + + HttpResponseException httpEx = new(message, response); + ErrorRecord er = new(httpEx, "WebCmdletWebResponseException", ErrorCategory.InvalidOperation, request); + string detailMsg = string.Empty; + StreamReader reader = null; + try { - string message = string.Format( - CultureInfo.CurrentCulture, - WebCmdletStrings.ResponseStatusCodeFailure, - (int)response.StatusCode, - response.ReasonPhrase); - - HttpResponseException httpEx = new(message, response); - ErrorRecord er = new(httpEx, "WebCmdletWebResponseException", ErrorCategory.InvalidOperation, request); - string detailMsg = string.Empty; - StreamReader reader = null; - try - { - reader = new StreamReader(StreamHelper.GetResponseStream(response)); - detailMsg = FormatErrorMessage(reader.ReadToEnd(), contentType); - } - catch - { - // Catch all - } - finally - { - reader?.Dispose(); - } - - if (!string.IsNullOrEmpty(detailMsg)) - { - er.ErrorDetails = new ErrorDetails(detailMsg); - } - - ThrowTerminatingError(er); + reader = new StreamReader(StreamHelper.GetResponseStream(response)); + detailMsg = FormatErrorMessage(reader.ReadToEnd(), contentType); } - - if (_parseRelLink || _followRelLink) + catch { - ParseLinkHeader(response); + // Catch all } - - ProcessResponse(response); - UpdateSession(response); - - // If we hit our maximum redirection count, generate an error. - // Errors with redirection counts of greater than 0 are handled automatically by .NET, but are - // impossible to detect programmatically when we hit this limit. By handling this ourselves - // (and still writing out the result), users can debug actual HTTP redirect problems. - if (WebSession.MaximumRedirection == 0 && IsRedirectCode(response.StatusCode)) + finally { - ErrorRecord er = new(new InvalidOperationException(), "MaximumRedirectExceeded", ErrorCategory.InvalidOperation, request); - er.ErrorDetails = new ErrorDetails(WebCmdletStrings.MaximumRedirectionCountExceeded); - WriteError(er); + reader?.Dispose(); } - } - catch (HttpRequestException ex) - { - ErrorRecord er = new(ex, "WebCmdletWebResponseException", ErrorCategory.InvalidOperation, request); - if (ex.InnerException is not null) + + if (!string.IsNullOrEmpty(detailMsg)) { - er.ErrorDetails = new ErrorDetails(ex.InnerException.Message); + er.ErrorDetails = new ErrorDetails(detailMsg); } ThrowTerminatingError(er); } - if (_followRelLink) + if (_parseRelLink || _followRelLink) { - if (!_relationLink.ContainsKey("next")) - { - return; - } + ParseLinkHeader(response); + } + + ProcessResponse(response); + UpdateSession(response); + + // If we hit our maximum redirection count, generate an error. + // Errors with redirection counts of greater than 0 are handled automatically by .NET, but are + // impossible to detect programmatically when we hit this limit. By handling this ourselves + // (and still writing out the result), users can debug actual HTTP redirect problems. + if (WebSession.MaximumRedirection == 0 && IsRedirectCode(response.StatusCode)) + { + ErrorRecord er = new(new InvalidOperationException(), "MaximumRedirectExceeded", ErrorCategory.InvalidOperation, request); + er.ErrorDetails = new ErrorDetails(WebCmdletStrings.MaximumRedirectionCountExceeded); + WriteError(er); + } + } + catch (HttpRequestException ex) + { + ErrorRecord er = new(ex, "WebCmdletWebResponseException", ErrorCategory.InvalidOperation, request); + if (ex.InnerException is not null) + { + er.ErrorDetails = new ErrorDetails(ex.InnerException.Message); + } - uri = new Uri(_relationLink["next"]); - followedRelLink++; + ThrowTerminatingError(er); + } + + if (_followRelLink) + { + if (!_relationLink.ContainsKey("next")) + { + return; } + + uri = new Uri(_relationLink["next"]); + followedRelLink++; } } - while (_followRelLink && (followedRelLink < _maximumFollowRelLink)); } + while (_followRelLink && (followedRelLink < _maximumFollowRelLink)); } catch (CryptographicException ex) { From fe8cc5dfe160e3961fded3965e553b6259c0657c Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Tue, 28 Feb 2023 01:02:51 +0000 Subject: [PATCH 389/779] Use `ArgumentException.ThrowIfNullOrEmpty` as appropriate [part 1] (#19215) --- .../cimSupport/cmdletization/cim/cimQuery.cs | 6 +---- .../commands/management/CIMHelper.cs | 8 +++---- .../commands/management/PingPathCommand.cs | 24 ++++++++++--------- 3 files changed, 17 insertions(+), 21 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimQuery.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimQuery.cs index 2c5c91fb1c8..a065f79204f 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimQuery.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimQuery.cs @@ -314,11 +314,7 @@ public override void FilterByAssociatedInstance(object associatedInstance, strin /// public override void AddQueryOption(string optionName, object optionValue) { - if (string.IsNullOrEmpty(optionName)) - { - throw new ArgumentNullException(nameof(optionName)); - } - + ArgumentException.ThrowIfNullOrEmpty(optionName); ArgumentNullException.ThrowIfNull(optionValue); this.queryOptions[optionName] = optionValue; diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/CIMHelper.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/CIMHelper.cs index 1b10bbfe7ab..035d5b17bbe 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/CIMHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/CIMHelper.cs @@ -79,8 +79,7 @@ internal static string WqlQueryAll(string from) /// internal static T GetFirst(CimSession session, string nameSpace, string wmiClassName) where T : class, new() { - if (string.IsNullOrEmpty(wmiClassName)) - throw new ArgumentException("String argument may not be null or empty", nameof(wmiClassName)); + ArgumentException.ThrowIfNullOrEmpty(wmiClassName); try { @@ -132,9 +131,8 @@ internal static string WqlQueryAll(string from) /// internal static T[] GetAll(CimSession session, string nameSpace, string wmiClassName) where T : class, new() { - if (string.IsNullOrEmpty(wmiClassName)) - throw new ArgumentException("String argument may not be null or empty", nameof(wmiClassName)); - + ArgumentException.ThrowIfNullOrEmpty(wmiClassName); + var rv = new List(); try diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/PingPathCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/PingPathCommand.cs index 9bebcd076ca..f5696712dd9 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/PingPathCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/PingPathCommand.cs @@ -186,19 +186,21 @@ protected override void ProcessRecord() { bool result = false; - if (path == null) - { - WriteError(new ErrorRecord( - new ArgumentNullException(TestPathResources.PathIsNullOrEmptyCollection), - "NullPathNotPermitted", - ErrorCategory.InvalidArgument, - Path)); - continue; - } - if (string.IsNullOrWhiteSpace(path)) { - WriteObject(result); + if (path is null) + { + WriteError(new ErrorRecord( + new ArgumentNullException(TestPathResources.PathIsNullOrEmptyCollection), + "NullPathNotPermitted", + ErrorCategory.InvalidArgument, + Path)); + } + else + { + WriteObject(result); + } + continue; } From d554d06f57829bdd5ab09072788e967c68bee3d1 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Tue, 28 Feb 2023 17:31:49 +0100 Subject: [PATCH 390/779] Small style changes (#19241) --- .../ManagementList/Common/WpfHelp.cs | 1 - .../Common/WebRequestPSCmdlet.Common.cs | 25 ++++++++++--------- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/WpfHelp.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/WpfHelp.cs index 42b8a06b845..628723b089a 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/WpfHelp.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/WpfHelp.cs @@ -418,7 +418,6 @@ public static bool TryExecute(this RoutedCommand command, object parameter, IInp public static T GetOptionalTemplateChild(Control templateParent, string childName) where T : FrameworkElement { ArgumentNullException.ThrowIfNull(templateParent); - ArgumentException.ThrowIfNullOrEmpty(childName); object templatePart = templateParent.Template.FindName(childName, templateParent); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index 70f03f5ddef..9417a9de5d7 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -578,7 +578,7 @@ protected override void ProcessRecord() // Disable writing to the OutFile. OutFile = null; } - + // Detect insecure redirection if (!AllowInsecureRedirect && response.RequestMessage.RequestUri.Scheme == "https" && response.Headers.Location?.Scheme == "http") { @@ -586,7 +586,7 @@ protected override void ProcessRecord() er.ErrorDetails = new ErrorDetails(WebCmdletStrings.InsecureRedirection); ThrowTerminatingError(er); } - + if (ShouldCheckHttpStatus && !_isSuccess) { string message = string.Format( @@ -928,7 +928,7 @@ internal virtual void PrepareSession() // We silently ignore header if value is null. if (value is not null) { - // Add the header value (or overwrite it if already present) + // Add the header value (or overwrite it if already present). WebSession.Headers[key] = value.ToString(); } } @@ -942,7 +942,7 @@ internal virtual void PrepareSession() WebSession.RetryIntervalInSeconds = RetryIntervalSec; } } - + internal virtual HttpClient GetHttpClient(bool handleRedirect) { HttpClientHandler handler = new(); @@ -1286,7 +1286,7 @@ internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestM requestWithoutRange.Version, requestWithoutRange.Method, requestContentLength); - + WriteVerbose(reqVerboseMsg); response.Dispose(); @@ -1303,9 +1303,9 @@ internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestM // If the status code is 429 get the retry interval from the Headers. // Ignore broken header and its value. - if (response.StatusCode is HttpStatusCode.Conflict && response.Headers.TryGetValues(HttpKnownHeaderNames.RetryAfter, out IEnumerable retryAfter)) + if (response.StatusCode is HttpStatusCode.Conflict && response.Headers.TryGetValues(HttpKnownHeaderNames.RetryAfter, out IEnumerable retryAfter)) { - try + try { IEnumerator enumerator = retryAfter.GetEnumerator(); if (enumerator.MoveNext()) @@ -1318,7 +1318,7 @@ internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestM // Ignore broken header. } } - + string retryMessage = string.Format( CultureInfo.CurrentCulture, WebCmdletStrings.RetryVerboseMsg, @@ -1388,7 +1388,7 @@ private static Uri CheckProtocol(Uri uri) } private string QualifyFilePath(string path) => PathUtils.ResolveFilePath(filePath: path, command: this, isLiteralPath: true); - + private static string FormatDictionary(IDictionary content) { ArgumentNullException.ThrowIfNull(content); @@ -1485,7 +1485,7 @@ internal void SetRequestContent(HttpRequestMessage request, string content) { ArgumentNullException.ThrowIfNull(request); ArgumentNullException.ThrowIfNull(content); - + Encoding encoding = null; if (ContentType is not null) { @@ -1565,7 +1565,7 @@ internal void SetRequestContent(HttpRequestMessage request, MultipartFormDataCon { ArgumentNullException.ThrowIfNull(request); ArgumentNullException.ThrowIfNull(multipartContent); - + // Content headers will be set by MultipartFormDataContent which will throw unless we clear them first WebSession.ContentHeaders.Clear(); @@ -1735,7 +1735,8 @@ private static string FormatErrorMessage(string error, string contentType) XmlDocument doc = new(); doc.LoadXml(error); - XmlWriterSettings settings = new XmlWriterSettings { + XmlWriterSettings settings = new XmlWriterSettings + { Indent = true, NewLineOnAttributes = true, OmitXmlDeclaration = true From 9764e3c22a7f73c976af28673ff48c429849a1b1 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Tue, 28 Feb 2023 17:24:31 -0800 Subject: [PATCH 391/779] Fix `VtSubstring` helper method to correctly check chars copied (#19240) --- src/System.Management.Automation/utils/StringUtil.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/System.Management.Automation/utils/StringUtil.cs b/src/System.Management.Automation/utils/StringUtil.cs index 6bdedd03a3b..8daf31866df 100644 --- a/src/System.Management.Automation/utils/StringUtil.cs +++ b/src/System.Management.Automation/utils/StringUtil.cs @@ -202,7 +202,7 @@ internal static string VtSubstring(this string str, int startOffset, int length, } // If the number of copied non-escape-sequence characters has reached the specified length, done copying. - if (offset == length) + if (copyStarted && offset == length) { break; } From f1b649556265c34ab32570964f1093572c38333f Mon Sep 17 00:00:00 2001 From: Berkan Diler Date: Wed, 1 Mar 2023 05:41:56 +0100 Subject: [PATCH 392/779] Use C# 11 UTF-8 string literals (#19243) --- .../engine/remoting/common/RemoteSessionHyperVSocket.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/System.Management.Automation/engine/remoting/common/RemoteSessionHyperVSocket.cs b/src/System.Management.Automation/engine/remoting/common/RemoteSessionHyperVSocket.cs index e71c5e82581..126004da829 100644 --- a/src/System.Management.Automation/engine/remoting/common/RemoteSessionHyperVSocket.cs +++ b/src/System.Management.Automation/engine/remoting/common/RemoteSessionHyperVSocket.cs @@ -551,13 +551,13 @@ public bool Connect( // if (emptyPassword) { - HyperVSocket.Send(Encoding.ASCII.GetBytes("EMPTYPW")); + HyperVSocket.Send("EMPTYPW"u8); HyperVSocket.Receive(response); responseString = Encoding.ASCII.GetString(response); } else { - HyperVSocket.Send(Encoding.ASCII.GetBytes("NONEMPTYPW")); + HyperVSocket.Send("NONEMPTYPW"u8); HyperVSocket.Receive(response); HyperVSocket.Send(password); @@ -590,11 +590,11 @@ public bool Connect( { if (emptyConfiguration) { - HyperVSocket.Send(Encoding.ASCII.GetBytes("EMPTYCF")); + HyperVSocket.Send("EMPTYCF"u8); } else { - HyperVSocket.Send(Encoding.ASCII.GetBytes("NONEMPTYCF")); + HyperVSocket.Send("NONEMPTYCF"u8); HyperVSocket.Receive(response); byte[] configName = Encoding.Unicode.GetBytes(configurationName); From cf622f869fd1240807b88d08141ea515375f79d9 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Wed, 1 Mar 2023 18:56:05 +0100 Subject: [PATCH 393/779] Take into account ContentType from Headers in WebCmdlets (#19227) --- .../Common/WebRequestPSCmdlet.Common.cs | 8 +++++--- .../WebCmdlets.Tests.ps1 | 16 +++++++++++++++- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index 9417a9de5d7..2d587d72e62 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -1487,14 +1487,16 @@ internal void SetRequestContent(HttpRequestMessage request, string content) ArgumentNullException.ThrowIfNull(content); Encoding encoding = null; - if (ContentType is not null) + string contentType = WebSession.ContentHeaders[HttpKnownHeaderNames.ContentType]; + + if (contentType is not null) { // If Content-Type contains the encoding format (as CharSet), use this encoding format // to encode the Body of the WebRequest sent to the server. Default Encoding format // would be used if Charset is not supplied in the Content-Type property. try { - MediaTypeHeaderValue mediaTypeHeaderValue = MediaTypeHeaderValue.Parse(ContentType); + MediaTypeHeaderValue mediaTypeHeaderValue = MediaTypeHeaderValue.Parse(contentType); if (!string.IsNullOrEmpty(mediaTypeHeaderValue.CharSet)) { encoding = Encoding.GetEncoding(mediaTypeHeaderValue.CharSet); @@ -1505,7 +1507,7 @@ internal void SetRequestContent(HttpRequestMessage request, string content) if (!SkipHeaderValidation) { ValidationMetadataException outerEx = new(WebCmdletStrings.ContentTypeException, ex); - ErrorRecord er = new(outerEx, "WebCmdletContentTypeException", ErrorCategory.InvalidArgument, ContentType); + ErrorRecord er = new(outerEx, "WebCmdletContentTypeException", ErrorCategory.InvalidArgument, contentType); ThrowTerminatingError(er); } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 index 2da345fcd3a..01946e5c5f0 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 @@ -568,6 +568,13 @@ Describe "Invoke-WebRequest tests" -Tags "Feature", "RequireAdminOnWindows" { $Result.Output.Content | Should -Match '⡌⠁⠧⠑ ⠼⠁⠒ ⡍⠜⠇⠑⠹⠰⠎ ⡣⠕⠌' } + It "Invoke-WebRequest -ContentType overwrites Content-Type from -Headers." { + $uri = Get-WebListenerUrl -Test 'POST' + $command = "Invoke-WebRequest -Uri '$uri' -ContentType 'application/json' -Headers @{'Content-Type'='plain/text'} -Method 'POST'" + $result = ExecuteWebCommand -command $command + $result.Output.BaseResponse.RequestMessage.Content.Headers.ContentType.MediaType | Should -BeExactly 'application/json' + } + It "Invoke-WebRequest supports sending request as UTF-8." { $uri = Get-WebListenerUrl -Test 'POST' # Body must contain non-ASCII characters @@ -576,7 +583,7 @@ Describe "Invoke-WebRequest tests" -Tags "Feature", "RequireAdminOnWindows" { $result = ExecuteWebCommand -command $command ValidateResponse -response $result - $Result.Output.Encoding.BodyName | Should -BeExactly 'utf-8' + $result.Output.Encoding.BodyName | Should -BeExactly 'utf-8' $object = $Result.Output.Content | ConvertFrom-Json $object.Data | Should -BeExactly 'проверка' } @@ -2338,6 +2345,13 @@ Describe "Invoke-RestMethod tests" -Tags "Feature", "RequireAdminOnWindows" { $Result.Output | Should -Match '⡌⠁⠧⠑ ⠼⠁⠒ ⡍⠜⠇⠑⠹⠰⠎ ⡣⠕⠌' } + It "Invoke-RestMethod -ContentType overwrites Content-Type from -Headers." { + $uri = Get-WebListenerUrl -Test 'POST' + $command = "Invoke-RestMethod -Uri '$uri' -ContentType 'application/json' -Headers @{'Content-Type'='plain/text'} -Method 'POST'" + $result = ExecuteWebCommand -command $command + $result.Output.headers."Content-Type" | Should -BeExactly 'application/json' + } + It "Invoke-RestMethod supports sending requests as UTF8" { $uri = Get-WebListenerUrl -Test POST # Body must contain non-ASCII characters From 89f0b0f1bc19f1197db6c26f6a97508d599b3301 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Wed, 1 Mar 2023 19:01:34 +0100 Subject: [PATCH 394/779] Remove comment and simplify condition in WebCmdlets (#19251) --- .../utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index 2d587d72e62..67d8a5e5a54 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -902,11 +902,9 @@ internal virtual void PrepareSession() { webProxy.Credentials = ProxyCredential.GetNetworkCredential(); } - else if (ProxyUseDefaultCredentials) + else { - // If both ProxyCredential and ProxyUseDefaultCredentials are passed, - // UseDefaultCredentials will overwrite the supplied credentials. - webProxy.UseDefaultCredentials = true; + webProxy.UseDefaultCredentials = ProxyUseDefaultCredentials; } WebSession.Proxy = webProxy; From f1ab653d29b9471051371e6a3aee2d27d9fd77e0 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Wed, 1 Mar 2023 20:04:20 +0100 Subject: [PATCH 395/779] Preserve WebSession.MaximumRedirection from changes (#19190) --- .../Common/WebRequestPSCmdlet.Common.cs | 13 +++- .../WebCmdlets.Tests.ps1 | 74 ++++++++++++++++++- 2 files changed, 83 insertions(+), 4 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index 67d8a5e5a54..ea42eff405f 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -107,6 +107,11 @@ public abstract class WebRequestPSCmdlet : PSCmdlet /// internal int _maximumFollowRelLink = int.MaxValue; + /// + /// Maximum number of Redirects to follow. + /// + internal int _maximumRedirection; + /// /// Parse Rel Links. /// @@ -549,6 +554,8 @@ protected override void ProcessRecord() WriteVerbose(reqVerboseMsg); + _maximumRedirection = WebSession.MaximumRedirection; + using HttpResponseMessage response = GetResponse(client, request, handleRedirect); string contentType = ContentHelper.GetContentType(response); @@ -1228,7 +1235,7 @@ internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestM response = client.SendAsync(currentRequest, HttpCompletionOption.ResponseHeadersRead, _cancelToken.Token).GetAwaiter().GetResult(); if (handleRedirect - && WebSession.MaximumRedirection is not 0 + && _maximumRedirection is not 0 && IsRedirectCode(response.StatusCode) && response.Headers.Location is not null) { @@ -1236,9 +1243,9 @@ internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestM _cancelToken = null; // If explicit count was provided, reduce it for this redirection. - if (WebSession.MaximumRedirection > 0) + if (_maximumRedirection > 0) { - WebSession.MaximumRedirection--; + _maximumRedirection--; } // For selected redirects, GET must be used with the redirected Location. diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 index 01946e5c5f0..ffaef4f8d94 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 @@ -624,7 +624,7 @@ Describe "Invoke-WebRequest tests" -Tags "Feature", "RequireAdminOnWindows" { param($proxy_address, $name, $protocol) # use external url, but with proxy the external url should not actually be called - $command = "Invoke-WebRequest -Uri ${protocol}://httpbin.org -Proxy '${protocol}://${proxy_address}' -SkipCertificateCheck" + $command = "Invoke-WebRequest -Uri ${protocol}://httpbin.org -Proxy '${protocol}://${proxy_address}'" $result = ExecuteWebCommand -command $command $command = "Invoke-WebRequest -Uri '${protocol}://${proxy_address}' -NoProxy" $expectedResult = ExecuteWebCommand -command $command @@ -976,6 +976,42 @@ Describe "Invoke-WebRequest tests" -Tags "Feature", "RequireAdminOnWindows" { $response.Content.Headers."Authorization" | Should -BeExactly "test" } + It "Validates Invoke-WebRequest with -WebSession and -PreserveAuthorizationOnRedirect doesn't change session variable on multiple redirects: " -TestCases $redirectTests { + param($redirectType) + + #[SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine", Justification="Demo/doc/test secret.")] + $token = "testpassword" | ConvertTo-SecureString -AsPlainText -Force + $credential = [pscredential]::new("testuser", $token) + $certificate = Get-WebListenerClientCertificate + $headers = @{"Authorization" = "test"} + $proxy = (Get-WebListenerUrl).Authority + $uri = Get-WebListenerUrl -Test 'Redirect' -TestValue 2 -Query @{type = $redirectType} + + $session = [Microsoft.PowerShell.Commands.WebRequestSession]::new() + $session.MaximumRedirection = 2 + $session.MaximumRetryCount = 2 + $session.RetryIntervalInSeconds = 2 + $session.UseDefaultCredentials = $true + $null = Invoke-WebRequest -Uri $uri -PreserveAuthorizationOnRedirect -WebSession $session -AllowUnencryptedAuthentication -Headers $headers + $session.MaximumRedirection | Should -BeExactly 2 + $session.MaximumRetryCount | Should -BeExactly 2 + $session.RetryIntervalInSeconds | Should -BeExactly 2 + $session.UseDefaultCredentials | Should -BeExactly $true + + $session = [Microsoft.PowerShell.Commands.WebRequestSession]::new() + $session.Credentials = $credential + $session.Certificates = [System.Security.Cryptography.X509Certificates.X509CertificateCollection]::new([X509Certificate]$certificate) + $null = Invoke-WebRequest -Uri $uri -PreserveAuthorizationOnRedirect -WebSession $session -SkipCertificateCheck -Headers $headers + $session.Credentials.UserName | Should -BeExactly $credential.UserName + $session.Credentials.Password | Should -BeExactly $credential.GetNetworkCredential().Password + $session.Certificates.Thumbprint | Should -BeExactly $certificate.Thumbprint + + $session = [Microsoft.PowerShell.Commands.WebRequestSession]::new() + $session.Proxy = [System.Net.WebProxy]::new($proxy) + $null = Invoke-WebRequest -Uri $uri -PreserveAuthorizationOnRedirect -WebSession $session -Headers $headers + $session.Proxy.GetProxy($uri).Authority | Should -BeExactly $proxy + } + It "Validates Invoke-WebRequest strips the authorization header on various redirects: " -TestCases $redirectTests { param($redirectType) $uri = Get-WebListenerUrl -Test 'Redirect' -Query @{type = $redirectType} @@ -2720,6 +2756,42 @@ Describe "Invoke-RestMethod tests" -Tags "Feature", "RequireAdminOnWindows" { $response.Content.Headers."Authorization" | Should -BeExactly "test" } + It "Validates Invoke-RestMethod with -WebSession and -PreserveAuthorizationOnRedirect doesn't change session variable on multiple redirects: " -TestCases $redirectTests { + param($redirectType) + + #[SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine", Justification="Demo/doc/test secret.")] + $token = "testpassword" | ConvertTo-SecureString -AsPlainText -Force + $credential = [pscredential]::new("testuser", $token) + $certificate = Get-WebListenerClientCertificate + $headers = @{"Authorization" = "test"} + $proxy = (Get-WebListenerUrl).Authority + $uri = Get-WebListenerUrl -Test 'Redirect' -TestValue 2 -Query @{type = $redirectType} + + $session = [Microsoft.PowerShell.Commands.WebRequestSession]::new() + $session.MaximumRedirection = 2 + $session.MaximumRetryCount = 2 + $session.RetryIntervalInSeconds = 2 + $session.UseDefaultCredentials = $true + $null = Invoke-RestMethod -Uri $uri -PreserveAuthorizationOnRedirect -WebSession $session -AllowUnencryptedAuthentication -Headers $headers + $session.MaximumRedirection | Should -BeExactly 2 + $session.MaximumRetryCount | Should -BeExactly 2 + $session.RetryIntervalInSeconds | Should -BeExactly 2 + $session.UseDefaultCredentials | Should -BeExactly $true + + $session = [Microsoft.PowerShell.Commands.WebRequestSession]::new() + $session.Credentials = $credential + $session.Certificates = [System.Security.Cryptography.X509Certificates.X509CertificateCollection]::new([X509Certificate]$certificate) + $null = Invoke-RestMethod -Uri $uri -PreserveAuthorizationOnRedirect -WebSession $session -SkipCertificateCheck -Headers $headers + $session.Credentials.UserName | Should -BeExactly $credential.UserName + $session.Credentials.Password | Should -BeExactly $credential.GetNetworkCredential().Password + $session.Certificates.Thumbprint | Should -BeExactly $certificate.Thumbprint + + $session = [Microsoft.PowerShell.Commands.WebRequestSession]::new() + $session.Proxy = [System.Net.WebProxy]::new($proxy) + $null = Invoke-RestMethod -Uri $uri -PreserveAuthorizationOnRedirect -WebSession $session -Headers $headers + $session.Proxy.GetProxy($uri).Authority | Should -BeExactly $proxy + } + It "Validates Invoke-RestMethod strips the authorization header on various redirects: " -TestCases $redirectTests { param($redirectType) $uri = Get-WebListenerUrl -Test 'Redirect' -Query @{type = $redirectType} From ec258e210f0c78ab87224ad77e4b77629a423737 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Wed, 1 Mar 2023 11:18:11 -0800 Subject: [PATCH 396/779] Fix `ConciseView` to handle custom `ParserError` error records (#19239) --- .../PowerShellCore_format_ps1xml.cs | 9 +++++++-- .../engine/Formatting/ErrorView.Tests.ps1 | 17 ++++++++++++++++- 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs index 3d6257f36a8..747c083ee51 100644 --- a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs +++ b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs @@ -1075,6 +1075,8 @@ private static IEnumerable ViewsOf_System_Management_Autom ") .AddScriptBlockExpressionBinding(@" Set-StrictMode -Off + $ErrorActionPreference = 'Stop' + trap { 'Error found in error view definition: ' + $_.Exception.Message } $newline = [Environment]::Newline $resetColor = '' @@ -1105,8 +1107,11 @@ function Get-ConciseViewPositionMessage { $message = '' $prefix = '' - # Don't show line information if script module - if (($myinv -and $myinv.ScriptName -or $myinv.ScriptLineNumber -gt 1 -or $err.CategoryInfo.Category -eq 'ParserError') -and !($myinv.ScriptName.EndsWith('.psm1', [System.StringComparison]::OrdinalIgnoreCase))) { + # The checks here determine if we show line detailed error information: + # - check if `ParserError` and comes from PowerShell which eventually results in a ParseException, but during this execution it's an ErrorRecord + # - check if invocation is a script or multiple lines in the console + # - check that it's not a script module as expectation is that users don't want to see the line of error within a module + if ((($err.CategoryInfo.Category -eq 'ParserError' -and $err.Exception -is 'System.Management.Automation.ParentContainsErrorRecordException') -or $myinv.ScriptName -or $myinv.ScriptLineNumber -gt 1) -and $myinv.ScriptName -notmatch '\.psm1$') { $useTargetObject = $false # Handle case where there is a TargetObject and we can show the error at the target rather than the script source diff --git a/test/powershell/engine/Formatting/ErrorView.Tests.ps1 b/test/powershell/engine/Formatting/ErrorView.Tests.ps1 index 18173354a65..2188648872a 100644 --- a/test/powershell/engine/Formatting/ErrorView.Tests.ps1 +++ b/test/powershell/engine/Formatting/ErrorView.Tests.ps1 @@ -109,7 +109,7 @@ Describe 'Tests for $ErrorView' -Tag CI { } It "Error shows if `$PSModuleAutoLoadingPreference is set to 'none'" { - $e = & "$PSHOME/pwsh" -noprofile -command '$PSModuleAutoLoadingPreference = ""none""; cmdletThatDoesntExist' 2>&1 | Out-String + $e = & "$PSHOME/pwsh" -noprofile -command '$PSModuleAutoLoadingPreference = "none"; cmdletThatDoesntExist' 2>&1 | Out-String $e | Should -BeLike "*cmdletThatDoesntExist*" } @@ -151,6 +151,21 @@ Describe 'Tests for $ErrorView' -Tag CI { $e | Should -Not -BeNullOrEmpty $e | Should -Not -BeLike "*Line*" } + + It 'Parser error shows line information' { + $testScript = '$psstyle.outputrendering = "plaintext"; 1 ++ 1' + $e = & "$PSHOME/pwsh" -noprofile -command $testScript 2>&1 | Out-String + $e | Should -Not -BeNullOrEmpty + $e = $e.Split([Environment]::NewLine) + $e[0] | Should -BeLike "ParserError:*" + $e[1] | Should -BeLike "Line *" -Because ($e | Out-String) + $e[2] | Should -BeLike "*|*1 ++ 1*" + } + + It 'Faux remote parser error shows concise message' { + start-job { [cmdletbinding()]param() $e = [System.Management.Automation.ErrorRecord]::new([System.Exception]::new('hello'), 1, 'ParserError', $null); $pscmdlet.ThrowTerminatingError($e) } | Wait-Job | Receive-Job -ErrorVariable e -ErrorAction SilentlyContinue + $e | Out-String | Should -BeLike '*ParserError*' + } } Context 'NormalView tests' { From 03396c42cb99021ccd4730e6a5c8551d9361e621 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Thu, 2 Mar 2023 03:20:59 +0100 Subject: [PATCH 397/779] Improve verbose message in web cmdlets when content length is unknown (#19252) --- .../WebCmdlet/Common/WebRequestPSCmdlet.Common.cs | 11 +++++------ .../resources/WebCmdletStrings.resx | 3 +++ 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index ea42eff405f..8172d58b03b 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -559,12 +559,11 @@ protected override void ProcessRecord() using HttpResponseMessage response = GetResponse(client, request, handleRedirect); string contentType = ContentHelper.GetContentType(response); - string respVerboseMsg = string.Format( - CultureInfo.CurrentCulture, - WebCmdletStrings.WebResponseVerboseMsg, - response.Content.Headers.ContentLength, - contentType); - + long? contentLength = response.Content.Headers.ContentLength; + string respVerboseMsg = contentLength is null + ? string.Format(CultureInfo.CurrentCulture, WebCmdletStrings.WebResponseNoSizeVerboseMsg, contentType) + : string.Format(CultureInfo.CurrentCulture, WebCmdletStrings.WebResponseVerboseMsg, contentLength, contentType); + WriteVerbose(respVerboseMsg); bool _isSuccess = response.IsSuccessStatusCode; diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/WebCmdletStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/WebCmdletStrings.resx index a9628c647e3..99a1d0ef7c6 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/WebCmdletStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/WebCmdletStrings.resx @@ -240,6 +240,9 @@ received {0}-byte response of content type {1} + + received response of content type {0} of unknown size + Retrying after interval of {0} seconds. Status code for previous attempt: {1} From 8d8f45e3dfd14a4c389b2a5009446d4649094af3 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Thu, 2 Mar 2023 18:29:46 +0100 Subject: [PATCH 398/779] Use ArgumentNullException.ThrowIfNull part 2 (#19258) --- .../ManagementList/Common/ListOrganizer.cs | 10 ++-------- .../FilterRules/PropertyValueSelectorFilterRule.cs | 5 +---- .../ManagementList/FilterProviders/FilterRulePanel.cs | 10 ++-------- .../FilterRuleToDisplayNameConverter.cs | 5 +---- .../ManagementList/PropertyValueGetter.cs | 6 +----- .../ManagementList/ManagementList/managementlist.cs | 10 ++-------- .../WindowsTaskbarJumpList/PropVariant.cs | 5 +---- .../DotNetCode/Eventing/EventProviderTraceListener.cs | 4 ++++ .../engine/hostifaces/HostUtilities.cs | 7 ++----- .../engine/remoting/client/ThrottlingJob.cs | 6 +++++- .../engine/runtime/MutableTuple.cs | 5 ++++- .../namespaces/FileSystemProvider.cs | 3 +-- .../namespaces/TransactedRegistryKey.cs | 8 ++++++++ test/perf/dotnet-tools/ResultsComparer/Program.cs | 2 ++ 14 files changed, 36 insertions(+), 50 deletions(-) diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/ListOrganizer.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/ListOrganizer.cs index 7f8a0f8bfc4..6d84a44c7e7 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/ListOrganizer.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/ListOrganizer.cs @@ -42,10 +42,7 @@ protected override void OnKeyDown(KeyEventArgs e) partial void OnSelectItemExecutedImplementation(ExecutedRoutedEventArgs e) { - if (e.Parameter == null) - { - throw new ArgumentException("e.Parameter is null", "e"); - } + ArgumentNullException.ThrowIfNull(e.Parameter); this.RaiseEvent(new DataRoutedEventArgs(e.Parameter, ItemSelectedEvent)); this.picker.IsOpen = false; @@ -53,10 +50,7 @@ partial void OnSelectItemExecutedImplementation(ExecutedRoutedEventArgs e) partial void OnDeleteItemExecutedImplementation(ExecutedRoutedEventArgs e) { - if (e.Parameter == null) - { - throw new ArgumentException("e.Parameter is null", "e"); - } + ArgumentNullException.ThrowIfNull(e.Parameter); this.RaiseEvent(new DataRoutedEventArgs(e.Parameter, ItemDeletedEvent)); } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/PropertyValueSelectorFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/PropertyValueSelectorFilterRule.cs index 9143336aa4c..7e9eca9b25c 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/PropertyValueSelectorFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/PropertyValueSelectorFilterRule.cs @@ -76,10 +76,7 @@ public PropertyValueSelectorFilterRule(string propertyName, string propertyDispl foreach (FilterRule rule in rules) { - if (rule == null) - { - throw new ArgumentException("A value within rules is null", "rules"); - } + ArgumentNullException.ThrowIfNull(rule); this.AvailableRules.AvailableValues.Add(rule); } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanel.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanel.cs index 3e577d3cb9f..07a19f6befa 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanel.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanel.cs @@ -230,10 +230,7 @@ partial void OnAddRulesExecutedImplementation(ExecutedRoutedEventArgs e) { Debug.Assert(e != null, "not null"); - if (e.Parameter == null) - { - throw new ArgumentException("e.Parameter is null.", "e"); - } + ArgumentNullException.ThrowIfNull(e.Parameter); List itemsToAdd = new List(); @@ -265,10 +262,7 @@ partial void OnRemoveRuleExecutedImplementation(ExecutedRoutedEventArgs e) { Debug.Assert(e != null, "not null"); - if (e.Parameter == null) - { - throw new ArgumentException("e.Parameter is null.", "e"); - } + ArgumentNullException.ThrowIfNull(e.Parameter); FilterRulePanelItem item = e.Parameter as FilterRulePanelItem; if (item == null) diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRuleToDisplayNameConverter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRuleToDisplayNameConverter.cs index 07a4ed58f8b..ee1291b8f09 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRuleToDisplayNameConverter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRuleToDisplayNameConverter.cs @@ -41,10 +41,7 @@ public object Convert(object value, Type targetType, object parameter, System.Gl } FilterRule rule = value as FilterRule; - if (rule == null) - { - throw new ArgumentException("value of type FilterRule expected.", "value"); - } + ArgumentNullException.ThrowIfNull(rule); return rule.DisplayName; } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/PropertyValueGetter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/PropertyValueGetter.cs index 2e9326cd909..02efbf2d920 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/PropertyValueGetter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/PropertyValueGetter.cs @@ -43,11 +43,7 @@ public virtual bool TryGetPropertyValue(string propertyName, object value, out o { propertyValue = null; - if (string.IsNullOrEmpty(propertyName)) - { - throw new ArgumentException("propertyName is empty", "propertyName"); - } - + ArgumentNullException.ThrowIfNullOrEmpty(propertyName); ArgumentNullException.ThrowIfNull(value); PropertyDescriptor descriptor = this.GetPropertyDescriptor(propertyName, value); diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/managementlist.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/managementlist.cs index 4ac51c702d8..16c038f575b 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/managementlist.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/managementlist.cs @@ -340,10 +340,7 @@ private StateDescriptor DoesViewAlreadyExist(string viewName) private void ViewManager_ItemSelected(object sender, DataRoutedEventArgs e) { - if (e.Data == null) - { - throw new ArgumentException("e.Data is null", "e"); - } + ArgumentNullException.ThrowIfNull(e.Data); StateDescriptor sd = (StateDescriptor)e.Data; sd.RestoreState(this); @@ -353,10 +350,7 @@ private void ViewManager_ItemSelected(object sender, DataRoutedEventArgs private void ViewManager_ItemDeleted(object sender, DataRoutedEventArgs e) { - if (e.Data == null) - { - throw new ArgumentException("e.Data is null", "e"); - } + ArgumentNullException.ThrowIfNull(e.Data); StateDescriptor sd = (StateDescriptor)e.Data; this.Views.Remove(sd); diff --git a/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropVariant.cs b/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropVariant.cs index 10db7912b4a..58935b2d9d4 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropVariant.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropVariant.cs @@ -29,10 +29,7 @@ internal sealed class PropVariant : IDisposable /// internal PropVariant(string value) { - if (value == null) - { - throw new ArgumentException("PropVariantNullString", nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); #pragma warning disable CS0618 // Type or member is obsolete (might get deprecated in future versions _valueType = (ushort)VarEnum.VT_LPWSTR; diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProviderTraceListener.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProviderTraceListener.cs index 1c82891b654..bb488d80ede 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProviderTraceListener.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProviderTraceListener.cs @@ -44,7 +44,9 @@ public string Delimiter ArgumentNullException.ThrowIfNull(value, nameof(Delimiter)); if (value.Length == 0) + { throw new ArgumentException(DotNetEventingStrings.Argument_NeedNonemptyDelimiter); + } _delimiter = value; } @@ -74,7 +76,9 @@ public EventProviderTraceListener(string providerId, string name, string delimit ArgumentNullException.ThrowIfNull(delimiter); if (delimiter.Length == 0) + { throw new ArgumentException(DotNetEventingStrings.Argument_NeedNonemptyDelimiter); + } _delimiter = delimiter; InitProvider(providerId); diff --git a/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs b/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs index e0d19c489c8..896ca99791b 100644 --- a/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs +++ b/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs @@ -413,8 +413,7 @@ internal static List GetSuggestion(HistoryInfo lastHistory, object lastE { suggestion["Enabled"] = false; - throw new ArgumentException( - SuggestionStrings.RuleMustBeScriptBlock, "Rule"); + throw new ArgumentException(SuggestionStrings.RuleMustBeScriptBlock, "Rule"); } try @@ -482,9 +481,7 @@ internal static List GetSuggestion(HistoryInfo lastHistory, object lastE { suggestion["Enabled"] = false; - throw new ArgumentException( - SuggestionStrings.InvalidMatchType, - "MatchType"); + throw new ArgumentException(SuggestionStrings.InvalidMatchType, "MatchType"); } // If the text matches, evaluate the suggestion diff --git a/src/System.Management.Automation/engine/remoting/client/ThrottlingJob.cs b/src/System.Management.Automation/engine/remoting/client/ThrottlingJob.cs index b9a0cc4dfab..fd5e5b7ef52 100644 --- a/src/System.Management.Automation/engine/remoting/client/ThrottlingJob.cs +++ b/src/System.Management.Automation/engine/remoting/client/ThrottlingJob.cs @@ -369,7 +369,11 @@ internal void DisableFlowControlForPendingCmdletActionsQueue() internal void AddChildJobWithoutBlocking(StartableJob childJob, ChildJobFlags flags, Action jobEnqueuedAction = null) { ArgumentNullException.ThrowIfNull(childJob); - if (childJob.JobStateInfo.State != JobState.NotStarted) throw new ArgumentException(RemotingErrorIdStrings.ThrottlingJobChildAlreadyRunning, nameof(childJob)); + if (childJob.JobStateInfo.State != JobState.NotStarted) + { + throw new ArgumentException(RemotingErrorIdStrings.ThrottlingJobChildAlreadyRunning, nameof(childJob)); + } + this.AssertNotDisposed(); JobStateInfo newJobStateInfo = null; diff --git a/src/System.Management.Automation/engine/runtime/MutableTuple.cs b/src/System.Management.Automation/engine/runtime/MutableTuple.cs index 480e8e111b8..3987c4ed296 100644 --- a/src/System.Management.Automation/engine/runtime/MutableTuple.cs +++ b/src/System.Management.Automation/engine/runtime/MutableTuple.cs @@ -365,7 +365,10 @@ internal static IEnumerable GetAccessProperties(Type tupleType, in { // ContractUtils.RequiresNotNull(tupleType, "tupleType"); - if (index < 0 || index >= size) throw new ArgumentException("index"); + if (index < 0 || index >= size) + { + throw new ArgumentException("index"); + } foreach (int curIndex in GetAccessPath(size, index)) { diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index 3d4c3e2f9da..4db3cf42a3a 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -7673,8 +7673,7 @@ public static string GetTarget(PSObject instance) { if (!fileSysInfo.Exists) { - throw new ArgumentException( - StringUtil.Format(SessionStateStrings.PathNotFound, fileSysInfo.FullName)); + throw new ArgumentException(StringUtil.Format(SessionStateStrings.PathNotFound, fileSysInfo.FullName)); } return fileSysInfo.LinkTarget; diff --git a/src/System.Management.Automation/namespaces/TransactedRegistryKey.cs b/src/System.Management.Automation/namespaces/TransactedRegistryKey.cs index 19e05ce99a7..198e4fea258 100644 --- a/src/System.Management.Automation/namespaces/TransactedRegistryKey.cs +++ b/src/System.Management.Automation/namespaces/TransactedRegistryKey.cs @@ -560,7 +560,9 @@ public void DeleteSubKey(string subkey, bool throwOnMissingSubKey) else { // there is no key which also means there is no subkey if (throwOnMissingSubKey) + { throw new ArgumentException(RegistryProviderStrings.ArgumentException_RegSubKeyAbsent); + } } } @@ -1396,7 +1398,9 @@ public unsafe void SetValue(string name, object value, RegistryValueKind valueKi } if (!Enum.IsDefined(typeof(RegistryValueKind), valueKind)) + { throw new ArgumentException(RegistryProviderStrings.Arg_RegBadKeyKind); + } EnsureWriteable(); @@ -2037,14 +2041,18 @@ private static void ValidateKeyName(string name) while (nextSlash != -1) { if ((nextSlash - current) > MaxKeyLength) + { throw new ArgumentException(RegistryProviderStrings.Arg_RegKeyStrLenBug); + } current = nextSlash + 1; nextSlash = name.IndexOf('\\', current); } if ((name.Length - current) > MaxKeyLength) + { throw new ArgumentException(RegistryProviderStrings.Arg_RegKeyStrLenBug); + } } private static void ValidateKeyMode(RegistryKeyPermissionCheck mode) diff --git a/test/perf/dotnet-tools/ResultsComparer/Program.cs b/test/perf/dotnet-tools/ResultsComparer/Program.cs index 68615f61c78..37afb965148 100644 --- a/test/perf/dotnet-tools/ResultsComparer/Program.cs +++ b/test/perf/dotnet-tools/ResultsComparer/Program.cs @@ -149,7 +149,9 @@ private static void PrintTable((string id, Benchmark baseResult, Benchmark diffR var diffFiles = GetFilesToParse(args.DiffPath); if (!baseFiles.Any() || !diffFiles.Any()) + { throw new ArgumentException($"Provided paths contained no {FullBdnJsonFileExtension} files."); + } var baseResults = baseFiles.Select(ReadFromFile); var diffResults = diffFiles.Select(ReadFromFile); From 8b9544b614f2c3455ee15441ffc7bcd73fa3cb58 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Thu, 2 Mar 2023 19:35:31 +0100 Subject: [PATCH 399/779] Adjust PUT method behavior to POST one for default content type in WebCmdlets (#19152) --- .../Common/WebRequestPSCmdlet.Common.cs | 2 +- .../WebCmdlets.Tests.ps1 | 21 +++++++++++++------ 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index 8172d58b03b..dfda73811ee 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -1109,7 +1109,7 @@ internal virtual void FillRequestStream(HttpRequestMessage request) { WebSession.ContentHeaders[HttpKnownHeaderNames.ContentType] = ContentType; } - else if (request.Method == HttpMethod.Post) + else if (request.Method == HttpMethod.Post || request.Method == HttpMethod.Put) { // Win8:545310 Invoke-WebRequest does not properly set MIME type for POST WebSession.ContentHeaders.TryGetValue(HttpKnownHeaderNames.ContentType, out string contentType); diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 index ffaef4f8d94..08183e714c7 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 @@ -759,9 +759,14 @@ Describe "Invoke-WebRequest tests" -Tags "Feature", "RequireAdminOnWindows" { ($result.Output.Content | ConvertFrom-Json).method | Should -Be "TEST" } - It "Validate Invoke-WebRequest default ContentType for CustomMethod POST" { - $uri = Get-WebListenerUrl -Test 'Post' - $command = "Invoke-WebRequest -Uri '$uri' -CustomMethod POST -Body 'testparam=testvalue'" + It "Validate Invoke-WebRequest default ContentType for CustomMethod " -TestCases @( + @{method = "POST"} + @{method = "PUT"} + ) { + param($method) + + $uri = Get-WebListenerUrl -Test $method + $command = "Invoke-WebRequest -Uri '$uri' -CustomMethod $method -Body 'testparam=testvalue'" $result = ExecuteWebCommand -command $command $jsonResult = $result.Output.Content | ConvertFrom-Json $jsonResult.form.testparam | Should -Be "testvalue" @@ -2559,9 +2564,13 @@ Describe "Invoke-RestMethod tests" -Tags "Feature", "RequireAdminOnWindows" { $result.Output.method | Should -Be "TEST" } - It "Validate Invoke-RestMethod default ContentType for CustomMethod POST" { - $uri = Get-WebListenerUrl -Test 'Post' - $command = "Invoke-RestMethod -Uri '$uri' -CustomMethod POST -Body 'testparam=testvalue'" + It "Validate Invoke-RestMethod default ContentType for CustomMethod " -TestCases @( + @{method = "POST"} + @{method = "PUT"} + ) { + param($method) + $uri = Get-WebListenerUrl -Test $method + $command = "Invoke-RestMethod -Uri '$uri' -CustomMethod $method -Body 'testparam=testvalue'" $result = ExecuteWebCommand -command $command $result.Output.form.testparam | Should -Be "testvalue" $result.Output.Headers.'Content-Type' | Should -Be "application/x-www-form-urlencoded" From 118db9062649c01b685c9c1fe2ce3a09c30a2ba5 Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Thu, 2 Mar 2023 10:56:24 -0800 Subject: [PATCH 400/779] Update and remove outdated docs to fix the URL link checks (#19261) --- .../visual-studio-simple-example.md | 4 +- .../CodeCoverageAnalysis.md | 109 ------------------ 2 files changed, 2 insertions(+), 111 deletions(-) delete mode 100644 docs/testing-guidelines/CodeCoverageAnalysis.md diff --git a/docs/cmdlet-example/visual-studio-simple-example.md b/docs/cmdlet-example/visual-studio-simple-example.md index f94cc912e34..b4a20ba138c 100644 --- a/docs/cmdlet-example/visual-studio-simple-example.md +++ b/docs/cmdlet-example/visual-studio-simple-example.md @@ -10,7 +10,7 @@ This document describes steps for building a C# Cmdlet with Visual Studio in 2 w This demonstrates how to build your own C# cmdlet for PowerShell Core with Visual Studio. Targeting for PowerShell Core means that the cmdlet may not work against Windows PowerShell if you take dependencies on new APIs introduced in PowerShell Core. -We will use the free [Visual Studio Community 2017](https://www.visualstudio.com/downloads). +We will use the free [Visual Studio Community 2017](https://visualstudio.microsoft.com/vs/). 1. When installing Visual Studio 2017 select `.NET Core cross-platform development` under `Other Toolsets` ![Step1](./Images/Step1.png) @@ -74,7 +74,7 @@ Steps below show how to build your own C# cmdlet for PowerShell Standard 3.0 wit Targeting PowerShell Standard 3.0 means that the same module will work against PowerShell Core as well as Windows PowerShell v3 and newer, however, you are limited to a subset of the available PowerShell APIs. -We will use the free [Visual Studio Community 2017](https://www.visualstudio.com/downloads). +We will use the free [Visual Studio Community 2017](https://visualstudio.microsoft.com/vs/). 1. When installing Visual Studio 2017 select `.NET Core cross-platform development` under `Other Toolsets` ![StdImage1](./Images/Step1.png) diff --git a/docs/testing-guidelines/CodeCoverageAnalysis.md b/docs/testing-guidelines/CodeCoverageAnalysis.md deleted file mode 100644 index bee669ea747..00000000000 --- a/docs/testing-guidelines/CodeCoverageAnalysis.md +++ /dev/null @@ -1,109 +0,0 @@ -# Code coverage analysis for commit [de5f69c](https://codecov.io/gh/PowerShell/PowerShell/tree/de5f69cf942a85839c907f11a29cf9c09f9de8b4/src) - -Code coverage runs are enabled on daily Windows builds for PowerShell Core 6. -The results of the latest build are available at [codecov.io](https://codecov.io/gh/PowerShell/PowerShell) - -The goal of this analysis is to find the hot spots of missing coverage. -The metrics used for selection of these hot spots were: # missing lines and likelihood of code path usage. - -## Coverage Status - -The following table shows the status for the above commit, dated 2018-11-28 - -| Assembly | Hit % | -| -------- |:-----:| -| Microsoft.Management.Infrastructure.CimCmdlets | 48.18% | -| Microsoft.PowerShell.Commands.Diagnostics | 47.58% | -| Microsoft.PowerShell.Commands.Management | 61.06% | -| Microsoft.PowerShell.Commands.Utility | 70.76% | -| Microsoft.PowerShell.ConsoleHost | 46.39% | -| Microsoft.PowerShell.CoreCLR.Eventing | 37.84% | -| Microsoft.PowerShell.MarkdownRender | 70.68% | -| Microsoft.PowerShell.Security | 49.36% | -| Microsoft.WSMan.Management | 62.36% | -| System.Management.Automation | 63.35% | -| Microsoft.WSMan.Runtime/WSManSessionOption.cs | 100.00% | -| powershell/Program.cs | 100.00% | - -## Hot Spots with missing coverage - -### Microsoft.PowerShell.Commands.Management - -- [ ] Add tests for *-Item cmdlets. Especially for literal paths and error cases. [#4148](https://github.com/PowerShell/PowerShell/issues/4148) -- [ ] Lots of resource strings not covered. Will probably get covered when coverage is added for error cases. [#4148](https://github.com/PowerShell/PowerShell/issues/4148) - -### Microsoft.PowerShell.Commands.Utility - -- [ ] Add tests for Debug-Runspace [#4153](https://github.com/PowerShell/PowerShell/issues/4153) - -### Microsoft.PowerShell.ConsoleHost - -- [ ] Various options, DebugHandler and hosting modes like server, namedpipe etc. [#4155](https://github.com/PowerShell/PowerShell/issues/4155) - -### Microsoft.PowerShell.CoreCLR.Eventing - -- [ ] Add tests for ETW events. [#4156](https://github.com/PowerShell/PowerShell/issues/4156) - -### Microsoft.PowerShell.Security - -- [ ] Add tests for *-Acl cmdlets. [#4157](https://github.com/PowerShell/PowerShell/issues/4157) -- [ ] Add tests for *-AuthenticodeSignature cmdlets. [#4157](https://github.com/PowerShell/PowerShell/issues/4157) -- [ ] Add coverage to various utility methods under src/Microsoft.PowerShell.Security/security/Utils.cs [#4157](https://github.com/PowerShell/PowerShell/issues/4157) - -### Microsoft.WSMan.Management - -- [ ] Add tests for WSMan provider [#4158](https://github.com/PowerShell/PowerShell/issues/4158) -- [ ] Add tests for WSMan cmdlets [#4158](https://github.com/PowerShell/PowerShell/issues/4158) -- [ ] Add tests for CredSSP [#4158](https://github.com/PowerShell/PowerShell/issues/4158) - -### System.Management.Automation - -#### CoreCLR - -- [ ] Lots of non-windows code can be ifdef'ed out. [#3565](https://github.com/PowerShell/PowerShell/issues/3565) - -#### Engine - -- [ ] Add tests for Tab Completion of various types of input. [#4160](https://github.com/PowerShell/PowerShell/issues/4160) -- [ ] Add tests for debugging PS Jobs. [#4153](https://github.com/PowerShell/PowerShell/issues/4153) -- [ ] Remove Snapin code from CommandDiscovery. [#4118](https://github.com/PowerShell/PowerShell/issues/4118) -- [ ] Add tests SessionStateItem, SessionStateContainer error cases, dynamic parameters. Coverage possibly added by *-Item, *-ChildItem error case tests. [#4148](https://github.com/PowerShell/PowerShell/issues/4148) -- [ ] Add more tests using PSCredential [#4165](https://github.com/PowerShell/PowerShell/issues/4165) - -#### Remoting - -- [ ] Can PSProxyJobs be removed as it is for Workflows? -- [ ] Add more tests for PS Jobs. [#4166](https://github.com/PowerShell/PowerShell/issues/4166) -- [ ] Add more tests using -ThrottleLimit [#4166](https://github.com/PowerShell/PowerShell/issues/4166) -- [ ] Add tests for Register-PSSessionConfiguration [#4166](https://github.com/PowerShell/PowerShell/issues/4166) -- [ ] Add tests for Connect/Disconnect session [#4166](https://github.com/PowerShell/PowerShell/issues/4166) -- [ ] Add more tests for Start-Job's various options [#4166](https://github.com/PowerShell/PowerShell/issues/4166) - -#### Security - -- [ ] Add more tests under various ExecutionPolicy modes. [#4168](https://github.com/PowerShell/PowerShell/issues/4168) - -#### Utils - -- [ ] Add more error case test to improve coverage of src/System.Management.Automation/utils [#4169](https://github.com/PowerShell/PowerShell/issues/4169) - -#### Providers - -##### FileSystemProvider - -- [ ] Add tests for Mapped Network Drive [#4148](https://github.com/PowerShell/PowerShell/issues/4148) -- [ ] Add tests for *-Item alternate stream [#4148](https://github.com/PowerShell/PowerShell/issues/4148) -- [ ] Add tests for Get-ChildItem -path "file" [#4148](https://github.com/PowerShell/PowerShell/issues/4148) -- [ ] Add tests for Rename-Item for a directory [#4148](https://github.com/PowerShell/PowerShell/issues/4148) -- [ ] Add tests for Copy-Item over remote session [#4148](https://github.com/PowerShell/PowerShell/issues/4148) -- [ ] Add tests for various error conditions [#4148](https://github.com/PowerShell/PowerShell/issues/4148) - -##### RegistryProvider - -- [ ] Add tests for *-Item [#4148](https://github.com/PowerShell/PowerShell/issues/4148) -- [ ] Add tests for *-Acl [#4157](https://github.com/PowerShell/PowerShell/issues/4157) -- [ ] Add tests for error conditions [#4148](https://github.com/PowerShell/PowerShell/issues/4148) - -##### FunctionProvider - -- [ ] Add *-Item tests [#4148](https://github.com/PowerShell/PowerShell/issues/4148) From 25f7bbc9c2b4b67b34213e8e7d03ac8b87cc92d8 Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Thu, 2 Mar 2023 11:58:42 -0800 Subject: [PATCH 401/779] Add '-Force' to `Move-Item` to fix the GitHub workflow (#19262) --- .github/workflows/exp-json.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/exp-json.yml b/.github/workflows/exp-json.yml index 629ff0f55e4..4d3fbfecc05 100644 --- a/.github/workflows/exp-json.yml +++ b/.github/workflows/exp-json.yml @@ -117,20 +117,20 @@ jobs: Write-Verbose -Verbose "Create PR Windows == $createPrWin" $createPrLinux = ShouldCreatePR $currentLinuxFile $newLinuxFile - Write-Verbose -Verbose "Create PR Windows == $createPrLinux" + Write-Verbose -Verbose "Create PR Linux == $createPrLinux" $createPr = $createPrWin -or $createPrLinux Write-Verbose -Verbose "Create PR == $createPr" if ($createPrWin) { - Move-Item $newWinFile $currentWinFile -Verbose + Move-Item $newWinFile $currentWinFile -Verbose -Force } else { Remove-Item $newWinFile -Verbose } if ($createPrLinux) { - Move-Item $newLinuxFile $currentLinuxFile -Verbose + Move-Item $newLinuxFile $currentLinuxFile -Verbose -Force } else { Remove-Item $newLinuxFile -Verbose From 3cdd1fa6ef94d5a0f3377adb854f38f0d3d5cfb8 Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Thu, 2 Mar 2023 12:00:23 -0800 Subject: [PATCH 402/779] Revert "Use ArgumentNullException.ThrowIfNull part 2 (#19258)" (#19263) This reverts commit 8d8f45e3dfd14a4c389b2a5009446d4649094af3. --- .../ManagementList/Common/ListOrganizer.cs | 10 ++++++++-- .../FilterRules/PropertyValueSelectorFilterRule.cs | 5 ++++- .../ManagementList/FilterProviders/FilterRulePanel.cs | 10 ++++++++-- .../FilterRuleToDisplayNameConverter.cs | 5 ++++- .../ManagementList/PropertyValueGetter.cs | 6 +++++- .../ManagementList/ManagementList/managementlist.cs | 10 ++++++++-- .../WindowsTaskbarJumpList/PropVariant.cs | 5 ++++- .../DotNetCode/Eventing/EventProviderTraceListener.cs | 4 ---- .../engine/hostifaces/HostUtilities.cs | 7 +++++-- .../engine/remoting/client/ThrottlingJob.cs | 6 +----- .../engine/runtime/MutableTuple.cs | 5 +---- .../namespaces/FileSystemProvider.cs | 3 ++- .../namespaces/TransactedRegistryKey.cs | 8 -------- test/perf/dotnet-tools/ResultsComparer/Program.cs | 2 -- 14 files changed, 50 insertions(+), 36 deletions(-) diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/ListOrganizer.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/ListOrganizer.cs index 6d84a44c7e7..7f8a0f8bfc4 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/ListOrganizer.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/ListOrganizer.cs @@ -42,7 +42,10 @@ protected override void OnKeyDown(KeyEventArgs e) partial void OnSelectItemExecutedImplementation(ExecutedRoutedEventArgs e) { - ArgumentNullException.ThrowIfNull(e.Parameter); + if (e.Parameter == null) + { + throw new ArgumentException("e.Parameter is null", "e"); + } this.RaiseEvent(new DataRoutedEventArgs(e.Parameter, ItemSelectedEvent)); this.picker.IsOpen = false; @@ -50,7 +53,10 @@ partial void OnSelectItemExecutedImplementation(ExecutedRoutedEventArgs e) partial void OnDeleteItemExecutedImplementation(ExecutedRoutedEventArgs e) { - ArgumentNullException.ThrowIfNull(e.Parameter); + if (e.Parameter == null) + { + throw new ArgumentException("e.Parameter is null", "e"); + } this.RaiseEvent(new DataRoutedEventArgs(e.Parameter, ItemDeletedEvent)); } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/PropertyValueSelectorFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/PropertyValueSelectorFilterRule.cs index 7e9eca9b25c..9143336aa4c 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/PropertyValueSelectorFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/PropertyValueSelectorFilterRule.cs @@ -76,7 +76,10 @@ public PropertyValueSelectorFilterRule(string propertyName, string propertyDispl foreach (FilterRule rule in rules) { - ArgumentNullException.ThrowIfNull(rule); + if (rule == null) + { + throw new ArgumentException("A value within rules is null", "rules"); + } this.AvailableRules.AvailableValues.Add(rule); } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanel.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanel.cs index 07a19f6befa..3e577d3cb9f 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanel.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanel.cs @@ -230,7 +230,10 @@ partial void OnAddRulesExecutedImplementation(ExecutedRoutedEventArgs e) { Debug.Assert(e != null, "not null"); - ArgumentNullException.ThrowIfNull(e.Parameter); + if (e.Parameter == null) + { + throw new ArgumentException("e.Parameter is null.", "e"); + } List itemsToAdd = new List(); @@ -262,7 +265,10 @@ partial void OnRemoveRuleExecutedImplementation(ExecutedRoutedEventArgs e) { Debug.Assert(e != null, "not null"); - ArgumentNullException.ThrowIfNull(e.Parameter); + if (e.Parameter == null) + { + throw new ArgumentException("e.Parameter is null.", "e"); + } FilterRulePanelItem item = e.Parameter as FilterRulePanelItem; if (item == null) diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRuleToDisplayNameConverter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRuleToDisplayNameConverter.cs index ee1291b8f09..07a4ed58f8b 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRuleToDisplayNameConverter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRuleToDisplayNameConverter.cs @@ -41,7 +41,10 @@ public object Convert(object value, Type targetType, object parameter, System.Gl } FilterRule rule = value as FilterRule; - ArgumentNullException.ThrowIfNull(rule); + if (rule == null) + { + throw new ArgumentException("value of type FilterRule expected.", "value"); + } return rule.DisplayName; } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/PropertyValueGetter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/PropertyValueGetter.cs index 02efbf2d920..2e9326cd909 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/PropertyValueGetter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/PropertyValueGetter.cs @@ -43,7 +43,11 @@ public virtual bool TryGetPropertyValue(string propertyName, object value, out o { propertyValue = null; - ArgumentNullException.ThrowIfNullOrEmpty(propertyName); + if (string.IsNullOrEmpty(propertyName)) + { + throw new ArgumentException("propertyName is empty", "propertyName"); + } + ArgumentNullException.ThrowIfNull(value); PropertyDescriptor descriptor = this.GetPropertyDescriptor(propertyName, value); diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/managementlist.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/managementlist.cs index 16c038f575b..4ac51c702d8 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/managementlist.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/managementlist.cs @@ -340,7 +340,10 @@ private StateDescriptor DoesViewAlreadyExist(string viewName) private void ViewManager_ItemSelected(object sender, DataRoutedEventArgs e) { - ArgumentNullException.ThrowIfNull(e.Data); + if (e.Data == null) + { + throw new ArgumentException("e.Data is null", "e"); + } StateDescriptor sd = (StateDescriptor)e.Data; sd.RestoreState(this); @@ -350,7 +353,10 @@ private void ViewManager_ItemSelected(object sender, DataRoutedEventArgs private void ViewManager_ItemDeleted(object sender, DataRoutedEventArgs e) { - ArgumentNullException.ThrowIfNull(e.Data); + if (e.Data == null) + { + throw new ArgumentException("e.Data is null", "e"); + } StateDescriptor sd = (StateDescriptor)e.Data; this.Views.Remove(sd); diff --git a/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropVariant.cs b/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropVariant.cs index 58935b2d9d4..10db7912b4a 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropVariant.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropVariant.cs @@ -29,7 +29,10 @@ internal sealed class PropVariant : IDisposable /// internal PropVariant(string value) { - ArgumentNullException.ThrowIfNull(value); + if (value == null) + { + throw new ArgumentException("PropVariantNullString", nameof(value)); + } #pragma warning disable CS0618 // Type or member is obsolete (might get deprecated in future versions _valueType = (ushort)VarEnum.VT_LPWSTR; diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProviderTraceListener.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProviderTraceListener.cs index bb488d80ede..1c82891b654 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProviderTraceListener.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProviderTraceListener.cs @@ -44,9 +44,7 @@ public string Delimiter ArgumentNullException.ThrowIfNull(value, nameof(Delimiter)); if (value.Length == 0) - { throw new ArgumentException(DotNetEventingStrings.Argument_NeedNonemptyDelimiter); - } _delimiter = value; } @@ -76,9 +74,7 @@ public EventProviderTraceListener(string providerId, string name, string delimit ArgumentNullException.ThrowIfNull(delimiter); if (delimiter.Length == 0) - { throw new ArgumentException(DotNetEventingStrings.Argument_NeedNonemptyDelimiter); - } _delimiter = delimiter; InitProvider(providerId); diff --git a/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs b/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs index 896ca99791b..e0d19c489c8 100644 --- a/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs +++ b/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs @@ -413,7 +413,8 @@ internal static List GetSuggestion(HistoryInfo lastHistory, object lastE { suggestion["Enabled"] = false; - throw new ArgumentException(SuggestionStrings.RuleMustBeScriptBlock, "Rule"); + throw new ArgumentException( + SuggestionStrings.RuleMustBeScriptBlock, "Rule"); } try @@ -481,7 +482,9 @@ internal static List GetSuggestion(HistoryInfo lastHistory, object lastE { suggestion["Enabled"] = false; - throw new ArgumentException(SuggestionStrings.InvalidMatchType, "MatchType"); + throw new ArgumentException( + SuggestionStrings.InvalidMatchType, + "MatchType"); } // If the text matches, evaluate the suggestion diff --git a/src/System.Management.Automation/engine/remoting/client/ThrottlingJob.cs b/src/System.Management.Automation/engine/remoting/client/ThrottlingJob.cs index fd5e5b7ef52..b9a0cc4dfab 100644 --- a/src/System.Management.Automation/engine/remoting/client/ThrottlingJob.cs +++ b/src/System.Management.Automation/engine/remoting/client/ThrottlingJob.cs @@ -369,11 +369,7 @@ internal void DisableFlowControlForPendingCmdletActionsQueue() internal void AddChildJobWithoutBlocking(StartableJob childJob, ChildJobFlags flags, Action jobEnqueuedAction = null) { ArgumentNullException.ThrowIfNull(childJob); - if (childJob.JobStateInfo.State != JobState.NotStarted) - { - throw new ArgumentException(RemotingErrorIdStrings.ThrottlingJobChildAlreadyRunning, nameof(childJob)); - } - + if (childJob.JobStateInfo.State != JobState.NotStarted) throw new ArgumentException(RemotingErrorIdStrings.ThrottlingJobChildAlreadyRunning, nameof(childJob)); this.AssertNotDisposed(); JobStateInfo newJobStateInfo = null; diff --git a/src/System.Management.Automation/engine/runtime/MutableTuple.cs b/src/System.Management.Automation/engine/runtime/MutableTuple.cs index 3987c4ed296..480e8e111b8 100644 --- a/src/System.Management.Automation/engine/runtime/MutableTuple.cs +++ b/src/System.Management.Automation/engine/runtime/MutableTuple.cs @@ -365,10 +365,7 @@ internal static IEnumerable GetAccessProperties(Type tupleType, in { // ContractUtils.RequiresNotNull(tupleType, "tupleType"); - if (index < 0 || index >= size) - { - throw new ArgumentException("index"); - } + if (index < 0 || index >= size) throw new ArgumentException("index"); foreach (int curIndex in GetAccessPath(size, index)) { diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index 4db3cf42a3a..3d4c3e2f9da 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -7673,7 +7673,8 @@ public static string GetTarget(PSObject instance) { if (!fileSysInfo.Exists) { - throw new ArgumentException(StringUtil.Format(SessionStateStrings.PathNotFound, fileSysInfo.FullName)); + throw new ArgumentException( + StringUtil.Format(SessionStateStrings.PathNotFound, fileSysInfo.FullName)); } return fileSysInfo.LinkTarget; diff --git a/src/System.Management.Automation/namespaces/TransactedRegistryKey.cs b/src/System.Management.Automation/namespaces/TransactedRegistryKey.cs index 198e4fea258..19e05ce99a7 100644 --- a/src/System.Management.Automation/namespaces/TransactedRegistryKey.cs +++ b/src/System.Management.Automation/namespaces/TransactedRegistryKey.cs @@ -560,9 +560,7 @@ public void DeleteSubKey(string subkey, bool throwOnMissingSubKey) else { // there is no key which also means there is no subkey if (throwOnMissingSubKey) - { throw new ArgumentException(RegistryProviderStrings.ArgumentException_RegSubKeyAbsent); - } } } @@ -1398,9 +1396,7 @@ public unsafe void SetValue(string name, object value, RegistryValueKind valueKi } if (!Enum.IsDefined(typeof(RegistryValueKind), valueKind)) - { throw new ArgumentException(RegistryProviderStrings.Arg_RegBadKeyKind); - } EnsureWriteable(); @@ -2041,18 +2037,14 @@ private static void ValidateKeyName(string name) while (nextSlash != -1) { if ((nextSlash - current) > MaxKeyLength) - { throw new ArgumentException(RegistryProviderStrings.Arg_RegKeyStrLenBug); - } current = nextSlash + 1; nextSlash = name.IndexOf('\\', current); } if ((name.Length - current) > MaxKeyLength) - { throw new ArgumentException(RegistryProviderStrings.Arg_RegKeyStrLenBug); - } } private static void ValidateKeyMode(RegistryKeyPermissionCheck mode) diff --git a/test/perf/dotnet-tools/ResultsComparer/Program.cs b/test/perf/dotnet-tools/ResultsComparer/Program.cs index 37afb965148..68615f61c78 100644 --- a/test/perf/dotnet-tools/ResultsComparer/Program.cs +++ b/test/perf/dotnet-tools/ResultsComparer/Program.cs @@ -149,9 +149,7 @@ private static void PrintTable((string id, Benchmark baseResult, Benchmark diffR var diffFiles = GetFilesToParse(args.DiffPath); if (!baseFiles.Any() || !diffFiles.Any()) - { throw new ArgumentException($"Provided paths contained no {FullBdnJsonFileExtension} files."); - } var baseResults = baseFiles.Select(ReadFromFile); var diffResults = diffFiles.Select(ReadFromFile); From a26a8d97c1d2344ea36a2e5d7bc5c79a42b43ddf Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Thu, 2 Mar 2023 12:54:13 -0800 Subject: [PATCH 403/779] Increase the timeout when waiting for the event log (#19264) --- test/powershell/engine/Basic/GroupPolicySettings.Tests.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/powershell/engine/Basic/GroupPolicySettings.Tests.ps1 b/test/powershell/engine/Basic/GroupPolicySettings.Tests.ps1 index 9c6765f0e17..1986a270259 100644 --- a/test/powershell/engine/Basic/GroupPolicySettings.Tests.ps1 +++ b/test/powershell/engine/Basic/GroupPolicySettings.Tests.ps1 @@ -90,7 +90,7 @@ Describe 'Group policy settings tests' -Tag CI,RequireAdminOnWindows { # usually event becomes visible in the log after ~500 ms # set timeout for 5 seconds Wait-UntilTrue -sb { Get-WinEvent -FilterHashtable @{ ProviderName="PowerShellCore"; Id = 4103 } -MaxEvents 5 | - Where-Object {$_.Message.Contains($RareCommand)} } -TimeoutInMilliseconds (5*1000) -IntervalInMilliseconds 100 | + Where-Object {$_.Message.Contains($RareCommand)} } -TimeoutInMilliseconds (10*1000) -IntervalInMilliseconds 100 | Should -BeTrue } From 87078a7c77ed4e800b3703f933fd390baf9dcddd Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Thu, 2 Mar 2023 13:23:26 -0800 Subject: [PATCH 404/779] Remove the 'Code Coverage Status' badge (#19265) --- README.md | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 206cf0adee9..d2f27c2a729 100644 --- a/README.md +++ b/README.md @@ -177,9 +177,9 @@ If you have any problems building, consult the developer [FAQ][]. ### Build status of nightly builds -| Azure CI (Windows) | Azure CI (Linux) | Azure CI (macOS) | Code Coverage Status | CodeFactor Grade | -|:-----------------------------------------|:-----------------------------------------------|:-----------------------------------------------|:-------------------------|:-------------------------| -| [![windows-nightly-image][]][windows-nightly-site] | [![linux-nightly-image][]][linux-nightly-site] | [![macOS-nightly-image][]][macos-nightly-site] | [![cc-image][]][cc-site] | [![cf-image][]][cf-site] | +| Azure CI (Windows) | Azure CI (Linux) | Azure CI (macOS) | CodeFactor Grade | +|:-----------------------------------------|:-----------------------------------------------|:-----------------------------------------------|:-------------------------| +| [![windows-nightly-image][]][windows-nightly-site] | [![linux-nightly-image][]][linux-nightly-site] | [![macOS-nightly-image][]][macos-nightly-site] | [![cf-image][]][cf-site] | [bd-linux]: https://github.com/PowerShell/PowerShell/tree/master/docs/building/linux.md [bd-windows]: https://github.com/PowerShell/PowerShell/tree/master/docs/building/windows-core.md @@ -193,8 +193,6 @@ If you have any problems building, consult the developer [FAQ][]. [windows-nightly-image]: https://powershell.visualstudio.com/PowerShell/_apis/build/status/PowerShell-CI-Windows-daily [linux-nightly-image]: https://powershell.visualstudio.com/PowerShell/_apis/build/status/PowerShell-CI-linux-daily?branchName=master [macOS-nightly-image]: https://powershell.visualstudio.com/PowerShell/_apis/build/status/PowerShell-CI-macos-daily?branchName=master -[cc-site]: https://codecov.io/gh/PowerShell/PowerShell -[cc-image]: https://codecov.io/gh/PowerShell/PowerShell/branch/master/graph/badge.svg [cf-site]: https://www.codefactor.io/repository/github/powershell/powershell [cf-image]: https://www.codefactor.io/repository/github/powershell/powershell/badge From 5acc664666254694498afc0352c058e6ab1d2f0c Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Fri, 3 Mar 2023 09:40:34 -0800 Subject: [PATCH 405/779] Increase the timeout for creating the `WebListener` (#19268) --- test/tools/Modules/WebListener/WebListener.psm1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/tools/Modules/WebListener/WebListener.psm1 b/test/tools/Modules/WebListener/WebListener.psm1 index 655b4cdd638..e065363e673 100644 --- a/test/tools/Modules/WebListener/WebListener.psm1 +++ b/test/tools/Modules/WebListener/WebListener.psm1 @@ -122,7 +122,7 @@ function Start-WebListener return $runningListener } - $initTimeoutSeconds = 15 + $initTimeoutSeconds = 25 $appExe = (Get-Command WebListener).Path $serverPfx = 'ServerCert.pfx' $serverPfxPassword = New-RandomHexString From d00407612caa982f040fa13371a1dc70472a1870 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Fri, 3 Mar 2023 19:51:53 +0100 Subject: [PATCH 406/779] Fix codefactor if part 1 (#19266) --- .../commands/management/Computer.cs | 110 ++++++++++++++---- .../commands/management/Eventlog.cs | 26 ++++- .../commands/management/WebServiceProxy.cs | 5 +- .../commands/utility/AddMember.cs | 5 +- .../commands/utility/AddType.cs | 10 +- .../commands/utility/DebugRunspaceCommand.cs | 10 +- .../EnableDisableRunspaceDebugCommand.cs | 5 +- .../commands/utility/NewEventCommand.cs | 5 +- .../commands/utility/Select-Object.cs | 16 ++- .../commands/utility/Update-TypeData.cs | 10 +- .../commands/utility/XmlCommands.cs | 5 +- .../host/msh/ConsoleHostUserInterface.cs | 16 ++- .../DotNetCode/Eventing/EventProvider.cs | 5 +- .../ScheduledJob.cs | 10 +- .../ConfigProvider.cs | 5 +- .../CoreCLR/CorePsPlatform.cs | 15 ++- .../cimSupport/cmdletization/ScriptWriter.cs | 18 ++- .../engine/Attributes.cs | 10 +- .../engine/ExternalScriptInfo.cs | 5 +- .../engine/InitialSessionState.cs | 6 +- .../engine/InternalCommands.cs | 5 +- .../engine/NativeCommandParameterBinder.cs | 22 +++- .../engine/NativeCommandProcessor.cs | 16 ++- .../engine/ParameterBinderBase.cs | 5 +- src/powershell/Program.cs | 6 +- 25 files changed, 283 insertions(+), 68 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs index e1b06c0bc94..126596818af 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs @@ -533,7 +533,10 @@ private List TestRestartStageUsingWsman(IEnumerable computerName { try { - if (token.IsCancellationRequested) { break; } + if (token.IsCancellationRequested) + { + break; + } using (CimSession cimSession = RemoteDiscoveryHelper.CreateCimSession(computer, Credential, WsmanAuthentication, isLocalHost: false, this, token)) { @@ -675,7 +678,10 @@ internal static List TestWmiConnectionUsingWsman(List computerNa { try { - if (token.IsCancellationRequested) { break; } + if (token.IsCancellationRequested) + { + break; + } using (CimSession cimSession = RemoteDiscoveryHelper.CreateCimSession(computer, credential, wsmanAuthentication, isLocalHost: false, cmdlet, token)) { @@ -830,7 +836,10 @@ protected override void ProcessRecord() ValidateComputerNames(); object[] flags = new object[] { 2, 0 }; - if (Force) flags[0] = forcedReboot; + if (Force) + { + flags[0] = forcedReboot; + } if (ParameterSetName.Equals(DefaultParameterSet, StringComparison.OrdinalIgnoreCase)) { @@ -905,14 +914,18 @@ protected override void ProcessRecord() while (true) { - int loopCount = actualDelay * 4; // (delay * 1000)/250ms + // (delay * 1000)/250ms + int loopCount = actualDelay * 4; while (loopCount > 0) { WriteProgress(_indicator[(indicatorIndex++) % 4] + _activity, _status, _percent, ProgressRecordType.Processing); loopCount--; _waitHandler.Wait(250); - if (_exit) { break; } + if (_exit) + { + break; + } } if (first) @@ -932,7 +945,10 @@ protected override void ProcessRecord() // Test restart stage. // We check if the target machine has already rebooted by querying the LastBootUpTime from the Win32_OperatingSystem object. // So after this step, we are sure that both the Network and the WMI or WinRM service have already come up. - if (_exit) { break; } + if (_exit) + { + break; + } if (restartStageTestList.Count > 0) { @@ -948,7 +964,10 @@ protected override void ProcessRecord() } // Test WMI service - if (_exit) { break; } + if (_exit) + { + break; + } if (wmiTestList.Count > 0) { @@ -966,10 +985,16 @@ protected override void ProcessRecord() } } - if (isForWmi) { break; } + if (isForWmi) + { + break; + } // Test WinRM service - if (_exit) { break; } + if (_exit) + { + break; + } if (winrmTestList.Count > 0) { @@ -994,16 +1019,25 @@ protected override void ProcessRecord() loopCount--; _waitHandler.Wait(250); - if (_exit) { break; } + if (_exit) + { + break; + } } } } } - if (isForWinRm) { break; } + if (isForWinRm) + { + break; + } // Test PowerShell - if (_exit) { break; } + if (_exit) + { + break; + } if (psTestList.Count > 0) { @@ -1019,7 +1053,10 @@ protected override void ProcessRecord() } while (false); // if time is up or Ctrl+c is typed, break out - if (_exit) { break; } + if (_exit) + { + break; + } // Check if the restart completes switch (_waitFor) @@ -1063,18 +1100,38 @@ protected override void ProcessRecord() // The timeout expires. Write out timeout error messages for the computers that haven't finished restarting do { - if (restartStageTestList.Count > 0) { WriteOutTimeoutError(restartStageTestList); } + if (restartStageTestList.Count > 0) + { + WriteOutTimeoutError(restartStageTestList); + } + + if (wmiTestList.Count > 0) + { + WriteOutTimeoutError(wmiTestList); + } - if (wmiTestList.Count > 0) { WriteOutTimeoutError(wmiTestList); } // Wait for WMI. All computers that finished restarting are put in "winrmTestList" - if (isForWmi) { break; } + if (isForWmi) + { + break; + } // Wait for WinRM. All computers that finished restarting are put in "psTestList" - if (winrmTestList.Count > 0) { WriteOutTimeoutError(winrmTestList); } + if (winrmTestList.Count > 0) + { + WriteOutTimeoutError(winrmTestList); + } - if (isForWinRm) { break; } + if (isForWinRm) + { + break; + } + + if (psTestList.Count > 0) + { + WriteOutTimeoutError(psTestList); + } - if (psTestList.Count > 0) { WriteOutTimeoutError(psTestList); } // Wait for PowerShell. All computers that finished restarting are put in "allDoneList" } while (false); } @@ -1221,7 +1278,10 @@ private void ProcessWSManProtocol(object[] flags) string strLocal = string.Empty; bool isLocalHost = false; - if (_cancel.Token.IsCancellationRequested) { break; } + if (_cancel.Token.IsCancellationRequested) + { + break; + } if ((computer.Equals("localhost", StringComparison.OrdinalIgnoreCase)) || (computer.Equals(".", StringComparison.OrdinalIgnoreCase))) { @@ -1576,7 +1636,10 @@ private void DoRenameComputerWsman(string computer, string computerName, string protected override void ProcessRecord() { string targetComputer = ValidateComputerName(); - if (targetComputer == null) return; + if (targetComputer == null) + { + return; + } bool isLocalhost = targetComputer.Equals("localhost", StringComparison.OrdinalIgnoreCase); if (isLocalhost) @@ -1596,7 +1659,10 @@ protected override void ProcessRecord() /// protected override void EndProcessing() { - if (!_containsLocalHost) return; + if (!_containsLocalHost) + { + return; + } DoRenameComputerAction("localhost", _newNameForLocalHost, true); } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Eventlog.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Eventlog.cs index 89c58acbf57..4732716841a 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Eventlog.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Eventlog.cs @@ -360,7 +360,11 @@ private void OutputEvents(string logName) } catch (InvalidOperationException e) { - if (processing) throw; + if (processing) + { + throw; + } + ThrowTerminatingError(new ErrorRecord( e, // default exception text is OK "EventLogNotFound", @@ -490,7 +494,10 @@ private bool FiltersMatch(EventLogEntry entry) } } - if (!entrymatch) return entrymatch; + if (!entrymatch) + { + return entrymatch; + } } if (_sources != null) @@ -511,7 +518,10 @@ private bool FiltersMatch(EventLogEntry entry) } } - if (!sourcematch) return sourcematch; + if (!sourcematch) + { + return sourcematch; + } } if (_message != null) @@ -545,7 +555,10 @@ private bool FiltersMatch(EventLogEntry entry) } } - if (!usernamematch) return usernamematch; + if (!usernamematch) + { + return usernamematch; + } } if (_isDateSpecified) @@ -582,7 +595,10 @@ private bool FiltersMatch(EventLogEntry entry) } } - if (!datematch) return datematch; + if (!datematch) + { + return datematch; + } } return true; diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/WebServiceProxy.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/WebServiceProxy.cs index 547b121c571..3fc313fe222 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/WebServiceProxy.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/WebServiceProxy.cs @@ -475,7 +475,10 @@ private object InstantiateWebServiceProxy(Assembly assembly) break; } - if (proxyType != null) break; + if (proxyType != null) + { + break; + } } System.Management.Automation.Diagnostics.Assert( diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddMember.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddMember.cs index efb035b7785..8ddd95e6b82 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddMember.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddMember.cs @@ -524,7 +524,10 @@ private void UpdateTypeNames() // Respect the type shortcut Type type; string typeNameInUse = _typeName; - if (LanguagePrimitives.TryConvertTo(_typeName, out type)) { typeNameInUse = type.FullName; } + if (LanguagePrimitives.TryConvertTo(_typeName, out type)) + { + typeNameInUse = type.FullName; + } _inputObject.TypeNames.Insert(0, typeNameInUse); } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs index bc1d6b0ba4e..926d6c3dc1f 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs @@ -301,7 +301,10 @@ public string[] ReferencedAssemblies set { - if (value != null) { _referencedAssemblies = value; } + if (value != null) + { + _referencedAssemblies = value; + } } } @@ -867,7 +870,10 @@ private IEnumerable GetPortableExecutableReferences var tempReferences = new List(s_autoReferencedAssemblies.Value); foreach (string assembly in ReferencedAssemblies) { - if (string.IsNullOrWhiteSpace(assembly)) { continue; } + if (string.IsNullOrWhiteSpace(assembly)) + { + continue; + } string resolvedAssemblyPath = ResolveAssemblyName(assembly, true); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/DebugRunspaceCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/DebugRunspaceCommand.cs index fc257810d55..579522a6d3d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/DebugRunspaceCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/DebugRunspaceCommand.cs @@ -270,7 +270,10 @@ private void WaitAndReceiveRunspaceOutput() // Wait for running script. _newRunningScriptEvent.Wait(); - if (!_debugging) { return; } + if (!_debugging) + { + return; + } AddDataEventHandlers(); @@ -503,7 +506,10 @@ private void HandlePowerShellPStreamItem(PSStreamObject streamItem) private void AddToDebugBlockingCollection(PSStreamObject streamItem) { - if (!_debugBlockingCollection.IsOpen) { return; } + if (!_debugBlockingCollection.IsOpen) + { + return; + } if (streamItem != null) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/EnableDisableRunspaceDebugCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/EnableDisableRunspaceDebugCommand.cs index e4d5b5d6b27..fdc2911fa6c 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/EnableDisableRunspaceDebugCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/EnableDisableRunspaceDebugCommand.cs @@ -59,7 +59,10 @@ public sealed class PSRunspaceDebug /// Runspace local Id. public PSRunspaceDebug(bool enabled, bool breakAll, string runspaceName, int runspaceId) { - if (string.IsNullOrEmpty(runspaceName)) { throw new PSArgumentNullException(nameof(runspaceName)); } + if (string.IsNullOrEmpty(runspaceName)) + { + throw new PSArgumentNullException(nameof(runspaceName)); + } this.Enabled = enabled; this.BreakAll = breakAll; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewEventCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewEventCommand.cs index 34c95a116f3..1e46241b2d8 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewEventCommand.cs @@ -121,7 +121,10 @@ protected override void EndProcessing() } object messageSender = null; - if (_sender != null) { messageSender = _sender.BaseObject; } + if (_sender != null) + { + messageSender = _sender.BaseObject; + } // And then generate the event WriteObject(Events.GenerateEvent(_sourceIdentifier, messageSender, baseEventArgs, _messageData, true, false)); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Select-Object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Select-Object.cs index d7ce5310c98..b54873067ef 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Select-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Select-Object.cs @@ -434,7 +434,11 @@ private void ProcessParameter(MshParameter p, PSObject inputObject, List tempExprResults = resolvedName.GetValues(inputObject); - if (tempExprResults == null) continue; + if (tempExprResults == null) + { + continue; + } + foreach (PSPropertyExpressionResult mshExpRes in tempExprResults) { expressionResults.Add(mshExpRes); @@ -525,7 +529,10 @@ private void ProcessExpandParameter(MshParameter p, PSObject inputObject, if (r.Exception == null) { // ignore the property value if it's null - if (r.Result == null) { return; } + if (r.Result == null) + { + return; + } System.Collections.IEnumerable results = LanguagePrimitives.GetEnumerable(r.Result); if (results == null) @@ -545,7 +552,10 @@ private void ProcessExpandParameter(MshParameter p, PSObject inputObject, foreach (object expandedValue in results) { // ignore the element if it's null - if (expandedValue == null) { continue; } + if (expandedValue == null) + { + continue; + } // add NoteProperties if there is any // If expandedValue is a base object, we don't want to associate the NoteProperty diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-TypeData.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-TypeData.cs index 8e07a80384d..675df274181 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-TypeData.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-TypeData.cs @@ -1117,7 +1117,10 @@ protected override void ProcessRecord() string removeFileTarget = UpdateDataStrings.UpdateTarget; Collection typeFileTotal = UpdateData.Glob(_typeFiles, "TypePathException", this); - if (typeFileTotal.Count == 0) { return; } + if (typeFileTotal.Count == 0) + { + return; + } // Key of the map is the name of the file that is in the cache. Value of the map is a index list. Duplicate files might // exist in the cache because the user can add arbitrary files to the cache by $host.Runspace.InitialSessionState.Types.Add() @@ -1129,7 +1132,10 @@ protected override void ProcessRecord() for (int index = 0; index < Context.InitialSessionState.Types.Count; index++) { string fileName = Context.InitialSessionState.Types[index].FileName; - if (fileName == null) { continue; } + if (fileName == null) + { + continue; + } // Resolving the file path because the path to the types file in module manifest is now specified as // ..\..\types.ps1xml which expands to C:\Windows\System32\WindowsPowerShell\v1.0\Modules\Microsoft.PowerShell.Core\..\..\types.ps1xml diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs index 8873676c61d..0cd748c6139 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs @@ -208,7 +208,10 @@ private void CreateFileStream() { Dbg.Assert(Path != null, "FileName is mandatory parameter"); - if (!ShouldProcess(Path)) return; + if (!ShouldProcess(Path)) + { + return; + } StreamWriter sw; PathUtils.MasterStreamOpen( diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs index 1ab19d41c36..cddaac5fbde 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs @@ -1491,7 +1491,10 @@ internal string ReadLine(bool endOnTab, string initialContent, out ReadLineResul result = ReadLineResult.endedOnEnter; // If the test hook is set, read from it. - if (s_h != null) return s_h.ReadLine(); + if (s_h != null) + { + return s_h.ReadLine(); + } string restOfLine = null; @@ -1536,14 +1539,21 @@ private string ReadLineFromFile(string initialContent) } var c = unchecked((char)inC); - if (!NoPrompt) Console.Out.Write(c); + if (!NoPrompt) + { + Console.Out.Write(c); + } if (c == '\r') { // Treat as newline, but consume \n if there is one. if (consoleIn.Peek() == '\n') { - if (!NoPrompt) Console.Out.Write('\n'); + if (!NoPrompt) + { + Console.Out.Write('\n'); + } + consoleIn.Read(); } diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs index d283a5dd298..af32014ab9d 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs @@ -131,7 +131,10 @@ protected virtual void Dispose(bool disposing) // // check if the object has been already disposed // - if (_disposed == 1) return; + if (_disposed == 1) + { + return; + } if (Interlocked.Exchange(ref _disposed, 1) != 0) { diff --git a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJob.cs b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJob.cs index 85680da94a4..59403d88520 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJob.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJob.cs @@ -926,7 +926,10 @@ private PSDataCollection CopyResults(ICollection fromResults) private void AddSetShouldExitToHost() { - if (!_allowSetShouldExit || _host == null) { return; } + if (!_allowSetShouldExit || _host == null) + { + return; + } PSObject hostPrivateData = _host.PrivateData as PSObject; if (hostPrivateData != null) @@ -938,7 +941,10 @@ private void AddSetShouldExitToHost() private void RemoveSetShouldExitFromHost() { - if (!_allowSetShouldExit || _host == null) { return; } + if (!_allowSetShouldExit || _host == null) + { + return; + } PSObject hostPrivateData = _host.PrivateData as PSObject; if (hostPrivateData != null) diff --git a/src/Microsoft.WSMan.Management/ConfigProvider.cs b/src/Microsoft.WSMan.Management/ConfigProvider.cs index a5d9d6a7cb0..701e6db510d 100644 --- a/src/Microsoft.WSMan.Management/ConfigProvider.cs +++ b/src/Microsoft.WSMan.Management/ConfigProvider.cs @@ -617,7 +617,10 @@ protected override void GetItem(string path) SessionObjCache.TryGetValue(host, out sessionobj); XmlDocument xmlResource = FindResourceValue(sessionobj, uri, null); - if (xmlResource == null) { return; } + if (xmlResource == null) + { + return; + } // if endswith '\', removes it. if (path.EndsWith(WSManStringLiterals.DefaultPathSeparator.ToString(), StringComparison.OrdinalIgnoreCase)) diff --git a/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs b/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs index 81b0e624ddf..25b1624c6cf 100644 --- a/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs +++ b/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs @@ -69,7 +69,10 @@ public static bool IsNanoServer #if UNIX return false; #else - if (_isNanoServer.HasValue) { return _isNanoServer.Value; } + if (_isNanoServer.HasValue) + { + return _isNanoServer.Value; + } _isNanoServer = false; using (RegistryKey regKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Server\ServerLevels")) @@ -99,7 +102,10 @@ public static bool IsIoT #if UNIX return false; #else - if (_isIoT.HasValue) { return _isIoT.Value; } + if (_isIoT.HasValue) + { + return _isIoT.Value; + } _isIoT = false; using (RegistryKey regKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion")) @@ -129,7 +135,10 @@ public static bool IsWindowsDesktop #if UNIX return false; #else - if (_isWindowsDesktop.HasValue) { return _isWindowsDesktop.Value; } + if (_isWindowsDesktop.HasValue) + { + return _isWindowsDesktop.Value; + } _isWindowsDesktop = !IsNanoServer && !IsIoT; return _isWindowsDesktop.Value; diff --git a/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs b/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs index a0e09694705..ccc95b9735c 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs @@ -1202,7 +1202,11 @@ string parameterSetName in MultiplyParameterSets( GetMethodParameterSet(method), StaticMethodParameterSetTemplate, commonParameterSets)) { - if (!firstParameterSet) output.Write(", "); + if (!firstParameterSet) + { + output.Write(", "); + } + firstParameterSet = false; output.Write("'{0}'", CodeGeneration.EscapeSingleQuotedStringContent(parameterSetName)); } @@ -1353,7 +1357,11 @@ private void GenerateMethodParametersProcessing( bool firstParameterSet = true; foreach (string parameterSetName in MultiplyParameterSets(GetMethodParameterSet(method), InstanceMethodParameterSetTemplate, commonParameterSets, queryParameterSets)) { - if (!firstParameterSet) output.Write(", "); + if (!firstParameterSet) + { + output.Write(", "); + } + firstParameterSet = false; output.Write("'{0}'", CodeGeneration.EscapeSingleQuotedStringContent(parameterSetName)); } @@ -1495,7 +1503,11 @@ private static void GenerateIfBoundParameter( foreach (string queryParameterSetName in cmdletParameterMetadata.ParameterSets.Keys) foreach (string parameterSetName in MultiplyParameterSets(queryParameterSetName, InstanceQueryParameterSetTemplate, commonParameterSets, methodParameterSets)) { - if (!firstParameterSet) output.Write(", "); + if (!firstParameterSet) + { + output.Write(", "); + } + firstParameterSet = false; output.Write("'{0}'", CodeGeneration.EscapeSingleQuotedStringContent(parameterSetName)); } diff --git a/src/System.Management.Automation/engine/Attributes.cs b/src/System.Management.Automation/engine/Attributes.cs index 0e11dc7aac3..e7b289418fc 100644 --- a/src/System.Management.Automation/engine/Attributes.cs +++ b/src/System.Management.Automation/engine/Attributes.cs @@ -2053,7 +2053,10 @@ protected override void Validate(object arguments, EngineIntrinsics engineIntrin { // If the element of the collection is of value type, then no need to check for null // because a value-type value cannot be null. - if (isElementValueType) { return; } + if (isElementValueType) + { + return; + } IEnumerator enumerator = LanguagePrimitives.GetEnumerator(arguments); while (enumerator.MoveNext()) @@ -2137,7 +2140,10 @@ protected override void Validate(object arguments, EngineIntrinsics engineIntrin { bool isEmpty = true; IEnumerator enumerator = LanguagePrimitives.GetEnumerator(arguments); - if (enumerator.MoveNext()) { isEmpty = false; } + if (enumerator.MoveNext()) + { + isEmpty = false; + } // If the element of the collection is of value type, then no need to check for null // because a value-type value cannot be null. diff --git a/src/System.Management.Automation/engine/ExternalScriptInfo.cs b/src/System.Management.Automation/engine/ExternalScriptInfo.cs index 52713edb874..31a520d6070 100644 --- a/src/System.Management.Automation/engine/ExternalScriptInfo.cs +++ b/src/System.Management.Automation/engine/ExternalScriptInfo.cs @@ -188,7 +188,10 @@ public override SessionStateEntryVisibility Visibility { get { - if (Context == null) return SessionStateEntryVisibility.Public; + if (Context == null) + { + return SessionStateEntryVisibility.Public; + } return Context.EngineSessionState.CheckScriptVisibility(_path); } diff --git a/src/System.Management.Automation/engine/InitialSessionState.cs b/src/System.Management.Automation/engine/InitialSessionState.cs index 23383826bae..4cf2bc44e35 100644 --- a/src/System.Management.Automation/engine/InitialSessionState.cs +++ b/src/System.Management.Automation/engine/InitialSessionState.cs @@ -5231,7 +5231,11 @@ private static void AnalyzeModuleAssemblyWithReflection( // the users of the cmdlet, instead of the author, should have control of what options applied to an alias // ('ScopedItemOptions.ReadOnly' and/or 'ScopedItemOptions.AllScopes'). var aliasEntry = new SessionStateAliasEntry(alias, cmdletName, description: string.Empty, ScopedItemOptions.None); - if (psSnapInInfo != null) { aliasEntry.SetPSSnapIn(psSnapInInfo); } + + if (psSnapInInfo != null) + { + aliasEntry.SetPSSnapIn(psSnapInInfo); + } if (moduleInfo != null) { diff --git a/src/System.Management.Automation/engine/InternalCommands.cs b/src/System.Management.Automation/engine/InternalCommands.cs index 0edc1a21a61..4f13089811d 100644 --- a/src/System.Management.Automation/engine/InternalCommands.cs +++ b/src/System.Management.Automation/engine/InternalCommands.cs @@ -685,7 +685,10 @@ private void ProcessPropertyAndMethodParameterSet() else { // if inputObject is of IDictionary, get the value - if (GetValueFromIDictionaryInput()) { return; } + if (GetValueFromIDictionaryInput()) + { + return; + } PSMemberInfo member = null; if (WildcardPattern.ContainsWildcardCharacters(_propertyOrMethodName)) diff --git a/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs b/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs index 104414f1fb8..7149f0a2e40 100644 --- a/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs +++ b/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs @@ -452,7 +452,10 @@ internal static bool NeedQuotes(string stringToCheck) private static string GetEnumerableArgSeparator(ArrayLiteralAst arrayLiteralAst, int index) { - if (arrayLiteralAst == null) return " "; + if (arrayLiteralAst == null) + { + return " "; + } // index points to the *next* element, so we're looking for space between // it and the previous element. @@ -464,14 +467,25 @@ private static string GetEnumerableArgSeparator(ArrayLiteralAst arrayLiteralAst, var afterPrev = prev.Extent.EndOffset; var beforeNext = next.Extent.StartOffset - 1; - if (afterPrev == beforeNext) return ","; + if (afterPrev == beforeNext) + { + return ","; + } var arrayText = arrayExtent.Text; afterPrev -= arrayExtent.StartOffset; beforeNext -= arrayExtent.StartOffset; - if (arrayText[afterPrev] == ',') return ", "; - if (arrayText[beforeNext] == ',') return " ,"; + if (arrayText[afterPrev] == ',') + { + return ", "; + } + + if (arrayText[beforeNext] == ',') + { + return " ,"; + } + return " , "; } diff --git a/src/System.Management.Automation/engine/NativeCommandProcessor.cs b/src/System.Management.Automation/engine/NativeCommandProcessor.cs index ecf5e79de14..b825c024ef3 100644 --- a/src/System.Management.Automation/engine/NativeCommandProcessor.cs +++ b/src/System.Management.Automation/engine/NativeCommandProcessor.cs @@ -1146,7 +1146,11 @@ internal void StopProcessing() { lock (_sync) { - if (_stopped) return; + if (_stopped) + { + return; + } + _stopped = true; } @@ -1651,9 +1655,15 @@ public ProcessOutputHandler(Process process, BlockingCollection Date: Sat, 4 Mar 2023 10:41:26 +1300 Subject: [PATCH 407/779] Update supported distros in Readme (#18667) --- README.md | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index d2f27c2a729..bea2a885769 100644 --- a/README.md +++ b/README.md @@ -30,10 +30,10 @@ You can download and install a PowerShell package for any of the following platf | -------------------------------------------| ------------------------| ------------------------| ----------------------| ------------------------------| | [Windows (x64)][corefx-win] | [.msi][lts-windows-64] | [.msi][rl-windows-64] | [.msi][pv-windows-64] | [Instructions][in-windows] | | [Windows (x86)][corefx-win] | [.msi][lts-windows-86] | [.msi][rl-windows-86] | [.msi][pv-windows-86] | [Instructions][in-windows] | +| [Ubuntu 22.04][corefx-linux] | [.deb][lts-deb] | [.deb][rl-ubuntu22] | [.deb][pv-deb] | [Instructions][in-ubuntu22] | | [Ubuntu 20.04][corefx-linux] | [.deb][lts-deb] | [.deb][rl-ubuntu20] | [.deb][pv-deb] | [Instructions][in-ubuntu20] | | [Ubuntu 18.04][corefx-linux] | [.deb][lts-deb] | [.deb][rl-ubuntu18] | [.deb][pv-deb] | [Instructions][in-ubuntu18] | -| [Ubuntu 16.04][corefx-linux] | [.deb][lts-deb] | [.deb][rl-ubuntu16] | [.deb][pv-deb] | [Instructions][in-ubuntu16] | -| [Debian 9][corefx-linux] | [.deb][lts-deb] | [.deb][rl-debian9] | [.deb][pv-deb] | [Instructions][in-deb9] | +| [Ubuntu 16.04][corefx-linux] | [.deb][lts-deb] | N/A | N/A | [Instructions][in-ubuntu16] | | [Debian 10][corefx-linux] | [.deb][lts-deb] | [.deb][rl-debian10] | [.deb][pv-deb] | [Instructions][in-deb9] | | [Debian 11][corefx-linux] | [.deb][lts-deb] | [.deb][rl-debian11] | [.deb][pv-deb] | | | [CentOS 7][corefx-linux] | [.rpm][lts-rh] | [.rpm][rl-centos] | [.rpm][pv-rpm] | [Instructions][in-centos] | @@ -42,7 +42,7 @@ You can download and install a PowerShell package for any of the following platf | [openSUSE 42.3][corefx-linux] | [.rpm][lts-rh] | [.rpm][rl-centos] | [.rpm][pv-rpm] | [Instructions][in-opensuse] | | [Fedora 35][corefx-linux] | [.rpm][lts-rh] | [.rpm][rl-centos] | [.rpm][pv-rpm] | [Instructions][in-fedora] | | [macOS 10.13+ (x64)][corefx-macos] | [.pkg][lts-macos] | [.pkg][rl-macos] | [.pkg][pv-macos] | [Instructions][in-macos] | -| [macOS 10.13+ (arm64)][corefx-macos] | [.pkg][lts-macos-arm64] | [.pkg][rl-macos-arm64] | [.pkg][pv-macos-arm64]| [Instructions][in-macos] | +| [macOS 11+ (arm64)][corefx-macos] | [.pkg][lts-macos-arm64] | [.pkg][rl-macos-arm64] | [.pkg][pv-macos-arm64]| [Instructions][in-macos] | | Docker | | | | [Instructions][in-docker] | You can download and install a PowerShell package for any of the following platforms, **which are supported by the community.** @@ -50,7 +50,7 @@ You can download and install a PowerShell package for any of the following platf | Platform | Downloads (stable) | Downloads (preview) | How to Install | | -------------------------| ------------------------| ----------------------------- | ------------------------------| | Arch Linux | | | [Instructions][in-archlinux] | -| Kali Linux | [.deb][rl-ubuntu16] | [.deb][pv-deb] | [Instructions][in-kali] | +| Kali Linux | [.deb][rl-deb] | [.deb][pv-deb] | [Instructions][in-kali] | | Many Linux distributions | [Snapcraft][rl-snap] | [Snapcraft][pv-snap] | | You can also download the PowerShell binary archives for Windows, macOS and Linux. @@ -61,8 +61,8 @@ You can also download the PowerShell binary archives for Windows, macOS and Linu | macOS (x64) | [64-bit][rl-macos-tar] | [64-bit][pv-macos-tar] | [Instructions][in-tar-macos] | | macOS (arm64) | [64-bit][rl-macos-tar-arm64] | [64-bit][pv-macos-tar-arm64] | [Instructions][in-tar-macos] | | Linux | [64-bit][rl-linux-tar] | [64-bit][pv-linux-tar] | [Instructions][in-tar-linux] | -| Windows (Arm) | [64-bit][rl-winarm64] (preview) | [64-bit][pv-winarm64] | [Instructions][in-arm] | -| Raspbian (Arm) | [32-bit][rl-arm32]/[64-bit][rl-arm64] | [32-bit][pv-arm32]/[64-bit][pv-arm64] | [Instructions][in-raspbian] | +| Windows (ARM) | [64-bit][rl-winarm64] (preview) | [64-bit][pv-winarm64] | [Instructions][in-arm] | +| Raspbian (ARM) | [32-bit][rl-arm32]/[64-bit][rl-arm64] | [32-bit][pv-arm32]/[64-bit][pv-arm64] | [Instructions][in-raspbian] | [lts-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.10/PowerShell-7.2.10-win-x86.msi [lts-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.10/PowerShell-7.2.10-win-x64.msi @@ -73,10 +73,10 @@ You can also download the PowerShell binary archives for Windows, macOS and Linu [rl-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.3/PowerShell-7.3.3-win-x64.msi [rl-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.3/PowerShell-7.3.3-win-x86.msi +[rl-deb]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.3/powershell_7.3.3-1.deb_amd64.deb +[rl-ubuntu22]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.3/powershell_7.3.3-1.deb_amd64.deb [rl-ubuntu20]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.3/powershell_7.3.3-1.deb_amd64.deb [rl-ubuntu18]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.3/powershell_7.3.3-1.deb_amd64.deb -[rl-ubuntu16]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.3/powershell_7.3.3-1.deb_amd64.deb -[rl-debian9]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.3/powershell_7.3.3-1.deb_amd64.deb [rl-debian10]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.3/powershell_7.3.3-1.deb_amd64.deb [rl-debian11]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.3/powershell_7.3.3-1.deb_amd64.deb [rl-centos]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.3/powershell-7.3.3-1.rh.x86_64.rpm @@ -113,6 +113,7 @@ You can also download the PowerShell binary archives for Windows, macOS and Linu [in-ubuntu16]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-linux#ubuntu-1604 [in-ubuntu18]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-linux#ubuntu-1804 [in-ubuntu20]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-linux#ubuntu-2004 +[in-ubuntu22]: https://learn.microsoft.com/powershell/scripting/install/installing-powershell-on-linux?view=powershell-7.3#ubuntu [in-deb9]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-linux#debian-9 [in-deb10]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-linux#debian-10 [in-centos]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-linux#centos-7 @@ -128,9 +129,9 @@ You can also download the PowerShell binary archives for Windows, macOS and Linu [in-tar-macos]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-macos#binary-archives [in-raspbian]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-linux#raspbian [in-arm]: https://docs.microsoft.com/powershell/scripting/install/powershell-core-on-arm -[corefx-win]:https://github.com/dotnet/core/blob/master/release-notes/3.0/3.0-supported-os.md#windows -[corefx-linux]:https://github.com/dotnet/core/blob/master/release-notes/3.0/3.0-supported-os.md#linux -[corefx-macos]:https://github.com/dotnet/core/blob/master/release-notes/3.0/3.0-supported-os.md#macos +[corefx-win]:https://github.com/dotnet/core/blob/main/release-notes/6.0/supported-os.md#windows +[corefx-linux]:https://github.com/dotnet/core/blob/main/release-notes/6.0/supported-os.md#linux +[corefx-macos]:https://github.com/dotnet/core/blob/main/release-notes/6.0/supported-os.md#macos To install a specific version, visit [releases](https://github.com/PowerShell/PowerShell/releases). From 0d6b93a23f92d3f39cd92eeaa7934d6d6778f089 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Sat, 4 Mar 2023 18:30:14 +0100 Subject: [PATCH 408/779] Fix codefactor if part 2 (#19267) --- .../common/DisplayDatabase/typeDataManager.cs | 15 ++++++++-- .../engine/Modules/ModuleIntrinsics.cs | 9 +++++- .../engine/Modules/ScriptAnalysis.cs | 5 +++- .../engine/parser/Position.cs | 12 ++++++-- .../engine/parser/SemanticChecks.cs | 22 ++++++++++++--- .../engine/parser/TypeResolver.cs | 5 +++- .../engine/remoting/commands/ResumeJob.cs | 28 ++++++++++++++++--- .../engine/remoting/commands/StopJob.cs | 12 ++++++-- .../engine/remoting/commands/SuspendJob.cs | 28 ++++++++++++++++--- .../engine/remoting/common/psstreamobject.cs | 17 +++++++++-- .../remoting/server/ServerPowerShellDriver.cs | 5 +++- .../engine/runtime/CompiledScriptBlock.cs | 10 +++++-- .../engine/runtime/Operations/MiscOps.cs | 5 +++- .../help/UpdatableHelpCommandBase.cs | 11 ++++++-- .../help/UpdatableHelpSystem.cs | 5 +++- .../namespaces/LocationGlobber.cs | 5 +++- .../namespaces/TransactedRegistryKey.cs | 10 +++++-- .../security/SecurityManager.cs | 23 ++++++++++++--- .../utils/ClrFacade.cs | 10 +++++-- .../utils/PsUtils.cs | 15 ++++++++-- .../utils/RuntimeException.cs | 6 +++- .../utils/assert.cs | 5 +++- src/TypeCatalogGen/TypeCatalogGen.cs | 6 +++- .../src/code/NamedPipeConnection.cs | 5 +++- 24 files changed, 226 insertions(+), 48 deletions(-) diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataManager.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataManager.cs index c42bd21adc7..629e419d5a2 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataManager.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataManager.cs @@ -409,7 +409,10 @@ private static TypeInfoDataBase LoadFromFileHelper( continue; } - if (etwEnabled) RunspaceEventSource.Log.ProcessFormatFileStart(file.FullPath); + if (etwEnabled) + { + RunspaceEventSource.Log.ProcessFormatFileStart(file.FullPath); + } if (!ProcessBuiltin(file, db, expressionFactory, logEntries, ref success)) { @@ -428,7 +431,10 @@ private static TypeInfoDataBase LoadFromFileHelper( { string mshsnapinMessage = StringUtil.Format(FormatAndOutXmlLoadingStrings.MshSnapinQualifiedError, info.psSnapinName, entry.message); info.errors.Add(mshsnapinMessage); - if (entry.failToLoadFile) { file.FailToLoadFile = true; } + if (entry.failToLoadFile) + { + file.FailToLoadFile = true; + } } } // now aggregate the entries... @@ -436,7 +442,10 @@ private static TypeInfoDataBase LoadFromFileHelper( } } - if (etwEnabled) RunspaceEventSource.Log.ProcessFormatFileStop(file.FullPath); + if (etwEnabled) + { + RunspaceEventSource.Log.ProcessFormatFileStop(file.FullPath); + } } // add any sensible defaults to the database diff --git a/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs b/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs index f15a567d655..49317331924 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs @@ -1139,12 +1139,19 @@ private static string AddToPath(string basePath, string pathToAdd, int insertPos if (insertPosition == -1) // append subPathToAdd to the end { bool endsWithPathSeparator = false; - if (result.Length > 0) endsWithPathSeparator = (result[result.Length - 1] == Path.PathSeparator); + if (result.Length > 0) + { + endsWithPathSeparator = (result[result.Length - 1] == Path.PathSeparator); + } if (endsWithPathSeparator) + { result.Append(subPathToAdd); + } else + { result.Append(Path.PathSeparator + subPathToAdd); + } } else if (insertPosition > result.Length) { diff --git a/src/System.Management.Automation/engine/Modules/ScriptAnalysis.cs b/src/System.Management.Automation/engine/Modules/ScriptAnalysis.cs index f8b188f47b5..591e29f657f 100644 --- a/src/System.Management.Automation/engine/Modules/ScriptAnalysis.cs +++ b/src/System.Management.Automation/engine/Modules/ScriptAnalysis.cs @@ -434,7 +434,10 @@ public override AstVisitAction VisitCommand(CommandAst commandAst) private void ProcessCmdletArguments(object value, Action onEachArgument) { - if (value == null) return; + if (value == null) + { + return; + } var commandName = value as string; if (commandName != null) diff --git a/src/System.Management.Automation/engine/parser/Position.cs b/src/System.Management.Automation/engine/parser/Position.cs index 571a0c587f4..589c3eb92a5 100644 --- a/src/System.Management.Automation/engine/parser/Position.cs +++ b/src/System.Management.Automation/engine/parser/Position.cs @@ -356,10 +356,18 @@ internal static bool ContainsLineAndColumn(this IScriptExtent extent, int line, { if (extent.StartLineNumber == line) { - if (column == 0) return true; + if (column == 0) + { + return true; + } + if (column >= extent.StartColumnNumber) { - if (extent.EndLineNumber != extent.StartLineNumber) return true; + if (extent.EndLineNumber != extent.StartLineNumber) + { + return true; + } + return (column < extent.EndColumnNumber); } diff --git a/src/System.Management.Automation/engine/parser/SemanticChecks.cs b/src/System.Management.Automation/engine/parser/SemanticChecks.cs index a7be00b2e13..b8853ab16a8 100644 --- a/src/System.Management.Automation/engine/parser/SemanticChecks.cs +++ b/src/System.Management.Automation/engine/parser/SemanticChecks.cs @@ -533,7 +533,10 @@ public override AstVisitAction VisitForEachStatement(ForEachStatementAst forEach public override AstVisitAction VisitTryStatement(TryStatementAst tryStatementAst) { - if (tryStatementAst.CatchClauses.Count <= 1) return AstVisitAction.Continue; + if (tryStatementAst.CatchClauses.Count <= 1) + { + return AstVisitAction.Continue; + } for (int i = 0; i < tryStatementAst.CatchClauses.Count - 1; ++i) { @@ -550,7 +553,10 @@ public override AstVisitAction VisitTryStatement(TryStatementAst tryStatementAst break; } - if (block2.IsCatchAll) continue; + if (block2.IsCatchAll) + { + continue; + } foreach (TypeConstraintAst typeLiteral1 in block1.CatchTypes) { @@ -1689,7 +1695,11 @@ private static void CheckGet(Parser parser, FunctionMemberAst functionMemberAst, /// True if it is a Test method with qualified return type and signature; otherwise, false. private static void CheckTest(FunctionMemberAst functionMemberAst, ref bool hasTest) { - if (hasTest) return; + if (hasTest) + { + return; + } + hasTest = (functionMemberAst.Name.Equals("Test", StringComparison.OrdinalIgnoreCase) && functionMemberAst.Parameters.Count == 0 && functionMemberAst.ReturnType != null && @@ -1702,7 +1712,11 @@ private static void CheckTest(FunctionMemberAst functionMemberAst, ref bool hasT /// True if it is a Set method with qualified return type and signature; otherwise, false. private static void CheckSet(FunctionMemberAst functionMemberAst, ref bool hasSet) { - if (hasSet) return; + if (hasSet) + { + return; + } + hasSet = (functionMemberAst.Name.Equals("Set", StringComparison.OrdinalIgnoreCase) && functionMemberAst.Parameters.Count == 0 && functionMemberAst.IsReturnTypeVoid()); diff --git a/src/System.Management.Automation/engine/parser/TypeResolver.cs b/src/System.Management.Automation/engine/parser/TypeResolver.cs index 1b5736df0ae..72258a4f459 100644 --- a/src/System.Management.Automation/engine/parser/TypeResolver.cs +++ b/src/System.Management.Automation/engine/parser/TypeResolver.cs @@ -80,7 +80,10 @@ private static Type LookForTypeInAssemblies(TypeName typeName, foreach (Assembly assembly in assemblies) { // Skip the assemblies that we already searched and found no matching type. - if (searchedAssemblies.Contains(assembly)) { continue; } + if (searchedAssemblies.Contains(assembly)) + { + continue; + } try { diff --git a/src/System.Management.Automation/engine/remoting/commands/ResumeJob.cs b/src/System.Management.Automation/engine/remoting/commands/ResumeJob.cs index 6545f74f7b7..0f9d302d6e1 100644 --- a/src/System.Management.Automation/engine/remoting/commands/ResumeJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/ResumeJob.cs @@ -231,15 +231,31 @@ protected override void EndProcessing() { _needToCheckForWaitingJobs = true; if (_pendingJobs.Count > 0) + { jobsPending = true; + } } if (Wait && jobsPending) + { _waitForJobs.WaitOne(); + } + + if (_warnInvalidState) + { + WriteWarning(RemotingErrorIdStrings.ResumeJobInvalidJobState); + } + + foreach (var e in _errorsToWrite) + { + WriteError(e); + } + + foreach (var j in _allJobsToResume) + { + WriteObject(j); + } - if (_warnInvalidState) WriteWarning(RemotingErrorIdStrings.ResumeJobInvalidJobState); - foreach (var e in _errorsToWrite) WriteError(e); - foreach (var j in _allJobsToResume) WriteObject(j); base.EndProcessing(); } @@ -267,7 +283,11 @@ public void Dispose() /// protected void Dispose(bool disposing) { - if (!disposing) return; + if (!disposing) + { + return; + } + foreach (var pair in _cleanUpActions) { pair.Key.ResumeJobCompleted -= pair.Value; diff --git a/src/System.Management.Automation/engine/remoting/commands/StopJob.cs b/src/System.Management.Automation/engine/remoting/commands/StopJob.cs index 7890bdc54f0..c298b495bb9 100644 --- a/src/System.Management.Automation/engine/remoting/commands/StopJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/StopJob.cs @@ -137,7 +137,11 @@ protected override void ProcessRecord() foreach (Job job in jobsToStop) { - if (this.Stopping) return; + if (this.Stopping) + { + return; + } + if (job.IsFinishedState(job.JobStateInfo.State)) { continue; @@ -280,7 +284,11 @@ public void Dispose() /// protected void Dispose(bool disposing) { - if (!disposing) return; + if (!disposing) + { + return; + } + foreach (var pair in _cleanUpActions) { pair.Key.StopJobCompleted -= pair.Value; diff --git a/src/System.Management.Automation/engine/remoting/commands/SuspendJob.cs b/src/System.Management.Automation/engine/remoting/commands/SuspendJob.cs index 983db3d76ba..e454247ae9a 100644 --- a/src/System.Management.Automation/engine/remoting/commands/SuspendJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/SuspendJob.cs @@ -325,15 +325,31 @@ protected override void EndProcessing() { _needToCheckForWaitingJobs = true; if (_pendingJobs.Count > 0) + { haveToWait = true; + } } if (haveToWait) + { _waitForJobs.WaitOne(); + } + + if (_warnInvalidState) + { + WriteWarning(RemotingErrorIdStrings.SuspendJobInvalidJobState); + } + + foreach (var e in _errorsToWrite) + { + WriteError(e); + } + + foreach (var j in _allJobsToSuspend) + { + WriteObject(j); + } - if (_warnInvalidState) WriteWarning(RemotingErrorIdStrings.SuspendJobInvalidJobState); - foreach (var e in _errorsToWrite) WriteError(e); - foreach (var j in _allJobsToSuspend) WriteObject(j); base.EndProcessing(); } @@ -361,7 +377,11 @@ public void Dispose() /// protected void Dispose(bool disposing) { - if (!disposing) return; + if (!disposing) + { + return; + } + foreach (var pair in _cleanUpActions) { pair.Key.SuspendJobCompleted -= pair.Value; diff --git a/src/System.Management.Automation/engine/remoting/common/psstreamobject.cs b/src/System.Management.Automation/engine/remoting/common/psstreamobject.cs index 6a39d8ed268..3091137730f 100644 --- a/src/System.Management.Automation/engine/remoting/common/psstreamobject.cs +++ b/src/System.Management.Automation/engine/remoting/common/psstreamobject.cs @@ -225,10 +225,17 @@ private static void GetIdentifierInfo(string message, out Guid jobInstanceId, ou jobInstanceId = Guid.Empty; computerName = string.Empty; - if (message == null) return; + if (message == null) + { + return; + } + string[] parts = message.Split(':', 3); - if (parts.Length != 3) return; + if (parts.Length != 3) + { + return; + } if (!Guid.TryParse(parts[0], out jobInstanceId)) jobInstanceId = Guid.Empty; @@ -456,7 +463,11 @@ internal static string CreateInformationalMessage(Guid instanceId, string messag internal static ErrorRecord AddSourceTagToError(ErrorRecord errorRecord, Guid sourceId) { - if (errorRecord == null) return null; + if (errorRecord == null) + { + return null; + } + errorRecord.ErrorDetails ??= new ErrorDetails(string.Empty); errorRecord.ErrorDetails.RecommendedAction = CreateInformationalMessage(sourceId, errorRecord.ErrorDetails.RecommendedAction); return errorRecord; diff --git a/src/System.Management.Automation/engine/remoting/server/ServerPowerShellDriver.cs b/src/System.Management.Automation/engine/remoting/server/ServerPowerShellDriver.cs index 871f4f21c4b..ddeb81aae17 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerPowerShellDriver.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerPowerShellDriver.cs @@ -427,7 +427,10 @@ private void HandlePowerShellInvocationStateChanged(object sender, if (LocalPowerShell.RunningExtraCommands) { // If completed successfully then allow extra commands to run. - if (state == PSInvocationState.Completed) { return; } + if (state == PSInvocationState.Completed) + { + return; + } // For failed or stopped state, extra commands cannot run and // we allow this command invocation to finish. diff --git a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs index 17793d78aa9..d62c58b4bca 100644 --- a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs +++ b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs @@ -187,7 +187,10 @@ private void ReallyCompile(bool optimize) TelemetryAPI.ReportScriptTelemetry((Ast)_ast, !optimize, sw.ElapsedMilliseconds); } #endif - if (etwEnabled) ParserEventSource.Log.CompileStop(); + if (etwEnabled) + { + ParserEventSource.Log.CompileStop(); + } } private void PerformSecurityChecks() @@ -2054,7 +2057,10 @@ public static string Match(string text) if (++longestPossiblePattern >= 4) { var result = CheckForMatches(runningHash, longestPossiblePattern); - if (result != null) return result; + if (result != null) + { + return result; + } } } diff --git a/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs b/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs index 6e67925ddb7..d37a2b4945d 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs @@ -1444,7 +1444,10 @@ private static void FindAndProcessHandler(Type[] types, int[] ranks, int handler = FindMatchingHandlerByType(exception.GetType(), types); // If no handler was found, return without changing the current result. - if (handler == -1) { return; } + if (handler == -1) + { + return; + } // New handler was found. // - If new-rank is less than current-rank -- meaning the new handler is more specific, diff --git a/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs b/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs index 2d62970da82..b759a281bde 100644 --- a/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs +++ b/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs @@ -60,7 +60,11 @@ public CultureInfo[] UICulture set { - if (value == null) return; + if (value == null) + { + return; + } + _language = new string[value.Length]; for (int index = 0; index < value.Length; index++) { @@ -443,7 +447,10 @@ internal void Process(IEnumerable moduleNames, IEnumerableModule objects given by the user. internal void Process(IEnumerable modules) { - if (modules == null || !modules.Any()) { return; } + if (modules == null || !modules.Any()) + { + return; + } var helpModules = new Dictionary, UpdatableHelpModuleInfo>(); diff --git a/src/System.Management.Automation/help/UpdatableHelpSystem.cs b/src/System.Management.Automation/help/UpdatableHelpSystem.cs index c909556adef..eb9796a2074 100644 --- a/src/System.Management.Automation/help/UpdatableHelpSystem.cs +++ b/src/System.Management.Automation/help/UpdatableHelpSystem.cs @@ -555,7 +555,10 @@ internal UpdatableHelpInfo CreateHelpInfo(string xml, string moduleName, Guid mo } catch (XmlException e) { - if (ignoreValidationException) { return null; } + if (ignoreValidationException) + { + return null; + } throw new UpdatableHelpSystemException(HelpInfoXmlValidationFailure, e.Message, ErrorCategory.InvalidData, null, e); diff --git a/src/System.Management.Automation/namespaces/LocationGlobber.cs b/src/System.Management.Automation/namespaces/LocationGlobber.cs index 8b51d6c9678..6cf082fc1f6 100644 --- a/src/System.Management.Automation/namespaces/LocationGlobber.cs +++ b/src/System.Management.Automation/namespaces/LocationGlobber.cs @@ -2065,7 +2065,10 @@ internal string GenerateRelativePath( driveRootRelativeWorkingPath = driveRootRelativeWorkingPath.Substring(drive.Root.Length); } - if (escapeCurrentLocation) { driveRootRelativeWorkingPath = WildcardPattern.Escape(driveRootRelativeWorkingPath); } + if (escapeCurrentLocation) + { + driveRootRelativeWorkingPath = WildcardPattern.Escape(driveRootRelativeWorkingPath); + } // These are static strings that we will parse and // interpret if they are leading the path. Otherwise diff --git a/src/System.Management.Automation/namespaces/TransactedRegistryKey.cs b/src/System.Management.Automation/namespaces/TransactedRegistryKey.cs index 19e05ce99a7..23316a31724 100644 --- a/src/System.Management.Automation/namespaces/TransactedRegistryKey.cs +++ b/src/System.Management.Automation/namespaces/TransactedRegistryKey.cs @@ -613,7 +613,10 @@ public void DeleteSubKeyTree(string subkey) } ret = Win32Native.RegDeleteKeyTransacted(_hkey, subkey, 0, 0, safeTransactionHandle, IntPtr.Zero); - if (ret != 0) Win32Error(ret, null); + if (ret != 0) + { + Win32Error(ret, null); + } } else { @@ -653,7 +656,10 @@ private void DeleteSubKeyTreeInternal(string subkey) } ret = Win32Native.RegDeleteKeyTransacted(_hkey, subkey, 0, 0, safeTransactionHandle, IntPtr.Zero); - if (ret != 0) Win32Error(ret, null); + if (ret != 0) + { + Win32Error(ret, null); + } } else { diff --git a/src/System.Management.Automation/security/SecurityManager.cs b/src/System.Management.Automation/security/SecurityManager.cs index e7874ec3524..5397ce2a048 100644 --- a/src/System.Management.Automation/security/SecurityManager.cs +++ b/src/System.Management.Automation/security/SecurityManager.cs @@ -160,7 +160,10 @@ private bool CheckPolicy(ExternalScriptInfo script, PSHost host, out Exception r } catch (System.ComponentModel.Win32Exception) { - if (saferAttempt > 4) { throw; } + if (saferAttempt > 4) + { + throw; + } saferAttempt++; System.Threading.Thread.Sleep(100); @@ -443,7 +446,12 @@ private static bool IsTrustedPublisher(Signature signature, string file) foreach (X509Certificate2 trustedCertificate in trustedPublishers.Certificates) { if (string.Equals(trustedCertificate.Thumbprint, thumbprint, StringComparison.OrdinalIgnoreCase)) - if (!IsUntrustedPublisher(signature, file)) return true; + { + if (!IsUntrustedPublisher(signature, file)) + { + return true; + } + } } return false; @@ -640,9 +648,16 @@ protected internal override bool ShouldRun(CommandInfo commandInfo, else { bool etwEnabled = ParserEventSource.Log.IsEnabled(); - if (etwEnabled) ParserEventSource.Log.CheckSecurityStart(si.Path); + if (etwEnabled) + { + ParserEventSource.Log.CheckSecurityStart(si.Path); + } + allowRun = CheckPolicy(si, host, out reason); - if (etwEnabled) ParserEventSource.Log.CheckSecurityStop(si.Path); + if (etwEnabled) + { + ParserEventSource.Log.CheckSecurityStop(si.Path); + } } break; diff --git a/src/System.Management.Automation/utils/ClrFacade.cs b/src/System.Management.Automation/utils/ClrFacade.cs index 8905b18087a..aa997734353 100644 --- a/src/System.Management.Automation/utils/ClrFacade.cs +++ b/src/System.Management.Automation/utils/ClrFacade.cs @@ -260,12 +260,18 @@ private static SecurityZone ReadFromZoneIdentifierDataStream(string filePath) else { Match match = Regex.Match(line, @"^ZoneId\s*=\s*(.*)", RegexOptions.IgnoreCase); - if (!match.Success) { continue; } + if (!match.Success) + { + continue; + } // Match found. Validate ZoneId value. string zoneIdRawValue = match.Groups[1].Value; match = Regex.Match(zoneIdRawValue, @"^[+-]?\d+", RegexOptions.IgnoreCase); - if (!match.Success) { return SecurityZone.NoZone; } + if (!match.Success) + { + return SecurityZone.NoZone; + } string zoneId = match.Groups[0].Value; SecurityZone result; diff --git a/src/System.Management.Automation/utils/PsUtils.cs b/src/System.Management.Automation/utils/PsUtils.cs index 0dde69ddf82..483491847fd 100644 --- a/src/System.Management.Automation/utils/PsUtils.cs +++ b/src/System.Management.Automation/utils/PsUtils.cs @@ -211,11 +211,20 @@ internal static Hashtable EvaluatePowerShellDataFile( bool allowEnvironmentVariables, bool skipPathValidation) { - if (!skipPathValidation && string.IsNullOrEmpty(parameterName)) { throw PSTraceSource.NewArgumentNullException(nameof(parameterName)); } + if (!skipPathValidation && string.IsNullOrEmpty(parameterName)) + { + throw PSTraceSource.NewArgumentNullException(nameof(parameterName)); + } - if (string.IsNullOrEmpty(psDataFilePath)) { throw PSTraceSource.NewArgumentNullException(nameof(psDataFilePath)); } + if (string.IsNullOrEmpty(psDataFilePath)) + { + throw PSTraceSource.NewArgumentNullException(nameof(psDataFilePath)); + } - if (context == null) { throw PSTraceSource.NewArgumentNullException(nameof(context)); } + if (context == null) + { + throw PSTraceSource.NewArgumentNullException(nameof(context)); + } string resolvedPath; if (skipPathValidation) diff --git a/src/System.Management.Automation/utils/RuntimeException.cs b/src/System.Management.Automation/utils/RuntimeException.cs index 3cb65ceb4c5..4ee2e1916b5 100644 --- a/src/System.Management.Automation/utils/RuntimeException.cs +++ b/src/System.Management.Automation/utils/RuntimeException.cs @@ -121,7 +121,11 @@ internal RuntimeException(ErrorCategory errorCategory, errorPosition = invocationInfo.ScriptPosition; } - if (invocationInfo == null) return; + if (invocationInfo == null) + { + return; + } + _errorRecord = new ErrorRecord( new ParentContainsErrorRecordException(this), _errorId, diff --git a/src/System.Management.Automation/utils/assert.cs b/src/System.Management.Automation/utils/assert.cs index cee958a5337..14692e9fd38 100644 --- a/src/System.Management.Automation/utils/assert.cs +++ b/src/System.Management.Automation/utils/assert.cs @@ -166,7 +166,10 @@ internal static void string whyThisShouldNeverHappen, string detailMessage) { // Early out avoids some slower code below (mostly the locking done in ThrowInsteadOfAssert). - if (condition) return; + if (condition) + { + return; + } #if ASSERTIONS_TRACE if (!condition) diff --git a/src/TypeCatalogGen/TypeCatalogGen.cs b/src/TypeCatalogGen/TypeCatalogGen.cs index 461757fcaf5..05a47814568 100644 --- a/src/TypeCatalogGen/TypeCatalogGen.cs +++ b/src/TypeCatalogGen/TypeCatalogGen.cs @@ -175,7 +175,11 @@ private static bool IsAttributeOfType(MetadataReader reader, CustomAttribute cus // Attribute is defined in the same module MethodDefinition methodDef = reader.GetMethodDefinition((MethodDefinitionHandle)customAttribute.Constructor); TypeDefinitionHandle declaringTypeDefHandle = methodDef.GetDeclaringType(); - if (declaringTypeDefHandle.IsNil) { /* Global method */ return false; } + if (declaringTypeDefHandle.IsNil) + { + // Global method + return false; + } TypeDefinition declaringTypeDef = reader.GetTypeDefinition(declaringTypeDefHandle); attributeFullName = GetTypeFullName(reader, declaringTypeDef); diff --git a/test/tools/NamedPipeConnection/src/code/NamedPipeConnection.cs b/test/tools/NamedPipeConnection/src/code/NamedPipeConnection.cs index 7a9bff15f79..4b83f5c6137 100644 --- a/test/tools/NamedPipeConnection/src/code/NamedPipeConnection.cs +++ b/test/tools/NamedPipeConnection/src/code/NamedPipeConnection.cs @@ -402,7 +402,10 @@ internal NamedPipeClientSessionTransportMgr( PSRemotingCryptoHelper cryptoHelper) : base(runspaceId, cryptoHelper) { - if (connectionInfo == null) { throw new PSArgumentException("connectionInfo"); } + if (connectionInfo == null) + { + throw new PSArgumentException("connectionInfo"); + } _connectionInfo = connectionInfo; } From 4e3f4ca62dc6ddf1bc64952332de210c6a4d629e Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Mon, 6 Mar 2023 05:59:56 +0100 Subject: [PATCH 409/779] Fix codefactor if part 3 (#19269) --- .../engine/COM/ComTypeInfo.cs | 5 +- .../engine/ComInterop/ComInvokeBinder.cs | 5 +- .../engine/PSVersionInfo.cs | 84 +++++++++++++++---- .../engine/PseudoParameters.cs | 10 ++- .../engine/SessionState.cs | 19 ++++- .../engine/SessionStateScope.cs | 22 ++++- .../engine/parser/ConstantValues.cs | 12 ++- .../remoting/client/ClientMethodExecutor.cs | 5 +- .../engine/remoting/commands/DebugJob.cs | 5 +- .../commands/EnterPSHostProcessCommand.cs | 5 +- .../engine/remoting/commands/GetJob.cs | 5 +- .../remoting/commands/PushRunspaceCommand.cs | 5 +- .../remoting/commands/ReceivePSSession.cs | 15 +++- .../engine/remoting/commands/RemoveJob.cs | 61 +++++++++++--- .../common/RemoteSessionHyperVSocket.cs | 10 ++- .../WireDataFormat/RemoteSessionCapability.cs | 10 ++- .../engine/remoting/common/psstreamobject.cs | 4 + .../fanin/InitialSessionStateProvider.cs | 11 ++- .../fanin/PSSessionConfigurationData.cs | 5 +- .../engine/serialization.cs | 5 +- 20 files changed, 245 insertions(+), 58 deletions(-) diff --git a/src/System.Management.Automation/engine/COM/ComTypeInfo.cs b/src/System.Management.Automation/engine/COM/ComTypeInfo.cs index 19ee494de07..eab6122a002 100644 --- a/src/System.Management.Automation/engine/COM/ComTypeInfo.cs +++ b/src/System.Management.Automation/engine/COM/ComTypeInfo.cs @@ -105,7 +105,10 @@ private void Initialize() for (int i = 0; i < typeattr.cFuncs; i++) { COM.FUNCDESC funcdesc = GetFuncDesc(_typeinfo, i); - if (funcdesc.memid == DISPID_NEWENUM) { NewEnumInvokeKind = funcdesc.invkind; } + if (funcdesc.memid == DISPID_NEWENUM) + { + NewEnumInvokeKind = funcdesc.invkind; + } if ((funcdesc.wFuncFlags & 0x1) == 0x1) { diff --git a/src/System.Management.Automation/engine/ComInterop/ComInvokeBinder.cs b/src/System.Management.Automation/engine/ComInterop/ComInvokeBinder.cs index f657f62e405..0e80a30ae1a 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComInvokeBinder.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComInvokeBinder.cs @@ -167,7 +167,10 @@ internal DynamicMetaObject Invoke() private static void AddNotNull(List list, ParameterExpression var) { - if (var != null) list.Add(var); + if (var != null) + { + list.Add(var); + } } private Expression CreateScope(Expression expression) diff --git a/src/System.Management.Automation/engine/PSVersionInfo.cs b/src/System.Management.Automation/engine/PSVersionInfo.cs index ec78842da18..f1b86e7354f 100644 --- a/src/System.Management.Automation/engine/PSVersionInfo.cs +++ b/src/System.Management.Automation/engine/PSVersionInfo.cs @@ -382,14 +382,20 @@ public SemanticVersion(int major, int minor, int patch, string preReleaseLabel, { if (!string.IsNullOrEmpty(preReleaseLabel)) { - if (!Regex.IsMatch(preReleaseLabel, LabelUnitRegEx)) throw new FormatException(nameof(preReleaseLabel)); + if (!Regex.IsMatch(preReleaseLabel, LabelUnitRegEx)) + { + throw new FormatException(nameof(preReleaseLabel)); + } PreReleaseLabel = preReleaseLabel; } if (!string.IsNullOrEmpty(buildLabel)) { - if (!Regex.IsMatch(buildLabel, LabelUnitRegEx)) throw new FormatException(nameof(buildLabel)); + if (!Regex.IsMatch(buildLabel, LabelUnitRegEx)) + { + throw new FormatException(nameof(buildLabel)); + } BuildLabel = buildLabel; } @@ -415,7 +421,10 @@ public SemanticVersion(int major, int minor, int patch, string label) if (!string.IsNullOrEmpty(label)) { var match = Regex.Match(label, LabelRegEx); - if (!match.Success) throw new FormatException(nameof(label)); + if (!match.Success) + { + throw new FormatException(nameof(label)); + } PreReleaseLabel = match.Groups["preLabel"].Value; BuildLabel = match.Groups["buildLabel"].Value; @@ -433,9 +442,20 @@ public SemanticVersion(int major, int minor, int patch, string label) /// public SemanticVersion(int major, int minor, int patch) { - if (major < 0) throw PSTraceSource.NewArgumentException(nameof(major)); - if (minor < 0) throw PSTraceSource.NewArgumentException(nameof(minor)); - if (patch < 0) throw PSTraceSource.NewArgumentException(nameof(patch)); + if (major < 0) + { + throw PSTraceSource.NewArgumentException(nameof(major)); + } + + if (minor < 0) + { + throw PSTraceSource.NewArgumentException(nameof(minor)); + } + + if (patch < 0) + { + throw PSTraceSource.NewArgumentException(nameof(patch)); + } Major = major; Minor = minor; @@ -477,8 +497,15 @@ public SemanticVersion(int major) : this(major, 0, 0) { } /// public SemanticVersion(Version version) { - if (version == null) throw PSTraceSource.NewArgumentNullException(nameof(version)); - if (version.Revision > 0) throw PSTraceSource.NewArgumentException(nameof(version)); + if (version == null) + { + throw PSTraceSource.NewArgumentNullException(nameof(version)); + } + + if (version.Revision > 0) + { + throw PSTraceSource.NewArgumentException(nameof(version)); + } Major = version.Major; Minor = version.Minor; @@ -565,8 +592,15 @@ public static implicit operator Version(SemanticVersion semver) /// public static SemanticVersion Parse(string version) { - if (version == null) throw PSTraceSource.NewArgumentNullException(nameof(version)); - if (version == string.Empty) throw new FormatException(nameof(version)); + if (version == null) + { + throw PSTraceSource.NewArgumentNullException(nameof(version)); + } + + if (version == string.Empty) + { + throw new FormatException(nameof(version)); + } var r = new VersionResult(); r.Init(true); @@ -886,9 +920,15 @@ private static int ComparePreLabel(string preLabel1, string preLabel2) // Numeric identifiers always have lower precedence than non-numeric identifiers. // A larger set of pre-release fields has a higher precedence than a smaller set, // if all of the preceding identifiers are equal. - if (string.IsNullOrEmpty(preLabel1)) { return string.IsNullOrEmpty(preLabel2) ? 0 : 1; } + if (string.IsNullOrEmpty(preLabel1)) + { + return string.IsNullOrEmpty(preLabel2) ? 0 : 1; + } - if (string.IsNullOrEmpty(preLabel2)) { return -1; } + if (string.IsNullOrEmpty(preLabel2)) + { + return -1; + } var units1 = preLabel1.Split('.'); var units2 = preLabel2.Split('.'); @@ -905,16 +945,28 @@ private static int ComparePreLabel(string preLabel1, string preLabel2) if (isNumber1 && isNumber2) { - if (number1 != number2) { return number1 < number2 ? -1 : 1; } + if (number1 != number2) + { + return number1 < number2 ? -1 : 1; + } } else { - if (isNumber1) { return -1; } + if (isNumber1) + { + return -1; + } - if (isNumber2) { return 1; } + if (isNumber2) + { + return 1; + } int result = string.CompareOrdinal(ac, bc); - if (result != 0) { return result; } + if (result != 0) + { + return result; + } } } diff --git a/src/System.Management.Automation/engine/PseudoParameters.cs b/src/System.Management.Automation/engine/PseudoParameters.cs index 97b1d60e8ad..261e8ee6c51 100644 --- a/src/System.Management.Automation/engine/PseudoParameters.cs +++ b/src/System.Management.Automation/engine/PseudoParameters.cs @@ -174,14 +174,20 @@ internal bool IsDisabled() { if (!hasSeenExpAttribute && attr is ExperimentalAttribute expAttribute) { - if (expAttribute.ToHide) { return true; } + if (expAttribute.ToHide) + { + return true; + } hasSeenExpAttribute = true; } else if (attr is ParameterAttribute paramAttribute) { hasParameterAttribute = true; - if (paramAttribute.ToHide) { continue; } + if (paramAttribute.ToHide) + { + continue; + } hasEnabledParamAttribute = true; } diff --git a/src/System.Management.Automation/engine/SessionState.cs b/src/System.Management.Automation/engine/SessionState.cs index e0bdbd23ee0..e65f65ff385 100644 --- a/src/System.Management.Automation/engine/SessionState.cs +++ b/src/System.Management.Automation/engine/SessionState.cs @@ -391,14 +391,27 @@ internal SessionStateEntryVisibility CheckApplicationVisibility(string applicati private static SessionStateEntryVisibility checkPathVisibility(List list, string path) { - if (list == null || list.Count == 0) return SessionStateEntryVisibility.Private; - if (string.IsNullOrEmpty(path)) return SessionStateEntryVisibility.Private; + if (list == null || list.Count == 0) + { + return SessionStateEntryVisibility.Private; + } + + if (string.IsNullOrEmpty(path)) + { + return SessionStateEntryVisibility.Private; + } + + if (list.Contains("*")) + { + return SessionStateEntryVisibility.Public; + } - if (list.Contains("*")) return SessionStateEntryVisibility.Public; foreach (string p in list) { if (string.Equals(p, path, StringComparison.OrdinalIgnoreCase)) + { return SessionStateEntryVisibility.Public; + } if (WildcardPattern.ContainsWildcardCharacters(p)) { diff --git a/src/System.Management.Automation/engine/SessionStateScope.cs b/src/System.Management.Automation/engine/SessionStateScope.cs index 080aebb2b0a..d947643c7d2 100644 --- a/src/System.Management.Automation/engine/SessionStateScope.cs +++ b/src/System.Management.Automation/engine/SessionStateScope.cs @@ -421,7 +421,10 @@ internal PSVariable SetVariable(string name, object value, bool asValue, bool fo bool varExists = TryGetVariable(name, origin, true, out variable); // Initialize the private variable dictionary if it's not yet - if (_variables == null) { GetPrivateVariables(); } + if (_variables == null) + { + GetPrivateVariables(); + } if (!asValue && variableToSet != null) { @@ -1639,9 +1642,14 @@ internal void AddType(string name, Type type) internal Type LookupType(string name) { - if (TypeTable == null) return null; + if (TypeTable == null) + { + return null; + } + Type result; TypeTable.TryGetValue(name, out result); + return result; } @@ -1682,12 +1690,18 @@ private static FunctionInfo CreateFunction(string name, ScriptBlock function, Fu // Then use the creation constructors - workflows don't get here because the workflow info // is created during compilation. - else if (function.IsFilter) { newValue = new FilterInfo(name, function, options, context, helpFile); } + else if (function.IsFilter) + { + newValue = new FilterInfo(name, function, options, context, helpFile); + } else if (function.IsConfiguration) { newValue = new ConfigurationInfo(name, function, options, context, helpFile, function.IsMetaConfiguration()); } - else newValue = new FunctionInfo(name, function, options, context, helpFile); + else + { + newValue = new FunctionInfo(name, function, options, context, helpFile); + } return newValue; } diff --git a/src/System.Management.Automation/engine/parser/ConstantValues.cs b/src/System.Management.Automation/engine/parser/ConstantValues.cs index a8ada5f96d5..d580148ddd2 100644 --- a/src/System.Management.Automation/engine/parser/ConstantValues.cs +++ b/src/System.Management.Automation/engine/parser/ConstantValues.cs @@ -148,8 +148,16 @@ public static bool IsConstant(Ast ast, out object constantValue, bool forAttribu public object VisitStatementBlock(StatementBlockAst statementBlockAst) { - if (statementBlockAst.Traps != null) return false; - if (statementBlockAst.Statements.Count > 1) return false; + if (statementBlockAst.Traps != null) + { + return false; + } + + if (statementBlockAst.Statements.Count > 1) + { + return false; + } + var pipeline = statementBlockAst.Statements.FirstOrDefault(); return pipeline != null && (bool)pipeline.Accept(this); } diff --git a/src/System.Management.Automation/engine/remoting/client/ClientMethodExecutor.cs b/src/System.Management.Automation/engine/remoting/client/ClientMethodExecutor.cs index e779b132f4d..73c432158f3 100644 --- a/src/System.Management.Automation/engine/remoting/client/ClientMethodExecutor.cs +++ b/src/System.Management.Automation/engine/remoting/client/ClientMethodExecutor.cs @@ -133,7 +133,10 @@ internal static void Dispatch( /// private static bool IsRunspacePushed(PSHost host) { - if (!(host is IHostSupportsInteractiveSession host2)) { return false; } + if (!(host is IHostSupportsInteractiveSession host2)) + { + return false; + } // IsRunspacePushed can throw (not implemented exception) try diff --git a/src/System.Management.Automation/engine/remoting/commands/DebugJob.cs b/src/System.Management.Automation/engine/remoting/commands/DebugJob.cs index 7494f902fb7..ece0ce45dbf 100644 --- a/src/System.Management.Automation/engine/remoting/commands/DebugJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/DebugJob.cs @@ -226,7 +226,10 @@ private bool CheckForDebuggableJob() foreach (var cJob in _job.ChildJobs) { debuggableJobFound = GetJobDebuggable(cJob); - if (debuggableJobFound) { break; } + if (debuggableJobFound) + { + break; + } } } diff --git a/src/System.Management.Automation/engine/remoting/commands/EnterPSHostProcessCommand.cs b/src/System.Management.Automation/engine/remoting/commands/EnterPSHostProcessCommand.cs index b6906bc7008..5acd33b2922 100644 --- a/src/System.Management.Automation/engine/remoting/commands/EnterPSHostProcessCommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/EnterPSHostProcessCommand.cs @@ -672,7 +672,10 @@ internal static IReadOnlyCollection GetAppDomainNamesFromProc } } - if (!found) { continue; } + if (!found) + { + continue; + } } } else diff --git a/src/System.Management.Automation/engine/remoting/commands/GetJob.cs b/src/System.Management.Automation/engine/remoting/commands/GetJob.cs index a48cb4dcc1a..fe5946f44f0 100644 --- a/src/System.Management.Automation/engine/remoting/commands/GetJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/GetJob.cs @@ -256,7 +256,10 @@ private List FindChildJobs(List jobList) { foreach (Job childJob in job.ChildJobs) { - if (childJob.JobStateInfo.State != ChildJobState) continue; + if (childJob.JobStateInfo.State != ChildJobState) + { + continue; + } matches.Add(childJob); } diff --git a/src/System.Management.Automation/engine/remoting/commands/PushRunspaceCommand.cs b/src/System.Management.Automation/engine/remoting/commands/PushRunspaceCommand.cs index 4268c21dee5..fad0f604c5e 100644 --- a/src/System.Management.Automation/engine/remoting/commands/PushRunspaceCommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/PushRunspaceCommand.cs @@ -332,7 +332,10 @@ protected override void ProcessRecord() } // If runspace is null then the error record has already been written and we can exit. - if (remoteRunspace == null) { return; } + if (remoteRunspace == null) + { + return; + } // If the runspace is in a disconnected state try to connect. bool runspaceConnected = false; diff --git a/src/System.Management.Automation/engine/remoting/commands/ReceivePSSession.cs b/src/System.Management.Automation/engine/remoting/commands/ReceivePSSession.cs index 798cf82d9fa..144a9c26b35 100644 --- a/src/System.Management.Automation/engine/remoting/commands/ReceivePSSession.cs +++ b/src/System.Management.Automation/engine/remoting/commands/ReceivePSSession.cs @@ -851,7 +851,10 @@ private void ConnectSessionToHost(PSSession session, PSRemotingJob job = null) { Job childJob = job.ChildJobs[0]; job.ConnectJobs(); - if (CheckForDebugMode(session, true)) { return; } + if (CheckForDebugMode(session, true)) + { + return; + } do { @@ -921,7 +924,10 @@ private void ConnectSessionToHost(PSSession session, PSRemotingJob job = null) pipelineConnectedEvent = null; - if (CheckForDebugMode(session, true)) { return; } + if (CheckForDebugMode(session, true)) + { + return; + } // Wait for remote command to complete, while writing any available data. while (!_remotePipeline.Output.EndOfPipeline) @@ -1100,7 +1106,10 @@ private void ConnectSessionToJob(PSSession session, PSRemotingJob job = null) } } - if (CheckForDebugMode(session, true)) { return; } + if (CheckForDebugMode(session, true)) + { + return; + } // Write the job object to output. WriteObject(job); diff --git a/src/System.Management.Automation/engine/remoting/commands/RemoveJob.cs b/src/System.Management.Automation/engine/remoting/commands/RemoveJob.cs index f8c0a71a0df..af98749c4e5 100644 --- a/src/System.Management.Automation/engine/remoting/commands/RemoveJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/RemoveJob.cs @@ -61,12 +61,17 @@ internal List FindJobsMatchingByName( List matches = new List(); Hashtable duplicateDetector = new Hashtable(); - if (_names == null) return matches; + if (_names == null) + { + return matches; + } foreach (string name in _names) { if (string.IsNullOrEmpty(name)) + { continue; + } // search all jobs in repository. bool jobFound = false; @@ -94,7 +99,10 @@ internal List FindJobsMatchingByName( jobFound = jobFound || job2Found; // if a match is not found, write an error) - if (jobFound || !writeErrorOnNoMatch || WildcardPattern.ContainsWildcardCharacters(name)) continue; + if (jobFound || !writeErrorOnNoMatch || WildcardPattern.ContainsWildcardCharacters(name)) + { + continue; + } Exception ex = PSTraceSource.NewArgumentException(NameParameter, RemotingErrorIdStrings.JobWithSpecifiedNameNotFound, name); WriteError(new ErrorRecord(ex, "JobWithSpecifiedNameNotFound", ErrorCategory.ObjectNotFound, name)); @@ -191,7 +199,10 @@ internal List FindJobsMatchingByInstanceId(bool recurse, bool writeobject, Hashtable duplicateDetector = new Hashtable(); - if (_instanceIds == null) return matches; + if (_instanceIds == null) + { + return matches; + } foreach (Guid id in _instanceIds) { @@ -217,7 +228,10 @@ internal List FindJobsMatchingByInstanceId(bool recurse, bool writeobject, jobFound = jobFound || job2Found; - if (jobFound || !writeErrorOnNoMatch) continue; + if (jobFound || !writeErrorOnNoMatch) + { + continue; + } Exception ex = PSTraceSource.NewArgumentException(InstanceIdParameter, RemotingErrorIdStrings.JobWithSpecifiedInstanceIdNotFound, @@ -306,7 +320,10 @@ internal List FindJobsMatchingBySessionId(bool recurse, bool writeobject, b { List matches = new List(); - if (_sessionIds == null) return matches; + if (_sessionIds == null) + { + return matches; + } Hashtable duplicateDetector = new Hashtable(); @@ -331,7 +348,10 @@ internal List FindJobsMatchingBySessionId(bool recurse, bool writeobject, b jobFound = jobFound || job2Found; - if (jobFound || !writeErrorOnNoMatch) continue; + if (jobFound || !writeErrorOnNoMatch) + { + continue; + } Exception ex = PSTraceSource.NewArgumentException(SessionIdParameter, RemotingErrorIdStrings.JobWithSpecifiedSessionIdNotFound, id); WriteError(new ErrorRecord(ex, "JobWithSpecifiedSessionNotFound", ErrorCategory.ObjectNotFound, id)); @@ -408,7 +428,10 @@ internal List FindJobsMatchingByCommand( { List matches = new List(); - if (_commands == null) return matches; + if (_commands == null) + { + return matches; + } List jobs = new List(); @@ -476,7 +499,10 @@ internal List FindJobsMatchingByState( foreach (Job job in jobs) { - if (job.JobStateInfo.State != _jobstate) continue; + if (job.JobStateInfo.State != _jobstate) + { + continue; + } if (writeobject) { @@ -558,7 +584,10 @@ private static bool FindJobsMatchingByFilterHelper(List matches, List internal List CopyJobsToList(Job[] jobs, bool writeobject, bool checkIfJobCanBeRemoved) { List matches = new List(); - if (jobs == null) return matches; + if (jobs == null) + { + return matches; + } foreach (Job job in jobs) { @@ -890,10 +919,12 @@ protected override void ProcessRecord() // Now actually remove the jobs foreach (Job job in listOfJobsToRemove) { - string message = GetMessage(RemotingErrorIdStrings.StopPSJobWhatIfTarget, - job.Command, job.Id); + string message = GetMessage(RemotingErrorIdStrings.StopPSJobWhatIfTarget, job.Command, job.Id); - if (!ShouldProcess(message, VerbsCommon.Remove)) continue; + if (!ShouldProcess(message, VerbsCommon.Remove)) + { + continue; + } Job2 job2 = job as Job2; if (!job.IsFinishedState(job.JobStateInfo.State)) @@ -1037,7 +1068,11 @@ public void Dispose() /// protected void Dispose(bool disposing) { - if (!disposing) return; + if (!disposing) + { + return; + } + foreach (var pair in _cleanUpActions) { pair.Key.StopJobCompleted -= pair.Value; diff --git a/src/System.Management.Automation/engine/remoting/common/RemoteSessionHyperVSocket.cs b/src/System.Management.Automation/engine/remoting/common/RemoteSessionHyperVSocket.cs index 126004da829..7fae8118310 100644 --- a/src/System.Management.Automation/engine/remoting/common/RemoteSessionHyperVSocket.cs +++ b/src/System.Management.Automation/engine/remoting/common/RemoteSessionHyperVSocket.cs @@ -295,7 +295,10 @@ public void Dispose() { lock (_syncObject) { - if (IsDisposed) { return; } + if (IsDisposed) + { + return; + } IsDisposed = true; } @@ -445,7 +448,10 @@ public void Dispose() { lock (_syncObject) { - if (IsDisposed) { return; } + if (IsDisposed) + { + return; + } IsDisposed = true; } diff --git a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteSessionCapability.cs b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteSessionCapability.cs index f0ccb496ebe..add424b8703 100644 --- a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteSessionCapability.cs +++ b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteSessionCapability.cs @@ -387,12 +387,18 @@ private static void CheckHostChain(PSHost host, ref bool isHostNull, ref bool is isHostNull = false; // Verify that the UI is not null. - if (host.UI == null) { return; } + if (host.UI == null) + { + return; + } isHostUINull = false; // Verify that the raw UI is not null. - if (host.UI.RawUI == null) { return; } + if (host.UI.RawUI == null) + { + return; + } isHostRawUINull = false; } diff --git a/src/System.Management.Automation/engine/remoting/common/psstreamobject.cs b/src/System.Management.Automation/engine/remoting/common/psstreamobject.cs index 3091137730f..f97b2b21d1f 100644 --- a/src/System.Management.Automation/engine/remoting/common/psstreamobject.cs +++ b/src/System.Management.Automation/engine/remoting/common/psstreamobject.cs @@ -238,7 +238,9 @@ private static void GetIdentifierInfo(string message, out Guid jobInstanceId, ou } if (!Guid.TryParse(parts[0], out jobInstanceId)) + { jobInstanceId = Guid.Empty; + } computerName = parts[1]; } @@ -458,6 +460,7 @@ internal static string CreateInformationalMessage(Guid instanceId, string messag var newMessage = new StringBuilder(instanceId.ToString()); newMessage.Append(':'); newMessage.Append(message); + return newMessage.ToString(); } @@ -470,6 +473,7 @@ internal static ErrorRecord AddSourceTagToError(ErrorRecord errorRecord, Guid so errorRecord.ErrorDetails ??= new ErrorDetails(string.Empty); errorRecord.ErrorDetails.RecommendedAction = CreateInformationalMessage(sourceId, errorRecord.ErrorDetails.RecommendedAction); + return errorRecord; } } diff --git a/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs b/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs index 600614ca764..9cea542ab95 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs @@ -812,8 +812,12 @@ internal sealed class DefaultRemotePowerShellConfiguration : PSSessionConfigurat public override InitialSessionState GetInitialSessionState(PSSenderInfo senderInfo) { InitialSessionState result = InitialSessionState.CreateDefault2(); + // TODO: Remove this after RDS moved to $using - if (senderInfo.ConnectionString != null && senderInfo.ConnectionString.Contains("MSP=7a83d074-bb86-4e52-aa3e-6cc73cc066c8")) { PSSessionConfigurationData.IsServerManager = true; } + if (senderInfo.ConnectionString != null && senderInfo.ConnectionString.Contains("MSP=7a83d074-bb86-4e52-aa3e-6cc73cc066c8")) + { + PSSessionConfigurationData.IsServerManager = true; + } return result; } @@ -852,7 +856,10 @@ public override InitialSessionState GetInitialSessionState(PSSessionConfiguratio } // TODO: Remove this after RDS moved to $using - if (senderInfo.ConnectionString != null && senderInfo.ConnectionString.Contains("MSP=7a83d074-bb86-4e52-aa3e-6cc73cc066c8")) { PSSessionConfigurationData.IsServerManager = true; } + if (senderInfo.ConnectionString != null && senderInfo.ConnectionString.Contains("MSP=7a83d074-bb86-4e52-aa3e-6cc73cc066c8")) + { + PSSessionConfigurationData.IsServerManager = true; + } return sessionState; } diff --git a/src/System.Management.Automation/engine/remoting/fanin/PSSessionConfigurationData.cs b/src/System.Management.Automation/engine/remoting/fanin/PSSessionConfigurationData.cs index fbd2653c8a7..1d5f6916981 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/PSSessionConfigurationData.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/PSSessionConfigurationData.cs @@ -80,7 +80,10 @@ internal static PSSessionConfigurationData Create(string configurationData) { PSSessionConfigurationData configuration = new PSSessionConfigurationData(); - if (string.IsNullOrEmpty(configurationData)) return configuration; + if (string.IsNullOrEmpty(configurationData)) + { + return configuration; + } configurationData = Unescape(configurationData); diff --git a/src/System.Management.Automation/engine/serialization.cs b/src/System.Management.Automation/engine/serialization.cs index 0a78c4ee26c..e885db41b65 100644 --- a/src/System.Management.Automation/engine/serialization.cs +++ b/src/System.Management.Automation/engine/serialization.cs @@ -2159,7 +2159,10 @@ int depth } Dbg.Assert(key != null, "Dictionary keys should never be null"); - if (key == null) break; + if (key == null) + { + break; + } WriteStartElement(SerializationStrings.DictionaryEntryTag); WriteOneObject(key, null, SerializationStrings.DictionaryKey, depth); From efc7385c50fb22d5af58de6b047f49e5acf175d7 Mon Sep 17 00:00:00 2001 From: Jordan Borean Date: Tue, 7 Mar 2023 04:31:16 +1000 Subject: [PATCH 410/779] Fix Start-Process -Wait with -Credential (#19096) Allows a non-administrator user to be able to -Wait on a Start-Process call with a custom credential specified. --- .../commands/management/Process.cs | 245 +++++++++--------- .../commands/management/Service.cs | 16 -- .../Windows/AssignProcessToJobObject.cs | 16 ++ .../engine/Interop/Windows/CloseHandle.cs | 16 ++ 4 files changed, 151 insertions(+), 142 deletions(-) create mode 100644 src/System.Management.Automation/engine/Interop/Windows/AssignProcessToJobObject.cs create mode 100644 src/System.Management.Automation/engine/Interop/Windows/CloseHandle.cs diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs index 82eccff3652..b731ce905cc 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs @@ -2029,7 +2029,55 @@ protected override void BeginProcessing() return; } - Process process = Start(startInfo); + Process process = null; + +#if !UNIX + ProcessCollection jobObject = null; + bool? jobAssigned = null; +#endif + if (startInfo.UseShellExecute) + { + process = StartWithShellExecute(startInfo); + } + else + { +#if UNIX + process = new Process() { StartInfo = startInfo }; + SetupInputOutputRedirection(process); + process.Start(); + if (process.StartInfo.RedirectStandardOutput) + { + process.BeginOutputReadLine(); + } + + if (process.StartInfo.RedirectStandardError) + { + process.BeginErrorReadLine(); + } + + if (process.StartInfo.RedirectStandardInput) + { + WriteToStandardInput(process); + } +#else + using ProcessInformation processInfo = StartWithCreateProcess(startInfo); + process = Process.GetProcessById(processInfo.ProcessId); + + // Starting a process as another user might make it impossible + // to get the process handle from the S.D.Process object. Use + // the ALL_ACCESS token from CreateProcess here to setup the + // job object assignment early if -Wait was specified. + // https://github.com/PowerShell/PowerShell/issues/17033 + if (Wait) + { + jobObject = new(); + jobAssigned = jobObject.AssignProcessToJobObject(processInfo.Process); + } + + // Resume the process now that is has been set up. + processInfo.Resume(); +#endif + } if (PassThru.IsPresent) { @@ -2054,29 +2102,21 @@ protected override void BeginProcessing() #if UNIX process.WaitForExit(); #else - if (_credential is not null) + _waithandle = new ManualResetEvent(false); + + // Create and start the job object. This may have + // already been done in StartWithCreateProcess. + jobObject ??= new(); + if (jobAssigned == true || (jobAssigned is null && jobObject.AssignProcessToJobObject(process.SafeHandle))) { - // If we are running as a different user, we cannot use a job object, so just wait on the process - process.WaitForExit(); + // Wait for the job object to finish + jobObject.WaitOne(_waithandle); } else { - _waithandle = new ManualResetEvent(false); - - // Create and start the job object - ProcessCollection jobObject = new(); - if (jobObject.AssignProcessToJobObject(process)) - { - // Wait for the job object to finish - jobObject.WaitOne(_waithandle); - } - else if (!process.HasExited) - { - // WinBlue: 27537 Start-Process -Wait doesn't work in a remote session on Windows 7 or lower. - process.Exited += myProcess_Exited; - process.EnableRaisingEvents = true; - process.WaitForExit(); - } + // WinBlue: 27537 Start-Process -Wait doesn't work in a remote session on Windows 7 or lower. + // A Remote session is in it's own job and nested job support was only added in Windows 8/Server 2012. + process.WaitForExit(); } #endif } @@ -2120,11 +2160,6 @@ private void Dispose(bool isDisposing) #region Private Methods - /// - /// When Process exits the wait handle is set. - /// - private void myProcess_Exited(object sender, System.EventArgs e) => _waithandle?.Set(); - private string ResolveFilePath(string path) { string filepath = PathUtils.ResolveFilePath(path, this); @@ -2152,41 +2187,6 @@ private static void LoadEnvironmentVariable(ProcessStartInfo startinfo, IDiction } } - private Process Start(ProcessStartInfo startInfo) - { - Process process = null; - if (startInfo.UseShellExecute) - { - process = StartWithShellExecute(startInfo); - } - else - { -#if UNIX - process = new Process() { StartInfo = startInfo }; - SetupInputOutputRedirection(process); - process.Start(); - if (process.StartInfo.RedirectStandardOutput) - { - process.BeginOutputReadLine(); - } - - if (process.StartInfo.RedirectStandardError) - { - process.BeginErrorReadLine(); - } - - if (process.StartInfo.RedirectStandardInput) - { - WriteToStandardInput(process); - } -#else - process = StartWithCreateProcess(startInfo); -#endif - } - - return process; - } - #if UNIX private StreamWriter _outputWriter; private StreamWriter _errorWriter; @@ -2436,10 +2436,10 @@ private void SetStartupInfo(ProcessStartInfo startinfo, ref ProcessNativeMethods /// /// This method will be used on all windows platforms, both full desktop and headless SKUs. /// - private Process StartWithCreateProcess(ProcessStartInfo startinfo) + private ProcessInformation StartWithCreateProcess(ProcessStartInfo startinfo) { ProcessNativeMethods.STARTUPINFO lpStartupInfo = new(); - SafeNativeMethods.PROCESS_INFORMATION lpProcessInformation = new(); + ProcessNativeMethods.PROCESS_INFORMATION lpProcessInformation = new(); int error = 0; GCHandle pinnedEnvironmentBlock = new(); IntPtr AddressOfEnvironmentBlock = IntPtr.Zero; @@ -2486,7 +2486,7 @@ private Process StartWithCreateProcess(ProcessStartInfo startinfo) try { password = (startinfo.Password == null) ? Marshal.StringToCoTaskMemUni(string.Empty) : Marshal.SecureStringToCoTaskMemUnicode(startinfo.Password); - flag = ProcessNativeMethods.CreateProcessWithLogonW(startinfo.UserName, startinfo.Domain, password, logonFlags, null, cmdLine, creationFlags, AddressOfEnvironmentBlock, startinfo.WorkingDirectory, lpStartupInfo, lpProcessInformation); + flag = ProcessNativeMethods.CreateProcessWithLogonW(startinfo.UserName, startinfo.Domain, password, logonFlags, null, cmdLine, creationFlags, AddressOfEnvironmentBlock, startinfo.WorkingDirectory, lpStartupInfo, ref lpProcessInformation); if (!flag) { error = Marshal.GetLastWin32Error(); @@ -2542,7 +2542,7 @@ private Process StartWithCreateProcess(ProcessStartInfo startinfo) ProcessNativeMethods.SECURITY_ATTRIBUTES lpProcessAttributes = new(); ProcessNativeMethods.SECURITY_ATTRIBUTES lpThreadAttributes = new(); - flag = ProcessNativeMethods.CreateProcess(null, cmdLine, lpProcessAttributes, lpThreadAttributes, true, creationFlags, AddressOfEnvironmentBlock, startinfo.WorkingDirectory, lpStartupInfo, lpProcessInformation); + flag = ProcessNativeMethods.CreateProcess(null, cmdLine, lpProcessAttributes, lpThreadAttributes, true, creationFlags, AddressOfEnvironmentBlock, startinfo.WorkingDirectory, lpStartupInfo, ref lpProcessInformation); if (!flag) { error = Marshal.GetLastWin32Error(); @@ -2555,11 +2555,7 @@ private Process StartWithCreateProcess(ProcessStartInfo startinfo) Label_03AE: - // At this point, we should have a suspended process. Get the .Net Process object, resume the process, and return. - Process result = Process.GetProcessById(lpProcessInformation.dwProcessId); - ProcessNativeMethods.ResumeThread(lpProcessInformation.hThread); - - return result; + return new ProcessInformation(lpProcessInformation); } finally { @@ -2573,7 +2569,6 @@ private Process StartWithCreateProcess(ProcessStartInfo startinfo) } lpStartupInfo.Dispose(); - lpProcessInformation.Dispose(); } } #endif @@ -2626,10 +2621,12 @@ internal ProcessCollection() /// Start API assigns the process to the JobObject and starts monitoring /// the child processes hosted by the process created by Start-Process cmdlet. /// - internal bool AssignProcessToJobObject(Process process) + internal bool AssignProcessToJobObject(SafeProcessHandle process) { // Add the process to the job object - bool result = NativeMethods.AssignProcessToJobObject(_jobObjectHandle, process.Handle); + bool result = Interop.Windows.AssignProcessToJobObject( + _jobObjectHandle.DangerousGetHandle(), + process.DangerousGetHandle()); return result; } @@ -2674,6 +2671,44 @@ internal void WaitOne(ManualResetEvent waitHandleToUse) } } + /// + /// ProcessInformation is a helper class that wraps the native PROCESS_INFORMATION structure + /// returned by CreateProcess or CreateProcessWithLogon. It ensures the process and thread + /// HANDLEs are disposed once it's not needed. + /// + internal sealed class ProcessInformation : IDisposable + { + public SafeProcessHandle Process { get; } + + public SafeProcessHandle Thread { get; } + + public Int32 ProcessId { get; } + + public Int32 ThreadId { get; } + + internal ProcessInformation(ProcessNativeMethods.PROCESS_INFORMATION info) + { + Process = new(info.hProcess, true); + Thread = new(info.hThread, true); + ProcessId = info.dwProcessId; + ThreadId = info.dwThreadId; + } + + public void Resume() + { + ProcessNativeMethods.ResumeThread(Thread.DangerousGetHandle()); + } + + public void Dispose() + { + Process.Dispose(); + Thread.Dispose(); + GC.SuppressFinalize(this); + } + + ~ProcessInformation() => Dispose(); + } + /// /// JOBOBJECT_BASIC_PROCESS_ID_LIST Contains the process identifier list for a job object. /// If the job is nested, the process identifier list consists of all @@ -2719,7 +2754,7 @@ internal static extern bool CreateProcessWithLogonW(string userName, IntPtr environmentBlock, [MarshalAs(UnmanagedType.LPWStr)] string lpCurrentDirectory, STARTUPINFO lpStartupInfo, - SafeNativeMethods.PROCESS_INFORMATION lpProcessInformation); + ref PROCESS_INFORMATION lpProcessInformation); [DllImport(PinvokeDllNames.CreateProcessDllName, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] @@ -2732,7 +2767,7 @@ public static extern bool CreateProcess([MarshalAs(UnmanagedType.LPWStr)] string IntPtr lpEnvironment, [MarshalAs(UnmanagedType.LPWStr)] string lpCurrentDirectory, STARTUPINFO lpStartupInfo, - SafeNativeMethods.PROCESS_INFORMATION lpProcessInformation); + ref PROCESS_INFORMATION lpProcessInformation); [DllImport(PinvokeDllNames.ResumeThreadDllName, CharSet = CharSet.Unicode, SetLastError = true)] public static extern uint ResumeThread(IntPtr threadHandle); @@ -2752,6 +2787,15 @@ internal enum LogonFlags LOGON_WITH_PROFILE = 1 } + [StructLayout(LayoutKind.Sequential)] + internal struct PROCESS_INFORMATION + { + public IntPtr hProcess; + public IntPtr hThread; + public int dwProcessId; + public int dwThreadId; + } + [StructLayout(LayoutKind.Sequential)] internal class SECURITY_ATTRIBUTES { @@ -2855,57 +2899,6 @@ public void Dispose() } } - internal static class SafeNativeMethods - { - [DllImport(PinvokeDllNames.CloseHandleDllName, SetLastError = true, ExactSpelling = true)] - public static extern bool CloseHandle(IntPtr handle); - - [StructLayout(LayoutKind.Sequential)] - internal class PROCESS_INFORMATION - { - public IntPtr hProcess; - public IntPtr hThread; - public int dwProcessId; - public int dwThreadId; - - public PROCESS_INFORMATION() - { - this.hProcess = IntPtr.Zero; - this.hThread = IntPtr.Zero; - } - - /// - /// Dispose. - /// - public void Dispose() - { - Dispose(true); - } - - /// - /// Dispose. - /// - /// - private void Dispose(bool disposing) - { - if (disposing) - { - if (this.hProcess != IntPtr.Zero) - { - CloseHandle(this.hProcess); - this.hProcess = IntPtr.Zero; - } - - if (this.hThread != IntPtr.Zero) - { - CloseHandle(this.hThread); - this.hThread = IntPtr.Zero; - } - } - } - } - } - [SuppressUnmanagedCodeSecurity] internal sealed class SafeJobHandle : SafeHandleZeroOrMinusOneIsInvalid { @@ -2917,7 +2910,7 @@ internal SafeJobHandle(IntPtr jobHandle) protected override bool ReleaseHandle() { - return SafeNativeMethods.CloseHandle(base.handle); + return Interop.Windows.CloseHandle(base.handle); } } #endif diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs index f05881751e9..0253cee5e39 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs @@ -2776,22 +2776,6 @@ byte[] lpSecurityDescriptor [DllImport("Kernel32.dll", CharSet = CharSet.Unicode)] internal static extern IntPtr CreateJobObject(IntPtr lpJobAttributes, string lpName); - /// - /// AssignProcessToJobObject API is used to assign a process to an existing job object. - /// - /// - /// A handle to the job object to which the process will be associated. - /// - /// - /// A handle to the process to associate with the job object. - /// - /// If the function succeeds, the return value is nonzero. - /// If the function fails, the return value is zero. - /// - [DllImport("Kernel32.dll", CharSet = CharSet.Unicode)] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool AssignProcessToJobObject(SafeHandle hJob, IntPtr hProcess); - /// /// Retrieves job state information from the job object. /// diff --git a/src/System.Management.Automation/engine/Interop/Windows/AssignProcessToJobObject.cs b/src/System.Management.Automation/engine/Interop/Windows/AssignProcessToJobObject.cs new file mode 100644 index 00000000000..1a924fb51dc --- /dev/null +++ b/src/System.Management.Automation/engine/Interop/Windows/AssignProcessToJobObject.cs @@ -0,0 +1,16 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal static partial class Windows + { + [LibraryImport("Kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static partial bool AssignProcessToJobObject(nint hJob, nint hProcess); + } +} diff --git a/src/System.Management.Automation/engine/Interop/Windows/CloseHandle.cs b/src/System.Management.Automation/engine/Interop/Windows/CloseHandle.cs new file mode 100644 index 00000000000..6832268272a --- /dev/null +++ b/src/System.Management.Automation/engine/Interop/Windows/CloseHandle.cs @@ -0,0 +1,16 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal static partial class Windows + { + [LibraryImport("api-ms-win-core-handle-l1-1-0.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + internal static partial bool CloseHandle(nint hObject); + } +} From 6dfba03aa3d76590d28619d41631f2115899af78 Mon Sep 17 00:00:00 2001 From: Christoph Bergmeister Date: Mon, 6 Mar 2023 21:18:34 +0000 Subject: [PATCH 411/779] MSI installer: Add checkbox and MSI property DISABLE_TELEMETRY to optionally disable telemetry. (#10725) Co-authored-by: Christoph Bergmeister Co-authored-by: Christoph Bergmeister Co-authored-by: travis plunk --- assets/wix/Product.wxs | 8 +++++- test/packaging/windows/msi.tests.ps1 | 38 ++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/assets/wix/Product.wxs b/assets/wix/Product.wxs index 54979ecb51c..674e67fc860 100644 --- a/assets/wix/Product.wxs +++ b/assets/wix/Product.wxs @@ -154,6 +154,7 @@ + @@ -213,6 +214,10 @@ + + DISABLE_TELEMETRY + + ADD_PATH=1 @@ -320,7 +325,8 @@ - + + The application is distributed under the MIT license.]]> diff --git a/test/packaging/windows/msi.tests.ps1 b/test/packaging/windows/msi.tests.ps1 index 0ee34ca482c..71254d287bc 100644 --- a/test/packaging/windows/msi.tests.ps1 +++ b/test/packaging/windows/msi.tests.ps1 @@ -301,5 +301,43 @@ Describe -Name "Windows MSI" -Fixture { Invoke-MsiExec -Uninstall -MsiPath $msiX64Path } | Should -Not -Throw } + + Context "Disable Telemetry" { + It "MSI should set POWERSHELL_TELEMETRY_OPTOUT env variable when MSI property DISABLE_TELEMETRY is set to 1" -Skip:(!(Test-Elevated)) { + try { + $originalValue = [System.Environment]::GetEnvironmentVariable('POWERSHELL_TELEMETRY_OPTOUT', [System.EnvironmentVariableTarget]::Machine) + [System.Environment]::SetEnvironmentVariable('POWERSHELL_TELEMETRY_OPTOUT', '0', [System.EnvironmentVariableTarget]::Machine) + { + Invoke-MsiExec -Install -MsiPath $msiX64Path -Properties @{DISABLE_TELEMETRY = 1 } + } | Should -Not -Throw + [System.Environment]::GetEnvironmentVariable('POWERSHELL_TELEMETRY_OPTOUT', [System.EnvironmentVariableTarget]::Machine) | + Should -Be 1 + } + finally { + [System.Environment]::SetEnvironmentVariable('POWERSHELL_TELEMETRY_OPTOUT', $originalValue, [System.EnvironmentVariableTarget]::Machine) + { + Invoke-MsiExec -Uninstall -MsiPath $msiX64Path + } | Should -Not -Throw + } + } + + It "MSI should not change POWERSHELL_TELEMETRY_OPTOUT env variable when MSI property DISABLE_TELEMETRY not set" -Skip:(!(Test-Elevated)) { + try { + $originalValue = [System.Environment]::GetEnvironmentVariable('POWERSHELL_TELEMETRY_OPTOUT', [System.EnvironmentVariableTarget]::Machine) + [System.Environment]::SetEnvironmentVariable('POWERSHELL_TELEMETRY_OPTOUT', 'untouched', [System.EnvironmentVariableTarget]::Machine) + { + Invoke-MsiExec -Install -MsiPath $msiX64Path + } | Should -Not -Throw + [System.Environment]::GetEnvironmentVariable('POWERSHELL_TELEMETRY_OPTOUT', [System.EnvironmentVariableTarget]::Machine) | + Should -Be 'untouched' + } + finally { + [System.Environment]::SetEnvironmentVariable('POWERSHELL_TELEMETRY_OPTOUT', $originalValue, [System.EnvironmentVariableTarget]::Machine) + { + Invoke-MsiExec -Uninstall -MsiPath $msiX64Path + } | Should -Not -Throw + } + } + } } } From 1925cf67af68b4c0e28fd0f7f96fbe75e119496c Mon Sep 17 00:00:00 2001 From: "Mathias R. Jessen" Date: Tue, 7 Mar 2023 00:01:42 +0100 Subject: [PATCH 412/779] Add Statement property to `$MyInvocation` (#19027) --- .../engine/InvocationInfo.cs | 12 ++++++++++++ .../Language/Scripting/MyInvocation.Tests.ps1 | 19 +++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/src/System.Management.Automation/engine/InvocationInfo.cs b/src/System.Management.Automation/engine/InvocationInfo.cs index d0ba2c15c41..402d7c8d4a6 100644 --- a/src/System.Management.Automation/engine/InvocationInfo.cs +++ b/src/System.Management.Automation/engine/InvocationInfo.cs @@ -271,6 +271,18 @@ public string Line } } + /// + /// The full text of the invocation statement, may span multiple lines. + /// + /// Statement that was entered to invoke this command. + public string Statement + { + get + { + return ScriptPosition.Text; + } + } + /// /// Formatted message indicating where the cmdlet appeared /// in the line. diff --git a/test/powershell/Language/Scripting/MyInvocation.Tests.ps1 b/test/powershell/Language/Scripting/MyInvocation.Tests.ps1 index d88ea288dbc..54906f5407b 100644 --- a/test/powershell/Language/Scripting/MyInvocation.Tests.ps1 +++ b/test/powershell/Language/Scripting/MyInvocation.Tests.ps1 @@ -23,6 +23,25 @@ Describe 'Testing of MyInvocation' -Tags "CI" { { & myfilter } | Should -Not -Throw } + Context 'MyInvocation works with multi-line invocations' { + It 'MyInvocation.Statement works in & Script block' { + $a = & { + $MyInvocation.Statement + } + $a.IndexOf('& { + $MyInvocation.Statement + }') |Should -BeGreaterThan -1 + } + It 'MyInvocation.Statement works in dot sourced Script block' { + $a = . { + $MyInvocation.Statement + } + $a.IndexOf('. { + $MyInvocation.Statement + }') |Should -BeGreaterThan -1 + } + } + Context 'MyInvocation works in Script block' { It 'MyInvocation works in dot sourced Script block' { From 6824d489bbe3b52e28cd036ba9b28a05a710dcf5 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Tue, 7 Mar 2023 05:35:36 +0100 Subject: [PATCH 413/779] Fix using xml -Body in webcmdlets without an encoding (#19281) --- .../Common/WebRequestPSCmdlet.Common.cs | 2 +- .../WebCmdlets.Tests.ps1 | 17 +++++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index dfda73811ee..de26f49c751 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -1528,7 +1528,7 @@ internal void SetRequestContent(HttpRequestMessage request, XmlNode xmlNode) byte[] bytes = null; XmlDocument doc = xmlNode as XmlDocument; - if (doc?.FirstChild is XmlDeclaration decl) + if (doc?.FirstChild is XmlDeclaration decl && !string.IsNullOrEmpty(decl.Encoding)) { Encoding encoding = Encoding.GetEncoding(decl.Encoding); bytes = StreamHelper.EncodeToBytes(doc.OuterXml, encoding); diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 index 08183e714c7..2109fc1fede 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 @@ -588,6 +588,15 @@ Describe "Invoke-WebRequest tests" -Tags "Feature", "RequireAdminOnWindows" { $object.Data | Should -BeExactly 'проверка' } + It "Invoke-WebRequest supports sending XML requests without encoding" { + $uri = Get-WebListenerUrl -Test POST + $body = '' + $result = Invoke-WebRequest -Uri $uri -body ([xml]$body) -ContentType 'text/xml' -method 'POST' + + $object = $result.Content | ConvertFrom-Json + $object.Data | Should -BeExactly $body + } + It "Invoke-WebRequest supports request that returns page containing CodPage 936 data." { $uri = Get-WebListenerUrl -Test 'Encoding' -TestValue 'CP936' $command = "Invoke-WebRequest -Uri '$uri'" @@ -2402,6 +2411,14 @@ Describe "Invoke-RestMethod tests" -Tags "Feature", "RequireAdminOnWindows" { $Result.Output.Data | Should -BeExactly 'проверка' } + It "Invoke-RestMethod supports sending XML requests without encoding" { + $uri = Get-WebListenerUrl -Test POST + $body = '' + $result = Invoke-RestMethod -Uri $uri -body ([xml]$body) -ContentType 'text/xml' -method 'POST' + + $result.Data | Should -BeExactly $body + } + It "Invoke-RestMethod supports request that returns page containing Code Page 936 data." { $uri = Get-WebListenerUrl -Test 'Encoding' -TestValue 'CP936' $command = "Invoke-RestMethod -Uri '$uri'" From 9e341148f40bd23ac71d90174a80ca3186f8f6b3 Mon Sep 17 00:00:00 2001 From: stevenebutler Date: Wed, 8 Mar 2023 03:42:08 +1000 Subject: [PATCH 414/779] Support HTTP persistent connections in Web Cmdlets (#19249) --- .../Common/WebRequestPSCmdlet.Common.cs | 142 ++++++----- .../utility/WebCmdlet/CoreCLR/WebProxy.cs | 19 +- .../utility/WebCmdlet/WebRequestSession.cs | 221 ++++++++++++++++-- .../resources/WebCmdletStrings.resx | 3 + .../WebCmdlets.Tests.ps1 | 142 +++++++++++ 5 files changed, 443 insertions(+), 84 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index de26f49c751..acf8135f73f 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -88,7 +88,7 @@ public enum WebSslProtocol /// /// Base class for Invoke-RestMethod and Invoke-WebRequest commands. /// - public abstract class WebRequestPSCmdlet : PSCmdlet + public abstract class WebRequestPSCmdlet : PSCmdlet, IDisposable { #region Fields @@ -132,6 +132,11 @@ public abstract class WebRequestPSCmdlet : PSCmdlet /// private bool _resumeSuccess = false; + /// + /// True if the Dispose() method has already been called to cleanup Disposable fields. + /// + private bool _disposed = false; + #endregion Fields #region Virtual Properties @@ -522,7 +527,7 @@ protected override void ProcessRecord() bool handleRedirect = keepAuthorizationOnRedirect || AllowInsecureRedirect || PreserveHttpMethodOnRedirect; - using HttpClient client = GetHttpClient(handleRedirect); + HttpClient client = GetHttpClient(handleRedirect); int followedRelLink = 0; Uri uri = Uri; @@ -639,7 +644,7 @@ protected override void ProcessRecord() // Errors with redirection counts of greater than 0 are handled automatically by .NET, but are // impossible to detect programmatically when we hit this limit. By handling this ourselves // (and still writing out the result), users can debug actual HTTP redirect problems. - if (WebSession.MaximumRedirection == 0 && IsRedirectCode(response.StatusCode)) + if (_maximumRedirection == 0 && IsRedirectCode(response.StatusCode)) { ErrorRecord er = new(new InvalidOperationException(), "MaximumRedirectExceeded", ErrorCategory.InvalidOperation, request); er.ErrorDetails = new ErrorDetails(WebCmdletStrings.MaximumRedirectionCountExceeded); @@ -688,6 +693,33 @@ protected override void ProcessRecord() /// protected override void StopProcessing() => _cancelToken?.Cancel(); + /// + /// Disposes the associated WebSession if it is not being used as part of a persistent session. + /// + /// True when called from Dispose() and false when called from finalizer. + protected virtual void Dispose(bool disposing) + { + if (!_disposed) + { + if (disposing && !IsPersistentSession()) + { + WebSession?.Dispose(); + WebSession = null; + } + + _disposed = true; + } + } + + /// + /// Disposes the associated WebSession if it is not being used as part of a persistent session. + /// + public void Dispose() + { + Dispose(disposing: true); + GC.SuppressFinalize(this); + } + #endregion Overrides #region Virtual Methods @@ -900,20 +932,41 @@ internal virtual void PrepareSession() WebSession.UserAgent = UserAgent; } - if (Proxy is not null) + // Proxy and NoProxy parameters are mutually exclusive. + // If NoProxy is provided, WebSession will turn off the proxy + // and if Proxy is provided NoProxy will be turned off. + if (NoProxy.IsPresent) { - WebProxy webProxy = new(Proxy); - webProxy.BypassProxyOnLocal = false; - if (ProxyCredential is not null) - { - webProxy.Credentials = ProxyCredential.GetNetworkCredential(); - } - else + WebSession.NoProxy = true; + } + else + { + if (Proxy is not null) { - webProxy.UseDefaultCredentials = ProxyUseDefaultCredentials; + WebProxy webProxy = new(Proxy); + webProxy.BypassProxyOnLocal = false; + if (ProxyCredential is not null) + { + webProxy.Credentials = ProxyCredential.GetNetworkCredential(); + } + else + { + webProxy.UseDefaultCredentials = ProxyUseDefaultCredentials; + } + + // We don't want to update the WebSession unless the proxies are different + // as that will require us to create a new HttpClientHandler and lose connection + // persistence. + if (!webProxy.Equals(WebSession.Proxy)) + { + WebSession.Proxy = webProxy; + } } + } - WebSession.Proxy = webProxy; + if (MyInvocation.BoundParameters.ContainsKey(nameof(SslProtocol))) + { + WebSession.SslProtocol = SslProtocol; } if (MaximumRedirection > -1) @@ -921,6 +974,8 @@ internal virtual void PrepareSession() WebSession.MaximumRedirection = MaximumRedirection; } + WebSession.SkipCertificateCheck = SkipCertificateCheck.IsPresent; + // Store the other supplied headers if (Headers is not null) { @@ -945,63 +1000,20 @@ internal virtual void PrepareSession() // Only set retry interval if retry count is set. WebSession.RetryIntervalInSeconds = RetryIntervalSec; } + + WebSession.TimeoutSec = TimeoutSec; } internal virtual HttpClient GetHttpClient(bool handleRedirect) { - HttpClientHandler handler = new(); - handler.CookieContainer = WebSession.Cookies; - handler.AutomaticDecompression = DecompressionMethods.All; - - // Set the credentials used by this request - if (WebSession.UseDefaultCredentials) - { - // The UseDefaultCredentials flag overrides other supplied credentials - handler.UseDefaultCredentials = true; - } - else if (WebSession.Credentials is not null) - { - handler.Credentials = WebSession.Credentials; - } - - if (NoProxy) - { - handler.UseProxy = false; - } - else if (WebSession.Proxy is not null) - { - handler.Proxy = WebSession.Proxy; - } + HttpClient client = WebSession.GetHttpClient(handleRedirect, out bool clientWasReset); - if (WebSession.Certificates is not null) + if (clientWasReset) { - handler.ClientCertificates.AddRange(WebSession.Certificates); + WriteVerbose(WebCmdletStrings.WebSessionConnectionRecreated); } - if (SkipCertificateCheck) - { - handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator; - handler.ClientCertificateOptions = ClientCertificateOption.Manual; - } - - // This indicates GetResponse will handle redirects. - if (handleRedirect || WebSession.MaximumRedirection == 0) - { - handler.AllowAutoRedirect = false; - } - else if (WebSession.MaximumRedirection > 0) - { - handler.MaxAutomaticRedirections = WebSession.MaximumRedirection; - } - - handler.SslProtocols = (SslProtocols)SslProtocol; - - HttpClient httpClient = new(handler); - - // Check timeout setting (in seconds instead of milliseconds as in HttpWebRequest) - httpClient.Timeout = TimeoutSec is 0 ? TimeSpan.FromMilliseconds(Timeout.Infinite) : new TimeSpan(0, 0, TimeoutSec); - - return httpClient; + return client; } internal virtual HttpRequestMessage GetRequest(Uri uri) @@ -1459,6 +1471,8 @@ private void ProcessAuthentication() } } + private bool IsPersistentSession() => MyInvocation.BoundParameters.ContainsKey(nameof(WebSession)) || MyInvocation.BoundParameters.ContainsKey(nameof(SessionVariable)); + /// /// Sets the ContentLength property of the request and writes the specified content to the request's RequestStream. /// @@ -1686,7 +1700,7 @@ private void AddMultipartContent(object fieldName, object fieldValue, MultipartF private static StringContent GetMultipartStringContent(object fieldName, object fieldValue) { ContentDispositionHeaderValue contentDisposition = new("form-data"); - + // .NET does not enclose field names in quotes, however, modern browsers and curl do. contentDisposition.Name = "\"" + LanguagePrimitives.ConvertTo(fieldName) + "\""; @@ -1773,7 +1787,7 @@ private static string FormatErrorMessage(string error, string contentType) { // Ignore errors } - + if (string.IsNullOrEmpty(formattedError)) { // Remove HTML tags making it easier to read diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebProxy.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebProxy.cs index 0f46827bd63..6890599b51b 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebProxy.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebProxy.cs @@ -6,7 +6,7 @@ namespace Microsoft.PowerShell.Commands { - internal class WebProxy : IWebProxy + internal class WebProxy : IWebProxy, IEquatable { private ICredentials _credentials; private readonly Uri _proxyAddress; @@ -18,6 +18,23 @@ internal WebProxy(Uri address) _proxyAddress = address; } + public override bool Equals(object obj) => Equals(obj as WebProxy); + + public override int GetHashCode() => HashCode.Combine(_proxyAddress, _credentials, BypassProxyOnLocal); + + public bool Equals(WebProxy other) + { + if (other is null) + { + return false; + } + + // _proxyAddress cannot be null as it is set in the constructor + return other._credentials == _credentials + && _proxyAddress.Equals(other._proxyAddress) + && BypassProxyOnLocal == other.BypassProxyOnLocal; + } + public ICredentials Credentials { get => _credentials; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestSession.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestSession.cs index c100f345a79..4e58503659e 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestSession.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestSession.cs @@ -4,15 +4,37 @@ using System; using System.Collections.Generic; using System.Net; +using System.Net.Http; +using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; +using System.Threading; namespace Microsoft.PowerShell.Commands { /// /// WebRequestSession for holding session infos. /// - public class WebRequestSession + public class WebRequestSession : IDisposable { + private HttpClient _client; + private CookieContainer _cookies; + private bool _useDefaultCredentials; + private ICredentials _credentials; + private X509CertificateCollection _certificates; + private IWebProxy _proxy; + private int _maximumRedirection; + private WebSslProtocol _sslProtocol; + private bool _allowAutoRedirect; + private bool _skipCertificateCheck; + private bool _noProxy; + private bool _disposed; + private int _timeoutSec; + + /// + /// Contains true if an existing HttpClient had to be disposed and recreated since the WebSession was last used. + /// + private bool _disposedClient; + /// /// Gets or sets the Header property. /// @@ -27,25 +49,25 @@ public class WebRequestSession /// /// Gets or sets the Cookies property. /// - public CookieContainer Cookies { get; set; } + public CookieContainer Cookies { get => _cookies; set => SetClassVar(ref _cookies, value); } #region Credentials /// /// Gets or sets the UseDefaultCredentials property. /// - public bool UseDefaultCredentials { get; set; } + public bool UseDefaultCredentials { get => _useDefaultCredentials; set => SetStructVar(ref _useDefaultCredentials, value); } /// /// Gets or sets the Credentials property. /// - public ICredentials Credentials { get; set; } + public ICredentials Credentials { get => _credentials; set => SetClassVar(ref _credentials, value); } /// /// Gets or sets the Certificates property. /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] - public X509CertificateCollection Certificates { get; set; } + public X509CertificateCollection Certificates { get => _certificates; set => SetClassVar(ref _certificates, value); } #endregion @@ -57,12 +79,23 @@ public class WebRequestSession /// /// Gets or sets the Proxy property. /// - public IWebProxy Proxy { get; set; } + public IWebProxy Proxy + { + get => _proxy; + set + { + SetClassVar(ref _proxy, value); + if (_proxy is not null) + { + NoProxy = false; + } + } + } /// - /// Gets or sets the RedirectMax property. + /// Gets or sets the MaximumRedirection property. /// - public int MaximumRedirection { get; set; } + public int MaximumRedirection { get => _maximumRedirection; set => SetStructVar(ref _maximumRedirection, value); } /// /// Gets or sets the count of retries for request failures. @@ -79,23 +112,42 @@ public class WebRequestSession /// public WebRequestSession() { - // build the headers collection + // Build the headers collection Headers = new Dictionary(StringComparer.OrdinalIgnoreCase); ContentHeaders = new Dictionary(StringComparer.OrdinalIgnoreCase); - // build the cookie jar - Cookies = new CookieContainer(); + // Build the cookie jar + _cookies = new CookieContainer(); - // initialize the credential and certificate caches - UseDefaultCredentials = false; - Credentials = null; - Certificates = null; + // Initialize the credential and certificate caches + _useDefaultCredentials = false; + _credentials = null; + _certificates = null; - // setup the default UserAgent + // Setup the default UserAgent UserAgent = PSUserAgent.UserAgent; - Proxy = null; - MaximumRedirection = -1; + _proxy = null; + _maximumRedirection = -1; + _allowAutoRedirect = true; + } + + internal WebSslProtocol SslProtocol { set => SetStructVar(ref _sslProtocol, value); } + + internal bool SkipCertificateCheck { set => SetStructVar(ref _skipCertificateCheck, value); } + + internal int TimeoutSec { set => SetStructVar(ref _timeoutSec, value); } + + internal bool NoProxy + { + set + { + SetStructVar(ref _noProxy, value); + if (_noProxy) + { + Proxy = null; + } + } } /// @@ -105,8 +157,139 @@ public WebRequestSession() internal void AddCertificate(X509Certificate certificate) { Certificates ??= new X509CertificateCollection(); + if (!Certificates.Contains(certificate)) + { + ResetClient(); + Certificates.Add(certificate); + } + } + + /// + /// Gets an existing or creates a new HttpClient for this WebRequest session if none currently exists (either because it was never + /// created, or because changes to the WebSession properties required the existing HttpClient to be disposed). + /// + /// True if the caller does not want the HttpClient to ever handle redirections automatically. + /// Contains true if an existing HttpClient had to be disposed and recreated since the WebSession was last used. + /// The HttpClient cached in the WebSession, based on all current settings. + internal HttpClient GetHttpClient(bool suppressHttpClientRedirects, out bool clientWasReset) + { + // Do not auto redirect if the the caller does not want it, or maximum redirections is 0 + SetStructVar(ref _allowAutoRedirect, !(suppressHttpClientRedirects || MaximumRedirection == 0)); + + clientWasReset = _disposedClient; + + if (_client is null) + { + _client = CreateHttpClient(); + _disposedClient = false; + } + + return _client; + } + + private HttpClient CreateHttpClient() + { + HttpClientHandler handler = new(); + + handler.CookieContainer = Cookies; + handler.AutomaticDecompression = DecompressionMethods.All; + + if (Credentials is not null) + { + handler.Credentials = Credentials; + } + else + { + handler.UseDefaultCredentials = UseDefaultCredentials; + } - Certificates.Add(certificate); + if (_noProxy) + { + handler.UseProxy = false; + } + else if (Proxy is not null) + { + handler.Proxy = Proxy; + } + + if (Certificates is not null) + { + handler.ClientCertificates.AddRange(Certificates); + } + + if (_skipCertificateCheck) + { + handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator; + handler.ClientCertificateOptions = ClientCertificateOption.Manual; + } + + handler.AllowAutoRedirect = _allowAutoRedirect; + if (_allowAutoRedirect && MaximumRedirection > 0) + { + handler.MaxAutomaticRedirections = MaximumRedirection; + } + + handler.SslProtocols = (SslProtocols)_sslProtocol; + + // Check timeout setting (in seconds instead of milliseconds as in HttpWebRequest) + return new HttpClient(handler) + { + Timeout = _timeoutSec is 0 ? TimeSpan.FromMilliseconds(Timeout.Infinite) : TimeSpan.FromSeconds(_timeoutSec) + }; + } + + private void SetClassVar(ref T oldValue, T newValue) where T : class + { + if (oldValue != newValue) + { + ResetClient(); + oldValue = newValue; + } + } + + private void SetStructVar(ref T oldValue, T newValue) where T : struct + { + if (!oldValue.Equals(newValue)) + { + ResetClient(); + oldValue = newValue; + } + } + + private void ResetClient() + { + if (_client is not null) + { + _disposedClient = true; + _client.Dispose(); + _client = null; + } + } + + /// + /// Dispose the WebRequestSession. + /// + /// True when called from Dispose() and false when called from finalizer. + protected virtual void Dispose(bool disposing) + { + if (!_disposed) + { + if (disposing) + { + _client?.Dispose(); + } + + _disposed = true; + } + } + + /// + /// Dispose the WebRequestSession. + /// + public void Dispose() + { + Dispose(disposing: true); + GC.SuppressFinalize(this); } } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/WebCmdletStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/WebCmdletStrings.resx index 99a1d0ef7c6..5b1b33eae62 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/WebCmdletStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/WebCmdletStrings.resx @@ -249,4 +249,7 @@ Resulting JSON is truncated as serialization has exceeded the set depth of {0}. + + The WebSession properties were changed between requests forcing all HTTP connections in the session to be recreated. + diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 index 2109fc1fede..fe6db03a2a1 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 @@ -2250,6 +2250,148 @@ Describe "Invoke-WebRequest tests" -Tags "Feature", "RequireAdminOnWindows" { $pathologicalRatio | Should -BeGreaterThan 5 } } + + Context 'Invoke-WebSession: Connection persistence in a WebSession' { + # Match verbose message from resource name WebSessionConnectionRecreated with message: + # The WebSession properties were changed between requests forcing all HTTP connections in the session to be recreated. + $matchConnRecreatedMessage = [regex]::new('WebSession.+HTTP') + + function RunCheckingPersistence { + param( + [uri]$Uri, + [string]$Command, + [object]$Session, + [switch]$ExpectConnectionRecreated, + [switch]$CaptureSession + ) + + $pwsh = [PowerShell]::Create() + $pwsh.Runspace.SessionStateProxy.SetVariable('uri', $Uri) + if ($Session) { + $pwsh.Runspace.SessionStateProxy.SetVariable('Session', $Session) + $command = "$command -WebSession `$Session" + } + if ($CaptureSession) { + $command = "$command -SessionVariable Session" + } + $script = "`$null = $command -Verbose" + $pwsh.AddScript($script).Invoke() + $session = $pwsh.Runspace.SessionStateProxy.GetVariable('Session') + + $expectedConnRecreatedCount = if ($ExpectConnectionRecreated) { 1 } else { 0 } + ($pwsh.Streams.Verbose | Where-Object { $matchConnRecreatedMessage.Matches($_.Message) }).Count | Should -Be $expectedConnRecreatedCount + + $pwsh.Dispose() + + return $session + } + + It 'Connection persistence maintained' { + $uri = Get-WebListenerUrl + $Session = RunCheckingPersistence -Uri $uri -Command 'Invoke-WebRequest -Uri $uri' -CaptureSession + 1 .. 3 | ForEach-Object { + RunCheckingPersistence -Uri $uri -Command 'Invoke-WebRequest -Uri $uri' -Session $Session + } + } + + It 'Connection persistence impacted by changing SkipCertificateCheck' { + $uri = Get-WebListenerUrl -Https + # This first request will throw because the certificate is invalid + $session = $null + $session = RunCheckingPersistence -Uri $uri -Command 'Invoke-WebRequest -Uri $uri' -CaptureSession + # No change in setting + $session = RunCheckingPersistence -Uri $uri -Command 'Invoke-WebRequest -Uri $uri -SkipCertificateCheck:$false' -Session $session + # Skipping cert check changes persistence + $session = RunCheckingPersistence -Uri $uri -Command 'Invoke-WebRequest -Uri $uri -SkipCertificateCheck' -Session $session -ExpectConnectionRecreated + # Same settings won't lose persistence + $session = RunCheckingPersistence -Uri $uri -Command 'Invoke-WebRequest -Uri $uri -SkipCertificateCheck' -Session $session + # Lose persistence due to changing cert check - this will also throw + $session = RunCheckingPersistence -Uri $uri -Command 'Invoke-WebRequest -Uri $uri -SkipCertificateCheck:$false' -Session $session -ExpectConnectionRecreated + } + + It 'Connection persistence is not impacted by changing request headers' { + $uri = Get-WebListenerUrl + $session = $null + $session = RunCheckingPersistence -Uri $uri -Command 'Invoke-WebRequest -Uri $uri' -CaptureSession + $session = RunCheckingPersistence -Uri $uri -Command 'Invoke-WebRequest -Uri $uri -Headers @{ A = "B" }' -Session $session + $session = RunCheckingPersistence -Uri $uri -Command 'Invoke-WebRequest -Uri $uri -Headers @{}' -Session $session + $session = RunCheckingPersistence -Uri $uri -Command 'Invoke-WebRequest -Uri $uri -Headers @{ A = "C"; B = "D"}' -Session $session + } + + It 'Connection persistence is impacted by changing the session cookie jar' { + $uri = Get-WebListenerUrl + $session = RunCheckingPersistence -Uri $uri -Command 'Invoke-WebRequest -Uri $uri' -CaptureSession + $session.Cookies = New-Object System.Net.CookieContainer + $session = RunCheckingPersistence -Uri $uri -Command 'Invoke-WebRequest -Uri $uri' -Session $session -ExpectConnectionRecreated + + # Adding a cookie to the container does not lose persistence + $Session.Cookies.Add('http://localhost', [system.net.cookie]::new('cookie', 'value')) + $session = RunCheckingPersistence -Uri $uri -Command 'Invoke-WebRequest -Uri $uri' -Session $session + } + + It 'Connection persistence is not impacted by changing the user agent' { + $uri = Get-WebListenerUrl + $session = RunCheckingPersistence -Uri $uri -Command 'Invoke-WebRequest -Uri $uri -UserAgent Powershell' -CaptureSession + $session = RunCheckingPersistence -Uri $uri -Command 'Invoke-WebRequest -Uri $uri -UserAgent "PowerShell Core"' -Session $session + $session = RunCheckingPersistence -Uri $uri -Command 'Invoke-WebRequest -Uri $uri -UserAgent "PowerShell Core with HttpClient"' -Session $session + # Ensure persistence is lost when we change a different setting + $session = RunCheckingPersistence -Uri $uri -Command 'Invoke-WebRequest -Uri $uri -NoProxy -UserAgent "PowerShell Core"' -Session $session -ExpectConnectionRecreated + } + + It 'Connection persistence is not impacted when NoProxy parameter is not supplied' { + $uri = Get-WebListenerUrl + $session = RunCheckingPersistence -Uri $uri -Command 'Invoke-WebRequest -Uri $uri' -CaptureSession + # Explicitly prevent proxy - connection lost + $session = RunCheckingPersistence -Uri $uri -Command 'Invoke-WebRequest -Uri $uri -NoProxy' -Session $session -ExpectConnectionRecreated + # Provide explicit switch value - connection maintained + $session = RunCheckingPersistence -Uri $uri -Command 'Invoke-WebRequest -Uri $uri -NoProxy:$true' -Session $session + # No spec for proxy - connection maintained + $session = RunCheckingPersistence -Uri $uri -Command 'Invoke-WebRequest -Uri $uri' -Session $session + # Two follow up calls without altering anything do not lose connection + $session = RunCheckingPersistence -Uri $uri -Command 'Invoke-WebRequest -Uri $uri' -Session $session + $session = RunCheckingPersistence -Uri $uri -Command 'Invoke-WebRequest -Uri $uri' -Session $session + } + + It 'Connection persistence is not impacted when SslProtocol parameter is not supplied' { + $uri = Get-WebListenerUrl + $session = RunCheckingPersistence -Uri $uri -Command 'Invoke-WebRequest -Uri $uri -SslProtocol Tls12' -CaptureSession + # No SslProtocol provided - keeps last value - connection retained + $session = RunCheckingPersistence -Uri $uri -Command 'Invoke-WebRequest -Uri $uri' -Session $session + # Explicit default - loses connection + $session = RunCheckingPersistence -Uri $uri -Command 'Invoke-WebRequest -Uri $uri -SslProtocol Default' -Session $session -ExpectConnectionRecreated + # No SslProtocol provided - keeps last value - connection retained + $session = RunCheckingPersistence -Uri $uri -Command 'Invoke-WebRequest -Uri $uri' -Session $session + # Explicitly set to same value as last time it was set - connection retained + $session = RunCheckingPersistence -Uri $uri -Command 'Invoke-WebRequest -Uri $uri -SslProtocol Default' -Session $session + } + + It 'Connection persistence is not impacted by Proxy and NoProxy unless changed parameters are used between invocations' { + $uri = Get-WebListenerUrl + $session = RunCheckingPersistence -Uri $uri -Command 'Invoke-WebRequest -Uri $uri' -CaptureSession + $proxy = 'http://127.0.0.1:8080' + $session = RunCheckingPersistence -Uri $uri -Command "Invoke-WebRequest -Uri $uri -proxy $proxy" -Session $session -ExpectConnectionRecreated + # same proxy - do not lose persistence + $session = RunCheckingPersistence -Uri $uri -Command "Invoke-WebRequest -Uri $uri -proxy $proxy" -Session $session + # No proxy at all - use previous setting and don't lose connection + $session = RunCheckingPersistence -Uri $uri -Command "Invoke-WebRequest -Uri $uri" -Session $session + + # NoProxy toggles proxy off - loses connection + $session = RunCheckingPersistence -Uri $uri -Command "Invoke-WebRequest -Uri $uri -NoProxy" -Session $session -ExpectConnectionRecreated + # No setting at all - retains NoProxy setting + $session = RunCheckingPersistence -Uri $uri -Command "Invoke-WebRequest -Uri $uri" -Session $session + + # Use proxy again - lose connection + $session = RunCheckingPersistence -Uri $uri -Command "Invoke-WebRequest -Uri $uri -proxy $proxy" -Session $session -ExpectConnectionRecreated + # No proxy specified - connection retained + $session = RunCheckingPersistence -Uri $uri -Command "Invoke-WebRequest -Uri $uri" -Session $session + + # Proxy changed - lose connection + $proxy = 'http://localhost:8080' + $session = RunCheckingPersistence -Uri $uri -Command "Invoke-WebRequest -Uri $uri -proxy $proxy" -Session $session -ExpectConnectionRecreated + # No proxy specified - connection retained + $session = RunCheckingPersistence -Uri $uri -Command "Invoke-WebRequest -Uri $uri" -Session $session + } + } } Describe "Invoke-RestMethod tests" -Tags "Feature", "RequireAdminOnWindows" { From ff32e01d3161f3f7b0730a4d9a9ba81abf4c32b6 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Tue, 7 Mar 2023 21:18:43 +0100 Subject: [PATCH 415/779] Fix `CodeFactor` issues in the code base - part 4 (#19270) --- .../ScheduledJobWTS.cs | 35 ++++- .../DscSupport/CimDSCParser.cs | 20 ++- ...lets-over-objects.xmlSerializer.autogen.cs | 132 +++++++++++++++--- .../engine/ComInterop/ComInvokeBinder.cs | 2 +- .../engine/ExecutionContext.cs | 48 +++++-- .../ExperimentalFeature.cs | 5 +- .../GetExperimentalFeatureCommand.cs | 15 +- .../engine/SessionStateScope.cs | 4 +- .../engine/hostifaces/Connection.cs | 5 +- .../engine/hostifaces/ConnectionBase.cs | 11 +- .../engine/hostifaces/HostUtilities.cs | 5 +- .../engine/hostifaces/InternalHost.cs | 5 +- .../engine/hostifaces/LocalConnection.cs | 10 +- .../engine/hostifaces/MshHostUserInterface.cs | 5 +- .../engine/hostifaces/PSDataCollection.cs | 5 +- .../hostifaces/PowerShellProcessInstance.cs | 12 +- .../engine/interpreter/CallInstruction.cs | 6 +- 17 files changed, 265 insertions(+), 60 deletions(-) diff --git a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobWTS.cs b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobWTS.cs index a8d76ef7da8..b8714816a71 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobWTS.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobWTS.cs @@ -878,19 +878,40 @@ private List ConvertMaskToDaysOfWeekArray(short mask) { List daysOfWeek = new List(); - if ((mask & WTSSunday) != 0) { daysOfWeek.Add(DayOfWeek.Sunday); } + if ((mask & WTSSunday) != 0) + { + daysOfWeek.Add(DayOfWeek.Sunday); + } - if ((mask & WTSMonday) != 0) { daysOfWeek.Add(DayOfWeek.Monday); } + if ((mask & WTSMonday) != 0) + { + daysOfWeek.Add(DayOfWeek.Monday); + } - if ((mask & WTSTuesday) != 0) { daysOfWeek.Add(DayOfWeek.Tuesday); } + if ((mask & WTSTuesday) != 0) + { + daysOfWeek.Add(DayOfWeek.Tuesday); + } - if ((mask & WTSWednesday) != 0) { daysOfWeek.Add(DayOfWeek.Wednesday); } + if ((mask & WTSWednesday) != 0) + { + daysOfWeek.Add(DayOfWeek.Wednesday); + } - if ((mask & WTSThursday) != 0) { daysOfWeek.Add(DayOfWeek.Thursday); } + if ((mask & WTSThursday) != 0) + { + daysOfWeek.Add(DayOfWeek.Thursday); + } - if ((mask & WTSFriday) != 0) { daysOfWeek.Add(DayOfWeek.Friday); } + if ((mask & WTSFriday) != 0) + { + daysOfWeek.Add(DayOfWeek.Friday); + } - if ((mask & WTSSaturday) != 0) { daysOfWeek.Add(DayOfWeek.Saturday); } + if ((mask & WTSSaturday) != 0) + { + daysOfWeek.Add(DayOfWeek.Saturday); + } return daysOfWeek; } diff --git a/src/System.Management.Automation/DscSupport/CimDSCParser.cs b/src/System.Management.Automation/DscSupport/CimDSCParser.cs index a3c80e577fa..261c567ac8d 100644 --- a/src/System.Management.Automation/DscSupport/CimDSCParser.cs +++ b/src/System.Management.Automation/DscSupport/CimDSCParser.cs @@ -807,7 +807,10 @@ private static void LoadDSCResourceIntoCache(Collection errors, List< { foreach (string moduleDir in modulePathList) { - if (!Directory.Exists(moduleDir)) continue; + if (!Directory.Exists(moduleDir)) + { + continue; + } var dscResourcesPath = Path.Combine(moduleDir, "DscResources"); if (Directory.Exists(dscResourcesPath)) @@ -2601,7 +2604,10 @@ private static bool GetResourceDefinitionsFromModule(string fileName, out IEnume for (int i = 0; i < typeAst.Attributes.Count; i++) { var a = typeAst.Attributes[i]; - if (a.TypeName.GetReflectionAttributeType() == typeof(DscResourceAttribute)) return true; + if (a.TypeName.GetReflectionAttributeType() == typeof(DscResourceAttribute)) + { + return true; + } } } @@ -2655,7 +2661,10 @@ private static bool ImportKeywordsFromScriptFile(string fileName, PSModuleInfo m } } - if (skip) continue; + if (skip) + { + continue; + } // Parse the Resource Attribute to see if RunAs behavior is specified for the resource. DSCResourceRunAsCredential runAsBehavior = DSCResourceRunAsCredential.Default; @@ -3130,7 +3139,10 @@ private static bool ImportKeywordsFromAssembly(PSModuleInfo module, } } - if (skip) continue; + if (skip) + { + continue; + } var mof = GenerateMofForType(r); diff --git a/src/System.Management.Automation/cimSupport/cmdletization/xml/cmdlets-over-objects.xmlSerializer.autogen.cs b/src/System.Management.Automation/cimSupport/cmdletization/xml/cmdlets-over-objects.xmlSerializer.autogen.cs index a05d597999a..f463e5052bb 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/xml/cmdlets-over-objects.xmlSerializer.autogen.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/xml/cmdlets-over-objects.xmlSerializer.autogen.cs @@ -514,7 +514,11 @@ private void Write49_EnumMetadataEnumValue(string n, string ns, global::Microsof { if ((object)o == null) { - if (isNullable) WriteNullTagLiteral(n, ns); + if (isNullable) + { + WriteNullTagLiteral(n, ns); + } + return; } @@ -531,7 +535,11 @@ private void Write49_EnumMetadataEnumValue(string n, string ns, global::Microsof } WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"EnumMetadataEnumValue", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); + if (needType) + { + WriteXsiType(@"EnumMetadataEnumValue", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); + } + WriteAttribute(@"Name", @"", ((global::System.String)o.@Name)); WriteAttribute(@"Value", @"", ((global::System.String)o.@Value)); WriteEndElement(o); @@ -541,7 +549,11 @@ private void Write48_EnumMetadataEnum(string n, string ns, global::Microsoft.Pow { if ((object)o == null) { - if (isNullable) WriteNullTagLiteral(n, ns); + if (isNullable) + { + WriteNullTagLiteral(n, ns); + } + return; } @@ -558,7 +570,11 @@ private void Write48_EnumMetadataEnum(string n, string ns, global::Microsoft.Pow } WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"EnumMetadataEnum", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); + if (needType) + { + WriteXsiType(@"EnumMetadataEnum", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); + } + WriteAttribute(@"EnumName", @"", ((global::System.String)o.@EnumName)); WriteAttribute(@"UnderlyingType", @"", ((global::System.String)o.@UnderlyingType)); if (o.@BitwiseFlagsSpecified) @@ -587,7 +603,11 @@ private void Write37_EnumMetadataEnumValue(string n, string ns, global::Microsof { if ((object)o == null) { - if (isNullable) WriteNullTagLiteral(n, ns); + if (isNullable) + { + WriteNullTagLiteral(n, ns); + } + return; } @@ -604,7 +624,11 @@ private void Write37_EnumMetadataEnumValue(string n, string ns, global::Microsof } WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); + if (needType) + { + WriteXsiType(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); + } + WriteAttribute(@"Name", @"", ((global::System.String)o.@Name)); WriteAttribute(@"Value", @"", ((global::System.String)o.@Value)); WriteEndElement(o); @@ -614,7 +638,11 @@ private void Write47_ClassMetadataData(string n, string ns, global::Microsoft.Po { if ((object)o == null) { - if (isNullable) WriteNullTagLiteral(n, ns); + if (isNullable) + { + WriteNullTagLiteral(n, ns); + } + return; } @@ -631,7 +659,11 @@ private void Write47_ClassMetadataData(string n, string ns, global::Microsoft.Po } WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"ClassMetadataData", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); + if (needType) + { + WriteXsiType(@"ClassMetadataData", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); + } + WriteAttribute(@"Name", @"", ((global::System.String)o.@Name)); if ((object)(o.@Value) != null) { @@ -660,7 +692,11 @@ private void Write13_WildcardablePropertyQuery(string n, string ns, global::Micr { if ((object)o == null) { - if (isNullable) WriteNullTagLiteral(n, ns); + if (isNullable) + { + WriteNullTagLiteral(n, ns); + } + return; } @@ -677,7 +713,11 @@ private void Write13_WildcardablePropertyQuery(string n, string ns, global::Micr } WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"WildcardablePropertyQuery", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); + if (needType) + { + WriteXsiType(@"WildcardablePropertyQuery", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); + } + if (o.@AllowGlobbingSpecified) { WriteAttribute(@"AllowGlobbing", @"", System.Xml.XmlConvert.ToString((global::System.Boolean)((global::System.Boolean)o.@AllowGlobbing))); @@ -695,7 +735,11 @@ private void Write12_Item(string n, string ns, global::Microsoft.PowerShell.Cmdl { if ((object)o == null) { - if (isNullable) WriteNullTagLiteral(n, ns); + if (isNullable) + { + WriteNullTagLiteral(n, ns); + } + return; } @@ -712,7 +756,11 @@ private void Write12_Item(string n, string ns, global::Microsoft.PowerShell.Cmdl } WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"CmdletParameterMetadataForGetCmdletFilteringParameter", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); + if (needType) + { + WriteXsiType(@"CmdletParameterMetadataForGetCmdletFilteringParameter", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); + } + if (o.@IsMandatorySpecified) { WriteAttribute(@"IsMandatory", @"", System.Xml.XmlConvert.ToString((global::System.Boolean)((global::System.Boolean)o.@IsMandatory))); @@ -725,7 +773,11 @@ private void Write12_Item(string n, string ns, global::Microsoft.PowerShell.Cmdl for (int i = 0; i < a.Length; i++) { global::System.String ai = (global::System.String)a[i]; - if (i != 0) Writer.WriteString(" "); + if (i != 0) + { + Writer.WriteString(" "); + } + WriteValue(ai); } @@ -752,7 +804,11 @@ private void Write12_Item(string n, string ns, global::Microsoft.PowerShell.Cmdl for (int i = 0; i < a.Length; i++) { global::System.String ai = (global::System.String)a[i]; - if (i != 0) Writer.WriteString(" "); + if (i != 0) + { + Writer.WriteString(" "); + } + WriteValue(ai); } @@ -811,7 +867,11 @@ private void Write7_ObsoleteAttributeMetadata(string n, string ns, global::Micro { if ((object)o == null) { - if (isNullable) WriteNullTagLiteral(n, ns); + if (isNullable) + { + WriteNullTagLiteral(n, ns); + } + return; } @@ -828,7 +888,11 @@ private void Write7_ObsoleteAttributeMetadata(string n, string ns, global::Micro } WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"ObsoleteAttributeMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); + if (needType) + { + WriteXsiType(@"ObsoleteAttributeMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); + } + WriteAttribute(@"Message", @"", ((global::System.String)o.@Message)); WriteEndElement(o); } @@ -837,7 +901,11 @@ private void Write6_Item(string n, string ns, global::Microsoft.PowerShell.Cmdle { if ((object)o == null) { - if (isNullable) WriteNullTagLiteral(n, ns); + if (isNullable) + { + WriteNullTagLiteral(n, ns); + } + return; } @@ -854,7 +922,11 @@ private void Write6_Item(string n, string ns, global::Microsoft.PowerShell.Cmdle } WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); + if (needType) + { + WriteXsiType(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); + } + WriteAttribute(@"Min", @"", ((global::System.String)o.@Min)); WriteAttribute(@"Max", @"", ((global::System.String)o.@Max)); WriteEndElement(o); @@ -864,7 +936,11 @@ private void Write5_Item(string n, string ns, global::Microsoft.PowerShell.Cmdle { if ((object)o == null) { - if (isNullable) WriteNullTagLiteral(n, ns); + if (isNullable) + { + WriteNullTagLiteral(n, ns); + } + return; } @@ -881,7 +957,11 @@ private void Write5_Item(string n, string ns, global::Microsoft.PowerShell.Cmdle } WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); + if (needType) + { + WriteXsiType(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); + } + WriteAttribute(@"Min", @"", ((global::System.String)o.@Min)); WriteAttribute(@"Max", @"", ((global::System.String)o.@Max)); WriteEndElement(o); @@ -891,7 +971,11 @@ private void Write4_Item(string n, string ns, global::Microsoft.PowerShell.Cmdle { if ((object)o == null) { - if (isNullable) WriteNullTagLiteral(n, ns); + if (isNullable) + { + WriteNullTagLiteral(n, ns); + } + return; } @@ -908,7 +992,11 @@ private void Write4_Item(string n, string ns, global::Microsoft.PowerShell.Cmdle } WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); + if (needType) + { + WriteXsiType(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); + } + WriteAttribute(@"Min", @"", ((global::System.String)o.@Min)); WriteAttribute(@"Max", @"", ((global::System.String)o.@Max)); WriteEndElement(o); diff --git a/src/System.Management.Automation/engine/ComInterop/ComInvokeBinder.cs b/src/System.Management.Automation/engine/ComInterop/ComInvokeBinder.cs index 0e80a30ae1a..3765f5ba68b 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComInvokeBinder.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComInvokeBinder.cs @@ -167,7 +167,7 @@ internal DynamicMetaObject Invoke() private static void AddNotNull(List list, ParameterExpression var) { - if (var != null) + if (var != null) { list.Add(var); } diff --git a/src/System.Management.Automation/engine/ExecutionContext.cs b/src/System.Management.Automation/engine/ExecutionContext.cs index 0f2fb0822b5..56f64c1a5c2 100644 --- a/src/System.Management.Automation/engine/ExecutionContext.cs +++ b/src/System.Management.Automation/engine/ExecutionContext.cs @@ -1472,9 +1472,17 @@ internal void ReportEngineStartupError(string resourceString, params object[] ar else { PSHost host = EngineHostInterface; - if (host == null) return; + if (host == null) + { + return; + } + PSHostUserInterface ui = host.UI; - if (ui == null) return; + if (ui == null) + { + return; + } + ui.WriteErrorLine( StringUtil.Format(resourceString, arguments)); } @@ -1502,9 +1510,17 @@ internal void ReportEngineStartupError(string error) else { PSHost host = EngineHostInterface; - if (host == null) return; + if (host == null) + { + return; + } + PSHostUserInterface ui = host.UI; - if (ui == null) return; + if (ui == null) + { + return; + } + ui.WriteErrorLine(error); } } @@ -1537,9 +1553,17 @@ internal void ReportEngineStartupError(Exception e) else { PSHost host = EngineHostInterface; - if (host == null) return; + if (host == null) + { + return; + } + PSHostUserInterface ui = host.UI; - if (ui == null) return; + if (ui == null) + { + return; + } + ui.WriteErrorLine(e.Message); } } @@ -1564,9 +1588,17 @@ internal void ReportEngineStartupError(ErrorRecord errorRecord) else { PSHost host = EngineHostInterface; - if (host == null) return; + if (host == null) + { + return; + } + PSHostUserInterface ui = host.UI; - if (ui == null) return; + if (ui == null) + { + return; + } + ui.WriteErrorLine(errorRecord.ToString()); } } diff --git a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs index b059c861cef..58ba1aa1075 100644 --- a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs +++ b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs @@ -164,7 +164,10 @@ static ExperimentalFeature() /// private static ReadOnlyBag ProcessEnabledFeatures(string[] enabledFeatures) { - if (enabledFeatures.Length == 0) { return ReadOnlyBag.Empty; } + if (enabledFeatures.Length == 0) + { + return ReadOnlyBag.Empty; + } var list = new List(enabledFeatures.Length); foreach (string name in enabledFeatures) diff --git a/src/System.Management.Automation/engine/ExperimentalFeature/GetExperimentalFeatureCommand.cs b/src/System.Management.Automation/engine/ExperimentalFeature/GetExperimentalFeatureCommand.cs index d87669000de..38525cb54ef 100644 --- a/src/System.Management.Automation/engine/ExperimentalFeature/GetExperimentalFeatureCommand.cs +++ b/src/System.Management.Automation/engine/ExperimentalFeature/GetExperimentalFeatureCommand.cs @@ -88,17 +88,26 @@ private IEnumerable GetValidModuleFiles(HashSet moduleNamesToFin foreach (string path in ModuleIntrinsics.GetModulePath(includeSystemModulePath: false, Context)) { string uniquePath = path.TrimEnd(Utils.Separators.Directory); - if (!modulePaths.Add(uniquePath)) { continue; } + if (!modulePaths.Add(uniquePath)) + { + continue; + } foreach (string moduleFile in ModuleUtils.GetDefaultAvailableModuleFiles(uniquePath)) { // We only care about module manifest files because that's where experimental features are declared. - if (!moduleFile.EndsWith(StringLiterals.PowerShellDataFileExtension, StringComparison.OrdinalIgnoreCase)) { continue; } + if (!moduleFile.EndsWith(StringLiterals.PowerShellDataFileExtension, StringComparison.OrdinalIgnoreCase)) + { + continue; + } if (moduleNamesToFind != null) { string currentModuleName = ModuleIntrinsics.GetModuleName(moduleFile); - if (!moduleNamesToFind.Contains(currentModuleName)) { continue; } + if (!moduleNamesToFind.Contains(currentModuleName)) + { + continue; + } } yield return moduleFile; diff --git a/src/System.Management.Automation/engine/SessionStateScope.cs b/src/System.Management.Automation/engine/SessionStateScope.cs index d947643c7d2..6a13e2f8d0b 100644 --- a/src/System.Management.Automation/engine/SessionStateScope.cs +++ b/src/System.Management.Automation/engine/SessionStateScope.cs @@ -1642,7 +1642,7 @@ internal void AddType(string name, Type type) internal Type LookupType(string name) { - if (TypeTable == null) + if (TypeTable == null) { return null; } @@ -1698,7 +1698,7 @@ private static FunctionInfo CreateFunction(string name, ScriptBlock function, Fu { newValue = new ConfigurationInfo(name, function, options, context, helpFile, function.IsMetaConfiguration()); } - else + else { newValue = new FunctionInfo(name, function, options, context, helpFile); } diff --git a/src/System.Management.Automation/engine/hostifaces/Connection.cs b/src/System.Management.Automation/engine/hostifaces/Connection.cs index 3dfe3a497cc..a637655aeeb 100644 --- a/src/System.Management.Automation/engine/hostifaces/Connection.cs +++ b/src/System.Management.Automation/engine/hostifaces/Connection.cs @@ -1513,7 +1513,10 @@ internal PowerShell PopRunningPowerShell() if (count > 0) { - if (count == 1) { _baseRunningPowerShell = null; } + if (count == 1) + { + _baseRunningPowerShell = null; + } return _runningPowerShells.Pop(); } diff --git a/src/System.Management.Automation/engine/hostifaces/ConnectionBase.cs b/src/System.Management.Automation/engine/hostifaces/ConnectionBase.cs index 64ca4956e02..23daa3c8713 100644 --- a/src/System.Management.Automation/engine/hostifaces/ConnectionBase.cs +++ b/src/System.Management.Automation/engine/hostifaces/ConnectionBase.cs @@ -237,7 +237,11 @@ public override void OpenAsync() private void CoreOpen(bool syncCall) { bool etwEnabled = RunspaceEventSource.Log.IsEnabled(); - if (etwEnabled) RunspaceEventSource.Log.OpenRunspaceStart(); + if (etwEnabled) + { + RunspaceEventSource.Log.OpenRunspaceStart(); + } + lock (SyncRoot) { // Call fails if RunspaceState is not BeforeOpen. @@ -260,7 +264,10 @@ private void CoreOpen(bool syncCall) RaiseRunspaceStateEvents(); OpenHelper(syncCall); - if (etwEnabled) RunspaceEventSource.Log.OpenRunspaceStop(); + if (etwEnabled) + { + RunspaceEventSource.Log.OpenRunspaceStop(); + } #if LEGACYTELEMETRY // We report startup telemetry when opening the runspace - because this is the first time diff --git a/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs b/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs index e0d19c489c8..11ff5d01f54 100644 --- a/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs +++ b/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs @@ -306,7 +306,10 @@ internal static string GetMaxLines(string source, int maxLines) internal static List GetSuggestion(Runspace runspace) { - if (!(runspace is LocalRunspace localRunspace)) { return new List(); } + if (!(runspace is LocalRunspace localRunspace)) + { + return new List(); + } // Get the last value of $? bool questionMarkVariableValue = localRunspace.ExecutionContext.QuestionMarkVariableValue; diff --git a/src/System.Management.Automation/engine/hostifaces/InternalHost.cs b/src/System.Management.Automation/engine/hostifaces/InternalHost.cs index e9a4b0e86e3..450941b4b63 100644 --- a/src/System.Management.Automation/engine/hostifaces/InternalHost.cs +++ b/src/System.Management.Automation/engine/hostifaces/InternalHost.cs @@ -537,7 +537,10 @@ internal void SetHostRef(PSHost psHost) internal void RevertHostRef() { // nothing to revert if Host reference is not set. - if (!IsHostRefSet) { return; } + if (!IsHostRefSet) + { + return; + } _externalHostRef.Revert(); _internalUIRef.Revert(); diff --git a/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs b/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs index 476502c7e37..64c9e19516f 100644 --- a/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs +++ b/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs @@ -934,7 +934,10 @@ private void DoCloseHelper() private static void CloseOrDisconnectAllRemoteRunspaces(Func> getRunspaces) { List runspaces = getRunspaces(); - if (runspaces.Count == 0) { return; } + if (runspaces.Count == 0) + { + return; + } // whether the close of all remoterunspaces completed using (ManualResetEvent remoteRunspaceCloseCompleted = new ManualResetEvent(false)) @@ -959,7 +962,10 @@ private static void CloseOrDisconnectAllRemoteRunspaces(Func private void StopOrDisconnectAllJobs() { - if (JobRepository.Jobs.Count == 0) { return; } + if (JobRepository.Jobs.Count == 0) + { + return; + } List disconnectRunspaces = new List(); diff --git a/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs index 057439f4731..3e4c082e101 100644 --- a/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs @@ -1294,7 +1294,10 @@ static Encoding GetPathEncoding(string path) /// public void Dispose() { - if (_disposed) { return; } + if (_disposed) + { + return; + } // Wait for any pending output to be flushed to disk so that Stop-Transcript // can be trusted to immediately have all content from that session in the file) diff --git a/src/System.Management.Automation/engine/hostifaces/PSDataCollection.cs b/src/System.Management.Automation/engine/hostifaces/PSDataCollection.cs index 9f928eca21d..90512b51768 100644 --- a/src/System.Management.Automation/engine/hostifaces/PSDataCollection.cs +++ b/src/System.Management.Automation/engine/hostifaces/PSDataCollection.cs @@ -1548,7 +1548,10 @@ internal void DecrementRef() Dbg.Assert(_refCount > 0, "RefCount cannot be <= 0"); _refCount--; - if (_refCount != 0 && (!_blockingEnumerator || _refCount != 1)) return; + if (_refCount != 0 && (!_blockingEnumerator || _refCount != 1)) + { + return; + } // release threads blocked on waithandle _readWaitHandle?.Set(); diff --git a/src/System.Management.Automation/engine/hostifaces/PowerShellProcessInstance.cs b/src/System.Management.Automation/engine/hostifaces/PowerShellProcessInstance.cs index 076aee75ae6..5ab95041877 100644 --- a/src/System.Management.Automation/engine/hostifaces/PowerShellProcessInstance.cs +++ b/src/System.Management.Automation/engine/hostifaces/PowerShellProcessInstance.cs @@ -189,10 +189,18 @@ public void Dispose() private void Dispose(bool disposing) { - if (_isDisposed) return; + if (_isDisposed) + { + return; + } + lock (_syncObject) { - if (_isDisposed) return; + if (_isDisposed) + { + return; + } + _isDisposed = true; } diff --git a/src/System.Management.Automation/engine/interpreter/CallInstruction.cs b/src/System.Management.Automation/engine/interpreter/CallInstruction.cs index 88ff4bc1357..f7173c745ff 100644 --- a/src/System.Management.Automation/engine/interpreter/CallInstruction.cs +++ b/src/System.Management.Automation/engine/interpreter/CallInstruction.cs @@ -222,7 +222,11 @@ private static bool IndexIsNotReturnType(int index, MethodInfo target, Parameter private static CallInstruction SlowCreate(MethodInfo info, ParameterInfo[] pis) { List types = new List(); - if (!info.IsStatic) types.Add(info.DeclaringType); + if (!info.IsStatic) + { + types.Add(info.DeclaringType); + } + foreach (ParameterInfo pi in pis) { types.Add(pi.ParameterType); From 66a89826bbaa7bb35c2938c3afc7785c469dbaba Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Tue, 7 Mar 2023 14:18:16 -0800 Subject: [PATCH 416/779] Fix `PlainText` output to correctly remove Reset VT sequence w/o number (#19283) --- .../FormatAndOutput/common/StringDecorated.cs | 2 +- .../engine/Formatting/OutputRendering.Tests.ps1 | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/System.Management.Automation/FormatAndOutput/common/StringDecorated.cs b/src/System.Management.Automation/FormatAndOutput/common/StringDecorated.cs index 6fa725c574f..c76d5ebc50e 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/StringDecorated.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/StringDecorated.cs @@ -98,7 +98,7 @@ private string PlainText } // graphics/color mode ESC[1;2;...m - private const string GraphicsRegex = @"(\x1b\[\d+(;\d+)*m)"; + private const string GraphicsRegex = @"(\x1b\[\d*(;\d+)*m)"; // CSI escape sequences private const string CsiRegex = @"(\x1b\[\?\d+[hl])"; diff --git a/test/powershell/engine/Formatting/OutputRendering.Tests.ps1 b/test/powershell/engine/Formatting/OutputRendering.Tests.ps1 index 0784c7a1f29..18adcf6a8d8 100644 --- a/test/powershell/engine/Formatting/OutputRendering.Tests.ps1 +++ b/test/powershell/engine/Formatting/OutputRendering.Tests.ps1 @@ -81,11 +81,11 @@ Describe 'OutputRendering tests' -Tag 'CI' { } It 'ToString(OutputRendering) works correctly' { - $s = [System.Management.Automation.Internal.StringDecorated]::new($PSStyle.Foreground.Red + 'Hello') + $s = [System.Management.Automation.Internal.StringDecorated]::new($PSStyle.Foreground.Red + "Hello`e[m.") $s.IsDecorated | Should -BeTrue - $s.ToString() | Should -BeExactly "$($PSStyle.Foreground.Red)Hello" - $s.ToString([System.Management.Automation.OutputRendering]::ANSI) | Should -BeExactly "$($PSStyle.Foreground.Red)Hello" - $s.ToString([System.Management.Automation.OutputRendering]::PlainText) | Should -BeExactly 'Hello' + $s.ToString() | Should -BeExactly "$($PSStyle.Foreground.Red)Hello`e[m." + $s.ToString([System.Management.Automation.OutputRendering]::ANSI) | Should -BeExactly "$($PSStyle.Foreground.Red)Hello`e[m." + $s.ToString([System.Management.Automation.OutputRendering]::PlainText) | Should -BeExactly 'Hello.' { $s.ToString([System.Management.Automation.OutputRendering]::Host) } | Should -Throw -ErrorId 'ArgumentException' } } From 14d7bfee1d5950215acf861b7165a3231e07c77e Mon Sep 17 00:00:00 2001 From: "James Truher [MSFT]" Date: Wed, 8 Mar 2023 09:29:11 -0800 Subject: [PATCH 417/779] Telemetry improvements for tracking experimental feature optout (#18762) --- .../ExperimentalFeature.cs | 18 ++++++++- .../engine/NativeCommandProcessor.cs | 33 ++++++++++++++- .../utils/Telemetry.cs | 40 ++++++++++++++++++- 3 files changed, 87 insertions(+), 4 deletions(-) diff --git a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs index 58ba1aa1075..f7c2a73ba2a 100644 --- a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs +++ b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs @@ -157,6 +157,20 @@ static ExperimentalFeature() EnabledExperimentalFeatureNames = ProcessEnabledFeatures(enabledFeatures); } + /// + /// We need to notify which features were not enabled. + /// + private static void SendTelemetryForDeactivatedFeatures(ReadOnlyBag enabledFeatures) + { + foreach (var feature in EngineExperimentalFeatures) + { + if (!enabledFeatures.Contains(feature.Name)) + { + ApplicationInsightsTelemetry.SendTelemetryMetric(TelemetryType.ExperimentalEngineFeatureDeactivation, feature.Name); + } + } + } + /// /// Process the array of enabled feature names retrieved from configuration. /// Ignore invalid feature names and unavailable engine feature names, and @@ -198,7 +212,9 @@ private static ReadOnlyBag ProcessEnabledFeatures(string[] enabledFeatur } } - return new ReadOnlyBag(new HashSet(list, StringComparer.OrdinalIgnoreCase)); + ReadOnlyBag features = new(new HashSet(list, StringComparer.OrdinalIgnoreCase)); + SendTelemetryForDeactivatedFeatures(features); + return features; } /// diff --git a/src/System.Management.Automation/engine/NativeCommandProcessor.cs b/src/System.Management.Automation/engine/NativeCommandProcessor.cs index b825c024ef3..f34fc1987bb 100644 --- a/src/System.Management.Automation/engine/NativeCommandProcessor.cs +++ b/src/System.Management.Automation/engine/NativeCommandProcessor.cs @@ -18,6 +18,7 @@ using System.Text; using System.Threading; using System.Xml; +using Microsoft.PowerShell.Telemetry; using Dbg = System.Management.Automation.Diagnostics; namespace System.Management.Automation @@ -872,8 +873,36 @@ internal override void Complete() this.commandRuntime.PipelineProcessor.ExecutionFailed = true; - if (!ExperimentalFeature.IsEnabled(ExperimentalFeature.PSNativeCommandErrorActionPreferenceFeatureName) - || !Command.Context.GetBooleanPreference(SpecialVariables.PSNativeCommandUseErrorActionPreferenceVarPath, defaultPref: false, out _)) + // Feature is not enabled, so return + if (!ExperimentalFeature.IsEnabled(ExperimentalFeature.PSNativeCommandErrorActionPreferenceFeatureName)) + { + return; + } + + // We send telemetry information only if the feature is enabled. + // This shouldn't be done once, because it's a run-time check we should send telemetry every time. + // Report on the following conditions: + // - The variable is not present + // - The value is not set (variable is null) + // - The value is set to true or false + bool useDefaultSetting; + bool nativeErrorActionPreferenceSetting = Command.Context.GetBooleanPreference( + SpecialVariables.PSNativeCommandUseErrorActionPreferenceVarPath, + defaultPref: false, + out useDefaultSetting); + + // The variable is unset + if (useDefaultSetting) + { + ApplicationInsightsTelemetry.SendExperimentalUseData(ExperimentalFeature.PSNativeCommandErrorActionPreferenceFeatureName, "unset"); + return; + } + + // Send the value that was set. + ApplicationInsightsTelemetry.SendExperimentalUseData(ExperimentalFeature.PSNativeCommandErrorActionPreferenceFeatureName, nativeErrorActionPreferenceSetting.ToString()); + + // if it was explicitly set to false, return + if (!nativeErrorActionPreferenceSetting) { return; } diff --git a/src/System.Management.Automation/utils/Telemetry.cs b/src/System.Management.Automation/utils/Telemetry.cs index 6ae1a93d6de..88193cc03a9 100644 --- a/src/System.Management.Automation/utils/Telemetry.cs +++ b/src/System.Management.Automation/utils/Telemetry.cs @@ -38,12 +38,31 @@ internal enum TelemetryType /// WinCompatModuleLoad, + /// + /// Send telemetry for experimental module feature deactivation. + /// All experimental engine features will be have telemetry. + /// + ExperimentalEngineFeatureDeactivation, + /// /// Send telemetry for experimental module feature activation. /// All experimental engine features will be have telemetry. /// ExperimentalEngineFeatureActivation, + /// + /// Send telemetry for an experimental feature when use. + /// + ExperimentalFeatureUse, + + /// + /// Send telemetry for experimental module feature deactivation. + /// Experimental module features will send telemetry based on the module it is in. + /// If we send telemetry for the module, we will also do so for any experimental feature + /// in that module. + /// + ExperimentalModuleFeatureDeactivation, + /// /// Send telemetry for experimental module feature activation. /// Experimental module features will send telemetry based on the module it is in. @@ -126,7 +145,7 @@ public static class ApplicationInsightsTelemetry private static readonly HashSet s_knownModules; /// Gets a value indicating whether telemetry can be sent. - public static bool CanSendTelemetry { get; private set; } + public static bool CanSendTelemetry { get; private set; } = false; /// /// Initializes static members of the class. @@ -703,9 +722,12 @@ internal static void SendTelemetryMetric(TelemetryType metricId, string data) case TelemetryType.PowerShellCreate: case TelemetryType.RemoteSessionOpen: case TelemetryType.ExperimentalEngineFeatureActivation: + case TelemetryType.ExperimentalEngineFeatureDeactivation: + case TelemetryType.ExperimentalFeatureUse: s_telemetryClient.GetMetric(metricName, "uuid", "SessionId", "Detail").TrackValue(metricValue: 1.0, s_uniqueUserIdentifier, s_sessionId, data); break; case TelemetryType.ExperimentalModuleFeatureActivation: + case TelemetryType.ExperimentalModuleFeatureDeactivation: string experimentalFeatureName = GetExperimentalFeatureName(data); s_telemetryClient.GetMetric(metricName, "uuid", "SessionId", "Detail").TrackValue(metricValue: 1.0, s_uniqueUserIdentifier, s_sessionId, experimentalFeatureName); break; @@ -718,6 +740,21 @@ internal static void SendTelemetryMetric(TelemetryType metricId, string data) } } + /// + /// Send additional information about an experimental feature as it is used. + /// + /// The name of the experimental feature. + /// The details about the experimental feature use. + internal static void SendExperimentalUseData(string featureName, string detail) + { + if (!CanSendTelemetry) + { + return; + } + + ApplicationInsightsTelemetry.SendTelemetryMetric(TelemetryType.ExperimentalFeatureUse, string.Join(":", featureName, detail)); + } + // Get the experimental feature name. If we can report it, we'll return the name of the feature, otherwise, we'll return "anonymous" private static string GetExperimentalFeatureName(string featureNameToValidate) { @@ -779,6 +816,7 @@ internal static void SendPSCoreStartupTelemetry(string mode, double parametersUs properties.Add("UUID", s_uniqueUserIdentifier); properties.Add("GitCommitID", PSVersionInfo.GitCommitId); properties.Add("OSDescription", RuntimeInformation.OSDescription); + properties.Add("RuntimeIdentifier", RuntimeInformation.RuntimeIdentifier); properties.Add("OSChannel", string.IsNullOrEmpty(channel) ? "unknown" : channel); properties.Add("StartMode", string.IsNullOrEmpty(mode) ? "unknown" : mode); From 740e689e861a1f5bd3821cd4055b94459dad8c3b Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Wed, 8 Mar 2023 13:35:34 -0800 Subject: [PATCH 418/779] Add a mariner install script (#19294) * Add a mariner install script * Update install-powershell.sh * REVERT ME - switch to branch * Update install-powershell.sh * Update installpsh-debian.sh * Update installpsh-mariner.sh Add copyright section * Update install-ps.yml * Update tools/installpsh-mariner.sh --- .vsts-ci/install-ps.yml | 22 +++- tools/install-powershell.sh | 6 +- tools/installpsh-debian.sh | 2 +- tools/installpsh-mariner.sh | 215 ++++++++++++++++++++++++++++++++++++ 4 files changed, 238 insertions(+), 7 deletions(-) create mode 100644 tools/installpsh-mariner.sh diff --git a/.vsts-ci/install-ps.yml b/.vsts-ci/install-ps.yml index 72f42551162..de78f55ce2c 100644 --- a/.vsts-ci/install-ps.yml +++ b/.vsts-ci/install-ps.yml @@ -48,11 +48,23 @@ phases: jobName: InstallPowerShellUbuntu pool: ubuntu-latest verification: | - if ([Version]"$($PSVersionTable.PSVersion.Major).$($PSVersionTable.PSVersion.Minor).$($PSVersionTable.PSVersion.Patch)" -lt [version]"6.2.0") + if ([Version]"$($PSVersionTable.PSVersion.Major).$($PSVersionTable.PSVersion.Minor).$($PSVersionTable.PSVersion.Patch)" -lt [version]"7.3.0") { throw "powershell was not upgraded: $($PSVersionTable.PSVersion)" } +- template: templates/install-ps-phase.yml + parameters: + scriptName: sudo ./tools/install-powershell.sh + jobName: InstallPowerShellMariner2 + pool: ubuntu-latest + container: mcr.microsoft.com/powershell/test-deps:mariner-2.0 + verification: | + if ([Version]"$($PSVersionTable.PSVersion.Major).$($PSVersionTable.PSVersion.Minor).$($PSVersionTable.PSVersion.Patch)" -lt [version]"7.3.0") + { + throw "powershell was not upgraded: $($PSVersionTable.PSVersion)" + } + - template: templates/install-ps-phase.yml parameters: scriptName: sudo ./tools/install-powershell.sh @@ -60,7 +72,7 @@ phases: pool: ubuntu-latest container: pshorg/powershellcommunity-test-deps:amazonlinux-2.0 verification: | - if ([Version]"$($PSVersionTable.PSVersion.Major).$($PSVersionTable.PSVersion.Minor).$($PSVersionTable.PSVersion.Patch)" -lt [version]"6.2.0") + if ([Version]"$($PSVersionTable.PSVersion.Major).$($PSVersionTable.PSVersion.Minor).$($PSVersionTable.PSVersion.Patch)" -lt [version]"7.3.0") { throw "powershell was not upgraded: $($PSVersionTable.PSVersion)" } @@ -72,7 +84,7 @@ phases: pool: ubuntu-latest container: pshorg/powershellcommunity-test-deps:amazonlinux-2.0 verification: | - if ([Version]"$($PSVersionTable.PSVersion.Major).$($PSVersionTable.PSVersion.Minor).$($PSVersionTable.PSVersion.Patch)" -lt [version]"6.2.0") + if ([Version]"$($PSVersionTable.PSVersion.Major).$($PSVersionTable.PSVersion.Minor).$($PSVersionTable.PSVersion.Patch)" -lt [version]"7.3.0") { throw "powershell was not upgraded: $($PSVersionTable.PSVersion)" } @@ -105,7 +117,7 @@ phases: jobName: InstallPowerShellMacOS pool: macOS-latest verification: | - if ([Version]"$($PSVersionTable.PSVersion.Major).$($PSVersionTable.PSVersion.Minor).$($PSVersionTable.PSVersion.Patch)" -lt [version]"6.2.0") + if ([Version]"$($PSVersionTable.PSVersion.Major).$($PSVersionTable.PSVersion.Minor).$($PSVersionTable.PSVersion.Patch)" -lt [version]"7.3.0") { # The script does not upgrade on mac os https://github.com/PowerShell/PowerShell/issues/9322 Write-Warning "powershell was not upgraded: $($PSVersionTable.PSVersion)" @@ -124,7 +136,7 @@ phases: pool: ubuntu-latest verification: | Write-Verbose $PSVersionTable.PSVersion -verbose - if ([Version]"$($PSVersionTable.PSVersion.Major).$($PSVersionTable.PSVersion.Minor).$($PSVersionTable.PSVersion.Patch)" -lt [version]"7.0.0") + if ([Version]"$($PSVersionTable.PSVersion.Major).$($PSVersionTable.PSVersion.Minor).$($PSVersionTable.PSVersion.Patch)" -lt [version]"7.3.0") { throw "powershell was not upgraded: $($PSVersionTable.PSVersion)" } diff --git a/tools/install-powershell.sh b/tools/install-powershell.sh index f13e76665bf..dbe9206c460 100755 --- a/tools/install-powershell.sh +++ b/tools/install-powershell.sh @@ -95,6 +95,10 @@ install(){ else DistroBasedOn='redhat' fi + elif [ -f /etc/mariner-release ] ; then + DistroBasedOn='mariner' + PSUEDONAME=$( (sed s/.*\(// | sed s/\)//) < /etc/mariner-release ) + REV=$( (sed s/.*release\ // | sed s/\ .*//) < /etc/mariner-release ) elif [ -f /etc/mandrake-release ] ; then DistroBasedOn='mandrake' PSUEDONAME=$( (sed s/.*\(// | sed s/\)//) < /etc/mandrake-release ) @@ -135,7 +139,7 @@ install(){ case "$DistroBasedOn" in - redhat|debian|osx|suse|amazonlinux|gentoo) + redhat|debian|osx|suse|amazonlinux|gentoo|mariner) echo "Configuring PowerShell Environment for: $DistroBasedOn $DIST $REV" if [ -f "$SCRIPTFOLDER/installpsh-$DistroBasedOn.sh" ]; then #Script files were copied local - use them diff --git a/tools/installpsh-debian.sh b/tools/installpsh-debian.sh index 2c70f0a7cec..cc771dfd753 100755 --- a/tools/installpsh-debian.sh +++ b/tools/installpsh-debian.sh @@ -176,7 +176,7 @@ fi case $DISTRIB_ID in ubuntu|linuxmint) case $DISTRIB_RELEASE in - 20.04|18.04|16.10|16.04|15.10|14.04) + 22.04|20.04|18.04|16.10|16.04|15.10|14.04) curl https://packages.microsoft.com/config/ubuntu/$DISTRIB_RELEASE/prod.list | $SUDO tee /etc/apt/sources.list.d/microsoft.list ;; *) diff --git a/tools/installpsh-mariner.sh b/tools/installpsh-mariner.sh new file mode 100644 index 00000000000..9bb389fbda6 --- /dev/null +++ b/tools/installpsh-mariner.sh @@ -0,0 +1,215 @@ +#!/bin/bash +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +#Companion code for the blog https://cloudywindows.com +#call this code direction from the web with: +#bash <(wget -O - https://raw.githubusercontent.com/PowerShell/PowerShell/master/tools/installpsh-mariner.sh) ARGUMENTS +#bash <(curl -s https://raw.githubusercontent.com/PowerShell/PowerShell/master/tools/installpsh-mariner.sh) + +#Usage - if you do not have the ability to run scripts directly from the web, +# pull all files in this repo folder and execute, this script +# automatically prefers local copies of sub-scripts + +#Completely automated install requires a root account or sudo with a password requirement + +#Switches +# -includeide - installs VSCode and VSCode PowerShell extension (only relevant to machines with desktop environment) +# -interactivetesting - do a quick launch test of VSCode (only relevant when used with -includeide) +# -skip-sudo-check - use sudo without verifying its availability (this is required to run in the VSTS Hosted Linux Preview) +# -preview - installs the latest preview release of PowerShell side-by-side with any existing production releasesS + +#gitrepo paths are overrideable to run from your own fork or branch for testing or private distribution + + +VERSION="1.2.0" +gitreposubpath="PowerShell/PowerShell/master" +gitreposcriptroot="https://raw.githubusercontent.com/$gitreposubpath/tools" +thisinstallerdistro=mariner +repobased=false +gitscriptname="installpsh-mariner.psh" +pwshlink=/usr/bin/pwsh + +echo +echo "*** PowerShell Development Environment Installer $VERSION for $thisinstallerdistro" +echo "*** Original script is at: $gitreposcriptroot/$gitscriptname" +echo +echo "*** Arguments used: $*" +echo + +# Let's quit on interrupt of subcommands +trap ' + trap - INT # restore default INT handler + echo "Interrupted" + kill -s INT "$$" +' INT + +#Verify The Installer Choice (for direct runs of this script) +lowercase(){ + echo "$1" | tr "[:upper:]" "[:lower:]" +} + +OS=$(lowercase "$(uname)") +if [ "${OS}" == "windowsnt" ]; then + OS=windows + DistroBasedOn=windows +elif [ "${OS}" == "darwin" ]; then + OS=osx + DistroBasedOn=osx +else + OS=$(uname) + if [ "${OS}" == "SunOS" ] ; then + OS=solaris + DistroBasedOn=sunos + elif [ "${OS}" == "AIX" ] ; then + DistroBasedOn=aix + elif [ "${OS}" == "Linux" ] ; then + if [ -f /etc/redhat-release ] ; then + DistroBasedOn='redhat' + elif [ -f /etc/system-release ] ; then + DIST=$(sed s/\ release.*// < /etc/system-release) + if [[ $DIST == *"Amazon Linux"* ]] ; then + DistroBasedOn='amazonlinux' + else + DistroBasedOn='redhat' + fi + elif [ -f /etc/mariner-release ] ; then + DistroBasedOn='mariner' + elif [ -f /etc/mandrake-release ] ; then + DistroBasedOn='mandrake' + elif [ -f /etc/debian_version ] ; then + DistroBasedOn='debian' + fi + if [ -f /etc/UnitedLinux-release ] ; then + DIST="${DIST}[$( (tr "\n" ' ' | sed s/VERSION.*//) < /etc/UnitedLinux-release )]" + DistroBasedOn=unitedlinux + fi + osname=$(source /etc/os-release; echo $PRETTY_NAME) + if [[ $osname = *SUSE* ]]; then + DistroBasedOn='suse' + fi + OS=$(lowercase "$OS") + DistroBasedOn=$(lowercase "$DistroBasedOn") + fi +fi + +if [ "$DistroBasedOn" != "$thisinstallerdistro" ]; then + echo "*** This installer is only for $thisinstallerdistro and you are running $DistroBasedOn, please run \"$gitreposcriptroot\install-powershell.sh\" to see if your distro is supported AND to auto-select the appropriate installer if it is." + exit 1 +fi + +## Check requirements and prerequisites + +#Check for sudo if not root +if [[ "${CI}" == "true" ]]; then + echo "Running on CI (as determined by env var CI set to true), skipping SUDO check." + set -- "$@" '-skip-sudo-check' +fi + +SUDO='' +if (( EUID != 0 )); then + #Check that sudo is available + if [[ ("'$*'" =~ skip-sudo-check) && ("$(whereis sudo)" == *'/'* && "$(sudo -nv 2>&1)" != 'Sorry, user'*) ]]; then + SUDO='sudo' + else + echo "ERROR: You must either be root or be able to use sudo" >&2 + #exit 5 + fi +fi + +#Collect any variation details if required for this distro +# shellcheck disable=SC1091 +source /etc/os-release +MAJORREV=${VERSION_ID/\.*/} +#END Collect any variation details if required for this distro + +#If there are known incompatible versions of this distro, put the test, message and script exit here: +if [[ $ID == 'mariner' && $MAJORREV -lt 2 ]]; then + echo "mariner $VERSION_ID is not supported!" >&2 + exit 2 +fi + +#END Verify The Installer Choice + +echo +echo "*** Installing prerequisites for PowerShell..." +$SUDO tdnf install -y \ + icu \ + less \ + openssh-clients \ + ca-certificates \ + tar \ + curl \ + && tdnf clean all + +##END Check requirements and prerequisites + +echo +echo "*** Installing PowerShell for $DistroBasedOn..." + +echo "ATTENTION: As of version 1.2.0 this script no longer uses pre-releases unless the '-preview' switch is used" + +if [[ "'$*'" =~ preview ]] ; then + echo + echo "-preview was used, the latest preview release will be installed (side-by-side with your production release)" + release=$(curl https://api.github.com/repos/powershell/powershell/releases/latest | sed '/tag_name/!d' | sed s/\"tag_name\"://g | sed s/\"//g | sed s/v// | sed s/,//g | sed s/\ //g) + pwshlink=/usr/bin/pwsh-preview +else + echo "Finding the latest production release" + release=$(curl https://api.github.com/repos/PowerShell/PowerShell/releases | grep -Po '"tag_name":(\d*?,|.*?[^\\]",)' | grep -Po '\d+.\d+.\d+[\da-z.-]*' | grep -v '[a-z]' | sort | tail -n1) +fi + +#DIRECT DOWNLOAD +package=powershell-${release}-linux-x64.tar.gz +downloadurl=https://github.com/PowerShell/PowerShell/releases/download/v$release/$package + +echo "Destination file: $package" +echo "Source URL: $downloadurl" + +curl -L -o "$package" "$downloadurl" + +if [[ ! -r "$package" ]]; then + echo "ERROR: $package failed to download! Aborting..." >&2 + exit 1 +fi + +echo "Installing PowerShell to /opt/microsoft/powershell/$release in overwrite mode" +## Create the target folder where powershell will be placed +$SUDO mkdir -p "/opt/microsoft/powershell/$release" +## Expand powershell to the target folder +$SUDO tar zxf "$package" -C "/opt/microsoft/powershell/$release" + +## Change the mode of 'pwsh' to 'rwxr-xr-x' to allow execution +$SUDO chmod 755 "/opt/microsoft/powershell/$release/pwsh" +## Create the symbolic link that points to powershell +$SUDO ln -sfn "/opt/microsoft/powershell/$release/pwsh" $pwshlink + +## Add the symbolic link path to /etc/shells +if [ ! -f /etc/shells ] ; then + echo $pwshlink | $SUDO tee /etc/shells ; +else + grep -q "^${pwshlink}$" /etc/shells || echo $pwshlink | $SUDO tee --append /etc/shells > /dev/null ; +fi + +## Remove the downloaded package file +rm -f "$package" + +# shellcheck disable=SC2016 +pwsh -noprofile -c '"Congratulations! PowerShell is installed at $PSHOME. +Run `"pwsh`" to start a PowerShell session."' + +success=$? + +if [[ "$success" != 0 ]]; then + echo "ERROR: PowerShell failed to install!" >&2 + exit "$success" +fi + + +if [[ "$repobased" == true ]] ; then + echo "*** NOTE: Run your regular package manager update cycle to update PowerShell" +else + echo "*** NOTE: Re-run this script to update PowerShell" +fi + +echo "*** Install Complete" From db9257c4b831cf59f941bc48b8d4f1a6ccfda30a Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Wed, 8 Mar 2023 14:27:39 -0800 Subject: [PATCH 419/779] Always regenerate files wxs fragment (#19196) --- .gitignore | 3 + assets/wix/files.wxs | 3883 ----------------------------- assets/wix/patch-template.wxs | 24 - tools/packaging/boms/linux.json | 2418 ++++++++++++++++++ tools/packaging/boms/mac.json | 2194 ++++++++++++++++ tools/packaging/boms/windows.json | 3614 +++++++++++++++++++++++++++ tools/packaging/packaging.psd1 | 2 +- tools/packaging/packaging.psm1 | 556 ++--- 8 files changed, 8480 insertions(+), 4214 deletions(-) delete mode 100644 assets/wix/files.wxs delete mode 100644 assets/wix/patch-template.wxs create mode 100644 tools/packaging/boms/linux.json create mode 100644 tools/packaging/boms/mac.json create mode 100644 tools/packaging/boms/windows.json diff --git a/.gitignore b/.gitignore index 61ad9efb407..f8fac8a21bb 100644 --- a/.gitignore +++ b/.gitignore @@ -98,3 +98,6 @@ test/tools/Modules/Microsoft.PowerShell.NamedPipeConnection/ # Test generated startup profile StartupProfileData-NonInteractive + +# Ignore logfiles +logfile/* diff --git a/assets/wix/files.wxs b/assets/wix/files.wxs deleted file mode 100644 index a3e5932d134..00000000000 --- a/assets/wix/files.wxs +++ /dev/null @@ -1,3883 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/assets/wix/patch-template.wxs b/assets/wix/patch-template.wxs deleted file mode 100644 index bde47a93f4e..00000000000 --- a/assets/wix/patch-template.wxs +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - - - - - - - - - diff --git a/tools/packaging/boms/linux.json b/tools/packaging/boms/linux.json new file mode 100644 index 00000000000..b115e72b551 --- /dev/null +++ b/tools/packaging/boms/linux.json @@ -0,0 +1,2418 @@ +[ + { + "Pattern": "createdump", + "FileType": "NonProduct" + }, + { + "Pattern": "cs/Microsoft.CodeAnalysis.CSharp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "cs/Microsoft.CodeAnalysis.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "cs/System.Private.ServiceModel.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "cs/System.ServiceModel.Http.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "cs/System.ServiceModel.NetFramingBase.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "cs/System.ServiceModel.NetTcp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "cs/System.ServiceModel.Primitives.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "cs/System.Web.Services.Description.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "de/Microsoft.CodeAnalysis.CSharp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "de/Microsoft.CodeAnalysis.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "de/System.Private.ServiceModel.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "de/System.ServiceModel.Http.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "de/System.ServiceModel.NetFramingBase.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "de/System.ServiceModel.NetTcp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "de/System.ServiceModel.Primitives.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "de/System.Web.Services.Description.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "en-US/default.help.txt", + "FileType": "NonProduct" + }, + { + "Pattern": "es/Microsoft.CodeAnalysis.CSharp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "es/Microsoft.CodeAnalysis.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "es/System.Private.ServiceModel.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "es/System.ServiceModel.Http.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "es/System.ServiceModel.NetFramingBase.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "es/System.ServiceModel.NetTcp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "es/System.ServiceModel.Primitives.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "es/System.Web.Services.Description.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "fr/Microsoft.CodeAnalysis.CSharp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "fr/Microsoft.CodeAnalysis.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "fr/System.Private.ServiceModel.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "fr/System.ServiceModel.Http.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "fr/System.ServiceModel.NetFramingBase.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "fr/System.ServiceModel.NetTcp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "fr/System.ServiceModel.Primitives.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "fr/System.Web.Services.Description.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "it/Microsoft.CodeAnalysis.CSharp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "it/Microsoft.CodeAnalysis.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "it/System.Private.ServiceModel.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "it/System.ServiceModel.Http.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "it/System.ServiceModel.NetFramingBase.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "it/System.ServiceModel.NetTcp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "it/System.ServiceModel.Primitives.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "it/System.Web.Services.Description.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ja/Microsoft.CodeAnalysis.CSharp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ja/Microsoft.CodeAnalysis.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ja/System.Private.ServiceModel.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ja/System.ServiceModel.Http.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ja/System.ServiceModel.NetFramingBase.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ja/System.ServiceModel.NetTcp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ja/System.ServiceModel.Primitives.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ja/System.Web.Services.Description.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ko/Microsoft.CodeAnalysis.CSharp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ko/Microsoft.CodeAnalysis.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ko/System.Private.ServiceModel.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ko/System.ServiceModel.Http.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ko/System.ServiceModel.NetFramingBase.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ko/System.ServiceModel.NetTcp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ko/System.ServiceModel.Primitives.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ko/System.Web.Services.Description.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "libclrgc.so", + "FileType": "NonProduct" + }, + { + "Pattern": "libclrjit.so", + "FileType": "NonProduct" + }, + { + "Pattern": "libcoreclr.so", + "FileType": "NonProduct" + }, + { + "Pattern": "libcoreclrtraceptprovider.so", + "FileType": "NonProduct" + }, + { + "Pattern": "libhostfxr.so", + "FileType": "NonProduct" + }, + { + "Pattern": "libhostpolicy.so", + "FileType": "NonProduct" + }, + { + "Pattern": "libmscordaccore.so", + "FileType": "NonProduct" + }, + { + "Pattern": "libmscordbi.so", + "FileType": "NonProduct" + }, + { + "Pattern": "libpsl-native.so", + "FileType": "NonProduct" + }, + { + "Pattern": "libSystem.Globalization.Native.so", + "FileType": "NonProduct" + }, + { + "Pattern": "libSystem.IO.Compression.Native.so", + "FileType": "NonProduct" + }, + { + "Pattern": "libSystem.IO.Ports.Native.so", + "FileType": "NonProduct" + }, + { + "Pattern": "libSystem.Native.so", + "FileType": "NonProduct" + }, + { + "Pattern": "libSystem.Net.Security.Native.so", + "FileType": "NonProduct" + }, + { + "Pattern": "libSystem.Security.Cryptography.Native.OpenSsl.so", + "FileType": "NonProduct" + }, + { + "Pattern": "LICENSE.txt", + "FileType": "NonProduct" + }, + { + "Pattern": "Markdig.Signed.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.ApplicationInsights.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.Bcl.AsyncInterfaces.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.CodeAnalysis.CSharp.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.CodeAnalysis.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.CSharp.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.Extensions.ObjectPool.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.Management.Infrastructure.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.PowerShell.Commands.Management.pdb", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.PowerShell.Commands.Management.xml", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.PowerShell.Commands.Utility.pdb", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.PowerShell.Commands.Utility.xml", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.PowerShell.ConsoleHost.pdb", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.PowerShell.ConsoleHost.xml", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.PowerShell.MarkdownRender.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.PowerShell.SDK.pdb", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.PowerShell.SDK.xml", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.PowerShell.Security.pdb", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.PowerShell.Security.xml", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.VisualBasic.Core.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.VisualBasic.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.Win32.Primitives.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.Win32.Registry.AccessControl.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.Win32.Registry.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.Win32.SystemEvents.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/*.json", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/*.sha256", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/Microsoft.PowerShell.Archive/*.cat", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/Microsoft.PowerShell.Archive/*.ps?1", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/PackageManagement/*.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/PackageManagement/*.mof", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/PackageManagement/*.ps?1", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/PackageManagement/*.ps1xml", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/PowerShellGet/*.mfl", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/PowerShellGet/*.mof", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/PowerShellGet/*.ps?1", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/PowerShellGet/*.ps1xml", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/PSReadLine/*.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/PSReadLine/*.ps?1", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/PSReadLine/*.ps1", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/PSReadLine/*.ps1xml", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/PSReadLine/*.txt", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/ThreadJob/*.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/ThreadJob/*.psd1", + "FileType": "NonProduct" + }, + { + "Pattern": "mscorlib.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Namotion.Reflection.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "netstandard.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Newtonsoft.Json.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "NJsonSchema.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pl/Microsoft.CodeAnalysis.CSharp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pl/Microsoft.CodeAnalysis.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pl/System.Private.ServiceModel.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pl/System.ServiceModel.Http.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pl/System.ServiceModel.NetFramingBase.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pl/System.ServiceModel.NetTcp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pl/System.ServiceModel.Primitives.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pl/System.Web.Services.Description.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "powershell.config.json", + "FileType": "NonProduct" + }, + { + "Pattern": "pt-BR/Microsoft.CodeAnalysis.CSharp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pt-BR/Microsoft.CodeAnalysis.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pt-BR/System.Private.ServiceModel.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pt-BR/System.ServiceModel.Http.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pt-BR/System.ServiceModel.NetFramingBase.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pt-BR/System.ServiceModel.NetTcp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pt-BR/System.ServiceModel.Primitives.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pt-BR/System.Web.Services.Description.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pwsh.deps.json", + "FileType": "NonProduct" + }, + { + "Pattern": "pwsh.pdb", + "FileType": "NonProduct" + }, + { + "Pattern": "pwsh.runtimeconfig.json", + "FileType": "NonProduct" + }, + { + "Pattern": "pwsh.xml", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/Microsoft.CSharp.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/Microsoft.VisualBasic.Core.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/Microsoft.VisualBasic.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/Microsoft.Win32.Primitives.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/Microsoft.Win32.Registry.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/mscorlib.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/netstandard.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.AppContext.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Buffers.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Collections.Concurrent.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Collections.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Collections.Immutable.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Collections.NonGeneric.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Collections.Specialized.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.ComponentModel.Annotations.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.ComponentModel.DataAnnotations.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.ComponentModel.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.ComponentModel.EventBasedAsync.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.ComponentModel.Primitives.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.ComponentModel.TypeConverter.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Configuration.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Console.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Core.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Data.Common.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Data.DataSetExtensions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Data.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Diagnostics.Contracts.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Diagnostics.Debug.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Diagnostics.DiagnosticSource.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Diagnostics.FileVersionInfo.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Diagnostics.Process.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Diagnostics.StackTrace.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Diagnostics.TextWriterTraceListener.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Diagnostics.Tools.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Diagnostics.TraceSource.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Diagnostics.Tracing.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Drawing.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Drawing.Primitives.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Dynamic.Runtime.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Formats.Asn1.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Formats.Tar.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Globalization.Calendars.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Globalization.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Globalization.Extensions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.IO.Compression.Brotli.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.IO.Compression.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.IO.Compression.FileSystem.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.IO.Compression.ZipFile.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.IO.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.IO.FileSystem.AccessControl.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.IO.FileSystem.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.IO.FileSystem.DriveInfo.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.IO.FileSystem.Primitives.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.IO.FileSystem.Watcher.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.IO.IsolatedStorage.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.IO.MemoryMappedFiles.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.IO.Pipes.AccessControl.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.IO.Pipes.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.IO.UnmanagedMemoryStream.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Linq.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Linq.Expressions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Linq.Parallel.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Linq.Queryable.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Memory.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Net.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Net.Http.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Net.Http.Json.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Net.HttpListener.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Net.Mail.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Net.NameResolution.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Net.NetworkInformation.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Net.Ping.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Net.Primitives.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Net.Quic.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Net.Requests.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Net.Security.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Net.ServicePoint.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Net.Sockets.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Net.WebClient.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Net.WebHeaderCollection.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Net.WebProxy.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Net.WebSockets.Client.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Net.WebSockets.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Numerics.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Numerics.Vectors.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.ObjectModel.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Reflection.DispatchProxy.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Reflection.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Reflection.Emit.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Reflection.Emit.ILGeneration.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Reflection.Emit.Lightweight.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Reflection.Extensions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Reflection.Metadata.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Reflection.Primitives.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Reflection.TypeExtensions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Resources.Reader.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Resources.ResourceManager.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Resources.Writer.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Runtime.CompilerServices.Unsafe.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Runtime.CompilerServices.VisualC.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Runtime.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Runtime.Extensions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Runtime.Handles.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Runtime.InteropServices.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Runtime.InteropServices.JavaScript.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Runtime.InteropServices.RuntimeInformation.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Runtime.Intrinsics.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Runtime.Loader.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Runtime.Numerics.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Runtime.Serialization.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Runtime.Serialization.Formatters.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Runtime.Serialization.Json.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Runtime.Serialization.Primitives.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Runtime.Serialization.Xml.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Security.AccessControl.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Security.Claims.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Security.Cryptography.Algorithms.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Security.Cryptography.Cng.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Security.Cryptography.Csp.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Security.Cryptography.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Security.Cryptography.Encoding.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Security.Cryptography.OpenSsl.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Security.Cryptography.Primitives.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Security.Cryptography.X509Certificates.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Security.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Security.Principal.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Security.Principal.Windows.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Security.SecureString.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.ServiceModel.Web.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.ServiceProcess.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Text.Encoding.CodePages.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Text.Encoding.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Text.Encoding.Extensions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Text.Encodings.Web.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Text.Json.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Text.RegularExpressions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Threading.Channels.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Threading.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Threading.Overlapped.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Threading.Tasks.Dataflow.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Threading.Tasks.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Threading.Tasks.Extensions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Threading.Tasks.Parallel.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Threading.Thread.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Threading.ThreadPool.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Threading.Timer.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Transactions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Transactions.Local.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.ValueTuple.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Web.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Web.HttpUtility.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Windows.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Xml.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Xml.Linq.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Xml.ReaderWriter.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Xml.Serialization.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Xml.XDocument.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Xml.XmlDocument.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Xml.XmlSerializer.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Xml.XPath.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Xml.XPath.XDocument.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/WindowsBase.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ru/Microsoft.CodeAnalysis.CSharp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ru/Microsoft.CodeAnalysis.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ru/System.Private.ServiceModel.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ru/System.ServiceModel.Http.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ru/System.ServiceModel.NetFramingBase.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ru/System.ServiceModel.NetTcp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ru/System.ServiceModel.Primitives.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ru/System.Web.Services.Description.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/base.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/baseConditional.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/block.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/blockCommon.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/blockSoftware.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/command.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/conditionSet.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developer.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerCommand.rld", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerCommand.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerDscResource.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerManaged.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerManagedClass.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerManagedConstructor.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerManagedDelegate.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerManagedEnumeration.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerManagedEvent.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerManagedField.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerManagedInterface.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerManagedMethod.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerManagedNamespace.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerManagedOperator.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerManagedOverload.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerManagedProperty.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerManagedStructure.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerReference.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerStructure.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerXaml.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/endUser.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/hierarchy.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/inline.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/inlineCommon.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/inlineSoftware.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/inlineUi.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/ITPro.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/Maml_HTML_Style.xsl", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/Maml_HTML.xsl", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/Maml.rld", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/Maml.tbr", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/Maml.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/Maml.xsx", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/ManagedDeveloper.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/ManagedDeveloperStructure.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/ProviderHelp.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/shellExecute.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/structure.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/structureGlossary.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/structureList.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/structureProcedure.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/structureTable.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/structureTaskExecution.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/task.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/troubleshooting.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "System.AppContext.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Buffers.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.CodeDom.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Collections.Concurrent.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Collections.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Collections.Immutable.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Collections.NonGeneric.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Collections.Specialized.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ComponentModel.Annotations.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ComponentModel.Composition.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ComponentModel.Composition.Registration.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ComponentModel.DataAnnotations.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ComponentModel.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ComponentModel.EventBasedAsync.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ComponentModel.Primitives.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ComponentModel.TypeConverter.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Configuration.ConfigurationManager.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Configuration.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Console.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Core.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Data.Common.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Data.DataSetExtensions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Data.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Data.Odbc.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Data.OleDb.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Data.SqlClient.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Diagnostics.Contracts.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Diagnostics.Debug.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Diagnostics.DiagnosticSource.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Diagnostics.EventLog.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Diagnostics.FileVersionInfo.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Diagnostics.PerformanceCounter.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Diagnostics.Process.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Diagnostics.StackTrace.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Diagnostics.TextWriterTraceListener.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Diagnostics.Tools.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Diagnostics.TraceSource.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Diagnostics.Tracing.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.DirectoryServices.AccountManagement.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.DirectoryServices.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.DirectoryServices.Protocols.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Drawing.Common.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Drawing.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Drawing.Primitives.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Dynamic.Runtime.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Formats.Asn1.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Formats.Tar.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Globalization.Calendars.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Globalization.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Globalization.Extensions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.IO.Compression.Brotli.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.IO.Compression.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.IO.Compression.FileSystem.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.IO.Compression.ZipFile.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.IO.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.IO.FileSystem.AccessControl.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.IO.FileSystem.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.IO.FileSystem.DriveInfo.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.IO.FileSystem.Primitives.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.IO.FileSystem.Watcher.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.IO.IsolatedStorage.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.IO.MemoryMappedFiles.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.IO.Packaging.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.IO.Pipes.AccessControl.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.IO.Pipes.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.IO.Ports.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.IO.UnmanagedMemoryStream.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Linq.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Linq.Expressions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Linq.Parallel.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Linq.Queryable.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Management.Automation.pdb", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Management.Automation.xml", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Management.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Memory.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.Http.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.Http.Json.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.Http.WinHttpHandler.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.HttpListener.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.Mail.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.NameResolution.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.NetworkInformation.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.Ping.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.Primitives.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.Quic.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.Requests.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.Security.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.ServicePoint.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.Sockets.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.WebClient.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.WebHeaderCollection.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.WebProxy.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.WebSockets.Client.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.WebSockets.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Numerics.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Numerics.Vectors.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ObjectModel.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Private.CoreLib.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Private.DataContractSerialization.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Private.ServiceModel.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Private.Uri.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Private.Xml.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Private.Xml.Linq.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Reflection.Context.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Reflection.DispatchProxy.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Reflection.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Reflection.Emit.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Reflection.Emit.ILGeneration.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Reflection.Emit.Lightweight.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Reflection.Extensions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Reflection.Metadata.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Reflection.Primitives.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Reflection.TypeExtensions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Resources.Reader.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Resources.ResourceManager.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Resources.Writer.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Runtime.Caching.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Runtime.CompilerServices.Unsafe.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Runtime.CompilerServices.VisualC.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Runtime.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Runtime.Extensions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Runtime.Handles.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Runtime.InteropServices.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Runtime.InteropServices.JavaScript.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Runtime.InteropServices.RuntimeInformation.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Runtime.Intrinsics.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Runtime.Loader.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Runtime.Numerics.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Runtime.Serialization.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Runtime.Serialization.Formatters.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Runtime.Serialization.Json.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Runtime.Serialization.Primitives.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Runtime.Serialization.Xml.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Security.AccessControl.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Security.Claims.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Security.Cryptography.Algorithms.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Security.Cryptography.Cng.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Security.Cryptography.Csp.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Security.Cryptography.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Security.Cryptography.Encoding.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Security.Cryptography.OpenSsl.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Security.Cryptography.Pkcs.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Security.Cryptography.Primitives.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Security.Cryptography.ProtectedData.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Security.Cryptography.X509Certificates.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Security.Cryptography.Xml.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Security.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Security.Permissions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Security.Principal.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Security.Principal.Windows.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Security.SecureString.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ServiceModel.Duplex.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ServiceModel.Http.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ServiceModel.NetFramingBase.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ServiceModel.NetTcp.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ServiceModel.Primitives.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ServiceModel.Security.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ServiceModel.Syndication.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ServiceModel.Web.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ServiceProcess.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ServiceProcess.ServiceController.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Speech.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Text.Encoding.CodePages.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Text.Encoding.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Text.Encoding.Extensions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Text.Encodings.Web.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Text.Json.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Text.RegularExpressions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Threading.AccessControl.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Threading.Channels.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Threading.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Threading.Overlapped.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Threading.Tasks.Dataflow.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Threading.Tasks.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Threading.Tasks.Extensions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Threading.Tasks.Parallel.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Threading.Thread.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Threading.ThreadPool.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Threading.Timer.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Transactions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Transactions.Local.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ValueTuple.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Web.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Web.HttpUtility.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Web.Services.Description.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Windows.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Windows.Extensions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Xml.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Xml.Linq.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Xml.ReaderWriter.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Xml.Serialization.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Xml.XDocument.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Xml.XmlDocument.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Xml.XmlSerializer.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Xml.XPath.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Xml.XPath.XDocument.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ThirdPartyNotices.txt", + "FileType": "NonProduct" + }, + { + "Pattern": "tr/Microsoft.CodeAnalysis.CSharp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "tr/Microsoft.CodeAnalysis.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "tr/System.Private.ServiceModel.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "tr/System.ServiceModel.Http.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "tr/System.ServiceModel.NetFramingBase.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "tr/System.ServiceModel.NetTcp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "tr/System.ServiceModel.Primitives.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "tr/System.Web.Services.Description.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "WindowsBase.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hans/Microsoft.CodeAnalysis.CSharp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hans/Microsoft.CodeAnalysis.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hans/System.Private.ServiceModel.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hans/System.ServiceModel.Http.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hans/System.ServiceModel.NetFramingBase.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hans/System.ServiceModel.NetTcp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hans/System.ServiceModel.Primitives.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hans/System.Web.Services.Description.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hant/Microsoft.CodeAnalysis.CSharp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hant/Microsoft.CodeAnalysis.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hant/System.Private.ServiceModel.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hant/System.ServiceModel.Http.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hant/System.ServiceModel.NetFramingBase.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hant/System.ServiceModel.NetTcp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hant/System.ServiceModel.Primitives.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hant/System.Web.Services.Description.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.PowerShell.Commands.Management.dll", + "FileType": "Product" + }, + { + "Pattern": "Microsoft.PowerShell.Commands.Utility.dll", + "FileType": "Product" + }, + { + "Pattern": "Microsoft.PowerShell.ConsoleHost.dll", + "FileType": "Product" + }, + { + "Pattern": "Microsoft.PowerShell.SDK.dll", + "FileType": "Product" + }, + { + "Pattern": "Microsoft.PowerShell.Security.dll", + "FileType": "Product" + }, + { + "Pattern": "Modules/Microsoft.PowerShell.Host/Microsoft.PowerShell.Host.psd1", + "FileType": "Product" + }, + { + "Pattern": "Modules/Microsoft.PowerShell.Management/Microsoft.PowerShell.Management.psd1", + "FileType": "Product" + }, + { + "Pattern": "Modules/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.psd1", + "FileType": "Product" + }, + { + "Pattern": "pwsh", + "FileType": "Product" + }, + { + "Pattern": "pwsh.dll", + "FileType": "Product" + }, + { + "Pattern": "System.Management.Automation.dll", + "FileType": "Product" + } +] diff --git a/tools/packaging/boms/mac.json b/tools/packaging/boms/mac.json new file mode 100644 index 00000000000..28593cdd142 --- /dev/null +++ b/tools/packaging/boms/mac.json @@ -0,0 +1,2194 @@ +[ + { + "Pattern": "_manifest/spdx_2.2/manifest.spdx.json", + "FileType": "Product" + }, + { + "Pattern": "_manifest/spdx_2.2/manifest.spdx.json.sha256", + "FileType": "Product" + }, + { + "Pattern": "createdump", + "FileType": "NonProduct" + }, + { + "Pattern": "cs/Microsoft.CodeAnalysis.CSharp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "cs/Microsoft.CodeAnalysis.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "cs/System.Private.ServiceModel.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "cs/System.Web.Services.Description.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "de/Microsoft.CodeAnalysis.CSharp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "de/Microsoft.CodeAnalysis.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "de/System.Private.ServiceModel.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "de/System.Web.Services.Description.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "en-US/default.help.txt", + "FileType": "NonProduct" + }, + { + "Pattern": "es/Microsoft.CodeAnalysis.CSharp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "es/Microsoft.CodeAnalysis.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "es/System.Private.ServiceModel.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "es/System.Web.Services.Description.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "fr/Microsoft.CodeAnalysis.CSharp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "fr/Microsoft.CodeAnalysis.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "fr/System.Private.ServiceModel.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "fr/System.Web.Services.Description.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "it/Microsoft.CodeAnalysis.CSharp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "it/Microsoft.CodeAnalysis.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "it/System.Private.ServiceModel.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "it/System.Web.Services.Description.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ja/Microsoft.CodeAnalysis.CSharp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ja/Microsoft.CodeAnalysis.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ja/System.Private.ServiceModel.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ja/System.Web.Services.Description.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ko/Microsoft.CodeAnalysis.CSharp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ko/Microsoft.CodeAnalysis.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ko/System.Private.ServiceModel.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ko/System.Web.Services.Description.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "libclrgc.dylib", + "FileType": "NonProduct" + }, + { + "Pattern": "libclrjit.dylib", + "FileType": "NonProduct" + }, + { + "Pattern": "libcoreclr.dylib", + "FileType": "NonProduct" + }, + { + "Pattern": "libhostfxr.dylib", + "FileType": "NonProduct" + }, + { + "Pattern": "libhostpolicy.dylib", + "FileType": "NonProduct" + }, + { + "Pattern": "libmi.dylib", + "FileType": "NonProduct" + }, + { + "Pattern": "libmscordaccore.dylib", + "FileType": "NonProduct" + }, + { + "Pattern": "libmscordbi.dylib", + "FileType": "NonProduct" + }, + { + "Pattern": "libpsl-native.dylib", + "FileType": "NonProduct" + }, + { + "Pattern": "libpsrpclient.dylib", + "FileType": "NonProduct" + }, + { + "Pattern": "libSystem.Globalization.Native.dylib", + "FileType": "NonProduct" + }, + { + "Pattern": "libSystem.IO.Compression.Native.dylib", + "FileType": "NonProduct" + }, + { + "Pattern": "libSystem.IO.Ports.Native.dylib", + "FileType": "NonProduct" + }, + { + "Pattern": "libSystem.Native.dylib", + "FileType": "NonProduct" + }, + { + "Pattern": "libSystem.Net.Security.Native.dylib", + "FileType": "NonProduct" + }, + { + "Pattern": "libSystem.Security.Cryptography.Native.Apple.dylib", + "FileType": "NonProduct" + }, + { + "Pattern": "libSystem.Security.Cryptography.Native.OpenSsl.dylib", + "FileType": "NonProduct" + }, + { + "Pattern": "Markdig.Signed.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.ApplicationInsights.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.Bcl.AsyncInterfaces.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.CodeAnalysis.CSharp.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.CodeAnalysis.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.CSharp.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.Extensions.ObjectPool.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.Management.Infrastructure.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.PowerShell.Commands.Management.xml", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.PowerShell.Commands.Utility.xml", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.PowerShell.ConsoleHost.xml", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.PowerShell.MarkdownRender.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.PowerShell.SDK.xml", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.PowerShell.Security.xml", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.VisualBasic.Core.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.VisualBasic.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.Win32.Primitives.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.Win32.Registry.AccessControl.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.Win32.Registry.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.Win32.SystemEvents.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/*.json", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/*.sha256", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/Microsoft.PowerShell.Archive/*.cat", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/Microsoft.PowerShell.Archive/*.ps?1", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/PackageManagement/*.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/PackageManagement/*.mof", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/PackageManagement/*.ps?1", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/PackageManagement/*.ps1xml", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/PowerShellGet/*.mfl", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/PowerShellGet/*.mof", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/PowerShellGet/*.ps?1", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/PowerShellGet/*.ps1xml", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/PSReadLine/*.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/PSReadLine/*.ps?1", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/PSReadLine/*.ps1", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/PSReadLine/*.ps1xml", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/PSReadLine/*.txt", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/ThreadJob/*.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/ThreadJob/*.psd1", + "FileType": "NonProduct" + }, + { + "Pattern": "mscorlib.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Namotion.Reflection.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "netstandard.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Newtonsoft.Json.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "NJsonSchema.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pl/Microsoft.CodeAnalysis.CSharp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pl/Microsoft.CodeAnalysis.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pl/System.Private.ServiceModel.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pl/System.Web.Services.Description.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "psoptions.json", + "FileType": "NonProduct" + }, + { + "Pattern": "pt-BR/Microsoft.CodeAnalysis.CSharp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pt-BR/Microsoft.CodeAnalysis.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pt-BR/System.Private.ServiceModel.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pt-BR/System.Web.Services.Description.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pwsh.deps.json", + "FileType": "NonProduct" + }, + { + "Pattern": "pwsh.runtimeconfig.json", + "FileType": "NonProduct" + }, + { + "Pattern": "pwsh.xml", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/Microsoft.CSharp.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/Microsoft.VisualBasic.Core.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/Microsoft.VisualBasic.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/Microsoft.Win32.Primitives.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/Microsoft.Win32.Registry.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/mscorlib.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/netstandard.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.AppContext.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Buffers.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Collections.Concurrent.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Collections.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Collections.Immutable.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Collections.NonGeneric.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Collections.Specialized.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.ComponentModel.Annotations.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.ComponentModel.DataAnnotations.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.ComponentModel.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.ComponentModel.EventBasedAsync.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.ComponentModel.Primitives.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.ComponentModel.TypeConverter.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Configuration.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Console.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Core.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Data.Common.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Data.DataSetExtensions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Data.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Diagnostics.Contracts.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Diagnostics.Debug.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Diagnostics.DiagnosticSource.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Diagnostics.FileVersionInfo.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Diagnostics.Process.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Diagnostics.StackTrace.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Diagnostics.TextWriterTraceListener.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Diagnostics.Tools.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Diagnostics.TraceSource.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Diagnostics.Tracing.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Drawing.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Drawing.Primitives.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Dynamic.Runtime.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Formats.Asn1.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Formats.Tar.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Globalization.Calendars.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Globalization.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Globalization.Extensions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.IO.Compression.Brotli.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.IO.Compression.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.IO.Compression.FileSystem.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.IO.Compression.ZipFile.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.IO.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.IO.FileSystem.AccessControl.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.IO.FileSystem.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.IO.FileSystem.DriveInfo.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.IO.FileSystem.Primitives.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.IO.FileSystem.Watcher.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.IO.IsolatedStorage.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.IO.MemoryMappedFiles.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.IO.Pipes.AccessControl.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.IO.Pipes.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.IO.UnmanagedMemoryStream.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Linq.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Linq.Expressions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Linq.Parallel.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Linq.Queryable.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Memory.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Net.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Net.Http.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Net.Http.Json.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Net.HttpListener.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Net.Mail.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Net.NameResolution.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Net.NetworkInformation.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Net.Ping.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Net.Primitives.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Net.Quic.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Net.Requests.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Net.Security.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Net.ServicePoint.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Net.Sockets.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Net.WebClient.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Net.WebHeaderCollection.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Net.WebProxy.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Net.WebSockets.Client.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Net.WebSockets.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Numerics.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Numerics.Vectors.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.ObjectModel.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Reflection.DispatchProxy.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Reflection.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Reflection.Emit.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Reflection.Emit.ILGeneration.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Reflection.Emit.Lightweight.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Reflection.Extensions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Reflection.Metadata.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Reflection.Primitives.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Reflection.TypeExtensions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Resources.Reader.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Resources.ResourceManager.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Resources.Writer.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Runtime.CompilerServices.Unsafe.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Runtime.CompilerServices.VisualC.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Runtime.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Runtime.Extensions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Runtime.Handles.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Runtime.InteropServices.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Runtime.InteropServices.JavaScript.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Runtime.InteropServices.RuntimeInformation.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Runtime.Intrinsics.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Runtime.Loader.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Runtime.Numerics.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Runtime.Serialization.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Runtime.Serialization.Formatters.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Runtime.Serialization.Json.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Runtime.Serialization.Primitives.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Runtime.Serialization.Xml.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Security.AccessControl.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Security.Claims.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Security.Cryptography.Algorithms.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Security.Cryptography.Cng.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Security.Cryptography.Csp.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Security.Cryptography.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Security.Cryptography.Encoding.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Security.Cryptography.OpenSsl.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Security.Cryptography.Primitives.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Security.Cryptography.X509Certificates.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Security.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Security.Principal.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Security.Principal.Windows.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Security.SecureString.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.ServiceModel.Web.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.ServiceProcess.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Text.Encoding.CodePages.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Text.Encoding.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Text.Encoding.Extensions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Text.Encodings.Web.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Text.Json.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Text.RegularExpressions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Threading.Channels.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Threading.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Threading.Overlapped.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Threading.Tasks.Dataflow.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Threading.Tasks.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Threading.Tasks.Extensions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Threading.Tasks.Parallel.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Threading.Thread.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Threading.ThreadPool.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Threading.Timer.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Transactions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Transactions.Local.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.ValueTuple.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Web.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Web.HttpUtility.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Windows.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Xml.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Xml.Linq.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Xml.ReaderWriter.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Xml.Serialization.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Xml.XDocument.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Xml.XmlDocument.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Xml.XmlSerializer.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Xml.XPath.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Xml.XPath.XDocument.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/WindowsBase.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ru/Microsoft.CodeAnalysis.CSharp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ru/Microsoft.CodeAnalysis.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ru/System.Private.ServiceModel.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ru/System.Web.Services.Description.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/base.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/baseConditional.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/block.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/blockCommon.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/blockSoftware.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/command.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/conditionSet.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developer.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerCommand.rld", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerCommand.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerDscResource.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerManaged.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerManagedClass.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerManagedConstructor.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerManagedDelegate.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerManagedEnumeration.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerManagedEvent.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerManagedField.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerManagedInterface.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerManagedMethod.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerManagedNamespace.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerManagedOperator.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerManagedOverload.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerManagedProperty.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerManagedStructure.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerReference.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerStructure.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerXaml.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/endUser.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/hierarchy.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/inline.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/inlineCommon.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/inlineSoftware.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/inlineUi.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/ITPro.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/Maml_HTML_Style.xsl", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/Maml_HTML.xsl", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/Maml.rld", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/Maml.tbr", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/Maml.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/Maml.xsx", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/ManagedDeveloper.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/ManagedDeveloperStructure.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/ProviderHelp.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/shellExecute.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/structure.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/structureGlossary.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/structureList.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/structureProcedure.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/structureTable.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/structureTaskExecution.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/task.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/troubleshooting.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "System.AppContext.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Buffers.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.CodeDom.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Collections.Concurrent.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Collections.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Collections.Immutable.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Collections.NonGeneric.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Collections.Specialized.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ComponentModel.Annotations.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ComponentModel.Composition.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ComponentModel.Composition.Registration.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ComponentModel.DataAnnotations.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ComponentModel.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ComponentModel.EventBasedAsync.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ComponentModel.Primitives.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ComponentModel.TypeConverter.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Configuration.ConfigurationManager.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Configuration.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Console.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Core.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Data.Common.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Data.DataSetExtensions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Data.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Data.Odbc.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Data.OleDb.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Data.SqlClient.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Diagnostics.Contracts.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Diagnostics.Debug.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Diagnostics.DiagnosticSource.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Diagnostics.EventLog.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Diagnostics.FileVersionInfo.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Diagnostics.PerformanceCounter.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Diagnostics.Process.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Diagnostics.StackTrace.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Diagnostics.TextWriterTraceListener.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Diagnostics.Tools.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Diagnostics.TraceSource.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Diagnostics.Tracing.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.DirectoryServices.AccountManagement.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.DirectoryServices.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.DirectoryServices.Protocols.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Drawing.Common.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Drawing.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Drawing.Primitives.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Dynamic.Runtime.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Formats.Asn1.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Formats.Tar.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Globalization.Calendars.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Globalization.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Globalization.Extensions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.IO.Compression.Brotli.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.IO.Compression.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.IO.Compression.FileSystem.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.IO.Compression.ZipFile.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.IO.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.IO.FileSystem.AccessControl.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.IO.FileSystem.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.IO.FileSystem.DriveInfo.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.IO.FileSystem.Primitives.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.IO.FileSystem.Watcher.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.IO.IsolatedStorage.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.IO.MemoryMappedFiles.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.IO.Packaging.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.IO.Pipes.AccessControl.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.IO.Pipes.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.IO.Ports.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.IO.UnmanagedMemoryStream.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Linq.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Linq.Expressions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Linq.Parallel.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Linq.Queryable.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Management.Automation.xml", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Management.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Memory.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.Http.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.Http.Json.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.Http.WinHttpHandler.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.HttpListener.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.Mail.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.NameResolution.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.NetworkInformation.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.Ping.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.Primitives.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.Quic.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.Requests.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.Security.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.ServicePoint.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.Sockets.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.WebClient.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.WebHeaderCollection.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.WebProxy.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.WebSockets.Client.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.WebSockets.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Numerics.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Numerics.Vectors.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ObjectModel.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Private.CoreLib.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Private.DataContractSerialization.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Private.ServiceModel.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Private.Uri.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Private.Xml.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Private.Xml.Linq.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Reflection.Context.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Reflection.DispatchProxy.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Reflection.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Reflection.Emit.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Reflection.Emit.ILGeneration.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Reflection.Emit.Lightweight.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Reflection.Extensions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Reflection.Metadata.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Reflection.Primitives.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Reflection.TypeExtensions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Resources.Reader.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Resources.ResourceManager.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Resources.Writer.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Runtime.Caching.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Runtime.CompilerServices.Unsafe.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Runtime.CompilerServices.VisualC.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Runtime.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Runtime.Extensions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Runtime.Handles.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Runtime.InteropServices.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Runtime.InteropServices.JavaScript.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Runtime.InteropServices.RuntimeInformation.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Runtime.Intrinsics.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Runtime.Loader.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Runtime.Numerics.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Runtime.Serialization.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Runtime.Serialization.Formatters.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Runtime.Serialization.Json.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Runtime.Serialization.Primitives.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Runtime.Serialization.Xml.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Security.AccessControl.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Security.Claims.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Security.Cryptography.Algorithms.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Security.Cryptography.Cng.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Security.Cryptography.Csp.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Security.Cryptography.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Security.Cryptography.Encoding.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Security.Cryptography.OpenSsl.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Security.Cryptography.Pkcs.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Security.Cryptography.Primitives.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Security.Cryptography.ProtectedData.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Security.Cryptography.X509Certificates.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Security.Cryptography.Xml.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Security.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Security.Permissions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Security.Principal.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Security.Principal.Windows.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Security.SecureString.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ServiceModel.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ServiceModel.Duplex.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ServiceModel.Http.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ServiceModel.NetTcp.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ServiceModel.Primitives.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ServiceModel.Security.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ServiceModel.Syndication.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ServiceModel.Web.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ServiceProcess.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ServiceProcess.ServiceController.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Speech.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Text.Encoding.CodePages.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Text.Encoding.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Text.Encoding.Extensions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Text.Encodings.Web.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Text.Json.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Text.RegularExpressions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Threading.AccessControl.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Threading.Channels.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Threading.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Threading.Overlapped.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Threading.Tasks.Dataflow.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Threading.Tasks.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Threading.Tasks.Extensions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Threading.Tasks.Parallel.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Threading.Thread.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Threading.ThreadPool.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Threading.Timer.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Transactions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Transactions.Local.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ValueTuple.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Web.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Web.HttpUtility.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Web.Services.Description.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Windows.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Windows.Extensions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Xml.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Xml.Linq.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Xml.ReaderWriter.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Xml.Serialization.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Xml.XDocument.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Xml.XmlDocument.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Xml.XmlSerializer.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Xml.XPath.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Xml.XPath.XDocument.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ThirdPartyNotices.txt", + "FileType": "NonProduct" + }, + { + "Pattern": "tr/Microsoft.CodeAnalysis.CSharp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "tr/Microsoft.CodeAnalysis.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "tr/System.Private.ServiceModel.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "tr/System.Web.Services.Description.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "WindowsBase.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hans/Microsoft.CodeAnalysis.CSharp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hans/Microsoft.CodeAnalysis.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hans/System.Private.ServiceModel.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hans/System.Web.Services.Description.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hant/Microsoft.CodeAnalysis.CSharp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hant/Microsoft.CodeAnalysis.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hant/System.Private.ServiceModel.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hant/System.Web.Services.Description.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.PowerShell.Commands.Management.dll", + "FileType": "Product" + }, + { + "Pattern": "Microsoft.PowerShell.Commands.Utility.dll", + "FileType": "Product" + }, + { + "Pattern": "Microsoft.PowerShell.ConsoleHost.dll", + "FileType": "Product" + }, + { + "Pattern": "Microsoft.PowerShell.SDK.dll", + "FileType": "Product" + }, + { + "Pattern": "Microsoft.PowerShell.Security.dll", + "FileType": "Product" + }, + { + "Pattern": "Modules/Microsoft.PowerShell.Host/Microsoft.PowerShell.Host.psd1", + "FileType": "Product" + }, + { + "Pattern": "Modules/Microsoft.PowerShell.Management/Microsoft.PowerShell.Management.psd1", + "FileType": "Product" + }, + { + "Pattern": "Modules/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.psd1", + "FileType": "Product" + }, + { + "Pattern": "pwsh", + "FileType": "Product" + }, + { + "Pattern": "pwsh.dll", + "FileType": "Product" + }, + { + "Pattern": "System.Management.Automation.dll", + "FileType": "Product" + } +] diff --git a/tools/packaging/boms/windows.json b/tools/packaging/boms/windows.json new file mode 100644 index 00000000000..c1d06bb2c64 --- /dev/null +++ b/tools/packaging/boms/windows.json @@ -0,0 +1,3614 @@ +[ + { + "Pattern": "_manifest/spdx_2.2/manifest.spdx.json", + "FileType": "Product" + }, + { + "Pattern": "_manifest/spdx_2.2/manifest.spdx.json.sha256", + "FileType": "Product" + }, + { + "Pattern": "Accessibility.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "assets/Powershell_av_colors.ico", + "FileType": "Product" + }, + { + "Pattern": "assets/Powershell_avatar.ico", + "FileType": "Product" + }, + { + "Pattern": "assets/Powershell_black.ico", + "FileType": "Product" + }, + { + "Pattern": "assets/ps_black_32x32.ico", + "FileType": "Product" + }, + { + "Pattern": "clretwrc.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "clrgc.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "clrjit.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "coreclr.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "createdump.exe", + "FileType": "NonProduct" + }, + { + "Pattern": "cs/Microsoft.CodeAnalysis.CSharp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "cs/Microsoft.CodeAnalysis.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "cs/Microsoft.VisualBasic.Forms.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "cs/PresentationCore.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "cs/PresentationFramework.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "cs/PresentationUI.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "cs/ReachFramework.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "cs/System.Private.ServiceModel.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "cs/System.ServiceModel.Http.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "cs/System.ServiceModel.NetFramingBase.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "cs/System.ServiceModel.NetTcp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "cs/System.ServiceModel.Primitives.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "cs/System.Web.Services.Description.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "cs/System.Windows.Controls.Ribbon.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "cs/System.Windows.Forms.Design.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "cs/System.Windows.Forms.Primitives.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "cs/System.Windows.Forms.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "cs/System.Windows.Input.Manipulations.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "cs/System.Xaml.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "cs/UIAutomationClient.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "cs/UIAutomationClientSideProviders.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "cs/UIAutomationProvider.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "cs/UIAutomationTypes.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "cs/WindowsBase.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "cs/WindowsFormsIntegration.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "D3DCompiler_47_cor3.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "de/Microsoft.CodeAnalysis.CSharp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "de/Microsoft.CodeAnalysis.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "de/Microsoft.VisualBasic.Forms.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "de/PresentationCore.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "de/PresentationFramework.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "de/PresentationUI.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "de/ReachFramework.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "de/System.Private.ServiceModel.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "de/System.ServiceModel.Http.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "de/System.ServiceModel.NetFramingBase.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "de/System.ServiceModel.NetTcp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "de/System.ServiceModel.Primitives.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "de/System.Web.Services.Description.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "de/System.Windows.Controls.Ribbon.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "de/System.Windows.Forms.Design.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "de/System.Windows.Forms.Primitives.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "de/System.Windows.Forms.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "de/System.Windows.Input.Manipulations.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "de/System.Xaml.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "de/UIAutomationClient.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "de/UIAutomationClientSideProviders.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "de/UIAutomationProvider.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "de/UIAutomationTypes.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "de/WindowsBase.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "de/WindowsFormsIntegration.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "DirectWriteForwarder.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "en-US/default.help.txt", + "FileType": "NonProduct" + }, + { + "Pattern": "es/Microsoft.CodeAnalysis.CSharp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "es/Microsoft.CodeAnalysis.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "es/Microsoft.VisualBasic.Forms.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "es/PresentationCore.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "es/PresentationFramework.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "es/PresentationUI.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "es/ReachFramework.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "es/System.Private.ServiceModel.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "es/System.ServiceModel.Http.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "es/System.ServiceModel.NetFramingBase.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "es/System.ServiceModel.NetTcp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "es/System.ServiceModel.Primitives.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "es/System.Web.Services.Description.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "es/System.Windows.Controls.Ribbon.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "es/System.Windows.Forms.Design.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "es/System.Windows.Forms.Primitives.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "es/System.Windows.Forms.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "es/System.Windows.Input.Manipulations.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "es/System.Xaml.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "es/UIAutomationClient.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "es/UIAutomationClientSideProviders.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "es/UIAutomationProvider.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "es/UIAutomationTypes.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "es/WindowsBase.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "es/WindowsFormsIntegration.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "fr/Microsoft.CodeAnalysis.CSharp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "fr/Microsoft.CodeAnalysis.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "fr/Microsoft.VisualBasic.Forms.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "fr/PresentationCore.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "fr/PresentationFramework.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "fr/PresentationUI.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "fr/ReachFramework.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "fr/System.Private.ServiceModel.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "fr/System.ServiceModel.Http.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "fr/System.ServiceModel.NetFramingBase.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "fr/System.ServiceModel.NetTcp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "fr/System.ServiceModel.Primitives.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "fr/System.Web.Services.Description.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "fr/System.Windows.Controls.Ribbon.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "fr/System.Windows.Forms.Design.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "fr/System.Windows.Forms.Primitives.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "fr/System.Windows.Forms.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "fr/System.Windows.Input.Manipulations.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "fr/System.Xaml.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "fr/UIAutomationClient.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "fr/UIAutomationClientSideProviders.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "fr/UIAutomationProvider.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "fr/UIAutomationTypes.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "fr/WindowsBase.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "fr/WindowsFormsIntegration.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "getfilesiginforedist.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "getfilesiginforedistwrapper.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "hostfxr.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "hostpolicy.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "it/Microsoft.CodeAnalysis.CSharp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "it/Microsoft.CodeAnalysis.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "it/Microsoft.VisualBasic.Forms.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "it/PresentationCore.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "it/PresentationFramework.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "it/PresentationUI.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "it/ReachFramework.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "it/System.Private.ServiceModel.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "it/System.ServiceModel.Http.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "it/System.ServiceModel.NetFramingBase.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "it/System.ServiceModel.NetTcp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "it/System.ServiceModel.Primitives.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "it/System.Web.Services.Description.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "it/System.Windows.Controls.Ribbon.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "it/System.Windows.Forms.Design.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "it/System.Windows.Forms.Primitives.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "it/System.Windows.Forms.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "it/System.Windows.Input.Manipulations.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "it/System.Xaml.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "it/UIAutomationClient.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "it/UIAutomationClientSideProviders.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "it/UIAutomationProvider.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "it/UIAutomationTypes.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "it/WindowsBase.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "it/WindowsFormsIntegration.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ja/Microsoft.CodeAnalysis.CSharp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ja/Microsoft.CodeAnalysis.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ja/Microsoft.VisualBasic.Forms.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ja/PresentationCore.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ja/PresentationFramework.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ja/PresentationUI.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ja/ReachFramework.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ja/System.Private.ServiceModel.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ja/System.ServiceModel.Http.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ja/System.ServiceModel.NetFramingBase.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ja/System.ServiceModel.NetTcp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ja/System.ServiceModel.Primitives.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ja/System.Web.Services.Description.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ja/System.Windows.Controls.Ribbon.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ja/System.Windows.Forms.Design.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ja/System.Windows.Forms.Primitives.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ja/System.Windows.Forms.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ja/System.Windows.Input.Manipulations.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ja/System.Xaml.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ja/UIAutomationClient.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ja/UIAutomationClientSideProviders.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ja/UIAutomationProvider.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ja/UIAutomationTypes.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ja/WindowsBase.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ja/WindowsFormsIntegration.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ko/Microsoft.CodeAnalysis.CSharp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ko/Microsoft.CodeAnalysis.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ko/Microsoft.VisualBasic.Forms.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ko/PresentationCore.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ko/PresentationFramework.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ko/PresentationUI.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ko/ReachFramework.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ko/System.Private.ServiceModel.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ko/System.ServiceModel.Http.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ko/System.ServiceModel.NetFramingBase.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ko/System.ServiceModel.NetTcp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ko/System.ServiceModel.Primitives.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ko/System.Web.Services.Description.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ko/System.Windows.Controls.Ribbon.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ko/System.Windows.Forms.Design.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ko/System.Windows.Forms.Primitives.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ko/System.Windows.Forms.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ko/System.Windows.Input.Manipulations.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ko/System.Xaml.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ko/UIAutomationClient.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ko/UIAutomationClientSideProviders.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ko/UIAutomationProvider.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ko/UIAutomationTypes.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ko/WindowsBase.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ko/WindowsFormsIntegration.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "LICENSE.txt", + "FileType": "Product" + }, + { + "Pattern": "Markdig.Signed.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "mi.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.ApplicationInsights.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.Bcl.AsyncInterfaces.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.CodeAnalysis.CSharp.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.CodeAnalysis.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.CSharp.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.Extensions.ObjectPool.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.Management.Infrastructure.CimCmdlets.xml", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.Management.Infrastructure.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.Management.Infrastructure.Native.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.Management.Infrastructure.Native.Unmanaged.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.PowerShell.Commands.Diagnostics.xml", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.PowerShell.Commands.Management.xml", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.PowerShell.Commands.Utility.xml", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.PowerShell.ConsoleHost.xml", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.PowerShell.CoreCLR.Eventing.xml", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.PowerShell.GraphicalHost.dll.config", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.PowerShell.GraphicalHost.xml", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.PowerShell.MarkdownRender.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.PowerShell.SDK.xml", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.PowerShell.Security.xml", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.VisualBasic.Core.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.VisualBasic.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.VisualBasic.Forms.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.Win32.Primitives.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.Win32.Registry.AccessControl.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.Win32.Registry.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.Win32.SystemEvents.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.WSMan.Management.xml", + "FileType": "NonProduct" + }, + { + "Pattern": "Microsoft.WSMan.Runtime.xml", + "FileType": "NonProduct" + }, + { + "Pattern": "miutils.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/*.json", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/*.sha256", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/Microsoft.PowerShell.Archive/*.cat", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/Microsoft.PowerShell.Archive/*.ps?1", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/PackageManagement/*.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/PackageManagement/*.mof", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/PackageManagement/*.ps?1", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/PackageManagement/*.ps1xml", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/PowerShellGet/*.mfl", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/PowerShellGet/*.mof", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/PowerShellGet/*.ps?1", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/PowerShellGet/*.ps1xml", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/PSReadLine/*.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/PSReadLine/*.ps?1", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/PSReadLine/*.ps1", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/PSReadLine/*.ps1xml", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/PSReadLine/*.txt", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/ThreadJob/*.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/ThreadJob/*.psd1", + "FileType": "NonProduct" + }, + { + "Pattern": "mscordaccore_*.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "mscordaccore.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "mscordbi.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "mscorlib.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "mscorrc.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "msquic.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Namotion.Reflection.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "netstandard.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Newtonsoft.Json.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "NJsonSchema.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "PenImc_cor3.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pl/Microsoft.CodeAnalysis.CSharp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pl/Microsoft.CodeAnalysis.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pl/Microsoft.VisualBasic.Forms.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pl/PresentationCore.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pl/PresentationFramework.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pl/PresentationUI.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pl/ReachFramework.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pl/System.Private.ServiceModel.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pl/System.ServiceModel.Http.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pl/System.ServiceModel.NetFramingBase.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pl/System.ServiceModel.NetTcp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pl/System.ServiceModel.Primitives.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pl/System.Web.Services.Description.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pl/System.Windows.Controls.Ribbon.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pl/System.Windows.Forms.Design.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pl/System.Windows.Forms.Primitives.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pl/System.Windows.Forms.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pl/System.Windows.Input.Manipulations.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pl/System.Xaml.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pl/UIAutomationClient.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pl/UIAutomationClientSideProviders.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pl/UIAutomationProvider.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pl/UIAutomationTypes.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pl/WindowsBase.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pl/WindowsFormsIntegration.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "powershell.config.json", + "FileType": "NonProduct" + }, + { + "Pattern": "PowerShell.Core.Instrumentation.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "PowerShell.Core.Instrumentation.man", + "FileType": "NonProduct" + }, + { + "Pattern": "PowerShellCoreExecutionPolicy.adml", + "FileType": "NonProduct" + }, + { + "Pattern": "PowerShellCoreExecutionPolicy.admx", + "FileType": "NonProduct" + }, + { + "Pattern": "PresentationCore.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "PresentationFramework-SystemCore.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "PresentationFramework-SystemData.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "PresentationFramework-SystemDrawing.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "PresentationFramework-SystemXml.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "PresentationFramework-SystemXmlLinq.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "PresentationFramework.Aero.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "PresentationFramework.Aero2.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "PresentationFramework.AeroLite.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "PresentationFramework.Classic.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "PresentationFramework.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "PresentationFramework.Luna.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "PresentationFramework.Royale.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "PresentationNative_cor3.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "PresentationUI.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "preview/pwsh-preview.cmd", + "FileType": "NonProduct" + }, + { + "Pattern": "psoptions.json", + "FileType": "NonProduct" + }, + { + "Pattern": "pt-BR/Microsoft.CodeAnalysis.CSharp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pt-BR/Microsoft.CodeAnalysis.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pt-BR/Microsoft.VisualBasic.Forms.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pt-BR/PresentationCore.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pt-BR/PresentationFramework.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pt-BR/PresentationUI.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pt-BR/ReachFramework.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pt-BR/System.Private.ServiceModel.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pt-BR/System.ServiceModel.Http.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pt-BR/System.ServiceModel.NetFramingBase.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pt-BR/System.ServiceModel.NetTcp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pt-BR/System.ServiceModel.Primitives.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pt-BR/System.Web.Services.Description.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pt-BR/System.Windows.Controls.Ribbon.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pt-BR/System.Windows.Forms.Design.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pt-BR/System.Windows.Forms.Primitives.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pt-BR/System.Windows.Forms.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pt-BR/System.Windows.Input.Manipulations.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pt-BR/System.Xaml.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pt-BR/UIAutomationClient.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pt-BR/UIAutomationClientSideProviders.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pt-BR/UIAutomationProvider.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pt-BR/UIAutomationTypes.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pt-BR/WindowsBase.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pt-BR/WindowsFormsIntegration.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pwrshplugin.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "pwsh.deps.json", + "FileType": "NonProduct" + }, + { + "Pattern": "pwsh.runtimeconfig.json", + "FileType": "NonProduct" + }, + { + "Pattern": "pwsh.xml", + "FileType": "NonProduct" + }, + { + "Pattern": "ReachFramework.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/Microsoft.CSharp.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/Microsoft.VisualBasic.Core.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/Microsoft.VisualBasic.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/Microsoft.Win32.Primitives.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/Microsoft.Win32.Registry.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/mscorlib.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/netstandard.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.AppContext.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Buffers.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Collections.Concurrent.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Collections.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Collections.Immutable.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Collections.NonGeneric.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Collections.Specialized.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.ComponentModel.Annotations.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.ComponentModel.DataAnnotations.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.ComponentModel.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.ComponentModel.EventBasedAsync.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.ComponentModel.Primitives.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.ComponentModel.TypeConverter.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Configuration.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Console.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Core.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Data.Common.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Data.DataSetExtensions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Data.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Diagnostics.Contracts.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Diagnostics.Debug.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Diagnostics.DiagnosticSource.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Diagnostics.FileVersionInfo.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Diagnostics.Process.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Diagnostics.StackTrace.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Diagnostics.TextWriterTraceListener.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Diagnostics.Tools.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Diagnostics.TraceSource.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Diagnostics.Tracing.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Drawing.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Drawing.Primitives.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Dynamic.Runtime.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Formats.Asn1.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Formats.Tar.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Globalization.Calendars.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Globalization.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Globalization.Extensions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.IO.Compression.Brotli.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.IO.Compression.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.IO.Compression.FileSystem.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.IO.Compression.ZipFile.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.IO.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.IO.FileSystem.AccessControl.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.IO.FileSystem.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.IO.FileSystem.DriveInfo.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.IO.FileSystem.Primitives.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.IO.FileSystem.Watcher.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.IO.IsolatedStorage.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.IO.MemoryMappedFiles.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.IO.Pipes.AccessControl.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.IO.Pipes.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.IO.UnmanagedMemoryStream.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Linq.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Linq.Expressions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Linq.Parallel.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Linq.Queryable.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Memory.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Net.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Net.Http.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Net.Http.Json.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Net.HttpListener.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Net.Mail.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Net.NameResolution.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Net.NetworkInformation.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Net.Ping.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Net.Primitives.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Net.Quic.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Net.Requests.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Net.Security.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Net.ServicePoint.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Net.Sockets.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Net.WebClient.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Net.WebHeaderCollection.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Net.WebProxy.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Net.WebSockets.Client.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Net.WebSockets.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Numerics.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Numerics.Vectors.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.ObjectModel.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Reflection.DispatchProxy.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Reflection.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Reflection.Emit.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Reflection.Emit.ILGeneration.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Reflection.Emit.Lightweight.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Reflection.Extensions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Reflection.Metadata.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Reflection.Primitives.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Reflection.TypeExtensions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Resources.Reader.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Resources.ResourceManager.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Resources.Writer.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Runtime.CompilerServices.Unsafe.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Runtime.CompilerServices.VisualC.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Runtime.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Runtime.Extensions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Runtime.Handles.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Runtime.InteropServices.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Runtime.InteropServices.JavaScript.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Runtime.InteropServices.RuntimeInformation.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Runtime.Intrinsics.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Runtime.Loader.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Runtime.Numerics.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Runtime.Serialization.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Runtime.Serialization.Formatters.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Runtime.Serialization.Json.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Runtime.Serialization.Primitives.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Runtime.Serialization.Xml.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Security.AccessControl.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Security.Claims.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Security.Cryptography.Algorithms.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Security.Cryptography.Cng.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Security.Cryptography.Csp.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Security.Cryptography.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Security.Cryptography.Encoding.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Security.Cryptography.OpenSsl.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Security.Cryptography.Primitives.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Security.Cryptography.X509Certificates.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Security.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Security.Principal.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Security.Principal.Windows.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Security.SecureString.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.ServiceModel.Web.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.ServiceProcess.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Text.Encoding.CodePages.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Text.Encoding.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Text.Encoding.Extensions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Text.Encodings.Web.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Text.Json.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Text.RegularExpressions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Threading.Channels.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Threading.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Threading.Overlapped.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Threading.Tasks.Dataflow.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Threading.Tasks.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Threading.Tasks.Extensions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Threading.Tasks.Parallel.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Threading.Thread.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Threading.ThreadPool.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Threading.Timer.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Transactions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Transactions.Local.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.ValueTuple.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Web.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Web.HttpUtility.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Windows.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Xml.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Xml.Linq.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Xml.ReaderWriter.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Xml.Serialization.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Xml.XDocument.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Xml.XmlDocument.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Xml.XmlSerializer.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Xml.XPath.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/System.Xml.XPath.XDocument.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ref/WindowsBase.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ru/Microsoft.CodeAnalysis.CSharp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ru/Microsoft.CodeAnalysis.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ru/Microsoft.VisualBasic.Forms.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ru/PresentationCore.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ru/PresentationFramework.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ru/PresentationUI.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ru/ReachFramework.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ru/System.Private.ServiceModel.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ru/System.ServiceModel.Http.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ru/System.ServiceModel.NetFramingBase.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ru/System.ServiceModel.NetTcp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ru/System.ServiceModel.Primitives.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ru/System.Web.Services.Description.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ru/System.Windows.Controls.Ribbon.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ru/System.Windows.Forms.Design.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ru/System.Windows.Forms.Primitives.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ru/System.Windows.Forms.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ru/System.Windows.Input.Manipulations.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ru/System.Xaml.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ru/UIAutomationClient.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ru/UIAutomationClientSideProviders.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ru/UIAutomationProvider.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ru/UIAutomationTypes.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ru/WindowsBase.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ru/WindowsFormsIntegration.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/base.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/baseConditional.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/block.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/blockCommon.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/blockSoftware.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/command.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/conditionSet.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developer.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerCommand.rld", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerCommand.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerDscResource.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerManaged.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerManagedClass.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerManagedConstructor.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerManagedDelegate.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerManagedEnumeration.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerManagedEvent.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerManagedField.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerManagedInterface.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerManagedMethod.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerManagedNamespace.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerManagedOperator.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerManagedOverload.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerManagedProperty.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerManagedStructure.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerReference.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerStructure.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/developerXaml.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/endUser.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/hierarchy.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/inline.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/inlineCommon.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/inlineSoftware.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/inlineUi.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/ITPro.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/Maml_HTML_Style.xsl", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/Maml_HTML.xsl", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/Maml.rld", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/Maml.tbr", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/Maml.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/Maml.xsx", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/ManagedDeveloper.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/ManagedDeveloperStructure.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/ProviderHelp.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/shellExecute.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/structure.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/structureGlossary.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/structureList.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/structureProcedure.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/structureTable.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/structureTaskExecution.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/task.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "Schemas/PSMaml/troubleshooting.xsd", + "FileType": "NonProduct" + }, + { + "Pattern": "sni.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.AppContext.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Buffers.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.CodeDom.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Collections.Concurrent.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Collections.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Collections.Immutable.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Collections.NonGeneric.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Collections.Specialized.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ComponentModel.Annotations.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ComponentModel.Composition.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ComponentModel.Composition.Registration.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ComponentModel.DataAnnotations.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ComponentModel.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ComponentModel.EventBasedAsync.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ComponentModel.Primitives.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ComponentModel.TypeConverter.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Configuration.ConfigurationManager.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Configuration.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Console.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Core.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Data.Common.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Data.DataSetExtensions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Data.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Data.Odbc.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Data.OleDb.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Data.SqlClient.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Design.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Diagnostics.Contracts.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Diagnostics.Debug.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Diagnostics.DiagnosticSource.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Diagnostics.EventLog.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Diagnostics.EventLog.Messages.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Diagnostics.FileVersionInfo.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Diagnostics.PerformanceCounter.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Diagnostics.Process.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Diagnostics.StackTrace.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Diagnostics.TextWriterTraceListener.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Diagnostics.Tools.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Diagnostics.TraceSource.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Diagnostics.Tracing.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.DirectoryServices.AccountManagement.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.DirectoryServices.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.DirectoryServices.Protocols.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Drawing.Common.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Drawing.Design.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Drawing.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Drawing.Primitives.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Dynamic.Runtime.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Formats.Asn1.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Formats.Tar.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Globalization.Calendars.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Globalization.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Globalization.Extensions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.IO.Compression.Brotli.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.IO.Compression.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.IO.Compression.FileSystem.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.IO.Compression.Native.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.IO.Compression.ZipFile.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.IO.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.IO.FileSystem.AccessControl.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.IO.FileSystem.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.IO.FileSystem.DriveInfo.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.IO.FileSystem.Primitives.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.IO.FileSystem.Watcher.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.IO.IsolatedStorage.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.IO.MemoryMappedFiles.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.IO.Packaging.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.IO.Pipes.AccessControl.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.IO.Pipes.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.IO.Ports.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.IO.UnmanagedMemoryStream.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Linq.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Linq.Expressions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Linq.Parallel.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Linq.Queryable.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Management.Automation.xml", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Management.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Memory.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.Http.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.Http.Json.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.Http.WinHttpHandler.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.HttpListener.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.Mail.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.NameResolution.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.NetworkInformation.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.Ping.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.Primitives.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.Quic.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.Requests.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.Security.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.ServicePoint.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.Sockets.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.WebClient.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.WebHeaderCollection.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.WebProxy.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.WebSockets.Client.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Net.WebSockets.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Numerics.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Numerics.Vectors.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ObjectModel.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Printing.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Private.CoreLib.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Private.DataContractSerialization.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Private.ServiceModel.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Private.Uri.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Private.Xml.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Private.Xml.Linq.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Reflection.Context.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Reflection.DispatchProxy.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Reflection.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Reflection.Emit.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Reflection.Emit.ILGeneration.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Reflection.Emit.Lightweight.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Reflection.Extensions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Reflection.Metadata.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Reflection.Primitives.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Reflection.TypeExtensions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Resources.Extensions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Resources.Reader.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Resources.ResourceManager.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Resources.Writer.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Runtime.Caching.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Runtime.CompilerServices.Unsafe.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Runtime.CompilerServices.VisualC.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Runtime.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Runtime.Extensions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Runtime.Handles.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Runtime.InteropServices.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Runtime.InteropServices.JavaScript.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Runtime.InteropServices.RuntimeInformation.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Runtime.Intrinsics.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Runtime.Loader.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Runtime.Numerics.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Runtime.Serialization.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Runtime.Serialization.Formatters.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Runtime.Serialization.Json.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Runtime.Serialization.Primitives.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Runtime.Serialization.Xml.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Security.AccessControl.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Security.Claims.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Security.Cryptography.Algorithms.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Security.Cryptography.Cng.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Security.Cryptography.Csp.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Security.Cryptography.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Security.Cryptography.Encoding.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Security.Cryptography.OpenSsl.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Security.Cryptography.Pkcs.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Security.Cryptography.Primitives.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Security.Cryptography.ProtectedData.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Security.Cryptography.X509Certificates.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Security.Cryptography.Xml.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Security.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Security.Permissions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Security.Principal.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Security.Principal.Windows.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Security.SecureString.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ServiceModel.Duplex.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ServiceModel.Http.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ServiceModel.NetFramingBase.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ServiceModel.NetTcp.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ServiceModel.Primitives.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ServiceModel.Security.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ServiceModel.Syndication.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ServiceModel.Web.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ServiceProcess.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ServiceProcess.ServiceController.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Speech.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Text.Encoding.CodePages.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Text.Encoding.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Text.Encoding.Extensions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Text.Encodings.Web.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Text.Json.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Text.RegularExpressions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Threading.AccessControl.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Threading.Channels.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Threading.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Threading.Overlapped.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Threading.Tasks.Dataflow.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Threading.Tasks.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Threading.Tasks.Extensions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Threading.Tasks.Parallel.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Threading.Thread.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Threading.ThreadPool.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Threading.Timer.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Transactions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Transactions.Local.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.ValueTuple.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Web.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Web.HttpUtility.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Web.Services.Description.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Windows.Controls.Ribbon.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Windows.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Windows.Extensions.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Windows.Forms.Design.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Windows.Forms.Design.Editors.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Windows.Forms.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Windows.Forms.Primitives.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Windows.Input.Manipulations.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Windows.Presentation.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Xaml.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Xml.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Xml.Linq.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Xml.ReaderWriter.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Xml.Serialization.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Xml.XDocument.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Xml.XmlDocument.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Xml.XmlSerializer.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Xml.XPath.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "System.Xml.XPath.XDocument.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "ThirdPartyNotices.txt", + "FileType": "NonProduct" + }, + { + "Pattern": "tr/Microsoft.CodeAnalysis.CSharp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "tr/Microsoft.CodeAnalysis.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "tr/Microsoft.VisualBasic.Forms.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "tr/PresentationCore.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "tr/PresentationFramework.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "tr/PresentationUI.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "tr/ReachFramework.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "tr/System.Private.ServiceModel.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "tr/System.ServiceModel.Http.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "tr/System.ServiceModel.NetFramingBase.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "tr/System.ServiceModel.NetTcp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "tr/System.ServiceModel.Primitives.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "tr/System.Web.Services.Description.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "tr/System.Windows.Controls.Ribbon.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "tr/System.Windows.Forms.Design.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "tr/System.Windows.Forms.Primitives.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "tr/System.Windows.Forms.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "tr/System.Windows.Input.Manipulations.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "tr/System.Xaml.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "tr/UIAutomationClient.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "tr/UIAutomationClientSideProviders.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "tr/UIAutomationProvider.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "tr/UIAutomationTypes.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "tr/WindowsBase.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "tr/WindowsFormsIntegration.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "UIAutomationClient.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "UIAutomationClientSideProviders.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "UIAutomationProvider.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "UIAutomationTypes.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "vcruntime140_cor3.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "WindowsBase.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "WindowsFormsIntegration.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "wpfgfx_cor3.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hans/Microsoft.CodeAnalysis.CSharp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hans/Microsoft.CodeAnalysis.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hans/Microsoft.VisualBasic.Forms.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hans/PresentationCore.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hans/PresentationFramework.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hans/PresentationUI.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hans/ReachFramework.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hans/System.Private.ServiceModel.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hans/System.ServiceModel.Http.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hans/System.ServiceModel.NetFramingBase.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hans/System.ServiceModel.NetTcp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hans/System.ServiceModel.Primitives.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hans/System.Web.Services.Description.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hans/System.Windows.Controls.Ribbon.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hans/System.Windows.Forms.Design.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hans/System.Windows.Forms.Primitives.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hans/System.Windows.Forms.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hans/System.Windows.Input.Manipulations.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hans/System.Xaml.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hans/UIAutomationClient.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hans/UIAutomationClientSideProviders.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hans/UIAutomationProvider.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hans/UIAutomationTypes.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hans/WindowsBase.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hans/WindowsFormsIntegration.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hant/Microsoft.CodeAnalysis.CSharp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hant/Microsoft.CodeAnalysis.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hant/Microsoft.VisualBasic.Forms.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hant/PresentationCore.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hant/PresentationFramework.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hant/PresentationUI.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hant/ReachFramework.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hant/System.Private.ServiceModel.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hant/System.ServiceModel.Http.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hant/System.ServiceModel.NetFramingBase.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hant/System.ServiceModel.NetTcp.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hant/System.ServiceModel.Primitives.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hant/System.Web.Services.Description.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hant/System.Windows.Controls.Ribbon.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hant/System.Windows.Forms.Design.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hant/System.Windows.Forms.Primitives.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hant/System.Windows.Forms.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hant/System.Windows.Input.Manipulations.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hant/System.Xaml.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hant/UIAutomationClient.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hant/UIAutomationClientSideProviders.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hant/UIAutomationProvider.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hant/UIAutomationTypes.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hant/WindowsBase.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "zh-Hant/WindowsFormsIntegration.resources.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Install-PowerShellRemoting.ps1", + "FileType": "Product" + }, + { + "Pattern": "InstallPSCorePolicyDefinitions.ps1", + "FileType": "Product" + }, + { + "Pattern": "Microsoft.Management.Infrastructure.CimCmdlets.dll", + "FileType": "Product" + }, + { + "Pattern": "Microsoft.PowerShell.Commands.Diagnostics.dll", + "FileType": "Product" + }, + { + "Pattern": "Microsoft.PowerShell.Commands.Management.dll", + "FileType": "Product" + }, + { + "Pattern": "Microsoft.PowerShell.Commands.Utility.dll", + "FileType": "Product" + }, + { + "Pattern": "Microsoft.PowerShell.ConsoleHost.dll", + "FileType": "Product" + }, + { + "Pattern": "Microsoft.PowerShell.CoreCLR.Eventing.dll", + "FileType": "Product" + }, + { + "Pattern": "Microsoft.PowerShell.GraphicalHost.dll", + "FileType": "Product" + }, + { + "Pattern": "Microsoft.PowerShell.SDK.dll", + "FileType": "Product" + }, + { + "Pattern": "Microsoft.PowerShell.Security.dll", + "FileType": "Product" + }, + { + "Pattern": "Microsoft.WSMan.Management.dll", + "FileType": "Product" + }, + { + "Pattern": "Microsoft.WSMan.Runtime.dll", + "FileType": "Product" + }, + { + "Pattern": "Modules/CimCmdlets/CimCmdlets.psd1", + "FileType": "Product" + }, + { + "Pattern": "Modules/Microsoft.PowerShell.Diagnostics/Diagnostics.format.ps1xml", + "FileType": "Product" + }, + { + "Pattern": "Modules/Microsoft.PowerShell.Diagnostics/Event.format.ps1xml", + "FileType": "Product" + }, + { + "Pattern": "Modules/Microsoft.PowerShell.Diagnostics/GetEvent.types.ps1xml", + "FileType": "Product" + }, + { + "Pattern": "Modules/Microsoft.PowerShell.Diagnostics/Microsoft.PowerShell.Diagnostics.psd1", + "FileType": "Product" + }, + { + "Pattern": "Modules/Microsoft.PowerShell.Host/Microsoft.PowerShell.Host.psd1", + "FileType": "Product" + }, + { + "Pattern": "Modules/Microsoft.PowerShell.Management/Microsoft.PowerShell.Management.psd1", + "FileType": "Product" + }, + { + "Pattern": "Modules/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.psd1", + "FileType": "Product" + }, + { + "Pattern": "Modules/Microsoft.PowerShell.Security/Security.types.ps1xml", + "FileType": "Product" + }, + { + "Pattern": "Modules/Microsoft.WSMan.Management/Microsoft.WSMan.Management.psd1", + "FileType": "Product" + }, + { + "Pattern": "Modules/Microsoft.WSMan.Management/WSMan.format.ps1xml", + "FileType": "Product" + }, + { + "Pattern": "Modules/PSDiagnostics/PSDiagnostics.psd1", + "FileType": "Product" + }, + { + "Pattern": "Modules/PSDiagnostics/PSDiagnostics.psm1", + "FileType": "Product" + }, + { + "Pattern": "pwsh.dll", + "FileType": "Product" + }, + { + "Pattern": "pwsh.exe", + "FileType": "Product" + }, + { + "Pattern": "RegisterManifest.ps1", + "FileType": "Product" + }, + { + "Pattern": "RegisterMicrosoftUpdate.ps1", + "FileType": "Product" + }, + { + "Pattern": "System.Management.Automation.dll", + "FileType": "Product" + } +] diff --git a/tools/packaging/packaging.psd1 b/tools/packaging/packaging.psd1 index 6482b866d43..0053428a481 100644 --- a/tools/packaging/packaging.psd1 +++ b/tools/packaging/packaging.psd1 @@ -19,13 +19,13 @@ 'New-GlobalToolNupkgFromSource' 'New-ILNugetPackageSource' 'New-ILNugetPackageFromSource' - 'New-MSIPatch' 'New-PSBuildZip' 'New-PSSignedBuildZip' 'Publish-NugetToMyGet' 'Start-PSPackage' 'Test-PackageManifest' 'Update-PSSignedBuildFolder' + 'Test-Bom' ) RootModule = "packaging.psm1" RequiredModules = @("build") diff --git a/tools/packaging/packaging.psm1 b/tools/packaging/packaging.psm1 index 6eae9550503..d50bd83151f 100644 --- a/tools/packaging/packaging.psm1 +++ b/tools/packaging/packaging.psm1 @@ -2628,8 +2628,8 @@ function New-ReferenceAssembly Copy-Item -Path $sourceProjectFile -Destination $destProjectFile -Force -Verbose Copy-Item -Path $nugetConfigFile -Destination $projectFolder -Verbose - Write-Host "##vso[artifact.upload containerfolder=artifact;artifactname=artifact]$destProjectFile" - Write-Host "##vso[artifact.upload containerfolder=artifact;artifactname=artifact]$generatedSource" + Send-AzdoFile -Path $destProjectFile + Send-AzdoFile -Path $generatedSource $arguments = GenerateBuildArguments -AssemblyName $assemblyName -RefAssemblyVersion $RefAssemblyVersion -SnkFilePath $SnkFilePath -SMAReferencePath $SMAReferenceAssembly @@ -3191,142 +3191,6 @@ function Get-WixPath } -<# - .Synopsis - Creates a Windows installer MSP package from two MSIs and WIXPDB files - This only works on a Windows machine due to the usage of WiX. - .EXAMPLE - # This example shows how to produce a x64 patch from 6.0.2 to a theoretical 6.0.3 - cd $RootPathOfPowerShellRepo - Import-Module .\build.psm1; Import-Module .\tools\packaging\packaging.psm1 - New-MSIPatch -NewVersion 6.0.1 -BaselineMsiPath .\PowerShell-6.0.2-win-x64.msi -BaselineWixPdbPath .\PowerShell-6.0.2-win-x64.wixpdb -PatchMsiPath .\PowerShell-6.0.3-win-x64.msi -PatchWixPdbPath .\PowerShell-6.0.3-win-x64.wixpdb -#> -function New-MSIPatch -{ - param( - [Parameter(Mandatory, HelpMessage='The version of the fixed or patch MSI.')] - [ValidatePattern("^\d+\.\d+\.\d+$")] - [string] $NewVersion, - - [Parameter(Mandatory, HelpMessage='The path to the original or baseline MSI.')] - [ValidateNotNullOrEmpty()] - [ValidateScript( {(Test-Path $_) -and $_ -like '*.msi'})] - [string] $BaselineMsiPath, - - [Parameter(Mandatory, HelpMessage='The path to the WIXPDB for the original or baseline MSI.')] - [ValidateNotNullOrEmpty()] - [ValidateScript( {(Test-Path $_) -and $_ -like '*.wixpdb'})] - [string] $BaselineWixPdbPath, - - [Parameter(Mandatory, HelpMessage='The path to the fixed or patch MSI.')] - [ValidateNotNullOrEmpty()] - [ValidateScript( {(Test-Path $_) -and $_ -like '*.msi'})] - [string] $PatchMsiPath, - - [Parameter(Mandatory, HelpMessage='The path to the WIXPDB for the fixed or patch MSI.')] - [ValidateNotNullOrEmpty()] - [ValidateScript( {(Test-Path $_) -and $_ -like '*.wixpdb'})] - [string] $PatchWixPdbPath, - - [Parameter(HelpMessage='Path to the patch template WXS. Usually you do not need to specify this')] - [ValidateNotNullOrEmpty()] - [ValidateScript( {Test-Path $_})] - [string] $PatchWxsPath = "$RepoRoot\assets\wix\patch-template.wxs", - - [Parameter(HelpMessage='Produce a delta patch instead of a full patch. Usually not worth it.')] - [switch] $Delta - ) - - $mspName = (Split-Path -Path $PatchMsiPath -Leaf).Replace('.msi','.fullpath.msp') - $mspDeltaName = (Split-Path -Path $PatchMsiPath -Leaf).Replace('.msi','.deltapatch.msp') - - $wixPatchXmlPath = Join-Path $env:Temp "patch.wxs" - $wixBaselineOriginalPdbPath = Join-Path $env:Temp "baseline.original.wixpdb" - $wixBaselinePdbPath = Join-Path $env:Temp "baseline.wixpdb" - $wixBaselineBinariesPath = Join-Path $env:Temp "baseline.binaries" - $wixPatchOriginalPdbPath = Join-Path $env:Temp "patch.original.wixpdb" - $wixPatchPdbPath = Join-Path $env:Temp "patch.wixpdb" - $wixPatchBinariesPath = Join-Path $env:Temp "patch.binaries" - $wixPatchMstPath = Join-Path $env:Temp "patch.wixmst" - $wixPatchObjPath = Join-Path $env:Temp "patch.wixobj" - $wixPatchWixMspPath = Join-Path $env:Temp "patch.wixmsp" - - $filesToCleanup = @( - $wixPatchXmlPath - $wixBaselinePdbPath - $wixBaselineBinariesPath - $wixPatchPdbPath - $wixPatchBinariesPath - $wixPatchMstPath - $wixPatchObjPath - $wixPatchWixMspPath - $wixPatchOriginalPdbPath - $wixBaselineOriginalPdbPath - ) - - # cleanup from previous builds - Remove-Item -Path $filesToCleanup -Force -Recurse -ErrorAction SilentlyContinue - - # Melt changes the original, so copy before running melt - Copy-Item -Path $BaselineWixPdbPath -Destination $wixBaselineOriginalPdbPath -Force - Copy-Item -Path $PatchWixPdbPath -Destination $wixPatchOriginalPdbPath -Force - - [xml] $filesAssetXml = Get-Content -Raw -Path "$RepoRoot\assets\wix\files.wxs" - [xml] $patchTemplateXml = Get-Content -Raw -Path $PatchWxsPath - - # Update the patch version - $patchFamilyNode = $patchTemplateXml.Wix.Fragment.PatchFamily - $patchFamilyNode.SetAttribute('Version', $NewVersion) - - # get all the file components from the files.wxs - $components = $filesAssetXml.GetElementsByTagName('Component') - - # add all the file components to the patch - foreach($component in $components) - { - $id = $component.Id - $componentRef = $patchTemplateXml.CreateElement('ComponentRef','http://schemas.microsoft.com/wix/2006/wi') - $idAttribute = $patchTemplateXml.CreateAttribute('Id') - $idAttribute.Value = $id - $null = $componentRef.Attributes.Append($idAttribute) - $null = $patchFamilyNode.AppendChild($componentRef) - } - - # save the updated patch xml - $patchTemplateXml.Save($wixPatchXmlPath) - - $wixPaths = Get-WixPath - - Write-Log "Processing baseline msi..." - Start-NativeExecution -VerboseOutputOnError {& $wixPaths.wixMeltExePath -nologo $BaselineMsiPath $wixBaselinePdbPath -pdb $wixBaselineOriginalPdbPath -x $wixBaselineBinariesPath} - - Write-Log "Processing patch msi..." - Start-NativeExecution -VerboseOutputOnError {& $wixPaths.wixMeltExePath -nologo $PatchMsiPath $wixPatchPdbPath -pdb $wixPatchOriginalPdbPath -x $wixPatchBinariesPath} - - Write-Log "generate diff..." - Start-NativeExecution -VerboseOutputOnError {& $wixPaths.wixTorchExePath -nologo -p -xi $wixBaselinePdbPath $wixPatchPdbPath -out $wixPatchMstPath} - - Write-Log "Compiling patch..." - Start-NativeExecution -VerboseOutputOnError {& $wixPaths.wixCandleExePath -nologo $wixPatchXmlPath -out $wixPatchObjPath} - - Write-Log "Linking patch..." - Start-NativeExecution -VerboseOutputOnError {& $wixPaths.wixLightExePath -nologo $wixPatchObjPath -out $wixPatchWixMspPath} - - if ($Delta.IsPresent) - { - Write-Log "Generating delta msp..." - Start-NativeExecution -VerboseOutputOnError {& $wixPaths.wixPyroExePath -nologo $wixPatchWixMspPath -out $mspDeltaName -t RTM $wixPatchMstPath } - } - else - { - Write-Log "Generating full msp..." - Start-NativeExecution -VerboseOutputOnError {& $wixPaths.wixPyroExePath -nologo $wixPatchWixMspPath -out $mspName -t RTM $wixPatchMstPath } - } - - # cleanup temporary files - Remove-Item -Path $filesToCleanup -Force -Recurse -ErrorAction SilentlyContinue -} - <# .Synopsis Creates a Windows installer MSI package and assumes that the binaries are already built using 'Start-PSBuild'. @@ -3364,11 +3228,6 @@ function New-MSIPackage [ValidateScript( {Test-Path $_})] [string] $ProductWxsPath = "$RepoRoot\assets\wix\Product.wxs", - # File describing the MSI file components - [ValidateNotNullOrEmpty()] - [ValidateScript( {Test-Path $_})] - [string] $FilesWxsPath = "$RepoRoot\assets\wix\Files.wxs", - # File describing the MSI Package creation semantics [ValidateNotNullOrEmpty()] [ValidateScript({Test-Path $_})] @@ -3442,7 +3301,7 @@ function New-MSIPackage Write-Error -Message "Package already exists, use -Force to overwrite, path: $msiLocationPath" -ErrorAction Stop } - Write-Log "verifying no new files have been added or removed..." + Write-Log "Generating wxs file manifest..." $arguments = @{ IsPreview = $isPreview ProductSourcePath = $staging @@ -3457,26 +3316,17 @@ function New-MSIPackage $buildArguments = New-MsiArgsArray -Argument $arguments + Test-Bom -Path $staging -BomName windows Start-NativeExecution -VerboseOutputOnError { & $wixPaths.wixHeatExePath dir $staging -dr VersionFolder -cg ApplicationFiles -ag -sfrag -srd -scom -sreg -out $wixFragmentPath -var var.ProductSourcePath $buildArguments -v} - # We are verifying that the generated $wixFragmentPath and $FilesWxsPath are functionally the same - Test-FileWxs -FilesWxsPath $FilesWxsPath -HeatFilesWxsPath $wixFragmentPath -FileArchitecture $fileArchitecture - - if ($isPreview) - { - # Now that we know that the two are functionally the same, - # We only need to use $FilesWxsPath for release we want to be able to Path - # and two releases shouldn't have the same identifiers, - # so we use the generated one for preview - $FilesWxsPath = $wixFragmentPath + Send-AzdoFile -Path $wixFragmentPath - $wixObjFragmentPath = Join-Path $env:Temp "Fragment.wixobj" + $wixObjFragmentPath = Join-Path $env:Temp "Fragment.wixobj" - # cleanup any garbage on the system - Remove-Item -ErrorAction SilentlyContinue $wixObjFragmentPath -Force - } + # cleanup any garbage on the system + Remove-Item -ErrorAction SilentlyContinue $wixObjFragmentPath -Force - Start-MsiBuild -WxsFile $ProductWxsPath, $FilesWxsPath -ProductTargetArchitecture $ProductTargetArchitecture -Argument $arguments -MsiLocationPath $msiLocationPath -MsiPdbLocationPath $msiPdbLocationPath + Start-MsiBuild -WxsFile $ProductWxsPath, $wixFragmentPath -ProductTargetArchitecture $ProductTargetArchitecture -Argument $arguments -MsiLocationPath $msiLocationPath -MsiPdbLocationPath $msiPdbLocationPath Remove-Item -ErrorAction SilentlyContinue $wixFragmentPath -Force @@ -3848,153 +3698,6 @@ function New-MSIXPackage } } -# verify no files have been added or removed -# if so, write an error with details -function Test-FileWxs -{ - param - ( - # File describing the MSI file components from the asset folder - [ValidateNotNullOrEmpty()] - [ValidateScript( {Test-Path $_})] - [string] $FilesWxsPath = "$RepoRoot\assets\wix\Files.wxs", - - # File describing the MSI file components generated by heat - [ValidateNotNullOrEmpty()] - [ValidateScript( {Test-Path $_})] - [string] $HeatFilesWxsPath, - - [string] $FileArchitecture - ) - - # Update the fileArchitecture in our file to the actual value. Since, the heat file will have the actual value. - # Wix will update this automaticaly, but the output is not the same xml - $filesAssetString = (Get-Content -Raw -Path $FilesWxsPath).Replace('$(var.FileArchitecture)', $FileArchitecture) - - [xml] $filesAssetXml = $filesAssetString - [xml] $newFilesAssetXml = $filesAssetString - $xmlns=[System.Xml.XmlNamespaceManager]::new($newFilesAssetXml.NameTable) - $xmlns.AddNamespace('Wix','http://schemas.microsoft.com/wix/2006/wi') - - [xml] $heatFilesXml = Get-Content -Raw -Path $HeatFilesWxsPath - $assetFiles = $filesAssetXml.GetElementsByTagName('File') - $heatFiles = $heatFilesXml.GetElementsByTagName('File') - $heatNodesByFile = @{} - - # Index the list of files generated by heat - foreach($file in $heatFiles) - { - $heatNodesByFile.Add($file.Source, $file) - } - - # Index the files from the asset wxs - # and verify that no files have been removed. - $passed = $true - $indexedAssetFiles = @() - foreach($file in $assetFiles) - { - $name = $file.Source - if ($heatNodesByFile.Keys -inotcontains $name) - { - $passed = $false - Write-Warning "{$name} is no longer in product and should be removed from {$FilesWxsPath}" - $componentId = $file.ParentNode.Id - $componentXPath = '//Wix:Component[@Id="{0}"]' -f $componentId - $componentNode = Get-XmlNodeByXPath -XmlDoc $newFilesAssetXml -XmlNsManager $xmlns -XPath $componentXPath - if ($componentNode) - { - # Remove the Component - Remove-XmlElement -Element $componentNode -RemoveEmptyParents - # Remove teh ComponentRef - Remove-ComponentRefNode -Id $componentId -XmlDoc $newFilesAssetXml -XmlNsManager $xmlns - } - else - { - Write-Warning "Could not remove this node!" - } - } - $indexedAssetFiles += $name - } - - # verify that no files have been added. - foreach($file in $heatNodesByFile.Keys) - { - if ($indexedAssetFiles -inotcontains $file) - { - $passed = $false - $folder = Split-Path -Path $file - $heatNode = $heatNodesByFile[$file] - $compGroupNode = Get-ComponentGroupNode -XmlDoc $newFilesAssetXml -XmlNsManager $xmlns - $filesNode = Get-DirectoryNode -Node $heatNode -XmlDoc $newFilesAssetXml -XmlNsManager $xmlns - # Create new Component - $newComponent = New-XmlElement -XmlDoc $newFilesAssetXml -LocalName 'Component' -Node $filesNode -PassThru -NamespaceUri 'http://schemas.microsoft.com/wix/2006/wi' - $componentId = New-WixId -Prefix 'cmp' - New-XmlAttribute -XmlDoc $newFilesAssetXml -Element $newComponent -Name 'Id' -Value $componentId - # Crete new File in Component - $newFile = New-XmlElement -XmlDoc $newFilesAssetXml -LocalName 'File' -Node $newComponent -PassThru -NamespaceUri 'http://schemas.microsoft.com/wix/2006/wi' - New-XmlAttribute -XmlDoc $newFilesAssetXml -Element $newFile -Name 'Id' -Value (New-WixId -Prefix 'fil') - New-XmlAttribute -XmlDoc $newFilesAssetXml -Element $newFile -Name 'KeyPath' -Value "yes" - New-XmlAttribute -XmlDoc $newFilesAssetXml -Element $newFile -Name 'Source' -Value $file - # Create new ComponentRef - $newComponentRef = New-XmlElement -XmlDoc $newFilesAssetXml -LocalName 'ComponentRef' -Node $compGroupNode -PassThru -NamespaceUri 'http://schemas.microsoft.com/wix/2006/wi' - New-XmlAttribute -XmlDoc $newFilesAssetXml -Element $newComponentRef -Name 'Id' -Value $componentId - - Write-Warning "new file in {$folder} with name {$name} in a {$($filesNode.LocalName)} need to be added to {$FilesWxsPath}" - } - } - - # get all the file components from the files.wxs - $components = $filesAssetXml.GetElementsByTagName('Component') - $componentRefs = $filesAssetXml.GetElementsByTagName('ComponentRef') - - $componentComparison = Compare-Object -ReferenceObject $components.id -DifferenceObject $componentRefs.id - if ( $componentComparison.Count -gt 0){ - $passed = $false - Write-Verbose "Rebuilding componentRefs" -Verbose - - # add all the file components to the patch - foreach($component in $componentRefs) - { - $componentId = $component.Id - Write-Verbose "Removing $componentId" -Verbose - Remove-ComponentRefNode -Id $componentId -XmlDoc $newFilesAssetXml -XmlNsManager $xmlns - } - - # There is only one ComponentGroup. - # So we get all of them and select the first one. - $componentGroups = @($newFilesAssetXml.GetElementsByTagName('ComponentGroup')) - $componentGroup = $componentGroups[0] - - # add all the file components to the patch - foreach($component in $components) - { - $id = $component.Id - Write-Verbose "Adding $id" -Verbose - $newComponentRef = New-XmlElement -XmlDoc $newFilesAssetXml -LocalName 'ComponentRef' -Node $componentGroup -PassThru -NamespaceUri 'http://schemas.microsoft.com/wix/2006/wi' - New-XmlAttribute -XmlDoc $newFilesAssetXml -Element $newComponentRef -Name 'Id' -Value $id - } - } - - if (!$passed) - { - $newXmlFileName = Join-Path -Path $env:TEMP -ChildPath ([System.io.path]::GetRandomFileName() + '.wxs') - $newFilesAssetXml.Save($newXmlFileName) - $newXml = Get-Content -Raw $newXmlFileName - $newXml = $newXml -replace 'amd64', '$(var.FileArchitecture)' - $newXml = $newXml -replace 'x86', '$(var.FileArchitecture)' - $newXml | Out-File -FilePath $newXmlFileName -Encoding ascii - Write-Log -message "Updated xml saved to $newXmlFileName." - Write-Log -message "If component files were intentionally changed, such as due to moving to a newer .NET Core runtime, update '$FilesWxsPath' with the content from '$newXmlFileName'." - Write-Information -MessageData @{FilesWxsPath = $FilesWxsPath; NewFile = $newXmlFileName} -Tags 'PackagingWxs' - if ($env:TF_BUILD) - { - Write-Host "##vso[artifact.upload containerfolder=wix;artifactname=wix]$newXmlFileName" - } - - throw "Current files to not match {$FilesWxsPath}" - } -} - # Removes a ComponentRef node in the files.wxs Xml Doc function Remove-ComponentRefNode { @@ -5067,3 +4770,244 @@ function ConvertTo-PEOperatingSystem { } } } + +# Upload an artifact in Azure DevOps +# On other systems will just log where the file was placed +function Send-AzdoFile { + param ( + [parameter(Mandatory, ParameterSetName = 'contents')] + [string[]] + $Contents, + [parameter(Mandatory, ParameterSetName = 'contents')] + [string] + $LogName, + [parameter(Mandatory, ParameterSetName = 'path')] + [ValidateScript({ Test-Path -Path $_ })] + [string] + $Path + ) + + $logFolder = Join-Path -Path $PWD -ChildPath 'logfile' + if (!(Test-Path -Path $logFolder)) { + $null = New-Item -Path $logFolder -ItemType Directory + if ($IsMacOS -or $IsLinux) { + $null = chmod a+rw $logFolder + } + } + + if ($LogName) { + $effectiveLogName = $LogName + '.txt' + } else { + $effectiveLogName = Split-Path -Leaf -Path $Path + } + + $newName = ([System.Io.Path]::GetRandomFileName() + "-$effectiveLogName") + if ($Contents) { + $logFile = Join-Path -Path $logFolder -ChildPath $newName + + $Contents | Out-File -path $logFile -Encoding ascii + } else { + $logFile = Join-Path -Path $logFolder -ChildPath $newName + Copy-Item -Path $Path -Destination $logFile + } + + Write-Host "##vso[artifact.upload containerfolder=$newName;artifactname=$newName]$logFile" + Write-Verbose "Log file captured as $newName" -Verbose +} + +# Class used for serializing and deserialing a BOM into Json +class BomRecord { + hidden + [string] + $Pattern + + [ValidateSet("Product", "NonProduct")] + [string] + $FileType = "NonProduct" + + # Add methods to normalize Pattern to use `/` as the directory separator, + # but give a Pattern that is usable on the current platform + [string] + GetPattern () { + # Get the directory separator character for the current OS + $dirSeparator = [System.io.path]::DirectorySeparatorChar + + # If the directory separator character is not a slash, then replace all slashes in the pattern with the OS-specific directory separator character + if ($dirSeparator -ne '/') { + return $this.Pattern.replace('/', $dirSeparator) + } + + # If the directory separator character is a slash, then return the pattern as-is + return $this.Pattern + } + + [void] + SetPattern ([string]$Pattern) { + # Get the directory separator character for the current OS + $dirSeparator = [System.io.path]::DirectorySeparatorChar + + # If the directory separator character is not a slash, then replace all instances of the OS-specific directory separator character with slashes in the pattern + if ($dirSeparator -ne '/') { + $this.Pattern = $Pattern.Replace($dirSeparator, '/') + } + + # If the directory separator character is a slash, then set the pattern as-is + $this.Pattern = $Pattern + } +} + +# Verify a folder based on a BOM json. +# Use -Fix to update the BOM, Please review the file types. +function Test-Bom { + param( + [ValidateSet('mac','windows','linux')] + [string] + $BomName, + [ValidateScript({ Test-Path $_ })] + [string] + $Path, + [switch] + $Fix + ) + + Write-Log "verifying no unauthorized files have been added or removed..." + $root = (Resolve-Path $Path).ProviderPath -replace "\$([System.io.path]::DirectorySeparatorChar)$" + + $bomFile = Join-Path -Path $PSScriptRoot -ChildPath "Boms\$BomName.json" + Write-Verbose "bomFile: $bomFile" -Verbose + [BomRecord[]]$bomRecords = Get-Content -Path $bomFile | ConvertFrom-Json + $bomList = [System.Collections.Generic.List[BomRecord]]::new($bomRecords) + $noMatch = @() + $patternsUsed = @() + $files = @(Get-ChildItem -File -Path $Path -Recurse) + $totalFiles = $files.Count + $currentFileCount = 0 + + # Test each file if it is a match for a pattern in the BOM + # Add patters found to $patternsUsed + # Generate a list of new BOMs in $noMatch + $files | ForEach-Object { + [System.IO.FileInfo] $file = $_ + $fileName = $file.Name + $filePath = $file.FullName + $currentFileCount++ + + Write-Progress -Activity "Testing $BomName BOM" -PercentComplete (100*$currentFileCount/$totalFiles) -Status "Processing $fileName" + + $match = $false + [BomRecord] $matchingRecord = $null + + # Test file against each BOM that can still have a match + foreach ($bom in $bomList) { + $pattern = $root + [system.io.path]::DirectorySeparatorChar + $bom.GetPattern() + if ($filePath -like $pattern) { + $matchingRecord = $bom + $match = $true + if ($patternsUsed -notcontains $bom) { + $patternsUsed += $bom + } + break + } + } + + # if we didn't find a match, create a record in the noMatch list. + if (!$match) { + $relativePath = $_.FullName.Replace($root, "").Substring(1) + $isProduct = Test-IsProductFile -Path $relativePath + $fileType = "NonProduct" + if ($isProduct) { + $fileType = "Product" + } + + [BomRecord] $newBomRecord = [BomRecord] @{ + FileType = $fileType + } + + $newBomRecord.SetPattern([WildcardPattern]::Escape($_.FullName.Replace($root, "").Substring(1))) + $noMatch += $newBomRecord + } + elseif ($matchingRecord -and ![WildcardPattern]::ContainsWildcardCharacters($matchingRecord.GetPattern())) { + # remove any exact pattern which have been matched to speed up file processing, + # because they should not have additional matches. + if ($matchingRecord -is [BomRecord]) { + $null = $bomList.Remove($matchingRecord) + } else { + Write-Warning "Cannot remove matchingRecord $($matchingRecord.GetPattern())" + } + } + } + + Write-Progress -Activity "Testing $BomName BOM" -Completed + + Write-Verbose "$($noMatch.count) records need to be added to $bomFile" -Verbose + + # Create the complete new manifest + $currentRecords = @() + # Add BOMs for all the files that didn't match + $currentRecords += $noMatch + # Add BOMs for all the patterns that did match + $currentRecords += $patternsUsed + + # Generate a name for the updated BOM + $newBom = Join-Path -Path ([system.io.path]::GetTempPath()) -ChildPath ("${bomName}-" + [system.io.path]::GetRandomFileName() + "-bom.json") + + # Sort and serialize the BOM + $currentRecords | Sort-Object -Property FileType, Pattern | ConvertTo-Json | Out-File -Encoding utf8NoBOM -FilePath $newBom + + # check if we removed any BOMs + $needsRemoval = $bom | Where-Object { + $_ -notin $patternsUsed + } + + Write-Verbose "$($needsRemoval.count) need removal from $bomFile" -Verbose + + # If we added or removed BOMs, log the new file and throw + if ($noMatch.count -gt 0 -or $needsRemoval.Count -gt 0) { + Send-AzdoFile -Path $newBom + + # If -Fix was specified, update the original BOM + if ($Fix) { + Copy-Item -Path $newBom -Destination $bomFile -Force -Verbose + } + + throw "Please update $bomFile per the above instructions" + } +} + +# Simple test to guess if a file is a product file +function Test-IsProductFile { + param( + $Path + ) + + $itemsToCopy = @( + "*.ps1" + "*Microsoft.PowerShell*.dll" + "*Microsoft.PowerShell*.psd1" + "*Microsoft.PowerShell*.ps1xml" + "*Microsoft.WSMan.Management*.psd1" + "*Microsoft.WSMan.Management*.ps1xml" + "*pwsh.dll" + "*System.Management.Automation.dll" + "*PSDiagnostics.ps?1" + "*pwsh" + "*pwsh.exe" + ) + + $itemsToExclude = @( + # This package is retrieved from https://www.github.com/powershell/MarkdownRender + "*Microsoft.PowerShell.MarkdownRender.dll" + + ) + if ($Path -like $itemsToExclude) { + return $false + } + + foreach ($pattern in $itemsToCopy) { + if ($Path -like $pattern) { + return $true + } + } + + return $false +} From f00887303d053f7f7bc81d947043bdf236640f7a Mon Sep 17 00:00:00 2001 From: PowerShell Team Bot <69177312+pwshBot@users.noreply.github.com> Date: Wed, 8 Mar 2023 15:02:06 -0800 Subject: [PATCH 420/779] Update the cgmanifest (#19296) --- tools/cgmanifest.json | 62 ++++++++++++++++++------------------------- 1 file changed, 26 insertions(+), 36 deletions(-) diff --git a/tools/cgmanifest.json b/tools/cgmanifest.json index eb29d157d4d..bb6dcb5f360 100644 --- a/tools/cgmanifest.json +++ b/tools/cgmanifest.json @@ -1,5 +1,4 @@ { - "$schema": "https://json.schemastore.org/component-detection-manifest.json", "Registrations": [ { "Component": { @@ -26,7 +25,7 @@ "Type": "nuget", "Nuget": { "Name": "Markdig.Signed", - "Version": "0.30.4" + "Version": "0.31.0" } }, "DevelopmentDependency": false @@ -46,7 +45,7 @@ "Type": "nuget", "Nuget": { "Name": "Microsoft.Bcl.AsyncInterfaces", - "Version": "7.0.0" + "Version": "5.0.0" } }, "DevelopmentDependency": false @@ -66,7 +65,7 @@ "Type": "nuget", "Nuget": { "Name": "Microsoft.CodeAnalysis.Common", - "Version": "4.4.0" + "Version": "4.5.0" } }, "DevelopmentDependency": false @@ -76,21 +75,11 @@ "Type": "nuget", "Nuget": { "Name": "Microsoft.CodeAnalysis.CSharp", - "Version": "4.4.0" + "Version": "4.5.0" } }, "DevelopmentDependency": false }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "Microsoft.CodeAnalysis.NetAnalyzers", - "Version": "7.0.0" - } - }, - "DevelopmentDependency": true - }, { "Component": { "Type": "nuget", @@ -106,7 +95,7 @@ "Type": "nuget", "Nuget": { "Name": "Microsoft.Extensions.ObjectPool", - "Version": "7.0.3" + "Version": "5.0.10" } }, "DevelopmentDependency": false @@ -206,7 +195,7 @@ "Type": "nuget", "Nuget": { "Name": "Microsoft.Win32.Registry", - "Version": "5.0.0" + "Version": "4.7.0" } }, "DevelopmentDependency": false @@ -786,7 +775,7 @@ "Type": "nuget", "Nuget": { "Name": "System.Diagnostics.DiagnosticSource", - "Version": "7.0.0" + "Version": "7.0.1" } }, "DevelopmentDependency": false @@ -836,7 +825,7 @@ "Type": "nuget", "Nuget": { "Name": "System.DirectoryServices", - "Version": "7.0.0" + "Version": "7.0.1" } }, "DevelopmentDependency": false @@ -941,16 +930,6 @@ }, "DevelopmentDependency": false }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "System.Memory", - "Version": "4.5.5" - } - }, - "DevelopmentDependency": false - }, { "Component": { "Type": "nuget", @@ -1066,7 +1045,7 @@ "Type": "nuget", "Nuget": { "Name": "System.Reflection.Metadata", - "Version": "5.0.0" + "Version": "6.0.1" } }, "DevelopmentDependency": false @@ -1186,7 +1165,7 @@ "Type": "nuget", "Nuget": { "Name": "System.Security.Cryptography.Pkcs", - "Version": "7.0.0" + "Version": "7.0.1" } }, "DevelopmentDependency": false @@ -1196,7 +1175,7 @@ "Type": "nuget", "Nuget": { "Name": "System.Security.Cryptography.ProtectedData", - "Version": "7.0.0" + "Version": "7.0.1" } }, "DevelopmentDependency": false @@ -1206,7 +1185,7 @@ "Type": "nuget", "Nuget": { "Name": "System.Security.Cryptography.Xml", - "Version": "7.0.0" + "Version": "7.0.1" } }, "DevelopmentDependency": false @@ -1251,6 +1230,16 @@ }, "DevelopmentDependency": false }, + { + "Component": { + "Type": "nuget", + "Nuget": { + "Name": "System.ServiceModel.NetFramingBase", + "Version": "6.0.0-preview1.23060.3" + } + }, + "DevelopmentDependency": false + }, { "Component": { "Type": "nuget", @@ -1346,7 +1335,7 @@ "Type": "nuget", "Nuget": { "Name": "System.Threading.AccessControl", - "Version": "7.0.0" + "Version": "7.0.1" } }, "DevelopmentDependency": false @@ -1386,7 +1375,7 @@ "Type": "nuget", "Nuget": { "Name": "System.Web.Services.Description", - "Version": "4.10.0" + "Version": "4.9.0" } }, "DevelopmentDependency": false @@ -1401,5 +1390,6 @@ }, "DevelopmentDependency": false } - ] + ], + "$schema": "https://json.schemastore.org/component-detection-manifest.json" } From e9a25c7d2c069d99fb24e006ecafe603224e04e2 Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Thu, 9 Mar 2023 11:24:34 -0800 Subject: [PATCH 421/779] Use reference assemblies generated by dotnet (#19302) --- tools/packaging/packaging.psm1 | 55 ++++++++-------- .../azureDevOps/templates/nuget-pkg-sbom.yml | 66 ++++++++++++++++++- .../azureDevOps/templates/nuget.yml | 9 --- 3 files changed, 90 insertions(+), 40 deletions(-) diff --git a/tools/packaging/packaging.psm1 b/tools/packaging/packaging.psm1 index d50bd83151f..ce4d3a95fb1 100644 --- a/tools/packaging/packaging.psm1 +++ b/tools/packaging/packaging.psm1 @@ -2160,8 +2160,11 @@ Path to source folder containing Windows framework dependent assemblies. .PARAMETER LinuxFxdBinPath Path to source folder containing Linux framework dependent assemblies. -.PARAMETER GenAPIToolPath -Path to the GenAPI.exe tool. +.PARAMETER RefAssemblyPath +Path to the reference assemblies. + +.PARAMETER CGManifestPath +Path to the CGManifest.json file. #> function New-ILNugetPackageSource { @@ -2183,10 +2186,11 @@ function New-ILNugetPackageSource [string] $LinuxFxdBinPath, [Parameter(Mandatory = $true)] - [string] $GenAPIToolPath, + [string] $RefAssemblyPath, [Parameter(Mandatory = $true)] [string] $CGManifestPath + ) if (! $Environment.IsWindows) @@ -2219,11 +2223,8 @@ function New-ILNugetPackageSource "Microsoft.WSMan.Management.dll", "Microsoft.WSMan.Runtime.dll") - $refBinPath = New-TempFolder $SnkFilePath = "$RepoRoot\src\signing\visualstudiopublic.snk" - New-ReferenceAssembly -linux64BinPath $LinuxFxdBinPath -RefAssemblyDestinationPath $refBinPath -RefAssemblyVersion $PackageVersion -SnkFilePath $SnkFilePath -GenAPIToolPath $GenAPIToolPath - if (! (Test-Path $PackagePath)) { $null = New-Item -Path $PackagePath -ItemType Directory } @@ -2237,7 +2238,7 @@ function New-ILNugetPackageSource #region ref $refFolder = New-Item (Join-Path $filePackageFolder.FullName "ref/$script:netCoreRuntime") -ItemType Directory -Force - CopyReferenceAssemblies -assemblyName $fileBaseName -refBinPath $refBinPath -refNugetPath $refFolder -assemblyFileList $fileList -winBinPath $WinFxdBinPath + CopyReferenceAssemblies -assemblyName $fileBaseName -refBinPath $RefAssemblyPath -refNugetPath $refFolder -assemblyFileList $fileList -winBinPath $WinFxdBinPath #endregion ref $packageRuntimesFolderPath = $packageRuntimesFolder.FullName @@ -2302,10 +2303,6 @@ function New-ILNugetPackageSource } $deps = New-FileDependencies -FileBaseName $fileBaseName -PackageVersion $PackageVersion New-CGManifest -FilePath (Join-Path -Path $CGManifestPath -ChildPath "CGManifest.json") -Dependencies $deps - - if (Test-Path $refBinPath) { - Remove-Item $refBinPath -Recurse -Force -ErrorAction SilentlyContinue - } } <# @@ -2392,33 +2389,33 @@ function CopyReferenceAssemblies $supportedRefList = @( "Microsoft.PowerShell.Commands.Utility", - "Microsoft.PowerShell.ConsoleHost") + "Microsoft.PowerShell.ConsoleHost", + "Microsoft.PowerShell.Commands.Management", + "Microsoft.PowerShell.Commands.Security", + "System.Management.Automation" + ) switch ($assemblyName) { - { $_ -in $supportedRefList } { - $refDll = Join-Path -Path $refBinPath -ChildPath "$assemblyName.dll" - $refDoc = Join-Path -Path $refBinPath -ChildPath "$assemblyName.xml" - Copy-Item $refDll, $refDoc -Destination $refNugetPath -Force - Write-Log "Copied file '$refDll' and '$refDoc' to '$refNugetPath'" - } - "Microsoft.PowerShell.SDK" { foreach ($asmFileName in $assemblyFileList) { - $refFile = Join-Path -Path $refBinPath -ChildPath $asmFileName - if (Test-Path -Path $refFile) { - $refDoc = Join-Path -Path $refBinPath -ChildPath ([System.IO.Path]::ChangeExtension($asmFileName, "xml")) - Copy-Item $refFile, $refDoc -Destination $refNugetPath -Force - Write-Log "Copied file '$refFile' and '$refDoc' to '$refNugetPath'" + $fileName = [System.IO.Path]::GetFileNameWithoutExtension($asmFileName) + + if ($fileName -in $supportedRefList) { + $refFile = Join-Path -Path $refBinPath -ChildPath $asmFileName + if (Test-Path -Path $refFile) { + $refDoc = Join-Path -Path $refBinPath -ChildPath ([System.IO.Path]::ChangeExtension($asmFileName, "xml")) + Copy-Item $refFile, $refDoc -Destination $refNugetPath -Force + Write-Log "Copied file '$refFile' and '$refDoc' to '$refNugetPath'" + } } } } default { - $ref_SMA = Join-Path -Path $refBinPath -ChildPath System.Management.Automation.dll - $ref_doc = Join-Path -Path $refBinPath -ChildPath System.Management.Automation.xml - $self_ref_doc = Join-Path -Path $winBinPath -ChildPath "$assemblyName.xml" - Copy-Item $ref_SMA, $ref_doc, $self_ref_doc -Destination $refNugetPath -Force - Write-Log "Copied file '$ref_SMA' and '$ref_doc' to '$refNugetPath'" + $refDll = Join-Path -Path $refBinPath -ChildPath "$assemblyName.dll" + $refDoc = Join-Path -Path $refBinPath -ChildPath "$assemblyName.xml" + Copy-Item $refDll, $refDoc -Destination $refNugetPath -Force + Write-Log "Copied file '$refDll' and '$refDoc' to '$refNugetPath'" } } } diff --git a/tools/releaseBuild/azureDevOps/templates/nuget-pkg-sbom.yml b/tools/releaseBuild/azureDevOps/templates/nuget-pkg-sbom.yml index fe8c1a872ff..f0a033fd9e4 100644 --- a/tools/releaseBuild/azureDevOps/templates/nuget-pkg-sbom.yml +++ b/tools/releaseBuild/azureDevOps/templates/nuget-pkg-sbom.yml @@ -3,7 +3,6 @@ parameters: - name: PackagePath - name: WinFxdPath - name: LinuxFxdPath - - name: GenAPIToolPath - name: ListOfFiles type: object default: @@ -20,6 +19,69 @@ parameters: - System.Management.Automation.dll steps: + +- pwsh: | + Import-Module "$env:REPOROOT/build.psm1" -Force + Start-PSBootstrap + + $sharedModules = @('Microsoft.PowerShell.Commands.Management', + 'Microsoft.PowerShell.Commands.Utility', + 'Microsoft.PowerShell.ConsoleHost', + 'Microsoft.PowerShell.Security', + 'System.Management.Automation' + ) + + $winOnlyModules = @('Microsoft.Management.Infrastructure.CimCmdlets', + 'Microsoft.PowerShell.Commands.Diagnostics', + 'Microsoft.PowerShell.CoreCLR.Eventing', + 'Microsoft.WSMan.Management', + 'Microsoft.WSMan.Runtime' + ) + + $refAssemblyFolder = Join-Path '$(System.ArtifactsDirectory)' 'RefAssembly' + $null = New-Item -Path $refAssemblyFolder -Force -Verbose -Type Directory + + Start-PSBuild -Clean -Runtime linux-x64 -Configuration Release + + $sharedModules | Foreach-Object { + $refFile = Get-ChildItem -Path "$env:REPOROOT\src\$_\obj\Release\net8.0\refint\$_.dll" + Write-Verbose -Verbose "RefAssembly: $refFile" + Copy-Item -Path $refFile -Destination "$refAssemblyFolder\$_.dll" -Verbose + $refDoc = "$env:REPOROOT\src\$_\bin\Release\net8.0\$_.xml" + if (-not (Test-Path $refDoc)) { + Write-Warning "$refDoc not found" + Get-ChildItem -Path "$env:REPOROOT\src\$_\bin\Release\net8.0\" | Out-String | Write-Verbose -Verbose + } + else { + Copy-Item -Path $refDoc -Destination "$refAssemblyFolder\$_.xml" -Verbose + } + } + + Start-PSBuild -Clean -Runtime win7-x64 -Configuration Release + + $winOnlyModules | Foreach-Object { + $refFile = Get-ChildItem -Path "$env:REPOROOT\src\$_\obj\Release\net8.0\refint\*.dll" + Write-Verbose -Verbose 'RefAssembly: $refFile' + Copy-Item -Path $refFile -Destination "$refAssemblyFolder\$_.dll" -Verbose + $refDoc = "$env:REPOROOT\src\$_\bin\Release\net8.0\$_.xml" + if (-not (Test-Path $refDoc)) { + Write-Warning "$refDoc not found" + Get-ChildItem -Path "$env:REPOROOT\src\$_\bin\Release\net8.0" | Out-String | Write-Verbose -Verbose + } + else { + Copy-Item -Path $refDoc -Destination "$refAssemblyFolder\$_.xml" -Verbose + } + } + + Get-ChildItem $refAssemblyFolder -Recurse | Out-String | Write-Verbose -Verbose + + # Set RefAssemblyPath path variable + $vstsCommandString = "vso[task.setvariable variable=RefAssemblyPath]${refAssemblyFolder}" + Write-Host "sending " + $vstsCommandString + Write-Host "##$vstsCommandString" + + displayName: Build reference assemblies + - ${{ each value in parameters.ListOfFiles }}: - pwsh: | $FileName = '${{ value }}' @@ -45,7 +107,7 @@ steps: Import-Module -Name $env:REPOROOT\build.psm1 Import-Module -Name $env:REPOROOT\tools\packaging Find-DotNet - New-ILNugetPackageSource -File $FileName -PackagePath '${{ parameters.PackagePath }}' -PackageVersion '${{ parameters.PackageVersion }}' -WinFxdBinPath '${{ parameters.WinFxdPath }}' -LinuxFxdBinPath '${{ parameters.LinuxFxdPath }}' -GenAPIToolPath '${{ parameters.GenAPIToolPath }}' -CGManifestPath $CGManifestPath + New-ILNugetPackageSource -File $FileName -PackagePath '${{ parameters.PackagePath }}' -PackageVersion '${{ parameters.PackageVersion }}' -WinFxdBinPath '${{ parameters.WinFxdPath }}' -LinuxFxdBinPath '${{ parameters.LinuxFxdPath }}' -CGManifestPath $CGManifestPath -RefAssemblyPath $(RefAssemblyPath) displayName: 'Create NuGet Package source for single file' - template: Sbom.yml@ComplianceRepo diff --git a/tools/releaseBuild/azureDevOps/templates/nuget.yml b/tools/releaseBuild/azureDevOps/templates/nuget.yml index f38e1a718c6..269b6149645 100644 --- a/tools/releaseBuild/azureDevOps/templates/nuget.yml +++ b/tools/releaseBuild/azureDevOps/templates/nuget.yml @@ -106,14 +106,6 @@ jobs: archiveFilePatterns: '$(System.ArtifactsDirectory)/packages/powershell-*-linux-x64-fxdependent.tar.gz' destinationFolder: '$(linuxFxdPath)' - - task: PkgESInstallNuGetToolsPackage@10 - displayName: 'Install package Microsoft.DotNet.BuildTools.GenAPI' - inputs: - packageName: Microsoft.DotNet.BuildTools.GenAPI - packageVersion: '1.0.0-beta-00081' - packageSources: 'https://nuget.org/api/v2' - installRoot: '$(GenAPIToolPath)' - - template: SetVersionVariables.yml parameters: ReleaseTagVar: $(ReleaseTagVar) @@ -130,7 +122,6 @@ jobs: PackagePath: $(PackagePath) WinFxdPath: $(winFxdPath) LinuxFxdPath: $(linuxFxdPath) - GenAPIToolPath: $(GenAPIToolPath) - pwsh: | Get-ChildItem $(linuxFxdPath) From 7ec4af82ac45fe829174f6f52fb17379f1d78c29 Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Thu, 9 Mar 2023 14:27:20 -0800 Subject: [PATCH 422/779] Move workflows that create PRs to private repo (#19276) * Update PR creation workflows to use secret * Delete action.yml * Delete daily.yml * Delete exp-json.yml --- .github/workflows/daily.yml | 154 --------------------------------- .github/workflows/exp-json.yml | 149 ------------------------------- 2 files changed, 303 deletions(-) delete mode 100644 .github/workflows/daily.yml delete mode 100644 .github/workflows/exp-json.yml diff --git a/.github/workflows/daily.yml b/.github/workflows/daily.yml deleted file mode 100644 index dbc85f6ee5b..00000000000 --- a/.github/workflows/daily.yml +++ /dev/null @@ -1,154 +0,0 @@ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT license. - -name: PowerShell Daily -on: - workflow_dispatch: - schedule: - # At 13:00 UTC every day. - - cron: '0 13 * * *' - -defaults: - run: - shell: pwsh - -env: - DOTNET_CLI_TELEMETRY_OPTOUT: 1 - POWERSHELL_TELEMETRY_OPTOUT: 1 - -permissions: - contents: read - -jobs: - update-dotnet-preview: - permissions: - contents: write # for peter-evans/create-pull-request to create branch - pull-requests: write # for peter-evans/create-pull-request to create a PR - name: Update .NET preview - timeout-minutes: 15 - runs-on: windows-latest - if: github.repository == 'PowerShell/PowerShell' - steps: - - name: Checkout - uses: actions/checkout@v3 - - name: Sync tags - run: | - git fetch --prune --unshallow --tags - - name: Execute Update .NET script - run: | - Import-Module ./.github/workflows/GHWorkflowHelper - $currentVersion = (Get-Content .\global.json | ConvertFrom-Json).sdk.version - Set-GWVariable -Name OLD_VERSION -Value $currentVersion - - ./tools/UpdateDotnetRuntime.ps1 -UpdateMSIPackaging - $newVersion = (Get-Content .\global.json | ConvertFrom-Json).sdk.version - Set-GWVariable -Name NEW_VERSION -Value $newVersion - - if ($currentVersion -ne $newVersion) { - Set-GWVariable -Name CREATE_PR -Value 'true' - } - - name: Microsoft Teams Notifier - uses: skitionek/notify-microsoft-teams@master - if: failure() - with: - webhook_url: ${{ secrets.PS_BUILD_TEAMS_CHANNEL }} - overwrite: "{title: `Failure in .github/daily.yml updating .NET build. Look at ${workflow_link}`}" - - name: Create Pull Request - uses: peter-evans/create-pull-request@v4 - id: cpr - if: env.CREATE_PR == 'true' - with: - commit-message: "Update .NET SDK version from `${{ env.OLD_VERSION }}` to `${{ env.NEW_VERSION }}`" - title: "Update .NET SDK version from `${{ env.OLD_VERSION }}` to `${{ env.NEW_VERSION }}`" - base: master - branch: dotnet_update - update-tpn: - permissions: - contents: write # for peter-evans/create-pull-request to create branch - pull-requests: write # for peter-evans/create-pull-request to create a PR - name: Update Notices File - timeout-minutes: 15 - runs-on: windows-latest - if: github.repository == 'PowerShell/PowerShell' - steps: - - name: Checkout - uses: actions/checkout@v3 - - name: Update Notices file - run: | - Invoke-WebRequest -Uri https://aka.ms/pwsh-daily-tpn -OutFile ./ThirdPartyNotices.txt - - name: Capture Git Status - run: | - git status --short - - name: Check if we need to create a PR - run: | - $ErrorActionPreference = 'continue' - git diff --quiet ThirdPartyNotices.txt - $exitCode = $LASTEXITCODE - Write-Verbose -Message "Exit code: $exitCode" -Verbose - if ($LASTEXITCODE -ne 0) { - Import-Module ./.github/workflows/GHWorkflowHelper - Set-GWVariable -Name CREATE_PR -Value 'true' - } else { - Write-Verbose "No difference found. Not creating a PR." -Verbose - } - exit 0 - - name: Create Pull Request - uses: peter-evans/create-pull-request@v4 - id: cprtpn - if: env.CREATE_PR == 'true' - with: - commit-message: "Update to the latest NOTICES file" - committer: GitHub - author: ${{ github.actor }} <${{ github.actor }}@users.noreply.github.com> - title: "Update to the latest NOTICES file" - reviewers: travisez13 - base: master - draft: false - branch: update-cgmanifest - update-cgmanifest: - permissions: - contents: write # for peter-evans/create-pull-request to create branch - pull-requests: write # for peter-evans/create-pull-request to create a PR - name: Update cgmanifest - timeout-minutes: 15 - runs-on: windows-latest - if: github.repository == 'PowerShell/PowerShell' - env: - CGMANIFEST_PATH: '' - steps: - - name: Checkout - uses: actions/checkout@v3 - - name: Sync tags - run: | - git fetch --prune --unshallow --tags - - name: Install Ships provider to deal with project.assets.json - run: | - Install-Module -Name dotnet.project.assets -force - - name: Bootstrap - run: | - Import-Module ./build.psm1 - Start-PSBootStrap - - name: Verify cgmanifest is up to date - run: | - Import-Module ./build.psm1 - Find-Dotnet - ./tools/findMissingNotices.ps1 -Fix - - name: Upload cgmanifest - uses: actions/upload-artifact@v3 - if: always() && env.CGMANIFEST_PATH != '' - with: - name: cgmanifest - path: ${{ env.CGMANIFEST_PATH }} - - name: Create Pull Request - uses: peter-evans/create-pull-request@v4 - id: cprcgmanifest - if: env.CGMANIFEST_PATH != '' - with: - commit-message: "Update the cgmanifest" - committer: GitHub - author: ${{ github.actor }} <${{ github.actor }}@users.noreply.github.com> - title: "Update the cgmanifest" - reviewers: travisez13 - base: master - draft: false - branch: update-cgmanifest diff --git a/.github/workflows/exp-json.yml b/.github/workflows/exp-json.yml deleted file mode 100644 index 4d3fbfecc05..00000000000 --- a/.github/workflows/exp-json.yml +++ /dev/null @@ -1,149 +0,0 @@ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT license. - -name: PowerShell Experimental Features Json Update -on: - workflow_dispatch: - schedule: - # At 13:00 UTC every day. - - cron: '0 13 * * *' - -defaults: - run: - shell: pwsh - -env: - DOTNET_CLI_TELEMETRY_OPTOUT: 1 - POWERSHELL_TELEMETRY_OPTOUT: 1 - -permissions: - contents: read - -jobs: - create-expjson: - strategy: - matrix: - os: [windows-latest, ubuntu-latest] - timeout-minutes: 15 - runs-on: ${{ matrix.os }} - env: - OS_TITLE: ${{ matrix.os }} - if: github.repository == 'PowerShell/PowerShell' - name: Update experimental features json - steps: - - name: Checkout - uses: actions/checkout@v3 - with: - fetch-depth: '0' - - name: Create experimental features file - run: | - Import-Module ./build.psm1 -Force - Start-PSBootstrap - Start-PSBuild -Clean -PSModuleRestore - $builtPwsh = Get-PSOutput - - Write-Verbose -Verbose "PWSH path: $builtPwsh" - - $getExpFeatureJsonScript = @' - [System.Collections.ArrayList] $expFeatures = Get-ExperimentalFeature | Where-Object Name -NE PS7DscSupport | ForEach-Object -MemberName Name - - # Make sure ExperimentalFeatures from modules in PSHome are added - # https://github.com/PowerShell/PowerShell/issues/10550 - $ExperimentalFeaturesFromGalleryModulesInPSHome = @() - $ExperimentalFeaturesFromGalleryModulesInPSHome | ForEach-Object { - if (!$expFeatures.Contains($_)) { - $null = $expFeatures.Add($_) - } - } - - ConvertTo-Json $expFeatures - '@ - - $expFeaturesJson = & $builtPwsh -c $getExpFeatureJsonScript - $osname = $env:OS_TITLE -like 'windows*' ? 'windows' : 'linux' - $fileNamePrefix = "experimental-feature-$osname" - $newFileName = "${fileNamePrefix}-new.json" - - Write-Verbose -Verbose 'Experimental features found' - $expFeaturesJson | Out-String | Write-Verbose -Verbose - $expFeaturesJson | Out-File $newFileName -Force - - - name: Upload experimental features windows - uses: actions/upload-artifact@v3 - with: - name: experimentalJson - path: experimental-feature-*-new.json - - compare-expjson-files: - permissions: - contents: write # for peter-evans/create-pull-request to create branch - pull-requests: write # for peter-evans/create-pull-request to create a PR - runs-on: ubuntu-latest - name: Compare experimental json files and create PR - needs: create-expjson - steps: - - name: Checkout - uses: actions/checkout@v3 - with: - fetch-depth: '0' - - name: Download artifacts - uses: actions/download-artifact@v3 - with: - name: experimentalJson - - name: Compare json files - run: | - Import-Module ./.github/workflows/GHWorkflowHelper -Force - - function ShouldCreatePR($currentFile, $newFile) { - if (Test-Path $currentFile) { - $currentExpFeatures = Get-Content $currentFile -Raw | ConvertFrom-Json - $newExpFeatures = Get-Content $newFile -Raw | ConvertFrom-Json - - if (-not (Compare-Object $currentExpFeatures $newExpFeatures)) { - Write-Verbose -Verbose "No changes to experimental features json file" - return $false - } - } - - return $true - } - - $currentWinFile = "experimental-feature-windows.json" - $currentLinuxFile = "experimental-feature-linux.json" - $newWinFile = "experimental-feature-windows-new.json" - $newLinuxFile = "experimental-feature-linux-new.json" - - $createPrWin = ShouldCreatePR $currentWinFile $newWinFile - Write-Verbose -Verbose "Create PR Windows == $createPrWin" - - $createPrLinux = ShouldCreatePR $currentLinuxFile $newLinuxFile - Write-Verbose -Verbose "Create PR Linux == $createPrLinux" - - $createPr = $createPrWin -or $createPrLinux - Write-Verbose -Verbose "Create PR == $createPr" - - if ($createPrWin) { - Move-Item $newWinFile $currentWinFile -Verbose -Force - } - else { - Remove-Item $newWinFile -Verbose - } - - if ($createPrLinux) { - Move-Item $newLinuxFile $currentLinuxFile -Verbose -Force - } - else { - Remove-Item $newLinuxFile -Verbose - } - - Set-GWVariable -Name CREATE_EXP_JSON_PR -Value $createPR - - - name: Create Pull Request - uses: peter-evans/create-pull-request@v4 - id: cpr - if: env.CREATE_EXP_JSON_PR == 'true' - with: - commit-message: "Update experimental-feature-windows.json" - title: "Update experimental-feature json files" - base: master - branch: expjson_update_windows From b58db8b8f70756301d63ca9c52d0cca69756ef73 Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Thu, 9 Mar 2023 15:06:36 -0800 Subject: [PATCH 423/779] Bump .NET to Preview 2 version (#19305) --- DotnetRuntimeMetadata.json | 8 ++++---- global.json | 2 +- nuget.config | 2 +- ...rosoft.PowerShell.Commands.Diagnostics.csproj | 2 +- ...crosoft.PowerShell.Commands.Management.csproj | 2 +- .../Microsoft.PowerShell.Commands.Utility.csproj | 6 +++--- .../Microsoft.PowerShell.CoreCLR.Eventing.csproj | 2 +- .../Microsoft.PowerShell.SDK.csproj | 8 ++++---- .../Microsoft.WSMan.Management.csproj | 2 +- .../System.Management.Automation.csproj | 16 ++++++++-------- test/tools/TestService/TestService.csproj | 2 +- test/tools/WebListener/WebListener.csproj | 4 ++-- 12 files changed, 28 insertions(+), 28 deletions(-) diff --git a/DotnetRuntimeMetadata.json b/DotnetRuntimeMetadata.json index f2dbaaae3e2..a9bd76078e4 100644 --- a/DotnetRuntimeMetadata.json +++ b/DotnetRuntimeMetadata.json @@ -1,11 +1,11 @@ { "sdk": { - "channel": "8.0.1xx-preview1", + "channel": "8.0.1xx-preview2", "quality": "daily", "qualityFallback": "preview", - "packageVersionPattern": "8.0.0-preview.1", - "sdkImageVersion": "7.0.101", - "nextChannel": "7.0.1xx-rc2", + "packageVersionPattern": "8.0.0-preview.2", + "sdkImageVersion": "8.0.100", + "nextChannel": "8.0.1xx-preview2", "azureFeed": "", "sdkImageOverride": "" }, diff --git a/global.json b/global.json index 1fbc1e123a1..845df69857c 100644 --- a/global.json +++ b/global.json @@ -1,5 +1,5 @@ { "sdk": { - "version": "8.0.100-preview.1.23115.2" + "version": "8.0.100-preview.2.23157.25" } } diff --git a/nuget.config b/nuget.config index 5137d0c33d6..b81fddb0e30 100644 --- a/nuget.config +++ b/nuget.config @@ -2,7 +2,7 @@ - + diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/Microsoft.PowerShell.Commands.Diagnostics.csproj b/src/Microsoft.PowerShell.Commands.Diagnostics/Microsoft.PowerShell.Commands.Diagnostics.csproj index 87928d00dfb..10d4d9de8e0 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/Microsoft.PowerShell.Commands.Diagnostics.csproj +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/Microsoft.PowerShell.Commands.Diagnostics.csproj @@ -8,7 +8,7 @@ - + diff --git a/src/Microsoft.PowerShell.Commands.Management/Microsoft.PowerShell.Commands.Management.csproj b/src/Microsoft.PowerShell.Commands.Management/Microsoft.PowerShell.Commands.Management.csproj index 07a067f518d..5a254cf199c 100644 --- a/src/Microsoft.PowerShell.Commands.Management/Microsoft.PowerShell.Commands.Management.csproj +++ b/src/Microsoft.PowerShell.Commands.Management/Microsoft.PowerShell.Commands.Management.csproj @@ -47,7 +47,7 @@ - + diff --git a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj index ac469c4fd9f..5170227d65f 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj +++ b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj @@ -32,9 +32,9 @@ - - - + + + diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/Microsoft.PowerShell.CoreCLR.Eventing.csproj b/src/Microsoft.PowerShell.CoreCLR.Eventing/Microsoft.PowerShell.CoreCLR.Eventing.csproj index cf29ac2442d..25bd002b426 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/Microsoft.PowerShell.CoreCLR.Eventing.csproj +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/Microsoft.PowerShell.CoreCLR.Eventing.csproj @@ -8,7 +8,7 @@ - + diff --git a/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj b/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj index 7a9c2a9eec1..67329671c88 100644 --- a/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj +++ b/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj @@ -19,9 +19,9 @@ - - - + + + @@ -30,7 +30,7 @@ - + diff --git a/src/Microsoft.WSMan.Management/Microsoft.WSMan.Management.csproj b/src/Microsoft.WSMan.Management/Microsoft.WSMan.Management.csproj index 5f9cdc385d4..c80283a4533 100644 --- a/src/Microsoft.WSMan.Management/Microsoft.WSMan.Management.csproj +++ b/src/Microsoft.WSMan.Management/Microsoft.WSMan.Management.csproj @@ -10,7 +10,7 @@ - + diff --git a/src/System.Management.Automation/System.Management.Automation.csproj b/src/System.Management.Automation/System.Management.Automation.csproj index 38642bf4598..86def0d3747 100644 --- a/src/System.Management.Automation/System.Management.Automation.csproj +++ b/src/System.Management.Automation/System.Management.Automation.csproj @@ -34,16 +34,16 @@ - - - - + + + + - + - - - + + + diff --git a/test/tools/TestService/TestService.csproj b/test/tools/TestService/TestService.csproj index 0e260e8dfa2..d1d924628e3 100644 --- a/test/tools/TestService/TestService.csproj +++ b/test/tools/TestService/TestService.csproj @@ -13,7 +13,7 @@ - + diff --git a/test/tools/WebListener/WebListener.csproj b/test/tools/WebListener/WebListener.csproj index ad92dc867fb..0a8bf752e9b 100644 --- a/test/tools/WebListener/WebListener.csproj +++ b/test/tools/WebListener/WebListener.csproj @@ -7,8 +7,8 @@ - - + + From fb7bb75ebc1c723c579b04585fad2d2b1ecd773d Mon Sep 17 00:00:00 2001 From: Anam Navied Date: Mon, 13 Mar 2023 12:18:58 -0400 Subject: [PATCH 424/779] Add stage for symbols job in Release build (#18937) --- .../azureDevOps/releasePipeline.yml | 14 +++++ .../templates/release-PublishSymbols.yml | 51 +++++++++++++++++++ 2 files changed, 65 insertions(+) create mode 100644 tools/releaseBuild/azureDevOps/templates/release-PublishSymbols.yml diff --git a/tools/releaseBuild/azureDevOps/releasePipeline.yml b/tools/releaseBuild/azureDevOps/releasePipeline.yml index 05b86ff3d20..bd52a99b844 100644 --- a/tools/releaseBuild/azureDevOps/releasePipeline.yml +++ b/tools/releaseBuild/azureDevOps/releasePipeline.yml @@ -338,6 +338,20 @@ stages: steps: - template: templates/release-PublishPackageMsftCom.yml +- stage: PublishSymbols + displayName: Publish symbols + dependsOn: PublishPackages + jobs: + - job: PublishSymbol + + pool: + name: PowerShell1ES + demands: + - ImageOverride -equals PSMMS2019-Secure + + steps: + - template: templates/release-PublishSymbols.yml + - stage: ChangesToMaster displayName: Ensure changes are in GH master dependsOn: PublishPackages diff --git a/tools/releaseBuild/azureDevOps/templates/release-PublishSymbols.yml b/tools/releaseBuild/azureDevOps/templates/release-PublishSymbols.yml new file mode 100644 index 00000000000..db2cc86e259 --- /dev/null +++ b/tools/releaseBuild/azureDevOps/templates/release-PublishSymbols.yml @@ -0,0 +1,51 @@ +steps: +- task: DownloadPipelineArtifact@2 + inputs: + source: specific + project: PowerShellCore + pipeline: '696' + preferTriggeringPipeline: true + runVersion: latestFromBranch + runBranch: '$(Build.SourceBranch)' + artifact: results + path: '$(Pipeline.Workspace)\results' + itemPattern: | + **/* + !**/*signed.zip + +- pwsh: | + Write-Verbose -Verbose "Enumerating $(Pipeline.Workspace)\results" + $downloadedArtifacts = Get-ChildItem -Recurse "$(Pipeline.Workspace)\results" + $downloadedArtifacts + $expandedRoot = New-Item -Path "$(Pipeline.Workspace)/expanded" -ItemType Directory -Verbose + $symbolsRoot = New-Item -Path "$(Pipeline.Workspace)/symbols" -ItemType Directory -Verbose + + $downloadedArtifacts | ForEach-Object { + $destFolder = New-Item -Path "$expandedRoot/$($_.BaseName)/" -ItemType Directory -Verbose + Expand-Archive -Path $_.FullName -DestinationPath $destFolder -Force + + $symbolsZipFile = Join-Path -Path $destFolder -ChildPath "symbols.zip" + $symbolZipFileContents = New-Item -Path "$destFolder/Symbols-$($_.BaseName)" -ItemType Directory -Verbose + Expand-Archive -Path $symbolsZipFile -DestinationPath $symbolZipFileContents -Force + + $symbolsToPublish = New-Item -Path "$symbolsRoot/$($_.BaseName)" -ItemType Directory -Verbose + + Get-ChildItem -Path $symbolZipFileContents -Recurse -Filter '*.pdb' | ForEach-Object { + Copy-Item -Path $_.FullName -Destination $symbolsToPublish -Verbose + } + } + + Write-Verbose -Verbose "Enumerating $symbolsRoot" + Get-ChildItem -Path $symbolsRoot -Recurse + $vstsCommandString = "vso[task.setvariable variable=SymbolsPath]$symbolsRoot" + Write-Verbose -Message "$vstsCommandString" -Verbose + Write-Host -Object "##$vstsCommandString" + displayName: Expand and capture symbols folders +- task: PublishSymbols@2 + inputs: + symbolsFolder: '$(SymbolsPath)' + searchPattern: '**/*.pdb' + indexSources: false + publishSymbols: true + symbolServerType: teamServices + detailedLog: true From 7afe8437d7b5d492d56a87c55be45c8fb5da09e7 Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Mon, 13 Mar 2023 11:56:41 -0700 Subject: [PATCH 425/779] Fix mariner sudo detection (#19304) * Change the permissions on the symlink created for mariner * Update installpsh-mariner.sh * Update install-ps.yml * Update linux.yml * Update installpsh-mariner.sh --- .vsts-ci/install-ps.yml | 15 +++------------ .vsts-ci/linux.yml | 1 + tools/installpsh-mariner.sh | 10 +++++----- 3 files changed, 9 insertions(+), 17 deletions(-) diff --git a/.vsts-ci/install-ps.yml b/.vsts-ci/install-ps.yml index de78f55ce2c..7c537bc1304 100644 --- a/.vsts-ci/install-ps.yml +++ b/.vsts-ci/install-ps.yml @@ -9,13 +9,8 @@ trigger: - feature* paths: include: - - /tools/install-powershell.sh - - /tools/installpsh-amazonlinux.sh - - /tools/installpsh-debian.sh - - /tools/installpsh-osx.sh - - /tools/installpsh-redhat.sh - - /tools/installpsh-suse.sh - - /tools/install-powershell.ps1 + - /tools/install-powershell.* + - /tools/installpsh-*.sh - /.vsts-ci/install-ps.yml pr: branches: @@ -26,11 +21,7 @@ pr: paths: include: - /tools/install-powershell.sh - - /tools/installpsh-amazonlinux.sh - - /tools/installpsh-debian.sh - - /tools/installpsh-osx.sh - - /tools/installpsh-redhat.sh - - /tools/installpsh-suse.sh + - /tools/installpsh-*.sh - /tools/install-powershell.ps1 - /.vsts-ci/install-ps.yml diff --git a/.vsts-ci/linux.yml b/.vsts-ci/linux.yml index 6a3f0280d0c..7e2b2235832 100644 --- a/.vsts-ci/linux.yml +++ b/.vsts-ci/linux.yml @@ -44,6 +44,7 @@ pr: - test/common/markdown/* - test/perf/* - tools/releaseBuild/* + - tools/install* - tools/releaseBuild/azureDevOps/templates/* - README.md - .spelling diff --git a/tools/installpsh-mariner.sh b/tools/installpsh-mariner.sh index 9bb389fbda6..e274f0b6714 100644 --- a/tools/installpsh-mariner.sh +++ b/tools/installpsh-mariner.sh @@ -27,7 +27,7 @@ gitreposubpath="PowerShell/PowerShell/master" gitreposcriptroot="https://raw.githubusercontent.com/$gitreposubpath/tools" thisinstallerdistro=mariner repobased=false -gitscriptname="installpsh-mariner.psh" +gitscriptname="installpsh-mariner.sh" pwshlink=/usr/bin/pwsh echo @@ -109,11 +109,11 @@ fi SUDO='' if (( EUID != 0 )); then #Check that sudo is available - if [[ ("'$*'" =~ skip-sudo-check) && ("$(whereis sudo)" == *'/'* && "$(sudo -nv 2>&1)" != 'Sorry, user'*) ]]; then + if [[ ("'$*'" =~ skip-sudo-check) || ("$(whereis sudo)" == *'/'* && "$(sudo -nv 2>&1)" != 'Sorry, user'*) ]]; then SUDO='sudo' else echo "ERROR: You must either be root or be able to use sudo" >&2 - #exit 5 + exit 5 fi fi @@ -139,8 +139,8 @@ $SUDO tdnf install -y \ openssh-clients \ ca-certificates \ tar \ - curl \ - && tdnf clean all + curl +$SUDO tdnf clean all ##END Check requirements and prerequisites From 9dd932256f2c1d9f4749b9a0e03ef4333bc1580b Mon Sep 17 00:00:00 2001 From: Ilya Date: Tue, 14 Mar 2023 02:19:03 +0500 Subject: [PATCH 426/779] Remove unused GUID detection code from console host (#18871) --- .../host/msh/ConsoleHostUserInterface.cs | 16 ------- .../engine/hostifaces/HostUtilities.cs | 42 ------------------- 2 files changed, 58 deletions(-) diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs index cddaac5fbde..6e3359275e0 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs @@ -1206,9 +1206,6 @@ internal string WrapToCurrentWindowWidth(string text) /// public override void WriteDebugLine(string message) { - // don't lock here as WriteLine is already protected. - message = HostUtilities.RemoveGuidFromMessage(message, out _); - // We should write debug to error stream only if debug is redirected.) if (_parent.ErrorFormat == Serialization.DataFormat.XML) { @@ -1266,9 +1263,6 @@ public override void WriteInformation(InformationRecord record) /// public override void WriteVerboseLine(string message) { - // don't lock here as WriteLine is already protected. - message = HostUtilities.RemoveGuidFromMessage(message, out _); - // NTRAID#Windows OS Bugs-1061752-2004/12/15-sburns should read a skin setting here...) if (_parent.ErrorFormat == Serialization.DataFormat.XML) { @@ -1309,9 +1303,6 @@ public override void WriteVerboseLine(string message) /// public override void WriteWarningLine(string message) { - // don't lock here as WriteLine is already protected. - message = HostUtilities.RemoveGuidFromMessage(message, out _); - // NTRAID#Windows OS Bugs-1061752-2004/12/15-sburns should read a skin setting here...) if (_parent.ErrorFormat == Serialization.DataFormat.XML) { @@ -1346,13 +1337,6 @@ public override void WriteProgress(long sourceId, ProgressRecord record) return; } - bool matchPattern; - string currentOperation = HostUtilities.RemoveIdentifierInfoFromMessage(record.CurrentOperation, out matchPattern); - if (matchPattern) - { - record = new ProgressRecord(record) { CurrentOperation = currentOperation }; - } - // We allow only one thread at a time to update the progress state.) if (_parent.ErrorFormat == Serialization.DataFormat.XML) { diff --git a/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs b/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs index 11ff5d01f54..01d1f4c1bac 100644 --- a/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs +++ b/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs @@ -519,48 +519,6 @@ internal static List GetSuggestion(HistoryInfo lastHistory, object lastE return returnSuggestions; } - /// - /// Remove the GUID from the message if the message is in the pre-defined format. - /// - /// - /// - /// - internal static string RemoveGuidFromMessage(string message, out bool matchPattern) - { - matchPattern = false; - if (string.IsNullOrEmpty(message)) - return message; - - const string pattern = @"^([\d\w]{8}\-[\d\w]{4}\-[\d\w]{4}\-[\d\w]{4}\-[\d\w]{12}:).*"; - Match matchResult = Regex.Match(message, pattern); - if (matchResult.Success) - { - string partToRemove = matchResult.Groups[1].Captures[0].Value; - message = message.Remove(0, partToRemove.Length); - matchPattern = true; - } - - return message; - } - - internal static string RemoveIdentifierInfoFromMessage(string message, out bool matchPattern) - { - matchPattern = false; - if (string.IsNullOrEmpty(message)) - return message; - - const string pattern = @"^([\d\w]{8}\-[\d\w]{4}\-[\d\w]{4}\-[\d\w]{4}\-[\d\w]{12}:\[.*\]:).*"; - Match matchResult = Regex.Match(message, pattern); - if (matchResult.Success) - { - string partToRemove = matchResult.Groups[1].Captures[0].Value; - message = message.Remove(0, partToRemove.Length); - matchPattern = true; - } - - return message; - } - /// /// Create suggestion with string rule and scriptblock suggestion. /// From cf93f01ea13ba267cc38d4e42f3eee4dceeca42c Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 13 Mar 2023 14:40:28 -0700 Subject: [PATCH 427/779] Bump `Newtonsoft.Json` from `13.0.2` to `13.0.3` (#19290) --- .../System.Management.Automation.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/System.Management.Automation/System.Management.Automation.csproj b/src/System.Management.Automation/System.Management.Automation.csproj index 86def0d3747..3110a52d623 100644 --- a/src/System.Management.Automation/System.Management.Automation.csproj +++ b/src/System.Management.Automation/System.Management.Automation.csproj @@ -30,7 +30,7 @@ - + From 9a2d2afb646fc4032a8bdcfc0eb9666a856f4e38 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Mon, 13 Mar 2023 23:05:28 +0100 Subject: [PATCH 428/779] Make `-Encoding` parameter able to take `ANSI` encoding in PowerShell (#19298) --- .../utils/EncodingUtils.cs | 37 ++++++++++--------- .../Parser/RedirectionOperator.Tests.ps1 | 4 +- .../Get-Content.Tests.ps1 | 7 ++-- .../Format-Hex.Tests.ps1 | 2 +- 4 files changed, 27 insertions(+), 23 deletions(-) diff --git a/src/System.Management.Automation/utils/EncodingUtils.cs b/src/System.Management.Automation/utils/EncodingUtils.cs index 029de9d94e9..8094115e92a 100644 --- a/src/System.Management.Automation/utils/EncodingUtils.cs +++ b/src/System.Management.Automation/utils/EncodingUtils.cs @@ -2,6 +2,7 @@ // Licensed under the MIT License. using System.Collections.Generic; +using System.Globalization; using System.Text; using System.Management.Automation.Internal; @@ -10,41 +11,43 @@ namespace System.Management.Automation { internal static class EncodingConversion { - internal const string Unknown = "unknown"; - internal const string String = "string"; - internal const string Unicode = "unicode"; + internal const string ANSI = "ansi"; + internal const string Ascii = "ascii"; internal const string BigEndianUnicode = "bigendianunicode"; internal const string BigEndianUtf32 = "bigendianutf32"; - internal const string Ascii = "ascii"; + internal const string Default = "default"; + internal const string OEM = "oem"; + internal const string String = "string"; + internal const string Unicode = "unicode"; + internal const string Unknown = "unknown"; + internal const string Utf7 = "utf7"; internal const string Utf8 = "utf8"; - internal const string Utf8NoBom = "utf8NoBOM"; internal const string Utf8Bom = "utf8BOM"; - internal const string Utf7 = "utf7"; + internal const string Utf8NoBom = "utf8NoBOM"; internal const string Utf32 = "utf32"; - internal const string Default = "default"; - internal const string OEM = "oem"; internal static readonly string[] TabCompletionResults = { - Ascii, BigEndianUnicode, BigEndianUtf32, OEM, Unicode, Utf7, Utf8, Utf8Bom, Utf8NoBom, Utf32 + ANSI, Ascii, BigEndianUnicode, BigEndianUtf32, OEM, Unicode, Utf7, Utf8, Utf8Bom, Utf8NoBom, Utf32 }; - internal static readonly Dictionary encodingMap = new Dictionary(StringComparer.OrdinalIgnoreCase) + internal static readonly Dictionary encodingMap = new(StringComparer.OrdinalIgnoreCase) { + { ANSI, Encoding.GetEncoding(CultureInfo.CurrentCulture.TextInfo.ANSICodePage) }, { Ascii, Encoding.ASCII }, { BigEndianUnicode, Encoding.BigEndianUnicode }, { BigEndianUtf32, new UTF32Encoding(bigEndian: true, byteOrderMark: true) }, { Default, Encoding.Default }, { OEM, ClrFacade.GetOEMEncoding() }, + { String, Encoding.Unicode }, { Unicode, Encoding.Unicode }, + { Unknown, Encoding.Unicode }, #pragma warning disable SYSLIB0001 { Utf7, Encoding.UTF7 }, #pragma warning restore SYSLIB0001 { Utf8, Encoding.Default }, { Utf8Bom, Encoding.UTF8 }, { Utf8NoBom, Encoding.Default }, - { Utf32, Encoding.UTF32 }, - { String, Encoding.Unicode }, - { Unknown, Encoding.Unicode }, + { Utf32, Encoding.UTF32 }, }; /// @@ -60,8 +63,7 @@ internal static Encoding Convert(Cmdlet cmdlet, string encoding) return Encoding.Default; } - Encoding foundEncoding; - if (encodingMap.TryGetValue(encoding, out foundEncoding)) + if (encodingMap.TryGetValue(encoding, out Encoding foundEncoding)) { // Write a warning if using utf7 as it is obsolete in .NET5 if (string.Equals(encoding, Utf7, StringComparison.OrdinalIgnoreCase)) @@ -122,10 +124,10 @@ public override object Transform(EngineIntrinsics engineIntrinsics, object input } else { - return System.Text.Encoding.GetEncoding(stringName); + return Encoding.GetEncoding(stringName); } case int intName: - return System.Text.Encoding.GetEncoding(intName); + return Encoding.GetEncoding(intName); } return inputData; @@ -138,6 +140,7 @@ public override object Transform(EngineIntrinsics engineIntrinsics, object input internal sealed class ArgumentEncodingCompletionsAttribute : ArgumentCompletionsAttribute { public ArgumentEncodingCompletionsAttribute() : base( + EncodingConversion.ANSI, EncodingConversion.Ascii, EncodingConversion.BigEndianUnicode, EncodingConversion.BigEndianUtf32, diff --git a/test/powershell/Language/Parser/RedirectionOperator.Tests.ps1 b/test/powershell/Language/Parser/RedirectionOperator.Tests.ps1 index 466f15bd695..0c9ef0f0b92 100644 --- a/test/powershell/Language/Parser/RedirectionOperator.Tests.ps1 +++ b/test/powershell/Language/Parser/RedirectionOperator.Tests.ps1 @@ -45,7 +45,7 @@ Describe "Redirection operator now supports encoding changes" -Tags "CI" { } } - $availableEncodings = + $availableEncodings = @([System.Text.Encoding]::ASCII [System.Text.Encoding]::BigEndianUnicode [System.Text.UTF32Encoding]::new($true,$true) @@ -53,7 +53,7 @@ Describe "Redirection operator now supports encoding changes" -Tags "CI" { [System.Text.Encoding]::UTF7 [System.Text.Encoding]::UTF8 [System.Text.Encoding]::UTF32) - + foreach($encoding in $availableEncodings) { $encodingName = $encoding.EncodingName diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Content.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Content.Tests.ps1 index 5fdc904580d..9f42be74149 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Content.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Content.Tests.ps1 @@ -104,7 +104,8 @@ Describe "Get-Content" -Tags "CI" { @{EncodingName = 'UTF8NoBOM'}, @{EncodingName = 'UTF7'}, @{EncodingName = 'UTF32'}, - @{EncodingName = 'Ascii'} + @{EncodingName = 'Ascii'}, + @{EncodingName = 'ANSI'} ){ param($EncodingName) @@ -114,7 +115,7 @@ Describe "Get-Content" -Tags "CI" { @('𐍈1','𐍈𐍈2','𐍈𐍈𐍈3','𐍈𐍈𐍈𐍈4','𐍈𐍈𐍈𐍈𐍈5')) # utf-32 ForEach ($content in $contentSets) { - $tailCount = 3 + $tailCount = 4 $testPath = Join-Path -Path $TestDrive -ChildPath 'TailWithEncoding.txt' $content | Set-Content -Path $testPath -Encoding $EncodingName @@ -221,7 +222,7 @@ Describe "Get-Content" -Tags "CI" { $expected = 'He', 'o,', '', 'Wor', "d${nl}He", 'o2,', '', 'Wor', "d2${nl}" for ($i = 0; $i -lt $result.Length ; $i++) { $result[$i] | Should -BeExactly $expected[$i]} } - + Context "Alternate Data Stream support on Windows" { It "Should support NTFS streams using colon syntax" -Skip:(!$IsWindows) { Set-Content "${testPath}:Stream" -Value "Foo" diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Format-Hex.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Format-Hex.Tests.ps1 index 0ae47aac8e3..6553cdfefcd 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Format-Hex.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Format-Hex.Tests.ps1 @@ -438,7 +438,7 @@ public enum TestSByteEnum : sbyte { Count = 2 ExpectedResult = "0000000000000000 00 00 00 68 00 00 00 65 00 00 00 6C 00 00 00 6C h e l l" ExpectedSecondResult = "0000000000000010 00 00 00 6F o" - } + } @{ Name = "Can process Unicode encoding 'fhx -InputObject 'hello' -Encoding Unicode'" Encoding = "Unicode" From 01e7b928baf8aba3fa2b973e9ec554d2d9c792e3 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 13 Mar 2023 22:08:48 +0000 Subject: [PATCH 429/779] Bump `Newtonsoft.Json` (#19289) --- .../Microsoft.PowerShell.Commands.Utility.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/packaging/projects/reference/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj b/tools/packaging/projects/reference/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj index 97e38b81a19..038045f904b 100644 --- a/tools/packaging/projects/reference/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj +++ b/tools/packaging/projects/reference/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj @@ -13,7 +13,7 @@ - + From e95f7fb50f4d398568f39e3894349e9930df8f29 Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Mon, 13 Mar 2023 15:40:27 -0700 Subject: [PATCH 430/779] Test fixes for stabilizing tests (#19068) --- build.psm1 | 15 +-- experimental-feature-linux.json | 3 +- experimental-feature-windows.json | 3 +- test/powershell/Host/HostUtilities.Tests.ps1 | 8 ++ .../TabCompletion/TabCompletion.Tests.ps1 | 101 ++++++++++++++---- .../NativeCommandProcessor.Tests.ps1 | 17 ++- .../RemoteGetModule.Tests.ps1 | 2 +- .../RemoteImportModule.Tests.ps1 | 2 +- .../CertificateProvider.Tests.ps1 | 75 ++++++++++++- .../CmsMessage.Tests.ps1 | 42 +++++++- .../certificateCommon.psm1 | 12 ++- .../Format-Table.Tests.ps1 | 16 ++- .../Implicit.Remoting.Tests.ps1 | 2 +- .../Get-ExperimentalFeature.Tests.ps1 | 2 +- .../RemoteSession.Disconnect.Tests.ps1 | 2 +- .../engine/Remoting/RunspacePool.Tests.ps1 | 12 ++- .../Modules/HelpersCommon/HelpersCommon.psd1 | 3 + .../Modules/HelpersCommon/HelpersCommon.psm1 | 46 ++++++++ ...soft.PowerShell.NamedPipeConnection.csproj | 4 +- 19 files changed, 305 insertions(+), 62 deletions(-) diff --git a/build.psm1 b/build.psm1 index 68f6a5ea070..3d0be1a846b 100644 --- a/build.psm1 +++ b/build.psm1 @@ -1118,17 +1118,6 @@ function Publish-CustomConnectionTestModule $sourcePath = "${PSScriptRoot}/test/tools/NamedPipeConnection" $outPath = "${PSScriptRoot}/test/tools/NamedPipeConnection/out/Microsoft.PowerShell.NamedPipeConnection" $publishPath = "${PSScriptRoot}/test/tools/Modules" - $refPath = "${sourcePath}/src/code/Ref" - - # Copy the current SMA build to the refPath. - $smaPath = Join-Path -Path (Split-Path -Path (Get-PSOutput)) -ChildPath 'System.Management.Automation.dll' - if (! (Test-Path -Path $smaPath)) { - throw "Publish-CustomConnectionTestModule: Cannot find reference SMA at: ${smaPath}" - } - if (! (Test-Path -Path $refPath)) { - $null = New-Item -Path $refPath -ItemType Directory -Force - } - Copy-Item -Path $smapath -Destination $refPath -Force Find-DotNet @@ -1146,7 +1135,6 @@ function Publish-CustomConnectionTestModule # Clean up build artifacts ./build.ps1 -Clean - Remove-Item -Path $refPath -Recurse -Force -ErrorAction SilentlyContinue } finally { Pop-Location @@ -1219,6 +1207,9 @@ function Publish-PSTestTools { # `dotnet restore` on test project is not called if product projects have been restored unless -Force is specified. Copy-PSGalleryModules -Destination "${PSScriptRoot}/test/tools/Modules" -CsProjPath "$PSScriptRoot/test/tools/Modules/PSGalleryTestModules.csproj" -Force + + # Publish the Microsoft.PowerShell.NamedPipeConnection module + Publish-CustomConnectionTestModule } function Get-ExperimentalFeatureTests { diff --git a/experimental-feature-linux.json b/experimental-feature-linux.json index 0e3bfc3d528..376ada0a790 100644 --- a/experimental-feature-linux.json +++ b/experimental-feature-linux.json @@ -5,5 +5,6 @@ "PSNativeCommandErrorActionPreference", "PSSubsystemPluginModel", "PSModuleAutoLoadSkipOfflineFiles", - "PSFeedbackProvider" + "PSFeedbackProvider", + "PSCommandWithArgs" ] diff --git a/experimental-feature-windows.json b/experimental-feature-windows.json index 0e3bfc3d528..376ada0a790 100644 --- a/experimental-feature-windows.json +++ b/experimental-feature-windows.json @@ -5,5 +5,6 @@ "PSNativeCommandErrorActionPreference", "PSSubsystemPluginModel", "PSModuleAutoLoadSkipOfflineFiles", - "PSFeedbackProvider" + "PSFeedbackProvider", + "PSCommandWithArgs" ] diff --git a/test/powershell/Host/HostUtilities.Tests.ps1 b/test/powershell/Host/HostUtilities.Tests.ps1 index b5c65af97e6..1f064408e3c 100644 --- a/test/powershell/Host/HostUtilities.Tests.ps1 +++ b/test/powershell/Host/HostUtilities.Tests.ps1 @@ -35,6 +35,12 @@ Describe "InvokeOnRunspace method as nested command" -tags "Feature" { Describe "InvokeOnRunspace method on remote runspace" -tags "Feature","RequireAdminOnWindows" { BeforeAll { + $originalDefaultParameterValues = $PSDefaultParameterValues.Clone() + + if (Test-IsWinWow64) { + $global:PSDefaultParameterValues["it:skip"] = $true + return + } if ($IsWindows) { $script:remoteRunspace = New-RemoteRunspace @@ -46,6 +52,8 @@ Describe "InvokeOnRunspace method on remote runspace" -tags "Feature","RequireAd { $script:remoteRunspace.Dispose(); } + + $global:PSDefaultParameterValues = $originalDefaultParameterValues } It "Method should successfully invoke command on remote runspace" -Skip:(!$IsWindows) { diff --git a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 index af35677834a..7a3722e93d2 100644 --- a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 +++ b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 @@ -541,11 +541,16 @@ using ` It 'Should show multiple constructors in the tooltip' { $res = TabExpansion2 -inputScript 'class ConstructorTestClass{ConstructorTestClass ([string] $s){}ConstructorTestClass ([int] $i){}ConstructorTestClass ([int] $i, [bool]$b){}};[ConstructorTestClass]::new' $res.CompletionMatches | Should -HaveCount 1 - $completionText = $res.CompletionMatches.ToolTip | Should -BeExactly @' + $completionText = $res.CompletionMatches.ToolTip + $completionText.replace("`r`n", [System.Environment]::NewLine).trim() + + $expected = @' ConstructorTestClass(string s) ConstructorTestClass(int i) ConstructorTestClass(int i, bool b) '@ + $expected.replace("`r`n", [System.Environment]::NewLine).trim() + $completionText.replace("`r`n", [System.Environment]::NewLine).trim() | Should -BeExactly $expected } It 'Should complete parameter in param block' { @@ -1229,12 +1234,8 @@ class InheritedClassTest : System.Attribute } It "Tab completion UNC path" -Skip:(!$IsWindows) { - if (!$env:HOMEDRIVE) { - Set-ItResult -Skipped -Because "Homerdrive is not set" - } - $homeDrive = $env:HOMEDRIVE.Replace(":", "$") - $beforeTab = "\\localhost\$homeDrive\wind" - $afterTab = "& '\\localhost\$homeDrive\Windows'" + $beforeTab = "\\localhost\ADMIN$\boo" + $afterTab = "& '\\localhost\ADMIN$\Boot'" $res = TabExpansion2 -inputScript $beforeTab -cursorColumn $beforeTab.Length $res.CompletionMatches.Count | Should -BeGreaterThan 0 $res.CompletionMatches[0].CompletionText | Should -BeExactly $afterTab @@ -2101,7 +2102,7 @@ dir -Recurse ` Context "Tab completion help test" { BeforeAll { - if ([System.Management.Automation.Platform]::IsWindows) { + if ($IsWindows) { $userHelpRoot = Join-Path $HOME "Documents/PowerShell/Help/" } else { $userModulesRoot = [System.Management.Automation.Platform]::SelectProductNameForDirectory([System.Management.Automation.Platform+XDG_Type]::USER_MODULES) @@ -2110,33 +2111,89 @@ dir -Recurse ` } It 'Should complete about help topic' { - $aboutHelpPathUserScope = Join-Path $userHelpRoot (Get-Culture).Name - $aboutHelpPathAllUsersScope = Join-Path $PSHOME (Get-Culture).Name + $helpName = "about_Splatting" + $helpFileName = "${helpName}.help.txt" + $inputScript = "get-help about_spla" + $culture = "en-US" + $aboutHelpPathUserScope = Join-Path $userHelpRoot $culture + $aboutHelpPathAllUsersScope = Join-Path $PSHOME $culture + $expectedCompletionCount = 0 ## If help content does not exist, tab completion will not work. So update it first. - $userScopeHelp = Test-Path (Join-Path $aboutHelpPathUserScope "about_Splatting.help.txt") - $allUserScopeHelp = Test-Path (Join-Path $aboutHelpPathAllUsersScope "about_Splatting.help.txt") - if ((-not $userScopeHelp) -and (-not $aboutHelpPathAllUsersScope)) { + $userHelpPath = Join-Path $aboutHelpPathUserScope $helpFileName + $userScopeHelp = Test-Path $userHelpPath + if ($userScopeHelp) { + $expectedCompletionCount++ + } else { Update-Help -Force -ErrorAction SilentlyContinue -Scope 'CurrentUser' + if (Test-Path $userHelpPath) { + $expectedCompletionCount++ + } } - # If help content is present on both scopes, expect 2 or else expect 1 completion. - $expectedCompletions = if ($userScopeHelp -and $allUserScopeHelp) { 2 } else { 1 } + $allUserScopeHelpPath = Test-Path (Join-Path $aboutHelpPathAllUsersScope $helpFileName) + if ($allUserScopeHelpPath) { + $expectedCompletionCount++ + } - $res = TabExpansion2 -inputScript 'get-help about_spla' -cursorColumn 'get-help about_spla'.Length - $res.CompletionMatches | Should -HaveCount $expectedCompletions - $res.CompletionMatches[0].CompletionText | Should -BeExactly 'about_Splatting' + $res = TabExpansion2 -inputScript $inputScript -cursorColumn $inputScript.Length + $res.CompletionMatches | Should -HaveCount $expectedCompletionCount + $res.CompletionMatches[0].CompletionText | Should -BeExactly $helpName } + It 'Should complete about help topic regardless of culture' { try { ## Save original culture and temporarily set it to da-DK because there's no localized help for da-DK. $OriginalCulture = [cultureinfo]::CurrentCulture - [cultureinfo]::CurrentCulture="da-DK" + $defaultCulture = "en-US" + $culture = "da-DK" + [cultureinfo]::CurrentCulture = $culture + $helpName = "about_Splatting" + $helpFileName = "${helpName}.help.txt" + + $aboutHelpPathUserScope = Join-Path $userHelpRoot $culture + $aboutHelpPathAllUsersScope = Join-Path $PSHOME $culture + $expectedCompletionCount = 0 + + ## If help content does not exist, tab completion will not work. So update it first. + $userHelpPath = Join-Path $aboutHelpPathUserScope $helpFileName + $userScopeHelp = Test-Path $userHelpPath + if ($userScopeHelp) { + $expectedCompletionCount++ + } + else { Update-Help -Force -ErrorAction SilentlyContinue -Scope 'CurrentUser' + if (Test-Path $userHelpPath) { + $expectedCompletionCount++ + } + else { + $aboutHelpPathUserScope = Join-Path $userHelpRoot $defaultCulture + $aboutHelpPathAllUsersScope = Join-Path $PSHOME $defaultCulture + $userHelpDefaultPath = Join-Path $aboutHelpPathUserScope $helpFileName + $userDefaultScopeHelp = Test-Path $userHelpDefaultPath + + if ($userDefaultScopeHelp) { + $expectedCompletionCount++ + } + } + } + + $allUserScopeHelpPath = Test-Path (Join-Path $aboutHelpPathAllUsersScope $helpFileName) + if ($allUserScopeHelpPath) { + $expectedCompletionCount++ + } + else { + $aboutHelpPathAllUsersDefaultScope = Join-Path $PSHOME $defaultCulture + $allUsersDefaultScopeHelpPath = Test-Path (Join-Path $aboutHelpPathAllUsersDefaultScope $helpFileName) + + if ($allUsersDefaultScopeHelpPath) { + $expectedCompletionCount++ + } + } $res = TabExpansion2 -inputScript 'get-help about_spla' -cursorColumn 'get-help about_spla'.Length - $res.CompletionMatches | Should -HaveCount 1 - $res.CompletionMatches[0].CompletionText | Should -BeExactly 'about_Splatting' + $res.CompletionMatches | Should -HaveCount $expectedCompletionCount + $res.CompletionMatches[0].CompletionText | Should -BeExactly $helpName } finally { @@ -2351,7 +2408,7 @@ function MyFunction ($param1, $param2) Describe "Tab completion tests with remote Runspace" -Tags Feature,RequireAdminOnWindows { BeforeAll { - if ($IsWindows) { + if ($IsWindows -and -not (Test-IsWinWow64)) { $session = New-RemoteSession $powershell = [powershell]::Create() $powershell.Runspace = $session.Runspace diff --git a/test/powershell/Language/Scripting/NativeExecution/NativeCommandProcessor.Tests.ps1 b/test/powershell/Language/Scripting/NativeExecution/NativeCommandProcessor.Tests.ps1 index d736d4b3945..41e3f3cebcf 100644 --- a/test/powershell/Language/Scripting/NativeExecution/NativeCommandProcessor.Tests.ps1 +++ b/test/powershell/Language/Scripting/NativeExecution/NativeCommandProcessor.Tests.ps1 @@ -312,6 +312,14 @@ Describe "Run native command from a mounted FAT-format VHD" -tags @("Feature", " if (-not $IsWindows) { return; } + else { + $storageModule = Get-Module -Name 'Storage' -ListAvailable -ErrorAction SilentlyContinue + + if (-not $storageModule) { + Write-Verbose -Verbose "Storage module is not available." + return; + } + } $vhdx = Join-Path -Path $TestDrive -ChildPath ncp.vhdx @@ -335,11 +343,18 @@ Describe "Run native command from a mounted FAT-format VHD" -tags @("Feature", " diskpart.exe /s $create_vhdx Mount-DiskImage -ImagePath $vhdx > $null - Copy-Item "$env:WinDir\System32\whoami.exe" T:\whoami.exe + Copy-Item "$env:WinDir\System32\whoami.exe" "T:\whoami.exe" } AfterAll { if ($IsWindows) { + $storageModule = Get-Module -Name 'Storage' -ListAvailable -ErrorAction SilentlyContinue + + if (-not $storageModule) { + Write-Verbose -Verbose "Storage module is not available." + return; + } + Dismount-DiskImage -ImagePath $vhdx Remove-Item $vhdx, $create_vhdx -Force } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Core/RemoteGetModule.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Core/RemoteGetModule.Tests.ps1 index 2ad47aa2414..95e522ab9aa 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Core/RemoteGetModule.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Core/RemoteGetModule.Tests.ps1 @@ -4,7 +4,7 @@ Describe "Remote module tests" -Tags 'Feature','RequireAdminOnWindows' { BeforeAll { - if (!$IsWindows) + if (!$IsWindows -or (Test-IsWinWow64)) { $originalDefaultParameterValues = $PSDefaultParameterValues.Clone() $PSDefaultParameterValues["it:skip"] = $true diff --git a/test/powershell/Modules/Microsoft.PowerShell.Core/RemoteImportModule.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Core/RemoteImportModule.Tests.ps1 index e783a6f69e7..ba7f35f0485 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Core/RemoteImportModule.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Core/RemoteImportModule.Tests.ps1 @@ -5,7 +5,7 @@ Describe "Remote import-module tests" -Tags 'Feature','RequireAdminOnWindows' { BeforeAll { $originalDefaultParameterValues = $PSDefaultParameterValues.Clone() $modulePath = "$testdrive\Modules\TestImport" - if (!$IsWindows) { + if (!$IsWindows -or (Test-IsWinWow64)) { $PSDefaultParameterValues["it:skip"] = $true } else { $pssession = New-RemoteSession diff --git a/test/powershell/Modules/Microsoft.PowerShell.Security/CertificateProvider.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Security/CertificateProvider.Tests.ps1 index 88bccb20a37..c6c468e5f0b 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Security/CertificateProvider.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Security/CertificateProvider.Tests.ps1 @@ -82,8 +82,13 @@ Describe "Certificate Provider tests" -Tags "Feature" { BeforeAll{ if($IsWindows) { - Install-TestCertificates - Push-Location Cert:\ + if (-not (Install-TestCertificates) ) { + $SetupFailure = $true + } + else { + Push-Location Cert:\ + $SetupFailure = $false + } } else { @@ -94,28 +99,45 @@ Describe "Certificate Provider tests" -Tags "Feature" { } AfterAll { - if($IsWindows) + if($IsWindows -and -not $SetupFailure) { Remove-TestCertificates Pop-Location } else { - $global:PSDefaultParameterValues = $defaultParamValues + if ($defaultParamValues -ne $null) { + $global:PSDefaultParameterValues = $defaultParamValues + } } } Context "Get-Item tests" { It "Should be able to get certifate by path: " -TestCases $currentUserMyLocations { param([string] $path) + if ($SetupFailure) { + Set-ItResult -Inconclusive -Because "Test certificates are not installed" + } + + if ($SetupFailure) { + Set-ItResult -Inconclusive -Because "Test certificates are not installed" + } + $expectedThumbprint = (Get-GoodCertificateObject).Thumbprint $leafPath = Join-Path -Path $path -ChildPath $expectedThumbprint $cert = (Get-Item -LiteralPath $leafPath) - $cert | Should -Not -Be null + if ($SetupFailure) { + Set-ItResult -Inconclusive -Because "Test certificates are not installed" + } $cert.Thumbprint | Should -Be $expectedThumbprint } It "Should be able to get DnsNameList of certifate by path: " -TestCases $currentUserMyLocations { param([string] $path) + + if ($SetupFailure) { + Set-ItResult -Inconclusive -Because "Test certificates are not installed" + } + $expectedThumbprint = (Get-GoodCertificateObject).Thumbprint $expectedName = (Get-GoodCertificateObject).DnsNameList $expectedEncodedName = (Get-GoodCertificateObject).DnsNameList @@ -133,6 +155,11 @@ Describe "Certificate Provider tests" -Tags "Feature" { } it "Should be able to get EnhancedKeyUsageList of certifate by path: " -TestCases $currentUserMyLocations { param([string] $path) + + if ($SetupFailure) { + Set-ItResult -Inconclusive -Because "Test certificates are not installed" + } + $expectedThumbprint = (Get-GoodCertificateObject).Thumbprint $expectedOid = (Get-GoodCertificateObject).EnhancedKeyUsageList[0].ObjectId $leafPath = Join-Path -Path $path -ChildPath $expectedThumbprint @@ -144,6 +171,11 @@ Describe "Certificate Provider tests" -Tags "Feature" { $cert.EnhancedKeyUsageList[0].ObjectId | Should -Be $expectedOid } It "Should filter to codesign certificates" { + + if ($SetupFailure) { + Set-ItResult -Inconclusive -Because "Test certificates are not installed" + } + $allCerts = Get-Item cert:\CurrentUser\My\* $codeSignCerts = Get-Item cert:\CurrentUser\My\* -CodeSigningCert $codeSignCerts | Should -Not -Be null @@ -152,6 +184,11 @@ Describe "Certificate Provider tests" -Tags "Feature" { $nonCodeSignCertCount | Should -Not -Be 0 } It "Should be able to exclude by thumbprint" { + + if ($SetupFailure) { + Set-ItResult -Inconclusive -Because "Test certificates are not installed" + } + $allCerts = Get-Item cert:\CurrentUser\My\* $testThumbprint = (Get-GoodCertificateObject).Thumbprint $allCertsExceptOne = (Get-Item "cert:\currentuser\my\*" -Exclude $testThumbprint) @@ -166,6 +203,11 @@ Describe "Certificate Provider tests" -Tags "Feature" { $cert = Get-GoodServerCertificateObject } it "Should filter to codesign certificates" { + + if ($SetupFailure) { + Set-ItResult -Inconclusive -Because "Test certificates are not installed" + } + $allCerts = get-ChildItem cert:\CurrentUser\My $codeSignCerts = get-ChildItem cert:\CurrentUser\My -CodeSigningCert $codeSignCerts | Should -Not -Be null @@ -174,6 +216,11 @@ Describe "Certificate Provider tests" -Tags "Feature" { $nonCodeSignCertCount | Should -Not -Be 0 } it "Should filter to ExpiringInDays certificates" { + + if ($SetupFailure) { + Set-ItResult -Inconclusive -Because "Test certificates are not installed" + } + $thumbprint = $cert.Thumbprint $NotAfter = $cert.NotAfter $before = ($NotAfter.AddDays(-1) - (Get-Date)).Days @@ -186,6 +233,11 @@ Describe "Certificate Provider tests" -Tags "Feature" { $afterCerts.Thumbprint | Should -BeExactly $thumbprint } it "Should filter to DocumentEncryptionCert certificates" { + + if ($SetupFailure) { + Set-ItResult -Inconclusive -Because "Test certificates are not installed" + } + $thumbprint = $cert.Thumbprint $certs = Get-ChildItem cert:\CurrentUser\My\$thumbprint -DocumentEncryptionCert @@ -199,6 +251,10 @@ Describe "Certificate Provider tests" -Tags "Feature" { ) { param($name, $searchName, $count, $thumbprint) + if ($SetupFailure) { + Set-ItResult -Inconclusive -Because "Test certificates are not installed" + } + $certs = Get-ChildItem cert:\CurrentUser\My\$thumbprint -DNSName $searchName $certs.Count | Should -Be $count @@ -206,6 +262,11 @@ Describe "Certificate Provider tests" -Tags "Feature" { } it "Should filter to SSLServerAuthentication certificates" { + + if ($SetupFailure) { + Set-ItResult -Inconclusive -Because "Test certificates are not installed" + } + $thumbprint = $cert.Thumbprint $certs = Get-ChildItem cert:\CurrentUser\My\$thumbprint -SSLServerAuthentication @@ -221,6 +282,10 @@ Describe "Certificate Provider tests" -Tags "Feature" { ) { param($name, $ekuSearch, $count, $thumbprint) + if ($SetupFailure) { + Set-ItResult -Inconclusive -Because "Test certificates are not installed" + } + $certs = Get-ChildItem cert:\CurrentUser\My\$thumbprint -EKU $ekuSearch $certs.Count | Should -Be $count diff --git a/test/powershell/Modules/Microsoft.PowerShell.Security/CmsMessage.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Security/CmsMessage.Tests.ps1 index 67159e5c9e2..50cbdebab69 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Security/CmsMessage.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Security/CmsMessage.Tests.ps1 @@ -81,7 +81,12 @@ Describe "CmsMessage cmdlets thorough tests" -Tags "Feature" { BeforeAll{ if($IsWindows) { - Install-TestCertificates + if (-not (Install-TestCertificates) ) { + $SetupFailure = $true + } else { + Push-Location Cert:\ + $SetupFailure = $false + } } else { @@ -92,13 +97,16 @@ Describe "CmsMessage cmdlets thorough tests" -Tags "Feature" { } AfterAll { - if($IsWindows) + if($IsWindows -and -not $SetupFailure) { Remove-TestCertificates } else { - $global:PSdefaultParameterValues = $defaultParamValues + if ($defaultParamValues -ne $null) { + $global:PSDefaultParameterValues = $defaultParamValues + } + } } @@ -136,6 +144,7 @@ Describe "CmsMessage cmdlets thorough tests" -Tags "Feature" { } It "Verify wildcarded recipient resolution by path [Decryption]" { + if ($SetupFailure) { Set-ItResult -Inconclusive -Because "Test certificates are not installed"} $errors = $null $recipient = [System.Management.Automation.CmsMessageRecipient] ((Get-GoodCertificateLocation) + "*") $recipient.Resolve($ExecutionContext.SessionState, "Decryption", [ref] $errors) @@ -145,6 +154,7 @@ Describe "CmsMessage cmdlets thorough tests" -Tags "Feature" { } It "Verify wildcarded recipient resolution by path [Encryption]" { + if ($SetupFailure) { Set-ItResult -Inconclusive -Because "Test certificates are not installed"} $errors = $null $recipient = [System.Management.Automation.CmsMessageRecipient] ((Get-GoodCertificateLocation) + "*") $recipient.Resolve($ExecutionContext.SessionState, "Encryption", [ref] $errors) @@ -153,6 +163,7 @@ Describe "CmsMessage cmdlets thorough tests" -Tags "Feature" { } It "Verify resolution by directory" { + if ($SetupFailure) { Set-ItResult -Inconclusive -Because "Test certificates are not installed"} $protectedEventLoggingCertPath = Join-Path $TestDrive ProtectedEventLoggingDir $null = New-Item -ItemType Directory $protectedEventLoggingCertPath -Force Copy-Item (Get-GoodCertificateLocation) $protectedEventLoggingCertPath @@ -167,6 +178,7 @@ Describe "CmsMessage cmdlets thorough tests" -Tags "Feature" { } It "Verify resolution by thumbprint" { + if ($SetupFailure) { Set-ItResult -Inconclusive -Because "Test certificates are not installed"} $errors = $null $recipient = [System.Management.Automation.CmsMessageRecipient] (Get-GoodCertificateObject).Thumbprint $recipient.Resolve($ExecutionContext.SessionState, "Decryption", [ref] $errors) @@ -177,6 +189,7 @@ Describe "CmsMessage cmdlets thorough tests" -Tags "Feature" { } It "Verify resolution by subject name" { + if ($SetupFailure) { Set-ItResult -Inconclusive -Because "Test certificates are not installed"} $errors = $null $recipient = [System.Management.Automation.CmsMessageRecipient] (Get-GoodCertificateObject).Subject $recipient.Resolve($ExecutionContext.SessionState, "Decryption", [ref] $errors) @@ -186,6 +199,7 @@ Describe "CmsMessage cmdlets thorough tests" -Tags "Feature" { } It "Verify error when no cert found in encryption for encryption" { + if ($SetupFailure) { Set-ItResult -Inconclusive -Because "Test certificates are not installed"} $errors = $null $recipient = [System.Management.Automation.CmsMessageRecipient] "SomeCertificateThatDoesNotExist*" $recipient.Resolve($ExecutionContext.SessionState, "Encryption", [ref] $errors) @@ -195,6 +209,7 @@ Describe "CmsMessage cmdlets thorough tests" -Tags "Feature" { } It "Verify error when encrypting to non-wildcarded identifier for decryption" { + if ($SetupFailure) { Set-ItResult -Inconclusive -Because "Test certificates are not installed"} $errors = $null $recipient = [System.Management.Automation.CmsMessageRecipient] "SomeCertificateThatDoesNotExist" $recipient.Resolve($ExecutionContext.SessionState, "Decryption", [ref] $errors) @@ -204,6 +219,7 @@ Describe "CmsMessage cmdlets thorough tests" -Tags "Feature" { } It "Verify error when encrypting to wrong cert" { + if ($SetupFailure) { Set-ItResult -Inconclusive -Because "Test certificates are not installed"} $errors = $null $recipient = [System.Management.Automation.CmsMessageRecipient] (Get-BadCertificateObject).Thumbprint $recipient.Resolve($ExecutionContext.SessionState, "Encryption", [ref] $errors) @@ -213,6 +229,7 @@ Describe "CmsMessage cmdlets thorough tests" -Tags "Feature" { } It "Verify no error when encrypting to wildcarded identifier for decryption" { + if ($SetupFailure) { Set-ItResult -Inconclusive -Because "Test certificates are not installed"} $errors = $null $recipient = [System.Management.Automation.CmsMessageRecipient] "SomeCertificateThatDoesNotExist*" $recipient.Resolve($ExecutionContext.SessionState, "Decryption", [ref] $errors) @@ -222,11 +239,14 @@ Describe "CmsMessage cmdlets thorough tests" -Tags "Feature" { } It "Verify Protect-CmsMessage emits recipient errors" { + if ($SetupFailure) { Set-ItResult -Inconclusive -Because "Test certificates are not installed"} { "Hello World" | Protect-CmsMessage -To "SomeThumbprintThatDoesNotExist" -ErrorAction Stop } | Should -Throw -ErrorId "NoCertificateFound,Microsoft.PowerShell.Commands.ProtectCmsMessageCommand" } It "Verify CmsMessage cmdlets works with paths" { + if ($SetupFailure) { Set-ItResult -Inconclusive -Because "Test certificates are not installed"} + try { $randomNum = Get-Random -Minimum 1000 -Maximum 9999 $tempPath = Join-Path $TestDrive "$randomNum-Path-Test-File" @@ -251,6 +271,8 @@ Describe "CmsMessage cmdlets thorough tests" -Tags "Feature" { } It "Verify Unprotect-CmsMessage works with local store" { + if ($SetupFailure) { Set-ItResult -Inconclusive -Because "Test certificates are not installed"} + try { $randomNum = Get-Random -Minimum 1000 -Maximum 9999 $tempPath = Join-Path $TestDrive "$randomNum-Path-Test-File" @@ -265,27 +287,37 @@ Describe "CmsMessage cmdlets thorough tests" -Tags "Feature" { } It "Verify Unprotect-CmsMessage emits recipient errors" { + if ($SetupFailure) { Set-ItResult -Inconclusive -Because "Test certificates are not installed"} + { "" | Unprotect-CmsMessage -To "SomeThumbprintThatDoesNotExist" -IncludeContext -ErrorAction Stop } | Should -Throw -ErrorId "NoCertificateFound,Microsoft.PowerShell.Commands.UnprotectCmsMessageCommand" } It "Verify failure to extract Ascii armor generates an error [Unprotect-CmsMessage]" { + if ($SetupFailure) { Set-ItResult -Inconclusive -Because "Test certificates are not installed"} + { "Hello World" | Unprotect-CmsMessage -ErrorAction Stop } | Should -Throw -ErrorId "InputContainedNoEncryptedContentIncludeContext,Microsoft.PowerShell.Commands.UnprotectCmsMessageCommand" } It "Verify failure to extract Ascii armor generates an error [Get-CmsMessage]" { + if ($SetupFailure) { Set-ItResult -Inconclusive -Because "Test certificates are not installed"} + { "Hello World" | Get-CmsMessage -ErrorAction Stop } | Should -Throw -ErrorId "InputContainedNoEncryptedContent,Microsoft.PowerShell.Commands.GetCmsMessageCommand" } It "Verify 'Unprotect-CmsMessage -IncludeContext' with no encrypted input" { + if ($SetupFailure) { Set-ItResult -Inconclusive -Because "Test certificates are not installed"} + # Should have round-tripped content $result = "Hello World" | Unprotect-CmsMessage -IncludeContext $result | Should -Be "Hello World" } It "Verify Unprotect-CmsMessage lets you include context" { + if ($SetupFailure) { Set-ItResult -Inconclusive -Because "Test certificates are not installed"} + $protected = "Hello World" | Protect-CmsMessage -To (Get-GoodCertificateLocation) $adjustedProtected = "Pre content" + [System.Environment]::NewLine + $protected + [System.Environment]::NewLine + "Post content" @@ -299,6 +331,8 @@ Describe "CmsMessage cmdlets thorough tests" -Tags "Feature" { } It "Verify Unprotect-CmsMessage treats event logs as a first class citizen" { + if ($SetupFailure) { Set-ItResult -Inconclusive -Because "Test certificates are not installed"} + $protected = "Encrypted Message1","Encrypted Message2" | Protect-CmsMessage -To (Get-GoodCertificateLocation) $virtualEventLog = Get-WinEvent Microsoft-Windows-PowerShell/Operational -MaxEvents 1 $savedId = $virtualEventLog.Id @@ -327,6 +361,8 @@ Describe "CmsMessage cmdlets thorough tests" -Tags "Feature" { } It "Verify protect message using OutString" { + if ($SetupFailure) { Set-ItResult -Inconclusive -Because "Test certificates are not installed"} + $protected = Get-Process -Id $PID | Protect-CmsMessage -To (Get-GoodCertificateLocation) $decrypted = $protected | Unprotect-CmsMessage -To (Get-GoodCertificateLocation) # Should have had PID in output diff --git a/test/powershell/Modules/Microsoft.PowerShell.Security/certificateCommon.psm1 b/test/powershell/Modules/Microsoft.PowerShell.Security/certificateCommon.psm1 index 42e990b714e..5601767a120 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Security/certificateCommon.psm1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Security/certificateCommon.psm1 @@ -240,13 +240,19 @@ nMbw+XY4C8xdDnHfS6mF+Hol98dURB/MC/x3sZ3gSjKo function Install-TestCertificates { $script:certLocation = New-GoodCertificate - $script:certLocation | Should -Not -BeNullOrEmpty | Out-Null + if (-not $script:certLocation) { + return $false + } $script:certServerLocation = New-GoodServerCertificate - $script:certServerLocation | Should -Not -BeNullOrEmpty | Out-Null + if (-not $script:certServerLocation) { + return $false + } $script:badCertLocation = New-BadCertificate - $script:badCertLocation | Should -Not -BeNullOrEmpty | Out-Null + if (-not $script:badCertLocation) { + return $false + } if ($IsCoreCLR -and $IsWindows) { diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Format-Table.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Format-Table.Tests.ps1 index 6f93c3903e9..78cfb88b613 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Format-Table.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Format-Table.Tests.ps1 @@ -892,10 +892,16 @@ Describe 'Table color tests' -Tag 'CI' { } It 'Table header should use TableHeader' { - ([pscustomobject]@{foo = 1} | Format-Table | Out-String).Trim() | Should -BeExactly @" -$($PSStyle.Formatting.TableHeader)foo$($PSStyle.Reset) -$($PSStyle.Formatting.TableHeader)---$($PSStyle.Reset) - 1 -"@ + $expected = @( + "" + "$($PSStyle.Formatting.TableHeader)foo$($PSStyle.Reset)" + "$($PSStyle.Formatting.TableHeader)---$($PSStyle.Reset)" + " 1" + "" + ) + + $actual = [pscustomobject]@{foo = 1} | Format-Table | Out-String -Stream + + $actual | Should -BeExactly $expected } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Implicit.Remoting.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Implicit.Remoting.Tests.ps1 index 0b73e7be7aa..4b459fe67d9 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Implicit.Remoting.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Implicit.Remoting.Tests.ps1 @@ -5,7 +5,7 @@ $originalDefaultParameterValues = $PSDefaultParameterValues.Clone() $originalWarningPreference = $WarningPreference $WarningPreference = "SilentlyContinue" -$skipTest = ! ($IsWindows -and $IsCoreCLR -and (Test-IsElevated)) +$skipTest = ! ($IsWindows -and $IsCoreCLR -and (Test-IsElevated)) -or (Test-IsWinWow64) $PSDefaultParameterValues["it:skip"] = $skipTest try diff --git a/test/powershell/engine/ExperimentalFeature/Get-ExperimentalFeature.Tests.ps1 b/test/powershell/engine/ExperimentalFeature/Get-ExperimentalFeature.Tests.ps1 index d36fc3fddb8..0c6f0d31195 100644 --- a/test/powershell/engine/ExperimentalFeature/Get-ExperimentalFeature.Tests.ps1 +++ b/test/powershell/engine/ExperimentalFeature/Get-ExperimentalFeature.Tests.ps1 @@ -133,7 +133,7 @@ Describe "Get-ExperimentalFeature Tests" -tags "Feature","RequireAdminOnWindows" Describe "Default enablement of Experimental Features" -Tags CI { BeforeAll { - $isPreview = $PSVersionTable.GitCommitId -match "preview|daily" + $isPreview = (Test-IsPreview -Version $PSVersionTable.PSVersion) -and (-not (Test-IsReleaseCandidate -Version $PSVersionTable.PSVersion)) Function BeEnabled { [CmdletBinding()] diff --git a/test/powershell/engine/Remoting/RemoteSession.Disconnect.Tests.ps1 b/test/powershell/engine/Remoting/RemoteSession.Disconnect.Tests.ps1 index c98e3045e7e..a6a4f23e082 100644 --- a/test/powershell/engine/Remoting/RemoteSession.Disconnect.Tests.ps1 +++ b/test/powershell/engine/Remoting/RemoteSession.Disconnect.Tests.ps1 @@ -7,7 +7,7 @@ Describe "WinRM based remoting session abrupt disconnect" -Tags 'Feature','Requi BeforeAll { $originalDefaultParameterValues = $PSDefaultParameterValues.Clone() - if (! $IsWindows) + if (! $IsWindows -or (Test-IsWinWow64)) { $PSDefaultParameterValues["it:skip"] = $true return diff --git a/test/powershell/engine/Remoting/RunspacePool.Tests.ps1 b/test/powershell/engine/Remoting/RunspacePool.Tests.ps1 index 1266a6956e9..f4481c85eb0 100644 --- a/test/powershell/engine/Remoting/RunspacePool.Tests.ps1 +++ b/test/powershell/engine/Remoting/RunspacePool.Tests.ps1 @@ -8,7 +8,7 @@ Describe "Remote runspace pool should expose commands in endpoint configuration" BeforeAll { - if ($IsWindows -and (Test-CanWriteToPsHome)) + if ($IsWindows -and (Test-CanWriteToPsHome) -and -not (Test-IsWinWow64)) { $configName = "restrictedV" $configPath = Join-Path $TestDrive ($configName + ".pssc") @@ -19,10 +19,20 @@ Describe "Remote runspace pool should expose commands in endpoint configuration" $remoteRunspacePool = New-RemoteRunspacePool -ConfigurationName $configName } + elseif (Test-IsWinWow64) + { + $originalDefaultParameterValues = $PSDefaultParameterValues.Clone() + $PSDefaultParameterValues["it:skip"] = $true + } } AfterAll { + if (Test-IsWinWow64) { + $global:PSDefaultParameterValues = $originalDefaultParameterValues + return + } + if ($IsWindows -and (Test-CanWriteToPsHome)) { if ($remoteRunspacePool -ne $null) diff --git a/test/tools/Modules/HelpersCommon/HelpersCommon.psd1 b/test/tools/Modules/HelpersCommon/HelpersCommon.psd1 index 8facd270576..f11f5432adf 100644 --- a/test/tools/Modules/HelpersCommon/HelpersCommon.psd1 +++ b/test/tools/Modules/HelpersCommon/HelpersCommon.psd1 @@ -30,10 +30,13 @@ FunctionsToExport = @( 'Start-NativeExecution' 'Test-CanWriteToPsHome' 'Test-IsElevated' + 'Test-IsPreview', + 'Test-IsReleaseCandidate' 'Test-IsRoot' 'Test-IsVstsLinux' 'Test-IsVstsWindows' 'Test-IsWindowsArm64' + 'Test-IsWinWow64' 'Test-TesthookIsSet' 'Wait-FileToBePresent' 'Wait-UntilTrue' diff --git a/test/tools/Modules/HelpersCommon/HelpersCommon.psm1 b/test/tools/Modules/HelpersCommon/HelpersCommon.psm1 index ef0683a6abe..013bd2cf700 100644 --- a/test/tools/Modules/HelpersCommon/HelpersCommon.psm1 +++ b/test/tools/Modules/HelpersCommon/HelpersCommon.psm1 @@ -400,3 +400,49 @@ function Get-WsManSupport { function Test-IsWindowsArm64 { return $IsWindows -and [System.Runtime.InteropServices.RuntimeInformation]::ProcessArchitecture -eq [System.Runtime.InteropServices.Architecture]::Arm64 } + +function Test-IsWinWow64 { + return $IsWindows -and [System.Environment]::Is64BitOperatingSystem -and -not [System.Environment]::Is64BitProcess +} + +function Test-IsPreview +{ + param( + [parameter(Mandatory)] + [string] + $Version, + + [switch]$IsLTS + ) + + if ($IsLTS.IsPresent) { + ## If we are building a LTS package, then never consider it preview. + return $false + } + + return $Version -like '*-*' +} + +<# + .Synopsis + Tests if a version is a Release Candidate + .EXAMPLE + Test-IsReleaseCandidate -version '6.1.0-sometthing' # returns false + Test-IsReleaseCandidate -version '6.1.0-rc.1' # returns true + Test-IsReleaseCandidate -version '6.1.0' # returns false +#> +function Test-IsReleaseCandidate +{ + param( + [parameter(Mandatory)] + [string] + $Version + ) + + if ($Version -like '*-rc.*') + { + return $true + } + + return $false +} diff --git a/test/tools/NamedPipeConnection/src/code/Microsoft.PowerShell.NamedPipeConnection.csproj b/test/tools/NamedPipeConnection/src/code/Microsoft.PowerShell.NamedPipeConnection.csproj index 0182a55f3e6..0a5ca72e317 100644 --- a/test/tools/NamedPipeConnection/src/code/Microsoft.PowerShell.NamedPipeConnection.csproj +++ b/test/tools/NamedPipeConnection/src/code/Microsoft.PowerShell.NamedPipeConnection.csproj @@ -15,8 +15,6 @@ - - .\Ref\System.Management.Automation.dll - + From 0ae521b7b5afe2f9f462ff269e69ad9c0e79aaac Mon Sep 17 00:00:00 2001 From: MartinGC94 <42123497+MartinGC94@users.noreply.github.com> Date: Mon, 13 Mar 2023 23:44:38 +0100 Subject: [PATCH 431/779] Improve type inference for `Get-Random` (#18972) --- .../engine/parser/TypeInferenceVisitor.cs | 17 ++++++++++++++++- .../engine/Api/TypeInference.Tests.ps1 | 18 ++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs index 993c5a45501..6795e5cfa49 100644 --- a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs +++ b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs @@ -1059,10 +1059,25 @@ private void InferTypesFrom(CommandAst commandAst, List inferredType inferredTypes.AddRange(inferTypesFromObjectCmdlets); return; } + + if (cmdletInfo.ImplementingType.FullName.EqualsOrdinalIgnoreCase("Microsoft.PowerShell.Commands.GetRandomCommand") + && pseudoBinding.BoundArguments.TryGetValue("InputObject", out var value)) + { + if (value.ParameterArgumentType == AstParameterArgumentType.PipeObject) + { + InferTypesFromPreviousCommand(commandAst, inferredTypes); + } + else if (value.ParameterArgumentType == AstParameterArgumentType.AstPair) + { + inferredTypes.AddRange(InferTypes(((AstPair)value).Argument)); + } + + return; + } } // The OutputType property ignores the parameter set specified in the OutputTypeAttribute. - // With psuedo-binding, we actually know the candidate parameter sets, so we could take + // With pseudo-binding, we actually know the candidate parameter sets, so we could take // advantage of it here, but I opted for the simpler code because so few cmdlets use // ParameterSetName in OutputType and of the ones I know about, it isn't that useful. inferredTypes.AddRange(commandInfo.OutputType); diff --git a/test/powershell/engine/Api/TypeInference.Tests.ps1 b/test/powershell/engine/Api/TypeInference.Tests.ps1 index 0376abdadab..612912029a8 100644 --- a/test/powershell/engine/Api/TypeInference.Tests.ps1 +++ b/test/powershell/engine/Api/TypeInference.Tests.ps1 @@ -524,6 +524,24 @@ Describe "Type inference Tests" -tags "CI" { $res.Name | Should -Be "System.String" } + It "Infers typeof Get-Random with pipeline input" { + $res = [AstTypeInference]::InferTypeOf( { "Hello","World" | Get-Random }.Ast) + $res.Count | Should -Be 1 + $res.Name | Should -Be "System.String" + } + + It "Infers typeof Get-Random with astpair input" { + $res = [AstTypeInference]::InferTypeOf( { Get-Random -InputObject Hello,World }.Ast) + $res.Count | Should -Be 1 + $res.Name | Should -Be "System.String[]" + } + + It "Infers typeof Get-Random with no input" { + $res = [AstTypeInference]::InferTypeOf( { Get-Random }.Ast) + $res.Count | Should -Be 3 + $res.Name -join ', ' | Should -Be "System.Int32, System.Int64, System.Double" + } + It "Infers typeof Group-Object Group" { $res = [AstTypeInference]::InferTypeOf( { Get-ChildItem | Group-Object | ForEach-Object Group }.Ast) $res.Count | Should -Be 3 From 972641c9b41a0f1db83f53c15860517548f18202 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Tue, 14 Mar 2023 00:07:23 +0100 Subject: [PATCH 432/779] Small cleanup in the WebCmdlet code (#19299) --- .../BasicHtmlWebResponseObject.Common.cs | 13 +--- .../Common/InvokeRestMethodCommand.Common.cs | 17 ++--- .../Common/WebRequestPSCmdlet.Common.cs | 11 +-- .../CoreCLR/WebResponseHelper.CoreClr.cs | 2 +- .../utility/WebCmdlet/StreamHelper.cs | 75 ++++++++----------- 5 files changed, 45 insertions(+), 73 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/BasicHtmlWebResponseObject.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/BasicHtmlWebResponseObject.Common.cs index 86d4c4dfbba..8e8c099c661 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/BasicHtmlWebResponseObject.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/BasicHtmlWebResponseObject.Common.cs @@ -167,11 +167,6 @@ protected void InitializeContent() // Fill the Content buffer string characterSet = WebResponseHelper.GetCharacterSet(BaseResponse); - if (string.IsNullOrEmpty(characterSet) && ContentHelper.IsJson(contentType)) - { - characterSet = Encoding.UTF8.HeaderName; - } - Content = StreamHelper.DecodeStream(RawContentStream, characterSet, out Encoding encoding); Encoding = encoding; } @@ -218,7 +213,7 @@ private void InitializeRawContent(HttpResponseMessage baseResponse) { StringBuilder raw = ContentHelper.GetRawContentHeader(baseResponse); raw.Append(Content); - this.RawContent = raw.ToString(); + RawContent = raw.ToString(); } private static void ParseAttributes(string outerHtml, PSObject elementObject) @@ -228,16 +223,16 @@ private static void ParseAttributes(string outerHtml, PSObject elementObject) { // Extract just the opening tag of the HTML element (omitting the closing tag and any contents, // including contained HTML elements) - var match = s_tagRegex.Match(outerHtml); + Match match = s_tagRegex.Match(outerHtml); // Extract all the attribute specifications within the HTML element opening tag - var attribMatches = s_attribsRegex.Matches(match.Value); + MatchCollection attribMatches = s_attribsRegex.Matches(match.Value); foreach (Match attribMatch in attribMatches) { // Extract the name and value for this attribute (allowing for variations like single/double/no // quotes, and no value at all) - var nvMatches = s_attribNameValueRegex.Match(attribMatch.Value); + Match nvMatches = s_attribNameValueRegex.Match(attribMatch.Value); Debug.Assert(nvMatches.Groups.Count == 5); // Name is always captured by group #1 diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs index a27e4e70008..0c97211faea 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs @@ -75,7 +75,7 @@ internal override void ProcessResponse(HttpResponseMessage response) { ArgumentNullException.ThrowIfNull(response); - var baseResponseStream = StreamHelper.GetResponseStream(response); + Stream baseResponseStream = StreamHelper.GetResponseStream(response); if (ShouldWriteToPipeline) { @@ -89,22 +89,17 @@ internal override void ProcessResponse(HttpResponseMessage response) } else { - // determine the response type + // Determine the response type RestReturnType returnType = CheckReturnType(response); // Try to get the response encoding from the ContentType header. - Encoding encoding = null; - string charSet = response.Content.Headers.ContentType?.CharSet; - if (!string.IsNullOrEmpty(charSet)) - { - StreamHelper.TryGetEncoding(charSet, out encoding); - } + string charSet = WebResponseHelper.GetCharacterSet(response); + + string str = StreamHelper.DecodeStream(responseStream, charSet, out Encoding encoding); object obj = null; Exception ex = null; - string str = StreamHelper.DecodeStream(responseStream, ref encoding); - string encodingVerboseName; try { @@ -315,7 +310,7 @@ private static bool TryConvertToJson(string json, out object obj, ref Exception } catch (JsonException ex) { - var msg = string.Format(System.Globalization.CultureInfo.CurrentCulture, WebCmdletStrings.JsonDeserializationFailed, ex.Message); + string msg = string.Format(System.Globalization.CultureInfo.CurrentCulture, WebCmdletStrings.JsonDeserializationFailed, ex.Message); exRef = new ArgumentException(msg, ex); obj = null; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index acf8135f73f..c1df22296e7 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -609,20 +609,15 @@ protected override void ProcessRecord() HttpResponseException httpEx = new(message, response); ErrorRecord er = new(httpEx, "WebCmdletWebResponseException", ErrorCategory.InvalidOperation, request); string detailMsg = string.Empty; - StreamReader reader = null; try { - reader = new StreamReader(StreamHelper.GetResponseStream(response)); - detailMsg = FormatErrorMessage(reader.ReadToEnd(), contentType); + string error = StreamHelper.GetResponseString(response); + detailMsg = FormatErrorMessage(error, contentType); } catch { // Catch all } - finally - { - reader?.Dispose(); - } if (!string.IsNullOrEmpty(detailMsg)) { @@ -1791,7 +1786,7 @@ private static string FormatErrorMessage(string error, string contentType) if (string.IsNullOrEmpty(formattedError)) { // Remove HTML tags making it easier to read - formattedError = System.Text.RegularExpressions.Regex.Replace(error, "<[^>]*>", string.Empty); + formattedError = Regex.Replace(error, "<[^>]*>", string.Empty); } return formattedError; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseHelper.CoreClr.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseHelper.CoreClr.cs index aaf921c7f0d..b1449de0692 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseHelper.CoreClr.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseHelper.CoreClr.cs @@ -10,7 +10,7 @@ namespace Microsoft.PowerShell.Commands { internal static class WebResponseHelper { - internal static string GetCharacterSet(HttpResponseMessage response) => response.Content.Headers.ContentType.CharSet; + internal static string GetCharacterSet(HttpResponseMessage response) => response.Content.Headers.ContentType?.CharSet; internal static Dictionary> GetHeadersDictionary(HttpResponseMessage response) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs index 0e219e591b9..1ddaf5a5794 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs @@ -382,49 +382,9 @@ private static string StreamToString(Stream stream, Encoding encoding) } internal static string DecodeStream(Stream stream, string characterSet, out Encoding encoding) - { - try - { - encoding = Encoding.GetEncoding(characterSet); - } - catch (ArgumentException) - { - encoding = null; - } - - return DecodeStream(stream, ref encoding); - } - - internal static bool TryGetEncoding(string characterSet, out Encoding encoding) - { - bool result = false; - try - { - encoding = Encoding.GetEncoding(characterSet); - result = true; - } - catch (ArgumentException) - { - encoding = null; - } - - return result; - } - - private static readonly Regex s_metaRegex = new( - @"<]*charset\s*=\s*[""'\n]?(?[A-Za-z].[^\s""'\n<>]*)[\s""'\n>]", - RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.ExplicitCapture | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase | RegexOptions.NonBacktracking - ); - - private static readonly Regex s_xmlRegex = new( - @"<\?xml\s.*[^.><]*encoding\s*=\s*[""'\n]?(?[A-Za-z].[^\s""'\n<>]*)[\s""'\n>]", - RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.ExplicitCapture | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase | RegexOptions.NonBacktracking - ); - - internal static string DecodeStream(Stream stream, ref Encoding encoding) { bool isDefaultEncoding = false; - if (encoding is null) + if (!TryGetEncoding(characterSet, out encoding)) { // Use the default encoding if one wasn't provided encoding = ContentHelper.GetDefaultEncoding(); @@ -449,10 +409,9 @@ internal static string DecodeStream(Stream stream, ref Encoding encoding) if (match.Success) { - Encoding localEncoding = null; - string characterSet = match.Groups["charset"].Value; + characterSet = match.Groups["charset"].Value; - if (TryGetEncoding(characterSet, out localEncoding)) + if (TryGetEncoding(characterSet, out Encoding localEncoding)) { stream.Seek(0, SeekOrigin.Begin); content = StreamToString(stream, localEncoding); @@ -464,6 +423,32 @@ internal static string DecodeStream(Stream stream, ref Encoding encoding) return content; } + internal static bool TryGetEncoding(string characterSet, out Encoding encoding) + { + bool result = false; + try + { + encoding = Encoding.GetEncoding(characterSet); + result = true; + } + catch (ArgumentException) + { + encoding = null; + } + + return result; + } + + private static readonly Regex s_metaRegex = new( + @"<]*charset\s*=\s*[""'\n]?(?[A-Za-z].[^\s""'\n<>]*)[\s""'\n>]", + RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.ExplicitCapture | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase | RegexOptions.NonBacktracking + ); + + private static readonly Regex s_xmlRegex = new( + @"<\?xml\s.*[^.><]*encoding\s*=\s*[""'\n]?(?[A-Za-z].[^\s""'\n<>]*)[\s""'\n>]", + RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.ExplicitCapture | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase | RegexOptions.NonBacktracking + ); + internal static byte[] EncodeToBytes(string str, Encoding encoding) { // Just use the default encoding if one wasn't provided @@ -472,6 +457,8 @@ internal static byte[] EncodeToBytes(string str, Encoding encoding) return encoding.GetBytes(str); } + internal static string GetResponseString(HttpResponseMessage response) => response.Content.ReadAsStringAsync().GetAwaiter().GetResult(); + internal static Stream GetResponseStream(HttpResponseMessage response) => response.Content.ReadAsStreamAsync().GetAwaiter().GetResult(); #endregion Static Methods From 799eed8f576969631221996c8ebe11231f93c8a6 Mon Sep 17 00:00:00 2001 From: MartinGC94 <42123497+MartinGC94@users.noreply.github.com> Date: Tue, 14 Mar 2023 00:17:28 +0100 Subject: [PATCH 433/779] Update and enable the test for the type of `$input` (#18968) --- .../Language/Parser/AutomaticVariables.Tests.ps1 | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/test/powershell/Language/Parser/AutomaticVariables.Tests.ps1 b/test/powershell/Language/Parser/AutomaticVariables.Tests.ps1 index cef1861f807..009def56758 100644 --- a/test/powershell/Language/Parser/AutomaticVariables.Tests.ps1 +++ b/test/powershell/Language/Parser/AutomaticVariables.Tests.ps1 @@ -2,16 +2,15 @@ # Licensed under the MIT License. Describe 'Automatic variable $input' -Tags "CI" { - # Skip on hold for discussion on https://github.com/PowerShell/PowerShell/issues/1563 # $input type in advanced functions - It '$input Type should be enumerator' -Skip { + It '$input Type should be arraylist and object array' { function from_begin { [cmdletbinding()]param() begin { Write-Output -NoEnumerate $input } } function from_process { [cmdletbinding()]param() process { Write-Output -NoEnumerate $input } } function from_end { [cmdletbinding()]param() end { Write-Output -NoEnumerate $input } } - (from_begin) -is [System.Collections.IEnumerator] | Should -BeTrue - (from_process) -is [System.Collections.IEnumerator] | Should -BeTrue - (from_end) -is [System.Collections.IEnumerator] | Should -BeTrue + (from_begin) -is [System.Collections.ArrayList] | Should -BeTrue + (from_process) -is [System.Collections.ArrayList] | Should -BeTrue + (from_end) -is [System.Object[]] | Should -BeTrue } It 'Empty $input really is empty' { From 6e408649c4490a3884ee228c17e17e650548a47a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 13 Mar 2023 17:34:39 -0700 Subject: [PATCH 434/779] Bump Microsoft.CodeAnalysis.CSharp from 4.5.0 to 4.6.0-2.23152.6 (#19306) --- .../Microsoft.PowerShell.Commands.Utility.csproj | 2 +- .../PSVersionInfoGenerator/PSVersionInfoGenerator.csproj | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj index 5170227d65f..e9c7c102290 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj +++ b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj @@ -32,7 +32,7 @@ - + diff --git a/src/System.Management.Automation/SourceGenerators/PSVersionInfoGenerator/PSVersionInfoGenerator.csproj b/src/System.Management.Automation/SourceGenerators/PSVersionInfoGenerator/PSVersionInfoGenerator.csproj index cc807a81cfd..831e38d7322 100644 --- a/src/System.Management.Automation/SourceGenerators/PSVersionInfoGenerator/PSVersionInfoGenerator.csproj +++ b/src/System.Management.Automation/SourceGenerators/PSVersionInfoGenerator/PSVersionInfoGenerator.csproj @@ -13,7 +13,7 @@ - + From e6655d1f1722cfd59188bc3cbf7d344bcfc23758 Mon Sep 17 00:00:00 2001 From: MartinGC94 <42123497+MartinGC94@users.noreply.github.com> Date: Tue, 14 Mar 2023 01:38:21 +0100 Subject: [PATCH 435/779] Fix completion for `PSCustomObject` variable properties (#18682) --- .../engine/parser/TypeInferenceVisitor.cs | 24 ++++++++++++++++++- .../TabCompletion/TabCompletion.Tests.ps1 | 7 ++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs index 6795e5cfa49..75ce67e22b1 100644 --- a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs +++ b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs @@ -427,7 +427,29 @@ private static bool TryGetRepresentativeTypeNameFromValue(object value, out PSTy value = PSObject.Base(value); if (value != null) { - type = new PSTypeName(value.GetType()); + var typeObject = value.GetType(); + + if (typeObject.FullName.Equals("System.Management.Automation.PSObject", StringComparison.Ordinal)) + { + var psobjectPropertyList = new List(); + foreach (var property in ((PSObject)value).Properties) + { + if (property.IsHidden) + { + continue; + } + + var propertyTypeName = new PSTypeName(property.TypeNameOfValue); + psobjectPropertyList.Add(new PSMemberNameAndType(property.Name, propertyTypeName, property.Value)); + } + + type = PSSyntheticTypeName.Create(typeObject, psobjectPropertyList); + } + else + { + type = new PSTypeName(typeObject); + } + return true; } } diff --git a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 index 7a3722e93d2..bf3195b7aa0 100644 --- a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 +++ b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 @@ -633,6 +633,13 @@ ConstructorTestClass(int i, bool b) $res.CompletionMatches[0].CompletionText | Should -BeExactly 'Length' } + It 'Should complete psobject members for variable' { + $TestVar = Get-Command Get-Command | Select-Object CommandType + $res = TabExpansion2 -inputScript '$TestVar | ForEach-Object {$_.commandtype' + $res | Should -HaveCount 1 + $res.CompletionMatches[0].CompletionText | Should -BeExactly 'CommandType' + } + Context "Format cmdlet's View paramter completion" { BeforeAll { $viewDefinition = @' From c2e06542cdcd9c21c427767bdfb28d7bdd3b0051 Mon Sep 17 00:00:00 2001 From: PowerShell Team Bot <69177312+pwshBot@users.noreply.github.com> Date: Mon, 13 Mar 2023 17:38:53 -0700 Subject: [PATCH 436/779] Update to the latest NOTICES file (#19309) --- ThirdPartyNotices.txt | 383 +++++++++++++++--------------------------- 1 file changed, 133 insertions(+), 250 deletions(-) diff --git a/ThirdPartyNotices.txt b/ThirdPartyNotices.txt index 99ad0e45ece..b945bd44d07 100644 --- a/ThirdPartyNotices.txt +++ b/ThirdPartyNotices.txt @@ -17,19 +17,119 @@ required to debug changes to any libraries licensed under the GNU Lesser General --------------------------------------------------------- -Markdig.Signed 0.30.4 - BSD-2-Clause +Microsoft.Extensions.ObjectPool 5.0.10 - Apache-2.0 +(c) Microsoft Corporation +Copyright (c) Andrew Arnott +Copyright (c) 2019 David Fowler +Copyright (c) 2016 Richard Morris +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) Microsoft Corporation +Copyright (c) 2014-2018 Michael Daines +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2019-2020 West Wind Technologies +Copyright (c) 2010-2019 Google LLC. http://angular.io/license +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Apache License + +Version 2.0, January 2004 + +http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + + + "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + + + + "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + + + + "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + + + + "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + + + + "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + + + + "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + + + + "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + + + + "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + + + + "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + + + + "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + + (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. -Copyright (c) . All rights reserved. + You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. - 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. - 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + +To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); + +you may not use this file except in compliance with the License. + +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software + +distributed under the License is distributed on an "AS IS" BASIS, + +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + +See the License for the specific language governing permissions and + +limitations under the License. --------------------------------------------------------- @@ -53,56 +153,44 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI --------------------------------------------------------- -Microsoft.Bcl.AsyncInterfaces 7.0.0 - MIT +Microsoft.Bcl.AsyncInterfaces 5.0.0 - MIT -(c) Microsoft Corporation +(c) Microsoft Corporation. Copyright (c) Andrew Arnott -Copyright 2019 LLVM Project Copyright 2018 Daniel Lemire -Copyright (c) .NET Foundation +Copyright 2012 the V8 project +Copyright (c) .NET Foundation. Copyright (c) 2011, Google Inc. -Copyright (c) 2020 Dan Shechter -(c) 1997-2005 Sean Eron Anderson Copyright (c) 1998 Microsoft. To +(c) 1997-2005 Sean Eron Anderson. Copyright (c) 2017 Yoshifumi Kawai -Copyright (c) 2005-2020 Rich Felker Copyright (c) Microsoft Corporation Copyright (c) 2007 James Newton-King Copyright (c) 2012-2014, Yann Collet -Copyright (c) 1991-2022 Unicode, Inc. Copyright (c) 2013-2017, Alfred Klomp -Copyright 2012 the V8 project authors -Copyright (c) 1999 Lucent Technologies -Copyright (c) 2008-2016, Wojciech Mula -Copyright (c) 2011-2020 Microsoft Corp Copyright (c) 2015-2017, Wojciech Mula -Copyright (c) 2021 csFastFloat authors Copyright (c) 2005-2007, Nick Galbreath -Copyright (c) 2015 The Chromium Authors Copyright (c) 2018 Alexander Chermyanin -Copyright (c) The Internet Society 1997 Portions (c) International Organization +Copyright (c) 2015 The Chromium Authors. +Copyright (c) The Internet Society 1997. Copyright (c) 2004-2006 Intel Corporation Copyright (c) 2013-2017, Milosz Krajewski Copyright (c) 2016-2017, Matthieu Darbois -Copyright (c) The Internet Society (2003) Copyright (c) .NET Foundation Contributors -Copyright (c) 2020 Mara Bos +Copyright (c) The Internet Society (2003). Copyright (c) .NET Foundation and Contributors -Copyright (c) 2008-2020 Advanced Micro Devices, Inc. -Copyright (c) 2019 Microsoft Corporation, Daan Leijen Copyright (c) 2011 Novell, Inc (http://www.novell.com) -Copyright (c) 1995-2022 Jean-loup Gailly and Mark Adler +Copyright (c) 1995-2017 Jean-loup Gailly and Mark Adler Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) -Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors. Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. -Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers -Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip -Copyright (c) 1980, 1986, 1993 The Regents of the University of California -Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California -Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip. +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers THIS WORK IS PROVIDED AS +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California. +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass. Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass. To The MIT License (MIT) @@ -130,66 +218,6 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ---------------------------------------------------------- - ---------------------------------------------------------- - -Microsoft.CodeAnalysis.Common 4.4.0 - MIT - - -(c) Microsoft Corporation -Copyright (c) .NET Foundation and Contributors - -MIT License - -Copyright (c) - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - ---------------------------------------------------------- - ---------------------------------------------------------- - -Microsoft.CodeAnalysis.CSharp 4.4.0 - MIT - - -(c) Microsoft Corporation -Copyright (c) Microsoft Corporation -Copyright (c) .NET Foundation and Contributors -Copyright (c) Microsoft Corporation. Alle Rechte - -MIT License - -Copyright (c) - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - ---------------------------------------------------------- - ---------------------------------------------------------- - -Microsoft.Extensions.ObjectPool 7.0.3 - MIT - - - -MIT License - -Copyright (c) - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - --------------------------------------------------------- --------------------------------------------------------- @@ -290,45 +318,29 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI --------------------------------------------------------- -Microsoft.Win32.Registry 5.0.0 - MIT +Microsoft.Win32.Registry 4.7.0 - MIT (c) Microsoft Corporation. -Copyright (c) Andrew Arnott -Copyright 2018 Daniel Lemire -Copyright 2012 the V8 project Copyright (c) .NET Foundation. Copyright (c) 2011, Google Inc. -Copyright (c) 1998 Microsoft. To (c) 1997-2005 Sean Eron Anderson. -Copyright (c) 2017 Yoshifumi Kawai -Copyright (c) Microsoft Corporation Copyright (c) 2007 James Newton-King -Copyright (c) 2012-2014, Yann Collet +Copyright (c) 1991-2017 Unicode, Inc. Copyright (c) 2013-2017, Alfred Klomp Copyright (c) 2015-2017, Wojciech Mula Copyright (c) 2005-2007, Nick Galbreath -Copyright (c) 2018 Alexander Chermyanin Portions (c) International Organization Copyright (c) 2015 The Chromium Authors. -Copyright (c) The Internet Society 1997. Copyright (c) 2004-2006 Intel Corporation -Copyright (c) 2013-2017, Milosz Krajewski Copyright (c) 2016-2017, Matthieu Darbois Copyright (c) .NET Foundation Contributors -Copyright (c) The Internet Society (2003). Copyright (c) .NET Foundation and Contributors Copyright (c) 2011 Novell, Inc (http://www.novell.com) Copyright (c) 1995-2017 Jean-loup Gailly and Mark Adler Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors. -Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com -Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. -Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip. Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers THIS WORK IS PROVIDED AS -Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California. -Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass. -Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass. To The MIT License (MIT) @@ -1823,57 +1835,9 @@ SOFTWARE. --------------------------------------------------------- -System.Diagnostics.DiagnosticSource 7.0.0 - MIT +System.Diagnostics.DiagnosticSource 7.0.1 - MIT -(c) Microsoft Corporation -Copyright (c) Andrew Arnott -Copyright 2019 LLVM Project -Copyright 2018 Daniel Lemire -Copyright (c) .NET Foundation -Copyright (c) 2011, Google Inc. -Copyright (c) 2020 Dan Shechter -(c) 1997-2005 Sean Eron Anderson -Copyright (c) 1998 Microsoft. To -Copyright (c) 2017 Yoshifumi Kawai -Copyright (c) 2005-2020 Rich Felker -Copyright (c) Microsoft Corporation -Copyright (c) 2007 James Newton-King -Copyright (c) 2012-2014, Yann Collet -Copyright (c) 1991-2022 Unicode, Inc. -Copyright (c) 2013-2017, Alfred Klomp -Copyright 2012 the V8 project authors -Copyright (c) 1999 Lucent Technologies -Copyright (c) 2008-2016, Wojciech Mula -Copyright (c) 2011-2020 Microsoft Corp -Copyright (c) 2015-2017, Wojciech Mula -Copyright (c) 2021 csFastFloat authors -Copyright (c) 2005-2007, Nick Galbreath -Copyright (c) 2015 The Chromium Authors -Copyright (c) 2018 Alexander Chermyanin -Copyright (c) The Internet Society 1997 -Portions (c) International Organization -Copyright (c) 2004-2006 Intel Corporation -Copyright (c) 2013-2017, Milosz Krajewski -Copyright (c) 2016-2017, Matthieu Darbois -Copyright (c) The Internet Society (2003) -Copyright (c) .NET Foundation Contributors -Copyright (c) 2020 Mara Bos -Copyright (c) .NET Foundation and Contributors -Copyright (c) 2008-2020 Advanced Micro Devices, Inc. -Copyright (c) 2019 Microsoft Corporation, Daan Leijen -Copyright (c) 2011 Novell, Inc (http://www.novell.com) -Copyright (c) 1995-2022 Jean-loup Gailly and Mark Adler -Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) -Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors -Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com -Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. -Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers -Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip -Copyright (c) 1980, 1986, 1993 The Regents of the University of California -Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California -Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass -Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass. To The MIT License (MIT) @@ -2066,7 +2030,7 @@ SOFTWARE. --------------------------------------------------------- -System.DirectoryServices 7.0.0 - MIT +System.DirectoryServices 7.0.1 - MIT (c) Microsoft Corporation @@ -2710,54 +2674,6 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ---------------------------------------------------------- - ---------------------------------------------------------- - -System.Memory 4.5.5 - MIT - - -(c) 2022 GitHub, Inc. -(c) Microsoft Corporation -Copyright (c) 2011, Google Inc. -(c) 1997-2005 Sean Eron Anderson -Copyright (c) 1991-2017 Unicode, Inc. -Copyright (c) 2015 The Chromium Authors -Portions (c) International Organization -Copyright (c) 2004-2006 Intel Corporation -Copyright (c) .NET Foundation Contributors -Copyright (c) .NET Foundation and Contributors -Copyright (c) 2011 Novell, Inc (http://www.novell.com) -Copyright (c) 1995-2017 Jean-loup Gailly and Mark Adler -Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) -Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors -Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers - -The MIT License (MIT) - -Copyright (c) .NET Foundation and Contributors - -All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - - --------------------------------------------------------- --------------------------------------------------------- @@ -3057,45 +2973,9 @@ SOFTWARE. --------------------------------------------------------- -System.Reflection.Metadata 5.0.0 - MIT +System.Reflection.Metadata 6.0.1 - MIT -(c) Microsoft Corporation. -Copyright (c) Andrew Arnott -Copyright 2018 Daniel Lemire -Copyright 2012 the V8 project -Copyright (c) .NET Foundation. -Copyright (c) 2011, Google Inc. -Copyright (c) 1998 Microsoft. To -(c) 1997-2005 Sean Eron Anderson. -Copyright (c) 2017 Yoshifumi Kawai -Copyright (c) Microsoft Corporation -Copyright (c) 2007 James Newton-King -Copyright (c) 2012-2014, Yann Collet -Copyright (c) 2013-2017, Alfred Klomp -Copyright (c) 2015-2017, Wojciech Mula -Copyright (c) 2005-2007, Nick Galbreath -Copyright (c) 2018 Alexander Chermyanin -Portions (c) International Organization -Copyright (c) 2015 The Chromium Authors. -Copyright (c) The Internet Society 1997. -Copyright (c) 2004-2006 Intel Corporation -Copyright (c) 2013-2017, Milosz Krajewski -Copyright (c) 2016-2017, Matthieu Darbois -Copyright (c) .NET Foundation Contributors -Copyright (c) The Internet Society (2003). -Copyright (c) .NET Foundation and Contributors -Copyright (c) 2011 Novell, Inc (http://www.novell.com) -Copyright (c) 1995-2017 Jean-loup Gailly and Mark Adler -Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) -Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors. -Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com -Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. -Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip. -Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers THIS WORK IS PROVIDED AS -Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California. -Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass. -Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass. To The MIT License (MIT) @@ -3347,7 +3227,7 @@ SOFTWARE. --------------------------------------------------------- -System.Security.Cryptography.Pkcs 7.0.0 - MIT +System.Security.Cryptography.Pkcs 7.0.1 - MIT (c) Microsoft Corporation @@ -3428,7 +3308,7 @@ SOFTWARE. --------------------------------------------------------- -System.Security.Cryptography.ProtectedData 7.0.0 - MIT +System.Security.Cryptography.ProtectedData 7.0.1 - MIT (c) Microsoft Corporation @@ -3509,7 +3389,7 @@ SOFTWARE. --------------------------------------------------------- -System.Security.Cryptography.Xml 7.0.0 - MIT +System.Security.Cryptography.Xml 7.0.1 - MIT (c) Microsoft Corporation @@ -4310,7 +4190,7 @@ SOFTWARE. --------------------------------------------------------- -System.Threading.AccessControl 7.0.0 - MIT +System.Threading.AccessControl 7.0.1 - MIT (c) Microsoft Corporation @@ -4438,9 +4318,12 @@ SOFTWARE. --------------------------------------------------------- -System.Web.Services.Description 4.10.0 - MIT +System.Web.Services.Description 4.9.0 - MIT +(c) Microsoft Corporation. +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2000-2014 The Legion of the Bouncy Castle Inc. (http://www.bouncycastle.org) The MIT License (MIT) From 7bca828670f3ef434010ad41a439b137c36112e8 Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Mon, 13 Mar 2023 19:22:30 -0700 Subject: [PATCH 437/779] Restructure the package build to simplify signing and packaging stages (#19321) --- .../releaseBuild/azureDevOps/releaseBuild.yml | 299 +++++++++++----- .../templates/compliance/compliance.yml | 2 +- .../azureDevOps/templates/json.yml | 2 +- .../azureDevOps/templates/linux-packaging.yml | 2 - .../templates/mac-file-signing.yml | 1 - .../templates/mac-package-build.yml | 1 - .../azureDevOps/templates/nuget.yml | 2 +- .../azureDevOps/templates/sign-build-file.yml | 324 ++++++++++++++++++ .../templates/windows-hosted-build.yml | 2 +- .../templates/windows-package-signing.yml | 2 +- .../templates/windows-packaging.yml | 3 +- 11 files changed, 534 insertions(+), 106 deletions(-) create mode 100644 tools/releaseBuild/azureDevOps/templates/sign-build-file.yml diff --git a/tools/releaseBuild/azureDevOps/releaseBuild.yml b/tools/releaseBuild/azureDevOps/releaseBuild.yml index 32f6bcca599..b670d55de74 100644 --- a/tools/releaseBuild/azureDevOps/releaseBuild.yml +++ b/tools/releaseBuild/azureDevOps/releaseBuild.yml @@ -51,6 +51,7 @@ variables: value: spdx:2.2 - name: BUILDSECMON_OPT_IN value: true + - group: PoolNames stages: - stage: prep @@ -68,30 +69,6 @@ stages: parameters: buildArchitecture: arm64 - - template: templates/mac-file-signing.yml - parameters: - buildArchitecture: x64 - - - template: templates/mac-file-signing.yml - parameters: - buildArchitecture: arm64 - - - template: templates/mac-package-build.yml - parameters: - buildArchitecture: x64 - - - template: templates/mac-package-build.yml - parameters: - buildArchitecture: arm64 - - - template: templates/mac-package-signing.yml - parameters: - buildArchitecture: x64 - - - template: templates/mac-package-signing.yml - parameters: - buildArchitecture: arm64 - - stage: linux dependsOn: ['prep'] jobs: @@ -113,29 +90,6 @@ stages: parameters: buildName: alpine - - template: templates/linux-authenticode-sign.yml - - - template: templates/linux-packaging.yml - parameters: - buildName: deb - parentJob: sign_linux_builds - - - template: templates/linux-packaging.yml - parameters: - buildName: rpm - uploadDisplayName: Upload and Sign - parentJob: sign_linux_builds - - - template: templates/linux-packaging.yml - parameters: - buildName: alpine - parentJob: sign_linux_builds - - - template: templates/linux-packaging.yml - parameters: - buildName: fxdependent - parentJob: sign_linux_builds - - stage: windows dependsOn: ['prep'] jobs: @@ -168,66 +122,221 @@ stages: parameters: Architecture: fxdependentWinDesktop - - template: templates/windows-packaging.yml - parameters: - Architecture: x64 - parentJob: build_windows_x64_release - - - template: templates/windows-packaging.yml - parameters: - Architecture: x64 - BuildConfiguration: minSize - parentJob: build_windows_x64_minSize - - - template: templates/windows-packaging.yml - parameters: - Architecture: x86 - parentJob: build_windows_x86_release - - - template: templates/windows-packaging.yml - parameters: - Architecture: arm - parentJob: build_windows_arm_release - - - template: templates/windows-packaging.yml - parameters: - Architecture: arm64 - parentJob: build_windows_arm64_release - - - template: templates/windows-packaging.yml - parameters: - Architecture: fxdependent - parentJob: build_windows_fxdependent_release + - stage: SignFiles + displayName: Sign files + dependsOn: ['windows', 'linux', 'macos'] + jobs: + - template: templates/mac-file-signing.yml + parameters: + buildArchitecture: x64 + + - template: templates/mac-file-signing.yml + parameters: + buildArchitecture: arm64 + + - job: SignFilesWinLinux + pool: + name: $(windowsPool) + demands: + - ImageOverride -equals PSMMS2019-Secure + displayName: Sign files + + variables: + - group: ESRP + - name: runCodesignValidationInjection + value: false + - name: NugetSecurityAnalysisWarningLevel + value: none + - name: repoFolder + value: PowerShell + - name: repoRoot + value: $(Agent.BuildDirectory)\$(repoFolder) + - name: complianceRepoFolder + value: compliance + + strategy: + matrix: + linux-x64: + runtime: linux-x64 + unsignedBuildArtifactContainer: pwshLinuxBuild.tar.gz + unsignedBuildArtifactName: pwshLinuxBuild.tar.gz + signedBuildArtifactName: pwshLinuxBuild.tar.gz + signedArtifactContainer: authenticode-signed + linux-x64-Alpine: + runtime: linux-x64-Alpine + unsignedBuildArtifactContainer: pwshLinuxBuildAlpine.tar.gz + unsignedBuildArtifactName: pwshLinuxBuild.tar.gz + signedBuildArtifactName: pwshLinuxBuildAlpine.tar.gz + signedArtifactContainer: authenticode-signed + linux-arm32: + runtime: linux-arm32 + unsignedBuildArtifactContainer: pwshLinuxBuildArm32.tar.gz + unsignedBuildArtifactName: pwshLinuxBuildArm32.tar.gz + signedBuildArtifactName: pwshLinuxBuildArm32.tar.gz + signedArtifactContainer: authenticode-signed + linux-arm64: + runtime: linux-arm64 + unsignedBuildArtifactContainer: pwshLinuxBuildArm64.tar.gz + unsignedBuildArtifactName: pwshLinuxBuildArm64.tar.gz + signedBuildArtifactName: pwshLinuxBuildArm64.tar.gz + signedArtifactContainer: authenticode-signed + linux-fxd: + runtime: linux-fxd + unsignedBuildArtifactContainer: pwshLinuxBuildFxdependent.tar.gz + unsignedBuildArtifactName: pwshLinuxBuild.tar.gz + signedBuildArtifactName: pwshLinuxBuildFxdependent.tar.gz + signedArtifactContainer: authenticode-signed + linux-mariner: + runtime: linux-mariner + unsignedBuildArtifactContainer: pwshMarinerBuildAmd64.tar.gz + unsignedBuildArtifactName: pwshMarinerBuildAmd64.tar.gz + signedBuildArtifactName: pwshMarinerBuildAmd64.tar.gz + signedArtifactContainer: authenticode-signed + linux-minsize: + runtime: linux-minsize + unsignedBuildArtifactContainer: pwshLinuxBuildMinSize.tar.gz + unsignedBuildArtifactName: pwshLinuxBuildMinSize.tar.gz + signedBuildArtifactName: pwshLinuxBuildMinSize.tar.gz + signedArtifactContainer: authenticode-signed + win-x64: + runtime: win-x64 + unsignedBuildArtifactContainer: results + unsignedBuildArtifactName: '**/*-symbols-win-x64.zip' + signedBuildArtifactName: '-symbols-win-x64-signed.zip' + signedArtifactContainer: results + win-x86: + runtime: win-x86 + unsignedBuildArtifactContainer: results + unsignedBuildArtifactName: '**/*-symbols-win-x86.zip' + signedBuildArtifactName: '-symbols-win-x86-signed.zip' + signedArtifactContainer: results + win-arm32: + runtime: win-arm32 + unsignedBuildArtifactContainer: results + unsignedBuildArtifactName: '**/*-symbols-win-arm32.zip' + signedBuildArtifactName: '-symbols-win-arm32-signed.zip' + signedArtifactContainer: results + win-arm64: + runtime: win-arm64 + unsignedBuildArtifactContainer: results + unsignedBuildArtifactName: '**/*-symbols-win-arm64.zip' + signedBuildArtifactName: '-symbols-win-arm64-signed.zip' + signedArtifactContainer: results + win-x64-gc: + runtime: win-x64-gc + unsignedBuildArtifactContainer: results + unsignedBuildArtifactName: '**/*-symbols-win-x64-gc.zip' + signedBuildArtifactName: '-symbols-win-x64-gc-signed.zip' + signedArtifactContainer: results + win-fxdependent: + runtime: win-fxdependent + unsignedBuildArtifactContainer: results + unsignedBuildArtifactName: '**/*-symbols-win-fxdependent.zip' + signedBuildArtifactName: '-symbols-win-fxdependent-signed.zip' + signedArtifactContainer: results + win-fxdependentWinDesktop: + runtime: win-fxdependentWinDesktop + unsignedBuildArtifactContainer: results + unsignedBuildArtifactName: '**/*-symbols-win-fxdependentWinDesktop.zip' + signedBuildArtifactName: '-symbols-win-fxdependentWinDesktop-signed.zip' + signedArtifactContainer: results + steps: + - template: templates/sign-build-file.yml + + - stage: mac_packaging + displayName: macOS packaging + dependsOn: ['SignFiles'] + jobs: + - template: templates/mac-package-build.yml + parameters: + buildArchitecture: x64 - - template: templates/windows-packaging.yml - parameters: - Architecture: fxdependentWinDesktop - parentJob: build_windows_fxdependentWinDesktop_release + - template: templates/mac-package-build.yml + parameters: + buildArchitecture: arm64 - - template: templates/windows-package-signing.yml - parameters: - parentJobs: - - sign_windows_x64_release - - sign_windows_x64_minSize - - sign_windows_x86_release - - sign_windows_arm_release - - sign_windows_arm64_release - - sign_windows_fxdependent_release - - sign_windows_fxdependentWinDesktop_release + - stage: linux_packaging + displayName: Linux Packaging + dependsOn: ['SignFiles'] + jobs: + - template: templates/linux-packaging.yml + parameters: + buildName: deb + + - template: templates/linux-packaging.yml + parameters: + buildName: rpm + uploadDisplayName: Upload and Sign + + - template: templates/linux-packaging.yml + parameters: + buildName: alpine + + - template: templates/linux-packaging.yml + parameters: + buildName: fxdependent + + - stage: win_packaging + displayName: Windows Packaging + dependsOn: ['SignFiles'] + jobs: + - template: templates/windows-packaging.yml + parameters: + Architecture: x64 + parentJob: build_windows_x64_release + + - template: templates/windows-packaging.yml + parameters: + Architecture: x64 + BuildConfiguration: minSize + parentJob: build_windows_x64_minSize + + - template: templates/windows-packaging.yml + parameters: + Architecture: x86 + parentJob: build_windows_x86_release + + - template: templates/windows-packaging.yml + parameters: + Architecture: arm + parentJob: build_windows_arm_release + + - template: templates/windows-packaging.yml + parameters: + Architecture: arm64 + parentJob: build_windows_arm64_release + + - template: templates/windows-packaging.yml + parameters: + Architecture: fxdependent + parentJob: build_windows_fxdependent_release + + - template: templates/windows-packaging.yml + parameters: + Architecture: fxdependentWinDesktop + parentJob: build_windows_fxdependentWinDesktop_release + + - stage: package_signing + displayName: Package Signing + dependsOn: ['mac_packaging', 'linux_packaging', 'win_packaging'] + jobs: + - template: templates/windows-package-signing.yml + # This is done late so that we dont use resources before the big signing and packaging tasks. - stage: compliance - dependsOn: ['windows'] + dependsOn: ['package_signing'] jobs: - template: templates/compliance.yml - stage: nuget_and_json - dependsOn: ['windows','linux','macOS'] + displayName: NuGet Packaging and Build Json + dependsOn: [package_signing] jobs: - template: templates/nuget.yml - - template: templates/json.yml - stage: test_and_release_artifacts + displayName: Test and Release Artifacts dependsOn: ['prep'] jobs: - template: templates/testartifacts.yml @@ -235,7 +344,7 @@ stages: - job: release_json displayName: Create and Upload release.json pool: - name: PowerShell1ES + name: $(windowsPool) demands: - ImageOverride -equals PSMMS2019-Secure steps: diff --git a/tools/releaseBuild/azureDevOps/templates/compliance/compliance.yml b/tools/releaseBuild/azureDevOps/templates/compliance/compliance.yml index 13603a0c808..8db52fc83f0 100644 --- a/tools/releaseBuild/azureDevOps/templates/compliance/compliance.yml +++ b/tools/releaseBuild/azureDevOps/templates/compliance/compliance.yml @@ -17,7 +17,7 @@ jobs: dependsOn: ${{ parameters.parentJobs }} pool: - name: PowerShell1ES + name: $(windowsPool) demands: - ImageOverride -equals PSMMS2019-Secure diff --git a/tools/releaseBuild/azureDevOps/templates/json.yml b/tools/releaseBuild/azureDevOps/templates/json.yml index 1d6c10b8f3e..48a50e0bf14 100644 --- a/tools/releaseBuild/azureDevOps/templates/json.yml +++ b/tools/releaseBuild/azureDevOps/templates/json.yml @@ -13,7 +13,7 @@ jobs: ${{ parameters.parentJobs }} condition: succeeded() pool: - name: PowerShell1ES + name: $(windowsPool) demands: - ImageOverride -equals PSMMS2019-Secure diff --git a/tools/releaseBuild/azureDevOps/templates/linux-packaging.yml b/tools/releaseBuild/azureDevOps/templates/linux-packaging.yml index 6837444b1be..1d6925c737c 100644 --- a/tools/releaseBuild/azureDevOps/templates/linux-packaging.yml +++ b/tools/releaseBuild/azureDevOps/templates/linux-packaging.yml @@ -1,7 +1,6 @@ parameters: buildName: '' uploadDisplayName: 'Upload' - parentJob: '' jobs: - job: pkg_${{ parameters.buildName }} @@ -11,7 +10,6 @@ jobs: name: PowerShell1ES demands: - ImageOverride -equals PSMMSUbuntu20.04-Secure - dependsOn: sign_linux_builds variables: - name: runCodesignValidationInjection value: false diff --git a/tools/releaseBuild/azureDevOps/templates/mac-file-signing.yml b/tools/releaseBuild/azureDevOps/templates/mac-file-signing.yml index 5af4295994e..8159c2bc7d9 100644 --- a/tools/releaseBuild/azureDevOps/templates/mac-file-signing.yml +++ b/tools/releaseBuild/azureDevOps/templates/mac-file-signing.yml @@ -4,7 +4,6 @@ parameters: jobs: - job: MacFileSigningJob_${{ parameters.buildArchitecture }} displayName: macOS File signing ${{ parameters.buildArchitecture }} - dependsOn: build_macOS_${{ parameters.buildArchitecture }} condition: succeeded() pool: name: PowerShell1ES diff --git a/tools/releaseBuild/azureDevOps/templates/mac-package-build.yml b/tools/releaseBuild/azureDevOps/templates/mac-package-build.yml index 0f5b9acbc13..fc5c638c268 100644 --- a/tools/releaseBuild/azureDevOps/templates/mac-package-build.yml +++ b/tools/releaseBuild/azureDevOps/templates/mac-package-build.yml @@ -5,7 +5,6 @@ parameters: jobs: - job: package_macOS_${{ parameters.buildArchitecture }} displayName: Package macOS ${{ parameters.buildArchitecture }} - dependsOn: MacFileSigningJob_${{ parameters.buildArchitecture }} condition: succeeded() pool: vmImage: macos-latest diff --git a/tools/releaseBuild/azureDevOps/templates/nuget.yml b/tools/releaseBuild/azureDevOps/templates/nuget.yml index 269b6149645..ddff73d3511 100644 --- a/tools/releaseBuild/azureDevOps/templates/nuget.yml +++ b/tools/releaseBuild/azureDevOps/templates/nuget.yml @@ -8,7 +8,7 @@ jobs: displayName: Build NuGet packages condition: succeeded() pool: - name: PowerShell1ES + name: $(windowsPool) demands: - ImageOverride -equals PSMMS2019-Secure diff --git a/tools/releaseBuild/azureDevOps/templates/sign-build-file.yml b/tools/releaseBuild/azureDevOps/templates/sign-build-file.yml new file mode 100644 index 00000000000..cfa172796d8 --- /dev/null +++ b/tools/releaseBuild/azureDevOps/templates/sign-build-file.yml @@ -0,0 +1,324 @@ +steps: +- pwsh: | + $platform = '$(runtime)' -match '^linux' ? 'linux' : 'windows' + $vstsCommandString = "vso[task.setvariable variable=ArtifactPlatform]$platform" + Write-Host ("sending " + $vstsCommandString) + Write-Host "##$vstsCommandString" + displayName: Set artifact platform + +- task: DownloadPipelineArtifact@2 + inputs: + artifactName: '$(unsignedBuildArtifactContainer)' + itemPattern: '$(unsignedBuildArtifactName)' + +- pwsh: | + Get-ChildItem "$(Pipeline.Workspace)\*" -Recurse + displayName: 'Capture Downloaded Artifacts' + # Diagnostics is not critical it passes every time it runs + continueOnError: true + +- checkout: self + clean: true + path: $(repoFolder) + +- template: SetVersionVariables.yml + parameters: + ReleaseTagVar: $(ReleaseTagVar) + +- template: cloneToOfficialPath.yml + +- pwsh: | + $zipFileFilter = '$(unsignedBuildArtifactName)' + $zipFileFilter = $zipFileFilter.Replace('**/', '') + + Write-Verbose -Verbose -Message "zipFileFilter = $zipFileFilter" + + Write-Verbose -Verbose -Message "Looking for $(Pipeline.Workspace)\$(unsignedBuildArtifactName)" + + $zipFilePath = Get-ChildItem -Path '$(Pipeline.Workspace)\$(unsignedBuildArtifactName)' -recurse + + if (-not (Test-Path $zipFilePath)) + { + throw "zip file not found: $zipfilePath" + } + + if ($zipFilePath.Count -ne 1) { + Write-Verbose "zip filename" -verbose + $zipFilePath | Out-String | Write-Verbose -Verbose + throw 'multiple zip files found when 1 was expected' + } + + $expandedFolderName = [System.io.path]::GetFileNameWithoutExtension($zipfilePath) + $expandedFolderPath = Join-Path '$(Pipeline.Workspace)' 'expanded' $expandedFolderName + + Write-Verbose -Verbose -Message "Expaning $zipFilePath to $expandedFolderPath" + + New-Item -Path $expandedFolderPath -ItemType Directory + Expand-Archive -Path $zipFilePath -DestinationPath $expandedFolderPath + + if (-not (Test-Path $expandedFolderPath\pwsh.exe) ) { + throw 'zip did not expand as expected' + } + else { + $vstsCommandString = "vso[task.setvariable variable=BinPath]$expandedFolderPath" + Write-Host ("sending " + $vstsCommandString) + Write-Host "##$vstsCommandString" + } + + displayName: Expand zip packages + condition: eq(variables['ArtifactPlatform'], 'windows') + +- pwsh: | + $tarPackageName = '$(unsignedBuildArtifactName)' + + Write-Verbose -Verbose -Message "tarPackageName = $tarPackageName" + + $tarPackagePath = Join-Path '$(Pipeline.Workspace)' $tarPackageName + + Write-Verbose -Verbose -Message "Looking for: $tarPackagePath" + + $expandedPathFolderName = $tarPackageName -replace '.tar.gz', '' + $expandedFolderPath = Join-Path '$(Pipeline.Workspace)' 'expanded' $expandedPathFolderName + + if (-not (Test-Path $tarPackagePath)) + { + throw "tar file not found: $tarPackagePath" + } + + Write-Verbose -Verbose -Message "Expanding $tarPackagePath to $expandedFolderPath" + + New-Item -Path $expandedFolderPath -ItemType Directory + tar -xf $tarPackagePath -C $expandedFolderPath + + if (-not (Test-Path $expandedFolderPath/pwsh) ) { + throw 'tar.gz did not expand as expected' + } + else { + $vstsCommandString = "vso[task.setvariable variable=BinPath]$expandedFolderPath" + Write-Host ("sending " + $vstsCommandString) + Write-Host "##$vstsCommandString" + } + + Write-Verbose -Verbose "File permisions after expanding" + Get-ChildItem -Path "$expandedFolderPath/pwsh" | Select-Object -Property 'unixmode', 'size', 'name' + displayName: Expand tar.gz packages + condition: eq(variables['ArtifactPlatform'], 'linux') + +- template: insert-nuget-config-azfeed.yml + parameters: + repoRoot: $(PowerShellRoot) + +- pwsh: | + Set-Location $env:POWERSHELLROOT + import-module "$env:POWERSHELLROOT/build.psm1" + Sync-PSTags -AddRemoteIfMissing + displayName: SyncTags + condition: and(succeeded(), ne(variables['SkipBuild'], 'true')) + +- checkout: ComplianceRepo + clean: true + path: $(complianceRepoFolder) + +- template: shouldSign.yml + +- pwsh: | + $fullSymbolsFolder = '$(BinPath)' + Write-Verbose -Verbose "fullSymbolsFolder == $fullSymbolsFolder" + + Get-ChildItem -Recurse $fullSymbolsFolder | out-string | Write-Verbose -Verbose + + $filesToSignDirectory = "$(System.ArtifactsDirectory)\toBeSigned" + + if ((Test-Path -Path $filesToSignDirectory)) { + Remove-Item -Path $filesToSignDirectory -Recurse -Force + } + + $null = New-Item -ItemType Directory -Path $filesToSignDirectory -Force + + $signedFilesDirectory = "$(System.ArtifactsDirectory)\signed" + + if ((Test-Path -Path $signedFilesDirectory)) { + Remove-Item -Path $signedFilesDirectory -Recurse -Force + } + + $null = New-Item -ItemType Directory -Path $signedFilesDirectory -Force + + $itemsToCopyWithRecurse = @( + "$($fullSymbolsFolder)\*.ps1" + "$($fullSymbolsFolder)\Microsoft.PowerShell*.dll" + ) + + $itemsToCopy = @{ + "$($fullSymbolsFolder)\*.ps1" = "" + "$($fullSymbolsFolder)\Modules\Microsoft.PowerShell.Host\Microsoft.PowerShell.Host.psd1" = "Modules\Microsoft.PowerShell.Host" + "$($fullSymbolsFolder)\Modules\Microsoft.PowerShell.Management\Microsoft.PowerShell.Management.psd1" = "Modules\Microsoft.PowerShell.Management" + "$($fullSymbolsFolder)\Modules\Microsoft.PowerShell.Security\Microsoft.PowerShell.Security.psd1" = "Modules\Microsoft.PowerShell.Security" + "$($fullSymbolsFolder)\Modules\Microsoft.PowerShell.Utility\Microsoft.PowerShell.Utility.psd1" = "Modules\Microsoft.PowerShell.Utility" + "$($fullSymbolsFolder)\pwsh.dll" = "" + "$($fullSymbolsFolder)\System.Management.Automation.dll" = "" + } + + ## Windows only modules + + if('$(ArtifactPlatform)' -eq 'windows') { + $itemsToCopy += @{ + "$($fullSymbolsFolder)\pwsh.exe" = "" + "$($fullSymbolsFolder)\Microsoft.Management.Infrastructure.CimCmdlets.dll" = "" + "$($fullSymbolsFolder)\Microsoft.WSMan.*.dll" = "" + "$($fullSymbolsFolder)\Modules\CimCmdlets\CimCmdlets.psd1" = "Modules\CimCmdlets" + "$($fullSymbolsFolder)\Modules\Microsoft.PowerShell.Diagnostics\Diagnostics.format.ps1xml" = "Modules\Microsoft.PowerShell.Diagnostics" + "$($fullSymbolsFolder)\Modules\Microsoft.PowerShell.Diagnostics\Event.format.ps1xml" = "Modules\Microsoft.PowerShell.Diagnostics" + "$($fullSymbolsFolder)\Modules\Microsoft.PowerShell.Diagnostics\GetEvent.types.ps1xml" = "Modules\Microsoft.PowerShell.Diagnostics" + "$($fullSymbolsFolder)\Modules\Microsoft.PowerShell.Security\Security.types.ps1xml" = "Modules\Microsoft.PowerShell.Security" + "$($fullSymbolsFolder)\Modules\Microsoft.PowerShell.Diagnostics\Microsoft.PowerShell.Diagnostics.psd1" = "Modules\Microsoft.PowerShell.Diagnostics" + "$($fullSymbolsFolder)\Modules\Microsoft.WSMan.Management\Microsoft.WSMan.Management.psd1" = "Modules\Microsoft.WSMan.Management" + "$($fullSymbolsFolder)\Modules\Microsoft.WSMan.Management\WSMan.format.ps1xml" = "Modules\Microsoft.WSMan.Management" + "$($fullSymbolsFolder)\Modules\PSDiagnostics\PSDiagnostics.ps?1" = "Modules\PSDiagnostics" + } + } + else { + $itemsToCopy += @{ + "$($fullSymbolsFolder)\pwsh" = "" + } + } + + $itemsToExclude = @( + # This package is retrieved from https://www.github.com/powershell/MarkdownRender + "$($fullSymbolsFolder)\Microsoft.PowerShell.MarkdownRender.dll" + ) + + Write-Verbose -verbose "recusively copying $($itemsToCopyWithRecurse | out-string) to $filesToSignDirectory" + Copy-Item -Path $itemsToCopyWithRecurse -Destination $filesToSignDirectory -Recurse -verbose -exclude $itemsToExclude + + foreach($pattern in $itemsToCopy.Keys) { + $destinationFolder = Join-Path $filesToSignDirectory -ChildPath $itemsToCopy.$pattern + $null = New-Item -ItemType Directory -Path $destinationFolder -Force + Write-Verbose -verbose "copying $pattern to $destinationFolder" + Copy-Item -Path $pattern -Destination $destinationFolder -Recurse -verbose + } + displayName: 'Prepare files to be signed' + +- template: EsrpSign.yml@ComplianceRepo + parameters: + buildOutputPath: $(System.ArtifactsDirectory)\toBeSigned + signOutputPath: $(System.ArtifactsDirectory)\signed + certificateId: "$(AUTHENTICODE_CERT)" + pattern: | + **\*.dll + **\*.psd1 + **\*.psm1 + **\*.ps1xml + **\*.ps1 + **\*.exe + useMinimatch: true + shouldSign: $(SHOULD_SIGN) + displayName: Authenticode sign our binaries + +- pwsh: | + Import-Module $(PowerShellRoot)/build.psm1 -Force + Import-Module $(PowerShellRoot)/tools/packaging -Force + $signedFilesPath = '$(System.ArtifactsDirectory)\signed\' + $BuildPath = '$(BinPath)' + Write-Verbose -Verbose -Message "BuildPath: $BuildPath" + + Update-PSSignedBuildFolder -BuildPath $BuildPath -SignedFilesPath $SignedFilesPath + $dlls = Get-ChildItem $BuildPath\*.dll, $BuildPath\*.exe -Recurse + $signatures = $dlls | Get-AuthenticodeSignature + $missingSignatures = $signatures | Where-Object { $_.status -eq 'notsigned' -or $_.SignerCertificate.Issuer -notmatch '^CN=Microsoft.*'}| select-object -ExpandProperty Path + + Write-Verbose -verbose "to be signed:`r`n $($missingSignatures | Out-String)" + + $filesToSignDirectory = "$(System.ArtifactsDirectory)\thirdPartyToBeSigned" + if (Test-Path $filesToSignDirectory) { + Remove-Item -Path $filesToSignDirectory -Recurse -Force + } + + $null = New-Item -ItemType Directory -Path $filesToSignDirectory -Force -Verbose + + $signedFilesDirectory = "$(System.ArtifactsDirectory)\thirdPartySigned" + if (Test-Path $signedFilesDirectory) { + Remove-Item -Path $signedFilesDirectory -Recurse -Force + } + + $null = New-Item -ItemType Directory -Path $signedFilesDirectory -Force -Verbose + + $missingSignatures | ForEach-Object { + $pathWithoutLeaf = Split-Path $_ + $relativePath = $pathWithoutLeaf.replace($BuildPath,'') + Write-Verbose -Verbose -Message "relativePath: $relativePath" + $targetDirectory = Join-Path -Path $filesToSignDirectory -ChildPath $relativePath + Write-Verbose -Verbose -Message "targetDirectory: $targetDirectory" + if(!(Test-Path $targetDirectory)) + { + $null = New-Item -ItemType Directory -Path $targetDirectory -Force -Verbose + } + Copy-Item -Path $_ -Destination $targetDirectory + } + + displayName: Create ThirdParty Signing Folder + condition: and(succeeded(), eq(variables['SHOULD_SIGN'], 'true')) + +- template: EsrpSign.yml@ComplianceRepo + parameters: + buildOutputPath: $(System.ArtifactsDirectory)\thirdPartyToBeSigned + signOutputPath: $(System.ArtifactsDirectory)\thirdPartySigned + certificateId: "CP-231522" + pattern: | + **\*.dll + useMinimatch: true + shouldSign: $(SHOULD_SIGN) + displayName: Sign ThirdParty binaries + +- pwsh: | + Get-ChildItem '$(System.ArtifactsDirectory)\thirdPartySigned\*' + displayName: Capture ThirdParty Signed files + condition: and(succeeded(), eq(variables['SHOULD_SIGN'], 'true')) + +- pwsh: | + Import-Module '$(PowerShellRoot)/build.psm1' -Force + Import-Module '$(PowerShellRoot)/tools/packaging' -Force + $signedFilesPath = '$(System.ArtifactsDirectory)\thirdPartySigned' + $BuildPath = '$(BinPath)' + + Update-PSSignedBuildFolder -BuildPath $BuildPath -SignedFilesPath $SignedFilesPath + if ($env:BuildConfiguration -eq 'minSize') { + ## Remove XML files when making a min-size package. + Remove-Item "$BuildPath/*.xml" -Force + } + displayName: Merge ThirdParty signed files with Build + condition: and(succeeded(), eq(variables['SHOULD_SIGN'], 'true')) + +- pwsh: | + $uploadFolder = '$(BinPath)' + $containerName = '$(signedArtifactContainer)' + + Write-Verbose -Verbose "File permissions after signing" + Get-ChildItem $uploadFolder\pwsh | Select-Object -Property 'unixmode', 'size', 'name' + + $uploadTarFilePath = Join-Path '$(System.ArtifactsDirectory)' '$(signedBuildArtifactName)' + Write-Verbose -Verbose -Message "Creating tar.gz - $uploadTarFilePath" + tar -czvf $uploadTarFilePath -C $uploadFolder * + + Get-ChildItem '$(System.ArtifactsDirectory)' | Out-String | Write-Verbose -Verbose + + Write-Host "##vso[artifact.upload containerfolder=$containerName;artifactname=$containerName]$uploadTarFilePath" + displayName: Upload signed tar.gz files to artifacts + condition: eq(variables['ArtifactPlatform'], 'linux') + +- pwsh: | + $uploadFolder = '$(BinPath)' + $containerName = '$(signedArtifactContainer)' + + Get-ChildItem $uploadFolder -Recurse | Out-String | Write-Verbose -Verbose + + $uploadZipFilePath = Join-Path '$(System.ArtifactsDirectory)' 'PowerShell-$(Version)$(signedBuildArtifactName)' + Write-Verbose -Verbose -Message "Creating zip - $uploadZipFilePath" + Compress-Archive -Path $uploadFolder/* -DestinationPath $uploadZipFilePath -Verbose + + Get-ChildItem '$(System.ArtifactsDirectory)' | Out-String | Write-Verbose -Verbose + + Write-Host "##vso[artifact.upload containerfolder=$containerName;artifactname=$containerName]$uploadZipFilePath" + displayName: Upload signed zip files to artifacts + condition: eq(variables['ArtifactPlatform'], 'windows') + +- template: /tools/releaseBuild/azureDevOps/templates/step/finalize.yml diff --git a/tools/releaseBuild/azureDevOps/templates/windows-hosted-build.yml b/tools/releaseBuild/azureDevOps/templates/windows-hosted-build.yml index fd04f5ba5f7..d0952568bf9 100644 --- a/tools/releaseBuild/azureDevOps/templates/windows-hosted-build.yml +++ b/tools/releaseBuild/azureDevOps/templates/windows-hosted-build.yml @@ -14,7 +14,7 @@ jobs: condition: succeeded() dependsOn: ${{ parameters.parentJob }} pool: - name: PowerShell1ES + name: $(windowsPool) demands: - ImageOverride -equals PSMMS2019-Secure variables: diff --git a/tools/releaseBuild/azureDevOps/templates/windows-package-signing.yml b/tools/releaseBuild/azureDevOps/templates/windows-package-signing.yml index c2e3f4d1c1c..44b76127ddc 100644 --- a/tools/releaseBuild/azureDevOps/templates/windows-package-signing.yml +++ b/tools/releaseBuild/azureDevOps/templates/windows-package-signing.yml @@ -8,7 +8,7 @@ jobs: ${{ parameters.parentJobs }} condition: succeeded() pool: - name: PowerShell1ES + name: $(windowsPool) demands: - ImageOverride -equals PSMMS2019-Secure variables: diff --git a/tools/releaseBuild/azureDevOps/templates/windows-packaging.yml b/tools/releaseBuild/azureDevOps/templates/windows-packaging.yml index 0b9ff979ef0..f0b1e10bbbb 100644 --- a/tools/releaseBuild/azureDevOps/templates/windows-packaging.yml +++ b/tools/releaseBuild/azureDevOps/templates/windows-packaging.yml @@ -12,9 +12,8 @@ jobs: - job: sign_windows_${{ parameters.Architecture }}_${{ parameters.BuildConfiguration }} displayName: Package Windows - ${{ parameters.Architecture }} ${{ parameters.BuildConfiguration }} condition: succeeded() - dependsOn: ${{ parameters.parentJob }} pool: - name: PowerShell1ES + name: $(windowsPool) demands: - ImageOverride -equals PSMMS2019-Secure variables: From 9d1756efa70210e52c587f44ea5c03bfd52d1318 Mon Sep 17 00:00:00 2001 From: Ikko Eltociear Ashimine Date: Tue, 14 Mar 2023 12:56:14 +0900 Subject: [PATCH 438/779] Fix typo in typeDataXmlLoader.cs (#19319) --- .../FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs index 5a241d0fed1..faa065f57eb 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs @@ -277,7 +277,7 @@ internal bool LoadXmlFile( /// The ExtendedTypeDefinition instance to load formatting data from. /// Database instance to load the formatting data into. /// Expression factory to validate the script block. - /// Do we implicitly trust the script blocks (so they should run in full langauge mode)? + /// Do we implicitly trust the script blocks (so they should run in full language mode)? /// True when the view is for help output. /// internal bool LoadFormattingData( From ce70a779f682d861b09314ef2addfc9d71eb7b2e Mon Sep 17 00:00:00 2001 From: PowerShell Team Bot <69177312+pwshBot@users.noreply.github.com> Date: Tue, 14 Mar 2023 09:50:49 -0700 Subject: [PATCH 439/779] Update the experimental feature JSON files (#19297) --- experimental-feature-linux.json | 8 ++++---- experimental-feature-windows.json | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/experimental-feature-linux.json b/experimental-feature-linux.json index 376ada0a790..188164cd710 100644 --- a/experimental-feature-linux.json +++ b/experimental-feature-linux.json @@ -1,10 +1,10 @@ [ "PSCommandNotFoundSuggestion", + "PSCommandWithArgs", "PSCustomTableHeaderLabelDecoration", + "PSFeedbackProvider", "PSLoadAssemblyFromNativeCode", - "PSNativeCommandErrorActionPreference", - "PSSubsystemPluginModel", "PSModuleAutoLoadSkipOfflineFiles", - "PSFeedbackProvider", - "PSCommandWithArgs" + "PSNativeCommandErrorActionPreference", + "PSSubsystemPluginModel" ] diff --git a/experimental-feature-windows.json b/experimental-feature-windows.json index 376ada0a790..188164cd710 100644 --- a/experimental-feature-windows.json +++ b/experimental-feature-windows.json @@ -1,10 +1,10 @@ [ "PSCommandNotFoundSuggestion", + "PSCommandWithArgs", "PSCustomTableHeaderLabelDecoration", + "PSFeedbackProvider", "PSLoadAssemblyFromNativeCode", - "PSNativeCommandErrorActionPreference", - "PSSubsystemPluginModel", "PSModuleAutoLoadSkipOfflineFiles", - "PSFeedbackProvider", - "PSCommandWithArgs" + "PSNativeCommandErrorActionPreference", + "PSSubsystemPluginModel" ] From 39d48f9c6288e72b6df6b73e2b7699d6f2353b7c Mon Sep 17 00:00:00 2001 From: MartinGC94 <42123497+MartinGC94@users.noreply.github.com> Date: Tue, 14 Mar 2023 19:24:43 +0100 Subject: [PATCH 440/779] Infer external application output as strings (#19193) --- .../engine/parser/TypeInferenceVisitor.cs | 26 ++++++++++++++++++- .../engine/Api/TypeInference.Tests.ps1 | 5 ++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs index 75ce67e22b1..5f2288e0106 100644 --- a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs +++ b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs @@ -1043,8 +1043,32 @@ private void InferTypesFrom(CommandAst commandAst, List inferredType PseudoBindingInfo pseudoBinding = new PseudoParameterBinder() .DoPseudoParameterBinding(commandAst, null, null, PseudoParameterBinder.BindingType.ParameterCompletion); - if (pseudoBinding?.CommandInfo == null) + if (pseudoBinding?.CommandInfo is null) { + var commandName = commandAst.GetCommandName(); + if (string.IsNullOrEmpty(commandName)) + { + return; + } + + try + { + var foundCommand = CommandDiscovery.LookupCommandInfo( + commandName, + CommandTypes.Application, + SearchResolutionOptions.ResolveLiteralThenPathPatterns, + CommandOrigin.Internal, + _context.ExecutionContext); + + // There's no way to know whether or not an application outputs anything + // but when they do, PowerShell will treat it as string data. + inferredTypes.Add(new PSTypeName(typeof(string))); + } + catch + { + // The command wasn't found so we can't infer anything. + } + return; } diff --git a/test/powershell/engine/Api/TypeInference.Tests.ps1 b/test/powershell/engine/Api/TypeInference.Tests.ps1 index 612912029a8..36293030da7 100644 --- a/test/powershell/engine/Api/TypeInference.Tests.ps1 +++ b/test/powershell/engine/Api/TypeInference.Tests.ps1 @@ -1401,6 +1401,11 @@ Describe "Type inference Tests" -tags "CI" { $res.Count | Should -Be 1 $res.Name | Should -Be 'System.Management.Automation.Internal.Host.InternalHost' } + + It 'Infers type of external applications' { + $res = [AstTypeInference]::InferTypeOf( { pwsh }.Ast) + $res.Name | Should -Be 'System.String' + } } Describe "AstTypeInference tests" -Tags CI { From df918e6a1492061edaae955dba4cc2291012554e Mon Sep 17 00:00:00 2001 From: Steven Bucher Date: Tue, 14 Mar 2023 12:10:51 -0700 Subject: [PATCH 441/779] Fixing MSI checkbox (#19325) --- assets/wix/Product.wxs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/assets/wix/Product.wxs b/assets/wix/Product.wxs index 674e67fc860..cbb46a48ddd 100644 --- a/assets/wix/Product.wxs +++ b/assets/wix/Product.wxs @@ -327,7 +327,7 @@ - + The application is distributed under the MIT license.]]> From 03cecc6cf5e0bf024de65d59ebb994ae374fb5c3 Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Tue, 14 Mar 2023 22:00:51 +0000 Subject: [PATCH 442/779] Merged PR 24784: Change log for v7.4.0-preview.2 Change log for v7.4.0-preview.2 --- .spelling | 47 ++++++++++ CHANGELOG/preview.md | 203 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 250 insertions(+) diff --git a/.spelling b/.spelling index d4f5d47ef4b..1296f973ad1 100644 --- a/.spelling +++ b/.spelling @@ -1290,6 +1290,47 @@ Microsoft.CSharp v7.2.10 7.2.x v7.3.3 +http +webcmdlet +argumentexception.throwifnullorempty +bitconverter.tostring +convert.tohexstring +requires.notnullorempty +argumentoutofrangeexception.throwifnegativeorzero +callerargumentexpression +requires.notnull +argumentnullexception +throwifnull +process.cs +setrequestcontent +streamhelper.cs +invokerestmethodcommand.common.cs +gethttpmethod +httpmethod +removenulls +notnull +argumentnullexception.throwifnull +disable_telemetry +langversion +microsoft.extensions.objectpool +microsoft.codeanalysis.analyzers +benchmarkdotnet +winforms +benchmarkdotnet.extensions +eg +10ms +100ns +1s +1.0ns +1.1ns +0.5ns +1ns +0.3ns. +ns +perflabtests.blockcopyperf.callblockcopy +numelements +system.tests.perf_string.trim_chararr +system.tests.perf_array.arraycopy3d - CHANGELOG.md aavdberg asrosent @@ -1676,3 +1717,9 @@ Security.types.ps1xml MicrosoftPowerBIMgmt - tools/clearlyDefined/readme.md ClearlyDefined + - CHANGELOG/preview.md +stevenebutler +spaette +syntax-tm +pwshBot +techguy16 diff --git a/CHANGELOG/preview.md b/CHANGELOG/preview.md index 8cd84ae8158..2e4abf05980 100644 --- a/CHANGELOG/preview.md +++ b/CHANGELOG/preview.md @@ -1,5 +1,208 @@ # Current preview release +## [7.4.0-preview.2] - 2023-03-14 + +### Breaking Changes + +- Update some PowerShell APIs to throw `ArgumentException` instead of `ArgumentNullException` when the argument is an empty string (#19215) (Thanks @xtqqczze!) +- Add the parameter `-ProgressAction` to the common parameters (#18887) + +### Engine Updates and Fixes + +- Fix `PlainText` output to correctly remove the `Reset` VT sequence without number (#19283) +- Fix `ConciseView` to handle custom `ParserError` error records (#19239) +- Fix `VtSubstring` helper method to correctly check characters copied (#19240) +- Update the `FeedbackProvider` interface to return structured data (#19133) +- Make the exception error in PowerShell able to associate with the right history entry (#19095) +- Fix for JEA session leaking functions (#19024) +- Add WDAC events and system lockdown notification (#18893) +- Fix support for nanoserver due to lack of AMSI (#18882) + +### Performance + +- Use interpolated strings (#19002)(#19003)(#18977)(#18980)(#18996)(#18979)(#18997)(#18978)(#18983)(#18992)(#18993)(#18985)(#18988) (Thanks @CarloToso!) + +### General Cmdlet Updates and Fixes + +- Fix completion for `PSCustomObject` variable properties (#18682) (Thanks @MartinGC94!) +- Improve type inference for `Get-Random` (#18972) (Thanks @MartinGC94!) +- Make `-Encoding` parameter able to take `ANSI` encoding in PowerShell (#19298) (Thanks @CarloToso!) +- Telemetry improvements for tracking experimental feature opt out (#18762) +- Support HTTP persistent connections in Web Cmdlets (#19249) (Thanks @stevenebutler!) +- Fix using xml `-Body` in webcmdlets without an encoding (#19281) (Thanks @CarloToso!) +- Add the `Statement` property to `$MyInvocation` (#19027) (Thanks @IISResetMe!) +- Fix `Start-Process` `-Wait` with `-Credential` (#19096) (Thanks @jborean93!) +- Adjust `PUT` method behavior to `POST` one for default content type in WebCmdlets (#19152) (Thanks @CarloToso!) +- Improve verbose message in web cmdlets when content length is unknown (#19252) (Thanks @CarloToso!) +- Preserve `WebSession.MaximumRedirection` from changes (#19190) (Thanks @CarloToso!) +- Take into account `ContentType` from Headers in WebCmdlets (#19227) (Thanks @CarloToso!) +- Use C# 11 UTF-8 string literals (#19243) (Thanks @turbedi!) +- Add property assignment completion for enums (#19178) (Thanks @MartinGC94!) +- Fix class member completion for classes with base types (#19179) (Thanks @MartinGC94!) +- Add `-Path` and `-LiteralPath` parameters to `Test-Json` cmdlet (#19042) (Thanks @ArmaanMcleod!) +- Allow to preserve the original HTTP method by adding `-PreserveHttpMethodOnRedirect` to Web cmdlets (#18894) (Thanks @CarloToso!) +- Webcmdlets display an error on https to http redirect (#18595) (Thanks @CarloToso!) +- Build the relative URI for links from the response in `Invoke-WebRequest` (#19092) (Thanks @CarloToso!) +- Fix redirection for `-CustomMethod` `POST` in WebCmdlets (#19111) (Thanks @CarloToso!) +- Dispose previous response in Webcmdlets (#19117) (Thanks @CarloToso!) +- Improve `Invoke-WebRequest` xml and json errors format (#18837) (Thanks @CarloToso!) +- Fix error formatting to remove the unneeded leading newline for concise view (#19080) +- Add `-NoHeader` parameter to `ConvertTo-Csv` and `Export-Csv` cmdlets (#19108) (Thanks @ArmaanMcleod!) +- Fix `Start-Process -Credential -Wait` to work on Windows (#19082) +- Add `ValidateNotNullOrEmpty` to `OutFile` and `InFile` parameters of WebCmdlets (#19044) (Thanks @CarloToso!) +- Correct spelling of "custom" in event (#19059) (Thanks @spaette!) +- Ignore expected error for file systems not supporting alternate streams (#19065) +- Adding missing guard for telemetry opt out to avoid `NullReferenceException` when importing modules (#18949) (Thanks @powercode!) +- Fix progress calculation divide by zero in Copy-Item (#19038) +- Add progress to `Copy-Item` (#18735) +- WebCmdlets parse XML declaration to get encoding value, if present. (#18748) (Thanks @CarloToso!) +- `HttpKnownHeaderNames` update headers list (#18947) (Thanks @CarloToso!) +- Fix bug with managing redirection and `KeepAuthorization` in Web cmdlets (#18902) (Thanks @CarloToso!) +- Fix `Get-Error` to work with strict mode (#18895) +- Add `AllowInsecureRedirect` switch to Web cmdlets (#18546) (Thanks @CarloToso!) +- `Invoke-RestMethod` `-FollowRelLink` fix links containing commas (#18829) (Thanks @CarloToso!) +- Prioritize the default parameter set when completing positional arguments (#18755) (Thanks @MartinGC94!) +- Add `-CommandWithArgs` parameter to pwsh (#18726) +- Enable creating composite subsystem implementation in modules (#18888) +- Fix `Format-Table -RepeatHeader` for property derived tables (#18870) +- Add `StatusCode` to `HttpResponseException` (#18842) (Thanks @CarloToso!) +- Fix type inference for all scope variables (#18758) (Thanks @MartinGC94!) +- Add completion for Using keywords (#16514) (Thanks @MartinGC94!) + +### Code Cleanup + +
    + + + +

    We thank the following contributors!

    +

    @CarloToso, @iSazonov, @xtqqczze, @turbedi, @syntax-tm, @eltociear, @ArmaanMcleod

    + +
    + +
      +
    • Small cleanup in the WebCmdlet code (#19299) (Thanks @CarloToso!)
    • +
    • Remove unused GUID detection code from console host (#18871) (Thanks @iSazonov!)
    • +
    • Fix CodeFactor issues in the code base - part 4 (#19270) (Thanks @CarloToso!)
    • +
    • Fix codefactor if part 3 (#19269) (Thanks @CarloToso!)
    • +
    • Fix codefactor if part 2 (#19267) (Thanks @CarloToso!)
    • +
    • Fix codefactor if part 1 (#19266) (Thanks @CarloToso!)
    • +
    • Remove comment and simplify condition in WebCmdlets (#19251) (Thanks @CarloToso!)
    • +
    • Small style changes (#19241) (Thanks @CarloToso!)
    • +
    • Use ArgumentException.ThrowIfNullOrEmpty as appropriate [part 1] (#19215) (Thanks @xtqqczze!)
    • +
    • Use using variable to reduce the nested level (#19229) (Thanks @CarloToso!)
    • +
    • Use ArgumentException.ThrowIfNullOrEmpty() in more places (#19213) (Thanks @CarloToso!)
    • +
    • Replace BitConverter.ToString with Convert.ToHexString where appropriate (#19216) (Thanks @turbedi!)
    • +
    • Replace Requires.NotNullOrEmpty(string) with ArgumentException.ThrowIfNullOrEmpty (#19197) (Thanks @xtqqczze!)
    • +
    • Use ArgumentOutOfRangeException.ThrowIfNegativeOrZero when applicable (#19201) (Thanks @xtqqczze!)
    • +
    • Use CallerArgumentExpression on Requires.NotNull (#19200) (Thanks @xtqqczze!)
    • +
    • Revert a few change to not use 'ArgumentNullException.ThrowIfNull' (#19151)
    • +
    • Corrected some minor spelling mistakes (#19176) (Thanks @syntax-tm!)
    • +
    • Fix a typo in InitialSessionState.cs (#19177) (Thanks @eltociear!)
    • +
    • Fix a typo in pwsh help content (#19153)
    • +
    • Revert comment changes in WebRequestPSCmdlet.Common.cs (#19136) (Thanks @CarloToso!)
    • +
    • Small cleanup webcmdlets (#19128) (Thanks @CarloToso!)
    • +
    • Merge partials in WebRequestPSCmdlet.Common.cs (#19126) (Thanks @CarloToso!)
    • +
    • Cleanup WebCmdlets comments (#19124) (Thanks @CarloToso!)
    • +
    • Added minor readability and refactoring fixes to Process.cs (#19123) (Thanks @ArmaanMcleod!)
    • +
    • Small changes in Webcmdlets (#19109) (Thanks @CarloToso!)
    • +
    • Rework SetRequestContent in WebCmdlets (#18964) (Thanks @CarloToso!)
    • +
    • Small cleanup WebCmdlets (#19030) (Thanks @CarloToso!)
    • +
    • Update additional interpolated string changes (#19029)
    • +
    • Revert some of the interpolated string changes (#19018)
    • +
    • Cleanup StreamHelper.cs, WebRequestPSCmdlet.Common.cs and InvokeRestMethodCommand.Common.cs (#18950) (Thanks @CarloToso!)
    • +
    • Small cleanup common code of webcmdlets (#18946) (Thanks @CarloToso!)
    • +
    • Simplification of GetHttpMethod and HttpMethod in WebCmdlets (#18846) (Thanks @CarloToso!)
    • +
    • Fix typo in ModuleCmdletBase.cs (#18933) (Thanks @eltociear!)
    • +
    • Fix regression in RemoveNulls (#18881) (Thanks @iSazonov!)
    • +
    • Replace all NotNull with ArgumentNullException.ThrowIfNull (#18820) (Thanks @CarloToso!)
    • +
    • Cleanup InvokeRestMethodCommand.Common.cs (#18861) (Thanks @CarloToso!)
    • +
    + +
    + +### Tools + +- Add a Mariner install script (#19294) +- Add tool to trigger license information gathering for NuGet modules (#18827) + +### Tests + +- Update and enable the test for the type of `$input` (#18968) (Thanks @MartinGC94!) +- Increase the timeout for creating the `WebListener` (#19268) +- Increase the timeout when waiting for the event log (#19264) +- Add Windows ARM64 CI (#19040) +- Change test so output does not include newline (#19026) +- Allow system lock down test debug hook to work with new WLDP API (#18962) +- Add tests for `Allowinsecureredirect` parameter in Web cmdlets (#18939) (Thanks @CarloToso!) +- Enable `get-help` pattern tests on Unix (#18855) (Thanks @xtqqczze!) +- Create test to check if WebCmdlets decompress brotli-encoded data (#18905) (Thanks @CarloToso!) + +### Build and Packaging Improvements + +
    + + + +

    We thank the following contributors!

    +

    @pwshBot, @bergmeister, @xtqqczze

    + +
    + +
      +
    • Restructure the package build to simplify signing and packaging stages (#19321)
    • +
    • Bump Microsoft.CodeAnalysis.CSharp from 4.4.0 to 4.6.0-2.23152.6 (#19306)(#19233)
    • +
    • Test fixes for stabilizing tests (#19068)
    • +
    • Bump Newtonsoft.Json from 13.0.2 to 13.0.3 (#19290)(#19289)
    • +
    • Fix mariner sudo detection (#19304)
    • +
    • Add stage for symbols job in Release build (#18937)
    • +
    • Bump .NET to Preview 2 version (#19305)
    • +
    • Move workflows that create PRs to private repo (#19276)
    • +
    • Use reference assemblies generated by dotnet (#19302)
    • +
    • Update the cgmanifest (#18814)(#19165)(#19296)
    • +
    • Always regenerate files WXS fragment (#19196)
    • +
    • MSI installer: Add checkbox and MSI property DISABLE_TELEMETRY to optionally disable telemetry. (#10725) (Thanks @bergmeister!)
    • +
    • Add -Force to Move-Item to fix the GitHub workflow (#19262)
    • +
    • Update and remove outdated docs to fix the URL link checks (#19261)
    • +
    • Bump Markdig.Signed from 0.30.4 to 0.31.0 (#19232)
    • +
    • Add pattern to replace for reference API generation (#19214)
    • +
    • Split test artifact build into windows and non-windows (#19199)
    • +
    • Set LangVersion compiler option to 11.0 (#18877) (Thanks @xtqqczze!)
    • +
    • Update to .NET 8 preview 1 build (#19194)
    • +
    • Simplify Windows Packaging CI Trigger YAML (#19160)
    • +
    • Bump Microsoft.NET.Test.Sdk from 17.4.0 to 17.5.0 (#18823)(#19191)
    • +
    • Add URL for all distributions (#19159)
    • +
    • Bump Microsoft.Extensions.ObjectPool from 7.0.1 to 7.0.3 (#18925)(#19155)
    • +
    • Add verification of R2R at packaging (#19129)
    • +
    • Allow cross compiling windows (#19119)
    • +
    • Update CodeQL build agent (#19113)
    • +
    • Bump XunitXml.TestLogger from 3.0.70 to 3.0.78 (#19066)
    • +
    • Bump Microsoft.CodeAnalysis.Analyzers from 3.3.3 to 3.3.4 (#18975)
    • +
    • Bump BenchmarkDotNet to 0.13.3 (#18878) (Thanks @xtqqczze!)
    • +
    • Bump Microsoft.PowerShell.Native from 7.4.0-preview.1 to 7.4.0-preview.2 (#18910)
    • +
    • Add checks for Windows 8.1 and Server 2012 in the MSI installer (#18904)
    • +
    • Update build to include WinForms / WPF in all Windows builds (#18859)
    • +
    + +
    + +### Documentation and Help Content + +- Update to the latest NOTICES file (#19169)(#19309)(#19086)(#19077) +- Update supported distros in Readme (#18667) (Thanks @techguy16!) +- Remove the 'Code Coverage Status' badge (#19265) +- Pull in change logs for `v7.2.10` and `v7.3.3` releases (#19219) +- Update tools `metadata` and `README` (#18831)(#19204)(#19014) +- Update a broken link in the `README.md` (#19187) +- Fix typos in comments (#19064) (Thanks @spaette!) +- Add `7.2` and `7.3` change logs (#19025) +- typos (#19058) (Thanks @spaette!) +- Fix typo in `dotnet-tools/README.md` (#19021) (Thanks @spaette!) +- Fix up all comments to be in the proper order with proper spacing (#18619) +- Change log for `v7.4.0-preview.1` release (#18835) + +[7.4.0-preview.2]: https://github.com/PowerShell/PowerShell/compare/v7.4.0-preview.1...v7.4.0-preview.2 + ## [7.4.0-preview.1] - 2022-12-20 ### Engine Updates and Fixes From d616478483f5c41cefe002c1902cb617b59c75c6 Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Tue, 14 Mar 2023 16:14:44 -0700 Subject: [PATCH 443/779] Update `README.md` and `metadata.json` for `v7.4.0-preview.2` (#19326) --- README.md | 28 ++++++++++++++-------------- tools/metadata.json | 4 ++-- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index bea2a885769..2bd93a5fc9a 100644 --- a/README.md +++ b/README.md @@ -93,20 +93,20 @@ You can also download the PowerShell binary archives for Windows, macOS and Linu [rl-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.3/powershell-7.3.3-linux-arm64.tar.gz [rl-snap]: https://snapcraft.io/powershell -[pv-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.1/PowerShell-7.4.0-preview.1-win-x64.msi -[pv-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.1/PowerShell-7.4.0-preview.1-win-x86.msi -[pv-deb]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.1/powershell-preview_7.4.0-preview.1-1.deb_amd64.deb -[pv-rpm]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.1/powershell-preview-7.4.0_preview.1-1.rh.x86_64.rpm -[pv-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.1/powershell-7.4.0-preview.1-osx-x64.pkg -[pv-macos-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.1/powershell-7.4.0-preview.1-osx-arm64.pkg -[pv-winarm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.1/PowerShell-7.4.0-preview.1-win-arm64.zip -[pv-winx86-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.1/PowerShell-7.4.0-preview.1-win-x86.zip -[pv-winx64-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.1/PowerShell-7.4.0-preview.1-win-x64.zip -[pv-macos-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.1/powershell-7.4.0-preview.1-osx-x64.tar.gz -[pv-macos-tar-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.1/powershell-7.4.0-preview.1-osx-arm64.tar.gz -[pv-linux-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.1/powershell-7.4.0-preview.1-linux-x64.tar.gz -[pv-arm32]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.1/powershell-7.4.0-preview.1-linux-arm32.tar.gz -[pv-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.1/powershell-7.4.0-preview.1-linux-arm64.tar.gz +[pv-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.2/PowerShell-7.4.0-preview.2-win-x64.msi +[pv-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.2/PowerShell-7.4.0-preview.2-win-x86.msi +[pv-deb]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.2/powershell-preview_7.4.0-preview.2-1.deb_amd64.deb +[pv-rpm]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.2/powershell-preview-7.4.0_preview.2-1.rh.x86_64.rpm +[pv-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.2/powershell-7.4.0-preview.2-osx-x64.pkg +[pv-macos-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.2/powershell-7.4.0-preview.2-osx-arm64.pkg +[pv-winarm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.2/PowerShell-7.4.0-preview.2-win-arm64.zip +[pv-winx86-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.2/PowerShell-7.4.0-preview.2-win-x86.zip +[pv-winx64-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.2/PowerShell-7.4.0-preview.2-win-x64.zip +[pv-macos-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.2/powershell-7.4.0-preview.2-osx-x64.tar.gz +[pv-macos-tar-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.2/powershell-7.4.0-preview.2-osx-arm64.tar.gz +[pv-linux-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.2/powershell-7.4.0-preview.2-linux-x64.tar.gz +[pv-arm32]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.2/powershell-7.4.0-preview.2-linux-arm32.tar.gz +[pv-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.2/powershell-7.4.0-preview.2-linux-arm64.tar.gz [pv-snap]: https://snapcraft.io/powershell-preview [in-windows]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-windows diff --git a/tools/metadata.json b/tools/metadata.json index a49c16c0ee9..3c885cbb492 100644 --- a/tools/metadata.json +++ b/tools/metadata.json @@ -1,10 +1,10 @@ { "StableReleaseTag": "v7.3.3", - "PreviewReleaseTag": "v7.4.0-preview.1", + "PreviewReleaseTag": "v7.4.0-preview.2", "ServicingReleaseTag": "v7.0.13", "ReleaseTag": "v7.3.3", "LTSReleaseTag" : ["v7.2.10"], - "NextReleaseTag": "v7.4.0-preview.2", + "NextReleaseTag": "v7.4.0-preview.3", "LTSRelease": { "Latest": false, "Package": false }, "StableRelease": { "Latest": false, "Package": false } } From 8b964ded3626bf8dc965ebce81d3621ff457c8b1 Mon Sep 17 00:00:00 2001 From: MartinGC94 <42123497+MartinGC94@users.noreply.github.com> Date: Wed, 15 Mar 2023 04:12:09 +0100 Subject: [PATCH 444/779] Speed up Resolve-Path relative path resolution (#19171) --- .../commands/management/ResolvePathCommand.cs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/ResolvePathCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ResolvePathCommand.cs index 6bae1a6c878..905a82c8e86 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ResolvePathCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/ResolvePathCommand.cs @@ -103,6 +103,8 @@ protected override void ProcessRecord() if (_relative) { + ReadOnlySpan baseCache = null; + ReadOnlySpan adjustedBaseCache = null; foreach (PathInfo currentPath in result) { // When result path and base path is on different PSDrive @@ -116,8 +118,18 @@ protected override void ProcessRecord() continue; } + int leafIndex = currentPath.Path.LastIndexOf(currentPath.Provider.ItemSeparator); + var basePath = currentPath.Path.AsSpan(0, leafIndex); + if (basePath == baseCache) + { + WriteObject(string.Concat(adjustedBaseCache, currentPath.Path.AsSpan(leafIndex + 1)), enumerateCollection: false); + continue; + } + + baseCache = basePath; string adjustedPath = SessionState.Path.NormalizeRelativePath(currentPath.Path, SessionState.Path.CurrentLocation.ProviderPath); + // Do not insert './' if result path is not relative if (!adjustedPath.StartsWith( currentPath.Drive?.Root ?? currentPath.Path, StringComparison.OrdinalIgnoreCase) && @@ -126,6 +138,9 @@ protected override void ProcessRecord() adjustedPath = SessionState.Path.Combine(".", adjustedPath); } + leafIndex = adjustedPath.LastIndexOf(currentPath.Provider.ItemSeparator); + adjustedBaseCache = adjustedPath.AsSpan(0, leafIndex + 1); + WriteObject(adjustedPath, enumerateCollection: false); } } From 673ffec65498563f5c948e83a3e564f1bdd25c55 Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Wed, 15 Mar 2023 11:33:28 -0700 Subject: [PATCH 445/779] Address CR feedback --- .spelling | 1 - CHANGELOG/preview.md | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/.spelling b/.spelling index 1296f973ad1..427dc41150a 100644 --- a/.spelling +++ b/.spelling @@ -1721,5 +1721,4 @@ ClearlyDefined stevenebutler spaette syntax-tm -pwshBot techguy16 diff --git a/CHANGELOG/preview.md b/CHANGELOG/preview.md index 2e4abf05980..9984b9b5423 100644 --- a/CHANGELOG/preview.md +++ b/CHANGELOG/preview.md @@ -145,7 +145,7 @@

    We thank the following contributors!

    -

    @pwshBot, @bergmeister, @xtqqczze

    +

    @bergmeister, @xtqqczze

    From 89237dfa31cd6f43d2ab7d9797ce8ab12a4485b8 Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Wed, 15 Mar 2023 11:41:26 -0700 Subject: [PATCH 446/779] Remove unnecessary spelling changes --- .spelling | 15 --------------- 1 file changed, 15 deletions(-) diff --git a/.spelling b/.spelling index 427dc41150a..f211f338528 100644 --- a/.spelling +++ b/.spelling @@ -1316,21 +1316,6 @@ microsoft.extensions.objectpool microsoft.codeanalysis.analyzers benchmarkdotnet winforms -benchmarkdotnet.extensions -eg -10ms -100ns -1s -1.0ns -1.1ns -0.5ns -1ns -0.3ns. -ns -perflabtests.blockcopyperf.callblockcopy -numelements -system.tests.perf_string.trim_chararr -system.tests.perf_array.arraycopy3d - CHANGELOG.md aavdberg asrosent From 4767c8c6d3d4d409f0835fce390d8713a816f8fb Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Wed, 15 Mar 2023 17:37:06 -0700 Subject: [PATCH 447/779] Fix issues in release build and release pipeline (#19338) --- tools/releaseBuild/azureDevOps/releaseBuild.yml | 8 ++++++++ tools/releaseBuild/azureDevOps/releasePipeline.yml | 4 ++-- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/tools/releaseBuild/azureDevOps/releaseBuild.yml b/tools/releaseBuild/azureDevOps/releaseBuild.yml index b670d55de74..dfde466a80b 100644 --- a/tools/releaseBuild/azureDevOps/releaseBuild.yml +++ b/tools/releaseBuild/azureDevOps/releaseBuild.yml @@ -322,6 +322,14 @@ stages: jobs: - template: templates/windows-package-signing.yml + - template: templates/mac-package-signing.yml + parameters: + buildArchitecture: x64 + + - template: templates/mac-package-signing.yml + parameters: + buildArchitecture: arm64 + # This is done late so that we dont use resources before the big signing and packaging tasks. - stage: compliance dependsOn: ['package_signing'] diff --git a/tools/releaseBuild/azureDevOps/releasePipeline.yml b/tools/releaseBuild/azureDevOps/releasePipeline.yml index bd52a99b844..7e474c3acb6 100644 --- a/tools/releaseBuild/azureDevOps/releasePipeline.yml +++ b/tools/releaseBuild/azureDevOps/releasePipeline.yml @@ -175,6 +175,7 @@ stages: jobs: - job: KickOffRA displayName: Kickoff Release Automation + timeoutInMinutes: 240 pool: name: PowerShell1ES @@ -257,7 +258,6 @@ stages: - StaticPkgValidation - StartDocker - ManualValidation - - ReleaseAutomation - ValidateFxdPackage - ValidateGlobalTool @@ -557,7 +557,7 @@ stages: $isPreview = $semanticVersion.PreReleaseLabel -ne $null if (-not $isPreview) { - $buildInvocationInfo = Start-AzDOBuild -BuildDefinitionId 1238 -Tag $metadata.ReleaseVersion, 'InProgress' -PassThru + $buildInvocationInfo = Start-AzDOBuild -BuildDefinitionId 1238 -Branch '$(Build.SourceBranch)' -Tag $metadata.ReleaseVersion, 'InProgress' -PassThru Write-Verbose -Verbose "Kicked off vPack build: $($buildInvocationInfo.WebUrl)" $status = $buildInvocationInfo | Wait-AzDOBuildStatus -Status Completed -timeoutMinutes 60 if ($status.result -ne 'Succeeded') { From e5690cb1760ebbcb44d0a6ffef32b28316114074 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Thu, 16 Mar 2023 13:33:29 +0100 Subject: [PATCH 448/779] Add nullable annotations in WebRequestSession.cs (#19291) --- .../utility/WebCmdlet/WebRequestSession.cs | 24 ++++++++++++------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestSession.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestSession.cs index 4e58503659e..d4a9a5cc48b 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestSession.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestSession.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +#nullable enable + using System; using System.Collections.Generic; using System.Net; @@ -16,12 +18,14 @@ namespace Microsoft.PowerShell.Commands ///
    public class WebRequestSession : IDisposable { - private HttpClient _client; + #region Fields + + private HttpClient? _client; private CookieContainer _cookies; private bool _useDefaultCredentials; - private ICredentials _credentials; - private X509CertificateCollection _certificates; - private IWebProxy _proxy; + private ICredentials? _credentials; + private X509CertificateCollection? _certificates; + private IWebProxy? _proxy; private int _maximumRedirection; private WebSslProtocol _sslProtocol; private bool _allowAutoRedirect; @@ -35,6 +39,8 @@ public class WebRequestSession : IDisposable ///
    private bool _disposedClient; + #endregion Fields + /// /// Gets or sets the Header property. /// @@ -61,15 +67,15 @@ public class WebRequestSession : IDisposable /// /// Gets or sets the Credentials property. /// - public ICredentials Credentials { get => _credentials; set => SetClassVar(ref _credentials, value); } + public ICredentials? Credentials { get => _credentials; set => SetClassVar(ref _credentials, value); } /// /// Gets or sets the Certificates property. /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] - public X509CertificateCollection Certificates { get => _certificates; set => SetClassVar(ref _certificates, value); } + public X509CertificateCollection? Certificates { get => _certificates; set => SetClassVar(ref _certificates, value); } - #endregion + #endregion Credentials /// /// Gets or sets the UserAgent property. @@ -79,7 +85,7 @@ public class WebRequestSession : IDisposable /// /// Gets or sets the Proxy property. /// - public IWebProxy Proxy + public IWebProxy? Proxy { get => _proxy; set @@ -238,7 +244,7 @@ private HttpClient CreateHttpClient() }; } - private void SetClassVar(ref T oldValue, T newValue) where T : class + private void SetClassVar(ref T oldValue, T newValue) where T : class? { if (oldValue != newValue) { From 69e9b439fd38177ff7f3af1ef62f5617454bcf23 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Thu, 16 Mar 2023 18:02:42 +0100 Subject: [PATCH 449/779] Fix codefactor if part 5 (#19286) --- .../utility/ImplicitRemotingCommands.cs | 35 +++++++++++++++---- .../host/msh/ConsoleHost.cs | 31 ++++++++++++---- .../engine/CmdletParameterBinderController.cs | 31 ++++++++++++---- .../engine/ComInterop/VariantArray.cs | 23 +++++++++--- .../engine/Modules/ModuleIntrinsics.cs | 5 ++- .../engine/Modules/PSModuleInfo.cs | 10 ++++-- .../DynamicInstructions.Generated.cs | 6 +++- .../engine/interpreter/LightCompiler.cs | 5 ++- .../engine/interpreter/Utilities.cs | 5 ++- .../engine/remoting/client/Job.cs | 10 ++++-- .../engine/remoting/client/JobManager.cs | 35 +++++++++++++++---- .../engine/remoting/client/ThrottlingJob.cs | 17 +++++++-- .../engine/remoting/commands/ReceiveJob.cs | 11 ++++-- .../remoting/common/RunspaceConnectionInfo.cs | 5 ++- .../remoting/fanin/WSManTransportManager.cs | 15 ++++++-- .../remoting/server/ServerRemoteHost.cs | 15 ++++++-- .../server/ServerRunspacePoolDriver.cs | 15 ++++++-- .../engine/runtime/MutableTuple.cs | 11 ++++-- .../namespaces/FileSystemProvider.cs | 15 ++++++-- .../security/wldpNativeMethods.cs | 27 ++++++++++---- .../assets/ExpTest/ExpTest.cs | 12 +++++-- 21 files changed, 273 insertions(+), 66 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs index 2e2e5acbfe3..003b1bf1e3d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs @@ -2259,19 +2259,40 @@ private string GenerateNewPSSessionOption() WSManConnectionInfo wsmanConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as WSManConnectionInfo; if (wsmanConnectionInfo != null) { - if (!wsmanConnectionInfo.UseCompression) { result.Append("-NoCompression "); } + if (!wsmanConnectionInfo.UseCompression) + { + result.Append("-NoCompression "); + } - if (wsmanConnectionInfo.NoEncryption) { result.Append("-NoEncryption "); } + if (wsmanConnectionInfo.NoEncryption) + { + result.Append("-NoEncryption "); + } - if (wsmanConnectionInfo.NoMachineProfile) { result.Append("-NoMachineProfile "); } + if (wsmanConnectionInfo.NoMachineProfile) + { + result.Append("-NoMachineProfile "); + } - if (wsmanConnectionInfo.UseUTF16) { result.Append("-UseUTF16 "); } + if (wsmanConnectionInfo.UseUTF16) + { + result.Append("-UseUTF16 "); + } - if (wsmanConnectionInfo.SkipCACheck) { result.Append("-SkipCACheck "); } + if (wsmanConnectionInfo.SkipCACheck) + { + result.Append("-SkipCACheck "); + } - if (wsmanConnectionInfo.SkipCNCheck) { result.Append("-SkipCNCheck "); } + if (wsmanConnectionInfo.SkipCNCheck) + { + result.Append("-SkipCNCheck "); + } - if (wsmanConnectionInfo.SkipRevocationCheck) { result.Append("-SkipRevocationCheck "); } + if (wsmanConnectionInfo.SkipRevocationCheck) + { + result.Append("-SkipRevocationCheck "); + } if (wsmanConnectionInfo.MaximumReceivedDataSizePerCommand.HasValue) { diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs index 577abc5c087..409869cd79e 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs @@ -611,7 +611,10 @@ public override PSHostUserInterface UI /// public void PushRunspace(Runspace newRunspace) { - if (_runspaceRef == null) { return; } + if (_runspaceRef == null) + { + return; + } RemoteRunspace remoteRunspace = newRunspace as RemoteRunspace; Dbg.Assert(remoteRunspace != null, "Expected remoteRunspace != null"); @@ -744,7 +747,10 @@ public Runspace Runspace { get { - if (this.RunspaceRef == null) { return null; } + if (this.RunspaceRef == null) + { + return null; + } return this.RunspaceRef.Runspace; } @@ -759,7 +765,10 @@ internal LocalRunspace LocalRunspace return RunspaceRef.OldRunspace as LocalRunspace; } - if (RunspaceRef == null) { return null; } + if (RunspaceRef == null) + { + return null; + } return RunspaceRef.Runspace as LocalRunspace; } @@ -964,7 +973,11 @@ public override PSObject PrivateData { get { - if (ui == null) return null; + if (ui == null) + { + return null; + } + return _consoleColorProxy ??= PSObject.AsPSObject(new ConsoleColorProxy(ui)); } } @@ -1514,7 +1527,10 @@ private uint DoRunspaceLoop( RunspaceCreationEventArgs args = new RunspaceCreationEventArgs(initialCommand, skipProfiles, staMode, configurationName, configurationFilePath, initialCommandArgs); CreateRunspace(args); - if (ExitCode == ExitCodeInitFailure) { break; } + if (ExitCode == ExitCodeInitFailure) + { + break; + } if (!_noExit) { @@ -2228,7 +2244,10 @@ private void OnExecutionSuspended(object sender, DebuggerStopEventArgs e) { // Check local runspace internalHost to see if debugging is enabled. LocalRunspace localrunspace = LocalRunspace; - if ((localrunspace != null) && !localrunspace.ExecutionContext.EngineHostInterface.DebuggerEnabled) { return; } + if ((localrunspace != null) && !localrunspace.ExecutionContext.EngineHostInterface.DebuggerEnabled) + { + return; + } _debuggerStopEventArgs = e; InputLoop baseLoop = null; diff --git a/src/System.Management.Automation/engine/CmdletParameterBinderController.cs b/src/System.Management.Automation/engine/CmdletParameterBinderController.cs index 83d5e98e954..88fadc3342d 100644 --- a/src/System.Management.Automation/engine/CmdletParameterBinderController.cs +++ b/src/System.Management.Automation/engine/CmdletParameterBinderController.cs @@ -1620,7 +1620,10 @@ private void HandleCommandLineDynamicParameters(out ParameterBindingException ou } catch (Exception e) // Catch-all OK, this is a third-party callout { - if (e is ProviderInvocationException) { throw; } + if (e is ProviderInvocationException) + { + throw; + } ParameterBindingException bindingException = new ParameterBindingException( @@ -3321,7 +3324,11 @@ private bool BindPipelineParametersPrivate(PSObject inputToOperateOn) if (needToPrioritizeOneSpecificParameterSet && i == 0) { // If the prioritized set can be bound successfully, there is no need to do the second round binding - if (_currentParameterSetFlag == _parameterSetToBePrioritizedInPipelineBinding) break; + if (_currentParameterSetFlag == _parameterSetToBePrioritizedInPipelineBinding) + { + break; + } + validParameterSets = _currentParameterSetFlag & (~_parameterSetToBePrioritizedInPipelineBinding); } } @@ -4379,7 +4386,10 @@ public override bool ContainsKey(object key) throw PSTraceSource.NewArgumentNullException(nameof(key)); } - if (!(key is string strKey)) { return false; } + if (!(key is string strKey)) + { + return false; + } string keyAfterTrim = strKey.Trim(); return base.ContainsKey(keyAfterTrim); @@ -4448,9 +4458,15 @@ public override object this[object key] { get { - if (key == null) { throw PSTraceSource.NewArgumentNullException(nameof(key)); } + if (key == null) + { + throw PSTraceSource.NewArgumentNullException(nameof(key)); + } - if (!(key is string strKey)) { return null; } + if (!(key is string strKey)) + { + return null; + } string keyAfterTrim = strKey.Trim(); return base[keyAfterTrim]; @@ -4473,7 +4489,10 @@ public override void Remove(object key) throw PSTraceSource.NewArgumentNullException(nameof(key)); } - if (!(key is string strKey)) { return; } + if (!(key is string strKey)) + { + return; + } string keyAfterTrim = strKey.Trim(); if (base.ContainsKey(keyAfterTrim)) diff --git a/src/System.Management.Automation/engine/ComInterop/VariantArray.cs b/src/System.Management.Automation/engine/ComInterop/VariantArray.cs index a196eb96079..d4f8af57b74 100644 --- a/src/System.Management.Automation/engine/ComInterop/VariantArray.cs +++ b/src/System.Management.Automation/engine/ComInterop/VariantArray.cs @@ -58,10 +58,25 @@ internal static MemberExpression GetStructField(ParameterExpression variantArray internal static Type GetStructType(int args) { Debug.Assert(args >= 0); - if (args <= 1) return typeof(VariantArray1); - if (args <= 2) return typeof(VariantArray2); - if (args <= 4) return typeof(VariantArray4); - if (args <= 8) return typeof(VariantArray8); + if (args <= 1) + { + return typeof(VariantArray1); + } + + if (args <= 2) + { + return typeof(VariantArray2); + } + + if (args <= 4) + { + return typeof(VariantArray4); + } + + if (args <= 8) + { + return typeof(VariantArray8); + } int size = 1; while (args > size) diff --git a/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs b/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs index 49317331924..e8b76de4837 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs @@ -859,7 +859,10 @@ internal static ExperimentalFeature[] GetExperimentalFeature(string manifestPath foreach (Hashtable feature in features) { string featureName = feature["Name"] as string; - if (string.IsNullOrEmpty(featureName)) { continue; } + if (string.IsNullOrEmpty(featureName)) + { + continue; + } if (ExperimentalFeature.IsModuleFeatureName(featureName, moduleName)) { diff --git a/src/System.Management.Automation/engine/Modules/PSModuleInfo.cs b/src/System.Management.Automation/engine/Modules/PSModuleInfo.cs index 48e0cee0797..4315f8bcb2b 100644 --- a/src/System.Management.Automation/engine/Modules/PSModuleInfo.cs +++ b/src/System.Management.Automation/engine/Modules/PSModuleInfo.cs @@ -545,7 +545,10 @@ public Dictionary ExportedFunctions // If the module is not binary, it may also have functions... if (DeclaredFunctionExports != null) { - if (DeclaredFunctionExports.Count == 0) { return exports; } + if (DeclaredFunctionExports.Count == 0) + { + return exports; + } foreach (string fn in DeclaredFunctionExports) { @@ -707,7 +710,10 @@ public Dictionary ExportedCmdlets if (DeclaredCmdletExports != null) { - if (DeclaredCmdletExports.Count == 0) { return exports; } + if (DeclaredCmdletExports.Count == 0) + { + return exports; + } foreach (string fn in DeclaredCmdletExports) { diff --git a/src/System.Management.Automation/engine/interpreter/DynamicInstructions.Generated.cs b/src/System.Management.Automation/engine/interpreter/DynamicInstructions.Generated.cs index ad10413f9d0..abe64c471af 100644 --- a/src/System.Management.Automation/engine/interpreter/DynamicInstructions.Generated.cs +++ b/src/System.Management.Automation/engine/interpreter/DynamicInstructions.Generated.cs @@ -22,7 +22,11 @@ namespace System.Management.Automation.Interpreter { internal partial class DynamicInstructionN { internal static Type GetDynamicInstructionType(Type delegateType) { Type[] argTypes = delegateType.GetGenericArguments(); - if (argTypes.Length == 0) return null; + if (argTypes.Length == 0) + { + return null; + } + Type genericType; Type[] newArgTypes = argTypes.Skip(1).ToArray(); switch (newArgTypes.Length) { diff --git a/src/System.Management.Automation/engine/interpreter/LightCompiler.cs b/src/System.Management.Automation/engine/interpreter/LightCompiler.cs index 700850fb394..e037d23fbf0 100644 --- a/src/System.Management.Automation/engine/interpreter/LightCompiler.cs +++ b/src/System.Management.Automation/engine/interpreter/LightCompiler.cs @@ -68,7 +68,10 @@ public bool Matches(Type exceptionType) public bool IsBetterThan(ExceptionHandler other) { - if (other == null) return true; + if (other == null) + { + return true; + } Debug.Assert(StartIndex == other.StartIndex && EndIndex == other.EndIndex, "we only need to compare handlers for the same try block"); return HandlerStartIndex < other.HandlerStartIndex; diff --git a/src/System.Management.Automation/engine/interpreter/Utilities.cs b/src/System.Management.Automation/engine/interpreter/Utilities.cs index b5b69f7415b..0eef4728e46 100644 --- a/src/System.Management.Automation/engine/interpreter/Utilities.cs +++ b/src/System.Management.Automation/engine/interpreter/Utilities.cs @@ -1078,7 +1078,10 @@ internal static bool TrueForAll(this IEnumerable collection, Predicate foreach (T item in collection) { - if (!predicate(item)) return false; + if (!predicate(item)) + { + return false; + } } return true; diff --git a/src/System.Management.Automation/engine/remoting/client/Job.cs b/src/System.Management.Automation/engine/remoting/client/Job.cs index 4c2bf10d462..3d276278eb9 100644 --- a/src/System.Management.Automation/engine/remoting/client/Job.cs +++ b/src/System.Management.Automation/engine/remoting/client/Job.cs @@ -1011,11 +1011,17 @@ protected virtual void DoUnloadJobStreams() ///
    public void LoadJobStreams() { - if (_jobStreamsLoaded) return; + if (_jobStreamsLoaded) + { + return; + } lock (syncObject) { - if (_jobStreamsLoaded) return; + if (_jobStreamsLoaded) + { + return; + } _jobStreamsLoaded = true; } diff --git a/src/System.Management.Automation/engine/remoting/client/JobManager.cs b/src/System.Management.Automation/engine/remoting/client/JobManager.cs index 53161c40fc0..3b2baec6654 100644 --- a/src/System.Management.Automation/engine/remoting/client/JobManager.cs +++ b/src/System.Management.Automation/engine/remoting/client/JobManager.cs @@ -158,7 +158,11 @@ internal static void SaveJobId(Guid instanceId, int id, string typeName) { lock (s_syncObject) { - if (s_jobIdsForReuse.ContainsKey(instanceId)) return; + if (s_jobIdsForReuse.ContainsKey(instanceId)) + { + return; + } + s_jobIdsForReuse.Add(instanceId, new KeyValuePair(id, typeName)); } } @@ -587,7 +591,11 @@ private List GetFilteredJobs( } #pragma warning restore 56500 - if (jobs == null) continue; + if (jobs == null) + { + continue; + } + allJobs.AddRange(jobs); } } @@ -752,7 +760,10 @@ private Job2 GetJobThroughId(Guid guid, int id, Cmdlet cmdlet, bool writeErro WriteErrorOrWarning(writeErrorOnException, cmdlet, exception, "JobSourceAdapterGetJobByInstanceIdError", sourceAdapter); } - if (job == null) continue; + if (job == null) + { + continue; + } if (writeObject) { @@ -928,12 +939,20 @@ internal bool RemoveJob(Job2 job, Cmdlet cmdlet, bool writeErrorOnException, boo // sourceAdapter.GetJobByInstanceId() threw unknown exception. _tracer.TraceException(exception); - if (throwExceptions) throw; + if (throwExceptions) + { + throw; + } + WriteErrorOrWarning(writeErrorOnException, cmdlet, exception, "JobSourceAdapterGetJobError", sourceAdapter); } #pragma warning restore 56500 - if (foundJob == null) continue; + if (foundJob == null) + { + continue; + } + jobFound = true; RemoveJobIdForReuse(foundJob); @@ -951,7 +970,11 @@ internal bool RemoveJob(Job2 job, Cmdlet cmdlet, bool writeErrorOnException, boo // sourceAdapter.RemoveJob() threw unknown exception. _tracer.TraceException(exception); - if (throwExceptions) throw; + if (throwExceptions) + { + throw; + } + WriteErrorOrWarning(writeErrorOnException, cmdlet, exception, "JobSourceAdapterRemoveJobError", sourceAdapter); } #pragma warning restore 56500 diff --git a/src/System.Management.Automation/engine/remoting/client/ThrottlingJob.cs b/src/System.Management.Automation/engine/remoting/client/ThrottlingJob.cs index b9a0cc4dfab..59f4fb5135d 100644 --- a/src/System.Management.Automation/engine/remoting/client/ThrottlingJob.cs +++ b/src/System.Management.Automation/engine/remoting/client/ThrottlingJob.cs @@ -369,14 +369,25 @@ internal void DisableFlowControlForPendingCmdletActionsQueue() internal void AddChildJobWithoutBlocking(StartableJob childJob, ChildJobFlags flags, Action jobEnqueuedAction = null) { ArgumentNullException.ThrowIfNull(childJob); - if (childJob.JobStateInfo.State != JobState.NotStarted) throw new ArgumentException(RemotingErrorIdStrings.ThrottlingJobChildAlreadyRunning, nameof(childJob)); + if (childJob.JobStateInfo.State != JobState.NotStarted) + { + throw new ArgumentException(RemotingErrorIdStrings.ThrottlingJobChildAlreadyRunning, nameof(childJob)); + } + this.AssertNotDisposed(); JobStateInfo newJobStateInfo = null; lock (_lockObject) { - if (this.IsEndOfChildJobs) throw new InvalidOperationException(RemotingErrorIdStrings.ThrottlingJobChildAddedAfterEndOfChildJobs); - if (_isStopping) { return; } + if (this.IsEndOfChildJobs) + { + throw new InvalidOperationException(RemotingErrorIdStrings.ThrottlingJobChildAddedAfterEndOfChildJobs); + } + + if (_isStopping) + { + return; + } if (_countOfAllChildJobs == 0) { diff --git a/src/System.Management.Automation/engine/remoting/commands/ReceiveJob.cs b/src/System.Management.Automation/engine/remoting/commands/ReceiveJob.cs index a62cef7d5d4..3bddc676137 100644 --- a/src/System.Management.Automation/engine/remoting/commands/ReceiveJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/ReceiveJob.cs @@ -1163,14 +1163,21 @@ private void Error_DataAdded(object sender, DataAddedEventArgs e) { lock (_syncObject) { - if (_isDisposed) return; + if (_isDisposed) + { + return; + } } _writeExistingData.WaitOne(); _resultsReaderWriterLock.EnterReadLock(); try { - if (!_results.IsOpen) return; + if (!_results.IsOpen) + { + return; + } + PSDataCollection errorRecords = sender as PSDataCollection; Diagnostics.Assert(errorRecords != null, "PSDataCollection is raising an inappropriate event"); ErrorRecord errorRecord = GetData(errorRecords, e.Index); diff --git a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs index 15d2b1470b1..9c221f01dbb 100644 --- a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs +++ b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs @@ -2019,7 +2019,10 @@ public SSHConnectionInfo( string computerName, string keyFilePath) { - if (computerName == null) { throw new PSArgumentNullException(nameof(computerName)); } + if (computerName == null) + { + throw new PSArgumentNullException(nameof(computerName)); + } UserName = userName; ComputerName = computerName; diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManTransportManager.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManTransportManager.cs index d344e5c386e..6ff9187d3bf 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManTransportManager.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManTransportManager.cs @@ -1784,7 +1784,10 @@ internal IntPtr SessionHandle /// True if a session create retry has been started. private bool RetrySessionCreation(int sessionCreateErrorCode) { - if (_connectionRetryCount >= ConnectionInfo.MaxConnectionRetryCount) { return false; } + if (_connectionRetryCount >= ConnectionInfo.MaxConnectionRetryCount) + { + return false; + } bool retryConnect; switch (sessionCreateErrorCode) @@ -2617,7 +2620,10 @@ private void CloseSessionAndClearResources() private void DisposeWSManAPIDataAsync() { WSManAPIDataCommon tempWSManApiData = WSManAPIData; - if (tempWSManApiData == null) { return; } + if (tempWSManApiData == null) + { + return; + } WSManAPIData = null; @@ -2720,7 +2726,10 @@ public void Dispose() { lock (_syncObject) { - if (_isDisposed) { return; } + if (_isDisposed) + { + return; + } _isDisposed = true; } diff --git a/src/System.Management.Automation/engine/remoting/server/ServerRemoteHost.cs b/src/System.Management.Automation/engine/remoting/server/ServerRemoteHost.cs index eaed49ef40a..7e7aa767d5c 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerRemoteHost.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerRemoteHost.cs @@ -407,7 +407,10 @@ internal bool PropagatePop private void AddPSEditForRunspace(RemoteRunspace remoteRunspace) { - if (remoteRunspace.Events == null) { return; } + if (remoteRunspace.Events == null) + { + return; + } // Add event handler. remoteRunspace.Events.ReceivedEvents.PSEventReceived += HandleRemoteSessionForwardedEvent; @@ -427,7 +430,10 @@ private void AddPSEditForRunspace(RemoteRunspace remoteRunspace) private void RemovePSEditFromRunspace(RemoteRunspace remoteRunspace) { - if (remoteRunspace.Events == null) { return; } + if (remoteRunspace.Events == null) + { + return; + } // It is possible for the popped runspace to be in a bad state after an error. if ((remoteRunspace.RunspaceStateInfo.State != RunspaceState.Opened) || (remoteRunspace.RunspaceAvailability != RunspaceAvailability.Available)) @@ -453,7 +459,10 @@ private void RemovePSEditFromRunspace(RemoteRunspace remoteRunspace) private void HandleRemoteSessionForwardedEvent(object sender, PSEventArgs args) { - if ((Runspace == null) || (Runspace.Events == null)) { return; } + if ((Runspace == null) || (Runspace.Events == null)) + { + return; + } // Forward events from nested pushed session to parent session. try diff --git a/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs b/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs index 83d0ed0755a..ba0728790e7 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs @@ -2386,7 +2386,10 @@ private void RemoveDebuggerCallbacks() private void HandleDebuggerStop(object sender, DebuggerStopEventArgs e) { // Ignore if we are in restricted mode. - if (!IsDebuggingSupported()) { return; } + if (!IsDebuggingSupported()) + { + return; + } if (LocalDebugMode) { @@ -2442,7 +2445,10 @@ private void HandleDebuggerStop(object sender, DebuggerStopEventArgs e) private void HandleBreakpointUpdated(object sender, BreakpointUpdatedEventArgs e) { // Ignore if we are in restricted mode. - if (!IsDebuggingSupported()) { return; } + if (!IsDebuggingSupported()) + { + return; + } if (LocalDebugMode) { @@ -2762,7 +2768,10 @@ internal void PushDebugger(Debugger debugger) internal void PopDebugger() { - if (!_wrappedDebugger.IsOverridden) { return; } + if (!_wrappedDebugger.IsOverridden) + { + return; + } // Swap wrapped debugger. UnsubscribeWrappedDebugger(_wrappedDebugger.Value); diff --git a/src/System.Management.Automation/engine/runtime/MutableTuple.cs b/src/System.Management.Automation/engine/runtime/MutableTuple.cs index 480e8e111b8..53c40ef3810 100644 --- a/src/System.Management.Automation/engine/runtime/MutableTuple.cs +++ b/src/System.Management.Automation/engine/runtime/MutableTuple.cs @@ -281,7 +281,11 @@ public static int GetSize(Type tupleType) // ContractUtils.RequiresNotNull(tupleType, "tupleType"); int count = 0; - lock (s_sizeDict) if (s_sizeDict.TryGetValue(tupleType, out count)) return count; + lock (s_sizeDict) if (s_sizeDict.TryGetValue(tupleType, out count)) + { + return count; + } + Stack types = new Stack(tupleType.GetGenericArguments()); while (types.Count != 0) @@ -298,7 +302,10 @@ public static int GetSize(Type tupleType) continue; } - if (t == typeof(DynamicNull)) continue; + if (t == typeof(DynamicNull)) + { + continue; + } count++; } diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index 3d4c3e2f9da..1db69c2a125 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -2885,7 +2885,10 @@ protected override void RemoveItem(string path, bool recurse) foreach (AlternateStreamData stream in AlternateDataStreamUtilities.GetStreams(fsinfo.FullName)) { - if (!p.IsMatch(stream.Stream)) { continue; } + if (!p.IsMatch(stream.Stream)) + { + continue; + } foundStream = true; @@ -4456,7 +4459,10 @@ private bool PerformCopyFileFromRemoteSession(string sourceFileFullName, FileInf private void InitializeFunctionsPSCopyFileToRemoteSession(System.Management.Automation.PowerShell ps) { - if ((ps == null) || !ValidRemoteSessionForScripting(ps.Runspace)) { return; } + if ((ps == null) || !ValidRemoteSessionForScripting(ps.Runspace)) + { + return; + } ps.AddScript(CopyFileRemoteUtils.AllCopyToRemoteScripts); SafeInvokeCommand.Invoke(ps, this, null, false); @@ -4464,7 +4470,10 @@ private void InitializeFunctionsPSCopyFileToRemoteSession(System.Management.Auto private void RemoveFunctionPSCopyFileToRemoteSession(System.Management.Automation.PowerShell ps) { - if ((ps == null) || !ValidRemoteSessionForScripting(ps.Runspace)) { return; } + if ((ps == null) || !ValidRemoteSessionForScripting(ps.Runspace)) + { + return; + } const string remoteScript = @" Microsoft.PowerShell.Management\Remove-Item function:PSCopyToSessionHelper -ea SilentlyContinue -Force diff --git a/src/System.Management.Automation/security/wldpNativeMethods.cs b/src/System.Management.Automation/security/wldpNativeMethods.cs index a44aad4e792..2fadcedb06b 100644 --- a/src/System.Management.Automation/security/wldpNativeMethods.cs +++ b/src/System.Management.Automation/security/wldpNativeMethods.cs @@ -357,23 +357,38 @@ private static SystemEnforcementMode GetAppLockerPolicy(string path, SafeHandle IO.File.WriteAllText(testPathScript, dtAppLockerTestFileContents); IO.File.WriteAllText(testPathModule, dtAppLockerTestFileContents); } - catch (System.IO.IOException) + catch (IO.IOException) { - if (iteration == 2) throw; + if (iteration == 2) + { + throw; + } + error = true; } - catch (System.UnauthorizedAccessException) + catch (UnauthorizedAccessException) { - if (iteration == 2) throw; + if (iteration == 2) + { + throw; + } + error = true; } catch (System.Security.SecurityException) { - if (iteration == 2) throw; + if (iteration == 2) + { + throw; + } + error = true; } - if (!error) { break; } + if (!error) + { + break; + } // Try again with the AppData\LocalLow\Temp path using known folder id: // https://msdn.microsoft.com/library/dd378457.aspx diff --git a/test/powershell/engine/ExperimentalFeature/assets/ExpTest/ExpTest.cs b/test/powershell/engine/ExperimentalFeature/assets/ExpTest/ExpTest.cs index 2b4b0980404..8c33c7039b3 100644 --- a/test/powershell/engine/ExperimentalFeature/assets/ExpTest/ExpTest.cs +++ b/test/powershell/engine/ExperimentalFeature/assets/ExpTest/ExpTest.cs @@ -61,9 +61,15 @@ protected override void EndProcessing() string message = $"Hello World {Name}."; if (ExperimentalFeature.IsEnabled("ExpTest.FeatureOne")) { - if (SwitchOne.IsPresent) { message += "-SwitchOne is on."; } - - if (SwitchTwo.IsPresent) { message += "-SwitchTwo is on."; } + if (SwitchOne.IsPresent) + { + message += "-SwitchOne is on."; + } + + if (SwitchTwo.IsPresent) + { + message += "-SwitchTwo is on."; + } } WriteObject(message); From 688c7f3689e918146309c2f62345bed07eab2381 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Sat, 18 Mar 2023 18:06:32 +0100 Subject: [PATCH 450/779] Initialize Regex lazy in BasicHtmlWebResponseObject (#19361) --- .../BasicHtmlWebResponseObject.Common.cs | 67 ++++++------------- 1 file changed, 22 insertions(+), 45 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/BasicHtmlWebResponseObject.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/BasicHtmlWebResponseObject.Common.cs index 8e8c099c661..8c15ac96d97 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/BasicHtmlWebResponseObject.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/BasicHtmlWebResponseObject.Common.cs @@ -16,17 +16,6 @@ namespace Microsoft.PowerShell.Commands ///
    public class BasicHtmlWebResponseObject : WebResponseObject { - #region Private Fields - - private static Regex s_attribNameValueRegex; - private static Regex s_attribsRegex; - private static Regex s_imageRegex; - private static Regex s_inputFieldRegex; - private static Regex s_linkRegex; - private static Regex s_tagRegex; - - #endregion Private Fields - #region Constructors /// @@ -43,7 +32,6 @@ public BasicHtmlWebResponseObject(HttpResponseMessage response) : this(response, /// public BasicHtmlWebResponseObject(HttpResponseMessage response, Stream contentStream) : base(response, contentStream) { - EnsureHtmlParser(); InitializeContent(); InitializeRawContent(response); } @@ -82,10 +70,8 @@ public WebCmdletElementCollection InputFields { if (_inputFields == null) { - EnsureHtmlParser(); - List parsedFields = new(); - MatchCollection fieldMatch = s_inputFieldRegex.Matches(Content); + MatchCollection fieldMatch = HtmlParser.InputFieldRegex.Matches(Content); foreach (Match field in fieldMatch) { parsedFields.Add(CreateHtmlObject(field.Value, "INPUT")); @@ -109,10 +95,8 @@ public WebCmdletElementCollection Links { if (_links == null) { - EnsureHtmlParser(); - List parsedLinks = new(); - MatchCollection linkMatch = s_linkRegex.Matches(Content); + MatchCollection linkMatch = HtmlParser.LinkRegex.Matches(Content); foreach (Match link in linkMatch) { parsedLinks.Add(CreateHtmlObject(link.Value, "A")); @@ -136,10 +120,8 @@ public WebCmdletElementCollection Images { if (_images == null) { - EnsureHtmlParser(); - List parsedImages = new(); - MatchCollection imageMatch = s_imageRegex.Matches(Content); + MatchCollection imageMatch = HtmlParser.ImageRegex.Matches(Content); foreach (Match image in imageMatch) { parsedImages.Add(CreateHtmlObject(image.Value, "IMG")); @@ -188,27 +170,6 @@ private static PSObject CreateHtmlObject(string html, string tagName) return elementObject; } - private static void EnsureHtmlParser() - { - s_tagRegex ??= new Regex(@"<\w+((\s+[^""'>/=\s\p{Cc}]+(\s*=\s*(?:"".*?""|'.*?'|[^'"">\s]+))?)+\s*|\s*)/?>", - RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled); - - s_attribsRegex ??= new Regex(@"(?<=\s+)([^""'>/=\s\p{Cc}]+(\s*=\s*(?:"".*?""|'.*?'|[^'"">\s]+))?)", - RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled); - - s_attribNameValueRegex ??= new Regex(@"([^""'>/=\s\p{Cc}]+)(?:\s*=\s*(?:""(.*?)""|'(.*?)'|([^'"">\s]+)))?", - RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled); - - s_inputFieldRegex ??= new Regex(@"]*(/?>|>.*?)", - RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled); - - s_linkRegex ??= new Regex(@"]*(/>|>.*?)", - RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled); - - s_imageRegex ??= new Regex(@"]*?>", - RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled); - } - private void InitializeRawContent(HttpResponseMessage baseResponse) { StringBuilder raw = ContentHelper.GetRawContentHeader(baseResponse); @@ -223,16 +184,16 @@ private static void ParseAttributes(string outerHtml, PSObject elementObject) { // Extract just the opening tag of the HTML element (omitting the closing tag and any contents, // including contained HTML elements) - Match match = s_tagRegex.Match(outerHtml); + Match match = HtmlParser.TagRegex.Match(outerHtml); // Extract all the attribute specifications within the HTML element opening tag - MatchCollection attribMatches = s_attribsRegex.Matches(match.Value); + MatchCollection attribMatches = HtmlParser.AttribsRegex.Matches(match.Value); foreach (Match attribMatch in attribMatches) { // Extract the name and value for this attribute (allowing for variations like single/double/no // quotes, and no value at all) - Match nvMatches = s_attribNameValueRegex.Match(attribMatch.Value); + Match nvMatches = HtmlParser.AttribNameValueRegex.Match(attribMatch.Value); Debug.Assert(nvMatches.Groups.Count == 5); // Name is always captured by group #1 @@ -259,5 +220,21 @@ private static void ParseAttributes(string outerHtml, PSObject elementObject) } #endregion Methods + + // This class is needed so the static Regexes are initialized only the first time they are used + private static class HtmlParser + { + internal static readonly Regex AttribsRegex = new Regex(@"(?<=\s+)([^""'>/=\s\p{Cc}]+(\s*=\s*(?:"".*?""|'.*?'|[^'"">\s]+))?)", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled); + + internal static readonly Regex AttribNameValueRegex = new Regex(@"([^""'>/=\s\p{Cc}]+)(?:\s*=\s*(?:""(.*?)""|'(.*?)'|([^'"">\s]+)))?", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled); + + internal static readonly Regex ImageRegex = new Regex(@"]*?>", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled); + + internal static readonly Regex InputFieldRegex = new Regex(@"]*(/?>|>.*?)", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled); + + internal static readonly Regex LinkRegex = new Regex(@"]*(/>|>.*?)", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled); + + internal static readonly Regex TagRegex = new Regex(@"<\w+((\s+[^""'>/=\s\p{Cc}]+(\s*=\s*(?:"".*?""|'.*?'|[^'"">\s]+))?)+\s*|\s*)/?>", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled); + } } } From 8f0cd65257ab8959dd16a424a5973fbf2fdb7651 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Mon, 20 Mar 2023 17:14:49 +0100 Subject: [PATCH 451/779] Simplify ContentHelper methods (#19367) --- .../WebCmdlet/Common/ContentHelper.Common.cs | 43 +++---------------- .../utility/WebCmdlet/StreamHelper.cs | 11 ++--- 2 files changed, 8 insertions(+), 46 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs index 41af8ebc6dc..bf127967ffe 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs @@ -60,28 +60,6 @@ internal static StringBuilder GetRawContentHeader(HttpResponseMessage response) } internal static bool IsJson(string contentType) - { - contentType = GetContentTypeSignature(contentType); - return CheckIsJson(contentType); - } - - internal static bool IsText(string contentType) - { - contentType = GetContentTypeSignature(contentType); - return CheckIsText(contentType); - } - - internal static bool IsXml(string contentType) - { - contentType = GetContentTypeSignature(contentType); - return CheckIsXml(contentType); - } - - #endregion Internal Methods - - #region Private Helper Methods - - private static bool CheckIsJson(string contentType) { if (string.IsNullOrEmpty(contentType)) { @@ -102,7 +80,7 @@ private static bool CheckIsJson(string contentType) return isJson; } - private static bool CheckIsText(string contentType) + internal static bool IsText(string contentType) { if (string.IsNullOrEmpty(contentType)) { @@ -111,8 +89,8 @@ private static bool CheckIsText(string contentType) // Any text, xml or json types are text bool isText = contentType.StartsWith("text/", StringComparison.OrdinalIgnoreCase) - || CheckIsXml(contentType) - || CheckIsJson(contentType); + || IsXml(contentType) + || IsJson(contentType); // Further content type analysis is available on Windows if (Platform.IsWindows && !isText) @@ -141,7 +119,7 @@ private static bool CheckIsText(string contentType) return isText; } - private static bool CheckIsXml(string contentType) + internal static bool IsXml(string contentType) { if (string.IsNullOrEmpty(contentType)) { @@ -157,17 +135,6 @@ private static bool CheckIsXml(string contentType) return isXml; } - private static string GetContentTypeSignature(string contentType) - { - if (string.IsNullOrEmpty(contentType)) - { - return null; - } - - string sig = contentType.Split(';', 2)[0].ToUpperInvariant(); - return sig; - } - - #endregion Private Helper Methods + #endregion Internal Methods } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs index 1ddaf5a5794..49cc7d43402 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs @@ -383,13 +383,7 @@ private static string StreamToString(Stream stream, Encoding encoding) internal static string DecodeStream(Stream stream, string characterSet, out Encoding encoding) { - bool isDefaultEncoding = false; - if (!TryGetEncoding(characterSet, out encoding)) - { - // Use the default encoding if one wasn't provided - encoding = ContentHelper.GetDefaultEncoding(); - isDefaultEncoding = true; - } + bool isDefaultEncoding = !TryGetEncoding(characterSet, out encoding); string content = StreamToString(stream, encoding); if (isDefaultEncoding) @@ -433,7 +427,8 @@ internal static bool TryGetEncoding(string characterSet, out Encoding encoding) } catch (ArgumentException) { - encoding = null; + // Use the default encoding if one wasn't provided + encoding = ContentHelper.GetDefaultEncoding(); } return result; From 4dfcbb313ed6bbbcd9d48638ae87f5a9ca6d4dc8 Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Mon, 20 Mar 2023 15:43:49 -0700 Subject: [PATCH 452/779] Fix stage dependencies and typo in release build (#19353) --- tools/releaseBuild/azureDevOps/releaseBuild.yml | 8 ++++---- .../azureDevOps/templates/mac-package-signing.yml | 1 - 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/tools/releaseBuild/azureDevOps/releaseBuild.yml b/tools/releaseBuild/azureDevOps/releaseBuild.yml index dfde466a80b..1e979e8c587 100644 --- a/tools/releaseBuild/azureDevOps/releaseBuild.yml +++ b/tools/releaseBuild/azureDevOps/releaseBuild.yml @@ -323,12 +323,12 @@ stages: - template: templates/windows-package-signing.yml - template: templates/mac-package-signing.yml - parameters: - buildArchitecture: x64 + parameters: + buildArchitecture: x64 - template: templates/mac-package-signing.yml - parameters: - buildArchitecture: arm64 + parameters: + buildArchitecture: arm64 # This is done late so that we dont use resources before the big signing and packaging tasks. - stage: compliance diff --git a/tools/releaseBuild/azureDevOps/templates/mac-package-signing.yml b/tools/releaseBuild/azureDevOps/templates/mac-package-signing.yml index c0fea010973..b4b6f05821b 100644 --- a/tools/releaseBuild/azureDevOps/templates/mac-package-signing.yml +++ b/tools/releaseBuild/azureDevOps/templates/mac-package-signing.yml @@ -4,7 +4,6 @@ parameters: jobs: - job: MacPackageSigningJob_${{ parameters.buildArchitecture }} displayName: macOS Package signing ${{ parameters.buildArchitecture }} - dependsOn: package_macOS_${{ parameters.buildArchitecture }} condition: succeeded() pool: name: PowerShell1ES From 5b1dedac61729d32edad0cefd3609a902cde3970 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Tue, 21 Mar 2023 09:06:50 +0100 Subject: [PATCH 453/779] Allow using a folder path in WebCmdlet's OutFile parameter (#19007) --- .../Common/InvokeRestMethodCommand.Common.cs | 8 +++-- .../Common/WebRequestPSCmdlet.Common.cs | 14 +++++++- .../InvokeWebRequestCommand.CoreClr.cs | 6 +++- .../CoreCLR/WebResponseHelper.CoreClr.cs | 9 +++++ .../resources/WebCmdletStrings.resx | 3 ++ .../WebCmdlets.Tests.ps1 | 36 +++++++++++++++++++ 6 files changed, 72 insertions(+), 4 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs index 0c97211faea..adfb4f1a610 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs @@ -135,8 +135,12 @@ internal override void ProcessResponse(HttpResponseMessage response) } } else if (ShouldSaveToOutFile) - { - StreamHelper.SaveStreamToFile(baseResponseStream, QualifiedOutFile, this, response.Content.Headers.ContentLength.GetValueOrDefault(), _cancelToken.Token); + { + string outFilePath = WebResponseHelper.GetOutFilePath(response, _qualifiedOutFile); + + WriteVerbose(string.Create(System.Globalization.CultureInfo.InvariantCulture, $"File Name: {Path.GetFileName(_qualifiedOutFile)}")); + + StreamHelper.SaveStreamToFile(baseResponseStream, outFilePath, this, response.Content.Headers.ContentLength.GetValueOrDefault(), _cancelToken.Token); } if (!string.IsNullOrEmpty(StatusCodeVariable)) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index c1df22296e7..c078faaed5c 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -484,6 +484,8 @@ public virtual string CustomMethod internal string QualifiedOutFile => QualifyFilePath(OutFile); + internal string _qualifiedOutFile; + internal bool ShouldCheckHttpStatus => !SkipHttpErrorCheck; /// @@ -852,7 +854,7 @@ internal virtual void ValidateParameters() } // Output ?? - if (PassThru && OutFile is null) + if (PassThru.IsPresent && OutFile is null) { ErrorRecord error = GetValidationError(WebCmdletStrings.OutFileMissing, "WebCmdletOutFileMissingException", nameof(PassThru)); ThrowTerminatingError(error); @@ -864,6 +866,15 @@ internal virtual void ValidateParameters() ErrorRecord error = GetValidationError(WebCmdletStrings.OutFileMissing, "WebCmdletOutFileMissingException", nameof(Resume)); ThrowTerminatingError(error); } + + _qualifiedOutFile = ShouldSaveToOutFile ? QualifiedOutFile : null; + + // OutFile must not be a directory to use Resume. + if (Resume.IsPresent && Directory.Exists(_qualifiedOutFile)) + { + ErrorRecord error = GetValidationError(WebCmdletStrings.ResumeNotFilePath, "WebCmdletResumeNotFilePathException", _qualifiedOutFile); + ThrowTerminatingError(error); + } } internal virtual void PrepareSession() @@ -1093,6 +1104,7 @@ internal virtual HttpRequestMessage GetRequest(Uri uri) if (Resume.IsPresent) { FileInfo fileInfo = new(QualifiedOutFile); + if (fileInfo.Exists) { request.Headers.Range = new RangeHeaderValue(fileInfo.Length, null); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/InvokeWebRequestCommand.CoreClr.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/InvokeWebRequestCommand.CoreClr.cs index e101bcc65b7..94245548e80 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/InvokeWebRequestCommand.CoreClr.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/InvokeWebRequestCommand.CoreClr.cs @@ -56,7 +56,11 @@ internal override void ProcessResponse(HttpResponseMessage response) if (ShouldSaveToOutFile) { - StreamHelper.SaveStreamToFile(responseStream, QualifiedOutFile, this, response.Content.Headers.ContentLength.GetValueOrDefault(), _cancelToken.Token); + string outFilePath = WebResponseHelper.GetOutFilePath(response, _qualifiedOutFile); + + WriteVerbose(string.Create(System.Globalization.CultureInfo.InvariantCulture, $"File Name: {Path.GetFileName(_qualifiedOutFile)}")); + + StreamHelper.SaveStreamToFile(responseStream, outFilePath, this, response.Content.Headers.ContentLength.GetValueOrDefault(), _cancelToken.Token); } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseHelper.CoreClr.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseHelper.CoreClr.cs index b1449de0692..eff0d658c81 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseHelper.CoreClr.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseHelper.CoreClr.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using System.Globalization; +using System.IO; using System.Net.Http; namespace Microsoft.PowerShell.Commands @@ -34,6 +35,14 @@ internal static Dictionary> GetHeadersDictionary(Htt return headers; } + internal static string GetOutFilePath(HttpResponseMessage response, string _qualifiedOutFile) + { + // Get file name from last segment of Uri + string lastUriSegment = System.Net.WebUtility.UrlDecode(response.RequestMessage.RequestUri.Segments[^1]); + + return Directory.Exists(_qualifiedOutFile) ? Path.Join(_qualifiedOutFile, lastUriSegment) : _qualifiedOutFile; + } + internal static string GetProtocol(HttpResponseMessage response) => string.Create(CultureInfo.InvariantCulture, $"HTTP/{response.Version}"); internal static int GetStatusCode(HttpResponseMessage response) => (int)response.StatusCode; diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/WebCmdletStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/WebCmdletStrings.resx index 5b1b33eae62..4236ba80791 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/WebCmdletStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/WebCmdletStrings.resx @@ -203,6 +203,9 @@ Downloaded: {0} of {1} + + + The Resume switch can only be used if OutFile targets a file but it resolves to a directory: {0}. The cmdlet cannot run because the following conflicting parameters are specified: Session and SessionVariable. Specify either Session or SessionVariable, then retry. diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 index fe6db03a2a1..5f1e6e4bae3 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 @@ -735,6 +735,19 @@ Describe "Invoke-WebRequest tests" -Tags "Feature", "RequireAdminOnWindows" { $jsonContent.headers.Host | Should -Be $uri.Authority } + It "Invoke-WebRequest -OutFile folder Downloads the file and names it" { + $uri = Get-WebListenerUrl -Test 'Get' + $content = Invoke-WebRequest -Uri $uri + $outFile = Join-Path $TestDrive $content.BaseResponse.RequestMessage.RequestUri.Segments[-1] + + # ensure the file does not exist + Remove-Item -Force -ErrorAction Ignore -Path $outFile + Invoke-WebRequest -Uri $uri -OutFile $TestDrive + + Test-Path $outFile | Should -Be $true + Get-Item $outFile | Select-Object -ExpandProperty Length | Should -Be $content.Content.Length + } + It "Invoke-WebRequest should fail if -OutFile is ." -TestCases @( @{ Name = "empty"; Value = [string]::Empty } @{ Name = "null"; Value = $null } @@ -2000,6 +2013,11 @@ Describe "Invoke-WebRequest tests" -Tags "Feature", "RequireAdminOnWindows" { Should -Throw -ErrorId 'WebCmdletOutFileMissingException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand' } + It "Invoke-WebRequest -Resume should fail if -OutFile folder" { + { Invoke-WebRequest -Resume -Uri $resumeUri -OutFile $TestDrive -ErrorAction Stop } | + Should -Throw -ErrorId 'WebCmdletResumeNotFilePathException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand' + } + It "Invoke-WebRequest -Resume Downloads the whole file when the file does not exist" { $response = Invoke-WebRequest -Uri $resumeUri -OutFile $outFile -Resume -PassThru @@ -2691,6 +2709,19 @@ Describe "Invoke-RestMethod tests" -Tags "Feature", "RequireAdminOnWindows" { $jsonContent.headers.Host | Should -Be $uri.Authority } + It "Invoke-RestMethod -OutFile folder Downloads the file and names it" { + $uri = Get-WebListenerUrl -Test 'Get' + $content = Invoke-WebRequest -Uri $uri + $outFile = Join-Path $TestDrive $content.BaseResponse.RequestMessage.RequestUri.Segments[-1] + + # ensure the file does not exist + Remove-Item -Force -ErrorAction Ignore -Path $outFile + Invoke-RestMethod -Uri $uri -OutFile $TestDrive + + Test-Path $outFile | Should -Be $true + Get-Item $outFile | Select-Object -ExpandProperty Length | Should -Be $content.Content.Length + } + It "Invoke-RestMethod should fail if -OutFile is ." -TestCases @( @{ Name = "empty"; Value = [string]::Empty } @{ Name = "null"; Value = $null } @@ -3881,6 +3912,11 @@ Describe "Invoke-RestMethod tests" -Tags "Feature", "RequireAdminOnWindows" { Should -Throw -ErrorId 'WebCmdletOutFileMissingException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand' } + It "Invoke-RestMethod -Resume should fail if -OutFile folder" { + { Invoke-RestMethod -Resume -Uri $resumeUri -OutFile $TestDrive -ErrorAction Stop } | + Should -Throw -ErrorId 'WebCmdletResumeNotFilePathException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand' + } + It "Invoke-RestMethod -Resume Downloads the whole file when the file does not exist" { # ensure the file does not exist Remove-Item -Force -ErrorAction 'SilentlyContinue' -Path $outFile From 190c99a416b6f3c7e48066eadf3943d4ddccb2d8 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Tue, 21 Mar 2023 18:59:14 +0100 Subject: [PATCH 454/779] Remove FormObject.cs and FormObjectCollection.cs (#19383) --- .../Common/WebRequestPSCmdlet.Common.cs | 3 - .../commands/utility/WebCmdlet/FormObject.cs | 55 ------------------- .../utility/WebCmdlet/FormObjectCollection.cs | 37 ------------- 3 files changed, 95 deletions(-) delete mode 100644 src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObject.cs delete mode 100644 src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObjectCollection.cs diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index c078faaed5c..597e7caa2bb 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -1157,9 +1157,6 @@ internal virtual void FillRequestStream(HttpRequestMessage request) switch (content) { - case FormObject form: - SetRequestContent(request, form.Fields); - break; case IDictionary dictionary when request.Method != HttpMethod.Get: SetRequestContent(request, dictionary); break; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObject.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObject.cs deleted file mode 100644 index b496a120329..00000000000 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObject.cs +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System.Collections.Generic; - -namespace Microsoft.PowerShell.Commands -{ - /// - /// FormObject used in HtmlWebResponseObject. - /// - public class FormObject - { - /// - /// Gets the Id property. - /// - public string Id { get; } - - /// - /// Gets the Method property. - /// - public string Method { get; } - - /// - /// Gets the Action property. - /// - public string Action { get; } - - /// - /// Gets the Fields property. - /// - public Dictionary Fields { get; } - - /// - /// Initializes a new instance of the class. - /// - /// - /// - /// - public FormObject(string id, string method, string action) - { - Id = id; - Method = method; - Action = action; - Fields = new Dictionary(); - } - - internal void AddField(string key, string value) - { - if (key is not null && !Fields.TryGetValue(key, out string test)) - { - Fields[key] = value; - } - } - } -} diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObjectCollection.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObjectCollection.cs deleted file mode 100644 index f435b92e484..00000000000 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObjectCollection.cs +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections.ObjectModel; - -namespace Microsoft.PowerShell.Commands -{ - /// - /// FormObjectCollection used in HtmlWebResponseObject. - /// - public class FormObjectCollection : Collection - { - /// - /// Gets the FormObject from the key. - /// - /// - /// - public FormObject this[string key] - { - get - { - FormObject form = null; - foreach (FormObject f in this) - { - if (string.Equals(key, f.Id, StringComparison.OrdinalIgnoreCase)) - { - form = f; - break; - } - } - - return form; - } - } - } -} From 18f0c5ad4bc65549dd3113eabc1b0b73f13dd0cd Mon Sep 17 00:00:00 2001 From: MartinGC94 <42123497+MartinGC94@users.noreply.github.com> Date: Wed, 22 Mar 2023 04:58:15 +0100 Subject: [PATCH 455/779] Exclude redundant parameter aliases from completion results (#19382) --- .../CommandCompletion/CompletionCompleters.cs | 41 ++++++++++++------- .../Host/TabCompletion/BugFix.Tests.ps1 | 3 +- .../TabCompletion/TabCompletion.Tests.ps1 | 20 +++++++-- 3 files changed, 44 insertions(+), 20 deletions(-) diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs index 9b10aa31eab..7d7ecf9ab91 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs @@ -719,13 +719,21 @@ private static List GetParameterCompletionResults(string param string tooltip = parameterType + matchedParameterName; result.Add(new CompletionResult(completionText, matchedParameterName, CompletionResultType.ParameterName, tooltip)); } - - // Process alias when there is partial input - result.AddRange(from alias in param.Parameter.Aliases - where pattern.IsMatch(alias) - select - new CompletionResult("-" + alias + colonSuffix, alias, CompletionResultType.ParameterName, - parameterType + alias)); + else + { + // Process alias when there is partial input + foreach (var alias in param.Parameter.Aliases) + { + if (pattern.IsMatch(alias)) + { + result.Add(new CompletionResult( + $"-{alias}{colonSuffix}", + alias, + CompletionResultType.ParameterName, + parameterType + alias)); + } + } + } return result; } @@ -791,15 +799,20 @@ private static List GetParameterCompletionResults( tooltip)); } } - - if (parameterName != string.Empty) + else if (parameterName != string.Empty) { // Process alias when there is partial input - listInUse.AddRange(from alias in param.Parameter.Aliases - where pattern.IsMatch(alias) - select - new CompletionResult("-" + alias + colonSuffix, alias, CompletionResultType.ParameterName, - type + alias)); + foreach (var alias in param.Parameter.Aliases) + { + if (pattern.IsMatch(alias)) + { + listInUse.Add(new CompletionResult( + $"-{alias}{colonSuffix}", + alias, + CompletionResultType.ParameterName, + type + alias)); + } + } } } diff --git a/test/powershell/Host/TabCompletion/BugFix.Tests.ps1 b/test/powershell/Host/TabCompletion/BugFix.Tests.ps1 index 3cc44f3c0e1..dabb215cb16 100644 --- a/test/powershell/Host/TabCompletion/BugFix.Tests.ps1 +++ b/test/powershell/Host/TabCompletion/BugFix.Tests.ps1 @@ -28,10 +28,9 @@ Describe "Tab completion bug fix" -Tags "CI" { It "Issue#1345 - 'Import-Module -n' should work" { $cmd = "Import-Module -n" $result = TabExpansion2 -inputScript $cmd -cursorColumn $cmd.Length - $result.CompletionMatches | Should -HaveCount 3 + $result.CompletionMatches | Should -HaveCount 2 $result.CompletionMatches[0].CompletionText | Should -BeExactly "-Name" $result.CompletionMatches[1].CompletionText | Should -BeExactly "-NoClobber" - $result.CompletionMatches[2].CompletionText | Should -BeExactly "-NoOverwrite" } It "Issue#11227 - [CompletionCompleters]::CompleteVariable and [CompletionCompleters]::CompleteType should work" { diff --git a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 index bf3195b7aa0..d7c98b1589d 100644 --- a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 +++ b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 @@ -871,6 +871,18 @@ class InheritedClassTest : System.Attribute $res.CompletionMatches.CompletionText | Should -Contain 'TypeId' } + it 'Should not complete parameter aliases if the real parameter is in the completion results' { + $res = TabExpansion2 -inputScript 'Get-ChildItem -p' + $res.CompletionMatches.CompletionText | Should -Not -Contain '-proga' + $res.CompletionMatches.CompletionText | Should -Contain '-ProgressAction' + } + + it 'Should not complete parameter aliases if the real parameter is in the completion results (Non ambiguous parameters)' { + $res = TabExpansion2 -inputScript 'Get-ChildItem -prog' + $res.CompletionMatches.CompletionText | Should -Not -Contain '-proga' + $res.CompletionMatches.CompletionText | Should -Contain '-ProgressAction' + } + Context "Script name completion" { BeforeAll { Setup -f 'install-powershell.ps1' -Content "" @@ -1646,15 +1658,15 @@ dir -Recurse ` It "Test completion with exact match" { $inputStr = 'get-content -wa' $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length - $res.CompletionMatches | Should -HaveCount 4 - [string]::Join(',', ($res.CompletionMatches.completiontext | Sort-Object)) | Should -BeExactly "-wa,-Wait,-WarningAction,-WarningVariable" + $res.CompletionMatches | Should -HaveCount 3 + [string]::Join(',', ($res.CompletionMatches.completiontext | Sort-Object)) | Should -BeExactly "-Wait,-WarningAction,-WarningVariable" } It "Test completion with splatted variable" { $inputStr = 'Get-Content @Splat -P' $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length - $res.CompletionMatches | Should -HaveCount 6 - [string]::Join(',', ($res.CompletionMatches.completiontext | Sort-Object)) | Should -BeExactly "-Path,-PipelineVariable,-proga,-ProgressAction,-PSPath,-pv" + $res.CompletionMatches | Should -HaveCount 4 + [string]::Join(',', ($res.CompletionMatches.completiontext | Sort-Object)) | Should -BeExactly "-Path,-PipelineVariable,-ProgressAction,-PSPath" } It "Test completion for HttpVersion parameter name" { From 098be4803396e50ffd84d3ccf266b3564eab9e5e Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Wed, 22 Mar 2023 18:22:29 +0100 Subject: [PATCH 456/779] Revert "Remove FormObject.cs and FormObjectCollection.cs (#19383)" (#19387) This reverts commit 190c99a416b6f3c7e48066eadf3943d4ddccb2d8. --- .../Common/WebRequestPSCmdlet.Common.cs | 3 + .../commands/utility/WebCmdlet/FormObject.cs | 55 +++++++++++++++++++ .../utility/WebCmdlet/FormObjectCollection.cs | 37 +++++++++++++ 3 files changed, 95 insertions(+) create mode 100644 src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObject.cs create mode 100644 src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObjectCollection.cs diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index 597e7caa2bb..c078faaed5c 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -1157,6 +1157,9 @@ internal virtual void FillRequestStream(HttpRequestMessage request) switch (content) { + case FormObject form: + SetRequestContent(request, form.Fields); + break; case IDictionary dictionary when request.Method != HttpMethod.Get: SetRequestContent(request, dictionary); break; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObject.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObject.cs new file mode 100644 index 00000000000..b496a120329 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObject.cs @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections.Generic; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// FormObject used in HtmlWebResponseObject. + /// + public class FormObject + { + /// + /// Gets the Id property. + /// + public string Id { get; } + + /// + /// Gets the Method property. + /// + public string Method { get; } + + /// + /// Gets the Action property. + /// + public string Action { get; } + + /// + /// Gets the Fields property. + /// + public Dictionary Fields { get; } + + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// + public FormObject(string id, string method, string action) + { + Id = id; + Method = method; + Action = action; + Fields = new Dictionary(); + } + + internal void AddField(string key, string value) + { + if (key is not null && !Fields.TryGetValue(key, out string test)) + { + Fields[key] = value; + } + } + } +} diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObjectCollection.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObjectCollection.cs new file mode 100644 index 00000000000..f435b92e484 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObjectCollection.cs @@ -0,0 +1,37 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.ObjectModel; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// FormObjectCollection used in HtmlWebResponseObject. + /// + public class FormObjectCollection : Collection + { + /// + /// Gets the FormObject from the key. + /// + /// + /// + public FormObject this[string key] + { + get + { + FormObject form = null; + foreach (FormObject f in this) + { + if (string.Equals(key, f.Id, StringComparison.OrdinalIgnoreCase)) + { + form = f; + break; + } + } + + return form; + } + } + } +} From 48c9d683565ed9402430a27e09410d56d52d4bfd Mon Sep 17 00:00:00 2001 From: MartinGC94 <42123497+MartinGC94@users.noreply.github.com> Date: Thu, 23 Mar 2023 00:44:48 +0100 Subject: [PATCH 457/779] Add the parameter `-RelativeBasePath` to `Resolve-Path` (#19358) --- .../commands/management/ResolvePathCommand.cs | 94 +++++++++++++++++-- .../Resolve-Path.Tests.ps1 | 4 + 2 files changed, 91 insertions(+), 7 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/ResolvePathCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ResolvePathCommand.cs index 905a82c8e86..06e8b3f7c69 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ResolvePathCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/ResolvePathCommand.cs @@ -22,6 +22,8 @@ public class ResolvePathCommand : CoreCommandWithCredentialsBase /// [Parameter(Position = 0, ParameterSetName = "Path", Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] + [Parameter(Position = 0, ParameterSetName = "PathWithRelativeBase", + Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] public string[] Path { get @@ -40,6 +42,8 @@ public string[] Path /// [Parameter(ParameterSetName = "LiteralPath", Mandatory = true, ValueFromPipeline = false, ValueFromPipelineByPropertyName = true)] + [Parameter(ParameterSetName = "LiteralPathWithRelativeBase", + Mandatory = true, ValueFromPipeline = false, ValueFromPipelineByPropertyName = true)] [Alias("PSPath", "LP")] public string[] LiteralPath { @@ -59,7 +63,8 @@ public string[] LiteralPath /// Gets or sets the value that determines if the resolved path should /// be resolved to its relative version. /// - [Parameter()] + [Parameter(ParameterSetName = "Path")] + [Parameter(ParameterSetName = "LiteralPath")] public SwitchParameter Relative { get @@ -75,6 +80,25 @@ public SwitchParameter Relative private SwitchParameter _relative; + /// + /// Gets or sets the path the resolved relative path should be based off. + /// + [Parameter(Mandatory = true, ParameterSetName = "PathWithRelativeBase")] + [Parameter(Mandatory = true, ParameterSetName = "LiteralPathWithRelativeBase")] + public string RelativeBasePath + { + get + { + return _relativeBasePath; + } + + set + { + _relative = true; + _relativeBasePath = value; + } + } + #endregion Parameters #region parameter data @@ -84,10 +108,68 @@ public SwitchParameter Relative /// private string[] _paths; + private PSDriveInfo _relativeDrive; + private string _relativeBasePath; + #endregion parameter data #region Command code + /// + /// Finds the path and drive that should be used for relative path resolution + /// represents. + /// + protected override void BeginProcessing() + { + if (_relative) + { + if (!string.IsNullOrEmpty(RelativeBasePath)) + { + try + { + _relativeBasePath = SessionState.Internal.Globber.GetProviderPath(RelativeBasePath, CmdletProviderContext, out _, out _relativeDrive); + } + catch (ProviderNotFoundException providerNotFound) + { + ThrowTerminatingError( + new ErrorRecord( + providerNotFound.ErrorRecord, + providerNotFound)); + } + catch (DriveNotFoundException driveNotFound) + { + ThrowTerminatingError( + new ErrorRecord( + driveNotFound.ErrorRecord, + driveNotFound)); + } + catch (ProviderInvocationException providerInvocation) + { + ThrowTerminatingError( + new ErrorRecord( + providerInvocation.ErrorRecord, + providerInvocation)); + } + catch (NotSupportedException notSupported) + { + ThrowTerminatingError( + new ErrorRecord(notSupported, "ProviderIsNotNavigationCmdletProvider", ErrorCategory.InvalidArgument, RelativeBasePath)); + } + catch (InvalidOperationException invalidOperation) + { + ThrowTerminatingError( + new ErrorRecord(invalidOperation, "InvalidHomeLocation", ErrorCategory.InvalidOperation, RelativeBasePath)); + } + + return; + } + + _relativeDrive = SessionState.Path.CurrentLocation.Drive; + _relativeBasePath = SessionState.Path.CurrentLocation.ProviderPath; + return; + } + } + /// /// Resolves the path containing glob characters to the PowerShell paths that it /// represents. @@ -109,10 +191,9 @@ protected override void ProcessRecord() { // When result path and base path is on different PSDrive // (../)*path should not go beyond the root of base path - if (currentPath.Drive != SessionState.Path.CurrentLocation.Drive && - SessionState.Path.CurrentLocation.Drive != null && - !currentPath.ProviderPath.StartsWith( - SessionState.Path.CurrentLocation.Drive.Root, StringComparison.OrdinalIgnoreCase)) + if (currentPath.Drive != _relativeDrive && + _relativeDrive != null && + !currentPath.ProviderPath.StartsWith(_relativeDrive.Root, StringComparison.OrdinalIgnoreCase)) { WriteObject(currentPath.Path, enumerateCollection: false); continue; @@ -127,8 +208,7 @@ protected override void ProcessRecord() } baseCache = basePath; - string adjustedPath = SessionState.Path.NormalizeRelativePath(currentPath.Path, - SessionState.Path.CurrentLocation.ProviderPath); + string adjustedPath = SessionState.Path.NormalizeRelativePath(currentPath.Path, _relativeBasePath); // Do not insert './' if result path is not relative if (!adjustedPath.StartsWith( diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Resolve-Path.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Resolve-Path.Tests.ps1 index 87195c26352..91a16eb507b 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Resolve-Path.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Resolve-Path.Tests.ps1 @@ -48,4 +48,8 @@ Describe "Resolve-Path returns proper path" -Tag "CI" { Pop-Location } } + It 'Resolve-Path should support user specified base paths' { + $Expected = Join-Path -Path .\ -ChildPath fakeroot + Resolve-Path -Path $fakeRoot -RelativeBasePath $testRoot | Should -BeExactly $Expected + } } From 25651ef6e9fdeab052bb6db191a1f473984e267f Mon Sep 17 00:00:00 2001 From: MartinGC94 <42123497+MartinGC94@users.noreply.github.com> Date: Thu, 23 Mar 2023 22:40:50 +0100 Subject: [PATCH 458/779] Fix a crash in the type inference code (#19400) --- .../engine/parser/TypeInferenceVisitor.cs | 24 +++++++++++++------ .../engine/Api/TypeInference.Tests.ps1 | 8 +++++++ 2 files changed, 25 insertions(+), 7 deletions(-) diff --git a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs index 5f2288e0106..afa33d0e918 100644 --- a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs +++ b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs @@ -739,19 +739,28 @@ object ICustomAstVisitor.VisitSubExpression(SubExpressionAst subExpressionAst) object ICustomAstVisitor.VisitErrorStatement(ErrorStatementAst errorStatementAst) { var inferredTypes = new List(); - foreach (var ast in errorStatementAst.Conditions) + if (errorStatementAst.Conditions is not null) { - inferredTypes.AddRange(InferTypes(ast)); + foreach (var ast in errorStatementAst.Conditions) + { + inferredTypes.AddRange(InferTypes(ast)); + } } - foreach (var ast in errorStatementAst.Bodies) + if (errorStatementAst.Bodies is not null) { - inferredTypes.AddRange(InferTypes(ast)); + foreach (var ast in errorStatementAst.Bodies) + { + inferredTypes.AddRange(InferTypes(ast)); + } } - foreach (var ast in errorStatementAst.NestedAst) + if (errorStatementAst.NestedAst is not null) { - inferredTypes.AddRange(InferTypes(ast)); + foreach (var ast in errorStatementAst.NestedAst) + { + inferredTypes.AddRange(InferTypes(ast)); + } } return inferredTypes; @@ -1944,7 +1953,8 @@ private void InferTypeFrom(VariableExpressionAst variableExpressionAst, List Date: Fri, 24 Mar 2023 05:11:40 +0100 Subject: [PATCH 459/779] Remove GetResponseObject (#19380) --- .../InvokeWebRequestCommand.CoreClr.cs | 2 +- .../WebResponseObjectFactory.CoreClr.cs | 19 ------------------- 2 files changed, 1 insertion(+), 20 deletions(-) delete mode 100644 src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseObjectFactory.CoreClr.cs diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/InvokeWebRequestCommand.CoreClr.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/InvokeWebRequestCommand.CoreClr.cs index 94245548e80..bde0847adc5 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/InvokeWebRequestCommand.CoreClr.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/InvokeWebRequestCommand.CoreClr.cs @@ -43,7 +43,7 @@ internal override void ProcessResponse(HttpResponseMessage response) StreamHelper.ChunkSize, this, response.Content.Headers.ContentLength.GetValueOrDefault()); - WebResponseObject ro = WebResponseObjectFactory.GetResponseObject(response, responseStream, this.Context); + WebResponseObject ro = WebResponseHelper.IsText(response) ? new BasicHtmlWebResponseObject(response, responseStream) : new WebResponseObject(response, responseStream); ro.RelationLink = _relationLink; WriteObject(ro); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseObjectFactory.CoreClr.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseObjectFactory.CoreClr.cs deleted file mode 100644 index 4c8f1c40321..00000000000 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseObjectFactory.CoreClr.cs +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System.IO; -using System.Management.Automation; -using System.Net.Http; - -namespace Microsoft.PowerShell.Commands -{ - internal static class WebResponseObjectFactory - { - internal static WebResponseObject GetResponseObject(HttpResponseMessage response, Stream responseStream, ExecutionContext executionContext) - { - WebResponseObject output = WebResponseHelper.IsText(response) ? new BasicHtmlWebResponseObject(response, responseStream) : new WebResponseObject(response, responseStream); - - return output; - } - } -} From 2553a56db2cc446eafe7c27fb3f48c5022ad7714 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Mon, 27 Mar 2023 11:05:04 -0700 Subject: [PATCH 460/779] Add `-Environment` parameter to `Start-Process` (#19374) * Add `-Environment` parameter to `Start-Process` * address codefactor * fix test for Windows * handle case where value is $null to remove env var * change variables to make it more clear what the test is doing --- .../commands/management/Process.cs | 48 +++++++++++++++---- .../Start-Process.Tests.ps1 | 31 +++++++++++- 2 files changed, 70 insertions(+), 9 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs index b731ce905cc..047aada0edd 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs @@ -1823,6 +1823,26 @@ public SwitchParameter UseNewEnvironment private SwitchParameter _UseNewEnvironment; + /// + /// Gets or sets the environment variables for the process. + /// + [Parameter] + public Hashtable Environment + { + get + { + return _environment; + } + + set + { + _environment = value; + _isDefaultSetParameterSpecified = true; + } + } + + private Hashtable _environment; + #endregion #region overrides @@ -1929,8 +1949,13 @@ protected override void BeginProcessing() if (_UseNewEnvironment) { startInfo.EnvironmentVariables.Clear(); - LoadEnvironmentVariable(startInfo, Environment.GetEnvironmentVariables(EnvironmentVariableTarget.Machine)); - LoadEnvironmentVariable(startInfo, Environment.GetEnvironmentVariables(EnvironmentVariableTarget.User)); + LoadEnvironmentVariable(startInfo, System.Environment.GetEnvironmentVariables(EnvironmentVariableTarget.Machine)); + LoadEnvironmentVariable(startInfo, System.Environment.GetEnvironmentVariables(EnvironmentVariableTarget.User)); + } + + if (_environment != null) + { + LoadEnvironmentVariable(startInfo, _environment); } startInfo.WindowStyle = _windowstyle; @@ -2176,13 +2201,20 @@ private static void LoadEnvironmentVariable(ProcessStartInfo startinfo, IDiction processEnvironment.Remove(entry.Key.ToString()); } - if (entry.Key.ToString().Equals("PATH")) + if (entry.Value != null) { - processEnvironment.Add(entry.Key.ToString(), Environment.GetEnvironmentVariable(entry.Key.ToString(), EnvironmentVariableTarget.Machine) + ";" + Environment.GetEnvironmentVariable(entry.Key.ToString(), EnvironmentVariableTarget.User)); - } - else - { - processEnvironment.Add(entry.Key.ToString(), entry.Value.ToString()); + if (entry.Key.ToString().Equals("PATH")) + { +#if UNIX + processEnvironment.Add(entry.Key.ToString(), entry.Value.ToString()); +#else + processEnvironment.Add(entry.Key.ToString(), entry.Value.ToString() + Path.PathSeparator + System.Environment.GetEnvironmentVariable(entry.Key.ToString(), EnvironmentVariableTarget.Machine) + Path.PathSeparator + System.Environment.GetEnvironmentVariable(entry.Key.ToString(), EnvironmentVariableTarget.User)); +#endif + } + else + { + processEnvironment.Add(entry.Key.ToString(), entry.Value.ToString()); + } } } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Start-Process.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Start-Process.Tests.ps1 index db89dd681fc..30bc1e676dc 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Start-Process.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Start-Process.Tests.ps1 @@ -181,7 +181,7 @@ Describe "Start-Process tests requiring admin" -Tags "Feature","RequireAdminOnWi } } -Describe "Start-Process" -Tags "Feature" { +Describe "Environment Tests" -Tags "Feature" { It "UseNewEnvironment parameter should reset environment variables for child process" { @@ -206,4 +206,33 @@ Describe "Start-Process" -Tags "Feature" { $env:TestEnvVariable = $null } } + + It '-Environment adds or replaces environment variables to child process' { + $outputfile = Join-Path -Path $TestDrive -ChildPath output.txt + Start-Process pwsh -ArgumentList '-NoProfile','-Nologo','-OutputFormat xml','-Command get-childitem env:' -Wait -Environment @{ a = 1; B = 'hello'; TERM = 'dumb'; PATH = 'mine' } -RedirectStandardOutput $outputfile + $out = Import-Clixml $outputfile + ($out | Where-Object { $_.Name -eq 'a' }).Value | Should -Be 1 + ($out | Where-Object { $_.Name -eq 'B' }).Value | Should -BeExactly 'hello' + ($out | Where-Object { $_.Name -eq 'TERM' }).Value | Should -BeExactly 'dumb' + $pathSeparator = [System.IO.Path]::PathSeparator + if ($IsWindows) { + ($out | Where-Object { $_.Name -eq 'PATH' }).Value | Should -BeLike "*${pathSeparator}mine${pathSeparator}*" + } else { + ($out | Where-Object { $_.Name -eq 'PATH' }).Value | Should -BeLike "*${pathSeparator}mine" + } + } + + It '-Environment can remove an environment variable from child process' { + try { + $env:existing = 1 # set a variable that we will remove + $env:nonexisting = $null # validate that removing a non-existing variable is a no-op + $outputfile = Join-Path -Path $TestDrive -ChildPath output.txt + Start-Process pwsh -ArgumentList '-NoProfile','-Nologo','-OutputFormat xml','-Command get-childitem env:' -Wait -Environment @{ existing = $null; nonexisting = $null } -RedirectStandardOutput $outputfile + $out = Import-Clixml $outputfile + $out | Where-Object { $_.Name -eq 'existing' } | Should -BeNullOrEmpty + $out | Where-Object { $_.Name -eq 'nonexisting' } | Should -BeNullOrEmpty + } finally { + $env:existing = $null + } + } } From 37c6166669360da54762bb9954fa9b0a294f4128 Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Mon, 27 Mar 2023 12:07:42 -0700 Subject: [PATCH 461/779] Add PoolNames variable group to compliance pipeline (#19408) --- tools/releaseBuild/azureDevOps/compliance.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/tools/releaseBuild/azureDevOps/compliance.yml b/tools/releaseBuild/azureDevOps/compliance.yml index 19935237216..43ef005402b 100644 --- a/tools/releaseBuild/azureDevOps/compliance.yml +++ b/tools/releaseBuild/azureDevOps/compliance.yml @@ -30,6 +30,7 @@ variables: - group: 'Azure Blob variable group' # Defines the variables CgPat, CgOrganization, and CgProject - group: 'ComponentGovernance' + - group: 'PoolNames' stages: - stage: compliance From 7ee22063c565541c2aa2e04f908567f1187f3f91 Mon Sep 17 00:00:00 2001 From: "James Truher [MSFT]" Date: Mon, 27 Mar 2023 14:54:53 -0700 Subject: [PATCH 462/779] Improve package management acceptance tests by not going to the gallery (#19412) --- .../PackageManagement.Tests.ps1 | 72 ++++++++++-------- .../assets/PowerShell.TestPackage.3.2.1.nupkg | Bin 0 -> 3225 bytes 2 files changed, 41 insertions(+), 31 deletions(-) create mode 100644 test/powershell/Modules/PackageManagement/assets/PowerShell.TestPackage.3.2.1.nupkg diff --git a/test/powershell/Modules/PackageManagement/PackageManagement.Tests.ps1 b/test/powershell/Modules/PackageManagement/PackageManagement.Tests.ps1 index 3fea57db36f..bd4d0218f5d 100644 --- a/test/powershell/Modules/PackageManagement/PackageManagement.Tests.ps1 +++ b/test/powershell/Modules/PackageManagement/PackageManagement.Tests.ps1 @@ -13,34 +13,36 @@ # # ------------------ PackageManagement Test ----------------------------------- -$gallery = "https://www.powershellgallery.com/api/v2" -$source = 'OneGetTestSource' - Describe "PackageManagement Acceptance Test" -Tags "Feature" { - BeforeAll{ - Register-PackageSource -Name Nugettest -provider NuGet -Location https://www.nuget.org/api/v2 -Force + BeforeAll { + # the package name for testing + $packageName = "PowerShell.TestPackage" + + # register the asset directory + $localSourceName = [Guid]::NewGuid().ToString("n") + $localSourceLocation = Join-Path $PSScriptRoot assets + Register-PackageSource -Name $localSourceName -provider NuGet -Location $localSourceLocation -Force -Trusted + + # register the gallery location + $galleryLocation = "https://www.powershellgallery.com/api/v2" + $gallerySourceName = [Guid]::newGuid().ToString("n") + Register-PackageSource -Name $gallerySourceName -Location $galleryLocation -ProviderName 'PowerShellGet' -Trusted -ErrorAction SilentlyContinue + + $SavedProgressPreference = $ProgressPreference + $ProgressPreference = "SilentlyContinue" + } - $packageSource = Get-PackageSource -Location $gallery -ErrorAction SilentlyContinue - if ($packageSource) { - $source = $packageSource.Name - Set-PackageSource -Name $source -Trusted - } else { - Register-PackageSource -Name $source -Location $gallery -ProviderName 'PowerShellGet' -Trusted -ErrorAction SilentlyContinue + AfterAll { + $ProgressPreference = $SavedProgressPreference + Unregister-PackageSource -Source $localSourceName -ErrorAction Ignore + Unregister-PackageSource -Name $gallerySourceName -ErrorAction Ignore + Uninstall-Module NanoServerPackage -ErrorAction Ignore -WarningAction SilentlyContinue } - $SavedProgressPreference = $ProgressPreference - $ProgressPreference = "SilentlyContinue" - } - AfterAll { - $ProgressPreference = $SavedProgressPreference - } It "get-packageprovider" { - $gpp = Get-PackageProvider - $gpp.Name | Should -Contain 'NuGet' - $gpp.Name | Should -Contain 'PowerShellGet' } @@ -50,32 +52,40 @@ Describe "PackageManagement Acceptance Test" -Tags "Feature" { } It "install-packageprovider, Expect succeed" { - $ipp = (Install-PackageProvider -Name NanoServerPackage -Force -Source $source -Scope CurrentUser).name + Set-ItResult -Pending -Because "local test package provider not installable" + $ippArgs = @{ + Name = "NanoServerPackage" + Force = $true + Source = $galleryLocation + Scope = "CurrentUser" + WarningAction = "SilentlyContinue" + } + $ipp = (Install-PackageProvider @ippArgs).name $ipp | Should -Contain "NanoServerPackage" } It "Find-package" { - $f = Find-Package -ProviderName NuGet -Name jquery -Source Nugettest - $f.Name | Should -Contain "jquery" + $f = Find-Package -ProviderName NuGet -Name $packageName -Source $localSourceName + $f.Name | Should -Contain "$packageName" } It "Install-package" { - $i = Install-Package -ProviderName NuGet -Name jquery -Force -Source Nugettest -Scope CurrentUser - $i.Name | Should -Contain "jquery" + $i = Install-Package -ProviderName NuGet -Name $packageName -Force -Source $localSourceName -Scope CurrentUser + $i.Name | Should -Contain "$packageName" } It "Get-package" { - $g = Get-Package -ProviderName NuGet -Name jquery - $g.Name | Should -Contain "jquery" + $g = Get-Package -ProviderName NuGet -Name $packageName + $g.Name | Should -Contain "$packageName" } It "save-package" { - $s = Save-Package -ProviderName NuGet -Name jquery -Path $TestDrive -Force -Source Nugettest - $s.Name | Should -Contain "jquery" + $s = Save-Package -ProviderName NuGet -Name $packageName -Path $TestDrive -Force -Source $localSourceName + $s.Name | Should -Contain "$packageName" } It "uninstall-package" { - $u = Uninstall-Package -ProviderName NuGet -Name jquery - $u.Name | Should -Contain "jquery" + $u = Uninstall-Package -ProviderName NuGet -Name $packageName + $u.Name | Should -Contain "$packageName" } } diff --git a/test/powershell/Modules/PackageManagement/assets/PowerShell.TestPackage.3.2.1.nupkg b/test/powershell/Modules/PackageManagement/assets/PowerShell.TestPackage.3.2.1.nupkg new file mode 100644 index 0000000000000000000000000000000000000000..bc3a6d9b094ff479b0acef2b1e54415e559c339d GIT binary patch literal 3225 zcmb_ecU03$8Vy}Rib(Y-hy|1qLMMWvB1ixUH7cTzgh&ku5K10B5I{sB5E1DmAWe9R zG=b1jKp@ha5D^fh3ZW=%;}OPy%i-QxuE{WeVYXO~9FDJpd^KrOxNN-$ey%!- zH3Sp7h?IU#-7+t?w=i&xG zlPCCL*gB$my5C|Hadqhsqa@*~u25Qp@S*PLDoD&Gmf(MT)2#f8r@9?E)VVO?EK5Z{8>^YVoiy zf-Gr%^FcdgD4Ihh(d#8?re&Q~Ys^7VA_RRVOT*%n$ROEiC2?5uHY=LChVI*888>G?N zV*DHQ%R99iO-q+5UQ{?waxMEUZ?938H)}T&V}?s5E#e}rLF(#}1Lr78-yN)*X26S5T^VRtg0&M73oM$Uf zEP`j7v|gIb2yspT@I+$L_zSy#eqtg)TR6TyxP(3NiFNktk)xGJsjkAbWpN=moBl0F z=R(OoWWgKs;DHz1@016Mw|81An%?n-t&zui4DqLHi8c#xXV)vAT8?~@A5rMB)h@c% zM|$^`mPdOPr|^YPwR}8_|EA{ms1OHmuA=tF=_bMLnFkD3XZQj}@eZVlC;REa8Lt1B3Mzb3nOLKSSQ$}Z1&UcK=^0)cTY5GNvBd!EJ=%Llf z;bE&9XX>QBdD1Ooq@B^vTy4_4^eh4$pb33Da;8>$KEXvjhe;9yGS-MW^v%mws2Elh*_8zF+K*6IQi=TC3aA(=b(CyRA+R@7HCm0onI-XfBOj zA_}E5kh*Yu<8w=e+p;`k1F)&~x*)%C-81?$dAFPba3Qa5<_tTGXcS;Kmw@I_k}I(c zwd&8edeXUNtuU%Cd}BBGMjxx~t12mMtTTIYMSl0Kq`AsKJMq8|YVUHwt*|9;Yab*u z?9N7i&2?uPo2Yptrvs}ypSdwZoi*6|zB`BE>B|Bo7|J$VznEPTK{$MgsPI#FqptMk z3q9ED+Ptp;Gi0P~y!rwe1eYUL3W9G~uZ|gA47K&$P4&HBn((oTS{(`P0P1UDb8Xh} zXQT6)zQjg#J9A~j&Iv4{`jUMVS-uNapv%Hy%P? zH=BIipFjWly}5d!L9DrwXY@njb<;r@iMz$-Yx`%FYK&whsdnT2Z`p%gH99~9<#T{` z4uj))o#N3MEN>{aCKQzMIR@#A^tjE^APot-g&OTXzrWWKh1j!uBvX?4|&ZcCrs=K zx(lw>#kTG^3teLn&}foJ4>Ck`Rp8AP=*P%8+R3V(aYdiUcKsRa@WHde={)Bs^9mMO z?f?sbBG2!o5K7=&eE$A1={qSbGkmi$bc@V_cQ2x%R1IwO)AdfXx!;-cK5WGJri9al zb(5M_a$<-F++A&24+)qNbHmq_pRO)gyx8RtlQ^lm@vuHf40+(xsWq<#+de@9Tdu7I zvGy6frEHT?&1mS$H}C4Z$y$14R=zyV(h6-!Lio*--8PhpEbU~?)QB#hxU{P&HQHs$ z3!MI+9FijT;)*Dd3pPvU?r)CmDg|3LJwjnsR=YD|FfkRoeMcSiah7Qq5tuEa|8S77 z@I_y!Z`VHFym7y`{hEYY?Eah?ZQ^J3x;#;C*2{c;JDBRllsCX_U5pzJ<%YAh#A8vO zcYwZV*A&tPwgjLlx#&$l!vzy66L9gM&aQ0a2#9_iSa-wU_CHc zln2gg} zN8fR4u}8D)#x>1cino*z{);1}&u=+F{9+d;cp^0)V$gNByU)~u6O#Oc*V>chBOS#A zK#hhd?^~vyyuHQ8rs6Gca>+T!Ve{(aVfH)bQSw8lU`DM4BTmjA9zhx|=^o^~@W8Q| zKzcwo+%L(vra$w(kkqfri=Ir=;BShotnk&a~CI{tMs;1uFx-ndI)QD&Gpj5t)(Z}FyuW#+@^Z`Fwl2CmIITg-kMG!Ty z8Y&0b1`uPn(<|xmN?lhj_E%$-8tB!o$;Qq~I3RTZiY@F}yYoiBc7 zZ-sd!2*t`Suo#P6OGf)w8B|8c^F)dcGS)Ls%zFdlv>-F8#>43=koLe5^Sy)rx?~ns zA-4Z)c$qi-&yN!FBmA5FH8uKq;ja$w&t(7rCB%T4HUHJ`{RH(luIDePAZGIYZx8en w9y4`+E#JTJI1l`7G5-qiYwrIAz|Exb|6U2EMjV_!w%}kkGLyVz?jOB>0Jg-hYybcN literal 0 HcmV?d00001 From 5a225877927d3fb15a9bed4cc8344d6276789f13 Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Mon, 27 Mar 2023 17:36:41 -0700 Subject: [PATCH 463/779] Skip VT100 tests on Windows Server 2012R2 as console does not support it (#19413) --- .../Scripting/SuppressAnsiEscapeSequence.Tests.ps1 | 7 +++++++ .../Microsoft.PowerShell.Utility/Get-Error.Tests.ps1 | 5 +++++ .../powershell/engine/Formatting/OutputRendering.Tests.ps1 | 5 +++-- 3 files changed, 15 insertions(+), 2 deletions(-) diff --git a/test/powershell/Language/Scripting/SuppressAnsiEscapeSequence.Tests.ps1 b/test/powershell/Language/Scripting/SuppressAnsiEscapeSequence.Tests.ps1 index 30a82309a70..0530aea93ee 100644 --- a/test/powershell/Language/Scripting/SuppressAnsiEscapeSequence.Tests.ps1 +++ b/test/powershell/Language/Scripting/SuppressAnsiEscapeSequence.Tests.ps1 @@ -3,12 +3,19 @@ Describe '$env:__SuppressAnsiEscapeSequences tests' -Tag CI { BeforeAll { + $originalDefaultParameterValues = $PSDefaultParameterValues.Clone() + + if (-not $host.ui.SupportsVirtualTerminal) { + $global:PSDefaultParameterValues["it:skip"] = $true + } + $originalSuppressPref = $env:__SuppressAnsiEscapeSequences $originalRendering = $PSStyle.OutputRendering $PSStyle.OutputRendering = 'Ansi' } AfterAll { + $global:PSDefaultParameterValues = $originalDefaultParameterValues $env:__SuppressAnsiEscapeSequences = $originalSuppressPref $PSStyle.OutputRendering = $originalRendering } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-Error.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-Error.Tests.ps1 index 1d89bf6c1fa..4f86ee561cb 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-Error.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-Error.Tests.ps1 @@ -119,6 +119,11 @@ Describe 'Get-Error tests' -Tag CI { } It 'Get-Error uses Error color for Message and PositionMessage members' { + + if (-not $host.ui.SupportsVirtualTerminal) { + Set-ItResult -Skipped -Because 'Windows Server 2012 R2 does not support VT100 escape sequences' + } + $suppressVT = $false if (Test-Path env:/__SuppressAnsiEscapeSequences) { $suppressVT = $true diff --git a/test/powershell/engine/Formatting/OutputRendering.Tests.ps1 b/test/powershell/engine/Formatting/OutputRendering.Tests.ps1 index 18adcf6a8d8..dda4bdbd1eb 100644 --- a/test/powershell/engine/Formatting/OutputRendering.Tests.ps1 +++ b/test/powershell/engine/Formatting/OutputRendering.Tests.ps1 @@ -5,8 +5,9 @@ Describe 'OutputRendering tests' -Tag 'CI' { BeforeAll { $originalDefaultParameterValues = $PSDefaultParameterValues.Clone() # Console host does not support VT100 escape sequences on Windows 2012R2 or earlier - if ($IsWindows -and [System.Environment]::OSVersion.Version -le [version]::new(6, 3)) { - $PSDefaultParameterValues["it:skip"] = $true + + if (-not $host.ui.SupportsVirtualTerminal) { + $global:PSDefaultParameterValues["it:skip"] = $true } } From 51f55f716ea29f94ba7373e2f619cb23569c8c5d Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Wed, 29 Mar 2023 11:27:04 -0700 Subject: [PATCH 464/779] Update the `ICommandPredictor` interface to reduce boilerplate code from predictor implementation (#19414) --- .../FeedbackSubsystem/IFeedbackProvider.cs | 164 ------------------ .../PredictionSubsystem/CommandPrediction.cs | 1 - .../PredictionSubsystem/ICommandPredictor.cs | 16 +- .../engine/hostifaces/Connection.cs | 4 +- .../engine/hostifaces/LocalConnection.cs | 2 +- test/xUnit/csharp/test_Subsystem.cs | 10 -- 6 files changed, 14 insertions(+), 183 deletions(-) diff --git a/src/System.Management.Automation/engine/Subsystem/FeedbackSubsystem/IFeedbackProvider.cs b/src/System.Management.Automation/engine/Subsystem/FeedbackSubsystem/IFeedbackProvider.cs index 0e126f9f27a..4a680f30db6 100644 --- a/src/System.Management.Automation/engine/Subsystem/FeedbackSubsystem/IFeedbackProvider.cs +++ b/src/System.Management.Automation/engine/Subsystem/FeedbackSubsystem/IFeedbackProvider.cs @@ -188,168 +188,4 @@ internal GeneralCommandErrorFeedback() return null; } } - - internal sealed class UnixCommandNotFound : IFeedbackProvider, ICommandPredictor - { - private readonly Guid _guid; - private List? _candidates; - - internal UnixCommandNotFound() - { - _guid = new Guid("47013747-CB9D-4EBC-9F02-F32B8AB19D48"); - } - - Dictionary? ISubsystem.FunctionsToDefine => null; - - public Guid Id => _guid; - - public string Name => "cmd-not-found"; - - public string Description => "The built-in feedback/prediction source for the Unix command utility."; - - #region IFeedbackProvider - - private static string? GetUtilityPath() - { - string cmd_not_found = "/usr/lib/command-not-found"; - bool exist = IsFileExecutable(cmd_not_found); - - if (!exist) - { - cmd_not_found = "/usr/share/command-not-found/command-not-found"; - exist = IsFileExecutable(cmd_not_found); - } - - return exist ? cmd_not_found : null; - - static bool IsFileExecutable(string path) - { - var file = new FileInfo(path); - return file.Exists && file.UnixFileMode.HasFlag(UnixFileMode.OtherExecute); - } - } - - public FeedbackItem? GetFeedback(string commandLine, ErrorRecord lastError, CancellationToken token) - { - if (Platform.IsWindows || lastError.FullyQualifiedErrorId != "CommandNotFoundException") - { - return null; - } - - var target = (string)lastError.TargetObject; - if (target is null) - { - return null; - } - - if (target.EndsWith(".ps1", StringComparison.OrdinalIgnoreCase)) - { - return null; - } - - string? cmd_not_found = GetUtilityPath(); - if (cmd_not_found is not null) - { - var startInfo = new ProcessStartInfo(cmd_not_found); - startInfo.ArgumentList.Add(target); - startInfo.RedirectStandardError = true; - startInfo.RedirectStandardOutput = true; - - using var process = Process.Start(startInfo); - if (process is not null) - { - string? header = null; - List? actions = null; - - while (true) - { - string? line = process.StandardError.ReadLine(); - if (line is null) - { - break; - } - - if (line == string.Empty) - { - continue; - } - - if (line.StartsWith("sudo ", StringComparison.Ordinal)) - { - actions ??= new List(); - actions.Add(line.TrimEnd()); - } - else if (actions is null) - { - header = line; - } - } - - if (actions is not null && header is not null) - { - _candidates = actions; - - var footer = process.StandardOutput.ReadToEnd().Trim(); - return string.IsNullOrEmpty(footer) - ? new FeedbackItem(header, actions) - : new FeedbackItem(header, actions, footer, FeedbackDisplayLayout.Portrait); - } - } - } - - return null; - } - - #endregion - - #region ICommandPredictor - - public bool CanAcceptFeedback(PredictionClient client, PredictorFeedbackKind feedback) - { - return feedback switch - { - PredictorFeedbackKind.CommandLineAccepted => true, - _ => false, - }; - } - - public SuggestionPackage GetSuggestion(PredictionClient client, PredictionContext context, CancellationToken cancellationToken) - { - if (_candidates is not null) - { - string input = context.InputAst.Extent.Text; - List? result = null; - - foreach (string c in _candidates) - { - if (c.StartsWith(input, StringComparison.OrdinalIgnoreCase)) - { - result ??= new List(_candidates.Count); - result.Add(new PredictiveSuggestion(c)); - } - } - - if (result is not null) - { - return new SuggestionPackage(result); - } - } - - return default; - } - - public void OnCommandLineAccepted(PredictionClient client, IReadOnlyList history) - { - // Reset the candidate state. - _candidates = null; - } - - public void OnSuggestionDisplayed(PredictionClient client, uint session, int countOrIndex) { } - - public void OnSuggestionAccepted(PredictionClient client, uint session, string acceptedSuggestion) { } - - public void OnCommandLineExecuted(PredictionClient client, string commandLine, bool success) { } - - #endregion; - } } diff --git a/src/System.Management.Automation/engine/Subsystem/PredictionSubsystem/CommandPrediction.cs b/src/System.Management.Automation/engine/Subsystem/PredictionSubsystem/CommandPrediction.cs index 3e06d046481..edb46960612 100644 --- a/src/System.Management.Automation/engine/Subsystem/PredictionSubsystem/CommandPrediction.cs +++ b/src/System.Management.Automation/engine/Subsystem/PredictionSubsystem/CommandPrediction.cs @@ -5,7 +5,6 @@ using System; using System.Collections.Generic; -using System.Management.Automation.Internal; using System.Management.Automation.Language; using System.Threading; using System.Threading.Tasks; diff --git a/src/System.Management.Automation/engine/Subsystem/PredictionSubsystem/ICommandPredictor.cs b/src/System.Management.Automation/engine/Subsystem/PredictionSubsystem/ICommandPredictor.cs index 1c632c541c4..275dc1733b6 100644 --- a/src/System.Management.Automation/engine/Subsystem/PredictionSubsystem/ICommandPredictor.cs +++ b/src/System.Management.Automation/engine/Subsystem/PredictionSubsystem/ICommandPredictor.cs @@ -36,7 +36,7 @@ public interface ICommandPredictor : ISubsystem /// Represents the client that initiates the call. /// A specific type of feedback. /// True or false, to indicate whether the specific feedback is accepted. - bool CanAcceptFeedback(PredictionClient client, PredictorFeedbackKind feedback); + bool CanAcceptFeedback(PredictionClient client, PredictorFeedbackKind feedback) => false; /// /// One or more suggestions provided by the predictor were displayed to the user. @@ -47,7 +47,7 @@ public interface ICommandPredictor : ISubsystem /// When the value is greater than 0, it's the number of displayed suggestions from the list returned in , starting from the index 0. /// When the value is less than or equal to 0, it means a single suggestion from the list got displayed, and the index is the absolute value. /// - void OnSuggestionDisplayed(PredictionClient client, uint session, int countOrIndex); + void OnSuggestionDisplayed(PredictionClient client, uint session, int countOrIndex) { } /// /// The suggestion provided by the predictor was accepted. @@ -55,7 +55,7 @@ public interface ICommandPredictor : ISubsystem /// Represents the client that initiates the call. /// Represents the mini-session where the accepted suggestion came from. /// The accepted suggestion text. - void OnSuggestionAccepted(PredictionClient client, uint session, string acceptedSuggestion); + void OnSuggestionAccepted(PredictionClient client, uint session, string acceptedSuggestion) { } /// /// A command line was accepted to execute. @@ -63,7 +63,7 @@ public interface ICommandPredictor : ISubsystem /// /// Represents the client that initiates the call. /// History command lines provided as references for prediction. - void OnCommandLineAccepted(PredictionClient client, IReadOnlyList history); + void OnCommandLineAccepted(PredictionClient client, IReadOnlyList history) { } /// /// A command line was done execution. @@ -71,7 +71,7 @@ public interface ICommandPredictor : ISubsystem /// Represents the client that initiates the call. /// The last accepted command line. /// Shows whether the execution was successful. - void OnCommandLineExecuted(PredictionClient client, string commandLine, bool success); + void OnCommandLineExecuted(PredictionClient client, string commandLine, bool success) { } } /// @@ -131,6 +131,12 @@ public sealed class PredictionClient /// public PredictionClientKind Kind { get; } + /// + /// Gets the current location of the default session. + /// It returns null if there is no default Runspace or if the default is a remote Runspace. + /// + public PathInfo? CurrentLocation { get; set; } + /// /// Initializes a new instance of the class. /// diff --git a/src/System.Management.Automation/engine/hostifaces/Connection.cs b/src/System.Management.Automation/engine/hostifaces/Connection.cs index a637655aeeb..50c7e49f92d 100644 --- a/src/System.Management.Automation/engine/hostifaces/Connection.cs +++ b/src/System.Management.Automation/engine/hostifaces/Connection.cs @@ -703,7 +703,7 @@ public Guid InstanceId /// /// Runspace is not opened. /// - internal System.Management.Automation.ExecutionContext ExecutionContext + internal ExecutionContext ExecutionContext { get { @@ -1577,7 +1577,7 @@ protected virtual void Dispose(bool disposing) /// /// Gets the execution context. /// - internal abstract System.Management.Automation.ExecutionContext GetExecutionContext + internal abstract ExecutionContext GetExecutionContext { get; } diff --git a/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs b/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs index 64c9e19516f..b88a466623d 100644 --- a/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs +++ b/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs @@ -237,7 +237,7 @@ protected override Pipeline CoreCreatePipeline(string command, bool addToHistory /// /// Gets the execution context. /// - internal override System.Management.Automation.ExecutionContext GetExecutionContext + internal override ExecutionContext GetExecutionContext { get { diff --git a/test/xUnit/csharp/test_Subsystem.cs b/test/xUnit/csharp/test_Subsystem.cs index 1318f13139d..2889bab378b 100644 --- a/test/xUnit/csharp/test_Subsystem.cs +++ b/test/xUnit/csharp/test_Subsystem.cs @@ -71,18 +71,8 @@ private MyCompositeSubsystem(Guid id) #region ICommandPredictor - public bool CanAcceptFeedback(PredictionClient client, PredictorFeedbackKind feedback) => false; - public SuggestionPackage GetSuggestion(PredictionClient client, PredictionContext context, CancellationToken cancellationToken) => default; - public void OnCommandLineAccepted(PredictionClient client, IReadOnlyList history) { } - - public void OnSuggestionDisplayed(PredictionClient client, uint session, int countOrIndex) { } - - public void OnSuggestionAccepted(PredictionClient client, uint session, string acceptedSuggestion) { } - - public void OnCommandLineExecuted(PredictionClient client, string commandLine, bool success) { } - #endregion } From 04b93af4ae333013e4fe00013a196268d314cb00 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Mon, 3 Apr 2023 09:36:36 -0700 Subject: [PATCH 465/779] Enable type conversion of `AutomationNull` to `$null` for assignment (#19415) --- .../engine/LanguagePrimitives.cs | 6 ++++++ .../Language/Scripting/Scripting.Followup.Tests.ps1 | 12 ++++++++++++ 2 files changed, 18 insertions(+) diff --git a/src/System.Management.Automation/engine/LanguagePrimitives.cs b/src/System.Management.Automation/engine/LanguagePrimitives.cs index b1c7cab0ace..ac3c1c1a70c 100644 --- a/src/System.Management.Automation/engine/LanguagePrimitives.cs +++ b/src/System.Management.Automation/engine/LanguagePrimitives.cs @@ -4691,6 +4691,12 @@ internal static PSObject SetObjectProperties(object o, IDictionary properties, T } } + // treat AutomationNull.Value as null for consistency + if (propValue == AutomationNull.Value) + { + propValue = null; + } + property.Value = propValue; } else diff --git a/test/powershell/Language/Scripting/Scripting.Followup.Tests.ps1 b/test/powershell/Language/Scripting/Scripting.Followup.Tests.ps1 index 888c43b3578..fff4993ffec 100644 --- a/test/powershell/Language/Scripting/Scripting.Followup.Tests.ps1 +++ b/test/powershell/Language/Scripting/Scripting.Followup.Tests.ps1 @@ -30,6 +30,18 @@ Describe "Scripting.Followup.Tests" -Tags "CI" { $arraylist.Count | Should -Be 0 } + It 'AutomationNull should be same as null for type conversion' { + $result = pwsh -noprofile -command { + class Example { + [string[]]$LogMessage + } + + [Example] @{ LogMessage = [System.Management.Automation.Internal.AutomationNull]::Value } + } + + $result.LogMessage | Should -BeNullOrEmpty + } + ## fix https://github.com/PowerShell/PowerShell/issues/17165 It "([bool] `$var = 42) should return the varaible value" { ([bool]$var = 42).GetType().FullName | Should -Be "System.Boolean" From 7c0fe762a90146f2897b39353c4e8832e5e3d01d Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Mon, 3 Apr 2023 14:56:40 -0700 Subject: [PATCH 466/779] Remove code related to `#requires -pssnapin` (#19320) --- .../engine/CommandDiscovery.cs | 109 ++---------------- .../engine/ExternalScriptInfo.cs | 9 -- .../engine/parser/ast.cs | 8 -- .../engine/parser/tokenizer.cs | 3 - 4 files changed, 8 insertions(+), 121 deletions(-) diff --git a/src/System.Management.Automation/engine/CommandDiscovery.cs b/src/System.Management.Automation/engine/CommandDiscovery.cs index 8efaff4d0a9..d0e2d568ab4 100644 --- a/src/System.Management.Automation/engine/CommandDiscovery.cs +++ b/src/System.Management.Automation/engine/CommandDiscovery.cs @@ -316,92 +316,25 @@ internal static void VerifyRequiredModules(ExternalScriptInfo scriptInfo, Execut } } - private static Collection GetPSSnapinNames(IEnumerable PSSnapins) - { - Collection result = new Collection(); - - foreach (var PSSnapin in PSSnapins) - { - result.Add(BuildPSSnapInDisplayName(PSSnapin)); - } - - return result; - } - private CommandProcessorBase CreateScriptProcessorForSingleShell(ExternalScriptInfo scriptInfo, ExecutionContext context, bool useLocalScope, SessionStateInternal sessionState) { VerifyScriptRequirements(scriptInfo, Context); - IEnumerable requiresPSSnapIns = scriptInfo.RequiresPSSnapIns; - if (requiresPSSnapIns != null && requiresPSSnapIns.Any()) - { - Collection requiresMissingPSSnapIns = null; - VerifyRequiredSnapins(requiresPSSnapIns, context, out requiresMissingPSSnapIns); - if (requiresMissingPSSnapIns != null) - { - ScriptRequiresException scriptRequiresException = - new ScriptRequiresException( - scriptInfo.Name, - requiresMissingPSSnapIns, - "ScriptRequiresMissingPSSnapIns", - true); - throw scriptRequiresException; - } - } - else + if (!string.IsNullOrEmpty(scriptInfo.RequiresApplicationID)) { - // If there were no PSSnapins required but there is a shellID required, then we need - // to error + ScriptRequiresException sre = + new ScriptRequiresException( + scriptInfo.Name, + string.Empty, + string.Empty, + "RequiresShellIDInvalidForSingleShell"); - if (!string.IsNullOrEmpty(scriptInfo.RequiresApplicationID)) - { - ScriptRequiresException sre = - new ScriptRequiresException( - scriptInfo.Name, - string.Empty, - string.Empty, - "RequiresShellIDInvalidForSingleShell"); - - throw sre; - } + throw sre; } return CreateCommandProcessorForScript(scriptInfo, Context, useLocalScope, sessionState); } - private static void VerifyRequiredSnapins(IEnumerable requiresPSSnapIns, ExecutionContext context, out Collection requiresMissingPSSnapIns) - { - requiresMissingPSSnapIns = null; - Dbg.Assert(context.InitialSessionState != null, "PowerShell should be hosted with InitialSessionState"); - - foreach (var requiresPSSnapIn in requiresPSSnapIns) - { - var loadedPSSnapIn = context.InitialSessionState.GetPSSnapIn(requiresPSSnapIn.Name); - if (loadedPSSnapIn is null) - { - requiresMissingPSSnapIns ??= new Collection(); - requiresMissingPSSnapIns.Add(BuildPSSnapInDisplayName(requiresPSSnapIn)); - } - else - { - // the requires PSSnapin is loaded. now check the PSSnapin version - Dbg.Assert(loadedPSSnapIn.Version != null, - string.Format( - CultureInfo.InvariantCulture, - "Version is null for loaded PSSnapin {0}.", loadedPSSnapIn)); - if (requiresPSSnapIn.Version != null) - { - if (!AreInstalledRequiresVersionsCompatible( - requiresPSSnapIn.Version, loadedPSSnapIn.Version)) - { - requiresMissingPSSnapIns ??= new Collection(); - requiresMissingPSSnapIns.Add(BuildPSSnapInDisplayName(requiresPSSnapIn)); - } - } - } - } - } - // This method verifies the following 3 elements of #Requires statement // #Requires -RunAsAdministrator // #Requires -PSVersion @@ -481,32 +414,6 @@ internal static void VerifyElevatedPrivileges(ExternalScriptInfo scriptInfo) } } - /// - /// Used to determine compatibility between the versions in the requires statement and - /// the installed version. The version can be PSSnapin or msh. - /// - /// Versions in the requires statement. - /// Version installed. - /// - /// true if requires and installed's major version match and requires' minor version - /// is smaller than or equal to installed's - /// - /// - /// In PowerShell V2, script requiring PowerShell 1.0 will fail. - /// - private static bool AreInstalledRequiresVersionsCompatible(Version requires, Version installed) - { - return requires.Major == installed.Major && requires.Minor <= installed.Minor; - } - - private static string BuildPSSnapInDisplayName(PSSnapInSpecification PSSnapin) - { - return PSSnapin.Version == null ? - PSSnapin.Name : - StringUtil.Format(DiscoveryExceptions.PSSnapInNameVersion, - PSSnapin.Name, PSSnapin.Version); - } - /// /// Look up a command using a CommandInfo object and return its CommandProcessorBase. /// diff --git a/src/System.Management.Automation/engine/ExternalScriptInfo.cs b/src/System.Management.Automation/engine/ExternalScriptInfo.cs index 31a520d6070..8e0938605ac 100644 --- a/src/System.Management.Automation/engine/ExternalScriptInfo.cs +++ b/src/System.Management.Automation/engine/ExternalScriptInfo.cs @@ -458,15 +458,6 @@ internal uint PSVersionLineNumber get { return 0; } } - internal IEnumerable RequiresPSSnapIns - { - get - { - var data = GetRequiresData(); - return data?.RequiresPSSnapIns; - } - } - /// /// Gets the original contents of the script. /// diff --git a/src/System.Management.Automation/engine/parser/ast.cs b/src/System.Management.Automation/engine/parser/ast.cs index 72906ebb72d..a4138a502ed 100644 --- a/src/System.Management.Automation/engine/parser/ast.cs +++ b/src/System.Management.Automation/engine/parser/ast.cs @@ -753,14 +753,6 @@ public class ScriptRequirements /// public ReadOnlyCollection RequiredModules { get; internal set; } - /// - /// The snapins this script requires, specified like: - /// #requires -PSSnapin Snapin - /// #requires -PSSnapin Snapin -Version 2 - /// If no snapins are required, this property is an empty collection. - /// - public ReadOnlyCollection RequiresPSSnapIns { get; internal set; } - /// /// The assemblies this script requires, specified like: /// #requires -Assembly path\to\foo.dll diff --git a/src/System.Management.Automation/engine/parser/tokenizer.cs b/src/System.Management.Automation/engine/parser/tokenizer.cs index 8b19c7dc385..3d0aa3a18aa 100644 --- a/src/System.Management.Automation/engine/parser/tokenizer.cs +++ b/src/System.Management.Automation/engine/parser/tokenizer.cs @@ -1976,9 +1976,6 @@ internal ScriptRequirements GetScriptRequirements() RequiredPSEditions = requiredEditions != null ? new ReadOnlyCollection(requiredEditions) : ScriptRequirements.EmptyEditionCollection, - RequiresPSSnapIns = requiredSnapins != null - ? new ReadOnlyCollection(requiredSnapins) - : ScriptRequirements.EmptySnapinCollection, RequiredAssemblies = requiredAssemblies != null ? new ReadOnlyCollection(requiredAssemblies) : ScriptRequirements.EmptyAssemblyCollection, From 17fb783736d98608cefe4a505c48901e63ba10f6 Mon Sep 17 00:00:00 2001 From: stevenebutler Date: Tue, 4 Apr 2023 09:08:35 +1000 Subject: [PATCH 467/779] Support CTRL-C when reading data and connection hangs for `Invoke-RestMethod` and `Invoke-WebRequest` (#19330) --- .../BasicHtmlWebResponseObject.Common.cs | 20 +-- .../Common/InvokeRestMethodCommand.Common.cs | 18 +-- .../Common/WebRequestPSCmdlet.Common.cs | 7 +- .../Common/WebResponseObject.Common.cs | 29 +++-- .../InvokeWebRequestCommand.CoreClr.cs | 7 +- .../utility/WebCmdlet/StreamHelper.cs | 65 +++++----- .../WebCmdlets.Tests.ps1 | 117 +++++++++++++++++ .../Modules/WebListener/WebListener.psm1 | 4 + .../Controllers/DelayController.cs | 119 +++++++++++++++++- test/tools/WebListener/Startup.cs | 16 +++ 10 files changed, 334 insertions(+), 68 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/BasicHtmlWebResponseObject.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/BasicHtmlWebResponseObject.Common.cs index 8c15ac96d97..8eaa95c224a 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/BasicHtmlWebResponseObject.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/BasicHtmlWebResponseObject.Common.cs @@ -8,6 +8,7 @@ using System.Net.Http; using System.Text; using System.Text.RegularExpressions; +using System.Threading; namespace Microsoft.PowerShell.Commands { @@ -21,18 +22,20 @@ public class BasicHtmlWebResponseObject : WebResponseObject /// /// Initializes a new instance of the class. /// - /// - public BasicHtmlWebResponseObject(HttpResponseMessage response) : this(response, null) { } + /// The response. + /// Cancellation token. + public BasicHtmlWebResponseObject(HttpResponseMessage response, CancellationToken cancellationToken) : this(response, null, cancellationToken) { } /// /// Initializes a new instance of the class /// with the specified . /// - /// - /// - public BasicHtmlWebResponseObject(HttpResponseMessage response, Stream contentStream) : base(response, contentStream) + /// The response. + /// The content stream associated with the response. + /// Cancellation token. + public BasicHtmlWebResponseObject(HttpResponseMessage response, Stream contentStream, CancellationToken cancellationToken) : base(response, contentStream, cancellationToken) { - InitializeContent(); + InitializeContent(cancellationToken); InitializeRawContent(response); } @@ -141,7 +144,8 @@ public WebCmdletElementCollection Images /// /// Reads the response content from the web response. /// - protected void InitializeContent() + /// The cancellation token. + protected void InitializeContent(CancellationToken cancellationToken) { string contentType = ContentHelper.GetContentType(BaseResponse); if (ContentHelper.IsText(contentType)) @@ -149,7 +153,7 @@ protected void InitializeContent() // Fill the Content buffer string characterSet = WebResponseHelper.GetCharacterSet(BaseResponse); - Content = StreamHelper.DecodeStream(RawContentStream, characterSet, out Encoding encoding); + Content = StreamHelper.DecodeStream(RawContentStream, characterSet, out Encoding encoding, cancellationToken); Encoding = encoding; } else diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs index adfb4f1a610..3fe6e2a91ad 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs @@ -6,6 +6,7 @@ using System.Management.Automation; using System.Net.Http; using System.Text; +using System.Threading; using System.Xml; using Newtonsoft.Json; @@ -74,12 +75,13 @@ public int MaximumFollowRelLink internal override void ProcessResponse(HttpResponseMessage response) { ArgumentNullException.ThrowIfNull(response); + ArgumentNullException.ThrowIfNull(_cancelToken); - Stream baseResponseStream = StreamHelper.GetResponseStream(response); + Stream baseResponseStream = StreamHelper.GetResponseStream(response, _cancelToken.Token); if (ShouldWriteToPipeline) { - using var responseStream = new BufferingStreamReader(baseResponseStream); + using var responseStream = new BufferingStreamReader(baseResponseStream, _cancelToken.Token); // First see if it is an RSS / ATOM feed, in which case we can // stream it - unless the user has overridden it with a return type of "XML" @@ -95,7 +97,7 @@ internal override void ProcessResponse(HttpResponseMessage response) // Try to get the response encoding from the ContentType header. string charSet = WebResponseHelper.GetCharacterSet(response); - string str = StreamHelper.DecodeStream(responseStream, charSet, out Encoding encoding); + string str = StreamHelper.DecodeStream(responseStream, charSet, out Encoding encoding, _cancelToken.Token); object obj = null; Exception ex = null; @@ -112,7 +114,7 @@ internal override void ProcessResponse(HttpResponseMessage response) // NOTE: Tests use this verbose output to verify the encoding. WriteVerbose(string.Create(System.Globalization.CultureInfo.InvariantCulture, $"Content encoding: {encodingVerboseName}")); - + bool convertSuccess = false; if (returnType == RestReturnType.Json) @@ -231,7 +233,7 @@ private bool TryProcessFeedStream(Stream responseStream) } } } - catch (XmlException) + catch (XmlException) { // Catch XmlException } @@ -349,17 +351,19 @@ public enum RestReturnType internal class BufferingStreamReader : Stream { - internal BufferingStreamReader(Stream baseStream) + internal BufferingStreamReader(Stream baseStream, CancellationToken cancellationToken) { _baseStream = baseStream; _streamBuffer = new MemoryStream(); _length = long.MaxValue; _copyBuffer = new byte[4096]; + _cancellationToken = cancellationToken; } private readonly Stream _baseStream; private readonly MemoryStream _streamBuffer; private readonly byte[] _copyBuffer; + private readonly CancellationToken _cancellationToken; public override bool CanRead => true; @@ -393,7 +397,7 @@ public override int Read(byte[] buffer, int offset, int count) // If we don't have enough data to fill this from memory, cache more. // We try to read 4096 bytes from base stream every time, so at most we // may cache 4095 bytes more than what is required by the Read operation. - int bytesRead = _baseStream.Read(_copyBuffer, 0, _copyBuffer.Length); + int bytesRead = _baseStream.ReadAsync(_copyBuffer, 0, _copyBuffer.Length, _cancellationToken).GetAwaiter().GetResult(); if (_streamBuffer.Position < _streamBuffer.Length) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index c078faaed5c..f979a763da8 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -613,7 +613,7 @@ protected override void ProcessRecord() string detailMsg = string.Empty; try { - string error = StreamHelper.GetResponseString(response); + string error = StreamHelper.GetResponseString(response, _cancelToken.Token); detailMsg = FormatErrorMessage(error, contentType); } catch @@ -658,6 +658,11 @@ protected override void ProcessRecord() ThrowTerminatingError(er); } + finally + { + _cancelToken?.Dispose(); + _cancelToken = null; + } if (_followRelLink) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebResponseObject.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebResponseObject.Common.cs index 5a55ccc2e73..8bfdeed2da4 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebResponseObject.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebResponseObject.Common.cs @@ -7,6 +7,7 @@ using System.IO; using System.Net.Http; using System.Text; +using System.Threading; namespace Microsoft.PowerShell.Commands { @@ -74,19 +75,21 @@ public class WebResponseObject /// /// Initializes a new instance of the class. /// - /// - public WebResponseObject(HttpResponseMessage response) : this(response, null) + /// The Http response. + /// The cancellation token. + public WebResponseObject(HttpResponseMessage response, CancellationToken cancellationToken) : this(response, null, cancellationToken) { } /// /// Initializes a new instance of the class /// with the specified . /// - /// - /// - public WebResponseObject(HttpResponseMessage response, Stream contentStream) + /// Http response. + /// The http content stream. + /// The cancellation token. + public WebResponseObject(HttpResponseMessage response, Stream contentStream, CancellationToken cancellationToken) { - SetResponse(response, contentStream); + SetResponse(response, contentStream, cancellationToken); InitializeContent(); InitializeRawContent(response); } @@ -116,13 +119,13 @@ private void InitializeRawContent(HttpResponseMessage baseResponse) RawContent = raw.ToString(); } - private static bool IsPrintable(char c) => char.IsLetterOrDigit(c) - || char.IsPunctuation(c) - || char.IsSeparator(c) - || char.IsSymbol(c) + private static bool IsPrintable(char c) => char.IsLetterOrDigit(c) + || char.IsPunctuation(c) + || char.IsSeparator(c) + || char.IsSymbol(c) || char.IsWhiteSpace(c); - private void SetResponse(HttpResponseMessage response, Stream contentStream) + private void SetResponse(HttpResponseMessage response, Stream contentStream, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(response); @@ -138,7 +141,7 @@ private void SetResponse(HttpResponseMessage response, Stream contentStream) Stream st = contentStream; if (contentStream is null) { - st = StreamHelper.GetResponseStream(response); + st = StreamHelper.GetResponseStream(response, cancellationToken); } long contentLength = response.Content.Headers.ContentLength.Value; @@ -148,7 +151,7 @@ private void SetResponse(HttpResponseMessage response, Stream contentStream) } int initialCapacity = (int)Math.Min(contentLength, StreamHelper.DefaultReadBuffer); - RawContentStream = new WebResponseContentMemoryStream(st, initialCapacity, cmdlet: null, response.Content.Headers.ContentLength.GetValueOrDefault()); + RawContentStream = new WebResponseContentMemoryStream(st, initialCapacity, cmdlet: null, response.Content.Headers.ContentLength.GetValueOrDefault(), cancellationToken); } // Set the position of the content stream to the beginning diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/InvokeWebRequestCommand.CoreClr.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/InvokeWebRequestCommand.CoreClr.cs index bde0847adc5..19ebc294c10 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/InvokeWebRequestCommand.CoreClr.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/InvokeWebRequestCommand.CoreClr.cs @@ -34,7 +34,7 @@ internal override void ProcessResponse(HttpResponseMessage response) { ArgumentNullException.ThrowIfNull(response); - Stream responseStream = StreamHelper.GetResponseStream(response); + Stream responseStream = StreamHelper.GetResponseStream(response, _cancelToken.Token); if (ShouldWriteToPipeline) { // creating a MemoryStream wrapper to response stream here to support IsStopping. @@ -42,8 +42,9 @@ internal override void ProcessResponse(HttpResponseMessage response) responseStream, StreamHelper.ChunkSize, this, - response.Content.Headers.ContentLength.GetValueOrDefault()); - WebResponseObject ro = WebResponseHelper.IsText(response) ? new BasicHtmlWebResponseObject(response, responseStream) : new WebResponseObject(response, responseStream); + response.Content.Headers.ContentLength.GetValueOrDefault(), + _cancelToken.Token); + WebResponseObject ro = WebResponseHelper.IsText(response) ? new BasicHtmlWebResponseObject(response, responseStream, _cancelToken.Token) : new WebResponseObject(response, responseStream, _cancelToken.Token); ro.RelationLink = _relationLink; WriteObject(ro); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs index 49cc7d43402..bec01ee8a1d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs @@ -25,8 +25,9 @@ internal class WebResponseContentMemoryStream : MemoryStream private readonly long? _contentLength; private readonly Stream _originalStreamToProxy; - private bool _isInitialized = false; private readonly Cmdlet _ownerCmdlet; + private readonly CancellationToken _cancellationToken; + private bool _isInitialized = false; #endregion Data @@ -34,15 +35,17 @@ internal class WebResponseContentMemoryStream : MemoryStream /// /// Initializes a new instance of the class. /// - /// - /// + /// Response stream. + /// Presize the memory stream. /// Owner cmdlet if any. /// Expected download size in Bytes. - internal WebResponseContentMemoryStream(Stream stream, int initialCapacity, Cmdlet cmdlet, long? contentLength) : base(initialCapacity) + /// Cancellation token. + internal WebResponseContentMemoryStream(Stream stream, int initialCapacity, Cmdlet cmdlet, long? contentLength, CancellationToken cancellationToken) : base(initialCapacity) { this._contentLength = contentLength; _originalStreamToProxy = stream; _ownerCmdlet = cmdlet; + _cancellationToken = cancellationToken; } #endregion Constructors @@ -77,7 +80,7 @@ public override long Length /// public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken) { - Initialize(); + Initialize(cancellationToken); return base.CopyToAsync(destination, bufferSize, cancellationToken); } @@ -102,7 +105,7 @@ public override int Read(byte[] buffer, int offset, int count) /// public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { - Initialize(); + Initialize(cancellationToken); return base.ReadAsync(buffer, offset, count, cancellationToken); } @@ -153,7 +156,7 @@ public override void Write(byte[] buffer, int offset, int count) /// public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { - Initialize(); + Initialize(cancellationToken); return base.WriteAsync(buffer, offset, count, cancellationToken); } @@ -182,15 +185,18 @@ protected override void Dispose(bool disposing) base.Dispose(disposing); } - /// - /// - private void Initialize() + private void Initialize(CancellationToken cancellationToken = default) { - if (_isInitialized) + if (_isInitialized) { return; } + if (cancellationToken == default) + { + cancellationToken = _cancellationToken; + } + _isInitialized = true; try { @@ -220,7 +226,7 @@ private void Initialize() } } - read = _originalStreamToProxy.Read(buffer, 0, buffer.Length); + read = _originalStreamToProxy.ReadAsync(buffer, 0, buffer.Length, cancellationToken).GetAwaiter().GetResult(); if (read > 0) { @@ -237,11 +243,11 @@ private void Initialize() // Make sure the length is set appropriately base.SetLength(totalRead); - base.Seek(0, SeekOrigin.Begin); + Seek(0, SeekOrigin.Begin); } catch (Exception) { - base.Dispose(); + Dispose(); throw; } } @@ -329,7 +335,7 @@ internal static void SaveStreamToFile(Stream stream, string filePath, PSCmdlet c WriteToStream(stream, output, cmdlet, contentLength, cancellationToken); } - private static string StreamToString(Stream stream, Encoding encoding) + private static string StreamToString(Stream stream, Encoding encoding, CancellationToken cancellationToken) { StringBuilder result = new(capacity: ChunkSize); Decoder decoder = encoding.GetDecoder(); @@ -347,7 +353,7 @@ private static string StreamToString(Stream stream, Encoding encoding) { // Read at most the number of bytes that will fit in the input buffer. The // return value is the actual number of bytes read, or zero if no bytes remain. - bytesRead = stream.Read(bytes, 0, useBufferSize * 4); + bytesRead = stream.ReadAsync(bytes, 0, useBufferSize * 4, cancellationToken).GetAwaiter().GetResult(); bool completed = false; int byteIndex = 0; @@ -355,10 +361,8 @@ private static string StreamToString(Stream stream, Encoding encoding) while (!completed) { // If this is the last input data, flush the decoder's internal buffer and state. - bool flush = (bytesRead == 0); - decoder.Convert(bytes, byteIndex, bytesRead - byteIndex, - chars, 0, useBufferSize, flush, - out int bytesUsed, out int charsUsed, out completed); + bool flush = bytesRead == 0; + decoder.Convert(bytes, byteIndex, bytesRead - byteIndex, chars, 0, useBufferSize, flush, out int bytesUsed, out int charsUsed, out completed); // The conversion produced the number of characters indicated by charsUsed. Write that number // of characters to our result buffer @@ -376,16 +380,17 @@ private static string StreamToString(Stream stream, Encoding encoding) break; } } - } while (bytesRead != 0); + } + while (bytesRead != 0); return result.ToString(); } - internal static string DecodeStream(Stream stream, string characterSet, out Encoding encoding) + internal static string DecodeStream(Stream stream, string characterSet, out Encoding encoding, CancellationToken cancellationToken) { bool isDefaultEncoding = !TryGetEncoding(characterSet, out encoding); - string content = StreamToString(stream, encoding); + string content = StreamToString(stream, encoding, cancellationToken); if (isDefaultEncoding) { // We only look within the first 1k characters as the meta element and @@ -394,13 +399,13 @@ internal static string DecodeStream(Stream stream, string characterSet, out Enco // Check for a charset attribute on the meta element to override the default Match match = s_metaRegex.Match(substring); - + // Check for a encoding attribute on the xml declaration to override the default if (!match.Success) { match = s_xmlRegex.Match(substring); } - + if (match.Success) { characterSet = match.Groups["charset"].Value; @@ -408,7 +413,7 @@ internal static string DecodeStream(Stream stream, string characterSet, out Enco if (TryGetEncoding(characterSet, out Encoding localEncoding)) { stream.Seek(0, SeekOrigin.Begin); - content = StreamToString(stream, localEncoding); + content = StreamToString(stream, localEncoding, cancellationToken); encoding = localEncoding; } } @@ -438,11 +443,11 @@ internal static bool TryGetEncoding(string characterSet, out Encoding encoding) @"<]*charset\s*=\s*[""'\n]?(?[A-Za-z].[^\s""'\n<>]*)[\s""'\n>]", RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.ExplicitCapture | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase | RegexOptions.NonBacktracking ); - + private static readonly Regex s_xmlRegex = new( @"<\?xml\s.*[^.><]*encoding\s*=\s*[""'\n]?(?[A-Za-z].[^\s""'\n<>]*)[\s""'\n>]", RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.ExplicitCapture | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase | RegexOptions.NonBacktracking - ); + ); internal static byte[] EncodeToBytes(string str, Encoding encoding) { @@ -452,9 +457,9 @@ internal static byte[] EncodeToBytes(string str, Encoding encoding) return encoding.GetBytes(str); } - internal static string GetResponseString(HttpResponseMessage response) => response.Content.ReadAsStringAsync().GetAwaiter().GetResult(); + internal static string GetResponseString(HttpResponseMessage response, CancellationToken cancellationToken) => response.Content.ReadAsStringAsync(cancellationToken).GetAwaiter().GetResult(); - internal static Stream GetResponseStream(HttpResponseMessage response) => response.Content.ReadAsStreamAsync().GetAwaiter().GetResult(); + internal static Stream GetResponseStream(HttpResponseMessage response, CancellationToken cancellationToken) => response.Content.ReadAsStreamAsync(cancellationToken).GetAwaiter().GetResult(); #endregion Static Methods } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 index 5f1e6e4bae3..bf4072ddfc2 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 @@ -4183,3 +4183,120 @@ Describe "Web cmdlets tests using the cmdlet's aliases" -Tags "CI", "RequireAdmi { Invoke-RestMethod -Uri $uri -ContentType $null } | Should -Not -Throw } } + +Describe 'Invoke-WebRequest and Invoke-RestMethod support Cancellation through CTRL-C' -Tags "CI", "RequireAdminOnWindows" { + BeforeAll { + $oldProgress = $ProgressPreference + $ProgressPreference = 'SilentlyContinue' + $WebListener = Start-WebListener + } + + AfterAll { + $ProgressPreference = $oldProgress + } + + function RunWithCancellation { + param( + [string]$Command = 'Invoke-WebRequest', + [string]$Arguments = '', + [uri]$Uri, + [int]$DelayMs = 100, + [switch]$WillComplete + ) + + $pwsh = [PowerShell]::Create() + $invoke = "`$result = $Command -Uri `"$Uri`" $Arguments" + $task = $pwsh.AddScript($invoke).InvokeAsync() + Start-Sleep -Milliseconds $DelayMs + $task.IsCompleted | Should -Be $WillComplete.ToBool() + $pwsh.Stop() + Wait-UntilTrue { [bool]($Task.IsCompleted) } | Should -BeTrue + $result = $pwsh.Runspace.SessionStateProxy.GetVariable('result') + $pwsh.Dispose() + + return $result + } + + It 'Invoke-WebRequest: CTRL-C Cancels request before request headers received' { + $uri = Get-WebListenerUrl -test Delay -TestValue 30 + RunWithCancellation -Uri $uri -DelayMs 0 + } + + It 'Invoke-WebRequest: CTRL-C Cancels request after request headers received' { + $uri = Get-WebListenerUrl -test Stall -TestValue '30/application%2fjson' + RunWithCancellation -Uri $uri + } + + It 'Invoke-WebRequest: HTTPS CTRL-C Cancels request after request headers' { + $uri = Get-WebListenerUrl -Https -Test Stall -TestValue '30/application%2fjson' + RunWithCancellation -Uri $uri -Arguments "-SkipCertificateCheck" + } + + It 'Invoke-WebRequest: Compression CTRL-C Cancels request after request headers' { + $uri = Get-WebListenerUrl -Test StallBrotli -TestValue '30/application%2fjson' + RunWithCancellation -Uri $uri + $uri = Get-WebListenerUrl -Test StallGzip -TestValue '30/application%2fjson' + RunWithCancellation -Uri $uri + $uri = Get-WebListenerUrl -Test StallDeflate -TestValue '30/application%2fjson' + RunWithCancellation -Uri $uri + } + + It 'Invoke-WebRequest: HTTPS with compression CTRL-C Cancels request after request headers' { + $uri = Get-WebListenerUrl -Https -Test StallBrotli -TestValue '30/application%2fjson' + RunWithCancellation -Uri $uri -Arguments '-SkipCertificateCheck' + $uri = Get-WebListenerUrl -Https -Test StallGzip -TestValue '30/application%2fjson' + RunWithCancellation -Uri $uri -Arguments '-SkipCertificateCheck' + $uri = Get-WebListenerUrl -Https -Test StallDeflate -TestValue '30/application%2fjson' + RunWithCancellation -Uri $uri -Arguments '-SkipCertificateCheck' + } + + It 'Invoke-WebRequest: CTRL-C Cancels file download request after request headers received' { + $uri = Get-WebListenerUrl -Test Stall -TestValue '30' + $outFile = Join-Path $TestDrive "output.txt" + RunWithCancellation -Uri $uri -Arguments "-OutFile $outFile" -DelayMs 300 + # No guarantee the file will be present since the D/L is interrupted + if (Test-Path -Path $outFile) { + Remove-Item -Path $outFile + } + } + + It 'Invoke-WebRequest: CTRL-C after stalled file download completes gives entire file' { + $uri = Get-WebListenerUrl -test Stall -TestValue '1' + $outFile = Join-Path $TestDrive "output.txt" + RunWithCancellation -Uri $uri -Arguments "-OutFile $outFile" -DelayMs 1200 -WillComplete + Get-content -Path $outFile | should -be 'Hello worldHello world' + Remove-Item -Path $outFile + } + + It 'Invoke-RestMethod: CTRL-C Cancels request before request headers received' { + $uri = Get-WebListenerUrl -test Delay -TestValue 30 + RunWithCancellation -Command 'Invoke-RestMethod' -Uri $uri -DelayMs 0 + } + + It 'Invoke-RestMethod: CTRL-C Cancels request after JSON request headers received' { + $uri = Get-WebListenerUrl -test Stall -TestValue '30/application%2fjson' + RunWithCancellation -Command 'Invoke-RestMethod' -Uri $uri + } + + It 'Invoke-RestMethod: CTRL-C after stalled JSON download processes JSON response' { + $uri = Get-WebListenerUrl -test Stall -TestValue '1/application%2fjson' + $result = RunWithCancellation -Command 'Invoke-RestMethod' -Uri $uri -DelayMs 1200 -WillComplete + $result.name3 | should -be 'value3' + } + + It 'Invoke-RestMethod: CTRL-C Cancels request after plain request headers received' { + $uri = Get-WebListenerUrl -test Stall -TestValue '30' + RunWithCancellation -Command 'Invoke-RestMethod' -Uri $uri + } + + It 'Invoke-RestMethod: CTRL-C after stalled atom feed download processes atom response' { + $uri = Get-WebListenerUrl -test Stall -TestValue '1/application%2fxml' + $result = RunWithCancellation -Command 'Invoke-RestMethod' -Uri $uri -DelayMs 1200 -WillComplete + $result.title | should -be 'Atom-Powered Robots Run Amok' + } + + It 'Invoke-RestMethod: CTRL-C Cancels request in XML atom processing' { + $uri = Get-WebListenerUrl -test Stall -TestValue '30/application%2fxml' + RunWithCancellation -Command 'Invoke-RestMethod' -Uri $uri + } +} diff --git a/test/tools/Modules/WebListener/WebListener.psm1 b/test/tools/Modules/WebListener/WebListener.psm1 index e065363e673..15ce1d8fe38 100644 --- a/test/tools/Modules/WebListener/WebListener.psm1 +++ b/test/tools/Modules/WebListener/WebListener.psm1 @@ -235,6 +235,10 @@ function Get-WebListenerUrl { 'ResponseHeaders', 'Resume', 'Retry', + 'Stall', + 'StallGZip', + 'StallBrotli', + 'StallDeflate', '/' )] [String]$Test, diff --git a/test/tools/WebListener/Controllers/DelayController.cs b/test/tools/WebListener/Controllers/DelayController.cs index f5e877cfe2e..5ab081d580d 100644 --- a/test/tools/WebListener/Controllers/DelayController.cs +++ b/test/tools/WebListener/Controllers/DelayController.cs @@ -1,24 +1,50 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -using System; -using System.Collections; -using System.Collections.Generic; using System.Diagnostics; -using System.Linq; +using System.IO; +using System.Net; using System.Threading; using System.Threading.Tasks; +using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Http.Extensions; using mvc.Models; +using System.IO.Compression; namespace mvc.Controllers { public class DelayController : Controller { + private static readonly byte[] GenericBytes = "Hello worldHello world"u8.ToArray(); + + private static readonly byte[] JsonBytes = """ + {"name1":"value1","name2":"value2","name3":"value3"} + """u8.ToArray(); + + private static readonly byte[] AtomFeed = """ + + + Example Feed + + 2003-12-13T18:30:02Z + + John Doe + + urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6 + + Atom-Powered Robots Run Amok + + urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a + 2003-12-13T18:30:02Z + Some text. + + + """u8.ToArray(); + public JsonResult Index(int seconds) { - if (seconds > 0){ + if (seconds > 0) + { int milliseconds = seconds * 1000; Thread.Sleep(milliseconds); } @@ -28,9 +54,90 @@ public JsonResult Index(int seconds) return getController.Index(); } + public async Task Stall(int seconds, string contentType, CancellationToken cancellationToken) + { + await WriteStallResponse(seconds, contentType, null, null, cancellationToken); + } + + public async Task StallBrotli(int seconds, string contentType, CancellationToken cancellationToken) + { + using var memStream = new MemoryStream(); + using var compressedStream = new BrotliStream(memStream, CompressionLevel.Fastest); + Response.Headers.ContentEncoding = "br"; + await WriteStallResponse(seconds, contentType, compressedStream, memStream, cancellationToken); + } + + public async Task StallDeflate(int seconds, string contentType, CancellationToken cancellationToken) + { + using var memStream = new MemoryStream(); + using var compressedStream = new DeflateStream(memStream, CompressionLevel.Fastest); + Response.Headers.ContentEncoding = "deflate"; + await WriteStallResponse(seconds, contentType, compressedStream, memStream, cancellationToken); + } + + public async Task StallGZip(int seconds, string contentType, CancellationToken cancellationToken) + { + using var memStream = new MemoryStream(); + using var compressedStream = new GZipStream(memStream, CompressionLevel.Fastest); + Response.Headers.ContentEncoding = "gzip"; + await WriteStallResponse(seconds, contentType, compressedStream, memStream, cancellationToken); + } + public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } + + private async Task WriteStallResponse(int seconds, string contentType, Stream stream, MemoryStream memStream, CancellationToken cancellationToken) + { + if (string.IsNullOrWhiteSpace(contentType)) + { + contentType = "text/plain"; + } + else + { + contentType = WebUtility.UrlDecode(contentType); + } + + Response.ContentType = contentType; + Response.StatusCode = StatusCodes.Status200OK; + byte[] response; + + if (contentType.Contains("json")) + { + response = JsonBytes; + } + else if (contentType.Contains("xml")) + { + response = AtomFeed; + } + else + { + response = GenericBytes; + } + + if (stream is not null && memStream is not null) + { + // Generate the compressed data for sending on the response stream + stream.Write(response); + stream.Flush(); + stream.Close(); + response = memStream.ToArray(); + } + int midPoint = response.Length / 2; + + // Start writing approx half the content, including headers and then delay before writing the rest. + await Response.Body.WriteAsync(response, 0, midPoint, cancellationToken); + await Response.Body.FlushAsync(cancellationToken); + + if (seconds > 0) + { + int milliseconds = seconds * 1000; + await Task.Delay(milliseconds); + } + + await Response.Body.WriteAsync(response, midPoint, response.Length - midPoint, cancellationToken); + await Response.Body.FlushAsync(cancellationToken); + } } } diff --git a/test/tools/WebListener/Startup.cs b/test/tools/WebListener/Startup.cs index 4bceaa0bf71..0136decb5f5 100644 --- a/test/tools/WebListener/Startup.cs +++ b/test/tools/WebListener/Startup.cs @@ -65,6 +65,22 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env) name: "delay", template: "Delay/{seconds?}", defaults: new { controller = "Delay", action = "Index" }); + routes.MapRoute( + name: "stall", + template: "Stall/{seconds?}/{contentType?}", + defaults: new { controller = "Delay", action = "Stall" }); + routes.MapRoute( + name: $"stallbrotli", + template: "StallBrotli/{seconds?}/{contentType?}", + defaults: new { controller = "Delay", action = $"StallBrotli" }); + routes.MapRoute( + name: $"stalldeflate", + template: "StallDeflate/{seconds?}/{contentType?}", + defaults: new { controller = "Delay", action = $"StallDeflate" }); + routes.MapRoute( + name: $"stallgzip", + template: "StallGZip/{seconds?}/{contentType?}", + defaults: new { controller = "Delay", action = $"StallGZip" }); routes.MapRoute( name: "post", template: "Post", From 6530133c278203fdf4856354733224a9c617d7b2 Mon Sep 17 00:00:00 2001 From: PowerShell Team Bot <69177312+pwshBot@users.noreply.github.com> Date: Wed, 5 Apr 2023 14:06:07 -0700 Subject: [PATCH 468/779] Update to the latest NOTICES file (#19332) --- ThirdPartyNotices.txt | 96 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 96 insertions(+) diff --git a/ThirdPartyNotices.txt b/ThirdPartyNotices.txt index b945bd44d07..a03f292a93d 100644 --- a/ThirdPartyNotices.txt +++ b/ThirdPartyNotices.txt @@ -135,6 +135,24 @@ limitations under the License. --------------------------------------------------------- +Markdig.Signed 0.31.0 - BSD-2-Clause + + + +Copyright (c) . All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +--------------------------------------------------------- + +--------------------------------------------------------- + Microsoft.ApplicationInsights 2.21.0 - MIT @@ -218,6 +236,48 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +--------------------------------------------------------- + +--------------------------------------------------------- + +Microsoft.CodeAnalysis.Common 4.5.0 - MIT + + +(c) Microsoft Corporation +Copyright (c) .NET Foundation and Contributors + +MIT License + +Copyright (c) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--------------------------------------------------------- + +--------------------------------------------------------- + +Microsoft.CodeAnalysis.CSharp 4.5.0 - MIT + + +(c) Microsoft Corporation +Copyright (c) Microsoft Corporation +Copyright (c) .NET Foundation and Contributors +Copyright (c) Microsoft Corporation. Alle Rechte + +MIT License + +Copyright (c) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + --------------------------------------------------------- --------------------------------------------------------- @@ -3682,6 +3742,42 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +--------------------------------------------------------- + +--------------------------------------------------------- + +System.ServiceModel.NetFramingBase 6.0.0-preview1.23060.3 - MIT + + +(c) Microsoft Corporation +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2000-2014 The Legion of the Bouncy Castle Inc. (http://www.bouncycastle.org) + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + --------------------------------------------------------- --------------------------------------------------------- From 0ddb187e61598ff9079103b1db7e4944d422f071 Mon Sep 17 00:00:00 2001 From: PowerShell Team Bot <69177312+pwshBot@users.noreply.github.com> Date: Wed, 5 Apr 2023 14:40:57 -0700 Subject: [PATCH 469/779] Update the cgmanifest (#19459) --- tools/cgmanifest.json | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/tools/cgmanifest.json b/tools/cgmanifest.json index bb6dcb5f360..a0559eaa6b6 100644 --- a/tools/cgmanifest.json +++ b/tools/cgmanifest.json @@ -55,7 +55,7 @@ "Type": "nuget", "Nuget": { "Name": "Microsoft.CodeAnalysis.Analyzers", - "Version": "3.3.3" + "Version": "3.3.4" } }, "DevelopmentDependency": true @@ -235,7 +235,7 @@ "Type": "nuget", "Nuget": { "Name": "Newtonsoft.Json", - "Version": "13.0.2" + "Version": "13.0.3" } }, "DevelopmentDependency": false @@ -775,7 +775,7 @@ "Type": "nuget", "Nuget": { "Name": "System.Diagnostics.DiagnosticSource", - "Version": "7.0.1" + "Version": "7.0.2" } }, "DevelopmentDependency": false @@ -1215,7 +1215,7 @@ "Type": "nuget", "Nuget": { "Name": "System.ServiceModel.Duplex", - "Version": "4.10.0" + "Version": "4.10.2" } }, "DevelopmentDependency": false @@ -1225,7 +1225,7 @@ "Type": "nuget", "Nuget": { "Name": "System.ServiceModel.Http", - "Version": "4.10.0" + "Version": "4.10.2" } }, "DevelopmentDependency": false @@ -1245,7 +1245,7 @@ "Type": "nuget", "Nuget": { "Name": "System.ServiceModel.NetTcp", - "Version": "4.10.0" + "Version": "4.10.2" } }, "DevelopmentDependency": false @@ -1255,7 +1255,7 @@ "Type": "nuget", "Nuget": { "Name": "System.ServiceModel.Primitives", - "Version": "4.10.0" + "Version": "4.10.2" } }, "DevelopmentDependency": false @@ -1265,7 +1265,7 @@ "Type": "nuget", "Nuget": { "Name": "System.ServiceModel.Security", - "Version": "4.10.0" + "Version": "4.10.2" } }, "DevelopmentDependency": false From 059b9524aa228724b135f72f6c81028c99901957 Mon Sep 17 00:00:00 2001 From: "James Truher [MSFT]" Date: Thu, 6 Apr 2023 16:24:44 -0700 Subject: [PATCH 470/779] WIP: Harden default command test. (#19416) --- .../engine/Basic/DefaultCommands.Tests.ps1 | 113 +++++++++--------- 1 file changed, 54 insertions(+), 59 deletions(-) diff --git a/test/powershell/engine/Basic/DefaultCommands.Tests.ps1 b/test/powershell/engine/Basic/DefaultCommands.Tests.ps1 index f5fc66748a7..9d1b030a6a5 100644 --- a/test/powershell/engine/Basic/DefaultCommands.Tests.ps1 +++ b/test/powershell/engine/Basic/DefaultCommands.Tests.ps1 @@ -2,6 +2,19 @@ # Licensed under the MIT License. Describe "Verify approved aliases list" -Tags "CI" { BeforeAll { + function ConvertTo-Hashtable { + [CmdletBinding()] + param ([Parameter(ValueFromPipeline=$true)][psobject]$o) + PROCESS { + $pNames = $o.psobject.properties.name + $ht = @{} + foreach($pName in $pNames) { + $ht[$pName] = $o.$pName + } + $ht + } + } + $FullCLR = !$IsCoreCLR $CoreWindows = $IsCoreCLR -and $IsWindows $CoreUnix = $IsCoreCLR -and !$IsWindows @@ -368,8 +381,8 @@ Describe "Verify approved aliases list" -Tags "CI" { "Cmdlet", "New-FileCatalog", "", $($FullCLR -or $CoreWindows ), "", "", "Medium" "Cmdlet", "New-GUID", "", $( $CoreWindows -or $CoreUnix), "", "", "None" "Cmdlet", "New-Item", "", $($FullCLR -or $CoreWindows -or $CoreUnix), "", "", "Medium" -"Cmdlet", "New-ItemProperty", "", $($FullCLR -or $CoreWindows -or $CoreUnix), "", "", "None" -"Cmdlet", "New-Module", "", $($FullCLR -or $CoreWindows -or $CoreUnix), "", "", "Medium" +"Cmdlet", "New-ItemProperty", "", $($FullCLR -or $CoreWindows -or $CoreUnix), "", "", "Medium" +"Cmdlet", "New-Module", "", $($FullCLR -or $CoreWindows -or $CoreUnix), "", "", "None" "Cmdlet", "New-ModuleManifest", "", $($FullCLR -or $CoreWindows -or $CoreUnix), "", "", "Low" "Cmdlet", "New-Object", "", $($FullCLR -or $CoreWindows -or $CoreUnix), "", "", "None" "Cmdlet", "New-PSDrive", "", $($FullCLR -or $CoreWindows -or $CoreUnix), "", "", "Low" @@ -387,7 +400,7 @@ Describe "Verify approved aliases list" -Tags "CI" { "Cmdlet", "New-WSManInstance", "", $($FullCLR -or $CoreWindows ), "", "", "None" "Cmdlet", "New-WSManSessionOption", "", $($FullCLR -or $CoreWindows ), "", "", "None" "Cmdlet", "Out-Default", "", $($FullCLR -or $CoreWindows -or $CoreUnix), "", "", "None" -"Cmdlet", "Out-File", "", $($FullCLR -or $CoreWindows -or $CoreUnix), "", "", "None" +"Cmdlet", "Out-File", "", $($FullCLR -or $CoreWindows -or $CoreUnix), "", "", "Medium" "Cmdlet", "Out-GridView", "", $($FullCLR -or $CoreWindows ), "", "", "None" "Cmdlet", "Out-Host", "", $($FullCLR -or $CoreWindows -or $CoreUnix), "", "", "None" "Cmdlet", "Out-LineOutput", "", $($FullCLR ), "", "", "" @@ -458,7 +471,7 @@ Describe "Verify approved aliases list" -Tags "CI" { "Cmdlet", "Set-Service", "", $($FullCLR -or $CoreWindows ), "", "", "Medium" "Cmdlet", "Set-StrictMode", "", $($FullCLR -or $CoreWindows -or $CoreUnix), "", "", "None" "Cmdlet", "Set-TimeZone", "", $($FullCLR -or $CoreWindows ), "", "", "Medium" -"Cmdlet", "Set-TraceSource", "", $($FullCLR -or $CoreWindows -or $CoreUnix), "", "", "Medium" +"Cmdlet", "Set-TraceSource", "", $($FullCLR -or $CoreWindows -or $CoreUnix), "", "", "None" "Cmdlet", "Set-Variable", "", $($FullCLR -or $CoreWindows -or $CoreUnix), "", "", "Medium" "Cmdlet", "Set-WmiInstance", "", $($FullCLR ), "", "", "" "Cmdlet", "Set-WSManInstance", "", $($FullCLR -or $CoreWindows ), "", "", "None" @@ -474,7 +487,7 @@ Describe "Verify approved aliases list" -Tags "CI" { "Cmdlet", "Start-Service", "", $($FullCLR -or $CoreWindows ), "", "", "Medium" "Cmdlet", "Start-Sleep", "", $($FullCLR -or $CoreWindows -or $CoreUnix), "", "", "None" "Cmdlet", "Start-Transaction", "", $($FullCLR ), "", "", "" -"Cmdlet", "Start-Transcript", "", $($FullCLR -or $CoreWindows -or $CoreUnix), "", "", "None" +"Cmdlet", "Start-Transcript", "", $($FullCLR -or $CoreWindows -or $CoreUnix), "", "", "Medium" "Cmdlet", "Stop-Computer", "", $($FullCLR -or $CoreWindows -or $CoreUnix), "", "", "Medium" "Cmdlet", "Stop-Job", "", $($FullCLR -or $CoreWindows -or $CoreUnix), "", "", "Medium" "Cmdlet", "Stop-Process", "", $($FullCLR -or $CoreWindows -or $CoreUnix), "", "", "Medium" @@ -483,7 +496,7 @@ Describe "Verify approved aliases list" -Tags "CI" { "Cmdlet", "Suspend-Job", "", $($FullCLR ), "", "", "" "Cmdlet", "Suspend-Service", "", $($FullCLR -or $CoreWindows ), "", "", "Medium" "Cmdlet", "Switch-Process", "", $( $CoreUnix), "", "", "None" -"Cmdlet", "Tee-Object", "", $($FullCLR -or $CoreWindows -or $CoreUnix), "", "", "Medium" +"Cmdlet", "Tee-Object", "", $($FullCLR -or $CoreWindows -or $CoreUnix), "", "", "None" "Cmdlet", "Test-Connection", "", $( $CoreWindows -or $CoreUnix), "", "", "None" "Cmdlet", "Test-ComputerSecureChannel", "", $($FullCLR ), "", "", "" "Cmdlet", "Test-FileCatalog", "", $($FullCLR -or $CoreWindows ), "", "", "Medium" @@ -519,9 +532,18 @@ Describe "Verify approved aliases list" -Tags "CI" { "Cmdlet", "Write-Warning", "", $($FullCLR -or $CoreWindows -or $CoreUnix), "", "", "None" "@ - # We control only default engine aliases (Source -eq "") and aliases from following default loaded modules + # We control only default engine aliases (Source -eq "") and aliases from following default loaded modules " # We control only default engine Cmdlets (Source -eq "") and Cmdlets from following default loaded modules - $moduleList = @("Microsoft.PowerShell.Utility", "Microsoft.PowerShell.Management", "Microsoft.PowerShell.Security", "Microsoft.PowerShell.Host", "Microsoft.PowerShell.Diagnostics", "Microsoft.WSMan.Management", "Microsoft.PowerShell.Core", "CimCmdlets") + $moduleList = @( + "Microsoft.PowerShell.Utility", + "Microsoft.PowerShell.Management", + "Microsoft.PowerShell.Security", + "Microsoft.PowerShell.Host", + "Microsoft.PowerShell.Diagnostics", + "Microsoft.WSMan.Management", + "Microsoft.PowerShell.Core", + "CimCmdlets" + ) $getAliases = { param($moduleList) @@ -557,7 +579,12 @@ Describe "Verify approved aliases list" -Tags "CI" { } $commandList = $commandString | ConvertFrom-Csv -Delimiter "," + $commandHashTableList = $commandList.Where({$_.Present -eq "True" -and $_.CommandType -eq "Cmdlet"}) | ConvertTo-Hashtable + $aliasFullList = $commandList | Where-Object { $_.Present -eq "True" -and $_.CommandType -eq "Alias" } + + $AllScopeOption = [System.Management.Automation.ScopedItemOptions]::AllScope + $ReadOnlyOption = [System.Management.Automation.ScopedItemOptions]::ReadOnly } AfterAll { @@ -567,68 +594,36 @@ Describe "Verify approved aliases list" -Tags "CI" { } It "All approved aliases present (no new aliases added, no aliases removed)" { - $currentDisplayNameAliasList = $currentAliasList | Select-Object -ExpandProperty DisplayName - $aliasDisplayNameAliasList = $aliasFullList | ForEach-Object { "{0} -> {1}" -f $_.Name, $_.Definition} - - $result = Compare-Object -ReferenceObject $currentDisplayNameAliasList -DifferenceObject $aliasDisplayNameAliasList - - # Below 'Should Be' don't show full list wrong aliases so we output them explicitly - # if all aliases is Ok we output nothing - $result | Write-Host - $result | Should -BeNullOrEmpty + $observedAliases = $currentAliasList.ForEach({"{0}:{1}" -f $_.Name,$_.Definition}) | Sort-Object + $expectedAliases = $aliasFullList.ForEach({"{0}:{1}" -f $_.Name, $_.Definition}) | Sort-Object + $observedAliases | Should -Be $expectedAliases } It "All approved aliases have the correct 'AllScope' option" { - $aliasAllScopeOptionList = $aliasFullList | Where-Object { $_.AllScopeOption -eq "AllScope"} | ForEach-Object { "{0} -> {1}" -f $_.Name, $_.Definition} - $currentAllScopeOptionList = $currentAliasList | Where-Object { $_.Options -band [System.Management.Automation.ScopedItemOptions]::AllScope } | Select-Object -ExpandProperty DisplayName - - $result = Compare-Object -ReferenceObject $currentAllScopeOptionList -DifferenceObject $aliasAllScopeOptionList - - # Below 'Should Be' don't show full list wrong aliases so we output them explicitly - # if all aliases is Ok we output nothing - $result | Write-Host - $result | Should -BeNullOrEmpty + $expectedAllScopeAliases = $aliasFullList.Where({$_.AllScopeOption -eq "AllScope"}).ForEach({"{0}:{1}" -f $_.Name, $_.Definition}) | Sort-Object + $observedAllScopeAliases = $currentAliasList.Where({($_.Options -as [System.Management.Automation.ScopedItemOptions]) -band $AllScopeOption}).Foreach({"{0}:{1}" -f $_.Name, $_.Definition}) | Sort-Object + $observedAllScopeAliases | Should -Be $expectedAllScopeAliases } It "All approved aliases have the correct 'ReadOnly' option" { - $aliasReadOnlyOptionList = $aliasFullList | Where-Object { $_.ReadOnlyOption -eq "ReadOnly"} | ForEach-Object { "{0} -> {1}" -f $_.Name, $_.Definition} - $currentReadOnlyOptionList = $currentAliasList | Where-Object { $_.Options -band [System.Management.Automation.ScopedItemOptions]::ReadOnly } | Select-Object -ExpandProperty DisplayName - - $result = Compare-Object -ReferenceObject $currentReadOnlyOptionList -DifferenceObject $aliasReadOnlyOptionList - - # Below 'Should Be' don't show full list wrong aliases so we output them explicitly - # if all aliases is Ok we output nothing - $result | Write-Host - $result | Should -BeNullOrEmpty + $expectedReadOnlyAliases = $aliasFullList.Where({$_.ReadOnlyOption -eq "ReadOnly"}).ForEach({"{0}:{1}" -f $_.Name, $_.Definition}) | Sort-Object + $observedReadOnlyAliases = $currentAliasList.Where({($_.Options -as [System.Management.Automation.ScopedItemOptions]) -band $ReadOnlyOption}).ForEach({"{0}:{1}" -f $_.Name, $_.Definition}) | Sort-Object + $observedReadOnlyAliases | Should -Be $expectedReadOnlyAliases } It "All approved Cmdlets present (no new Cmdlets added, no Cmdlets removed)" { - $cmdletList = $commandList | Where-Object { $_.Present -eq "True" -and $_.CommandType -eq "Cmdlet" } | Select-Object -ExpandProperty Name - - $result = (Compare-Object -ReferenceObject $currentCmdletList.Name -DifferenceObject $cmdletList).InputObject - $result | Should -BeNullOrEmpty + $expectedCmdletList = $commandList.Where({$_.Present -eq "True" -and $_.CommandType -eq "Cmdlet"}).Name | Sort-Object + $observedCmdletList = $currentCmdletList.Name | Sort-Object + $observedCmdletList | Should -Be $expectedCmdletList } - It "All present Cmdlets should have the correct ConfirmImpact" { - $CmdletList = $commandList | - Where-Object { $_.Present -eq "True" -and $_.CommandType -eq "Cmdlet"} | - Select-Object -Property Name, ConfirmImpact - - # if Preview, $currentCmdletList is deserialized, so we re-hydrate them so comparison succeeds - $currentCmdletList = $currentCmdletList | ForEach-Object { Get-Command $_.Name } | - Where-Object { $moduleList -contains $_.Source -and $null -ne $_.ImplementingType } | - Select-Object -Property Name, @{ - Name = 'ConfirmImpact' - Expression = { - if (($t = $_.ImplementingType)) { - $t.GetCustomAttributes($true).Where{$_.TypeId.Name -eq 'CmdletAttribute'}.ConfirmImpact - } - } - } - - # -PassThru is provided to give meaningful output when differences arise - $result = Compare-Object -ReferenceObject $currentCmdletList -DifferenceObject $CmdletList -Property ConfirmImpact -PassThru - $result | Should -BeNullOrEmpty + It "'' Cmdlet should have the correct ConfirmImpact ''" -TestCases $commandHashtableList { + param ( $Name, $ConfirmImpact ) + # retrieve again because we may have serialized the commandinfo + $cmdlet = Get-Command $Name + $cmdletAttribute = $cmdlet.ImplementingType.GetCustomAttributes($true).Where({$_ -is [System.Management.Automation.CmdletAttribute]}) + $impact = $cmdletAttribute.ConfirmImpact + $impact | Should -Be $ConfirmImpact } } From 9d036c4876fb078d09002eca66bf6fc7ecd9aab0 Mon Sep 17 00:00:00 2001 From: Darren Kattan <1424395+dkattan@users.noreply.github.com> Date: Mon, 10 Apr 2023 19:24:42 -0500 Subject: [PATCH 471/779] Revert "Bump Microsoft.CodeAnalysis.CSharp from 4.5.0 to 4.6.0-2.23152.6" (#19464) --- .../Microsoft.PowerShell.Commands.Utility.csproj | 2 +- .../PSVersionInfoGenerator/PSVersionInfoGenerator.csproj | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj index e9c7c102290..5170227d65f 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj +++ b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj @@ -32,7 +32,7 @@ - + diff --git a/src/System.Management.Automation/SourceGenerators/PSVersionInfoGenerator/PSVersionInfoGenerator.csproj b/src/System.Management.Automation/SourceGenerators/PSVersionInfoGenerator/PSVersionInfoGenerator.csproj index 831e38d7322..be1ad33448e 100644 --- a/src/System.Management.Automation/SourceGenerators/PSVersionInfoGenerator/PSVersionInfoGenerator.csproj +++ b/src/System.Management.Automation/SourceGenerators/PSVersionInfoGenerator/PSVersionInfoGenerator.csproj @@ -13,7 +13,7 @@ - + From 3dd943d212fd45cf38947ce6c2748b1712d271ac Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Wed, 12 Apr 2023 02:56:24 +0200 Subject: [PATCH 472/779] Detect insecure https-to-http redirect only if both URIs are absolute (#19468) --- .../Common/WebRequestPSCmdlet.Common.cs | 18 +++++++++++++----- .../WebCmdlets.Tests.ps1 | 18 ++++++++++++++++++ 2 files changed, 31 insertions(+), 5 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index f979a763da8..60ee931591a 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -592,12 +592,20 @@ protected override void ProcessRecord() OutFile = null; } - // Detect insecure redirection - if (!AllowInsecureRedirect && response.RequestMessage.RequestUri.Scheme == "https" && response.Headers.Location?.Scheme == "http") + // Detect insecure redirection. + if (!AllowInsecureRedirect) { - ErrorRecord er = new(new InvalidOperationException(), "InsecureRedirection", ErrorCategory.InvalidOperation, request); - er.ErrorDetails = new ErrorDetails(WebCmdletStrings.InsecureRedirection); - ThrowTerminatingError(er); + // We will skip detection if either of the URIs is relative, because the 'Scheme' property is not supported on a relative URI. + // If we have to skip the check, an error may be thrown later if it's actually an insecure https-to-http redirect. + bool originIsHttps = response.RequestMessage.RequestUri.IsAbsoluteUri && response.RequestMessage.RequestUri.Scheme == "https"; + bool destinationIsHttp = response.Headers.Location is not null && response.Headers.Location.IsAbsoluteUri && response.Headers.Location.Scheme == "http"; + + if (originIsHttps && destinationIsHttp) + { + ErrorRecord er = new(new InvalidOperationException(), "InsecureRedirection", ErrorCategory.InvalidOperation, request); + er.ErrorDetails = new ErrorDetails(WebCmdletStrings.InsecureRedirection); + ThrowTerminatingError(er); + } } if (ShouldCheckHttpStatus && !_isSuccess) diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 index bf4072ddfc2..5deb9308bd2 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 @@ -1149,6 +1149,15 @@ Describe "Invoke-WebRequest tests" -Tags "Feature", "RequireAdminOnWindows" { $result = ExecuteWebCommand -command $command $result.Error.FullyQualifiedErrorId | Should -Be "InsecureRedirection,Microsoft.PowerShell.Commands.InvokeWebRequestCommand" } + + It "Validate Invoke-WebRequest Https to Http (No Scheme) redirect without -AllowInsecureRedirect" { + $httpUri = Get-WebListenerUrl -Test 'Get' + $uri = Get-WebListenerUrl -Test 'Redirect' -Https -Query @{destination = $httpUri.Authority} + $command = "Invoke-WebRequest -Uri '$uri' -SkipCertificateCheck" + + $result = ExecuteWebCommand -command $command + $result.Error.FullyQualifiedErrorId | Should -Be "WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand" + } } @@ -3100,6 +3109,15 @@ Describe "Invoke-RestMethod tests" -Tags "Feature", "RequireAdminOnWindows" { $result.Error.FullyQualifiedErrorId | Should -Be "InsecureRedirection,Microsoft.PowerShell.Commands.InvokeRestMethodCommand" } + It "Validate Invoke-RestMethod Https to Http (No Scheme) redirect without -AllowInsecureRedirect" { + $httpUri = Get-WebListenerUrl -Test 'Get' + $uri = Get-WebListenerUrl -Test 'Redirect' -Https -Query @{destination = $httpUri.Authority} + $command = "Invoke-RestMethod -Uri '$uri' -SkipCertificateCheck" + + $result = ExecuteWebCommand -command $command + $result.Error.FullyQualifiedErrorId | Should -Be "WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand" + } + #endregion Redirect tests Context "Invoke-RestMethod SkipHeaderVerification Tests" { From af2f2f454efc21164cac9978d00de534dcbbd4a3 Mon Sep 17 00:00:00 2001 From: Ikko Eltociear Ashimine Date: Wed, 12 Apr 2023 13:51:22 +0900 Subject: [PATCH 473/779] Fix typo in Compiler.cs (#19491) inital -> initial --- src/System.Management.Automation/engine/parser/Compiler.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/System.Management.Automation/engine/parser/Compiler.cs b/src/System.Management.Automation/engine/parser/Compiler.cs index a262ec520a0..99b38a3fa06 100644 --- a/src/System.Management.Automation/engine/parser/Compiler.cs +++ b/src/System.Management.Automation/engine/parser/Compiler.cs @@ -3601,7 +3601,7 @@ public object VisitPipelineChain(PipelineChainAst pipelineChainAst) var dispatchTargets = new List(); var tryBodyExprs = new List() { - null, // Add a slot for the inital switch/case that we'll come back to + null, // Add a slot for the initial switch/case that we'll come back to }; // L0: dispatchIndex = 1; pipeline1 From 8ed8b5270099db08b0c1d822419b5ada28f96569 Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Wed, 12 Apr 2023 21:41:43 -0700 Subject: [PATCH 474/779] Fix a race condition in `Add-Type` (#19471) --- .../commands/utility/AddType.cs | 16 +++++++--------- .../Add-Type.Tests.ps1 | 12 ++++++++++++ 2 files changed, 19 insertions(+), 9 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs index 926d6c3dc1f..d7954178063 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs @@ -653,8 +653,8 @@ protected override void EndProcessing() // These dictionaries prevent reloading already loaded and unchanged code. // We don't worry about unbounded growing of the cache because in .Net Core 2.0 we can not unload assemblies. // TODO: review if we will be able to unload assemblies after migrating to .Net Core 2.1. - private static readonly HashSet s_sourceTypesCache = new(); - private static readonly Dictionary s_sourceAssemblyCache = new(); + private static readonly ConcurrentDictionary s_sourceTypesCache = new(); + private static readonly ConcurrentDictionary s_sourceAssemblyCache = new(); private static readonly string s_defaultSdkDirectory = Utils.DefaultPowerShellAppBase; @@ -963,7 +963,7 @@ private CompilationOptions GetDefaultCompilationOptions() } } - private bool isSourceCodeUpdated(List syntaxTrees, out Assembly assembly) + private bool IsSourceCodeUpdated(List syntaxTrees, out Assembly assembly) { Diagnostics.Assert(syntaxTrees.Count != 0, "syntaxTrees should contains a source code."); @@ -1048,7 +1048,7 @@ private void SourceCodeProcessing() { // if the source code was already compiled and loaded and not changed // we get the assembly from the cache. - if (isSourceCodeUpdated(syntaxTrees, out Assembly assembly)) + if (IsSourceCodeUpdated(syntaxTrees, out Assembly assembly)) { CompileToAssembly(syntaxTrees, compilationOptions, emitOptions); } @@ -1138,7 +1138,7 @@ public override void VisitNamedType(INamedTypeSymbol symbol) // It is namespace-fully-qualified name var symbolFullName = symbol.ToString(); - if (s_sourceTypesCache.TryGetValue(symbolFullName, out _)) + if (s_sourceTypesCache.ContainsKey(symbolFullName)) { DuplicateSymbols.Add(symbolFullName); } @@ -1153,13 +1153,13 @@ private static void CacheNewTypes(ConcurrentBag newTypes) { foreach (var typeName in newTypes) { - s_sourceTypesCache.Add(typeName); + s_sourceTypesCache.TryAdd(typeName, null); } } private void CacheAssembly(Assembly assembly) { - s_sourceAssemblyCache.Add(_syntaxTreesHash, assembly); + s_sourceAssemblyCache.TryAdd(_syntaxTreesHash, assembly); } private void DoEmitAndLoadAssembly(Compilation compilation, EmitOptions emitOptions) @@ -1178,8 +1178,6 @@ private void DoEmitAndLoadAssembly(Compilation compilation, EmitOptions emitOpti if (emitResult.Success) { - // TODO: We could use Assembly.LoadFromStream() in future. - // See https://github.com/dotnet/corefx/issues/26994 ms.Seek(0, SeekOrigin.Begin); Assembly assembly = AssemblyLoadContext.Default.LoadFromStream(ms); diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Add-Type.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Add-Type.Tests.ps1 index 72d42af1d12..c9a20b42403 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Add-Type.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Add-Type.Tests.ps1 @@ -260,4 +260,16 @@ public class AttributeTest$guid : PSCmdlet param($outputType) { Add-Type -TypeDefinition "Hello" -OutputType $outputType } | Should -Throw -ErrorId 'AssemblyTypeNotSupported,Microsoft.PowerShell.Commands.AddTypeCommand' } + + It "Can run with the same C# code simultaneously from multiple Runspaces" { + $script = { + $source = 'public class BasicTest {}' + 1..10 | ForEach-Object -ThrottleLimit 10 -Parallel { + Add-Type -TypeDefinition $using:source + } + } + + pwsh -noprofile -command $script.ToString() + $LASTEXITCODE | Should -Be 0 + } } From a8f20a36e09b07ff936156d5e73c886826f5855d Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Thu, 13 Apr 2023 14:26:25 -0700 Subject: [PATCH 475/779] Update `README.md` and `metadata.json` for release v7.2.11 and v7.3.4 (#19497) --- README.md | 54 ++++++++++++++++++++++----------------------- tools/metadata.json | 6 ++--- 2 files changed, 30 insertions(+), 30 deletions(-) diff --git a/README.md b/README.md index 2bd93a5fc9a..3dca4d501c6 100644 --- a/README.md +++ b/README.md @@ -64,33 +64,33 @@ You can also download the PowerShell binary archives for Windows, macOS and Linu | Windows (ARM) | [64-bit][rl-winarm64] (preview) | [64-bit][pv-winarm64] | [Instructions][in-arm] | | Raspbian (ARM) | [32-bit][rl-arm32]/[64-bit][rl-arm64] | [32-bit][pv-arm32]/[64-bit][pv-arm64] | [Instructions][in-raspbian] | -[lts-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.10/PowerShell-7.2.10-win-x86.msi -[lts-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.10/PowerShell-7.2.10-win-x64.msi -[lts-deb]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.10/powershell-lts_7.2.10-1.deb_amd64.deb -[lts-rh]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.10/powershell-lts-7.2.10-1.rh.x86_64.rpm -[lts-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.10/powershell-lts-7.2.10-osx-x64.pkg -[lts-macos-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.10/powershell-lts-7.2.10-osx-arm64.pkg - -[rl-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.3/PowerShell-7.3.3-win-x64.msi -[rl-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.3/PowerShell-7.3.3-win-x86.msi -[rl-deb]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.3/powershell_7.3.3-1.deb_amd64.deb -[rl-ubuntu22]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.3/powershell_7.3.3-1.deb_amd64.deb -[rl-ubuntu20]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.3/powershell_7.3.3-1.deb_amd64.deb -[rl-ubuntu18]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.3/powershell_7.3.3-1.deb_amd64.deb -[rl-debian10]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.3/powershell_7.3.3-1.deb_amd64.deb -[rl-debian11]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.3/powershell_7.3.3-1.deb_amd64.deb -[rl-centos]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.3/powershell-7.3.3-1.rh.x86_64.rpm -[rl-centos8]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.3/powershell-7.3.3-1.rh.x86_64.rpm -[rl-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.3/powershell-7.3.3-osx-x64.pkg -[rl-macos-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.3/powershell-7.3.3-osx-arm64.pkg -[rl-winarm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.3/PowerShell-7.3.3-win-arm64.zip -[rl-winx86-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.3/PowerShell-7.3.3-win-x86.zip -[rl-winx64-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.3/PowerShell-7.3.3-win-x64.zip -[rl-macos-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.3/powershell-7.3.3-osx-x64.tar.gz -[rl-macos-tar-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.3/powershell-7.3.3-osx-arm64.tar.gz -[rl-linux-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.3/powershell-7.3.3-linux-x64.tar.gz -[rl-arm32]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.3/powershell-7.3.3-linux-arm32.tar.gz -[rl-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.3/powershell-7.3.3-linux-arm64.tar.gz +[lts-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.11/PowerShell-7.2.11-win-x86.msi +[lts-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.11/PowerShell-7.2.11-win-x64.msi +[lts-deb]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.11/powershell-lts_7.2.11-1.deb_amd64.deb +[lts-rh]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.11/powershell-lts-7.2.11-1.rh.x86_64.rpm +[lts-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.11/powershell-lts-7.2.11-osx-x64.pkg +[lts-macos-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.11/powershell-lts-7.2.11-osx-arm64.pkg + +[rl-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.4/PowerShell-7.3.4-win-x64.msi +[rl-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.4/PowerShell-7.3.4-win-x86.msi +[rl-deb]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.4/powershell_7.3.4-1.deb_amd64.deb +[rl-ubuntu22]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.4/powershell_7.3.4-1.deb_amd64.deb +[rl-ubuntu20]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.4/powershell_7.3.4-1.deb_amd64.deb +[rl-ubuntu18]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.4/powershell_7.3.4-1.deb_amd64.deb +[rl-debian10]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.4/powershell_7.3.4-1.deb_amd64.deb +[rl-debian11]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.4/powershell_7.3.4-1.deb_amd64.deb +[rl-centos]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.4/powershell-7.3.4-1.rh.x86_64.rpm +[rl-centos8]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.4/powershell-7.3.4-1.rh.x86_64.rpm +[rl-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.4/powershell-7.3.4-osx-x64.pkg +[rl-macos-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.4/powershell-7.3.4-osx-arm64.pkg +[rl-winarm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.4/PowerShell-7.3.4-win-arm64.zip +[rl-winx86-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.4/PowerShell-7.3.4-win-x86.zip +[rl-winx64-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.4/PowerShell-7.3.4-win-x64.zip +[rl-macos-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.4/powershell-7.3.4-osx-x64.tar.gz +[rl-macos-tar-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.4/powershell-7.3.4-osx-arm64.tar.gz +[rl-linux-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.4/powershell-7.3.4-linux-x64.tar.gz +[rl-arm32]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.4/powershell-7.3.4-linux-arm32.tar.gz +[rl-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.4/powershell-7.3.4-linux-arm64.tar.gz [rl-snap]: https://snapcraft.io/powershell [pv-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.2/PowerShell-7.4.0-preview.2-win-x64.msi diff --git a/tools/metadata.json b/tools/metadata.json index 3c885cbb492..31a94cc7443 100644 --- a/tools/metadata.json +++ b/tools/metadata.json @@ -1,9 +1,9 @@ { - "StableReleaseTag": "v7.3.3", + "StableReleaseTag": "v7.3.4", "PreviewReleaseTag": "v7.4.0-preview.2", "ServicingReleaseTag": "v7.0.13", - "ReleaseTag": "v7.3.3", - "LTSReleaseTag" : ["v7.2.10"], + "ReleaseTag": "v7.3.4", + "LTSReleaseTag" : ["v7.2.11"], "NextReleaseTag": "v7.4.0-preview.3", "LTSRelease": { "Latest": false, "Package": false }, "StableRelease": { "Latest": false, "Package": false } From 8d4cc7b9849adbbec9d67a75f1a61cba909b6d94 Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Thu, 13 Apr 2023 14:27:15 -0700 Subject: [PATCH 476/779] Update changelogs for the `v7.2.11` and `v7.3.4` releases (#19504) --- .spelling | 1 + CHANGELOG/7.2.md | 35 +++++++++++++++++++++++++++++++++++ CHANGELOG/7.3.md | 41 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 77 insertions(+) diff --git a/.spelling b/.spelling index f211f338528..93360cfdf8b 100644 --- a/.spelling +++ b/.spelling @@ -1698,6 +1698,7 @@ ci.psm1 jcotton42 centos-7 Security.types.ps1xml +optout - ADOPTERS.md MicrosoftPowerBIMgmt - tools/clearlyDefined/readme.md diff --git a/CHANGELOG/7.2.md b/CHANGELOG/7.2.md index d1f1da8ea9e..78313f1f084 100644 --- a/CHANGELOG/7.2.md +++ b/CHANGELOG/7.2.md @@ -1,5 +1,40 @@ # 7.2 Changelog +## [7.2.11] - 2023-04-12 + +### Build and Packaging Improvements + +
    + + + +

    Bump .NET version to 6.0.16

    + +
    + +
      +
    • Update ThirdPartyNotices.txt
    • +
    • Update cgmanifest.json
    • +
    • Fix the template that creates nuget package
    • +
    • Update the wix file
    • +
    • Update .NET SDK to 6.0.408
    • +
    • Fix the build script and signing template
    • +
    • Fix stage dependencies and typo in release build (#19353)
    • +
    • Fix issues in release build and release pipeline (#19338)
    • +
    • Restructure the package build to simplify signing and packaging stages (#19321)
    • +
    • Skip VT100 tests on Windows Server 2012R2 as console does not support it (#19413)
    • +
    • Improve package management acceptance tests by not going to the gallery (#19412)
    • +
    • Test fixes for stabilizing tests (#19068)
    • +
    • Add stage for symbols job in Release build (#18937)
    • +
    • Use reference assemblies generated by dotnet (#19302)
    • +
    • Add URL for all distributions (#19159)
    • +
    • Update release pipeline to use Approvals and automate some manual tasks (#17837)
    • +
    + +
    + +[7.2.11]: https://github.com/PowerShell/PowerShell/compare/v7.2.10...v7.2.11 + ## [7.2.10] - 2023-02-23 ### Build and Packaging Improvements diff --git a/CHANGELOG/7.3.md b/CHANGELOG/7.3.md index 57c1e3b99f3..295cf217fc0 100644 --- a/CHANGELOG/7.3.md +++ b/CHANGELOG/7.3.md @@ -1,5 +1,46 @@ # 7.3 Changelog +## [7.3.4] - 2023-04-12 + +### Engine Updates and Fixes + +- Add instrumentation to `AmsiUtil` and make the `init` variable readonly (#18727) +- Fix support for `NanoServer` due to the lack of AMSI (#18882) +- Adding missing guard for telemetry optout to avoid `NullReferenceException` when importing modules (#18949) (Thanks @powercode!) +- Fix `VtSubstring` helper method to correctly check chars copied (#19240) +- Fix `ConciseView` to handle custom `ParserError` error records (#19239) + +### Build and Packaging Improvements + +
    + + + +

    Bump to use .NET 7.0.5

    + +
    + +
      +
    • Update ThirdPartyNotices.txt
    • +
    • Update cgmanifest.json
    • +
    • Fix the template that creates nuget package
    • +
    • Update the wix file
    • +
    • Update to .NET SDK 7.0.203
    • +
    • Skip VT100 tests on Windows Server 2012R2 as console does not support it (#19413)
    • +
    • Improve package management acceptance tests by not going to the gallery (#19412)
    • +
    • Fix stage dependencies and typo in release build (#19353)
    • +
    • Fix issues in release build and release pipeline (#19338)
    • +
    • Restructure the package build to simplify signing and packaging stages (#19321)
    • +
    • Test fixes for stabilizing tests (#19068)
    • +
    • Add stage for symbols job in Release build (#18937)
    • +
    • Use reference assemblies generated by dotnet (#19302)
    • +
    • Add URL for all distributions (#19159)
    • +
    + +
    + +[7.3.4]: https://github.com/PowerShell/PowerShell/compare/v7.3.3...v7.3.4 + ## [7.3.3] - 2023-02-23 ### Build and Packaging Improvements From bce0ccb070614169f44fe1e8902ec40338263d39 Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Fri, 14 Apr 2023 09:50:15 -0700 Subject: [PATCH 477/779] Make the vPack PAT library more obvious (#19505) --- tools/releaseBuild/azureDevOps/vpackRelease.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tools/releaseBuild/azureDevOps/vpackRelease.yml b/tools/releaseBuild/azureDevOps/vpackRelease.yml index 11b93b25899..8e58720c67b 100644 --- a/tools/releaseBuild/azureDevOps/vpackRelease.yml +++ b/tools/releaseBuild/azureDevOps/vpackRelease.yml @@ -16,6 +16,10 @@ variables: - name: POWERSHELL_TELEMETRY_OPTOUT value: 1 - group: Azure Blob variable group + # adds the pat to publish the vPack + # instructions to create are in the description of the library + - group: vPack + stages: - stage: prep From 420c29d12c65e49a8d76909162286c24eee11d17 Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Fri, 14 Apr 2023 10:45:10 -0700 Subject: [PATCH 478/779] Fix the regex used for package name check in `vPack` build (#19511) --- tools/releaseBuild/azureDevOps/templates/vpackReleaseJob.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/releaseBuild/azureDevOps/templates/vpackReleaseJob.yml b/tools/releaseBuild/azureDevOps/templates/vpackReleaseJob.yml index 3e58295ad8f..429daa983cd 100644 --- a/tools/releaseBuild/azureDevOps/templates/vpackReleaseJob.yml +++ b/tools/releaseBuild/azureDevOps/templates/vpackReleaseJob.yml @@ -55,7 +55,7 @@ jobs: - pwsh: | $message = @() Get-ChildItem $(System.ArtifactsDirectory)\* -recurse -include *.zip, *.msi | ForEach-Object { - if($_.Name -notmatch 'PowerShell-\d\.\d\.\d\-([a-z]*.\d+\-)?win\-(fxdependent|x64|arm32|arm64|x86|fxdependentWinDesktop)\.(msi|zip){1}') + if($_.Name -notmatch 'PowerShell-\d+\.\d+\.\d+\-([a-z]*.\d+\-)?win\-(fxdependent|x64|arm32|arm64|x86|fxdependentWinDesktop)\.(msi|zip){1}') { $messageInstance = "$($_.Name) is not a valid package name" $message += $messageInstance From 6e7c29a104658515d65ad8ee532cb53cec956809 Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Mon, 17 Apr 2023 10:45:00 -0700 Subject: [PATCH 479/779] Move PSGallery sync to a pool (#19523) --- .../azureDevOps/AzArtifactFeed/PSGalleryToAzArtifacts.yml | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/tools/releaseBuild/azureDevOps/AzArtifactFeed/PSGalleryToAzArtifacts.yml b/tools/releaseBuild/azureDevOps/AzArtifactFeed/PSGalleryToAzArtifacts.yml index 221a385b8b8..ff8dbd6d720 100644 --- a/tools/releaseBuild/azureDevOps/AzArtifactFeed/PSGalleryToAzArtifacts.yml +++ b/tools/releaseBuild/azureDevOps/AzArtifactFeed/PSGalleryToAzArtifacts.yml @@ -4,8 +4,11 @@ resources: - repo: self clean: true -queue: - name: Hosted VS2017 +pool: + name: 1es + demands: + - ImageOverride -equals PSMMS2019-Minimal + steps: - pwsh: | $minVer = [version]"2.2.3" From 236c6521628015970bec13e1616363e96f37ab1f Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Tue, 18 Apr 2023 10:58:49 -0700 Subject: [PATCH 480/779] Update `DotnetRuntimeMetadata.json` to consume the .NET 8.0.0-preview.3 release (#19529) --- DotnetRuntimeMetadata.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/DotnetRuntimeMetadata.json b/DotnetRuntimeMetadata.json index a9bd76078e4..e5d2c716694 100644 --- a/DotnetRuntimeMetadata.json +++ b/DotnetRuntimeMetadata.json @@ -1,11 +1,11 @@ { "sdk": { - "channel": "8.0.1xx-preview2", + "channel": "8.0.1xx-preview3", "quality": "daily", "qualityFallback": "preview", - "packageVersionPattern": "8.0.0-preview.2", + "packageVersionPattern": "8.0.0-preview.3", "sdkImageVersion": "8.0.100", - "nextChannel": "8.0.1xx-preview2", + "nextChannel": "8.0.1xx-preview3", "azureFeed": "", "sdkImageOverride": "" }, From e05a09734f32baf3ed1f8e4e3813b0c5fc7b6295 Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Tue, 18 Apr 2023 12:07:46 -0700 Subject: [PATCH 481/779] Force updating the transitive dependency on `Microsoft.CSharp` (#19514) --- ...crosoft.PowerShell.Commands.Utility.csproj | 4 + tools/cgmanifest.json | 570 +----------------- 2 files changed, 9 insertions(+), 565 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj index 5170227d65f..52ecbceedef 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj +++ b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj @@ -36,6 +36,10 @@ + +
    diff --git a/tools/cgmanifest.json b/tools/cgmanifest.json index a0559eaa6b6..d3845fc0502 100644 --- a/tools/cgmanifest.json +++ b/tools/cgmanifest.json @@ -1,4 +1,5 @@ { + "$schema": "https://json.schemastore.org/component-detection-manifest.json", "Registrations": [ { "Component": { @@ -85,7 +86,7 @@ "Type": "nuget", "Nuget": { "Name": "Microsoft.CSharp", - "Version": "4.3.0" + "Version": "4.7.0" } }, "DevelopmentDependency": false @@ -130,26 +131,6 @@ }, "DevelopmentDependency": false }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "Microsoft.NETCore.Platforms", - "Version": "1.1.0" - } - }, - "DevelopmentDependency": false - }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "Microsoft.NETCore.Targets", - "Version": "1.1.0" - } - }, - "DevelopmentDependency": false - }, { "Component": { "Type": "nuget", @@ -215,7 +196,7 @@ "Type": "nuget", "Nuget": { "Name": "Microsoft.Windows.Compatibility", - "Version": "7.0.0" + "Version": "7.0.1" } }, "DevelopmentDependency": false @@ -250,156 +231,6 @@ }, "DevelopmentDependency": false }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "runtime.any.System.Collections", - "Version": "4.3.0" - } - }, - "DevelopmentDependency": false - }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "runtime.any.System.Globalization", - "Version": "4.3.0" - } - }, - "DevelopmentDependency": false - }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "runtime.any.System.IO", - "Version": "4.3.0" - } - }, - "DevelopmentDependency": false - }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "runtime.any.System.Reflection.Extensions", - "Version": "4.3.0" - } - }, - "DevelopmentDependency": false - }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "runtime.any.System.Reflection.Primitives", - "Version": "4.3.0" - } - }, - "DevelopmentDependency": false - }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "runtime.any.System.Reflection", - "Version": "4.3.0" - } - }, - "DevelopmentDependency": false - }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "runtime.any.System.Resources.ResourceManager", - "Version": "4.3.0" - } - }, - "DevelopmentDependency": false - }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "runtime.any.System.Runtime.Handles", - "Version": "4.3.0" - } - }, - "DevelopmentDependency": false - }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "runtime.any.System.Runtime.InteropServices", - "Version": "4.3.0" - } - }, - "DevelopmentDependency": false - }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "runtime.any.System.Runtime", - "Version": "4.3.0" - } - }, - "DevelopmentDependency": false - }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "runtime.any.System.Text.Encoding", - "Version": "4.3.0" - } - }, - "DevelopmentDependency": false - }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "runtime.any.System.Threading.Tasks", - "Version": "4.3.0" - } - }, - "DevelopmentDependency": false - }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "runtime.debian.8-x64.runtime.native.System.Security.Cryptography.OpenSsl", - "Version": "4.3.0" - } - }, - "DevelopmentDependency": false - }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "runtime.fedora.23-x64.runtime.native.System.Security.Cryptography.OpenSsl", - "Version": "4.3.0" - } - }, - "DevelopmentDependency": false - }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "runtime.fedora.24-x64.runtime.native.System.Security.Cryptography.OpenSsl", - "Version": "4.3.0" - } - }, - "DevelopmentDependency": false - }, { "Component": { "Type": "nuget", @@ -450,46 +281,6 @@ }, "DevelopmentDependency": false }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "runtime.native.System.Security.Cryptography.OpenSsl", - "Version": "4.3.0" - } - }, - "DevelopmentDependency": false - }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "runtime.native.System", - "Version": "4.3.0" - } - }, - "DevelopmentDependency": false - }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "runtime.opensuse.13.2-x64.runtime.native.System.Security.Cryptography.OpenSsl", - "Version": "4.3.0" - } - }, - "DevelopmentDependency": false - }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "runtime.opensuse.42.1-x64.runtime.native.System.Security.Cryptography.OpenSsl", - "Version": "4.3.0" - } - }, - "DevelopmentDependency": false - }, { "Component": { "Type": "nuget", @@ -510,86 +301,6 @@ }, "DevelopmentDependency": false }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "runtime.osx.10.10-x64.runtime.native.System.Security.Cryptography.OpenSsl", - "Version": "4.3.0" - } - }, - "DevelopmentDependency": false - }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "runtime.rhel.7-x64.runtime.native.System.Security.Cryptography.OpenSsl", - "Version": "4.3.0" - } - }, - "DevelopmentDependency": false - }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "runtime.ubuntu.14.04-x64.runtime.native.System.Security.Cryptography.OpenSsl", - "Version": "4.3.0" - } - }, - "DevelopmentDependency": false - }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "runtime.ubuntu.16.04-x64.runtime.native.System.Security.Cryptography.OpenSsl", - "Version": "4.3.0" - } - }, - "DevelopmentDependency": false - }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "runtime.ubuntu.16.10-x64.runtime.native.System.Security.Cryptography.OpenSsl", - "Version": "4.3.0" - } - }, - "DevelopmentDependency": false - }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "runtime.unix.System.Diagnostics.Debug", - "Version": "4.3.0" - } - }, - "DevelopmentDependency": false - }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "runtime.unix.System.Private.Uri", - "Version": "4.3.0" - } - }, - "DevelopmentDependency": false - }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "runtime.unix.System.Runtime.Extensions", - "Version": "4.3.0" - } - }, - "DevelopmentDependency": false - }, { "Component": { "Type": "nuget", @@ -620,36 +331,6 @@ }, "DevelopmentDependency": false }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "runtime.win.System.Diagnostics.Debug", - "Version": "4.3.0" - } - }, - "DevelopmentDependency": false - }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "runtime.win.System.Runtime.Extensions", - "Version": "4.3.0" - } - }, - "DevelopmentDependency": false - }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "runtime.win7.System.Private.Uri", - "Version": "4.3.0" - } - }, - "DevelopmentDependency": false - }, { "Component": { "Type": "nuget", @@ -690,16 +371,6 @@ }, "DevelopmentDependency": false }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "System.Collections", - "Version": "4.3.0" - } - }, - "DevelopmentDependency": false - }, { "Component": { "Type": "nuget", @@ -760,16 +431,6 @@ }, "DevelopmentDependency": false }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "System.Diagnostics.Debug", - "Version": "4.3.0" - } - }, - "DevelopmentDependency": false - }, { "Component": { "Type": "nuget", @@ -840,16 +501,6 @@ }, "DevelopmentDependency": false }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "System.Dynamic.Runtime", - "Version": "4.3.0" - } - }, - "DevelopmentDependency": false - }, { "Component": { "Type": "nuget", @@ -860,16 +511,6 @@ }, "DevelopmentDependency": false }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "System.Globalization", - "Version": "4.3.0" - } - }, - "DevelopmentDependency": false - }, { "Component": { "Type": "nuget", @@ -890,42 +531,12 @@ }, "DevelopmentDependency": false }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "System.IO", - "Version": "4.3.0" - } - }, - "DevelopmentDependency": false - }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "System.Linq.Expressions", - "Version": "4.3.0" - } - }, - "DevelopmentDependency": false - }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "System.Linq", - "Version": "4.3.0" - } - }, - "DevelopmentDependency": false - }, { "Component": { "Type": "nuget", "Nuget": { "Name": "System.Management", - "Version": "7.0.0" + "Version": "7.0.1" } }, "DevelopmentDependency": false @@ -950,16 +561,6 @@ }, "DevelopmentDependency": false }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "System.ObjectModel", - "Version": "4.3.0" - } - }, - "DevelopmentDependency": false - }, { "Component": { "Type": "nuget", @@ -970,16 +571,6 @@ }, "DevelopmentDependency": false }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "System.Private.Uri", - "Version": "4.3.0" - } - }, - "DevelopmentDependency": false - }, { "Component": { "Type": "nuget", @@ -1000,46 +591,6 @@ }, "DevelopmentDependency": false }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "System.Reflection.Emit.ILGeneration", - "Version": "4.3.0" - } - }, - "DevelopmentDependency": false - }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "System.Reflection.Emit.Lightweight", - "Version": "4.3.0" - } - }, - "DevelopmentDependency": false - }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "System.Reflection.Emit", - "Version": "4.3.0" - } - }, - "DevelopmentDependency": false - }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "System.Reflection.Extensions", - "Version": "4.3.0" - } - }, - "DevelopmentDependency": false - }, { "Component": { "Type": "nuget", @@ -1050,46 +601,6 @@ }, "DevelopmentDependency": false }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "System.Reflection.Primitives", - "Version": "4.3.0" - } - }, - "DevelopmentDependency": false - }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "System.Reflection.TypeExtensions", - "Version": "4.3.0" - } - }, - "DevelopmentDependency": false - }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "System.Reflection", - "Version": "4.3.0" - } - }, - "DevelopmentDependency": false - }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "System.Resources.ResourceManager", - "Version": "4.3.0" - } - }, - "DevelopmentDependency": false - }, { "Component": { "Type": "nuget", @@ -1110,46 +621,6 @@ }, "DevelopmentDependency": false }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "System.Runtime.Extensions", - "Version": "4.3.0" - } - }, - "DevelopmentDependency": false - }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "System.Runtime.Handles", - "Version": "4.3.0" - } - }, - "DevelopmentDependency": false - }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "System.Runtime.InteropServices", - "Version": "4.3.0" - } - }, - "DevelopmentDependency": false - }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "System.Runtime", - "Version": "4.3.0" - } - }, - "DevelopmentDependency": false - }, { "Component": { "Type": "nuget", @@ -1310,16 +781,6 @@ }, "DevelopmentDependency": false }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "System.Text.Encoding", - "Version": "4.3.0" - } - }, - "DevelopmentDependency": false - }, { "Component": { "Type": "nuget", @@ -1350,26 +811,6 @@ }, "DevelopmentDependency": false }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "System.Threading.Tasks", - "Version": "4.3.0" - } - }, - "DevelopmentDependency": false - }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "System.Threading", - "Version": "4.3.0" - } - }, - "DevelopmentDependency": false - }, { "Component": { "Type": "nuget", @@ -1390,6 +831,5 @@ }, "DevelopmentDependency": false } - ], - "$schema": "https://json.schemastore.org/component-detection-manifest.json" + ] } From e1b392b6ffeaaf391c8bbc0e83bf6856940267b9 Mon Sep 17 00:00:00 2001 From: PowerShell Team Bot <69177312+pwshBot@users.noreply.github.com> Date: Tue, 18 Apr 2023 15:24:51 -0700 Subject: [PATCH 482/779] Update .NET SDK version from `8.0.100-preview.2.23157.25` to `8.0.100-preview.3.23178.7` (#19381) --- global.json | 2 +- ...oft.PowerShell.Commands.Diagnostics.csproj | 2 +- ...soft.PowerShell.Commands.Management.csproj | 2 +- ...crosoft.PowerShell.Commands.Utility.csproj | 2 +- ...crosoft.PowerShell.CoreCLR.Eventing.csproj | 2 +- .../Microsoft.PowerShell.SDK.csproj | 20 +- .../Microsoft.WSMan.Management.csproj | 2 +- .../System.Management.Automation.csproj | 16 +- .../ResultsComparer/ResultsComparer.csproj | 2 +- ...soft.PowerShell.NamedPipeConnection.csproj | 2 +- test/tools/TestService/TestService.csproj | 2 +- test/tools/WebListener/WebListener.csproj | 4 +- tools/packaging/boms/windows.json | 270 ++---------------- 13 files changed, 60 insertions(+), 268 deletions(-) diff --git a/global.json b/global.json index 845df69857c..1a6ad4fbb96 100644 --- a/global.json +++ b/global.json @@ -1,5 +1,5 @@ { "sdk": { - "version": "8.0.100-preview.2.23157.25" + "version": "8.0.100-preview.3.23178.7" } } diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/Microsoft.PowerShell.Commands.Diagnostics.csproj b/src/Microsoft.PowerShell.Commands.Diagnostics/Microsoft.PowerShell.Commands.Diagnostics.csproj index 10d4d9de8e0..46f8b45199c 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/Microsoft.PowerShell.Commands.Diagnostics.csproj +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/Microsoft.PowerShell.Commands.Diagnostics.csproj @@ -8,7 +8,7 @@ - + diff --git a/src/Microsoft.PowerShell.Commands.Management/Microsoft.PowerShell.Commands.Management.csproj b/src/Microsoft.PowerShell.Commands.Management/Microsoft.PowerShell.Commands.Management.csproj index 5a254cf199c..d5325a78bbc 100644 --- a/src/Microsoft.PowerShell.Commands.Management/Microsoft.PowerShell.Commands.Management.csproj +++ b/src/Microsoft.PowerShell.Commands.Management/Microsoft.PowerShell.Commands.Management.csproj @@ -47,7 +47,7 @@ - + diff --git a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj index 52ecbceedef..085f7cf63bc 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj +++ b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj @@ -33,7 +33,7 @@ - + - + diff --git a/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj b/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj index 67329671c88..5767001acac 100644 --- a/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj +++ b/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj @@ -19,18 +19,18 @@ - - - + + + - - - - - - + + + + + + - + diff --git a/src/Microsoft.WSMan.Management/Microsoft.WSMan.Management.csproj b/src/Microsoft.WSMan.Management/Microsoft.WSMan.Management.csproj index c80283a4533..50ad75c44ac 100644 --- a/src/Microsoft.WSMan.Management/Microsoft.WSMan.Management.csproj +++ b/src/Microsoft.WSMan.Management/Microsoft.WSMan.Management.csproj @@ -10,7 +10,7 @@ - + diff --git a/src/System.Management.Automation/System.Management.Automation.csproj b/src/System.Management.Automation/System.Management.Automation.csproj index 3110a52d623..bff75e77480 100644 --- a/src/System.Management.Automation/System.Management.Automation.csproj +++ b/src/System.Management.Automation/System.Management.Automation.csproj @@ -34,16 +34,16 @@ - - - - + + + + - + - - - + + + diff --git a/test/perf/dotnet-tools/ResultsComparer/ResultsComparer.csproj b/test/perf/dotnet-tools/ResultsComparer/ResultsComparer.csproj index 2e0c00506c9..f63f5adde24 100644 --- a/test/perf/dotnet-tools/ResultsComparer/ResultsComparer.csproj +++ b/test/perf/dotnet-tools/ResultsComparer/ResultsComparer.csproj @@ -10,6 +10,6 @@ - + diff --git a/test/tools/NamedPipeConnection/src/code/Microsoft.PowerShell.NamedPipeConnection.csproj b/test/tools/NamedPipeConnection/src/code/Microsoft.PowerShell.NamedPipeConnection.csproj index 0a5ca72e317..3959c584e8c 100644 --- a/test/tools/NamedPipeConnection/src/code/Microsoft.PowerShell.NamedPipeConnection.csproj +++ b/test/tools/NamedPipeConnection/src/code/Microsoft.PowerShell.NamedPipeConnection.csproj @@ -15,6 +15,6 @@ - + diff --git a/test/tools/TestService/TestService.csproj b/test/tools/TestService/TestService.csproj index d1d924628e3..1e25fb6b580 100644 --- a/test/tools/TestService/TestService.csproj +++ b/test/tools/TestService/TestService.csproj @@ -13,7 +13,7 @@ - + diff --git a/test/tools/WebListener/WebListener.csproj b/test/tools/WebListener/WebListener.csproj index 0a8bf752e9b..2bc28b42845 100644 --- a/test/tools/WebListener/WebListener.csproj +++ b/test/tools/WebListener/WebListener.csproj @@ -7,8 +7,8 @@ - - + + diff --git a/tools/packaging/boms/windows.json b/tools/packaging/boms/windows.json index c1d06bb2c64..dc4329e4751 100644 --- a/tools/packaging/boms/windows.json +++ b/tools/packaging/boms/windows.json @@ -1,32 +1,8 @@ [ - { - "Pattern": "_manifest/spdx_2.2/manifest.spdx.json", - "FileType": "Product" - }, - { - "Pattern": "_manifest/spdx_2.2/manifest.spdx.json.sha256", - "FileType": "Product" - }, { "Pattern": "Accessibility.dll", "FileType": "NonProduct" }, - { - "Pattern": "assets/Powershell_av_colors.ico", - "FileType": "Product" - }, - { - "Pattern": "assets/Powershell_avatar.ico", - "FileType": "Product" - }, - { - "Pattern": "assets/Powershell_black.ico", - "FileType": "Product" - }, - { - "Pattern": "assets/ps_black_32x32.ico", - "FileType": "Product" - }, { "Pattern": "clretwrc.dll", "FileType": "NonProduct" @@ -79,22 +55,6 @@ "Pattern": "cs/System.Private.ServiceModel.resources.dll", "FileType": "NonProduct" }, - { - "Pattern": "cs/System.ServiceModel.Http.resources.dll", - "FileType": "NonProduct" - }, - { - "Pattern": "cs/System.ServiceModel.NetFramingBase.resources.dll", - "FileType": "NonProduct" - }, - { - "Pattern": "cs/System.ServiceModel.NetTcp.resources.dll", - "FileType": "NonProduct" - }, - { - "Pattern": "cs/System.ServiceModel.Primitives.resources.dll", - "FileType": "NonProduct" - }, { "Pattern": "cs/System.Web.Services.Description.resources.dll", "FileType": "NonProduct" @@ -183,22 +143,6 @@ "Pattern": "de/System.Private.ServiceModel.resources.dll", "FileType": "NonProduct" }, - { - "Pattern": "de/System.ServiceModel.Http.resources.dll", - "FileType": "NonProduct" - }, - { - "Pattern": "de/System.ServiceModel.NetFramingBase.resources.dll", - "FileType": "NonProduct" - }, - { - "Pattern": "de/System.ServiceModel.NetTcp.resources.dll", - "FileType": "NonProduct" - }, - { - "Pattern": "de/System.ServiceModel.Primitives.resources.dll", - "FileType": "NonProduct" - }, { "Pattern": "de/System.Web.Services.Description.resources.dll", "FileType": "NonProduct" @@ -291,22 +235,6 @@ "Pattern": "es/System.Private.ServiceModel.resources.dll", "FileType": "NonProduct" }, - { - "Pattern": "es/System.ServiceModel.Http.resources.dll", - "FileType": "NonProduct" - }, - { - "Pattern": "es/System.ServiceModel.NetFramingBase.resources.dll", - "FileType": "NonProduct" - }, - { - "Pattern": "es/System.ServiceModel.NetTcp.resources.dll", - "FileType": "NonProduct" - }, - { - "Pattern": "es/System.ServiceModel.Primitives.resources.dll", - "FileType": "NonProduct" - }, { "Pattern": "es/System.Web.Services.Description.resources.dll", "FileType": "NonProduct" @@ -391,22 +319,6 @@ "Pattern": "fr/System.Private.ServiceModel.resources.dll", "FileType": "NonProduct" }, - { - "Pattern": "fr/System.ServiceModel.Http.resources.dll", - "FileType": "NonProduct" - }, - { - "Pattern": "fr/System.ServiceModel.NetFramingBase.resources.dll", - "FileType": "NonProduct" - }, - { - "Pattern": "fr/System.ServiceModel.NetTcp.resources.dll", - "FileType": "NonProduct" - }, - { - "Pattern": "fr/System.ServiceModel.Primitives.resources.dll", - "FileType": "NonProduct" - }, { "Pattern": "fr/System.Web.Services.Description.resources.dll", "FileType": "NonProduct" @@ -507,22 +419,6 @@ "Pattern": "it/System.Private.ServiceModel.resources.dll", "FileType": "NonProduct" }, - { - "Pattern": "it/System.ServiceModel.Http.resources.dll", - "FileType": "NonProduct" - }, - { - "Pattern": "it/System.ServiceModel.NetFramingBase.resources.dll", - "FileType": "NonProduct" - }, - { - "Pattern": "it/System.ServiceModel.NetTcp.resources.dll", - "FileType": "NonProduct" - }, - { - "Pattern": "it/System.ServiceModel.Primitives.resources.dll", - "FileType": "NonProduct" - }, { "Pattern": "it/System.Web.Services.Description.resources.dll", "FileType": "NonProduct" @@ -607,22 +503,6 @@ "Pattern": "ja/System.Private.ServiceModel.resources.dll", "FileType": "NonProduct" }, - { - "Pattern": "ja/System.ServiceModel.Http.resources.dll", - "FileType": "NonProduct" - }, - { - "Pattern": "ja/System.ServiceModel.NetFramingBase.resources.dll", - "FileType": "NonProduct" - }, - { - "Pattern": "ja/System.ServiceModel.NetTcp.resources.dll", - "FileType": "NonProduct" - }, - { - "Pattern": "ja/System.ServiceModel.Primitives.resources.dll", - "FileType": "NonProduct" - }, { "Pattern": "ja/System.Web.Services.Description.resources.dll", "FileType": "NonProduct" @@ -707,22 +587,6 @@ "Pattern": "ko/System.Private.ServiceModel.resources.dll", "FileType": "NonProduct" }, - { - "Pattern": "ko/System.ServiceModel.Http.resources.dll", - "FileType": "NonProduct" - }, - { - "Pattern": "ko/System.ServiceModel.NetFramingBase.resources.dll", - "FileType": "NonProduct" - }, - { - "Pattern": "ko/System.ServiceModel.NetTcp.resources.dll", - "FileType": "NonProduct" - }, - { - "Pattern": "ko/System.ServiceModel.Primitives.resources.dll", - "FileType": "NonProduct" - }, { "Pattern": "ko/System.Web.Services.Description.resources.dll", "FileType": "NonProduct" @@ -775,10 +639,6 @@ "Pattern": "ko/WindowsFormsIntegration.resources.dll", "FileType": "NonProduct" }, - { - "Pattern": "LICENSE.txt", - "FileType": "Product" - }, { "Pattern": "Markdig.Signed.dll", "FileType": "NonProduct" @@ -1063,22 +923,6 @@ "Pattern": "pl/System.Private.ServiceModel.resources.dll", "FileType": "NonProduct" }, - { - "Pattern": "pl/System.ServiceModel.Http.resources.dll", - "FileType": "NonProduct" - }, - { - "Pattern": "pl/System.ServiceModel.NetFramingBase.resources.dll", - "FileType": "NonProduct" - }, - { - "Pattern": "pl/System.ServiceModel.NetTcp.resources.dll", - "FileType": "NonProduct" - }, - { - "Pattern": "pl/System.ServiceModel.Primitives.resources.dll", - "FileType": "NonProduct" - }, { "Pattern": "pl/System.Web.Services.Description.resources.dll", "FileType": "NonProduct" @@ -1251,22 +1095,6 @@ "Pattern": "pt-BR/System.Private.ServiceModel.resources.dll", "FileType": "NonProduct" }, - { - "Pattern": "pt-BR/System.ServiceModel.Http.resources.dll", - "FileType": "NonProduct" - }, - { - "Pattern": "pt-BR/System.ServiceModel.NetFramingBase.resources.dll", - "FileType": "NonProduct" - }, - { - "Pattern": "pt-BR/System.ServiceModel.NetTcp.resources.dll", - "FileType": "NonProduct" - }, - { - "Pattern": "pt-BR/System.ServiceModel.Primitives.resources.dll", - "FileType": "NonProduct" - }, { "Pattern": "pt-BR/System.Web.Services.Description.resources.dll", "FileType": "NonProduct" @@ -2023,22 +1851,6 @@ "Pattern": "ru/System.Private.ServiceModel.resources.dll", "FileType": "NonProduct" }, - { - "Pattern": "ru/System.ServiceModel.Http.resources.dll", - "FileType": "NonProduct" - }, - { - "Pattern": "ru/System.ServiceModel.NetFramingBase.resources.dll", - "FileType": "NonProduct" - }, - { - "Pattern": "ru/System.ServiceModel.NetTcp.resources.dll", - "FileType": "NonProduct" - }, - { - "Pattern": "ru/System.ServiceModel.Primitives.resources.dll", - "FileType": "NonProduct" - }, { "Pattern": "ru/System.Web.Services.Description.resources.dll", "FileType": "NonProduct" @@ -2940,15 +2752,15 @@ "FileType": "NonProduct" }, { - "Pattern": "System.ServiceModel.Duplex.dll", + "Pattern": "System.ServiceModel.dll", "FileType": "NonProduct" }, { - "Pattern": "System.ServiceModel.Http.dll", + "Pattern": "System.ServiceModel.Duplex.dll", "FileType": "NonProduct" }, { - "Pattern": "System.ServiceModel.NetFramingBase.dll", + "Pattern": "System.ServiceModel.Http.dll", "FileType": "NonProduct" }, { @@ -3187,22 +2999,6 @@ "Pattern": "tr/System.Private.ServiceModel.resources.dll", "FileType": "NonProduct" }, - { - "Pattern": "tr/System.ServiceModel.Http.resources.dll", - "FileType": "NonProduct" - }, - { - "Pattern": "tr/System.ServiceModel.NetFramingBase.resources.dll", - "FileType": "NonProduct" - }, - { - "Pattern": "tr/System.ServiceModel.NetTcp.resources.dll", - "FileType": "NonProduct" - }, - { - "Pattern": "tr/System.ServiceModel.Primitives.resources.dll", - "FileType": "NonProduct" - }, { "Pattern": "tr/System.Web.Services.Description.resources.dll", "FileType": "NonProduct" @@ -3319,22 +3115,6 @@ "Pattern": "zh-Hans/System.Private.ServiceModel.resources.dll", "FileType": "NonProduct" }, - { - "Pattern": "zh-Hans/System.ServiceModel.Http.resources.dll", - "FileType": "NonProduct" - }, - { - "Pattern": "zh-Hans/System.ServiceModel.NetFramingBase.resources.dll", - "FileType": "NonProduct" - }, - { - "Pattern": "zh-Hans/System.ServiceModel.NetTcp.resources.dll", - "FileType": "NonProduct" - }, - { - "Pattern": "zh-Hans/System.ServiceModel.Primitives.resources.dll", - "FileType": "NonProduct" - }, { "Pattern": "zh-Hans/System.Web.Services.Description.resources.dll", "FileType": "NonProduct" @@ -3419,22 +3199,6 @@ "Pattern": "zh-Hant/System.Private.ServiceModel.resources.dll", "FileType": "NonProduct" }, - { - "Pattern": "zh-Hant/System.ServiceModel.Http.resources.dll", - "FileType": "NonProduct" - }, - { - "Pattern": "zh-Hant/System.ServiceModel.NetFramingBase.resources.dll", - "FileType": "NonProduct" - }, - { - "Pattern": "zh-Hant/System.ServiceModel.NetTcp.resources.dll", - "FileType": "NonProduct" - }, - { - "Pattern": "zh-Hant/System.ServiceModel.Primitives.resources.dll", - "FileType": "NonProduct" - }, { "Pattern": "zh-Hant/System.Web.Services.Description.resources.dll", "FileType": "NonProduct" @@ -3487,6 +3251,30 @@ "Pattern": "zh-Hant/WindowsFormsIntegration.resources.dll", "FileType": "NonProduct" }, + { + "Pattern": "_manifest/spdx_2.2/manifest.spdx.json", + "FileType": "Product" + }, + { + "Pattern": "_manifest/spdx_2.2/manifest.spdx.json.sha256", + "FileType": "Product" + }, + { + "Pattern": "assets/Powershell_av_colors.ico", + "FileType": "Product" + }, + { + "Pattern": "assets/Powershell_avatar.ico", + "FileType": "Product" + }, + { + "Pattern": "assets/Powershell_black.ico", + "FileType": "Product" + }, + { + "Pattern": "assets/ps_black_32x32.ico", + "FileType": "Product" + }, { "Pattern": "Install-PowerShellRemoting.ps1", "FileType": "Product" @@ -3495,6 +3283,10 @@ "Pattern": "InstallPSCorePolicyDefinitions.ps1", "FileType": "Product" }, + { + "Pattern": "LICENSE.txt", + "FileType": "Product" + }, { "Pattern": "Microsoft.Management.Infrastructure.CimCmdlets.dll", "FileType": "Product" From d028da3e032de8261a27beb6a784d22f58abea23 Mon Sep 17 00:00:00 2001 From: PowerShell Team Bot <69177312+pwshBot@users.noreply.github.com> Date: Tue, 18 Apr 2023 15:40:13 -0700 Subject: [PATCH 483/779] Update the cgmanifest (#19465) --- tools/cgmanifest.json | 26 +++----------------------- 1 file changed, 3 insertions(+), 23 deletions(-) diff --git a/tools/cgmanifest.json b/tools/cgmanifest.json index d3845fc0502..2e1f79bbdd2 100644 --- a/tools/cgmanifest.json +++ b/tools/cgmanifest.json @@ -1,5 +1,4 @@ { - "$schema": "https://json.schemastore.org/component-detection-manifest.json", "Registrations": [ { "Component": { @@ -566,7 +565,7 @@ "Type": "nuget", "Nuget": { "Name": "System.Private.ServiceModel", - "Version": "4.10.0" + "Version": "4.10.2" } }, "DevelopmentDependency": false @@ -701,16 +700,6 @@ }, "DevelopmentDependency": false }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "System.ServiceModel.NetFramingBase", - "Version": "6.0.0-preview1.23060.3" - } - }, - "DevelopmentDependency": false - }, { "Component": { "Type": "nuget", @@ -801,16 +790,6 @@ }, "DevelopmentDependency": false }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "System.Threading.Tasks.Extensions", - "Version": "4.5.4" - } - }, - "DevelopmentDependency": false - }, { "Component": { "Type": "nuget", @@ -831,5 +810,6 @@ }, "DevelopmentDependency": false } - ] + ], + "$schema": "https://json.schemastore.org/component-detection-manifest.json" } From 457606af9424a86081e47f30f65f80b2a8b13638 Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Tue, 18 Apr 2023 17:15:09 -0700 Subject: [PATCH 484/779] Support trigger registration in feedback provider (#19525) --- .../FeedbackSubsystem/FeedbackHub.cs | 208 +++++++++++++----- .../FeedbackSubsystem/IFeedbackProvider.cs | 202 +++++++++++++---- test/xUnit/csharp/test_Feedback.cs | 4 +- test/xUnit/csharp/test_Subsystem.cs | 2 +- 4 files changed, 311 insertions(+), 105 deletions(-) diff --git a/src/System.Management.Automation/engine/Subsystem/FeedbackSubsystem/FeedbackHub.cs b/src/System.Management.Automation/engine/Subsystem/FeedbackSubsystem/FeedbackHub.cs index fa12c0ca751..7dfe79a2cd9 100644 --- a/src/System.Management.Automation/engine/Subsystem/FeedbackSubsystem/FeedbackHub.cs +++ b/src/System.Management.Automation/engine/Subsystem/FeedbackSubsystem/FeedbackHub.cs @@ -3,10 +3,10 @@ #nullable enable -using System; using System.Collections; using System.Collections.Generic; -using System.Management.Automation.Internal; +using System.Diagnostics.CodeAnalysis; +using System.Management.Automation.Language; using System.Management.Automation.Runspaces; using System.Threading; using System.Threading.Tasks; @@ -62,61 +62,54 @@ public static class FeedbackHub { ArgumentOutOfRangeException.ThrowIfNegativeOrZero(millisecondsTimeout); - var localRunspace = runspace as LocalRunspace; - if (localRunspace is null) + if (runspace is not LocalRunspace localRunspace) { return null; } - // Get the last value of $? - bool questionMarkValue = localRunspace.ExecutionContext.QuestionMarkVariableValue; - if (questionMarkValue) - { - return null; - } - - // Get the last history item - HistoryInfo[] histories = localRunspace.History.GetEntries(id: 0, count: 1, newest: true); - if (histories.Length == 0) + var providers = SubsystemManager.GetSubsystems(); + if (providers.Count is 0) { return null; } - HistoryInfo lastHistory = histories[0]; + ExecutionContext executionContext = localRunspace.ExecutionContext; + bool questionMarkValue = executionContext.QuestionMarkVariableValue; - // Get the last error - ArrayList errorList = (ArrayList)localRunspace.ExecutionContext.DollarErrorVariable; - if (errorList.Count == 0) + // The command line would have run successfully in most cases during an interactive use of the shell. + // So, we do a quick check to see whether we can skip proceeding, so as to avoid unneeded allocations + // from the 'TryGetFeedbackContext' call below. + if (questionMarkValue && CanSkip(providers)) { return null; } - var lastError = errorList[0] as ErrorRecord; - if (lastError is null && errorList[0] is RuntimeException rtEx) - { - lastError = rtEx.ErrorRecord; - } - - if (lastError?.InvocationInfo is null || lastError.InvocationInfo.HistoryId != lastHistory.Id) + // Get the last history item + HistoryInfo[] histories = localRunspace.History.GetEntries(id: 0, count: 1, newest: true); + if (histories.Length is 0) { return null; } - var providers = SubsystemManager.GetSubsystems(); - int count = providers.Count; - if (count == 0) + // Try creating the feedback context object. + if (!TryGetFeedbackContext(executionContext, questionMarkValue, histories[0], out FeedbackContext? feedbackContext)) { return null; } + int count = providers.Count; IFeedbackProvider? generalFeedback = null; List>? tasks = null; CancellationTokenSource? cancellationSource = null; Func? callBack = null; - for (int i = 0; i < providers.Count; i++) + foreach (IFeedbackProvider provider in providers) { - IFeedbackProvider provider = providers[i]; + if (!provider.Trigger.HasFlag(feedbackContext.Trigger)) + { + continue; + } + if (provider is GeneralCommandErrorFeedback) { // This built-in feedback provider needs to run on the target Runspace. @@ -128,7 +121,7 @@ public static class FeedbackHub { tasks = new List>(capacity: count); cancellationSource = new CancellationTokenSource(); - callBack = GetCallBack(lastHistory.CommandLine, lastError, cancellationSource); + callBack = GetCallBack(feedbackContext, cancellationSource); } // Other feedback providers will run on background threads in parallel. @@ -151,33 +144,11 @@ public static class FeedbackHub List? resultList = null; if (generalFeedback is not null) { - bool changedDefault = false; - Runspace? oldDefault = Runspace.DefaultRunspace; - - try - { - if (oldDefault != localRunspace) - { - changedDefault = true; - Runspace.DefaultRunspace = localRunspace; - } - - FeedbackItem? item = generalFeedback.GetFeedback(lastHistory.CommandLine, lastError, CancellationToken.None); - if (item is not null) - { - resultList ??= new List(count); - resultList.Add(new FeedbackResult(generalFeedback.Id, generalFeedback.Name, item)); - } - } - finally + FeedbackResult? builtInResult = GetBuiltInFeedback(generalFeedback, localRunspace, feedbackContext, questionMarkValue); + if (builtInResult is not null) { - if (changedDefault) - { - Runspace.DefaultRunspace = oldDefault; - } - - // Restore $? for the target Runspace. - localRunspace.ExecutionContext.QuestionMarkVariableValue = questionMarkValue; + resultList ??= new List(count); + resultList.Add(builtInResult); } } @@ -210,17 +181,134 @@ public static class FeedbackHub return resultList; } + private static bool CanSkip(IEnumerable providers) + { + const FeedbackTrigger possibleTriggerOnSuccess = FeedbackTrigger.Success | FeedbackTrigger.Comment; + + bool canSkip = true; + foreach (IFeedbackProvider provider in providers) + { + if ((provider.Trigger & possibleTriggerOnSuccess) != 0) + { + canSkip = false; + break; + } + } + + return canSkip; + } + + private static FeedbackResult? GetBuiltInFeedback( + IFeedbackProvider builtInFeedback, + LocalRunspace localRunspace, + FeedbackContext feedbackContext, + bool questionMarkValue) + { + bool changedDefault = false; + Runspace? oldDefault = Runspace.DefaultRunspace; + + try + { + if (oldDefault != localRunspace) + { + changedDefault = true; + Runspace.DefaultRunspace = localRunspace; + } + + FeedbackItem? item = builtInFeedback.GetFeedback(feedbackContext, CancellationToken.None); + if (item is not null) + { + return new FeedbackResult(builtInFeedback.Id, builtInFeedback.Name, item); + } + } + finally + { + if (changedDefault) + { + Runspace.DefaultRunspace = oldDefault; + } + + // Restore $? for the target Runspace. + localRunspace.ExecutionContext.QuestionMarkVariableValue = questionMarkValue; + } + + return null; + } + + private static bool TryGetFeedbackContext( + ExecutionContext executionContext, + bool questionMarkValue, + HistoryInfo lastHistory, + [NotNullWhen(true)] out FeedbackContext? feedbackContext) + { + feedbackContext = null; + Ast ast = Parser.ParseInput(lastHistory.CommandLine, out Token[] tokens, out _); + + FeedbackTrigger trigger; + ErrorRecord? lastError = null; + + if (IsPureComment(tokens)) + { + trigger = FeedbackTrigger.Comment; + } + else if (questionMarkValue) + { + trigger = FeedbackTrigger.Success; + } + else if (TryGetLastError(executionContext, lastHistory, out lastError)) + { + trigger = lastError.FullyQualifiedErrorId is "CommandNotFoundException" + ? FeedbackTrigger.CommandNotFound + : FeedbackTrigger.Error; + } + else + { + return false; + } + + PathInfo cwd = executionContext.SessionState.Path.CurrentLocation; + feedbackContext = new(trigger, ast, tokens, cwd, lastError); + return true; + } + + private static bool IsPureComment(Token[] tokens) + { + return tokens.Length is 2 && tokens[0].Kind is TokenKind.Comment && tokens[1].Kind is TokenKind.EndOfInput; + } + + private static bool TryGetLastError(ExecutionContext context, HistoryInfo lastHistory, [NotNullWhen(true)] out ErrorRecord? lastError) + { + lastError = null; + ArrayList errorList = (ArrayList)context.DollarErrorVariable; + if (errorList.Count == 0) + { + return false; + } + + lastError = errorList[0] as ErrorRecord; + if (lastError is null && errorList[0] is RuntimeException rtEx) + { + lastError = rtEx.ErrorRecord; + } + + if (lastError?.InvocationInfo is null || lastError.InvocationInfo.HistoryId != lastHistory.Id) + { + return false; + } + + return true; + } + // A local helper function to avoid creating an instance of the generated delegate helper class // when no feedback provider is registered. private static Func GetCallBack( - string commandLine, - ErrorRecord lastError, + FeedbackContext feedbackContext, CancellationTokenSource cancellationSource) { return state => { var provider = (IFeedbackProvider)state!; - var item = provider.GetFeedback(commandLine, lastError, cancellationSource.Token); + var item = provider.GetFeedback(feedbackContext, cancellationSource.Token); return item is null ? null : new FeedbackResult(provider.Id, provider.Name, item); }; } diff --git a/src/System.Management.Automation/engine/Subsystem/FeedbackSubsystem/IFeedbackProvider.cs b/src/System.Management.Automation/engine/Subsystem/FeedbackSubsystem/IFeedbackProvider.cs index 4a680f30db6..d028e5baa62 100644 --- a/src/System.Management.Automation/engine/Subsystem/FeedbackSubsystem/IFeedbackProvider.cs +++ b/src/System.Management.Automation/engine/Subsystem/FeedbackSubsystem/IFeedbackProvider.cs @@ -4,15 +4,48 @@ #nullable enable using System.Collections.Generic; -using System.Diagnostics; using System.IO; using System.Management.Automation.Internal; +using System.Management.Automation.Language; using System.Management.Automation.Runspaces; -using System.Management.Automation.Subsystem.Prediction; using System.Threading; namespace System.Management.Automation.Subsystem.Feedback { + /// + /// Types of trigger for the feedback provider. + /// + [Flags] + public enum FeedbackTrigger + { + /// + /// The last command line is comment only. + /// + Comment = 0x0001, + + /// + /// The last command line executed successfully. + /// + Success = 0x0002, + + /// + /// The last command line failed due to a command-not-found error. + /// This is a special case of . + /// + CommandNotFound = 0x0004, + + /// + /// The last command line failed with an error record. + /// This includes the case of command-not-found error. + /// + Error = CommandNotFound | 0x0008, + + /// + /// All possible triggers. + /// + All = Comment | Success | Error + } + /// /// Layout for displaying the recommended actions. /// @@ -29,6 +62,84 @@ public enum FeedbackDisplayLayout Landscape, } + /// + /// Context information about the last command line. + /// + public sealed class FeedbackContext + { + /// + /// Gets the feedback trigger. + /// + public FeedbackTrigger Trigger { get; } + + /// + /// Gets the last command line that was just executed. + /// + public string CommandLine { get; } + + /// + /// Gets the abstract syntax tree (AST) generated from parsing the last command line. + /// + public Ast CommandLineAst { get; } + + /// + /// Gets the tokens generated from parsing the last command line. + /// + public IReadOnlyList CommandLineTokens { get; } + + /// + /// Gets the current location of the default session. + /// + public PathInfo CurrentLocation { get; } + + /// + /// Gets the last error record generated from executing the last command line. + /// + public ErrorRecord? LastError { get; } + + /// + /// Initializes a new instance of the class. + /// + /// The trigger of this feedback call. + /// The command line that was just executed. + /// The current location of the default session. + /// The error that was triggerd by the last command line. + public FeedbackContext(FeedbackTrigger trigger, string commandLine, PathInfo cwd, ErrorRecord? lastError) + { + ArgumentException.ThrowIfNullOrEmpty(commandLine); + ArgumentNullException.ThrowIfNull(cwd); + + Trigger = trigger; + CommandLine = commandLine; + CommandLineAst = Parser.ParseInput(commandLine, out Token[] tokens, out _); + CommandLineTokens = tokens; + LastError = lastError; + CurrentLocation = cwd; + } + + /// + /// Initializes a new instance of the class. + /// + /// The trigger of this feedback call. + /// The abstract syntax tree (AST) from parsing the last command line. + /// The tokens from parsing the last command line. + /// The current location of the default session. + /// The error that was triggerd by the last command line. + public FeedbackContext(FeedbackTrigger trigger, Ast commandLineAst, Token[] commandLineTokens, PathInfo cwd, ErrorRecord? lastError) + { + ArgumentNullException.ThrowIfNull(commandLineAst); + ArgumentNullException.ThrowIfNull(commandLineTokens); + ArgumentNullException.ThrowIfNull(cwd); + + Trigger = trigger; + CommandLine = commandLineAst.Extent.Text; + CommandLineAst = commandLineAst; + CommandLineTokens = commandLineTokens; + LastError = lastError; + CurrentLocation = cwd; + } + } + /// /// The class represents a feedback item generated by the feedback provider. /// @@ -108,14 +219,21 @@ public interface IFeedbackProvider : ISubsystem ///
    Dictionary? ISubsystem.FunctionsToDefine => null; + /// + /// Gets the types of trigger for this feedback provider. + /// + /// + /// The default implementation triggers a feedback provider by only. + /// + FeedbackTrigger Trigger => FeedbackTrigger.CommandNotFound; + /// /// Gets feedback based on the given commandline and error record. /// - /// The command line that was just executed. - /// The error that was triggerd by the command line. + /// The context for the feedback call. /// The cancellation token to cancel the operation. /// The feedback item. - FeedbackItem? GetFeedback(string commandLine, ErrorRecord lastError, CancellationToken token); + FeedbackItem? GetFeedback(FeedbackContext context, CancellationToken token); } internal sealed class GeneralCommandErrorFeedback : IFeedbackProvider @@ -133,7 +251,7 @@ internal GeneralCommandErrorFeedback() public string Description => "The built-in general feedback source for command errors."; - public FeedbackItem? GetFeedback(string commandLine, ErrorRecord lastError, CancellationToken token) + public FeedbackItem? GetFeedback(FeedbackContext context, CancellationToken token) { var rsToUse = Runspace.DefaultRunspace; if (rsToUse is null) @@ -141,47 +259,47 @@ internal GeneralCommandErrorFeedback() return null; } - if (lastError.FullyQualifiedErrorId == "CommandNotFoundException") - { - EngineIntrinsics context = rsToUse.ExecutionContext.EngineIntrinsics; + // This feedback provider is only triggered by 'CommandNotFound' error, so the + // 'LastError' property is guaranteed to be not null. + ErrorRecord lastError = context.LastError!; + SessionState sessionState = rsToUse.ExecutionContext.SessionState; - var target = (string)lastError.TargetObject; - CommandInvocationIntrinsics invocation = context.SessionState.InvokeCommand; + var target = (string)lastError.TargetObject; + CommandInvocationIntrinsics invocation = sessionState.InvokeCommand; - // See if target is actually an executable file in current directory. - var localTarget = Path.Combine(".", target); - var command = invocation.GetCommand( - localTarget, - CommandTypes.Application | CommandTypes.ExternalScript); + // See if target is actually an executable file in current directory. + var localTarget = Path.Combine(".", target); + var command = invocation.GetCommand( + localTarget, + CommandTypes.Application | CommandTypes.ExternalScript); - if (command is not null) - { - return new FeedbackItem( - StringUtil.Format(SuggestionStrings.Suggestion_CommandExistsInCurrentDirectory, target), - new List { localTarget }); - } + if (command is not null) + { + return new FeedbackItem( + StringUtil.Format(SuggestionStrings.Suggestion_CommandExistsInCurrentDirectory, target), + new List { localTarget }); + } + + // Check fuzzy matching command names. + if (ExperimentalFeature.IsEnabled("PSCommandNotFoundSuggestion")) + { + var pwsh = PowerShell.Create(RunspaceMode.CurrentRunspace); + var results = pwsh.AddCommand("Get-Command") + .AddParameter("UseFuzzyMatching") + .AddParameter("FuzzyMinimumDistance", 1) + .AddParameter("Name", target) + .AddCommand("Select-Object") + .AddParameter("First", 5) + .AddParameter("Unique") + .AddParameter("ExpandProperty", "Name") + .Invoke(); - // Check fuzzy matching command names. - if (ExperimentalFeature.IsEnabled("PSCommandNotFoundSuggestion")) + if (results.Count > 0) { - var pwsh = PowerShell.Create(RunspaceMode.CurrentRunspace); - var results = pwsh.AddCommand("Get-Command") - .AddParameter("UseFuzzyMatching") - .AddParameter("FuzzyMinimumDistance", 1) - .AddParameter("Name", target) - .AddCommand("Select-Object") - .AddParameter("First", 5) - .AddParameter("Unique") - .AddParameter("ExpandProperty", "Name") - .Invoke(); - - if (results.Count > 0) - { - return new FeedbackItem( - SuggestionStrings.Suggestion_CommandNotFound, - new List(results), - FeedbackDisplayLayout.Landscape); - } + return new FeedbackItem( + SuggestionStrings.Suggestion_CommandNotFound, + new List(results), + FeedbackDisplayLayout.Landscape); } } diff --git a/test/xUnit/csharp/test_Feedback.cs b/test/xUnit/csharp/test_Feedback.cs index b3c1fb08ecf..2c90118be55 100644 --- a/test/xUnit/csharp/test_Feedback.cs +++ b/test/xUnit/csharp/test_Feedback.cs @@ -43,7 +43,7 @@ private MyFeedback(Guid id, string name, string description, bool delay) public string Description => _description; - public FeedbackItem GetFeedback(string commandLine, ErrorRecord errorRecord, CancellationToken token) + public FeedbackItem GetFeedback(FeedbackContext context, CancellationToken token) { if (_delay) { @@ -54,7 +54,7 @@ public FeedbackItem GetFeedback(string commandLine, ErrorRecord errorRecord, Can return new FeedbackItem( "slow-feedback-caption", - new List { $"{commandLine}+{errorRecord.FullyQualifiedErrorId}" }); + new List { $"{context.CommandLine}+{context.LastError.FullyQualifiedErrorId}" }); } } diff --git a/test/xUnit/csharp/test_Subsystem.cs b/test/xUnit/csharp/test_Subsystem.cs index 2889bab378b..41f7b6c9e69 100644 --- a/test/xUnit/csharp/test_Subsystem.cs +++ b/test/xUnit/csharp/test_Subsystem.cs @@ -65,7 +65,7 @@ private MyCompositeSubsystem(Guid id) #region IFeedbackProvider - public FeedbackItem GetFeedback(string commandLine, ErrorRecord errorRecord, CancellationToken token) => new FeedbackItem("nothing", null); + public FeedbackItem GetFeedback(FeedbackContext context, CancellationToken token) => new FeedbackItem("nothing", null); #endregion From 5e96ed38225c702e96cb584367cf1df925e36cc3 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Tue, 18 Apr 2023 17:15:51 -0700 Subject: [PATCH 485/779] Change the arrow used in feedback suggestion to a more common Unicode character (#19534) --- .../engine/hostifaces/HostUtilities.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs b/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs index 01d1f4c1bac..4398269842b 100644 --- a/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs +++ b/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs @@ -42,7 +42,7 @@ public static class HostUtilities { #region Internal Access - private static readonly char s_actionIndicator = HostSupportUnicode() ? '\u2b9e' : '>'; + private static readonly char s_actionIndicator = HostSupportUnicode() ? '\u27a4' : '>'; private static readonly string s_checkForCommandInCurrentDirectoryScript = @" [System.Diagnostics.DebuggerHidden()] From e0eb5ca4070090329f0cb570c427d1bc176eb8fb Mon Sep 17 00:00:00 2001 From: PowerShell Team Bot <69177312+pwshBot@users.noreply.github.com> Date: Wed, 19 Apr 2023 15:24:11 -0700 Subject: [PATCH 486/779] Update to the latest NOTICES file (#19537) --- ThirdPartyNotices.txt | 294 ++++++++++++------------------------------ 1 file changed, 84 insertions(+), 210 deletions(-) diff --git a/ThirdPartyNotices.txt b/ThirdPartyNotices.txt index a03f292a93d..5a815440a4a 100644 --- a/ThirdPartyNotices.txt +++ b/ThirdPartyNotices.txt @@ -278,6 +278,59 @@ The above copyright notice and this permission notice shall be included in all c THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +--------------------------------------------------------- + +--------------------------------------------------------- + +Microsoft.CSharp 4.7.0 - MIT + + +(c) Microsoft Corporation. +Copyright (c) .NET Foundation. +Copyright (c) 2011, Google Inc. +(c) 1997-2005 Sean Eron Anderson. +Copyright (c) 2007 James Newton-King +Copyright (c) 1991-2017 Unicode, Inc. +Copyright (c) 2013-2017, Alfred Klomp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2005-2007, Nick Galbreath +Portions (c) International Organization +Copyright (c) 2015 The Chromium Authors. +Copyright (c) 2004-2006 Intel Corporation +Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) .NET Foundation Contributors +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2011 Novell, Inc (http://www.novell.com) +Copyright (c) 1995-2017 Jean-loup Gailly and Mark Adler +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors. +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers THIS WORK IS PROVIDED AS + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + --------------------------------------------------------- --------------------------------------------------------- @@ -589,87 +642,6 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ---------------------------------------------------------- - ---------------------------------------------------------- - -Microsoft.Windows.Compatibility 7.0.0 - MIT - - -(c) Microsoft Corporation -Copyright (c) Andrew Arnott -Copyright 2019 LLVM Project -Copyright 2018 Daniel Lemire -Copyright (c) .NET Foundation -Copyright (c) 2011, Google Inc. -Copyright (c) 2020 Dan Shechter -(c) 1997-2005 Sean Eron Anderson -Copyright (c) 1998 Microsoft. To -Copyright (c) 2017 Yoshifumi Kawai -Copyright (c) 2005-2020 Rich Felker -Copyright (c) Microsoft Corporation -Copyright (c) 2007 James Newton-King -Copyright (c) 2012-2014, Yann Collet -Copyright (c) 1991-2022 Unicode, Inc. -Copyright (c) 2013-2017, Alfred Klomp -Copyright 2012 the V8 project authors -Copyright (c) 1999 Lucent Technologies -Copyright (c) 2008-2016, Wojciech Mula -Copyright (c) 2011-2020 Microsoft Corp -Copyright (c) 2015-2017, Wojciech Mula -Copyright (c) 2021 csFastFloat authors -Copyright (c) 2005-2007, Nick Galbreath -Copyright (c) 2015 The Chromium Authors -Copyright (c) 2018 Alexander Chermyanin -Copyright (c) The Internet Society 1997 -Portions (c) International Organization -Copyright (c) 2004-2006 Intel Corporation -Copyright (c) 2013-2017, Milosz Krajewski -Copyright (c) 2016-2017, Matthieu Darbois -Copyright (c) The Internet Society (2003) -Copyright (c) .NET Foundation Contributors -Copyright (c) 2020 Mara Bos -Copyright (c) .NET Foundation and Contributors -Copyright (c) 2008-2020 Advanced Micro Devices, Inc. -Copyright (c) 2019 Microsoft Corporation, Daan Leijen -Copyright (c) 2011 Novell, Inc (http://www.novell.com) -Copyright (c) 1995-2022 Jean-loup Gailly and Mark Adler -Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) -Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors -Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com -Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. -Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers -Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip -Copyright (c) 1980, 1986, 1993 The Regents of the University of California -Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California -Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass -Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass. To - -The MIT License (MIT) - -Copyright (c) .NET Foundation and Contributors - -All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - - --------------------------------------------------------- --------------------------------------------------------- @@ -692,7 +664,7 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI --------------------------------------------------------- -Newtonsoft.Json 13.0.2 - MIT +Newtonsoft.Json 13.0.3 - MIT Copyright James Newton-King 2008 @@ -1895,40 +1867,7 @@ SOFTWARE. --------------------------------------------------------- -System.Diagnostics.DiagnosticSource 7.0.1 - MIT - - - -The MIT License (MIT) - -Copyright (c) .NET Foundation and Contributors - -All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - - ---------------------------------------------------------- - ---------------------------------------------------------- - -System.Diagnostics.EventLog 7.0.0 - MIT +System.Diagnostics.DiagnosticSource 7.0.2 - MIT (c) Microsoft Corporation @@ -2009,7 +1948,7 @@ SOFTWARE. --------------------------------------------------------- -System.Diagnostics.PerformanceCounter 7.0.0 - MIT +System.Diagnostics.EventLog 7.0.0 - MIT (c) Microsoft Corporation @@ -2090,7 +2029,7 @@ SOFTWARE. --------------------------------------------------------- -System.DirectoryServices 7.0.1 - MIT +System.Diagnostics.PerformanceCounter 7.0.0 - MIT (c) Microsoft Corporation @@ -2171,7 +2110,7 @@ SOFTWARE. --------------------------------------------------------- -System.DirectoryServices.AccountManagement 7.0.0 - MIT +System.DirectoryServices 7.0.1 - MIT (c) Microsoft Corporation @@ -2252,7 +2191,7 @@ SOFTWARE. --------------------------------------------------------- -System.DirectoryServices.Protocols 7.0.0 - MIT +System.DirectoryServices.AccountManagement 7.0.0 - MIT (c) Microsoft Corporation @@ -2333,7 +2272,7 @@ SOFTWARE. --------------------------------------------------------- -System.Drawing.Common 7.0.0 - MIT +System.DirectoryServices.Protocols 7.0.0 - MIT (c) Microsoft Corporation @@ -2414,7 +2353,7 @@ SOFTWARE. --------------------------------------------------------- -System.Formats.Asn1 7.0.0 - MIT +System.Drawing.Common 7.0.0 - MIT (c) Microsoft Corporation @@ -2495,7 +2434,7 @@ SOFTWARE. --------------------------------------------------------- -System.IO.Packaging 7.0.0 - MIT +System.Formats.Asn1 7.0.0 - MIT (c) Microsoft Corporation @@ -2576,7 +2515,7 @@ SOFTWARE. --------------------------------------------------------- -System.IO.Ports 7.0.0 - MIT +System.IO.Packaging 7.0.0 - MIT (c) Microsoft Corporation @@ -2657,7 +2596,7 @@ SOFTWARE. --------------------------------------------------------- -System.Management 7.0.0 - MIT +System.IO.Ports 7.0.0 - MIT (c) Microsoft Corporation @@ -2866,9 +2805,12 @@ SOFTWARE. --------------------------------------------------------- -System.Private.ServiceModel 4.10.0 - MIT +System.Private.ServiceModel 4.10.2 - MIT +(c) Microsoft Corporation +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2000-2014 The Legion of the Bouncy Castle Inc. (http://www.bouncycastle.org) The MIT License (MIT) @@ -3680,42 +3622,12 @@ SOFTWARE. --------------------------------------------------------- -System.ServiceModel.Duplex 4.10.0 - MIT - +System.ServiceModel.Duplex 4.10.2 - MIT -The MIT License (MIT) - +(c) Microsoft Corporation Copyright (c) .NET Foundation and Contributors - -All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - - ---------------------------------------------------------- - ---------------------------------------------------------- - -System.ServiceModel.Http 4.10.0 - MIT - - +Copyright (c) 2000-2014 The Legion of the Bouncy Castle Inc. (http://www.bouncycastle.org) The MIT License (MIT) @@ -3746,7 +3658,7 @@ SOFTWARE. --------------------------------------------------------- -System.ServiceModel.NetFramingBase 6.0.0-preview1.23060.3 - MIT +System.ServiceModel.Http 4.10.2 - MIT (c) Microsoft Corporation @@ -3782,9 +3694,12 @@ SOFTWARE. --------------------------------------------------------- -System.ServiceModel.NetTcp 4.10.0 - MIT +System.ServiceModel.NetTcp 4.10.2 - MIT +(c) Microsoft Corporation +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2000-2014 The Legion of the Bouncy Castle Inc. (http://www.bouncycastle.org) The MIT License (MIT) @@ -3815,9 +3730,12 @@ SOFTWARE. --------------------------------------------------------- -System.ServiceModel.Primitives 4.10.0 - MIT +System.ServiceModel.Primitives 4.10.2 - MIT +(c) Microsoft Corporation +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2000-2014 The Legion of the Bouncy Castle Inc. (http://www.bouncycastle.org) The MIT License (MIT) @@ -3848,9 +3766,12 @@ SOFTWARE. --------------------------------------------------------- -System.ServiceModel.Security 4.10.0 - MIT +System.ServiceModel.Security 4.10.2 - MIT +(c) Microsoft Corporation +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2000-2014 The Legion of the Bouncy Castle Inc. (http://www.bouncycastle.org) The MIT License (MIT) @@ -4363,53 +4284,6 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ---------------------------------------------------------- - ---------------------------------------------------------- - -System.Threading.Tasks.Extensions 4.5.4 - MIT - - -(c) Microsoft Corporation. -Copyright (c) 2011, Google Inc. -(c) 1997-2005 Sean Eron Anderson. -Copyright (c) 1991-2017 Unicode, Inc. -Portions (c) International Organization -Copyright (c) 2015 The Chromium Authors. -Copyright (c) 2004-2006 Intel Corporation -Copyright (c) .NET Foundation Contributors -Copyright (c) .NET Foundation and Contributors -Copyright (c) 2011 Novell, Inc (http://www.novell.com) -Copyright (c) 1995-2017 Jean-loup Gailly and Mark Adler -Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) -Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors. -Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers THIS WORK IS PROVIDED AS - -The MIT License (MIT) - -Copyright (c) .NET Foundation and Contributors - -All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - - --------------------------------------------------------- --------------------------------------------------------- From 2f8b74c45b4e213b1c2af673d47bc183ea08bfd2 Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Wed, 19 Apr 2023 23:39:32 +0000 Subject: [PATCH 487/779] Merged PR 25453: Update changelog for the v7.4.0-preview.3 release Update changelog for the v7.4.0-preview.3 release --- .spelling | 9 +++++ CHANGELOG/preview.md | 90 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 99 insertions(+) diff --git a/.spelling b/.spelling index 93360cfdf8b..507ab9e16bd 100644 --- a/.spelling +++ b/.spelling @@ -1707,4 +1707,13 @@ ClearlyDefined stevenebutler spaette syntax-tm +URIs +typeDataXmlLoader.cs +GetResponseObject +ContentHelper +BasicHtmlWebResponseObject +WebRequestSession.cs +dkattan +preview.3.23178.7 +PoolNames techguy16 diff --git a/CHANGELOG/preview.md b/CHANGELOG/preview.md index 9984b9b5423..32999c16889 100644 --- a/CHANGELOG/preview.md +++ b/CHANGELOG/preview.md @@ -1,5 +1,95 @@ # Current preview release +## [7.4.0-preview.3] - 2023-04-20 + +### Breaking Changes + +- Remove code related to `#requires -pssnapin` (#19320) + +### Engine Updates and Fixes + +- Change the arrow used in feedback suggestion to a more common Unicode character (#19534) +- Support trigger registration in feedback provider (#19525) +- Update the `ICommandPredictor` interface to reduce boilerplate code from predictor implementation (#19414) +- Fix a crash in the type inference code (#19400) (Thanks @MartinGC94!) + +### Performance + +- Speed up `Resolve-Path` relative path resolution (#19171) (Thanks @MartinGC94!) + +### General Cmdlet Updates and Fixes + +- Infer external application output as strings (#19193) (Thanks @MartinGC94!) +- Fix a race condition in `Add-Type` (#19471) +- Detect insecure `https-to-http` redirect only if both URIs are absolute (#19468) (Thanks @CarloToso!) +- Support `Ctrl+c` when connection hangs while reading data in WebCmdlets (#19330) (Thanks @stevenebutler!) +- Enable type conversion of `AutomationNull` to `$null` for assignment (#19415) +- Add the parameter `-Environment` to `Start-Process` (#19374) +- Add the parameter `-RelativeBasePath` to `Resolve-Path` (#19358) (Thanks @MartinGC94!) +- Exclude redundant parameter aliases from completion results (#19382) (Thanks @MartinGC94!) +- Allow using a folder path in WebCmdlets' `-OutFile` parameter (#19007) (Thanks @CarloToso!) + +### Code Cleanup + +
    + + + +

    We thank the following contributors!

    +

    @eltociear, @CarloToso

    + +
    + +
      +
    • Fix typo in typeDataXmlLoader.cs (#19319) (Thanks @eltociear!)
    • +
    • Fix typo in Compiler.cs (#19491) (Thanks @eltociear!)
    • +
    • Inline the GetResponseObject method (#19380) (Thanks @CarloToso!)
    • +
    • Simplify ContentHelper methods (#19367) (Thanks @CarloToso!)
    • +
    • Initialize regex lazily in BasicHtmlWebResponseObject (#19361) (Thanks @CarloToso!)
    • +
    • Fix codefactor issue in if-statement (part 5) (#19286) (Thanks @CarloToso!)
    • +
    • Add nullable annotations in WebRequestSession.cs (#19291) (Thanks @CarloToso!)
    • +
    + +
    + +### Tests + +- Harden the default command test (#19416) +- Skip VT100 tests on Windows Server 2012R2 as console does not support it (#19413) +- Improve package management acceptance tests by not going to the gallery (#19412) + +### Build and Packaging Improvements + +
    + + + +

    We thank the following contributors!

    +

    @dkattan

    + +
    + +
      +
    • Fixing MSI checkbox (#19325)
    • +
    • Update the experimental feature JSON files (#19297)
    • +
    • Update the cgmanifest (#19459, #19465)
    • +
    • Update .NET SDK version to 8.0.100-preview.3.23178.7 (#19381)
    • +
    • Force updating the transitive dependency on Microsoft.CSharp (#19514)
    • +
    • Update DotnetRuntimeMetadata.json to consume the .NET 8.0.0-preview.3 release (#19529)
    • +
    • Move PSGallery sync to a pool (#19523)
    • +
    • Fix the regex used for package name check in vPack build (#19511)
    • +
    • Make the vPack PAT library more obvious (#19505)
    • +
    • Change Microsoft.CodeAnalysis.CSharp back to 4.5.0 (#19464) (Thanks @dkattan!)
    • +
    • Update to the latest NOTICES file (#19332)
    • +
    • Add PoolNames variable group to compliance pipeline (#19408)
    • +
    • Fix stage dependencies and typo in release build (#19353)
    • +
    • Fix issues in release build and release pipeline (#19338)
    • +
    + +
    + +[7.4.0-preview.3]: https://github.com/PowerShell/PowerShell/compare/v7.4.0-preview.2...v7.4.0-preview.3 + ## [7.4.0-preview.2] - 2023-03-14 ### Breaking Changes From 319c9faf5738a31deceb2c851aa0c6386e7f7807 Mon Sep 17 00:00:00 2001 From: stevenebutler Date: Fri, 21 Apr 2023 02:40:01 +1000 Subject: [PATCH 488/779] Improve reliability of the `Ctrl+c` tests for WebCmdlets (#19532) --- .../WebCmdlets.Tests.ps1 | 40 ++++++++++++++----- 1 file changed, 29 insertions(+), 11 deletions(-) diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 index 5deb9308bd2..2b2968ea3da 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 @@ -4218,26 +4218,32 @@ Describe 'Invoke-WebRequest and Invoke-RestMethod support Cancellation through C [string]$Command = 'Invoke-WebRequest', [string]$Arguments = '', [uri]$Uri, - [int]$DelayMs = 100, + [int]$DelayBeforeStopSimulationMs = 5000, [switch]$WillComplete ) $pwsh = [PowerShell]::Create() $invoke = "`$result = $Command -Uri `"$Uri`" $Arguments" $task = $pwsh.AddScript($invoke).InvokeAsync() - Start-Sleep -Milliseconds $DelayMs + $delay = [System.Threading.Tasks.Task]::Delay($DelayBeforeStopSimulationMs) + + # Simulate CTRL-C as soon as the timeout expires or the main task ends + $null = [System.Threading.Tasks.Task]::WaitAny($task, $delay) $task.IsCompleted | Should -Be $WillComplete.ToBool() $pwsh.Stop() + + # The download stall is normally 30 seconds from the web listener based + # on the first slash separated parameter in the -TestValue provided to + # Get-WebListenerUrl -test Stall -TestValue duration/content-type. Wait-UntilTrue { [bool]($Task.IsCompleted) } | Should -BeTrue $result = $pwsh.Runspace.SessionStateProxy.GetVariable('result') $pwsh.Dispose() - return $result } It 'Invoke-WebRequest: CTRL-C Cancels request before request headers received' { $uri = Get-WebListenerUrl -test Delay -TestValue 30 - RunWithCancellation -Uri $uri -DelayMs 0 + RunWithCancellation -Uri $uri -DelayBeforeStopSimulationMs 1000 } It 'Invoke-WebRequest: CTRL-C Cancels request after request headers received' { @@ -4250,20 +4256,32 @@ Describe 'Invoke-WebRequest and Invoke-RestMethod support Cancellation through C RunWithCancellation -Uri $uri -Arguments "-SkipCertificateCheck" } - It 'Invoke-WebRequest: Compression CTRL-C Cancels request after request headers' { + It 'Invoke-WebRequest: Brotli Compression CTRL-C Cancels request after request headers' { $uri = Get-WebListenerUrl -Test StallBrotli -TestValue '30/application%2fjson' RunWithCancellation -Uri $uri + } + + It 'Invoke-WebRequest: Gzip Compression CTRL-C Cancels request after request headers' { $uri = Get-WebListenerUrl -Test StallGzip -TestValue '30/application%2fjson' RunWithCancellation -Uri $uri + } + + It 'Invoke-WebRequest: Defalate Compression CTRL-C Cancels request after request headers' { $uri = Get-WebListenerUrl -Test StallDeflate -TestValue '30/application%2fjson' RunWithCancellation -Uri $uri } - It 'Invoke-WebRequest: HTTPS with compression CTRL-C Cancels request after request headers' { + It 'Invoke-WebRequest: HTTPS with Brotli compression CTRL-C Cancels request after request headers' { $uri = Get-WebListenerUrl -Https -Test StallBrotli -TestValue '30/application%2fjson' RunWithCancellation -Uri $uri -Arguments '-SkipCertificateCheck' + } + + It 'Invoke-WebRequest: HTTPS with Gzip compression CTRL-C Cancels request after request headers' { $uri = Get-WebListenerUrl -Https -Test StallGzip -TestValue '30/application%2fjson' RunWithCancellation -Uri $uri -Arguments '-SkipCertificateCheck' + } + + It 'Invoke-WebRequest: HTTPS with Defalte compression CTRL-C Cancels request after request headers' { $uri = Get-WebListenerUrl -Https -Test StallDeflate -TestValue '30/application%2fjson' RunWithCancellation -Uri $uri -Arguments '-SkipCertificateCheck' } @@ -4271,7 +4289,7 @@ Describe 'Invoke-WebRequest and Invoke-RestMethod support Cancellation through C It 'Invoke-WebRequest: CTRL-C Cancels file download request after request headers received' { $uri = Get-WebListenerUrl -Test Stall -TestValue '30' $outFile = Join-Path $TestDrive "output.txt" - RunWithCancellation -Uri $uri -Arguments "-OutFile $outFile" -DelayMs 300 + RunWithCancellation -Uri $uri -Arguments "-OutFile $outFile" # No guarantee the file will be present since the D/L is interrupted if (Test-Path -Path $outFile) { Remove-Item -Path $outFile @@ -4281,14 +4299,14 @@ Describe 'Invoke-WebRequest and Invoke-RestMethod support Cancellation through C It 'Invoke-WebRequest: CTRL-C after stalled file download completes gives entire file' { $uri = Get-WebListenerUrl -test Stall -TestValue '1' $outFile = Join-Path $TestDrive "output.txt" - RunWithCancellation -Uri $uri -Arguments "-OutFile $outFile" -DelayMs 1200 -WillComplete + RunWithCancellation -Uri $uri -Arguments "-OutFile $outFile" -WillComplete Get-content -Path $outFile | should -be 'Hello worldHello world' Remove-Item -Path $outFile } It 'Invoke-RestMethod: CTRL-C Cancels request before request headers received' { $uri = Get-WebListenerUrl -test Delay -TestValue 30 - RunWithCancellation -Command 'Invoke-RestMethod' -Uri $uri -DelayMs 0 + RunWithCancellation -Command 'Invoke-RestMethod' -Uri $uri -DelayBeforeStopSimulationMs 1000 } It 'Invoke-RestMethod: CTRL-C Cancels request after JSON request headers received' { @@ -4298,7 +4316,7 @@ Describe 'Invoke-WebRequest and Invoke-RestMethod support Cancellation through C It 'Invoke-RestMethod: CTRL-C after stalled JSON download processes JSON response' { $uri = Get-WebListenerUrl -test Stall -TestValue '1/application%2fjson' - $result = RunWithCancellation -Command 'Invoke-RestMethod' -Uri $uri -DelayMs 1200 -WillComplete + $result = RunWithCancellation -Command 'Invoke-RestMethod' -Uri $uri -WillComplete $result.name3 | should -be 'value3' } @@ -4309,7 +4327,7 @@ Describe 'Invoke-WebRequest and Invoke-RestMethod support Cancellation through C It 'Invoke-RestMethod: CTRL-C after stalled atom feed download processes atom response' { $uri = Get-WebListenerUrl -test Stall -TestValue '1/application%2fxml' - $result = RunWithCancellation -Command 'Invoke-RestMethod' -Uri $uri -DelayMs 1200 -WillComplete + $result = RunWithCancellation -Command 'Invoke-RestMethod' -Uri $uri -WillComplete $result.title | should -be 'Atom-Powered Robots Run Amok' } From 72e4732874735fcd797dcb4946715ac43a6c66d6 Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Thu, 20 Apr 2023 11:28:19 -0700 Subject: [PATCH 489/779] Update `README.md` and `metadata.json` for release v7.4.0-preview.3 (#19542) --- README.md | 28 ++++++++++++++-------------- tools/metadata.json | 4 ++-- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index 3dca4d501c6..879695d8d04 100644 --- a/README.md +++ b/README.md @@ -93,20 +93,20 @@ You can also download the PowerShell binary archives for Windows, macOS and Linu [rl-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.4/powershell-7.3.4-linux-arm64.tar.gz [rl-snap]: https://snapcraft.io/powershell -[pv-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.2/PowerShell-7.4.0-preview.2-win-x64.msi -[pv-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.2/PowerShell-7.4.0-preview.2-win-x86.msi -[pv-deb]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.2/powershell-preview_7.4.0-preview.2-1.deb_amd64.deb -[pv-rpm]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.2/powershell-preview-7.4.0_preview.2-1.rh.x86_64.rpm -[pv-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.2/powershell-7.4.0-preview.2-osx-x64.pkg -[pv-macos-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.2/powershell-7.4.0-preview.2-osx-arm64.pkg -[pv-winarm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.2/PowerShell-7.4.0-preview.2-win-arm64.zip -[pv-winx86-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.2/PowerShell-7.4.0-preview.2-win-x86.zip -[pv-winx64-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.2/PowerShell-7.4.0-preview.2-win-x64.zip -[pv-macos-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.2/powershell-7.4.0-preview.2-osx-x64.tar.gz -[pv-macos-tar-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.2/powershell-7.4.0-preview.2-osx-arm64.tar.gz -[pv-linux-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.2/powershell-7.4.0-preview.2-linux-x64.tar.gz -[pv-arm32]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.2/powershell-7.4.0-preview.2-linux-arm32.tar.gz -[pv-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.2/powershell-7.4.0-preview.2-linux-arm64.tar.gz +[pv-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.3/PowerShell-7.4.0-preview.3-win-x64.msi +[pv-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.3/PowerShell-7.4.0-preview.3-win-x86.msi +[pv-deb]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.3/powershell-preview_7.4.0-preview.3-1.deb_amd64.deb +[pv-rpm]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.3/powershell-preview-7.4.0_preview.3-1.rh.x86_64.rpm +[pv-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.3/powershell-7.4.0-preview.3-osx-x64.pkg +[pv-macos-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.3/powershell-7.4.0-preview.3-osx-arm64.pkg +[pv-winarm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.3/PowerShell-7.4.0-preview.3-win-arm64.zip +[pv-winx86-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.3/PowerShell-7.4.0-preview.3-win-x86.zip +[pv-winx64-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.3/PowerShell-7.4.0-preview.3-win-x64.zip +[pv-macos-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.3/powershell-7.4.0-preview.3-osx-x64.tar.gz +[pv-macos-tar-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.3/powershell-7.4.0-preview.3-osx-arm64.tar.gz +[pv-linux-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.3/powershell-7.4.0-preview.3-linux-x64.tar.gz +[pv-arm32]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.3/powershell-7.4.0-preview.3-linux-arm32.tar.gz +[pv-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.3/powershell-7.4.0-preview.3-linux-arm64.tar.gz [pv-snap]: https://snapcraft.io/powershell-preview [in-windows]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-windows diff --git a/tools/metadata.json b/tools/metadata.json index 31a94cc7443..4742b3b0268 100644 --- a/tools/metadata.json +++ b/tools/metadata.json @@ -1,10 +1,10 @@ { "StableReleaseTag": "v7.3.4", - "PreviewReleaseTag": "v7.4.0-preview.2", + "PreviewReleaseTag": "v7.4.0-preview.3", "ServicingReleaseTag": "v7.0.13", "ReleaseTag": "v7.3.4", "LTSReleaseTag" : ["v7.2.11"], - "NextReleaseTag": "v7.4.0-preview.3", + "NextReleaseTag": "v7.4.0-preview.4", "LTSRelease": { "Latest": false, "Package": false }, "StableRelease": { "Latest": false, "Package": false } } From 4141592e4f78d2d9cc110d8ac3cb6e8ad50720c2 Mon Sep 17 00:00:00 2001 From: PowerShell Team Bot <69177312+pwshBot@users.noreply.github.com> Date: Thu, 20 Apr 2023 14:19:00 -0700 Subject: [PATCH 490/779] Update to the latest `NOTICES` file (#19546) --- ThirdPartyNotices.txt | 66 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) diff --git a/ThirdPartyNotices.txt b/ThirdPartyNotices.txt index 5a815440a4a..b36884e6c8a 100644 --- a/ThirdPartyNotices.txt +++ b/ThirdPartyNotices.txt @@ -642,6 +642,39 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +--------------------------------------------------------- + +--------------------------------------------------------- + +Microsoft.Windows.Compatibility 7.0.1 - MIT + + + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + --------------------------------------------------------- --------------------------------------------------------- @@ -2673,6 +2706,39 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +--------------------------------------------------------- + +--------------------------------------------------------- + +System.Management 7.0.1 - MIT + + + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + --------------------------------------------------------- --------------------------------------------------------- From dadcf0656562156b434d71b33d1fbc7b2f627bb7 Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Thu, 20 Apr 2023 15:56:31 -0700 Subject: [PATCH 491/779] Update the team member list in `releaseTools.psm1` (#19544) --- tools/releaseTools.psm1 | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tools/releaseTools.psm1 b/tools/releaseTools.psm1 index 7755495d6ce..65c6fc54ed4 100644 --- a/tools/releaseTools.psm1 +++ b/tools/releaseTools.psm1 @@ -41,6 +41,8 @@ $Script:powershell_team = @( "Andrew Schwartzmeyer" "Jason Helmick" "Patrick Meinecke" + "Steven Bucher" + "PowerShell Team Bot" ) # They are very active contributors, so we keep their email-login mappings here to save a few queries to Github. From a7898d28861e301fb0d622903b7a044b7c9a82d4 Mon Sep 17 00:00:00 2001 From: "James Truher [MSFT]" Date: Thu, 20 Apr 2023 16:14:09 -0700 Subject: [PATCH 492/779] Harden 'All approved Cmdlets present' test (#19530) --- test/powershell/engine/Basic/DefaultCommands.Tests.ps1 | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/test/powershell/engine/Basic/DefaultCommands.Tests.ps1 b/test/powershell/engine/Basic/DefaultCommands.Tests.ps1 index 9d1b030a6a5..27be013ec6b 100644 --- a/test/powershell/engine/Basic/DefaultCommands.Tests.ps1 +++ b/test/powershell/engine/Basic/DefaultCommands.Tests.ps1 @@ -1,6 +1,6 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. -Describe "Verify approved aliases list" -Tags "CI" { +Describe "Verify aliases and cmdlets" -Tags "CI" { BeforeAll { function ConvertTo-Hashtable { [CmdletBinding()] @@ -612,9 +612,9 @@ Describe "Verify approved aliases list" -Tags "CI" { } It "All approved Cmdlets present (no new Cmdlets added, no Cmdlets removed)" { - $expectedCmdletList = $commandList.Where({$_.Present -eq "True" -and $_.CommandType -eq "Cmdlet"}).Name | Sort-Object - $observedCmdletList = $currentCmdletList.Name | Sort-Object - $observedCmdletList | Should -Be $expectedCmdletList + $observedCmdletNames = $currentCmdletList.ForEach({"{0}" -f $_.Name}) | Sort-Object + $expectedCmdletNames = $commandHashTableList.ForEach({"{0}" -f $_.Name}) | Sort-Object + $observedCmdletNames | Should -Be $expectedCmdletNames } It "'' Cmdlet should have the correct ConfirmImpact ''" -TestCases $commandHashtableList { From b4f2e3ad8c0921b683cabfead23f1c8e8c7462b9 Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Thu, 20 Apr 2023 17:34:32 -0700 Subject: [PATCH 493/779] Add an explicit manual stage for changelog update (#19551) --- .../azureDevOps/releasePipeline.yml | 20 ++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/tools/releaseBuild/azureDevOps/releasePipeline.yml b/tools/releaseBuild/azureDevOps/releasePipeline.yml index 7e474c3acb6..10796c7a0db 100644 --- a/tools/releaseBuild/azureDevOps/releasePipeline.yml +++ b/tools/releaseBuild/azureDevOps/releasePipeline.yml @@ -248,8 +248,8 @@ stages: $azDoBuild | Remove-AzDOBuildTag -tag 'InProgress' -Pass | Add-AzDOBuildTag -tag 'SignedOff' displayName: Signoff Release-Automation run -- stage: GitHubDraftRelease - displayName: Create GitHub draft release +- stage: UpdateChangeLog + displayName: Update the changelog # do not include stages that are likely to fail in dependency as there is no way to force deploy. dependsOn: - MSIXBundle @@ -261,7 +261,21 @@ stages: - ValidateFxdPackage - ValidateGlobalTool -# The environment here is used for approval. + jobs: + - template: templates/release/approvalJob.yml + parameters: + displayName: Make sure the changelog is updated + jobName: MergeChangeLog + instructions: | + Update and merge the changelog for the release. + This step is required for creating GitHub draft release. + +- stage: GitHubDraftRelease + displayName: Create GitHub draft release + # do not include stages that are likely to fail in dependency as there is no way to force deploy. + dependsOn: UpdateChangeLog + + # The environment here is used for approval. jobs: - deployment: AzureBlobPublic displayName: Make Azure Blob Public From 232b6b127367c9b951063d591b363c8cf7f7da4a Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Fri, 21 Apr 2023 11:50:49 -0700 Subject: [PATCH 494/779] Verify that packages have license data (#19543) --- tools/clearlyDefined/ClearlyDefined.ps1 | 8 ++++++-- .../azureDevOps/templates/compliance/generateNotice.yml | 4 ++++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/tools/clearlyDefined/ClearlyDefined.ps1 b/tools/clearlyDefined/ClearlyDefined.ps1 index ded0b229938..1830c2969e5 100644 --- a/tools/clearlyDefined/ClearlyDefined.ps1 +++ b/tools/clearlyDefined/ClearlyDefined.ps1 @@ -7,6 +7,9 @@ param( [parameter(Mandatory = $true, ParameterSetName='Test')] [switch] $Test, + [parameter(Mandatory = $true, ParameterSetName='TestAndHarvest')] + [switch] + $TestAndHarvest, [switch] $ForceModuleReload ) @@ -35,9 +38,10 @@ $needHarvest = $fullList | Where-Object { !$_.harvested } Write-Verbose "Full List count: $($fullList.Count)" -Verbose Write-Verbose "Need harvest: $($needHarvest.Count)" -Verbose -if ($Harvest) { +if ($Harvest -or $TestAndHarvest) { $needHarvest | select-object -ExpandProperty coordinates | Start-ClearlyDefinedHarvest -} elseif ($Test) { +} +if ($Test -or $TestAndHarvest) { if($needHarvest.Count -gt 0) { $needHarvest | Format-List | Out-String -Width 9999 | Write-Verbose -Verbose throw "There are $($needHarvest.Count) packages that need to be harvested" diff --git a/tools/releaseBuild/azureDevOps/templates/compliance/generateNotice.yml b/tools/releaseBuild/azureDevOps/templates/compliance/generateNotice.yml index d56d8c1176b..2431ded7448 100644 --- a/tools/releaseBuild/azureDevOps/templates/compliance/generateNotice.yml +++ b/tools/releaseBuild/azureDevOps/templates/compliance/generateNotice.yml @@ -46,6 +46,10 @@ jobs: inputs: sourceScanPath: '$(Build.SourcesDirectory)\tools' + - pwsh: | + ./tools/clearlyDefined/ClearlyDefined.ps1 -TestAndHarvest + displayName: Verify that packages have license data + - task: msospo.ospo-extension.8d7f9abb-6896-461d-9e25-4f74ed65ddb2.notice@0 displayName: 'NOTICE File Generator' inputs: From 3547acaa1ca9e1141cf1f7d4725c045285618911 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Fri, 21 Apr 2023 11:54:20 -0700 Subject: [PATCH 495/779] Add comment in wix detailing use of `UseMU` (#19371) * remove `UseMU` reg value on uninstall of MSI * change to a comment --- assets/wix/Product.wxs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/assets/wix/Product.wxs b/assets/wix/Product.wxs index cbb46a48ddd..d4c5e8a2960 100644 --- a/assets/wix/Product.wxs +++ b/assets/wix/Product.wxs @@ -194,7 +194,7 @@ USE_MU=1 - + From 543b20b4ed0c3dc2a5d31259cbb899c3670ea006 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Mon, 24 Apr 2023 05:38:30 +0200 Subject: [PATCH 496/779] Enable more nullable annotations in WebCmdlets (#19359) --- .../BasicHtmlWebResponseObject.Common.cs | 20 +++++---- .../WebCmdlet/Common/ContentHelper.Common.cs | 24 ++++++----- .../Common/InvokeRestMethodCommand.Common.cs | 28 +++++++------ .../Common/WebResponseObject.Common.cs | 41 ++++++++++--------- .../WebCmdlet/CoreCLR/HttpKnownHeaderNames.cs | 2 + .../InvokeWebRequestCommand.CoreClr.cs | 6 ++- .../utility/WebCmdlet/CoreCLR/WebProxy.cs | 10 +++-- .../CoreCLR/WebResponseHelper.CoreClr.cs | 8 ++-- .../commands/utility/WebCmdlet/FormObject.cs | 4 +- .../utility/WebCmdlet/FormObjectCollection.cs | 6 ++- .../commands/utility/WebCmdlet/PSUserAgent.cs | 4 +- .../utility/WebCmdlet/StreamHelper.cs | 14 ++++--- .../WebCmdlet/WebCmdletElementCollection.cs | 10 +++-- .../utility/WebCmdlet/WebRequestMethod.cs | 2 + 14 files changed, 105 insertions(+), 74 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/BasicHtmlWebResponseObject.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/BasicHtmlWebResponseObject.Common.cs index 8eaa95c224a..75775428bc9 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/BasicHtmlWebResponseObject.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/BasicHtmlWebResponseObject.Common.cs @@ -1,8 +1,11 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +#nullable enable + using System.Collections.Generic; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.IO; using System.Management.Automation; using System.Net.Http; @@ -33,7 +36,7 @@ public BasicHtmlWebResponseObject(HttpResponseMessage response, CancellationToke /// The response. /// The content stream associated with the response. /// Cancellation token. - public BasicHtmlWebResponseObject(HttpResponseMessage response, Stream contentStream, CancellationToken cancellationToken) : base(response, contentStream, cancellationToken) + public BasicHtmlWebResponseObject(HttpResponseMessage response, Stream? contentStream, CancellationToken cancellationToken) : base(response, contentStream, cancellationToken) { InitializeContent(cancellationToken); InitializeRawContent(response); @@ -60,9 +63,9 @@ public BasicHtmlWebResponseObject(HttpResponseMessage response, Stream contentSt /// Encoding of the response body from the Content-Type header, /// or if the encoding could not be determined. /// - public Encoding Encoding { get; private set; } + public Encoding? Encoding { get; private set; } - private WebCmdletElementCollection _inputFields; + private WebCmdletElementCollection? _inputFields; /// /// Gets the HTML input field elements parsed from . @@ -87,7 +90,7 @@ public WebCmdletElementCollection InputFields } } - private WebCmdletElementCollection _links; + private WebCmdletElementCollection? _links; /// /// Gets the HTML a link elements parsed from . @@ -112,7 +115,7 @@ public WebCmdletElementCollection Links } } - private WebCmdletElementCollection _images; + private WebCmdletElementCollection? _images; /// /// Gets the HTML img elements parsed from . @@ -145,13 +148,14 @@ public WebCmdletElementCollection Images /// Reads the response content from the web response. /// /// The cancellation token. + [MemberNotNull(nameof(Content))] protected void InitializeContent(CancellationToken cancellationToken) { - string contentType = ContentHelper.GetContentType(BaseResponse); + string? contentType = ContentHelper.GetContentType(BaseResponse); if (ContentHelper.IsText(contentType)) { // Fill the Content buffer - string characterSet = WebResponseHelper.GetCharacterSet(BaseResponse); + string? characterSet = WebResponseHelper.GetCharacterSet(BaseResponse); Content = StreamHelper.DecodeStream(RawContentStream, characterSet, out Encoding encoding, cancellationToken); Encoding = encoding; @@ -204,7 +208,7 @@ private static void ParseAttributes(string outerHtml, PSObject elementObject) string name = nvMatches.Groups[1].Value; // The value (if any) is captured by group #2, #3, or #4, depending on quoting or lack thereof - string value = null; + string? value = null; if (nvMatches.Groups[2].Success) { value = nvMatches.Groups[2].Value; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs index bf127967ffe..bb31366f794 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs @@ -1,7 +1,10 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +#nullable enable + using System; +using System.Diagnostics.CodeAnalysis; using System.Management.Automation; using System.Net.Http; using System.Net.Http.Headers; @@ -16,7 +19,7 @@ internal static class ContentHelper #region Internal Methods // ContentType may not exist in response header. Return null if not. - internal static string GetContentType(HttpResponseMessage response) => response.Content.Headers.ContentType?.MediaType; + internal static string? GetContentType(HttpResponseMessage response) => response.Content.Headers.ContentType?.MediaType; internal static Encoding GetDefaultEncoding() => Encoding.UTF8; @@ -35,7 +38,7 @@ internal static StringBuilder GetRawContentHeader(HttpResponseMessage response) HttpHeaders[] headerCollections = { response.Headers, - response.Content?.Headers + response.Content.Headers }; foreach (var headerCollection in headerCollections) @@ -59,7 +62,7 @@ internal static StringBuilder GetRawContentHeader(HttpResponseMessage response) return raw; } - internal static bool IsJson(string contentType) + internal static bool IsJson([NotNullWhen(true)] string? contentType) { if (string.IsNullOrEmpty(contentType)) { @@ -80,7 +83,7 @@ internal static bool IsJson(string contentType) return isJson; } - internal static bool IsText(string contentType) + internal static bool IsText([NotNullWhen(true)] string? contentType) { if (string.IsNullOrEmpty(contentType)) { @@ -96,19 +99,18 @@ internal static bool IsText(string contentType) if (Platform.IsWindows && !isText) { // Media types registered with Windows as having a perceived type of text, are text - using (RegistryKey contentTypeKey = Registry.ClassesRoot.OpenSubKey(@"MIME\Database\Content Type\" + contentType)) + using (RegistryKey? contentTypeKey = Registry.ClassesRoot.OpenSubKey(@"MIME\Database\Content Type\" + contentType)) { if (contentTypeKey != null) { - string extension = contentTypeKey.GetValue("Extension") as string; - if (extension != null) + if (contentTypeKey.GetValue("Extension") is string extension) { - using (RegistryKey extensionKey = Registry.ClassesRoot.OpenSubKey(extension)) + using (RegistryKey? extensionKey = Registry.ClassesRoot.OpenSubKey(extension)) { if (extensionKey != null) { - string perceivedType = extensionKey.GetValue("PerceivedType") as string; - isText = (perceivedType == "text"); + string? perceivedType = extensionKey.GetValue("PerceivedType") as string; + isText = perceivedType == "text"; } } } @@ -119,7 +121,7 @@ internal static bool IsText(string contentType) return isText; } - internal static bool IsXml(string contentType) + internal static bool IsXml([NotNullWhen(true)] string? contentType) { if (string.IsNullOrEmpty(contentType)) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs index 3fe6e2a91ad..a0ec902fb96 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs @@ -1,7 +1,10 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +#nullable enable + using System; +using System.Diagnostics.CodeAnalysis; using System.IO; using System.Management.Automation; using System.Net.Http; @@ -56,13 +59,13 @@ public int MaximumFollowRelLink /// [Parameter] [Alias("RHV")] - public string ResponseHeadersVariable { get; set; } + public string? ResponseHeadersVariable { get; set; } /// /// Gets or sets the variable name to use for storing the status code from the response. /// [Parameter] - public string StatusCodeVariable { get; set; } + public string? StatusCodeVariable { get; set; } #endregion Parameters @@ -95,12 +98,12 @@ internal override void ProcessResponse(HttpResponseMessage response) RestReturnType returnType = CheckReturnType(response); // Try to get the response encoding from the ContentType header. - string charSet = WebResponseHelper.GetCharacterSet(response); + string? characterSet = WebResponseHelper.GetCharacterSet(response); - string str = StreamHelper.DecodeStream(responseStream, charSet, out Encoding encoding, _cancelToken.Token); + string str = StreamHelper.DecodeStream(responseStream, characterSet, out Encoding encoding, _cancelToken.Token); - object obj = null; - Exception ex = null; + object? obj = null; + Exception? ex = null; string encodingVerboseName; try @@ -167,7 +170,7 @@ private static RestReturnType CheckReturnType(HttpResponseMessage response) ArgumentNullException.ThrowIfNull(response); RestReturnType rt = RestReturnType.Detect; - string contentType = ContentHelper.GetContentType(response); + string? contentType = ContentHelper.GetContentType(response); if (string.IsNullOrEmpty(contentType)) { rt = RestReturnType.Detect; @@ -223,7 +226,7 @@ private bool TryProcessFeedStream(Stream responseStream) ) { // This one will do reader.Read() internally - XmlNode result = workingDocument.ReadNode(reader); + XmlNode? result = workingDocument.ReadNode(reader); WriteObject(result); } else @@ -262,7 +265,7 @@ private static XmlReaderSettings GetSecureXmlReaderSettings() return xrs; } - private static bool TryConvertToXml(string xml, out object doc, ref Exception exRef) + private static bool TryConvertToXml(string xml, [NotNullWhen(true)] out object? doc, ref Exception? exRef) { try { @@ -284,13 +287,12 @@ private static bool TryConvertToXml(string xml, out object doc, ref Exception ex return doc != null; } - private static bool TryConvertToJson(string json, out object obj, ref Exception exRef) + private static bool TryConvertToJson(string json, [NotNullWhen(true)] out object? obj, ref Exception? exRef) { bool converted = false; try { - ErrorRecord error; - obj = JsonObject.ConvertFromJson(json, out error); + obj = JsonObject.ConvertFromJson(json, out ErrorRecord error); if (obj == null) { @@ -340,7 +342,7 @@ public enum RestReturnType /// /// Json return type. /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] Json, /// diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebResponseObject.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebResponseObject.Common.cs index 8bfdeed2da4..5b89a2352fe 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebResponseObject.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebResponseObject.Common.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +#nullable enable + using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -26,14 +28,14 @@ public class WebResponseObject /// /// Gets or protected sets the response body content. /// - public byte[] Content { get; protected set; } + public byte[]? Content { get; protected set; } /// /// Gets the Headers property. /// public Dictionary> Headers => _headers ??= WebResponseHelper.GetHeadersDictionary(BaseResponse); - private Dictionary> _headers = null; + private Dictionary>? _headers; /// /// Gets or protected sets the full response content. @@ -41,7 +43,7 @@ public class WebResponseObject /// /// Full response content, including the HTTP status line, headers, and body. /// - public string RawContent { get; protected set; } + public string? RawContent { get; protected set; } /// /// Gets the length (in bytes) of . @@ -56,7 +58,7 @@ public class WebResponseObject /// /// Gets the RelationLink property. /// - public Dictionary RelationLink { get; internal set; } + public Dictionary? RelationLink { get; internal set; } /// /// Gets the response status code. @@ -77,8 +79,7 @@ public class WebResponseObject /// /// The Http response. /// The cancellation token. - public WebResponseObject(HttpResponseMessage response, CancellationToken cancellationToken) : this(response, null, cancellationToken) - { } + public WebResponseObject(HttpResponseMessage response, CancellationToken cancellationToken) : this(response, null, cancellationToken) { } /// /// Initializes a new instance of the class @@ -87,7 +88,7 @@ public WebResponseObject(HttpResponseMessage response, CancellationToken cancell /// Http response. /// The http content stream. /// The cancellation token. - public WebResponseObject(HttpResponseMessage response, Stream contentStream, CancellationToken cancellationToken) + public WebResponseObject(HttpResponseMessage response, Stream? contentStream, CancellationToken cancellationToken) { SetResponse(response, contentStream, cancellationToken); InitializeContent(); @@ -111,9 +112,9 @@ private void InitializeRawContent(HttpResponseMessage baseResponse) StringBuilder raw = ContentHelper.GetRawContentHeader(baseResponse); // Use ASCII encoding for the RawContent visual view of the content. - if (Content.Length > 0) + if (Content?.Length > 0) { - raw.Append(this.ToString()); + raw.Append(ToString()); } RawContent = raw.ToString(); @@ -125,26 +126,23 @@ private static bool IsPrintable(char c) => char.IsLetterOrDigit(c) || char.IsSymbol(c) || char.IsWhiteSpace(c); - private void SetResponse(HttpResponseMessage response, Stream contentStream, CancellationToken cancellationToken) + [MemberNotNull(nameof(RawContentStream))] + [MemberNotNull(nameof(BaseResponse))] + private void SetResponse(HttpResponseMessage response, Stream? contentStream, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(response); BaseResponse = response; - MemoryStream ms = contentStream as MemoryStream; - if (ms is not null) + if (contentStream is MemoryStream ms) { RawContentStream = ms; } else { - Stream st = contentStream; - if (contentStream is null) - { - st = StreamHelper.GetResponseStream(response, cancellationToken); - } + Stream st = contentStream ?? StreamHelper.GetResponseStream(response, cancellationToken); - long contentLength = response.Content.Headers.ContentLength.Value; + long contentLength = response.Content.Headers.ContentLength.GetValueOrDefault(); if (contentLength <= 0) { contentLength = StreamHelper.DefaultReadBuffer; @@ -164,7 +162,12 @@ private void SetResponse(HttpResponseMessage response, Stream contentStream, Can /// The string representation of this web response. public sealed override string ToString() { - char[] stringContent = System.Text.Encoding.ASCII.GetChars(Content); + if (Content is null) + { + return string.Empty; + } + + char[] stringContent = Encoding.ASCII.GetChars(Content); for (int counter = 0; counter < stringContent.Length; counter++) { if (!IsPrintable(stringContent[counter])) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/HttpKnownHeaderNames.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/HttpKnownHeaderNames.cs index e0a9b3760ef..6571696e5bf 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/HttpKnownHeaderNames.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/HttpKnownHeaderNames.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +#nullable enable + using System; using System.Collections.Generic; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/InvokeWebRequestCommand.CoreClr.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/InvokeWebRequestCommand.CoreClr.cs index 19ebc294c10..1e66157ef0c 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/InvokeWebRequestCommand.CoreClr.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/InvokeWebRequestCommand.CoreClr.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +#nullable enable + using System; using System.IO; using System.Management.Automation; @@ -37,7 +39,7 @@ internal override void ProcessResponse(HttpResponseMessage response) Stream responseStream = StreamHelper.GetResponseStream(response, _cancelToken.Token); if (ShouldWriteToPipeline) { - // creating a MemoryStream wrapper to response stream here to support IsStopping. + // Creating a MemoryStream wrapper to response stream here to support IsStopping. responseStream = new WebResponseContentMemoryStream( responseStream, StreamHelper.ChunkSize, @@ -48,7 +50,7 @@ internal override void ProcessResponse(HttpResponseMessage response) ro.RelationLink = _relationLink; WriteObject(ro); - // use the rawcontent stream from WebResponseObject for further + // Use the rawcontent stream from WebResponseObject for further // processing of the stream. This is need because WebResponse's // stream can be used only once. responseStream = ro.RawContentStream; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebProxy.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebProxy.cs index 6890599b51b..6e9f6bdf98e 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebProxy.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebProxy.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +#nullable enable + using System; using System.Net; @@ -8,7 +10,7 @@ namespace Microsoft.PowerShell.Commands { internal class WebProxy : IWebProxy, IEquatable { - private ICredentials _credentials; + private ICredentials? _credentials; private readonly Uri _proxyAddress; internal WebProxy(Uri address) @@ -18,11 +20,11 @@ internal WebProxy(Uri address) _proxyAddress = address; } - public override bool Equals(object obj) => Equals(obj as WebProxy); + public override bool Equals(object? obj) => Equals(obj as WebProxy); public override int GetHashCode() => HashCode.Combine(_proxyAddress, _credentials, BypassProxyOnLocal); - public bool Equals(WebProxy other) + public bool Equals(WebProxy? other) { if (other is null) { @@ -35,7 +37,7 @@ public bool Equals(WebProxy other) && BypassProxyOnLocal == other.BypassProxyOnLocal; } - public ICredentials Credentials + public ICredentials? Credentials { get => _credentials; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseHelper.CoreClr.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseHelper.CoreClr.cs index eff0d658c81..6e24629548b 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseHelper.CoreClr.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseHelper.CoreClr.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +#nullable enable + using System; using System.Collections.Generic; using System.Globalization; @@ -11,7 +13,7 @@ namespace Microsoft.PowerShell.Commands { internal static class WebResponseHelper { - internal static string GetCharacterSet(HttpResponseMessage response) => response.Content.Headers.ContentType?.CharSet; + internal static string? GetCharacterSet(HttpResponseMessage response) => response.Content.Headers.ContentType?.CharSet; internal static Dictionary> GetHeadersDictionary(HttpResponseMessage response) { @@ -38,7 +40,7 @@ internal static Dictionary> GetHeadersDictionary(Htt internal static string GetOutFilePath(HttpResponseMessage response, string _qualifiedOutFile) { // Get file name from last segment of Uri - string lastUriSegment = System.Net.WebUtility.UrlDecode(response.RequestMessage.RequestUri.Segments[^1]); + string? lastUriSegment = System.Net.WebUtility.UrlDecode(response.RequestMessage?.RequestUri?.Segments[^1]); return Directory.Exists(_qualifiedOutFile) ? Path.Join(_qualifiedOutFile, lastUriSegment) : _qualifiedOutFile; } @@ -52,7 +54,7 @@ internal static string GetOutFilePath(HttpResponseMessage response, string _qual internal static bool IsText(HttpResponseMessage response) { // ContentType may not exist in response header. - string contentType = ContentHelper.GetContentType(response); + string? contentType = ContentHelper.GetContentType(response); return ContentHelper.IsText(contentType); } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObject.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObject.cs index b496a120329..5ac4adfbb64 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObject.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObject.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +#nullable enable + using System.Collections.Generic; namespace Microsoft.PowerShell.Commands @@ -46,7 +48,7 @@ public FormObject(string id, string method, string action) internal void AddField(string key, string value) { - if (key is not null && !Fields.TryGetValue(key, out string test)) + if (key is not null && !Fields.TryGetValue(key, out string? _)) { Fields[key] = value; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObjectCollection.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObjectCollection.cs index f435b92e484..5f923558185 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObjectCollection.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObjectCollection.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +#nullable enable + using System; using System.Collections.ObjectModel; @@ -16,11 +18,11 @@ public class FormObjectCollection : Collection /// /// /// - public FormObject this[string key] + public FormObject? this[string key] { get { - FormObject form = null; + FormObject? form = null; foreach (FormObject f in this) { if (string.Equals(key, f.Id, StringComparison.OrdinalIgnoreCase)) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/PSUserAgent.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/PSUserAgent.cs index e4312e74975..1a19d6b0457 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/PSUserAgent.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/PSUserAgent.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +#nullable enable + using System; using System.Globalization; using System.Management.Automation; @@ -14,7 +16,7 @@ namespace Microsoft.PowerShell.Commands /// public static class PSUserAgent { - private static string s_windowsUserAgent; + private static string? s_windowsUserAgent; // Format the user-agent string from the various component parts internal static string UserAgent => string.Create(CultureInfo.InvariantCulture, $"{Compatibility} ({PlatformName}; {OS}; {Culture}) {App}"); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs index bec01ee8a1d..6d217cdc909 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +#nullable enable + using System; using System.IO; using System.Management.Automation; @@ -25,7 +27,7 @@ internal class WebResponseContentMemoryStream : MemoryStream private readonly long? _contentLength; private readonly Stream _originalStreamToProxy; - private readonly Cmdlet _ownerCmdlet; + private readonly Cmdlet? _ownerCmdlet; private readonly CancellationToken _cancellationToken; private bool _isInitialized = false; @@ -40,7 +42,7 @@ internal class WebResponseContentMemoryStream : MemoryStream /// Owner cmdlet if any. /// Expected download size in Bytes. /// Cancellation token. - internal WebResponseContentMemoryStream(Stream stream, int initialCapacity, Cmdlet cmdlet, long? contentLength, CancellationToken cancellationToken) : base(initialCapacity) + internal WebResponseContentMemoryStream(Stream stream, int initialCapacity, Cmdlet? cmdlet, long? contentLength, CancellationToken cancellationToken) : base(initialCapacity) { this._contentLength = contentLength; _originalStreamToProxy = stream; @@ -361,7 +363,7 @@ private static string StreamToString(Stream stream, Encoding encoding, Cancellat while (!completed) { // If this is the last input data, flush the decoder's internal buffer and state. - bool flush = bytesRead == 0; + bool flush = bytesRead is 0; decoder.Convert(bytes, byteIndex, bytesRead - byteIndex, chars, 0, useBufferSize, flush, out int bytesUsed, out int charsUsed, out completed); // The conversion produced the number of characters indicated by charsUsed. Write that number @@ -386,7 +388,7 @@ private static string StreamToString(Stream stream, Encoding encoding, Cancellat return result.ToString(); } - internal static string DecodeStream(Stream stream, string characterSet, out Encoding encoding, CancellationToken cancellationToken) + internal static string DecodeStream(Stream stream, string? characterSet, out Encoding encoding, CancellationToken cancellationToken) { bool isDefaultEncoding = !TryGetEncoding(characterSet, out encoding); @@ -422,12 +424,12 @@ internal static string DecodeStream(Stream stream, string characterSet, out Enco return content; } - internal static bool TryGetEncoding(string characterSet, out Encoding encoding) + internal static bool TryGetEncoding(string? characterSet, out Encoding encoding) { bool result = false; try { - encoding = Encoding.GetEncoding(characterSet); + encoding = Encoding.GetEncoding(characterSet!); result = true; } catch (ArgumentException) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebCmdletElementCollection.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebCmdletElementCollection.cs index 8336249efb5..99326898d9f 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebCmdletElementCollection.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebCmdletElementCollection.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +#nullable enable + using System.Collections.Generic; using System.Collections.ObjectModel; using System.Management.Automation; @@ -21,23 +23,23 @@ internal WebCmdletElementCollection(IList list) : base(list) /// /// /// Found element as PSObject. - public PSObject Find(string nameOrId) => FindById(nameOrId) ?? FindByName(nameOrId); + public PSObject? Find(string nameOrId) => FindById(nameOrId) ?? FindByName(nameOrId); /// /// Finds the element by id. /// /// /// Found element as PSObject. - public PSObject FindById(string id) => Find(id, findById: true); + public PSObject? FindById(string id) => Find(id, findById: true); /// /// Finds the element by name. /// /// /// Found element as PSObject. - public PSObject FindByName(string name) => Find(name, findById: false); + public PSObject? FindByName(string name) => Find(name, findById: false); - private PSObject Find(string nameOrId, bool findById) + private PSObject? Find(string nameOrId, bool findById) { foreach (PSObject candidate in this) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestMethod.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestMethod.cs index aa7067f1c23..9b90115a1d5 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestMethod.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestMethod.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +#nullable enable + namespace Microsoft.PowerShell.Commands { /// From cf6fc53c9ffcdeea9022022e54a13fd01718c7b0 Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Tue, 25 Apr 2023 11:06:34 -0700 Subject: [PATCH 497/779] Fix test failures on Windows for time zone and remoting (#19466) --- test/powershell/Host/HostUtilities.Tests.ps1 | 8 +- .../TabCompletion/TabCompletion.Tests.ps1 | 14 +- .../SuppressAnsiEscapeSequence.Tests.ps1 | 2 +- .../PSSessionConfiguration.Tests.ps1 | 2 +- .../RemoteGetModule.Tests.ps1 | 19 +- .../RemoteImportModule.Tests.ps1 | 10 +- .../TimeZone.Tests.ps1 | 190 +++++++++--------- .../Formatting/OutputRendering.Tests.ps1 | 2 +- .../RemoteSession.Disconnect.Tests.ps1 | 15 +- .../engine/Remoting/RunspacePool.Tests.ps1 | 42 ++-- .../Modules/HelpersCommon/HelpersCommon.psd1 | 1 + .../Modules/HelpersCommon/HelpersCommon.psm1 | 10 + 12 files changed, 187 insertions(+), 128 deletions(-) diff --git a/test/powershell/Host/HostUtilities.Tests.ps1 b/test/powershell/Host/HostUtilities.Tests.ps1 index 1f064408e3c..7f738cb01c3 100644 --- a/test/powershell/Host/HostUtilities.Tests.ps1 +++ b/test/powershell/Host/HostUtilities.Tests.ps1 @@ -37,8 +37,10 @@ Describe "InvokeOnRunspace method on remote runspace" -tags "Feature","RequireAd BeforeAll { $originalDefaultParameterValues = $PSDefaultParameterValues.Clone() - if (Test-IsWinWow64) { - $global:PSDefaultParameterValues["it:skip"] = $true + $pendingTest = (Test-IsWinWow64) + + if ($pendingTest) { + $global:PSDefaultParameterValues["it:pending"] = $true return } @@ -48,7 +50,7 @@ Describe "InvokeOnRunspace method on remote runspace" -tags "Feature","RequireAd } AfterAll { - if ($script:remoteRunspace) + if ($script:remoteRunspace -and -not $pendingTest) { $script:remoteRunspace.Dispose(); } diff --git a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 index d7c98b1589d..c56cd2ca94a 100644 --- a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 +++ b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 @@ -2427,7 +2427,10 @@ function MyFunction ($param1, $param2) Describe "Tab completion tests with remote Runspace" -Tags Feature,RequireAdminOnWindows { BeforeAll { - if ($IsWindows -and -not (Test-IsWinWow64)) { + $skipTest = -not $IsWindows + $pendingTest = $IsWindows -and (Test-IsWinWow64) + + if (-not $skipTest -and -not $pendingTest) { $session = New-RemoteSession $powershell = [powershell]::Create() $powershell.Runspace = $session.Runspace @@ -2445,11 +2448,16 @@ Describe "Tab completion tests with remote Runspace" -Tags Feature,RequireAdminO ) } else { $defaultParameterValues = $PSDefaultParameterValues.Clone() - $PSDefaultParameterValues["It:Skip"] = $true + + if ($skipTest) { + $PSDefaultParameterValues["It:Skip"] = $true + } elseif ($pendingTest) { + $PSDefaultParameterValues["It:Pending"] = $true + } } } AfterAll { - if ($IsWindows) { + if (-not $skipTest -and -not $pendingTest) { Remove-PSSession $session $powershell.Dispose() } else { diff --git a/test/powershell/Language/Scripting/SuppressAnsiEscapeSequence.Tests.ps1 b/test/powershell/Language/Scripting/SuppressAnsiEscapeSequence.Tests.ps1 index 0530aea93ee..c1440857b45 100644 --- a/test/powershell/Language/Scripting/SuppressAnsiEscapeSequence.Tests.ps1 +++ b/test/powershell/Language/Scripting/SuppressAnsiEscapeSequence.Tests.ps1 @@ -6,7 +6,7 @@ Describe '$env:__SuppressAnsiEscapeSequences tests' -Tag CI { $originalDefaultParameterValues = $PSDefaultParameterValues.Clone() if (-not $host.ui.SupportsVirtualTerminal) { - $global:PSDefaultParameterValues["it:skip"] = $true + $PSDefaultParameterValues["it:skip"] = $true } $originalSuppressPref = $env:__SuppressAnsiEscapeSequences diff --git a/test/powershell/Modules/Microsoft.PowerShell.Core/PSSessionConfiguration.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Core/PSSessionConfiguration.Tests.ps1 index 8ab4047c279..48763dc00fa 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Core/PSSessionConfiguration.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Core/PSSessionConfiguration.Tests.ps1 @@ -838,7 +838,7 @@ namespace PowershellTestConfigNamespace } if ($IsNotSkipped) { - Enable-PSRemoting + Enable-PSRemoting -SkipNetworkProfileCheck -Force } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Core/RemoteGetModule.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Core/RemoteGetModule.Tests.ps1 index 95e522ab9aa..d410e4db2f4 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Core/RemoteGetModule.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Core/RemoteGetModule.Tests.ps1 @@ -3,11 +3,22 @@ Describe "Remote module tests" -Tags 'Feature','RequireAdminOnWindows' { BeforeAll { + $pendingTest = (Test-IsWinWow64) + $skipTest = !$IsWindows - if (!$IsWindows -or (Test-IsWinWow64)) + $originalDefaultParameterValues = $PSDefaultParameterValues.Clone() + + if ($pendingTest -or $skipTest) { - $originalDefaultParameterValues = $PSDefaultParameterValues.Clone() - $PSDefaultParameterValues["it:skip"] = $true + if ($skipTest) + { + $PSDefaultParameterValues["it:skip"] = $true + } + elseif ($pendingTest) + { + $PSDefaultParameterValues["it:pending"] = $true + } + return } @@ -18,7 +29,7 @@ Describe "Remote module tests" -Tags 'Feature','RequireAdminOnWindows' { AfterAll { - if (!$IsWindows) + if ($pendingTest -or $skipTest) { $global:PSDefaultParameterValues = $originalDefaultParameterValues return diff --git a/test/powershell/Modules/Microsoft.PowerShell.Core/RemoteImportModule.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Core/RemoteImportModule.Tests.ps1 index ba7f35f0485..19cf4e07871 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Core/RemoteImportModule.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Core/RemoteImportModule.Tests.ps1 @@ -5,8 +5,14 @@ Describe "Remote import-module tests" -Tags 'Feature','RequireAdminOnWindows' { BeforeAll { $originalDefaultParameterValues = $PSDefaultParameterValues.Clone() $modulePath = "$testdrive\Modules\TestImport" - if (!$IsWindows -or (Test-IsWinWow64)) { + + $pendingTest = (Test-IsWinWow64) + $skipTest = !$IsWindows + + if ($skipTest) { $PSDefaultParameterValues["it:skip"] = $true + } elseif ($pendingTest) { + $PSDefaultParameterValues["it:pending"] = $true } else { $pssession = New-RemoteSession Invoke-Command -Session $pssession -Scriptblock { $env:PSModulePath += ";${using:testdrive}" } @@ -21,7 +27,7 @@ Describe "Remote import-module tests" -Tags 'Feature','RequireAdminOnWindows' { AfterAll { $global:PSDefaultParameterValues = $originalDefaultParameterValues - if ($IsWindows) { + if ($IsWindows -and !$pendingTest -and !$skipTest) { $pssession | Remove-PSSession -ErrorAction SilentlyContinue } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/TimeZone.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/TimeZone.Tests.ps1 index 43b1cae28df..5a23c7df75a 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/TimeZone.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/TimeZone.Tests.ps1 @@ -13,14 +13,12 @@ [snippet] Both StandardName and DaylightName are localized according to the current user default UI language. #> -function Assert-ListsSame -{ +function Assert-ListsSame { param([object[]] $expected, [object[]] $observed ) $compResult = Compare-Object $observed $expected | Select-Object -ExpandProperty InputObject - if ($compResult) - { - $observedList = ([string]::Join("|",$observed)) - $expectedList = ([string]::Join("|",$expected)) + if ($compResult) { + $observedList = ([string]::Join("|", $observed)) + $expectedList = ([string]::Join("|", $expected)) $observedList | Should -Be $expectedList } } @@ -53,7 +51,7 @@ Describe "Get-Timezone test cases" -Tags "CI" { $list = Get-TimeZone -ListAvailable $list.Count | Should -BeGreaterThan 0 - ,$list | Should -BeOfType Object[] + , $list | Should -BeOfType Object[] $list[0] | Should -BeOfType TimeZoneInfo } @@ -86,8 +84,8 @@ Describe "Get-Timezone test cases" -Tags "CI" { It "Call Get-TimeZone using ID param and multiple items, where first and third are invalid ids - expect error" { $selectedTZ = $TimeZonesAvailable[0].Id - $null = Get-TimeZone -Id @("Cape Verde Standard",$selectedTZ,"Azores Standard") ` - -ErrorVariable errVar -ErrorAction SilentlyContinue + $null = Get-TimeZone -Id @("Cape Verde Standard", $selectedTZ, "Azores Standard") ` + -ErrorVariable errVar -ErrorAction SilentlyContinue $errVar.Count | Should -Be 2 $errVar[0].FullyQualifiedErrorID | Should -Be "TimeZoneNotFound,Microsoft.PowerShell.Commands.GetTimeZoneCommand" } @@ -126,112 +124,118 @@ Describe "Get-Timezone test cases" -Tags "CI" { } } -try { - $defaultParamValues = $PSdefaultParameterValues.Clone() - # Set-TimeZone fails due to missing ApiSet dependency on Windows Server 2012 R2. - $osInfo = [System.Environment]::OSVersion.Version - $isSrv2k12R2 = $osInfo.Major -eq 6 -and $osInfo.Minor -eq 3 +Describe "Set-Timezone test case: call by single Id" -Tags @('CI', 'RequireAdminOnWindows') { + BeforeAll { - $PSDefaultParameterValues["it:skip"] = !$IsWindows -or $isSrv2k12R2 + $defaultParamValues = $PSdefaultParameterValues.Clone() - Describe "Set-Timezone test case: call by single Id" -Tags @('CI', 'RequireAdminOnWindows') { - BeforeAll { - if ($IsWindows) { - $originalTimeZoneId = (Get-TimeZone).Id - } - } - AfterAll { - if ($IsWindows) { - Set-TimeZone -Id $originalTimeZoneId - } + if (-not $IsWindows -or (Test-IsWinServer2012R2)) { + # Set-TimeZone fails due to missing ApiSet dependency on Windows Server 2012 R2. + $PSDefaultParameterValues["it:skip"] = $true + return } - It "Call Set-TimeZone by Id" { - $origTimeZoneID = (Get-TimeZone).Id - $timezoneList = Get-TimeZone -ListAvailable - $testTimezone = $null - foreach ($timezone in $timezoneList) { - if ($timezone.Id -ne $origTimeZoneID) { - $testTimezone = $timezone - break - } - } - Set-TimeZone -Id $testTimezone.Id - $observed = Get-TimeZone - $testTimezone.Id | Should -Be $observed.Id + $originalTimeZoneId = (Get-TimeZone).Id + } + AfterAll { + if (-not $IsWindows -or (Test-IsWinServer2012R2)) { + $global:PSDefaultParameterValues = $defaultParamValues + return } + + Set-TimeZone -Id $originalTimeZoneId } - Describe "Set-Timezone test cases" -Tags @('Feature', 'RequireAdminOnWindows') { - BeforeAll { - if ($IsWindows) - { - $originalTimeZoneId = (Get-TimeZone).Id + It "Call Set-TimeZone by Id" { + $origTimeZoneID = (Get-TimeZone).Id + $timezoneList = Get-TimeZone -ListAvailable + $testTimezone = $null + foreach ($timezone in $timezoneList) { + if ($timezone.Id -ne $origTimeZoneID) { + $testTimezone = $timezone + break } } - AfterAll { - if ($IsWindows) { - Set-TimeZone -Id $originalTimeZoneId - } + Set-TimeZone -Id $testTimezone.Id + $observed = Get-TimeZone + $testTimezone.Id | Should -Be $observed.Id + } +} + +Describe "Set-Timezone test cases" -Tags @('Feature', 'RequireAdminOnWindows') { + BeforeAll { + $defaultParamValues = $PSdefaultParameterValues.Clone() + + if (-not $IsWindows -or (Test-IsWinServer2012R2)) { + # Set-TimeZone fails due to missing ApiSet dependency on Windows Server 2012 R2. + $PSDefaultParameterValues["it:skip"] = $true + return } - It "Call Set-TimeZone with invalid Id" { - { Set-TimeZone -Id "zzInvalidID" } | Should -Throw -ErrorId "TimeZoneNotFound,Microsoft.PowerShell.Commands.SetTimeZoneCommand" + $originalTimeZoneId = (Get-TimeZone).Id + } + AfterAll { + if (-not $IsWindows -or (Test-IsWinServer2012R2)) { + $global:PSDefaultParameterValues = $defaultParamValues + return } - It "Call Set-TimeZone by Name" { - $origTimeZoneName = (Get-TimeZone).StandardName - $timezoneList = Get-TimeZone -ListAvailable - $testTimezone = $null - foreach ($timezone in $timezoneList) { - if ($timezone.StandardName -ne $origTimeZoneName) { - $testTimezone = $timezone - break - } + Set-TimeZone -Id $originalTimeZoneId + } + + It "Call Set-TimeZone with invalid Id" { + { Set-TimeZone -Id "zzInvalidID" } | Should -Throw -ErrorId "TimeZoneNotFound,Microsoft.PowerShell.Commands.SetTimeZoneCommand" + } + + It "Call Set-TimeZone by Name" { + $origTimeZoneName = (Get-TimeZone).StandardName + $timezoneList = Get-TimeZone -ListAvailable + $testTimezone = $null + foreach ($timezone in $timezoneList) { + if ($timezone.StandardName -ne $origTimeZoneName) { + $testTimezone = $timezone + break } - Set-TimeZone -Name $testTimezone.StandardName - $observed = Get-TimeZone - $testTimezone.StandardName | Should -Be $observed.StandardName } + Set-TimeZone -Name $testTimezone.StandardName + $observed = Get-TimeZone + $testTimezone.StandardName | Should -Be $observed.StandardName + } - It "Call Set-TimeZone with invalid Name" { - { Set-TimeZone -Name "zzINVALID_Name" } | Should -Throw -ErrorId "TimeZoneNotFound,Microsoft.PowerShell.Commands.SetTimeZoneCommand" - } + It "Call Set-TimeZone with invalid Name" { + { Set-TimeZone -Name "zzINVALID_Name" } | Should -Throw -ErrorId "TimeZoneNotFound,Microsoft.PowerShell.Commands.SetTimeZoneCommand" + } - It "Call Set-TimeZone from pipeline input object of type TimeZoneInfo" { - $origTimeZoneID = (Get-TimeZone).Id - $timezoneList = Get-TimeZone -ListAvailable - $testTimezone = $null - foreach ($timezone in $timezoneList) { - if ($timezone.Id -ne $origTimeZoneID) { - $testTimezone = $timezone - break - } + It "Call Set-TimeZone from pipeline input object of type TimeZoneInfo" { + $origTimeZoneID = (Get-TimeZone).Id + $timezoneList = Get-TimeZone -ListAvailable + $testTimezone = $null + foreach ($timezone in $timezoneList) { + if ($timezone.Id -ne $origTimeZoneID) { + $testTimezone = $timezone + break } - - $testTimezone | Set-TimeZone - $observed = Get-TimeZone - $observed.ID | Should -Be $testTimezone.Id } - It "Call Set-TimeZone from pipeline input object of type TimeZoneInfo, verify supports whatif" { - $origTimeZoneID = (Get-TimeZone).Id - $timezoneList = Get-TimeZone -ListAvailable - $testTimezone = $null - foreach ($timezone in $timezoneList) { - if ($timezone.Id -ne $origTimeZoneID) { - $testTimezone = $timezone - break - } - } + $testTimezone | Set-TimeZone + $observed = Get-TimeZone + $observed.ID | Should -Be $testTimezone.Id + } - Set-TimeZone -Id $testTimezone.Id -WhatIf > $null - $observed = Get-TimeZone - $observed.Id | Should -Be $origTimeZoneID + It "Call Set-TimeZone from pipeline input object of type TimeZoneInfo, verify supports whatif" { + $origTimeZoneID = (Get-TimeZone).Id + $timezoneList = Get-TimeZone -ListAvailable + $testTimezone = $null + foreach ($timezone in $timezoneList) { + if ($timezone.Id -ne $origTimeZoneID) { + $testTimezone = $timezone + break + } } + + Set-TimeZone -Id $testTimezone.Id -WhatIf > $null + $observed = Get-TimeZone + $observed.Id | Should -Be $origTimeZoneID } } -finally { - $global:PSDefaultParameterValues = $defaultParamValues -} diff --git a/test/powershell/engine/Formatting/OutputRendering.Tests.ps1 b/test/powershell/engine/Formatting/OutputRendering.Tests.ps1 index dda4bdbd1eb..52aef0151af 100644 --- a/test/powershell/engine/Formatting/OutputRendering.Tests.ps1 +++ b/test/powershell/engine/Formatting/OutputRendering.Tests.ps1 @@ -7,7 +7,7 @@ Describe 'OutputRendering tests' -Tag 'CI' { # Console host does not support VT100 escape sequences on Windows 2012R2 or earlier if (-not $host.ui.SupportsVirtualTerminal) { - $global:PSDefaultParameterValues["it:skip"] = $true + $PSDefaultParameterValues["it:skip"] = $true } } diff --git a/test/powershell/engine/Remoting/RemoteSession.Disconnect.Tests.ps1 b/test/powershell/engine/Remoting/RemoteSession.Disconnect.Tests.ps1 index a6a4f23e082..60c69c09a03 100644 --- a/test/powershell/engine/Remoting/RemoteSession.Disconnect.Tests.ps1 +++ b/test/powershell/engine/Remoting/RemoteSession.Disconnect.Tests.ps1 @@ -7,7 +7,15 @@ Describe "WinRM based remoting session abrupt disconnect" -Tags 'Feature','Requi BeforeAll { $originalDefaultParameterValues = $PSDefaultParameterValues.Clone() - if (! $IsWindows -or (Test-IsWinWow64)) + $pendingTest = (Test-IsWinWow64) + $skipTest = !$IsWindows + + if ($pendingTest) + { + $PSDefaultParameterValues["it:pending"] = $true + return + } + elseif ($skipTest) { $PSDefaultParameterValues["it:skip"] = $true return @@ -56,6 +64,11 @@ Describe "WinRM based remoting session abrupt disconnect" -Tags 'Feature','Requi AfterAll { $global:PSDefaultParameterValues = $originalDefaultParameterValues + if ($pendingTest -or $skipTest) + { + return + } + if ($ps -ne $null) { $ps.Dispose() } if ($session -ne $null) { Remove-PSSession -Session $session } if ($script:job -ne $null) { Remove-Job -Job $script:job -Force } diff --git a/test/powershell/engine/Remoting/RunspacePool.Tests.ps1 b/test/powershell/engine/Remoting/RunspacePool.Tests.ps1 index f4481c85eb0..6f5ad9f1131 100644 --- a/test/powershell/engine/Remoting/RunspacePool.Tests.ps1 +++ b/test/powershell/engine/Remoting/RunspacePool.Tests.ps1 @@ -8,40 +8,44 @@ Describe "Remote runspace pool should expose commands in endpoint configuration" BeforeAll { - if ($IsWindows -and (Test-CanWriteToPsHome) -and -not (Test-IsWinWow64)) - { - $configName = "restrictedV" - $configPath = Join-Path $TestDrive ($configName + ".pssc") - - New-PSSessionConfigurationFile -Path $configPath -SessionType RestrictedRemoteServer -VisibleCmdlets 'Get-CimInstance' + $pendingTest = (Test-IsWinWow64) + $skipTest = !$IsWindows -or !(Test-CanWriteToPsHome) - $null = Register-PSSessionConfiguration -Name $configName -Path $configPath -Force -ErrorAction SilentlyContinue + $originalDefaultParameterValues = $PSDefaultParameterValues.Clone() - $remoteRunspacePool = New-RemoteRunspacePool -ConfigurationName $configName + if ($pendingTest) { + $PSDefaultParameterValues["it:pending"] = $true + return } - elseif (Test-IsWinWow64) - { - $originalDefaultParameterValues = $PSDefaultParameterValues.Clone() + + if ($skipTest) { $PSDefaultParameterValues["it:skip"] = $true + return } + + $configName = "restrictedV" + $configPath = Join-Path $TestDrive ($configName + ".pssc") + + New-PSSessionConfigurationFile -Path $configPath -SessionType RestrictedRemoteServer -VisibleCmdlets 'Get-CimInstance' + + $null = Register-PSSessionConfiguration -Name $configName -Path $configPath -Force -ErrorAction SilentlyContinue + + $remoteRunspacePool = New-RemoteRunspacePool -ConfigurationName $configName } AfterAll { - if (Test-IsWinWow64) { + if ($pendingTest -or $skipTest) { $global:PSDefaultParameterValues = $originalDefaultParameterValues return } - if ($IsWindows -and (Test-CanWriteToPsHome)) + if ($remoteRunspacePool -ne $null) { - if ($remoteRunspacePool -ne $null) - { - $remoteRunspacePool.Dispose() - } - - Unregister-PSSessionConfiguration -Name $configName -Force -ErrorAction SilentlyContinue + $remoteRunspacePool.Dispose() } + + Unregister-PSSessionConfiguration -Name $configName -Force -ErrorAction SilentlyContinue } It "Verifies that the configured endpoint cmdlet is available in all runspace pool instances" -Skip:(!$IsWindows -or !(Test-CanWriteToPsHome)) { diff --git a/test/tools/Modules/HelpersCommon/HelpersCommon.psd1 b/test/tools/Modules/HelpersCommon/HelpersCommon.psd1 index f11f5432adf..ca9fb8a8131 100644 --- a/test/tools/Modules/HelpersCommon/HelpersCommon.psd1 +++ b/test/tools/Modules/HelpersCommon/HelpersCommon.psd1 @@ -36,6 +36,7 @@ FunctionsToExport = @( 'Test-IsVstsLinux' 'Test-IsVstsWindows' 'Test-IsWindowsArm64' + 'Test-IsWinServer2012R2' 'Test-IsWinWow64' 'Test-TesthookIsSet' 'Wait-FileToBePresent' diff --git a/test/tools/Modules/HelpersCommon/HelpersCommon.psm1 b/test/tools/Modules/HelpersCommon/HelpersCommon.psm1 index 013bd2cf700..d59b64b7942 100644 --- a/test/tools/Modules/HelpersCommon/HelpersCommon.psm1 +++ b/test/tools/Modules/HelpersCommon/HelpersCommon.psm1 @@ -446,3 +446,13 @@ function Test-IsReleaseCandidate return $false } + +function Test-IsWinServer2012R2 +{ + if (-not $IsWindows) { + return $false + } + + $osInfo = [System.Environment]::OSVersion.Version + return ($osInfo.Major -eq 6 -and $osInfo.Minor -eq 3) +} From 93e9c63331f34af6c535654e585ace99ab36d28f Mon Sep 17 00:00:00 2001 From: Jordan Borean Date: Wed, 26 Apr 2023 05:11:04 +1000 Subject: [PATCH 498/779] Fix `Get-AuthenticodeSignature -Content` to not roundtrip the bytes to a Unicode string and then back to bytes (#18774) --- .../security/SignatureCommands.cs | 2 +- .../security/Authenticode.cs | 27 ++-- .../security/SecurityManager.cs | 19 ++- .../engine/Security/FileSignature.Tests.ps1 | 148 ++++++++++++++++++ 4 files changed, 179 insertions(+), 17 deletions(-) diff --git a/src/Microsoft.PowerShell.Security/security/SignatureCommands.cs b/src/Microsoft.PowerShell.Security/security/SignatureCommands.cs index 411c7952ea8..09fefdfb8e9 100644 --- a/src/Microsoft.PowerShell.Security/security/SignatureCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/SignatureCommands.cs @@ -294,7 +294,7 @@ protected override Signature PerformAction(string filePath) /// protected override Signature PerformAction(string sourcePathOrExtension, byte[] content) { - return SignatureHelper.GetSignature(sourcePathOrExtension, System.Text.Encoding.Unicode.GetString(content)); + return SignatureHelper.GetSignature(sourcePathOrExtension, content); } } diff --git a/src/System.Management.Automation/security/Authenticode.cs b/src/System.Management.Automation/security/Authenticode.cs index e732420b188..591f64d6298 100644 --- a/src/System.Management.Automation/security/Authenticode.cs +++ b/src/System.Management.Automation/security/Authenticode.cs @@ -275,7 +275,7 @@ internal static Signature SignFile(SigningOption option, /// /// Thrown if the file specified by argument fileName is not found. /// - internal static Signature GetSignature(string fileName, string fileContent) + internal static Signature GetSignature(string fileName, byte[] fileContent) { Signature signature = null; @@ -398,7 +398,7 @@ private static uint GetErrorFromSignatureState(SignatureState signatureState) } #endif - private static Signature GetSignatureFromWinVerifyTrust(string fileName, string fileContent) + private static Signature GetSignatureFromWinVerifyTrust(string fileName, byte[] fileContent) { Signature signature = null; @@ -409,6 +409,7 @@ private static Signature GetSignatureFromWinVerifyTrust(string fileName, string { Utils.CheckArgForNullOrEmpty(fileName, "fileName"); SecuritySupport.CheckIfFileExists(fileName); + // SecurityUtils.CheckIfFileSmallerThan4Bytes(fileName); } @@ -424,7 +425,8 @@ private static Signature GetSignatureFromWinVerifyTrust(string fileName, string signature = GetSignatureFromWintrustData(fileName, error, wtd); wtd.dwStateAction = WinTrustAction.WTD_STATEACTION_CLOSE; - error = WinTrustMethods.WinVerifyTrust(IntPtr.Zero, + error = WinTrustMethods.WinVerifyTrust( + IntPtr.Zero, ref WINTRUST_ACTION_GENERIC_VERIFY_V2, ref wtd); @@ -441,8 +443,10 @@ private static Signature GetSignatureFromWinVerifyTrust(string fileName, string return signature; } - private static uint GetWinTrustData(string fileName, string fileContent, - out WinTrustMethods.WINTRUST_DATA wtData) + private static uint GetWinTrustData( + string fileName, + byte[] fileContent, + out WinTrustMethods.WINTRUST_DATA wtData) { wtData = new() { @@ -451,9 +455,6 @@ private static uint GetWinTrustData(string fileName, string fileContent, dwStateAction = WinTrustAction.WTD_STATEACTION_VERIFY, }; - byte[] contentBytes = fileContent == null - ? Array.Empty() - : System.Text.Encoding.Unicode.GetBytes(fileContent); unsafe { fixed (char* fileNamePtr = fileName) @@ -468,12 +469,13 @@ private static uint GetWinTrustData(string fileName, string fileContent, wtData.dwUnionChoice = WinTrustUnionChoice.WTD_CHOICE_FILE; wtData.pChoice = &wfi; - return WinTrustMethods.WinVerifyTrust(IntPtr.Zero, + return WinTrustMethods.WinVerifyTrust( + IntPtr.Zero, ref WINTRUST_ACTION_GENERIC_VERIFY_V2, ref wtData); } - fixed (byte* contentPtr = contentBytes) + fixed (byte* contentPtr = fileContent) { Guid pwshSIP = new("603BCC1F-4B59-4E08-B724-D2C6297EF351"); WinTrustMethods.WINTRUST_BLOB_INFO wbi = new() @@ -481,13 +483,14 @@ private static uint GetWinTrustData(string fileName, string fileContent, cbStruct = (uint)Marshal.SizeOf(), gSubject = pwshSIP, pcwszDisplayName = fileNamePtr, - cbMemObject = (uint)contentBytes.Length, + cbMemObject = (uint)fileContent.Length, pbMemObject = contentPtr, }; wtData.dwUnionChoice = WinTrustUnionChoice.WTD_CHOICE_BLOB; wtData.pChoice = &wbi; - return WinTrustMethods.WinVerifyTrust(IntPtr.Zero, + return WinTrustMethods.WinVerifyTrust( + IntPtr.Zero, ref WINTRUST_ACTION_GENERIC_VERIFY_V2, ref wtData); } diff --git a/src/System.Management.Automation/security/SecurityManager.cs b/src/System.Management.Automation/security/SecurityManager.cs index 5397ce2a048..38a9aa511dc 100644 --- a/src/System.Management.Automation/security/SecurityManager.cs +++ b/src/System.Management.Automation/security/SecurityManager.cs @@ -542,16 +542,16 @@ private static Signature GetSignatureWithEncodingRetry(string path, ExternalScri // try harder to validate the signature by being explicit about encoding // and providing the script contents - string verificationContents = Encoding.Unicode.GetString(script.OriginalEncoding.GetPreamble()) + script.ScriptContents; - signature = SignatureHelper.GetSignature(path, verificationContents); + byte[] bytesWithBom = GetContentBytesWithBom(script.OriginalEncoding, script.ScriptContents); + signature = SignatureHelper.GetSignature(path, bytesWithBom); // A last ditch effort - // If the file was originally ASCII or UTF8, the SIP may have added the Unicode BOM if (signature.Status != SignatureStatus.Valid && script.OriginalEncoding != Encoding.Unicode) { - verificationContents = Encoding.Unicode.GetString(Encoding.Unicode.GetPreamble()) + script.ScriptContents; - Signature fallbackSignature = SignatureHelper.GetSignature(path, verificationContents); + bytesWithBom = GetContentBytesWithBom(Encoding.Unicode, script.ScriptContents); + Signature fallbackSignature = SignatureHelper.GetSignature(path, bytesWithBom); if (fallbackSignature.Status == SignatureStatus.Valid) signature = fallbackSignature; @@ -560,6 +560,17 @@ private static Signature GetSignatureWithEncodingRetry(string path, ExternalScri return signature; } + private static byte[] GetContentBytesWithBom(Encoding encoding, string scriptContent) + { + ReadOnlySpan bomBytes = encoding.Preamble; + byte[] contentBytes = encoding.GetBytes(scriptContent); + byte[] bytesWithBom = new byte[bomBytes.Length + contentBytes.Length]; + + bomBytes.CopyTo(bytesWithBom); + contentBytes.CopyTo(bytesWithBom, index: bomBytes.Length); + return bytesWithBom; + } + #endregion signing check /// diff --git a/test/powershell/engine/Security/FileSignature.Tests.ps1 b/test/powershell/engine/Security/FileSignature.Tests.ps1 index 892aa0e40ea..948ff4d1a8b 100644 --- a/test/powershell/engine/Security/FileSignature.Tests.ps1 +++ b/test/powershell/engine/Security/FileSignature.Tests.ps1 @@ -20,3 +20,151 @@ Describe "Windows platform file signatures" -Tags 'Feature' { $signature.SignatureType | Should -BeExactly 'Catalog' } } + +Describe "Windows file content signatures" -Tags @('Feature', 'RequireAdminOnWindows') { + $PSDefaultParameterValues = @{ "It:Skip" = (-not $IsWindows) } + + BeforeAll { + $session = New-PSSession -UseWindowsPowerShell + try { + # New-SelfSignedCertificate runs in implicit remoting so do all the + # setup work over there + $caRootThumbprint, $signingThumbprint = Invoke-Command -Session $session -ScriptBlock { + $testPrefix = 'SelfSignedTest' + + $enhancedKeyUsage = [Security.Cryptography.OidCollection]::new() + $null = $enhancedKeyUsage.Add('1.3.6.1.5.5.7.3.3') # Code Signing + + $caParams = @{ + Extension = @( + [Security.Cryptography.X509Certificates.X509BasicConstraintsExtension]::new($true, $false, 0, $true), + [Security.Cryptography.X509Certificates.X509KeyUsageExtension]::new('KeyCertSign', $false), + [Security.Cryptography.X509Certificates.X509EnhancedKeyUsageExtension ]::new($enhancedKeyUsage, $false) + ) + CertStoreLocation = 'Cert:\CurrentUser\My' + NotAfter = (Get-Date).AddDays(1) + Type = 'Custom' + } + $caRoot = PKI\New-SelfSignedCertificate @caParams -Subject "CN=$testPrefix-CA" + + $rootStore = Get-Item -Path Cert:\LocalMachine\Root + $rootStore.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite) + try { + $rootStore.Add([System.Security.Cryptography.X509Certificates.X509Certificate2]::new($caRoot.RawData)) + } finally { + $rootStore.Close() + } + + $certParams = @{ + CertStoreLocation = 'Cert:\CurrentUser\My' + KeyUsage = 'DigitalSignature' + TextExtension = @("2.5.29.37={text}1.3.6.1.5.5.7.3.3", "2.5.29.19={text}") + Type = 'Custom' + } + $certificate = PKI\New-SelfSignedCertificate @certParams -Subject "CN=$testPrefix-Signed" -Signer $caRoot + + $publisherStore = Get-Item -Path Cert:\LocalMachine\TrustedPublisher + $publisherStore.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite) + try { + $publisherStore.Add([System.Security.Cryptography.X509Certificates.X509Certificate2]::new($certificate.RawData)) + } finally { + $publisherStore.Close() + } + + $caRoot | Remove-Item + + $caRoot.Thumbprint, $certificate.Thumbprint + } + } finally { + $session | Remove-PSSession + } + + $certificate = Get-Item -Path Cert:\CurrentUser\My\$signingThumbprint + } + + AfterAll { + Remove-Item -Path Cert:\LocalMachine\Root\$caRootThumbprint -Force + Remove-Item -Path Cert:\LocalMachine\TrustedPublisher\$signingThumbprint -Force + Remove-Item -Path Cert:\CurrentUser\My\$signingThumbprint -Force + } + + It "Validates signature using path on even char count with Encoding " -TestCases @( + @{ Encoding = 'ASCII' } + @{ Encoding = 'Unicode' } + @{ Encoding = 'UTF8BOM' } + @{ Encoding = 'UTF8NoBOM' } + ) { + param ($Encoding) + + Set-Content -Path testdrive:\test.ps1 -Value 'Write-Output "Hello World"' -Encoding $Encoding + + $scriptPath = Join-Path $TestDrive test.ps1 + $status = Set-AuthenticodeSignature -FilePath $scriptPath -Certificate $certificate + $status.Status | Should -Be 'Valid' + + $actual = Get-AuthenticodeSignature -FilePath $scriptPath + $actual.SignerCertificate.Thumbprint | Should -Be $certificate.Thumbprint + $actual.Status | Should -Be 'Valid' + } + + It "Validates signature using path on odd char count with Encoding " -TestCases @( + @{ Encoding = 'ASCII' } + @{ Encoding = 'Unicode' } + @{ Encoding = 'UTF8BOM' } + @{ Encoding = 'UTF8NoBOM' } + ) { + param ($Encoding) + + Set-Content -Path testdrive:\test.ps1 -Value 'Write-Output "Hello World!"' -Encoding $Encoding + + $scriptPath = Join-Path $TestDrive test.ps1 + $status = Set-AuthenticodeSignature -FilePath $scriptPath -Certificate $certificate + $status.Status | Should -Be 'Valid' + + $actual = Get-AuthenticodeSignature -FilePath $scriptPath + $actual.SignerCertificate.Thumbprint | Should -Be $certificate.Thumbprint + $actual.Status | Should -Be 'Valid' + } + + It "Validates signature using content on even char count with Encoding " -TestCases @( + @{ Encoding = 'ASCII' } + @{ Encoding = 'Unicode' } + @{ Encoding = 'UTF8BOM' } + @{ Encoding = 'UTF8NoBOM' } + ) { + param ($Encoding) + + Set-Content -Path testdrive:\test.ps1 -Value 'Write-Output "Hello World"' -Encoding $Encoding + + $scriptPath = Join-Path $TestDrive test.ps1 + $status = Set-AuthenticodeSignature -FilePath $scriptPath -Certificate $certificate + $status.Status | Should -Be 'Valid' + + $fileBytes = Get-Content -Path testdrive:\test.ps1 -AsByteStream + + $actual = Get-AuthenticodeSignature -Content $fileBytes -SourcePathOrExtension .ps1 + $actual.SignerCertificate.Thumbprint | Should -Be $certificate.Thumbprint + $actual.Status | Should -Be 'Valid' + } + + It "Validates signature using content on odd char count with Encoding " -TestCases @( + @{ Encoding = 'ASCII' } + @{ Encoding = 'Unicode' } + @{ Encoding = 'UTF8BOM' } + @{ Encoding = 'UTF8NoBOM' } + ) { + param ($Encoding) + + Set-Content -Path testdrive:\test.ps1 -Value 'Write-Output "Hello World!"' -Encoding $Encoding + + $scriptPath = Join-Path $TestDrive test.ps1 + $status = Set-AuthenticodeSignature -FilePath $scriptPath -Certificate $certificate + $status.Status | Should -Be 'Valid' + + $fileBytes = Get-Content -Path testdrive:\test.ps1 -AsByteStream + + $actual = Get-AuthenticodeSignature -Content $fileBytes -SourcePathOrExtension .ps1 + $actual.SignerCertificate.Thumbprint | Should -Be $certificate.Thumbprint + $actual.Status | Should -Be 'Valid' + } +} From cbe18db47bf0491f0f1ba5fa9d0e6676c0db90cc Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Wed, 26 Apr 2023 09:47:53 -0700 Subject: [PATCH 499/779] Add backport function to release tools (#19568) * Add backport function * delete backport action --- .github/workflows/backport.yml | 66 ------------- tools/actions/backport/action.yml | 20 ---- tools/actions/backport/index.js | 157 ------------------------------ tools/releaseTools.psm1 | 84 +++++++++++++++- 4 files changed, 83 insertions(+), 244 deletions(-) delete mode 100644 .github/workflows/backport.yml delete mode 100644 tools/actions/backport/action.yml delete mode 100644 tools/actions/backport/index.js diff --git a/.github/workflows/backport.yml b/.github/workflows/backport.yml deleted file mode 100644 index 0dd8b331051..00000000000 --- a/.github/workflows/backport.yml +++ /dev/null @@ -1,66 +0,0 @@ -name: Backport PR to branch -on: - issue_comment: - types: [created] - -permissions: - contents: write - issues: write - pull-requests: write - -jobs: - backport: - if: github.event.issue.pull_request != '' && contains(github.event.comment.body, '/backport to') - runs-on: ubuntu-20.04 - steps: - - name: Extract backport target branch - uses: actions/github-script@v6 - id: target-branch-extractor - with: - result-encoding: string - script: | - if (context.eventName !== "issue_comment") throw "Error: This action only works on issue_comment events."; - - // extract the target branch name from the trigger phrase containing these characters: a-z, A-Z, digits, forward slash, dot, hyphen, underscore - const regex = /^\/backport to ([a-zA-Z\d\/\.\-\_]+)/; - target_branch = regex.exec(context.payload.comment.body); - if (target_branch == null) throw "Error: No backport branch found in the trigger phrase."; - - return target_branch[1]; - - name: Post backport started comment to pull request - uses: actions/github-script@v6 - continue-on-error: true - with: - script: | - const backport_start_body = `Started backporting to ${{ steps.target-branch-extractor.outputs.result }}: https://github.com/${context.repo.owner}/${context.repo.repo}/actions/runs/${process.env.GITHUB_RUN_ID}`; - console.log(`issue_number: ${context.issue.number}`); - console.log(`owner: ${context.repo.owner}`); - console.log(`repo: ${context.repo.repo}`); - console.log(`body: ${backport_start_body}`); - await github.issues.createComment({ - issue_number: context.issue.number, - owner: context.repo.owner, - repo: context.repo.repo, - body: backport_start_body - }); - - name: Checkout repo - uses: actions/checkout@v3 - with: - fetch-depth: 0 - - name: Run backport - uses: ./tools/actions/backport - with: - target_branch: ${{ steps.target-branch-extractor.outputs.result }} - auth_token: ${{ secrets.GITHUB_TOKEN }} - pr_description_template: | - Backport of #%source_pr_number% to %target_branch% - - /cc %cc_users% - - ## Customer Impact - - ## Testing - - - [ ] For any change that affects the release process, please work with a maintainer to come up with a plan to test this. - - ## Risk diff --git a/tools/actions/backport/action.yml b/tools/actions/backport/action.yml deleted file mode 100644 index e596f1dd586..00000000000 --- a/tools/actions/backport/action.yml +++ /dev/null @@ -1,20 +0,0 @@ -name: 'PR Backporter' -description: 'Backports a pull request to a branch using the "/backport to " comment' -inputs: - target_branch: - description: 'Backport target branch.' - auth_token: - description: 'The token used to authenticate to GitHub.' - pr_title_template: - description: 'The template used for the PR title. Special placeholder tokens that will be replaced with a value: %target_branch%, %source_pr_title%, %source_pr_number%, %cc_users%.' - default: '[%target_branch%] %source_pr_title%' - pr_description_template: - description: 'The template used for the PR description. Special placeholder tokens that will be replaced with a value: %target_branch%, %source_pr_title%, %source_pr_number%, %cc_users%.' - default: | - Backport of #%source_pr_number% to %target_branch% - - /cc %cc_users% - -runs: - using: 'node12' - main: 'index.js' diff --git a/tools/actions/backport/index.js b/tools/actions/backport/index.js deleted file mode 100644 index 88d348f167d..00000000000 --- a/tools/actions/backport/index.js +++ /dev/null @@ -1,157 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// from https://github.com/dotnet/runtime/blob/main/eng/actions/backport/index.js - -function BackportException(message, postToGitHub = true) { - this.message = message; - this.postToGitHub = postToGitHub; - } - - async function run() { - const util = require("util"); - const jsExec = util.promisify(require("child_process").exec); - - console.log("Installing npm dependencies"); - const { stdout, stderr } = await jsExec("npm install @actions/core @actions/github @actions/exec"); - console.log("npm-install stderr:\n\n" + stderr); - console.log("npm-install stdout:\n\n" + stdout); - console.log("Finished installing npm dependencies"); - - const core = require("@actions/core"); - const github = require("@actions/github"); - const exec = require("@actions/exec"); - - const repo_owner = github.context.payload.repository.owner.login; - const repo_name = github.context.payload.repository.name; - const pr_number = github.context.payload.issue.number; - const comment_user = github.context.payload.comment.user.login; - - let octokit = github.getOctokit(core.getInput("auth_token", { required: true })); - let target_branch = core.getInput("target_branch", { required: true }); - - try { - // verify the comment user is a repo collaborator - try { - await octokit.rest.repos.checkCollaborator({ - owner: repo_owner, - repo: repo_name, - username: comment_user - }); - console.log(`Verified ${comment_user} is a repo collaborator.`); - } catch (error) { - console.log(error); - throw new BackportException(`Error: @${comment_user} is not a repo collaborator, backporting is not allowed. If you're a collaborator please make sure your Microsoft team membership visibility is set to Public on https://github.com/orgs/microsoft/people?query=${comment_user}`); - } - - try { await exec.exec(`git ls-remote --exit-code --heads origin ${target_branch}`) } catch { throw new BackportException(`Error: The specified backport target branch ${target_branch} wasn't found in the repo.`); } - console.log(`Backport target branch: ${target_branch}`); - - console.log("Applying backport patch"); - - await exec.exec(`git checkout ${target_branch}`); - await exec.exec(`git clean -xdff`); - - // configure git - await exec.exec(`git config user.name "github-actions"`); - await exec.exec(`git config user.email "github-actions@github.com"`); - - // create temporary backport branch - const temp_branch = `backport/pr-${pr_number}-to-${target_branch}`; - await exec.exec(`git checkout -b ${temp_branch}`); - - // skip opening PR if the branch already exists on the origin remote since that means it was opened - // by an earlier backport and force pushing to the branch updates the existing PR - let should_open_pull_request = true; - try { - await exec.exec(`git ls-remote --exit-code --heads origin ${temp_branch}`); - should_open_pull_request = false; - } catch { } - - // download and apply patch - await exec.exec(`curl -sSL "${github.context.payload.issue.pull_request.patch_url}" --output changes.patch`); - - const git_am_command = "git am --3way --ignore-whitespace --keep-non-patch changes.patch"; - let git_am_output = `$ ${git_am_command}\n\n`; - let git_am_failed = false; - try { - await exec.exec(git_am_command, [], { - listeners: { - stdout: function stdout(data) { git_am_output += data; }, - stderr: function stderr(data) { git_am_output += data; } - } - }); - } catch (error) { - git_am_output += error; - git_am_failed = true; - } - - if (git_am_failed) { - const git_am_failed_body = `@${github.context.payload.comment.user.login} backporting to ${target_branch} failed, the patch most likely resulted in conflicts:\n\n\`\`\`shell\n${git_am_output}\n\`\`\`\n\nPlease backport manually!`; - await octokit.rest.issues.createComment({ - owner: repo_owner, - repo: repo_name, - issue_number: pr_number, - body: git_am_failed_body - }); - throw new BackportException("Error: git am failed, most likely due to a merge conflict.", false); - } - else { - // push the temp branch to the repository - await exec.exec(`git push --force --set-upstream origin HEAD:${temp_branch}`); - } - - if (!should_open_pull_request) { - console.log("Backport temp branch already exists, skipping opening a PR."); - return; - } - - // prepate the GitHub PR details - let backport_pr_title = core.getInput("pr_title_template"); - let backport_pr_description = core.getInput("pr_description_template"); - - // get users to cc (append PR author if different from user who issued the backport command) - let cc_users = `@${comment_user}`; - if (comment_user != github.context.payload.issue.user.login) cc_users += ` @${github.context.payload.issue.user.login}`; - - // replace the special placeholder tokens with values - backport_pr_title = backport_pr_title - .replace(/%target_branch%/g, target_branch) - .replace(/%source_pr_title%/g, github.context.payload.issue.title) - .replace(/%source_pr_number%/g, github.context.payload.issue.number) - .replace(/%cc_users%/g, cc_users); - - backport_pr_description = backport_pr_description - .replace(/%target_branch%/g, target_branch) - .replace(/%source_pr_title%/g, github.context.payload.issue.title) - .replace(/%source_pr_number%/g, github.context.payload.issue.number) - .replace(/%cc_users%/g, cc_users); - - // open the GitHub PR - await octokit.rest.pulls.create({ - owner: repo_owner, - repo: repo_name, - title: backport_pr_title, - body: backport_pr_description, - head: temp_branch, - base: target_branch - }); - - console.log("Successfully opened the GitHub PR."); - } catch (error) { - - core.setFailed(error); - - if (error.postToGitHub === undefined || error.postToGitHub == true) { - // post failure to GitHub comment - const unknown_error_body = `@${comment_user} an error occurred while backporting to ${target_branch}, please check the run log for details!\n\n${error.message}`; - await octokit.rest.issues.createComment({ - owner: repo_owner, - repo: repo_name, - issue_number: pr_number, - body: unknown_error_body - }); - } - } - } - - run(); diff --git a/tools/releaseTools.psm1 b/tools/releaseTools.psm1 index 65c6fc54ed4..f156a8e1044 100644 --- a/tools/releaseTools.psm1 +++ b/tools/releaseTools.psm1 @@ -724,4 +724,86 @@ function Get-PRBackportReport { } } -Export-ModuleMember -Function Get-ChangeLog, Get-NewOfficalPackage, Update-PsVersionInCode, Get-PRBackportReport +# Backports a PR +# requires: +# * a remote called upstream pointing to powershell/powershell +# * the github cli installed and authenticated +# Usage: +# Invoke-PRBackport -PRNumber 1234 -Target release/v7.0.1 +# To overwrite a local branch add -Overwrite +# To add an postfix to the branch name use -BranchPostFix +function Invoke-PRBackport { + [cmdletbinding(SupportsShouldProcess, ConfirmImpact = 'High')] + param( + [Parameter(Mandatory)] + [string] + $PrNumber, + + [Parameter(Mandatory)] + [ValidateScript({$_ -match '^release/v\d+\.\d+\.\d+'})] + [string] + $Target, + + [switch] + $Overwrite, + + [string] + $BranchPostFix + ) + function script:Invoke-NativeCommand { + param( + [scriptblock] $ScriptBlock + ) + &$ScriptBlock + if ($LASTEXITCODE -ne 0) { + throw "$ScriptBlock fail with $LASTEXITCODE" + } + } + $ErrorActionPreference = 'stop' + + $pr = gh pr view $PrNumber --json 'mergeCommit,state,title' | ConvertFrom-Json + + $commitId = $pr.mergeCommit.oid + $state = $pr.state + $originaltitle = $pr.title + $backportTitle = "[$Target]$originalTitle" + + Write-Verbose -Verbose "commitId: $commitId; state: $state" + Write-Verbose -Verbose "title:$backportTitle" + + if ($state -ne 'MERGED') { + throw "PR is not merged ($state)" + } + + $upstream = $null + $upstreamName = 'powershell/powershell' + $upstream = Invoke-NativeCommand { git remote -v } | Where-Object { $_ -match "^upstream.*$upstreamName.*fetch" } + + if (!$upstream) { + throw "Please create an upstream remote that points to $upstreamName" + } + + Invoke-NativeCommand { git fetch upstream $Target } + + $switch = '-c' + if ($Overwrite) { + $switch = '-C' + } + + $branchName = "backport-$PrNumber" + if ($BranchPostFix) { + $branchName += "-$BranchPostFix" + } + + if ($PSCmdlet.ShouldProcess("Create branch $branchName from upstream/$Target")) { + Invoke-NativeCommand { git switch upstream/$Target $switch $branchName } + } + + Invoke-NativeCommand { git cherry-pick $commitId } + + if ($PSCmdlet.ShouldProcess("Create the PR")) { + gh pr create --base $Target --title $backportTitle --body "Backport #$PrNumber" + } +} + +Export-ModuleMember -Function Get-ChangeLog, Get-NewOfficalPackage, Update-PsVersionInCode, Get-PRBackportReport, Invoke-PRBackport From 6e34b1b7ac5cc520600da1bbdb588202aac48328 Mon Sep 17 00:00:00 2001 From: Andy Jordan <2226434+andschwa@users.noreply.github.com> Date: Wed, 26 Apr 2023 11:33:28 -0700 Subject: [PATCH 500/779] Add Git mailmap for Andy Jordan (#19469) This makes Git transparently remap commits under my prior name and email to my new name and Microsoft email. --- .mailmap | 1 + 1 file changed, 1 insertion(+) create mode 100644 .mailmap diff --git a/.mailmap b/.mailmap new file mode 100644 index 00000000000..0bc786ac445 --- /dev/null +++ b/.mailmap @@ -0,0 +1 @@ +Andy Jordan From 2424ad83aa4d44fe9e8f507485744e00c66cde58 Mon Sep 17 00:00:00 2001 From: Patrick Meinecke Date: Thu, 27 Apr 2023 20:17:32 -0400 Subject: [PATCH 501/779] Support byte stream piping between native commands and file redirection (#17857) --- .../engine/AsyncByteStreamTransfer.cs | 83 +++++ .../engine/BytePipe.cs | 115 ++++++ .../ExperimentalFeature.cs | 4 + .../engine/NativeCommandProcessor.cs | 220 +++++++++-- .../engine/pipeline.cs | 31 ++ .../engine/runtime/Operations/MiscOps.cs | 37 +- .../utils/PathUtils.cs | 351 +++++++++++++++--- .../Basic/NativeCommandBytePiping.Tests.ps1 | 66 ++++ test/tools/TestExe/TestExe.cs | 48 +++ 9 files changed, 877 insertions(+), 78 deletions(-) create mode 100644 src/System.Management.Automation/engine/AsyncByteStreamTransfer.cs create mode 100644 src/System.Management.Automation/engine/BytePipe.cs create mode 100644 test/powershell/engine/Basic/NativeCommandBytePiping.Tests.ps1 diff --git a/src/System.Management.Automation/engine/AsyncByteStreamTransfer.cs b/src/System.Management.Automation/engine/AsyncByteStreamTransfer.cs new file mode 100644 index 00000000000..f1391924d6b --- /dev/null +++ b/src/System.Management.Automation/engine/AsyncByteStreamTransfer.cs @@ -0,0 +1,83 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System.Buffers; +using System.IO; +using System.Threading; +using System.Threading.Tasks; + +namespace System.Management.Automation; + +/// +/// Represents the transfer of bytes from one to another +/// asynchronously. +/// +internal sealed class AsyncByteStreamTransfer : IDisposable +{ + private const int DefaultBufferSize = 1024; + + private readonly BytePipe _bytePipe; + + private readonly BytePipe _destinationPipe; + + private readonly Memory _buffer; + + private readonly CancellationTokenSource _cts = new(); + + private Task? _readToBufferTask; + + public AsyncByteStreamTransfer( + BytePipe bytePipe, + BytePipe destinationPipe) + { + _bytePipe = bytePipe; + _destinationPipe = destinationPipe; + _buffer = new byte[DefaultBufferSize]; + } + + public Task EOF => _readToBufferTask ?? Task.CompletedTask; + + public void BeginReadChunks() + { + _readToBufferTask = Task.Run(ReadBufferAsync); + } + + public void Dispose() => _cts.Cancel(); + + private async Task ReadBufferAsync() + { + Stream stream; + Stream? destinationStream = null; + try + { + stream = await _bytePipe.GetStream(_cts.Token); + destinationStream = await _destinationPipe.GetStream(_cts.Token); + + while (true) + { + int bytesRead; + bytesRead = await stream.ReadAsync(_buffer, _cts.Token); + if (bytesRead is 0) + { + break; + } + + destinationStream.Write(_buffer.Span.Slice(0, bytesRead)); + } + } + catch (IOException) + { + return; + } + catch (OperationCanceledException) + { + return; + } + finally + { + destinationStream?.Close(); + } + } +} diff --git a/src/System.Management.Automation/engine/BytePipe.cs b/src/System.Management.Automation/engine/BytePipe.cs new file mode 100644 index 00000000000..3d4832d6043 --- /dev/null +++ b/src/System.Management.Automation/engine/BytePipe.cs @@ -0,0 +1,115 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System.Diagnostics; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.PowerShell.Telemetry; + +namespace System.Management.Automation; + +/// +/// Represents a lazily retrieved for transfering bytes +/// to or from. +/// +internal abstract class BytePipe +{ + public abstract Task GetStream(CancellationToken cancellationToken); + + internal AsyncByteStreamTransfer Bind(BytePipe bytePipe) + { + Debug.Assert(bytePipe is not null); + return new AsyncByteStreamTransfer(bytePipe, destinationPipe: this); + } +} + +/// +/// Represents a lazily retrieved from the underlying +/// . +/// +internal sealed class NativeCommandProcessorBytePipe : BytePipe +{ + private readonly NativeCommandProcessor _nativeCommand; + + private readonly bool _stdout; + + internal NativeCommandProcessorBytePipe( + NativeCommandProcessor nativeCommand, + bool stdout) + { + Debug.Assert(nativeCommand is not null); + _nativeCommand = nativeCommand; + _stdout = stdout; + } + + public override async Task GetStream(CancellationToken cancellationToken) + { + // If the native command we're wrapping is the upstream command then + // NativeCommandProcessor.Prepare will have already been called before + // the creation of this BytePipe. + if (_stdout) + { + return _nativeCommand.GetStream(stdout: true); + } + + await _nativeCommand.WaitForProcessInitializationAsync(cancellationToken); + return _nativeCommand.GetStream(stdout: false); + } +} + +/// +/// Provides an byte pipe implementation representing a . +/// +internal sealed class FileBytePipe : BytePipe +{ + private readonly Stream _stream; + + private FileBytePipe(Stream stream) + { + Debug.Assert(stream is not null); + _stream = stream; + } + + internal static FileBytePipe Create(string fileName, bool append) + { + FileStream fileStream; + try + { + PathUtils.MasterStreamOpen( + fileName, + resolvedEncoding: null, + defaultEncoding: false, + append, + Force: true, + NoClobber: false, + out fileStream, + streamWriter: out _, + readOnlyFileInfo: out _, + isLiteralPath: true); + } + catch (Exception e) when (e.Data.Contains(typeof(ErrorRecord))) + { + // The error record is attached to the exception when thrown to preserve + // the call stack. + ErrorRecord? errorRecord = e.Data[typeof(ErrorRecord)] as ErrorRecord; + if (errorRecord is null) + { + throw; + } + + e.Data.Remove(typeof(ErrorRecord)); + throw new RuntimeException(null, e, errorRecord); + } + + ApplicationInsightsTelemetry.SendExperimentalUseData( + ExperimentalFeature.PSNativeCommandPreserveBytePipe, + "f"); + + return new FileBytePipe(fileStream); + } + + public override Task GetStream(CancellationToken cancellationToken) => Task.FromResult(_stream); +} diff --git a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs index f7c2a73ba2a..bc826fa2780 100644 --- a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs +++ b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs @@ -22,6 +22,7 @@ public class ExperimentalFeature internal const string EngineSource = "PSEngine"; internal const string PSNativeCommandErrorActionPreferenceFeatureName = "PSNativeCommandErrorActionPreference"; + internal const string PSNativeCommandPreserveBytePipe = "PSNativeCommandPreserveBytePipe"; internal const string PSModuleAutoLoadSkipOfflineFilesFeatureName = "PSModuleAutoLoadSkipOfflineFiles"; internal const string PSCustomTableHeaderLabelDecoration = "PSCustomTableHeaderLabelDecoration"; internal const string PSFeedbackProvider = "PSFeedbackProvider"; @@ -126,6 +127,9 @@ static ExperimentalFeature() new ExperimentalFeature( name: PSCustomTableHeaderLabelDecoration, description: "Formatting differentiation for table header labels that aren't property members"), + new ExperimentalFeature( + name: PSNativeCommandPreserveBytePipe, + description: "Byte output is retained when piping between two or more native commands"), new ExperimentalFeature( name: PSFeedbackProvider, description: "Replace the hard-coded suggestion framework with the extensible feedback provider"), diff --git a/src/System.Management.Automation/engine/NativeCommandProcessor.cs b/src/System.Management.Automation/engine/NativeCommandProcessor.cs index f34fc1987bb..3bb0fef21b9 100644 --- a/src/System.Management.Automation/engine/NativeCommandProcessor.cs +++ b/src/System.Management.Automation/engine/NativeCommandProcessor.cs @@ -17,6 +17,7 @@ using System.Runtime.Serialization; using System.Text; using System.Threading; +using System.Threading.Tasks; using System.Xml; using Microsoft.PowerShell.Telemetry; using Dbg = System.Management.Automation.Diagnostics; @@ -339,16 +340,16 @@ private string Path } } + internal NativeCommandProcessor DownStreamNativeCommand { get; set; } + + internal bool UpstreamIsNativeCommand { get; set; } + + internal BytePipe StdOutDestination { get; set; } + #endregion ctor/native command properties #region parameter binder - /// - /// Variable which is set to true when prepare is called. - /// Parameter Binder should only be created after Prepare method is called. - /// - private bool _isPreparedCalled = false; - /// /// Parameter binder used by this command processor. /// @@ -365,8 +366,6 @@ private string Path /// internal ParameterBinderController NewParameterBinderController(InternalCommand command) { - Dbg.Assert(_isPreparedCalled, "parameter binder should not be created before prepared is called"); - if (_isMiniShell) { _nativeParameterBinderController = @@ -405,8 +404,6 @@ internal NativeCommandParameterBinderController NativeParameterBinderController /// internal override void Prepare(IDictionary psDefaultParameterValues) { - _isPreparedCalled = true; - // Check if the application is minishell _isMiniShell = IsMiniShell(); @@ -436,9 +433,15 @@ internal override void ProcessRecord() { try { - while (Read()) + // If upstream is a native command it'll be writing directly to our stdin stream + // so we can skip reading here. + if (ExperimentalFeature.IsEnabled(ExperimentalFeature.PSNativeCommandPreserveBytePipe) + && !UpstreamIsNativeCommand) { - _inputWriter.Add(Command.CurrentPipelineObject); + while (Read()) + { + _inputWriter.Add(Command.CurrentPipelineObject); + } } ConsumeAvailableNativeProcessOutput(blocking: false); @@ -496,6 +499,59 @@ internal override void ProcessRecord() /// private readonly object _sync = new object(); + private SemaphoreSlim _processInitialized; + + internal async Task WaitForProcessInitializationAsync(CancellationToken cancellationToken) + { + SemaphoreSlim processInitialized = _processInitialized; + if (processInitialized is null) + { + lock (_sync) + { + processInitialized = _processInitialized ??= new SemaphoreSlim(0, 1); + } + } + + try + { + await processInitialized.WaitAsync(cancellationToken); + } + finally + { + processInitialized.Release(); + } + } + + /// + /// Creates a pipe representing the streaming of unprocessed bytes. + /// + /// + /// The stream that the pipe should represent. + /// for stdout, for stdin. + /// + /// A new byte pipe representing the specified stream. + internal BytePipe CreateBytePipe(bool stdout) => new NativeCommandProcessorBytePipe(this, stdout); + + /// + /// Gets the specified base for the underlying + /// . + /// + /// + /// The stream that should be retrieved. for + /// stdout, for stdin. + /// + /// The specified . + internal Stream GetStream(bool stdout) + { + Debug.Assert( + _nativeProcess is not null, + "Caller should verify that initialization has completed before attempting to get the underlying stream."); + + return stdout + ? _nativeProcess.StandardOutput.BaseStream + : _nativeProcess.StandardInput.BaseStream; + } + /// /// Executes the native command once all of the input has been gathered. /// @@ -581,6 +637,19 @@ private void InitNativeProcess() { _nativeProcess = new Process() { StartInfo = startInfo }; _nativeProcess.Start(); + if (UpstreamIsNativeCommand) + { + SemaphoreSlim processInitialized = _processInitialized; + if (processInitialized is null) + { + lock (_sync) + { + processInitialized = _processInitialized ??= new SemaphoreSlim(0, 1); + } + } + + processInitialized?.Release(); + } } catch (Win32Exception) { @@ -691,7 +760,9 @@ private void InitNativeProcess() lock (_sync) { - if (!_stopped) + if (!_stopped + && (!ExperimentalFeature.IsEnabled(ExperimentalFeature.PSNativeCommandPreserveBytePipe) + || !UpstreamIsNativeCommand)) { _inputWriter.Start(_nativeProcess, inputFormat); } @@ -740,6 +811,8 @@ private void InitNativeProcess() } } + private AsyncByteStreamTransfer _stdOutByteTransfer; + private void InitOutputQueue() { // if output is redirected, start reading output of process in queue. @@ -749,9 +822,38 @@ private void InitOutputQueue() { if (!_stopped) { + if (CommandRuntime.ErrorMergeTo is MshCommandRuntime.MergeDataStream.Output) + { + StdOutDestination = null; + if (ExperimentalFeature.IsEnabled(ExperimentalFeature.PSNativeCommandPreserveBytePipe)) + { + if (DownStreamNativeCommand is not null) + { + DownStreamNativeCommand.UpstreamIsNativeCommand = false; + DownStreamNativeCommand = null; + } + } + } + _nativeProcessOutputQueue = new BlockingCollection(); // we don't assign the handler to anything, because it's used only for objects marshaling - new ProcessOutputHandler(_nativeProcess, _nativeProcessOutputQueue); + BytePipe stdOutDestination = ExperimentalFeature.IsEnabled(ExperimentalFeature.PSNativeCommandPreserveBytePipe) + ? StdOutDestination ?? DownStreamNativeCommand?.CreateBytePipe(stdout: false) + : null; + + BytePipe stdOutSource = null; + if (stdOutDestination is not null) + { + stdOutSource = CreateBytePipe(stdout: true); + } + + _ = new ProcessOutputHandler( + _nativeProcess, + _nativeProcessOutputQueue, + stdOutDestination, + stdOutSource, + out _stdOutByteTransfer); + } } } @@ -761,6 +863,13 @@ private ProcessOutputObject DequeueProcessOutput(bool blocking) { if (blocking) { + if (ExperimentalFeature.IsEnabled(ExperimentalFeature.PSNativeCommandPreserveBytePipe) + && _stdOutByteTransfer is not null) + { + _stdOutByteTransfer.EOF.GetAwaiter().GetResult(); + return null; + } + // If adding was completed and collection is empty (IsCompleted == true) // there is no need to do a blocking Take(), we should just return. if (!_nativeProcessOutputQueue.IsCompleted) @@ -784,6 +893,12 @@ private ProcessOutputObject DequeueProcessOutput(bool blocking) } else { + if (ExperimentalFeature.IsEnabled(ExperimentalFeature.PSNativeCommandPreserveBytePipe) + && _stdOutByteTransfer is not null) + { + return null; + } + ProcessOutputObject record = null; _nativeProcessOutputQueue.TryTake(out record); return record; @@ -822,7 +937,11 @@ internal override void Complete() if (!_isRunningInBackground) { // Wait for input writer to finish. - _inputWriter.Done(); + if (!ExperimentalFeature.IsEnabled(ExperimentalFeature.PSNativeCommandPreserveBytePipe) + || !UpstreamIsNativeCommand) + { + _inputWriter.Done(); + } // read all the available output in the blocking way ConsumeAvailableNativeProcessOutput(blocking: true); @@ -1188,8 +1307,13 @@ internal void StopProcessing() if (!_runStandAlone) { // Stop input writer - _inputWriter.Stop(); + if (!ExperimentalFeature.IsEnabled(ExperimentalFeature.PSNativeCommandPreserveBytePipe) + || !UpstreamIsNativeCommand) + { + _inputWriter.Stop(); + } + _stdOutByteTransfer?.Dispose(); KillProcess(_nativeProcess); } } @@ -1675,7 +1799,19 @@ internal class ProcessOutputHandler private bool _isXmlCliError; private readonly string _processFileName; + private readonly AsyncByteStreamTransfer _stdOutDrainer; + public ProcessOutputHandler(Process process, BlockingCollection queue) + : this(process, queue, null, null, out _) + { + } + + public ProcessOutputHandler( + Process process, + BlockingCollection queue, + BytePipe stdOutDestination, + BytePipe stdOutSource, + out AsyncByteStreamTransfer stdOutDrainer) { Debug.Assert(process.StartInfo.RedirectStandardOutput || process.StartInfo.RedirectStandardError, "Caller should redirect at least one stream"); _refCount = 0; @@ -1695,14 +1831,6 @@ public ProcessOutputHandler(Process process, BlockingCollection internal int Add(CommandProcessorBase commandProcessor) { + if (ExperimentalFeature.IsEnabled(ExperimentalFeature.PSNativeCommandPreserveBytePipe)) + { + if (commandProcessor is NativeCommandProcessor nativeCommand) + { + if (_lastNativeCommand is not null) + { + // Only report experimental feature usage once per pipeline. + if (!_haveReportedNativePipeUsage) + { + ApplicationInsightsTelemetry.SendExperimentalUseData( + ExperimentalFeature.PSNativeCommandPreserveBytePipe, + "p"); + _haveReportedNativePipeUsage = true; + } + + _lastNativeCommand.DownStreamNativeCommand = nativeCommand; + nativeCommand.UpstreamIsNativeCommand = true; + } + + _lastNativeCommand = nativeCommand; + } + else + { + _lastNativeCommand = null; + } + } + commandProcessor.CommandRuntime.PipelineProcessor = this; return AddCommand(commandProcessor, _commands.Count, readErrorQueue: false); } diff --git a/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs b/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs index d37a2b4945d..152fb289145 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs @@ -162,6 +162,7 @@ private static CommandProcessorBase AddCommand(PipelineProcessor pipe, (cmd is ScriptCommand || cmd is PSScriptCmdlet); bool isNativeCommand = commandProcessor is NativeCommandProcessor; + for (int i = commandIndex + 1; i < commandElements.Length; ++i) { var cpi = commandElements[i]; @@ -208,9 +209,27 @@ private static CommandProcessorBase AddCommand(PipelineProcessor pipe, bool redirectedInformation = false; if (redirections != null) { - foreach (var redirection in redirections) + bool shouldProcessMergesFirst = ExperimentalFeature.IsEnabled(ExperimentalFeature.PSNativeCommandPreserveBytePipe) + && isNativeCommand; + + if (shouldProcessMergesFirst) + { + foreach (CommandRedirection redirection in redirections) + { + if (redirection is MergingRedirection) + { + redirection.Bind(pipe, commandProcessor, context); + } + } + } + + foreach (CommandRedirection redirection in redirections) { - redirection.Bind(pipe, commandProcessor, context); + if (!shouldProcessMergesFirst || redirection is not MergingRedirection) + { + redirection.Bind(pipe, commandProcessor, context); + } + switch (redirection.FromStream) { case RedirectionStream.Error: @@ -1050,6 +1069,18 @@ public override string ToString() // dir > out internal override void Bind(PipelineProcessor pipelineProcessor, CommandProcessorBase commandProcessor, ExecutionContext context) { + if (ExperimentalFeature.IsEnabled(ExperimentalFeature.PSNativeCommandPreserveBytePipe)) + { + if (commandProcessor is NativeCommandProcessor nativeCommand + && nativeCommand.CommandRuntime.ErrorMergeTo is not MshCommandRuntime.MergeDataStream.Output + && FromStream is RedirectionStream.Output + && !string.IsNullOrWhiteSpace(File)) + { + nativeCommand.StdOutDestination = FileBytePipe.Create(File, Appending); + return; + } + } + Pipe pipe = GetRedirectionPipe(context, pipelineProcessor); switch (FromStream) @@ -3627,7 +3658,7 @@ internal static void LogMemberInvocation(string targetName, string name, object[ } catch (PSSecurityException) { - // ReportContent() will throw PSSecurityException if AMSI detects malware, which + // ReportContent() will throw PSSecurityException if AMSI detects malware, which // must be propagated. throw; } diff --git a/src/System.Management.Automation/utils/PathUtils.cs b/src/System.Management.Automation/utils/PathUtils.cs index 558ca25f2fd..1d7c3140d69 100644 --- a/src/System.Management.Automation/utils/PathUtils.cs +++ b/src/System.Management.Automation/utils/PathUtils.cs @@ -6,6 +6,7 @@ using System.Globalization; using System.IO; using System.Management.Automation.Internal; +using System.Management.Automation.Runspaces; using System.Runtime.CompilerServices; using System.Text; using Microsoft.PowerShell.Commands; @@ -83,55 +84,19 @@ internal static void MasterStreamOpen( fileStream = null; streamWriter = null; readOnlyFileInfo = null; - - // resolve the path and the encoding string resolvedPath = ResolveFilePath(filePath, cmdlet, isLiteralPath); - try { - // variable to track file open mode - // this is controlled by append/force parameters - FileMode mode = FileMode.Create; - if (Append) - { - mode = FileMode.Append; - } - else if (NoClobber) - { - // throw IOException if file exists - mode = FileMode.CreateNew; - } - - if (Force && (Append || !NoClobber)) - { - if (File.Exists(resolvedPath)) - { - FileInfo fInfo = new FileInfo(resolvedPath); - if ((fInfo.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) - { - // remember to reset the read-only attribute later - readOnlyFileInfo = fInfo; - // Clear the read-only attribute - fInfo.Attributes &= ~(FileAttributes.ReadOnly); - } - } - } - - // if the user knows what he/she is doing and uses "-Force" switch, - // then we let more than 1 process write to the same file at the same time - FileShare fileShare = Force ? FileShare.ReadWrite : FileShare.Read; - - // mode is controlled by force and ShouldContinue() - fileStream = new FileStream(resolvedPath, mode, FileAccess.Write, fileShare); - - // create stream writer - // NTRAID#Windows Out Of Band Releases-931008-2006/03/27 - // For some reason, calling this without specifying - // the encoding is different from passing Encoding.Default. - if (defaultEncoding) - streamWriter = new StreamWriter(fileStream); - else - streamWriter = new StreamWriter(fileStream, resolvedEncoding); + MasterStreamOpenImpl( + resolvedPath, + resolvedEncoding, + defaultEncoding, + Append, + Force, + NoClobber, + out fileStream, + out streamWriter, + out readOnlyFileInfo); } // These are the known exceptions for File.Load and StreamWriter.ctor catch (ArgumentException e) @@ -144,7 +109,7 @@ internal static void MasterStreamOpen( if (NoClobber && File.Exists(resolvedPath)) { // This probably happened because the file already exists - ErrorRecord errorRecord = new ErrorRecord( + ErrorRecord errorRecord = new( e, "NoClobber", ErrorCategory.ResourceExists, resolvedPath); errorRecord.ErrorDetails = new ErrorDetails( cmdlet, @@ -176,6 +141,177 @@ internal static void MasterStreamOpen( } } + /// + /// THE method for opening a file for writing. + /// Should be used by all cmdlets that write to a file. + /// + /// Path to the file (as specified on the command line - this method will resolve the path). + /// Encoding (this method will convert the command line string to an Encoding instance). + /// If , then we will use default .NET encoding instead of the encoding specified in parameter. + /// + /// + /// + /// Result1: opened for writing. + /// Result2: (inherits from ) opened for writing. + /// Result3: file info that should be used to restore file attributes after done with the file ( is this is not needed). + /// True if wildcard expansion should be bypassed. + internal static void MasterStreamOpen( + string filePath, + Encoding resolvedEncoding, + bool defaultEncoding, + bool Append, + bool Force, + bool NoClobber, + out FileStream fileStream, + out StreamWriter streamWriter, + out FileInfo readOnlyFileInfo, + bool isLiteralPath) + { + fileStream = null; + streamWriter = null; + readOnlyFileInfo = null; + string resolvedPath = ResolveFilePath(filePath, isLiteralPath); + try + { + MasterStreamOpenImpl( + resolvedPath, + resolvedEncoding, + defaultEncoding, + Append, + Force, + NoClobber, + out fileStream, + out streamWriter, + out readOnlyFileInfo); + } + // These are the known exceptions for File.Load and StreamWriter.ctor + catch (ArgumentException e) + { + AddFileOpenErrorRecord(e); + throw; + } + catch (IOException e) + { + if (NoClobber && File.Exists(resolvedPath)) + { + string msg = StringUtil.Format( + PathUtilsStrings.UtilityFileExistsNoClobber, + filePath, + "NoClobber"); + + // This probably happened because the file already exists + ErrorRecord errorRecord = new ErrorRecord( + e, "NoClobber", ErrorCategory.ResourceExists, resolvedPath); + errorRecord.ErrorDetails = new ErrorDetails(msg); + + e.Data[typeof(ErrorRecord)] = errorRecord; + throw; + } + + AddFileOpenErrorRecord(e); + throw; + } + catch (UnauthorizedAccessException e) + { + AddFileOpenErrorRecord(e); + throw; + } + catch (NotSupportedException e) + { + AddFileOpenErrorRecord(e); + throw; + } + catch (System.Security.SecurityException e) + { + AddFileOpenErrorRecord(e); + throw; + } + + static void AddFileOpenErrorRecord(Exception e) + { + ErrorRecord errorRecord = new ErrorRecord( + e, + "FileOpenFailure", + ErrorCategory.OpenError, + null); + + e.Data[typeof(ErrorRecord)] = errorRecord; + } + } + + /// + /// THE method for opening a file for writing. + /// Should be used by all cmdlets that write to a file. + /// + /// Path to the file (as specified on the command line - this method will resolve the path). + /// Encoding (this method will convert the command line string to an Encoding instance). + /// If , then we will use default .NET encoding instead of the encoding specified in parameter. + /// + /// + /// + /// Result1: opened for writing. + /// Result2: (inherits from ) opened for writing. + /// Result3: file info that should be used to restore file attributes after done with the file ( is this is not needed). + internal static void MasterStreamOpenImpl( + string resolvedPath, + Encoding resolvedEncoding, + bool defaultEncoding, + bool Append, + bool Force, + bool NoClobber, + out FileStream fileStream, + out StreamWriter streamWriter, + out FileInfo readOnlyFileInfo) + { + fileStream = null; + streamWriter = null; + readOnlyFileInfo = null; + + // variable to track file open mode + // this is controlled by append/force parameters + FileMode mode = FileMode.Create; + if (Append) + { + mode = FileMode.Append; + } + else if (NoClobber) + { + // throw IOException if file exists + mode = FileMode.CreateNew; + } + + if (Force && (Append || !NoClobber)) + { + if (File.Exists(resolvedPath)) + { + FileInfo fInfo = new FileInfo(resolvedPath); + if ((fInfo.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) + { + // remember to reset the read-only attribute later + readOnlyFileInfo = fInfo; + // Clear the read-only attribute + fInfo.Attributes &= ~(FileAttributes.ReadOnly); + } + } + } + + // if the user knows what he/she is doing and uses "-Force" switch, + // then we let more than 1 process write to the same file at the same time + FileShare fileShare = Force ? FileShare.ReadWrite : FileShare.Read; + + // mode is controlled by force and ShouldContinue() + fileStream = new FileStream(resolvedPath, mode, FileAccess.Write, fileShare); + + // create stream writer + // NTRAID#Windows Out Of Band Releases-931008-2006/03/27 + // For some reason, calling this without specifying + // the encoding is different from passing Encoding.Default. + if (defaultEncoding) + streamWriter = new StreamWriter(fileStream); + else + streamWriter = new StreamWriter(fileStream, resolvedEncoding); + } + internal static void ReportFileOpenFailure(Cmdlet cmdlet, string filePath, Exception e) { ErrorRecord errorRecord = new ErrorRecord( @@ -187,6 +323,20 @@ internal static void ReportFileOpenFailure(Cmdlet cmdlet, string filePath, Excep cmdlet.ThrowTerminatingError(errorRecord); } + internal static void ReportFileOpenFailure(string filePath, Exception e) + { + ErrorRecord errorRecord = new ErrorRecord( + e, + "FileOpenFailure", + ErrorCategory.OpenError, + null); + + throw new RuntimeException( + e.Message, + errorRecord.Exception, + errorRecord); + } + internal static StreamReader OpenStreamReader(PSCmdlet command, string filePath, Encoding encoding, bool isLiteralPath) { FileStream fileStream = OpenFileStream(filePath, command, isLiteralPath); @@ -308,6 +458,63 @@ internal static string ResolveFilePath(string filePath, PSCmdlet command, bool i return path; } + /// + /// Resolve a user provided file name or path (including globbing characters) + /// to a fully qualified file path, using the file system provider. + /// + /// + /// + /// + internal static string ResolveFilePath(string filePath, bool isLiteralPath) + { + string path = null; + + SessionState sessionState = LocalPipeline.GetExecutionContextFromTLS()?.EngineSessionState?.PublicSessionState; + if (sessionState is null) + { + return null; + } + + try + { + ProviderInfo provider = null; + PSDriveInfo drive = null; + List filePaths = new(); + + if (isLiteralPath) + { + filePaths.Add(sessionState.Path.GetUnresolvedProviderPathFromPSPath(filePath, out provider, out drive)); + } + else + { + filePaths.AddRange(sessionState.Path.GetResolvedProviderPathFromPSPath(filePath, out provider)); + } + + if (!provider.NameEquals(FileSystemProvider.ProviderName)) + { + ReportWrongProviderType(provider.FullName); + } + + if (filePaths.Count > 1) + { + ReportMultipleFilesNotSupported(); + } + + if (filePaths.Count == 0) + { + ReportWildcardingFailure(filePath); + } + + path = filePaths[0]; + } + catch (ItemNotFoundException) + { + path = null; + } + + return path; + } + internal static void ReportWrongProviderType(Cmdlet cmdlet, string providerId) { string msg = StringUtil.Format(PathUtilsStrings.OutFile_ReadWriteFileNotFileSystemProvider, providerId); @@ -322,6 +529,23 @@ internal static void ReportWrongProviderType(Cmdlet cmdlet, string providerId) cmdlet.ThrowTerminatingError(errorRecord); } + internal static void ReportWrongProviderType(string providerId) + { + string msg = StringUtil.Format(PathUtilsStrings.OutFile_ReadWriteFileNotFileSystemProvider, providerId); + + PSInvalidOperationException exception = PSTraceSource.NewInvalidOperationException(); + + ErrorRecord errorRecord = new( + exception, + "ReadWriteFileNotFileSystemProvider", + ErrorCategory.InvalidArgument, + null); + + errorRecord.ErrorDetails = new ErrorDetails(msg); + exception.Data[typeof(ErrorRecord)] = errorRecord; + throw exception; + } + internal static void ReportMultipleFilesNotSupported(Cmdlet cmdlet) { string msg = StringUtil.Format(PathUtilsStrings.OutFile_MultipleFilesNotSupported); @@ -336,6 +560,23 @@ internal static void ReportMultipleFilesNotSupported(Cmdlet cmdlet) cmdlet.ThrowTerminatingError(errorRecord); } + internal static void ReportMultipleFilesNotSupported() + { + string msg = StringUtil.Format(PathUtilsStrings.OutFile_MultipleFilesNotSupported); + + PSInvalidOperationException exception = PSTraceSource.NewInvalidOperationException(); + + ErrorRecord errorRecord = new( + exception, + "ReadWriteMultipleFilesNotSupported", + ErrorCategory.InvalidArgument, + null); + + errorRecord.ErrorDetails = new ErrorDetails(msg); + exception.Data[typeof(ErrorRecord)] = errorRecord; + throw exception; + } + internal static void ReportWildcardingFailure(Cmdlet cmdlet, string filePath) { string msg = StringUtil.Format(PathUtilsStrings.OutFile_DidNotResolveFile, filePath); @@ -350,6 +591,22 @@ internal static void ReportWildcardingFailure(Cmdlet cmdlet, string filePath) cmdlet.ThrowTerminatingError(errorRecord); } + internal static void ReportWildcardingFailure(string filePath) + { + string msg = StringUtil.Format(PathUtilsStrings.OutFile_DidNotResolveFile, filePath); + + FileNotFoundException exception = new(); + ErrorRecord errorRecord = new( + exception, + "FileOpenFailure", + ErrorCategory.OpenError, + filePath); + + errorRecord.ErrorDetails = new ErrorDetails(msg); + exception.Data[typeof(ErrorRecord)] = errorRecord; + throw exception; + } + internal static DirectoryInfo CreateModuleDirectory(PSCmdlet cmdlet, string moduleNameOrPath, bool force) { Dbg.Assert(cmdlet != null, "Caller should verify cmdlet != null"); diff --git a/test/powershell/engine/Basic/NativeCommandBytePiping.Tests.ps1 b/test/powershell/engine/Basic/NativeCommandBytePiping.Tests.ps1 new file mode 100644 index 00000000000..8126c08473f --- /dev/null +++ b/test/powershell/engine/Basic/NativeCommandBytePiping.Tests.ps1 @@ -0,0 +1,66 @@ + +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +# Functional tests to verify that output from native executables is not encoded +# and decoded when piping to another native executable. + +Describe 'Native command byte piping tests' -Tags 'CI' { + BeforeAll { + $originalDefaultParameterValues = $PSDefaultParameterValues.Clone() + if (-not [ExperimentalFeature]::IsEnabled('PSNativeCommandPreserveBytePipe')) + { + $PSDefaultParameterValues['It:Skip'] = $true + return + } + + # Without this the test would otherwise be hard coded to a specific set + # of [Console]::OutputEncoding/$OutputEncoding settings. + $mangledFFByte = $OutputEncoding.GetBytes( + [Console]::OutputEncoding.GetString(0xFF) + [Environment]::NewLine). + ForEach{ '{0:X2}' -f [int]$_ } + } + + AfterAll { + $global:PSDefaultParameterValues = $originalDefaultParameterValues + } + + It 'Bytes are retained between native executables' { + testexe -writebytes FF | testexe -readbytes | Should -BeExactly FF + } + + It 'Byte literals are retained when piped directly' { + 0xFFuy | testexe -readbytes | Should -BeExactly FF + 0xBEuy, 0xEFuy | testexe -readbytes | Should -BeExactly BE, EF + ,[byte[]](0xBEuy, 0xEFuy) | testexe -readbytes | Should -BeExactly BE, EF + } + + It 'Output behavior falls back when stderr is redirected to stdout' { + testexe -writebytes FF 2>&1 | testexe -readbytes | Should -BeExactly $mangledFFByte + } + + It 'Bytes are retained when using SMA.PowerShell' { + $ps = $null + try { + $ps = [powershell]::Create(). + AddCommand('testexe').AddArgument('-writebytes').AddArgument('FF'). + AddCommand('testexe').AddArgument('-readbytes') + + $ps.Invoke() | Should -BeExactly 'FF' + } finally { + ($ps)?.Dispose() + } + } + + It 'Bytes are retained when using SteppablePipeline' { + $pipe = $null + try { + $pipe = { testexe -writebytes FF | testexe -readbytes }.GetSteppablePipeline('Internal') + $pipe.Begin($false) + $pipe.Process() + $pipe.End() | Should -BeExactly 'FF' + } finally { + ($pipe)?.Dispose() + } + } +} diff --git a/test/tools/TestExe/TestExe.cs b/test/tools/TestExe/TestExe.cs index ab8f76d5425..a91e2141b58 100644 --- a/test/tools/TestExe/TestExe.cs +++ b/test/tools/TestExe/TestExe.cs @@ -4,7 +4,10 @@ using System; using System.Threading; using System.Diagnostics; +using System.Runtime.CompilerServices; using System.Runtime.InteropServices; +using System.IO; +using System.Globalization; namespace TestExe { @@ -33,6 +36,12 @@ private static int Main(string[] args) case "-stderr": Console.Error.WriteLine(args[1]); break; + case "-readbytes": + ReadBytes(); + break; + case "-writebytes": + WriteBytes(args.AsSpan()[1..]); + break; case "--help": case "-h": PrintHelp(); @@ -52,6 +61,45 @@ private static int Main(string[] args) return exitCode; } + private static void WriteBytes(ReadOnlySpan args) + { + using Stream stdout = Console.OpenStandardOutput(); + foreach (string arg in args) + { + if (!byte.TryParse(arg, NumberStyles.AllowHexSpecifier, provider: null, out byte value)) + { + throw new ArgumentException( + nameof(args), + "All args after -writebytes must be single byte hex strings."); + } + + stdout.WriteByte(value); + } + } + + [SkipLocalsInit] + private static void ReadBytes() + { + using Stream stdin = Console.OpenStandardInput(); + Span buffer = stackalloc byte[0x200]; + Unsafe.InitBlock(ref MemoryMarshal.GetReference(buffer), 0, 0x200); + Span hex = stackalloc char[] { '\0', '\0' }; + while (true) + { + int received = stdin.Read(buffer); + if (received is 0) + { + return; + } + + for (int i = 0; i < received; i++) + { + buffer[i].TryFormat(hex, out _, "X2"); + Console.Out.WriteLine(hex); + } + } + } + // // Echos back to stdout the arguments passed in // From 561365e67c204bb673954b48e4402af9444f5f8b Mon Sep 17 00:00:00 2001 From: PowerShell Team Bot <69177312+pwshBot@users.noreply.github.com> Date: Mon, 1 May 2023 10:53:28 -0700 Subject: [PATCH 502/779] Update the `experimental-feature` JSON files (#19588) --- experimental-feature-linux.json | 1 + experimental-feature-windows.json | 1 + 2 files changed, 2 insertions(+) diff --git a/experimental-feature-linux.json b/experimental-feature-linux.json index 188164cd710..3c588657a18 100644 --- a/experimental-feature-linux.json +++ b/experimental-feature-linux.json @@ -6,5 +6,6 @@ "PSLoadAssemblyFromNativeCode", "PSModuleAutoLoadSkipOfflineFiles", "PSNativeCommandErrorActionPreference", + "PSNativeCommandPreserveBytePipe", "PSSubsystemPluginModel" ] diff --git a/experimental-feature-windows.json b/experimental-feature-windows.json index 188164cd710..3c588657a18 100644 --- a/experimental-feature-windows.json +++ b/experimental-feature-windows.json @@ -6,5 +6,6 @@ "PSLoadAssemblyFromNativeCode", "PSModuleAutoLoadSkipOfflineFiles", "PSNativeCommandErrorActionPreference", + "PSNativeCommandPreserveBytePipe", "PSSubsystemPluginModel" ] From 72c81b820ae16027efa5e4f6098d31f48325c1ca Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Mon, 1 May 2023 10:56:16 -0700 Subject: [PATCH 503/779] Set `SetLastError` to `true` for symbolic and hard link native APIs (#19566) --- .../engine/Interop/Windows/CreateHardLink.cs | 2 +- .../engine/Interop/Windows/CreateSymbolicLink.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/System.Management.Automation/engine/Interop/Windows/CreateHardLink.cs b/src/System.Management.Automation/engine/Interop/Windows/CreateHardLink.cs index a6cbc61619e..f27f095fc1a 100644 --- a/src/System.Management.Automation/engine/Interop/Windows/CreateHardLink.cs +++ b/src/System.Management.Automation/engine/Interop/Windows/CreateHardLink.cs @@ -9,7 +9,7 @@ internal static partial class Interop { internal static unsafe partial class Windows { - [LibraryImport("api-ms-win-core-file-l2-1-0.dll", EntryPoint = "CreateHardLinkW", StringMarshalling = StringMarshalling.Utf16)] + [LibraryImport("api-ms-win-core-file-l2-1-0.dll", EntryPoint = "CreateHardLinkW", StringMarshalling = StringMarshalling.Utf16, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static partial bool CreateHardLink(string name, string existingFileName, nint securityAttributes); } diff --git a/src/System.Management.Automation/engine/Interop/Windows/CreateSymbolicLink.cs b/src/System.Management.Automation/engine/Interop/Windows/CreateSymbolicLink.cs index 2c4995d8786..c6519f94ec4 100644 --- a/src/System.Management.Automation/engine/Interop/Windows/CreateSymbolicLink.cs +++ b/src/System.Management.Automation/engine/Interop/Windows/CreateSymbolicLink.cs @@ -18,7 +18,7 @@ internal enum SymbolicLinkFlags AllowUnprivilegedCreate = 2, } - [LibraryImport("api-ms-win-core-file-l2-1-0.dll", EntryPoint = "CreateSymbolicLinkW", StringMarshalling = StringMarshalling.Utf16)] + [LibraryImport("api-ms-win-core-file-l2-1-0.dll", EntryPoint = "CreateSymbolicLinkW", StringMarshalling = StringMarshalling.Utf16, SetLastError = true)] [return: MarshalAs(UnmanagedType.I1)] internal static partial bool CreateSymbolicLink(string name, string destination, SymbolicLinkFlags symbolicLinkFlags); } From 31bc65ef650b79f3714a2985a14492183360936a Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Mon, 1 May 2023 19:43:04 +0100 Subject: [PATCH 504/779] Refactor `MUIFileSearcher.AddFiles` in the help related code (#18825) --- .../help/MUIFileSearcher.cs | 51 ++++--------------- 1 file changed, 9 insertions(+), 42 deletions(-) diff --git a/src/System.Management.Automation/help/MUIFileSearcher.cs b/src/System.Management.Automation/help/MUIFileSearcher.cs index 1873a341c42..dd437fa90c0 100644 --- a/src/System.Management.Automation/help/MUIFileSearcher.cs +++ b/src/System.Management.Automation/help/MUIFileSearcher.cs @@ -57,6 +57,14 @@ private MUIFileSearcher(string target, Collection searchPaths) /// internal SearchMode SearchMode { get; } = SearchMode.Unique; + private static readonly System.IO.EnumerationOptions _enumerationOptions = new() + { + IgnoreInaccessible = false, + AttributesToSkip = 0, + MatchType = MatchType.Win32, + MatchCasing = MatchCasing.CaseInsensitive, + }; + private Collection _result = null; /// @@ -113,52 +121,11 @@ private void SearchForFiles() } } - private static string[] GetFiles(string path, string pattern) - { -#if UNIX - // On Linux, file names are case sensitive, so we need to add - // extra logic to select the files that match the given pattern. - var result = new List(); - string[] files = Directory.GetFiles(path); - - var wildcardPattern = WildcardPattern.ContainsWildcardCharacters(pattern) - ? WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase) - : null; - - foreach (string filePath in files) - { - if (filePath.Contains(pattern, StringComparison.OrdinalIgnoreCase)) - { - result.Add(filePath); - break; - } - - if (wildcardPattern != null) - { - string fileName = Path.GetFileName(filePath); - if (wildcardPattern.IsMatch(fileName)) - { - result.Add(filePath); - } - } - } - - return result.ToArray(); -#else - return Directory.GetFiles(path, pattern); -#endif - } - private void AddFiles(string muiDirectory, string directory, string pattern) { if (Directory.Exists(muiDirectory)) { - string[] files = GetFiles(muiDirectory, pattern); - - if (files == null) - return; - - foreach (string file in files) + foreach (string file in Directory.EnumerateFiles(muiDirectory, pattern, _enumerationOptions)) { string path = Path.Combine(muiDirectory, file); From a63487950f93a757df6353d12b851ac7380a2c27 Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Mon, 1 May 2023 12:14:23 -0700 Subject: [PATCH 505/779] Add prompt to fix conflict during backport (#19583) * Add prompt to fix conflicts * Add function to backport all approved PRs * Update tools/releaseTools.psm1 Co-authored-by: Dongbo Wang * Update tools/releaseTools.psm1 --------- Co-authored-by: Dongbo Wang --- tools/releaseTools.psm1 | 46 +++++++++++++++++++++++++++++++++++++++-- 1 file changed, 44 insertions(+), 2 deletions(-) diff --git a/tools/releaseTools.psm1 b/tools/releaseTools.psm1 index f156a8e1044..3c222482348 100644 --- a/tools/releaseTools.psm1 +++ b/tools/releaseTools.psm1 @@ -759,6 +759,23 @@ function Invoke-PRBackport { throw "$ScriptBlock fail with $LASTEXITCODE" } } + function script:Test-ShouldContinue { + param ( + $Message + ) + $continue = $false + while(!$continue) { + $input= Read-Host -Prompt ($Message + "`nType 'Yes' to continue 'No' to exit") + switch($input) { + 'yes' { + $continue= $true + } + 'no' { + throw "User abort" + } + } + } + } $ErrorActionPreference = 'stop' $pr = gh pr view $PrNumber --json 'mergeCommit,state,title' | ConvertFrom-Json @@ -799,11 +816,36 @@ function Invoke-PRBackport { Invoke-NativeCommand { git switch upstream/$Target $switch $branchName } } - Invoke-NativeCommand { git cherry-pick $commitId } + try { + Invoke-NativeCommand { git cherry-pick $commitId } + } + catch { + Test-ShouldContinue -Message "Fix any conflicts with the cherry-pick." + } if ($PSCmdlet.ShouldProcess("Create the PR")) { gh pr create --base $Target --title $backportTitle --body "Backport #$PrNumber" } } -Export-ModuleMember -Function Get-ChangeLog, Get-NewOfficalPackage, Update-PsVersionInCode, Get-PRBackportReport, Invoke-PRBackport +# Backport all approved backports +# Usage: +# Invoke-PRBackportApproved -Version 7.2.12 +function Invoke-PRBackportApproved { + param( + [Parameter(Mandatory)] + [semver] + $Version + ) + + $tagVersion = "$($Version.Major).$($Version.Minor)" + $target = "release/$ReleaseTag" + + Get-PRBackportReport -Version $tagVersion | + ForEach-Object { + $prNumber = $_.Number + Invoke-PRBackport -ErrorAction Stop -PrNumber $prNumber -Target $target + } +} + +Export-ModuleMember -Function Get-ChangeLog, Get-NewOfficalPackage, Update-PsVersionInCode, Get-PRBackportReport, Invoke-PRBackport, Invoke-PRBackportApproved From 698742ea9f0d4d86976281eda3ab4566e687a7a4 Mon Sep 17 00:00:00 2001 From: Jack Casey Date: Mon, 1 May 2023 14:16:11 -0700 Subject: [PATCH 506/779] Test-Connection: Increase output detail when performing a tcp test (#11452) * Added verbose TCP test logic * Cleaned up output, removed source IP address * Consolidated detailed output logic into ProcessConnectionByTCPPort() * Updated existing tests with -Quiet switch * Improved output formatting, changed logic to match * Error handling and logic improvements * Updated tests to match new output * Updated logic, tcp tests now run once by default * Moved TcpConnectionTestResult enum into TcpTestStatus class * Removed unnecessary whitespace * Wrapped TcpClient() in Using statement * Appended missing period on comments * Change TcpTestStatus to TcpPortStatus for better clarity * Set default count back to 4 * Move stopwatch reset into finally block * Change TcpConnectionTestResult.New to TcpConnectionTestResult.None * Formatting fixes * Increase column size for Result output * Update logic for -quiet option * Change "TestNum" property to "Id" * Change Destination and DestinationAddress to Target and TargetAddress in TcpPortStatus * Implement new form of using declaration * Fix indentation * Update output, improve logic and update tests * Add CancellationToken to allow cancel before timeout * Assign testResult.Connected to client.Connected * Move TcpPortStatus object creation to after connection test * Remove delay from final connection test in loop * Move Count logic from ProcessConnectionByTCPPort into own function * Fix small formatting error * Add handling for TaskCanceledException * Remove redundant CancellationToken getter * Clean up handling of SocketException * Increase readability of final loop check * Remove unnecessary TimeSpan invocation * Rename cancellationTokenSource to match convention * Move SetCountForTcpTest() into BeginProcessing() * Added nameof to Count check * Removed explicit type declaration for TcpClient * Move delay and timeout evaluation out of the cycle * Remove redundant CancellationTokenSource * Initialize detailed SwitchParameter * Add check for Detailed parameter * Remove redundant tests for non-detailed output * Add return after first boolean output * Update tests with new detailed parameter set --------- Co-authored-by: Travis Plunk --- .../management/TestConnectionCommand.cs | 184 +++++++++++++++--- .../PowerShellCore_format_ps1xml.cs | 29 +++ .../Test-Connection.Tests.ps1 | 38 +++- 3 files changed, 225 insertions(+), 26 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/TestConnectionCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/TestConnectionCommand.cs index e11be68156a..3e9bbedc605 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/TestConnectionCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/TestConnectionCommand.cs @@ -27,6 +27,7 @@ namespace Microsoft.PowerShell.Commands [OutputType(typeof(PingMtuStatus), ParameterSetName = new string[] { MtuSizeDetectParameterSet })] [OutputType(typeof(int), ParameterSetName = new string[] { MtuSizeDetectParameterSet })] [OutputType(typeof(TraceStatus), ParameterSetName = new string[] { TraceRouteParameterSet })] + [OutputType(typeof(TcpPortStatus), ParameterSetName = new string[] { TcpPortParameterSet })] public class TestConnectionCommand : PSCmdlet, IDisposable { #region Parameter Set Names @@ -134,6 +135,7 @@ public class TestConnectionCommand : PSCmdlet, IDisposable /// The default (from Windows) is 4 times. /// [Parameter(ParameterSetName = DefaultPingParameterSet)] + [Parameter(ParameterSetName = TcpPortParameterSet)] [ValidateRange(ValidateRangeKind.Positive)] public int Count { get; set; } = 4; @@ -143,6 +145,7 @@ public class TestConnectionCommand : PSCmdlet, IDisposable /// [Parameter(ParameterSetName = DefaultPingParameterSet)] [Parameter(ParameterSetName = RepeatPingParameterSet)] + [Parameter(ParameterSetName = TcpPortParameterSet)] [ValidateRange(ValidateRangeKind.Positive)] public int Delay { get; set; } = 1; @@ -169,6 +172,7 @@ public class TestConnectionCommand : PSCmdlet, IDisposable /// Gets or sets whether to continue pinging until user presses Ctrl-C (or Int.MaxValue threshold reached). ///
    [Parameter(Mandatory = true, ParameterSetName = RepeatPingParameterSet)] + [Parameter(ParameterSetName = TcpPortParameterSet)] [Alias("Continuous")] public SwitchParameter Repeat { get; set; } @@ -180,6 +184,13 @@ public class TestConnectionCommand : PSCmdlet, IDisposable [Parameter] public SwitchParameter Quiet { get; set; } + /// + /// Gets or sets whether to enable detailed output mode while running a TCP connection test. + /// Without this flag, the TCP test will return a boolean result. + /// + [Parameter] + public SwitchParameter Detailed; + /// /// Gets or sets the timeout value for an individual ping in seconds. /// If a response is not received in this time, no response is assumed. @@ -227,6 +238,7 @@ public class TestConnectionCommand : PSCmdlet, IDisposable /// /// BeginProcessing implementation for TestConnectionCommand. + /// Sets Count for different types of tests unless specified explicitly. /// protected override void BeginProcessing() { @@ -235,6 +247,9 @@ protected override void BeginProcessing() case RepeatPingParameterSet: Count = int.MaxValue; break; + case TcpPortParameterSet: + SetCountForTcpTest(); + break; } } @@ -281,6 +296,18 @@ protected override void StopProcessing() #region ConnectionTest + private void SetCountForTcpTest() + { + if (Repeat.IsPresent) + { + Count = int.MaxValue; + } + else if (!MyInvocation.BoundParameters.ContainsKey(nameof(Count))) + { + Count = 1; + } + } + private void ProcessConnectionByTCPPort(string targetNameOrAddress) { if (!TryResolveNameOrAddress(targetNameOrAddress, out _, out IPAddress? targetAddress)) @@ -293,42 +320,80 @@ private void ProcessConnectionByTCPPort(string targetNameOrAddress) return; } - TcpClient client = new(); + int timeoutMilliseconds = TimeoutSeconds * 1000; + int delayMilliseconds = Delay * 1000; - try + for (var i = 1; i <= Count; i++) { - Task connectionTask = client.ConnectAsync(targetAddress, TcpPort); - string targetString = targetAddress.ToString(); + long latency = 0; + SocketError status = SocketError.SocketError; + + Stopwatch stopwatch = new Stopwatch(); - for (var i = 1; i <= TimeoutSeconds; i++) + using var client = new TcpClient(); + + try { - Task timeoutTask = Task.Delay(millisecondsDelay: 1000); - Task.WhenAny(connectionTask, timeoutTask).Result.Wait(); + stopwatch.Start(); - if (timeoutTask.Status == TaskStatus.Faulted || timeoutTask.Status == TaskStatus.Canceled) + if (client.ConnectAsync(targetAddress, TcpPort).Wait(timeoutMilliseconds, _dnsLookupCancel.Token)) { - // Waiting is interrupted by Ctrl-C. - WriteObject(false); - return; + latency = stopwatch.ElapsedMilliseconds; + status = SocketError.Success; } - - if (connectionTask.Status == TaskStatus.RanToCompletion) + else { - WriteObject(true); - return; + status = SocketError.TimedOut; } } - } - catch - { - // Silently ignore connection errors. - } - finally - { - client.Close(); - } + catch (AggregateException ae) + { + ae.Handle((ex) => + { + if (ex is TaskCanceledException) + { + throw new PipelineStoppedException(); + } + if (ex is SocketException socketException) + { + status = socketException.SocketErrorCode; + return true; + } + else + { + return false; + } + }); + } + finally + { + stopwatch.Reset(); + } + + if (!Detailed.IsPresent) + { + WriteObject(status == SocketError.Success); + return; + } + else + { + WriteObject(new TcpPortStatus( + i, + Source, + targetNameOrAddress, + targetAddress, + TcpPort, + latency, + status == SocketError.Success, + status + )); + } - WriteObject(false); + if (i < Count) + { + Task.Delay(delayMilliseconds).Wait(_dnsLookupCancel.Token); + } + } } #endregion ConnectionTest @@ -877,6 +942,75 @@ private PingReply SendCancellablePing( } } + /// + /// The class contains information about the TCP connection test. + /// + public class TcpPortStatus + { + /// + /// Initializes a new instance of the class. + /// + /// The number of this test. + /// The source machine name or IP of the test. + /// The target machine name or IP of the test. + /// The resolved IP from the target. + /// The port used for the connection. + /// The latency of the test. + /// If the test connection succeeded. + /// Status of the underlying socket. + internal TcpPortStatus(int id, string source, string target, IPAddress targetAddress, int port, long latency, bool connected, SocketError status) + { + Id = id; + Source = source; + Target = target; + TargetAddress = targetAddress; + Port = port; + Latency = latency; + Connected = connected; + Status = status; + } + + /// + /// Gets and sets the count of the test. + /// + public int Id { get; set; } + + /// + /// Gets the source from which the test was sent. + /// + public string Source { get; } + + /// + /// Gets the target name. + /// + public string Target { get; } + + /// + /// Gets the resolved address for the target. + /// + public IPAddress TargetAddress { get; } + + /// + /// Gets the port used for the test. + /// + public int Port { get; } + + /// + /// Gets or sets the latancy of the connection. + /// + public long Latency { get; set; } + + /// + /// Gets or sets the result of the test. + /// + public bool Connected { get; set; } + + /// + /// Gets or sets the state of the socket after the test. + /// + public SocketError Status { get; set; } + } + /// /// The class contains information about the source, the destination and ping results. /// diff --git a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs index 747c083ee51..182af55d641 100644 --- a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs +++ b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs @@ -252,6 +252,10 @@ internal static IEnumerable GetFormatData() "Microsoft.PowerShell.MarkdownRender.PSMarkdownOptionInfo", ViewsOf_Microsoft_PowerShell_MarkdownRender_MarkdownOptionInfo()); + yield return new ExtendedTypeDefinition( + "Microsoft.PowerShell.Commands.TestConnectionCommand+TcpPortStatus", + ViewsOf_Microsoft_PowerShell_Commands_TestConnectionCommand_TcpPortStatus()); + yield return new ExtendedTypeDefinition( "Microsoft.PowerShell.Commands.TestConnectionCommand+PingStatus", ViewsOf_Microsoft_PowerShell_Commands_TestConnectionCommand_PingStatus()); @@ -1916,6 +1920,31 @@ private static IEnumerable ViewsOf_Microsoft_PowerShell_Ma .EndList()); } + private static IEnumerable ViewsOf_Microsoft_PowerShell_Commands_TestConnectionCommand_TcpPortStatus() + { + yield return new FormatViewDefinition( + "Microsoft.PowerShell.Commands.TestConnectionCommand+TcpPortStatus", + TableControl.Create() + .AddHeader(Alignment.Right, label: "Id", width: 4) + .AddHeader(Alignment.Left, label: "Source", width: 16) + .AddHeader(Alignment.Left, label: "Address", width: 25) + .AddHeader(Alignment.Right, label: "Port", width: 7) + .AddHeader(Alignment.Right, label: "Latency(ms)", width: 7) + .AddHeader(Alignment.Left, label: "Connected", width: 10) + .AddHeader(Alignment.Left, label: "Status", width: 24) + .StartRowDefinition() + .AddPropertyColumn("Id") + .AddPropertyColumn("Source") + .AddPropertyColumn("TargetAddress") + .AddPropertyColumn("Port") + .AddPropertyColumn("Latency") + .AddPropertyColumn("Connected") + .AddPropertyColumn("Status") + .EndRowDefinition() + .GroupByProperty("Target") + .EndTable()); + } + private static IEnumerable ViewsOf_Microsoft_PowerShell_Commands_TestConnectionCommand_PingStatus() { yield return new FormatViewDefinition( diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Test-Connection.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Test-Connection.Tests.ps1 index b70aff4d3a7..cf6c7e2f78e 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Test-Connection.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Test-Connection.Tests.ps1 @@ -321,13 +321,49 @@ Describe "Connection" -Tag "CI", "RequireAdminOnWindows" { $UnreachableAddress = "10.11.12.13" } - It "Test connection to local host port 80" { + It "Test connection to local host on working port" { Test-Connection '127.0.0.1' -TcpPort $WebListener.HttpPort | Should -BeTrue } It "Test connection to unreachable host port 80" { Test-Connection $UnreachableAddress -TcpPort 80 -TimeOut 1 | Should -BeFalse } + + It "Test detailed connection to local host on working port" { + $result = Test-Connection '127.0.0.1' -TcpPort $WebListener.HttpPort -Detailed + + $result.Count | Should -Be 1 + $result[0].Id | Should -BeExactly 1 + $result[0].TargetAddress | Should -BeExactly '127.0.0.1' + $result[0].Port | Should -Be $WebListener.HttpPort + $result[0].Latency | Should -BeGreaterOrEqual 0 + $result[0].Connected | Should -BeTrue + $result[0].Status | Should -BeExactly 'Success' + } + + It "Test detailed connection to local host on working port with modified count" { + $result = Test-Connection '127.0.0.1' -TcpPort $WebListener.HttpPort -Detailed -Count 2 + + $result.Count | Should -Be 2 + $result[0].Id | Should -BeExactly 1 + $result[0].TargetAddress | Should -BeExactly '127.0.0.1' + $result[0].Port | Should -Be $WebListener.HttpPort + $result[0].Latency | Should -BeGreaterOrEqual 0 + $result[0].Connected | Should -BeTrue + $result[0].Status | Should -BeExactly 'Success' + } + + It "Test detailed connection to unreachable host port 80" { + $result = Test-Connection $UnreachableAddress -TcpPort 80 -Detailed -TimeOut 1 + + $result.Count | Should -Be 1 + $result[0].Id | Should -BeExactly 1 + $result[0].TargetAddress | Should -BeExactly $UnreachableAddress + $result[0].Port | Should -Be 80 + $result[0].Latency | Should -BeExactly 0 + $result[0].Connected | Should -BeFalse + $result[0].Status | Should -Not -BeExactly 'Success' + } } Describe "Test-Connection should run in the default synchronization context (threadpool)" -Tag "CI" { From ea68edc686d5f2370041aa9284805d976d9c7553 Mon Sep 17 00:00:00 2001 From: Dominik Kaszewski Date: Mon, 1 May 2023 23:53:31 +0200 Subject: [PATCH 507/779] Set-Clipboard -AsOSC52 (#18222) * Set remote clipboard using OSC52 * Fix codefactor comment * Rename parameter from Using to As * Rename alias --- .../management/SetClipboardCommand.cs | 29 ++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/SetClipboardCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/SetClipboardCommand.cs index 69cea8361a8..49ab5d768f6 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/SetClipboardCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/SetClipboardCommand.cs @@ -44,6 +44,13 @@ public class SetClipboardCommand : PSCmdlet [Parameter] public SwitchParameter PassThru { get; set; } + /// + /// Gets or sets whether to use OSC52 escape sequence to set the clipboard of host instead of target. + /// + [Parameter] + [Alias("ToLocalhost")] + public SwitchParameter AsOSC52 { get; set; } + /// /// This method implements the BeginProcessing method for Set-Clipboard command. /// @@ -129,8 +136,28 @@ private void SetClipboardContent(List contentList, bool append) if (ShouldProcess(setClipboardShouldProcessTarget, "Set-Clipboard")) { - Clipboard.SetText(content.ToString()); + SetClipboardContent(content.ToString()); } } + + /// + /// Set the clipboard content. + /// + /// The content to store into the clipboard. + private void SetClipboardContent(string content) + { + if (!AsOSC52) + { + Clipboard.SetText(content); + return; + } + + var bytes = System.Text.Encoding.UTF8.GetBytes(content); + var encoded = System.Convert.ToBase64String(bytes); + var osc = $"\u001B]52;;{encoded}\u0007"; + + var message = new HostInformationMessage { Message = osc, NoNewLine = true }; + WriteInformation(message, new string[] { "PSHOST" }); + } } } From 5605b24b08b9e416cf587c9eaff4a544d0e3a0a9 Mon Sep 17 00:00:00 2001 From: MartinGC94 <42123497+MartinGC94@users.noreply.github.com> Date: Tue, 2 May 2023 01:26:41 +0200 Subject: [PATCH 508/779] Improve Hashtable key completion for type constrained variable assignments, nested Hashtables and more (#17660) --- .../CommandCompletion/CompletionCompleters.cs | 457 +++++++++++++----- .../engine/parser/TypeInferenceVisitor.cs | 5 + .../TabCompletion/TabCompletion.Tests.ps1 | 122 +++-- 3 files changed, 426 insertions(+), 158 deletions(-) diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs index 7d7ecf9ab91..1da684732dd 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs @@ -6154,19 +6154,42 @@ internal static void CompleteMemberByInferredType( Func filter, bool isStatic, HashSet excludedMembers = null, - bool addMethodParenthesis = true) + bool addMethodParenthesis = true, + bool ignoreTypesWithoutDefaultConstructor = false) { bool extensionMethodsAdded = false; HashSet typeNameUsed = new HashSet(StringComparer.OrdinalIgnoreCase); WildcardPattern memberNamePattern = WildcardPattern.Get(memberName, WildcardOptions.IgnoreCase); foreach (var psTypeName in inferredTypes) { - if (typeNameUsed.Contains(psTypeName.Name)) + if (!typeNameUsed.Add(psTypeName.Name) + || (ignoreTypesWithoutDefaultConstructor && psTypeName.Type is not null && psTypeName.Type.GetConstructor(Type.EmptyTypes) is null && !psTypeName.Type.IsInterface)) { continue; } - typeNameUsed.Add(psTypeName.Name); + if (ignoreTypesWithoutDefaultConstructor && psTypeName.TypeDefinitionAst is not null) + { + bool foundConstructor = false; + bool foundDefaultConstructor = false; + foreach (var member in psTypeName.TypeDefinitionAst.Members) + { + if (member is FunctionMemberAst methodDefinition && methodDefinition.IsConstructor) + { + foundConstructor = true; + if (methodDefinition.Parameters.Count == 0) + { + foundDefaultConstructor = true; + break; + } + } + } + if (foundConstructor && !foundDefaultConstructor) + { + continue; + } + } + var members = context.GetMembersByInferredType(psTypeName, isStatic, filter); foreach (var member in members) { @@ -6321,6 +6344,12 @@ private static bool IsWriteablePropertyMember(object member) return psPropertyInfo.IsSettable; } + if (member is PropertyMemberAst) + { + // Properties in PowerShell classes are always writeable + return true; + } + return false; } @@ -7192,127 +7221,254 @@ internal static List CompleteHashtableKeyForDynamicKeyword( return results; } + private static PSTypeName GetNestedHashtableKeyType(TypeInferenceContext typeContext, PSTypeName parentType, IList nestedKeys) + { + var currentType = parentType; + // The nestedKeys list should have the outer most key as the last element, and the inner most key as the first element + // If we fail to resolve the type of any key we return null + for (int i = nestedKeys.Count - 1; i >= 0; i--) + { + if (currentType is null) + { + return null; + } + + var typeMembers = typeContext.GetMembersByInferredType(currentType, false, null); + currentType = null; + foreach (var member in typeMembers) + { + if (member is PropertyInfo propertyInfo) + { + if (propertyInfo.Name.Equals(nestedKeys[i], StringComparison.OrdinalIgnoreCase)) + { + currentType = new PSTypeName(propertyInfo.PropertyType); + break; + } + } + else if (member is PropertyMemberAst memberAst && memberAst.Name.Equals(nestedKeys[i], StringComparison.OrdinalIgnoreCase)) + { + if (memberAst.PropertyType is null) + { + return null; + } + else + { + if (memberAst.PropertyType.TypeName is ArrayTypeName arrayType) + { + currentType = new PSTypeName(arrayType.ElementType); + } + else + { + currentType = new PSTypeName(memberAst.PropertyType.TypeName); + } + } + + break; + } + } + } + + return currentType; + } + internal static List CompleteHashtableKey(CompletionContext completionContext, HashtableAst hashtableAst) { + Ast previousAst = hashtableAst; + Ast parentAst = hashtableAst.Parent; + string parameterName = null; + var nestedHashtableKeys = new List(); + + // This loop determines if it's a nested hashtable and what the outermost hashtable is used for (Dynamic keyword, command argument, etc.) + // Note this also considers hashtables with arrays of hashtables to be nested to support scenarios like this: + // class Level1 + // { + // [Level2[]] $Prop1 + // } + // class Level2 + // { + // [string] $Prop2 + // } + // [Level1] @{ + // Prop1 = @( + // @{Prop2="Hello"} + // @{Pro} + // ) + // } + while (parentAst is not null) + { + switch (parentAst) + { + case HashtableAst parentTable: + foreach (var pair in parentTable.KeyValuePairs) + { + if (pair.Item2 == previousAst) + { + // Try to get the value of the hashtable key in the nested hashtable. + // If we fail to get the value then return early because we can't generate any useful completions + if (SafeExprEvaluator.TrySafeEval(pair.Item1, completionContext.ExecutionContext, out object value)) + { + if (value is not string stringValue) + { + return null; + } + + nestedHashtableKeys.Add(stringValue); + break; + } + else + { + return null; + } + } + } + break; + + case DynamicKeywordStatementAst dynamicKeyword: + return CompleteHashtableKeyForDynamicKeyword(completionContext, dynamicKeyword, hashtableAst); + + case CommandParameterAst cmdParam: + parameterName = cmdParam.ParameterName; + parentAst = cmdParam.Parent; + goto ExitWhileLoop; + + case AssignmentStatementAst assignment: + if (assignment.Left is MemberExpressionAst or ConvertExpressionAst) + { + parentAst = assignment.Left; + } + goto ExitWhileLoop; + + case CommandAst: + case ConvertExpressionAst: + case UsingStatementAst: + goto ExitWhileLoop; + + case CommandExpressionAst: + case PipelineAst: + case StatementBlockAst: + case ArrayExpressionAst: + case ArrayLiteralAst: + break; + + default: + return null; + } + + previousAst = parentAst; + parentAst = parentAst.Parent; + } + + ExitWhileLoop: + + bool hashtableIsNested = nestedHashtableKeys.Count > 0; int cursorOffset = completionContext.CursorPosition.Offset; string wordToComplete = completionContext.WordToComplete; var excludedKeys = new HashSet(StringComparer.OrdinalIgnoreCase); + // Filters out keys that have already been defined in the hashtable, except the one the cursor is at foreach (var keyPair in hashtableAst.KeyValuePairs) { - // Exclude all existing keys, except the key the cursor is currently at if (!(cursorOffset >= keyPair.Item1.Extent.StartOffset && cursorOffset <= keyPair.Item1.Extent.EndOffset)) { excludedKeys.Add(keyPair.Item1.Extent.Text); } } - var typeAst = hashtableAst.Parent as ConvertExpressionAst; - if (typeAst != null) + if (parentAst is UsingStatementAst usingStatement) { + if (hashtableIsNested || usingStatement.UsingStatementKind != UsingStatementKind.Module) + { + return null; + } + var result = new List(); - CompleteMemberByInferredType( - completionContext.TypeInferenceContext, AstTypeInference.InferTypeOf(typeAst, completionContext.TypeInferenceContext, TypeInferenceRuntimePermissions.AllowSafeEval), - result, wordToComplete + "*", IsWriteablePropertyMember, isStatic: false, excludedKeys); + foreach (var key in s_requiresModuleSpecKeys.Keys) + { + if (excludedKeys.Contains(key) + || (wordToComplete is not null && !key.StartsWith(wordToComplete, StringComparison.OrdinalIgnoreCase)) + || (key.Equals("RequiredVersion") && (excludedKeys.Contains("ModuleVersion") || excludedKeys.Contains("MaximumVersion"))) + || ((key.Equals("ModuleVersion") || key.Equals("MaximumVersion")) && excludedKeys.Contains("RequiredVersion"))) + { + continue; + } + result.Add(new CompletionResult(key, key, CompletionResultType.Property, s_requiresModuleSpecKeys[key])); + } + return result; } - // hashtable arguments sometimes have expected keys. Examples: - // new-object System.Drawing.Point -prop @{ X=1; Y=1 } - // dir | sort-object -prop @{Expression=... ; Ascending=... } - // format-table -Property - // Expression - // FormatString - // Label - // Width - // Alignment - // format-list -Property - // Expression - // FormatString - // Label - // format-custom -Property - // Expression - // Depth - // format-* -GroupBy - // Expression - // FormatString - // Label - // - - // Find out if we are in a command argument. Consider the following possibilities: - // cmd @{} - // cmd -foo @{} - // cmd -foo:@{} - // cmd @{},@{} - // cmd -foo @{},@{} - // cmd -foo:@{},@{} - - var ast = hashtableAst.Parent; - - // Handle completion for hashtable within DynamicKeyword statement - var dynamicKeywordStatementAst = ast as DynamicKeywordStatementAst; - if (dynamicKeywordStatementAst != null) + if (parentAst is MemberExpressionAst or ConvertExpressionAst) { - return CompleteHashtableKeyForDynamicKeyword(completionContext, dynamicKeywordStatementAst, hashtableAst); - } + IEnumerable inferredTypes; + if (hashtableIsNested) + { + var nestedType = GetNestedHashtableKeyType( + completionContext.TypeInferenceContext, + AstTypeInference.InferTypeOf(parentAst, completionContext.TypeInferenceContext, TypeInferenceRuntimePermissions.AllowSafeEval)[0], + nestedHashtableKeys); + if (nestedType is null) + { + return null; + } - if (ast is ArrayLiteralAst) - { - ast = ast.Parent; - } + inferredTypes = TypeInferenceVisitor.GetInferredEnumeratedTypes(new PSTypeName[] { nestedType }); + } + else + { + inferredTypes = TypeInferenceVisitor.GetInferredEnumeratedTypes( + AstTypeInference.InferTypeOf(parentAst, completionContext.TypeInferenceContext, TypeInferenceRuntimePermissions.AllowSafeEval)); + } - if (ast is CommandParameterAst) - { - ast = ast.Parent; + var result = new List(); + CompleteMemberByInferredType( + completionContext.TypeInferenceContext, + inferredTypes, + result, + wordToComplete + "*", + IsWriteablePropertyMember, + isStatic: false, + excludedKeys, + ignoreTypesWithoutDefaultConstructor: true); + return result; } - var commandAst = ast as CommandAst; - if (commandAst != null) + if (parentAst is CommandAst commandAst) { var binding = new PseudoParameterBinder().DoPseudoParameterBinding(commandAst, null, null, bindingType: PseudoParameterBinder.BindingType.ArgumentCompletion); - if (binding == null) + if (binding is null) { return null; } - string parameterName = null; - foreach (var boundArg in binding.BoundArguments) + if (parameterName is null) { - var astPair = boundArg.Value as AstPair; - if (astPair != null) + foreach (var boundArg in binding.BoundArguments) { - if (astPair.Argument == hashtableAst) + if (boundArg.Value is AstPair pair && pair.Argument == previousAst) { parameterName = boundArg.Key; - break; } - - continue; - } - - var astArrayPair = boundArg.Value as AstArrayPair; - if (astArrayPair != null) - { - if (astArrayPair.Argument.Contains(hashtableAst)) + else if (boundArg.Value is AstArrayPair arrayPair && arrayPair.Argument.Contains(previousAst)) { parameterName = boundArg.Key; - break; } - - continue; } } - if (parameterName != null) + if (parameterName is not null) { + List results; if (parameterName.Equals("GroupBy", StringComparison.OrdinalIgnoreCase)) { - switch (binding.CommandName) + if (!hashtableIsNested) { - case "Format-Table": - case "Format-List": - case "Format-Wide": - case "Format-Custom": - return GetSpecialHashTableKeyMembers(excludedKeys, wordToComplete, "Expression", "FormatString", "Label"); + switch (binding.CommandName) + { + case "Format-Table": + case "Format-List": + case "Format-Wide": + case "Format-Custom": + return GetSpecialHashTableKeyMembers(excludedKeys, wordToComplete, "Expression", "FormatString", "Label"); + } } return null; @@ -7320,41 +7476,44 @@ internal static List CompleteHashtableKey(CompletionContext co if (parameterName.Equals("Property", StringComparison.OrdinalIgnoreCase)) { - switch (binding.CommandName) + if (!hashtableIsNested) { - case "New-Object": - var inferredType = AstTypeInference.InferTypeOf(commandAst, completionContext.TypeInferenceContext, TypeInferenceRuntimePermissions.AllowSafeEval); - var result = new List(); - CompleteMemberByInferredType( - completionContext.TypeInferenceContext, inferredType, - result, completionContext.WordToComplete + "*", IsWriteablePropertyMember, isStatic: false, excludedKeys); - return result; - case "Select-Object": - return GetSpecialHashTableKeyMembers(excludedKeys, wordToComplete, "Name", "Expression"); - case "Sort-Object": - return GetSpecialHashTableKeyMembers(excludedKeys, wordToComplete, "Expression", "Ascending", "Descending"); - case "Group-Object": - return GetSpecialHashTableKeyMembers(excludedKeys, wordToComplete, "Expression"); - case "Format-Table": - return GetSpecialHashTableKeyMembers(excludedKeys, wordToComplete, "Expression", "FormatString", "Label", "Width", "Alignment"); - case "Format-List": - return GetSpecialHashTableKeyMembers(excludedKeys, wordToComplete, "Expression", "FormatString", "Label"); - case "Format-Wide": - return GetSpecialHashTableKeyMembers(excludedKeys, wordToComplete, "Expression", "FormatString"); - case "Format-Custom": - return GetSpecialHashTableKeyMembers(excludedKeys, wordToComplete, "Expression", "Depth"); - case "Set-CimInstance": - case "New-CimInstance": - var results = new List(); - NativeCompletionCimCommands(parameterName, binding.BoundArguments, results, commandAst, completionContext, excludedKeys, binding.CommandName); - // this method adds a null CompletionResult to the list but we don't want that here. - if (results.Count > 1) - { - results.RemoveAt(results.Count - 1); + switch (binding.CommandName) + { + case "New-Object": + var inferredType = AstTypeInference.InferTypeOf(commandAst, completionContext.TypeInferenceContext, TypeInferenceRuntimePermissions.AllowSafeEval); + results = new List(); + CompleteMemberByInferredType( + completionContext.TypeInferenceContext, inferredType, + results, completionContext.WordToComplete + "*", IsWriteablePropertyMember, isStatic: false, excludedKeys); return results; - } - - return null; + case "Select-Object": + return GetSpecialHashTableKeyMembers(excludedKeys, wordToComplete, "Name", "Expression"); + case "Sort-Object": + return GetSpecialHashTableKeyMembers(excludedKeys, wordToComplete, "Expression", "Ascending", "Descending"); + case "Group-Object": + return GetSpecialHashTableKeyMembers(excludedKeys, wordToComplete, "Expression"); + case "Format-Table": + return GetSpecialHashTableKeyMembers(excludedKeys, wordToComplete, "Expression", "FormatString", "Label", "Width", "Alignment"); + case "Format-List": + return GetSpecialHashTableKeyMembers(excludedKeys, wordToComplete, "Expression", "FormatString", "Label"); + case "Format-Wide": + return GetSpecialHashTableKeyMembers(excludedKeys, wordToComplete, "Expression", "FormatString"); + case "Format-Custom": + return GetSpecialHashTableKeyMembers(excludedKeys, wordToComplete, "Expression", "Depth"); + case "Set-CimInstance": + case "New-CimInstance": + results = new List(); + NativeCompletionCimCommands(parameterName, binding.BoundArguments, results, commandAst, completionContext, excludedKeys, binding.CommandName); + // this method adds a null CompletionResult to the list but we don't want that here. + if (results.Count > 1) + { + results.RemoveAt(results.Count - 1); + return results; + } + return null; + } + return null; } } @@ -7363,32 +7522,76 @@ internal static List CompleteHashtableKey(CompletionContext co switch (binding.CommandName) { case "Get-WinEvent": - return GetSpecialHashTableKeyMembers(excludedKeys, wordToComplete, "LogName", "ProviderName", "Path", "Keywords", "ID", "Level", + if (nestedHashtableKeys.Count == 1 + && nestedHashtableKeys[0].Equals("SuppressHashFilter", StringComparison.OrdinalIgnoreCase) + && hashtableAst.Parent.Parent.Parent is HashtableAst) + { + return GetSpecialHashTableKeyMembers(excludedKeys, wordToComplete, "LogName", "ProviderName", "Path", "Keywords", "ID", "Level", + "StartTime", "EndTime", "UserID", "Data"); + } + else if (!hashtableIsNested) + { + return GetSpecialHashTableKeyMembers(excludedKeys, wordToComplete, "LogName", "ProviderName", "Path", "Keywords", "ID", "Level", "StartTime", "EndTime", "UserID", "Data", "SuppressHashFilter"); + } + + return null; } } if (parameterName.Equals("Arguments", StringComparison.OrdinalIgnoreCase)) { - switch (binding.CommandName) + if (!hashtableIsNested) { - case "Invoke-CimMethod": - var result = new List(); - NativeCompletionCimCommands(parameterName, binding.BoundArguments, result, commandAst, completionContext, excludedKeys, binding.CommandName); - // this method adds a null CompletionResult to the list but we don't want that here. - if (result.Count > 1) - { - result.RemoveAt(result.Count - 1); - return result; - } + switch (binding.CommandName) + { + case "Invoke-CimMethod": + results = new List(); + NativeCompletionCimCommands(parameterName, binding.BoundArguments, results, commandAst, completionContext, excludedKeys, binding.CommandName); + // this method adds a null CompletionResult to the list but we don't want that here. + if (results.Count > 1) + { + results.RemoveAt(results.Count - 1); + return results; + } + return null; + } + } + return null; + } - return null; + IEnumerable inferredTypes; + if (hashtableIsNested) + { + var nestedType = GetNestedHashtableKeyType( + completionContext.TypeInferenceContext, + new PSTypeName(binding.BoundParameters[parameterName].Parameter.Type), + nestedHashtableKeys); + if (nestedType is null) + { + return null; } + inferredTypes = TypeInferenceVisitor.GetInferredEnumeratedTypes(new PSTypeName[] { nestedType }); + } + else + { + inferredTypes = TypeInferenceVisitor.GetInferredEnumeratedTypes(new PSTypeName[] { new PSTypeName(binding.BoundParameters[parameterName].Parameter.Type) }); } + + results = new List(); + CompleteMemberByInferredType( + completionContext.TypeInferenceContext, + inferredTypes, + results, + $"{wordToComplete}*", + IsWriteablePropertyMember, + isStatic: false, + excludedKeys, + ignoreTypesWithoutDefaultConstructor: true); + return results; } } - - if (ast.Parent is AssignmentStatementAst assignment && assignment.Left is VariableExpressionAst assignmentVar) + else if (!hashtableIsNested && parentAst is AssignmentStatementAst assignment && assignment.Left is VariableExpressionAst assignmentVar) { var firstSplatUse = completionContext.RelatedAsts[0].Find( currentAst => diff --git a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs index afa33d0e918..be3b045f703 100644 --- a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs +++ b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs @@ -708,6 +708,11 @@ object ICustomAstVisitor.VisitConvertExpression(ConvertExpressionAst convertExpr // [PSObject] @{ Key = "Value" } and the [PSCustomObject] @{ Key = "Value" } case. var type = convertExpressionAst.Type.TypeName.GetReflectionType(); + if (type is null && convertExpressionAst.Type.TypeName is TypeName unavailableType && unavailableType._typeDefinitionAst is not null) + { + return new[] { new PSTypeName(unavailableType._typeDefinitionAst) }; + } + if (type == typeof(PSObject) && convertExpressionAst.Child is HashtableAst hashtableAst) { if (InferTypes(hashtableAst).FirstOrDefault() is PSSyntheticTypeName syntheticTypeName) diff --git a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 index c56cd2ca94a..5a786e50e53 100644 --- a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 +++ b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 @@ -269,44 +269,87 @@ switch ($x) $completionText -join ' ' | Should -BeExactly 'Ascending Descending Expression' } - It 'Should complete New-Object hashtable' { - class X { - $A - $B - $C + context TypeConstructionWithHashtable { + BeforeAll { + class RandomTestType { + $A + $B + $C + } + function RandomTestTypeClassTestCompletion([RandomTestType]$Param1){} + Class LevelOneClass { + [LevelTwoClass] $Property1 + } + class LevelTwoClass { + [string] $Property2 + } + function LevelOneClassTestCompletion([LevelOneClass[]]$Param1){} + Add-Type -TypeDefinition 'public interface IRandomInterfaceTest{string DemoProperty { get; set; }}' + function functionWithInterfaceParam ([IRandomInterfaceTest]$Param1){} } - $res = TabExpansion2 -inputScript 'New-Object -TypeName X -Property @{ ' -cursorColumn 'New-Object -TypeName X -Property @{ '.Length - $res.CompletionMatches | Should -HaveCount 3 - $res.CompletionMatches.CompletionText -join ' ' | Should -BeExactly 'A B C' - } - It 'Complete hashtable key without duplicate keys' { - class X { - $A - $B - $C + It 'Should complete New-Object hashtable' { + $res = TabExpansion2 -inputScript 'New-Object -TypeName RandomTestType -Property @{ ' + $res.CompletionMatches | Should -HaveCount 3 + $res.CompletionMatches.CompletionText -join ' ' | Should -BeExactly 'A B C' } - $TestString = '[x]@{A="";^}' - $CursorIndex = $TestString.IndexOf('^') - $res = TabExpansion2 -inputScript $TestString.Remove($CursorIndex, 1) -cursorColumn $CursorIndex - $res.CompletionMatches | Should -HaveCount 2 - $res.CompletionMatches.CompletionText -join ' ' | Should -BeExactly 'B C' - } - It 'Complete hashtable key on empty line after key/value pair' { - class X { - $A - $B - $C + + It 'Complete hashtable key without duplicate keys' { + $TestString = '[RandomTestType]@{A="";^}' + $CursorIndex = $TestString.IndexOf('^') + $res = TabExpansion2 -inputScript $TestString.Remove($CursorIndex, 1) -cursorColumn $CursorIndex + $res.CompletionMatches | Should -HaveCount 2 + $res.CompletionMatches.CompletionText -join ' ' | Should -BeExactly 'B C' } - $TestString = @' -[x]@{ + + It 'Complete hashtable key on empty line after key/value pair' { + $TestString = @' +[RandomTestType]@{ B="" ^ } '@ - $CursorIndex = $TestString.IndexOf('^') - $res = TabExpansion2 -inputScript $TestString.Remove($CursorIndex, 1) -cursorColumn $CursorIndex - $res.CompletionMatches | Should -HaveCount 2 - $res.CompletionMatches.CompletionText -join ' ' | Should -BeExactly 'A C' + $CursorIndex = $TestString.IndexOf('^') + $res = TabExpansion2 -inputScript $TestString.Remove($CursorIndex, 1) -cursorColumn $CursorIndex + $res.CompletionMatches | Should -HaveCount 2 + $res.CompletionMatches.CompletionText -join ' ' | Should -BeExactly 'A C' + } + + It 'Should complete class properties for typed variable declaration with hashtable' { + $res = TabExpansion2 -inputScript '[RandomTestType]$TestVar = @{' + $res.CompletionMatches | Should -HaveCount 3 + $res.CompletionMatches.CompletionText -join ' ' | Should -BeExactly 'A B C' + } + + It 'Should complete class properties for typed command parameter with hashtable input' { + $res = TabExpansion2 -inputScript 'RandomTestTypeClassTestCompletion -Param1 @{' + $res.CompletionMatches | Should -HaveCount 3 + $res.CompletionMatches.CompletionText -join ' ' | Should -BeExactly 'A B C' + } + + It 'Should complete class properties for nested hashtable' { + $res = TabExpansion2 -inputScript '[LevelOneClass]@{Property1=@{' + $res.CompletionMatches[0].CompletionText | Should -BeExactly 'Property2' + } + + It 'Should complete class properties for underlying type in array parameter' { + $res = TabExpansion2 -inputScript 'LevelOneClassTestCompletion @{' + $res.CompletionMatches[0].CompletionText | Should -BeExactly 'Property1' + } + + It 'Should complete class properties for new class assignment to property' { + $res = TabExpansion2 -inputScript '$Var=[LevelOneClass]::new();$Var.Property1=@{' + $res.CompletionMatches[0].CompletionText | Should -BeExactly 'Property2' + } + + It 'Should not complete class properties from class with constructor that takes arguments' { + $res = TabExpansion2 -inputScript 'class ClassWithCustomConstructor {ClassWithCustomConstructor ($Param){}$A};[ClassWithCustomConstructor]@{' + $res.CompletionMatches[0].CompletionText | Should -BeNullOrEmpty + } + + It 'Should complete class properties for function with an interface type' { + $res = TabExpansion2 -inputScript 'functionWithInterfaceParam -Param1 @{' + $res.CompletionMatches[0].CompletionText | Should -BeExactly 'DemoProperty' + } } It 'Complete hashtable keys for Get-WinEvent FilterHashtable' -Skip:(!$IsWindows) { @@ -317,6 +360,18 @@ switch ($x) $res.CompletionMatches.CompletionText -join ' ' | Should -BeExactly 'LogName ProviderName Path Keywords ID Level StartTime EndTime UserID Data SuppressHashFilter' } + It 'Complete hashtable keys for Get-WinEvent SuppressHashFilter' -Skip:(!$IsWindows) { + $TestString = 'Get-WinEvent -FilterHashtable @{SuppressHashFilter=@{' + $res = TabExpansion2 -inputScript $TestString + $res.CompletionMatches | Should -HaveCount 10 + $res.CompletionMatches.CompletionText -join ' ' | Should -BeExactly 'LogName ProviderName Path Keywords ID Level StartTime EndTime UserID Data' + } + + It 'Complete hashtable keys for hashtable in array of arguments' { + $res = TabExpansion2 -inputScript 'Get-ChildItem | Format-Table -Property Attributes,@{' + $res.CompletionMatches.CompletionText -join ' ' | Should -BeExactly 'Expression FormatString Label Width Alignment' + } + It 'Complete hashtable keys for a hashtable used for splatting' { $TestString = '$GetChildItemParams=@{^};Get-ChildItem @GetChildItemParams -Force -Recurse' $CursorIndex = $TestString.IndexOf('^') @@ -2423,6 +2478,11 @@ function MyFunction ($param1, $param2) $res.CompletionMatches.CompletionText | Should -BeExactly $Expected } } + + It 'Should complete module specification keys in using module statement' { + $res = TabExpansion2 -inputScript 'using module @{' + $res.CompletionMatches.CompletionText -join ' ' | Should -BeExactly "GUID MaximumVersion ModuleName ModuleVersion RequiredVersion" + } } Describe "Tab completion tests with remote Runspace" -Tags Feature,RequireAdminOnWindows { From c77c286d7adfbe777226d7b0d6f480fe8f4d9452 Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Tue, 2 May 2023 06:00:07 +0100 Subject: [PATCH 509/779] Remove `PSv2CompletionCompleter` as part of the PowerShell v2 code cleanup (#18337) --- .../CommandCompletion/CommandCompletion.cs | 782 +----------------- .../TabCompletion/TabCompletion.Tests.ps1 | 25 - 2 files changed, 16 insertions(+), 791 deletions(-) diff --git a/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs b/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs index 21b4832a363..c40e3bdc8fb 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs @@ -4,13 +4,11 @@ using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; -using System.Diagnostics; using System.Diagnostics.CodeAnalysis; -using System.Globalization; using System.Management.Automation.Language; using System.Management.Automation.Runspaces; -using System.Text.RegularExpressions; #if LEGACYTELEMETRY +using System.Diagnostics; using Microsoft.PowerShell.Telemetry.Internal; #endif @@ -131,7 +129,6 @@ public static CommandCompletion CompleteInput(Ast ast, Token[] tokens, IScriptPo /// /// Invokes the script function TabExpansion2. - /// For legacy support, TabExpansion2 will indirectly call TabExpansion if it exists. /// /// The input script to complete. /// The offset in where completion is requested. @@ -180,17 +177,11 @@ public static CommandCompletion CompleteInput(string input, int cursorIndex, Has if (!powershell.IsChild) { CheckScriptCallOnRemoteRunspace(remoteRunspace); + + // TabExpansion2 script is not available prior to PSv3. if (remoteRunspace.GetCapabilities().Equals(Runspaces.RunspaceCapability.Default)) { - // Remoting to a Win7 machine. Use the legacy tab completion function from V1/V2 - int replacementIndex; - int replacementLength; - - powershell.Commands.Clear(); - var results = InvokeLegacyTabExpansion(powershell, input, cursorIndex, true, out replacementIndex, out replacementLength); - return new CommandCompletion( - new Collection(results ?? EmptyCompletionResult), - -1, replacementIndex, replacementLength); + return s_emptyCommandCompletion; } } } @@ -200,7 +191,6 @@ public static CommandCompletion CompleteInput(string input, int cursorIndex, Has /// /// Invokes the script function TabExpansion2. - /// For legacy support, TabExpansion2 will indirectly call TabExpansion if it exists. /// /// The ast for pre-parsed input. /// @@ -251,31 +241,17 @@ public static CommandCompletion CompleteInput(Ast ast, Token[] tokens, IScriptPo if (!powershell.IsChild) { CheckScriptCallOnRemoteRunspace(remoteRunspace); + + // TabExpansion2 script is not available prior to PSv3. if (remoteRunspace.GetCapabilities().Equals(Runspaces.RunspaceCapability.Default)) { - // Capability: - // SupportsDisconnect (0x1) -> If remoteMachine is Win8 or later - // Default (0x0) -> If remoteMachine is Win7 - // Remoting to a Win7 machine. Use the legacy tab completion function from V1/V2 - int replacementIndex; - int replacementLength; - - // When call the win7 TabExpansion script, the input should be the single current line - powershell.Commands.Clear(); - var inputAndCursor = GetInputAndCursorFromAst(cursorPosition); - var results = InvokeLegacyTabExpansion(powershell, inputAndCursor.Item1, inputAndCursor.Item2, true, out replacementIndex, out replacementLength); - return new CommandCompletion( - new Collection(results ?? EmptyCompletionResult), - -1, replacementIndex + inputAndCursor.Item3, replacementLength); - } - else - { - // Call script on a remote win8 machine - // when call the win8 TabExpansion2 script, the input should be the whole script text - string input = ast.Extent.Text; - int cursorIndex = ((InternalScriptPosition)cursorPosition).Offset; - return CallScriptWithStringParameterSet(input, cursorIndex, options, powershell); + return s_emptyCommandCompletion; } + + // When calling the TabExpansion2 script, the input should be the whole script text + string input = ast.Extent.Text; + int cursorIndex = ((InternalScriptPosition)cursorPosition).Offset; + return CallScriptWithStringParameterSet(input, cursorIndex, options, powershell); } } @@ -522,20 +498,10 @@ private static CommandCompletion CompleteInputImpl(Ast ast, Token[] tokens, IScr { var context = LocalPipeline.GetExecutionContextFromTLS(); - // First, check if a V1/V2 implementation of TabExpansion exists. If so, the user had overridden - // the built-in version, so we should continue to use theirs. int replacementIndex = -1; int replacementLength = -1; List results = null; - if (NeedToInvokeLegacyTabExpansion(powershell)) - { - var inputAndCursor = GetInputAndCursorFromAst(positionOfCursor); - results = InvokeLegacyTabExpansion(powershell, inputAndCursor.Item1, inputAndCursor.Item2, false, out replacementIndex, out replacementLength); - replacementIndex += inputAndCursor.Item3; - } - - if (results == null || results.Count == 0) { /* BROKEN code commented out, fix sometime // If we were invoked from TabExpansion2, we want to "remove" TabExpansion2 and anything it calls @@ -588,10 +554,10 @@ private static CommandCompletion CompleteInputImpl(Ast ast, Token[] tokens, IScr var completionResults = results ?? EmptyCompletionResult; #if LEGACYTELEMETRY - // no telemetry here. We don't capture tab completion performance. - sw.Stop(); - TelemetryAPI.ReportTabCompletionTelemetry(sw.ElapsedMilliseconds, completionResults.Count, - completionResults.Count > 0 ? completionResults[0].ResultType : CompletionResultType.Text); + // no telemetry here. We don't capture tab completion performance. + sw.Stop(); + TelemetryAPI.ReportTabCompletionTelemetry(sw.ElapsedMilliseconds, completionResults.Count, + completionResults.Count > 0 ? completionResults[0].ResultType : CompletionResultType.Text); #endif return new CommandCompletion( new Collection(completionResults), @@ -601,722 +567,6 @@ private static CommandCompletion CompleteInputImpl(Ast ast, Token[] tokens, IScr } } - private static Tuple GetInputAndCursorFromAst(IScriptPosition cursorPosition) - { - var line = cursorPosition.Line; - var cursor = cursorPosition.ColumnNumber - 1; - var adjustment = cursorPosition.Offset - cursor; - return Tuple.Create(line.Substring(0, cursor), cursor, adjustment); - } - - private static bool NeedToInvokeLegacyTabExpansion(PowerShell powershell) - { - var executionContext = powershell.GetContextFromTLS(); - - // We don't want command discovery to search unloaded modules for TabExpansion. - var functionInfo = executionContext.EngineSessionState.GetFunction("TabExpansion"); - if (functionInfo != null) - return true; - - var aliasInfo = executionContext.EngineSessionState.GetAlias("TabExpansion"); - if (aliasInfo != null) - return true; - - return false; - } - - private static List InvokeLegacyTabExpansion(PowerShell powershell, string input, int cursorIndex, bool remoteToWin7, out int replacementIndex, out int replacementLength) - { - List results = null; - - var legacyInput = (cursorIndex != input.Length) ? input.Substring(0, cursorIndex) : input; - char quote; - var lastword = LastWordFinder.FindLastWord(legacyInput, out replacementIndex, out quote); - replacementLength = legacyInput.Length - replacementIndex; - var helper = new PowerShellExecutionHelper(powershell); - - powershell.AddCommand("TabExpansion").AddArgument(legacyInput).AddArgument(lastword); - - Exception exceptionThrown; - var oldResults = helper.ExecuteCurrentPowerShell(out exceptionThrown); - if (oldResults != null) - { - results = new List(); - foreach (var oldResult in oldResults) - { - var completionResult = PSObject.Base(oldResult) as CompletionResult; - if (completionResult == null) - { - var oldResultStr = oldResult.ToString(); - - // Add back the quotes we removed if the result isn't quoted - if (quote != '\0') - { - if (oldResultStr.Length > 2 && oldResultStr[0] != quote) - { - oldResultStr = quote + oldResultStr + quote; - } - } - - completionResult = new CompletionResult(oldResultStr); - } - - results.Add(completionResult); - } - } - - if (remoteToWin7 && (results == null || results.Count == 0)) - { - string quoteStr = quote == '\0' ? string.Empty : quote.ToString(); - results = PSv2CompletionCompleter.PSv2GenerateMatchSetOfFiles(helper, lastword, replacementIndex == 0, quoteStr); - var cmdletResults = PSv2CompletionCompleter.PSv2GenerateMatchSetOfCmdlets(helper, lastword, quoteStr, replacementIndex == 0); - - if (cmdletResults != null && cmdletResults.Count > 0) - { - results.AddRange(cmdletResults); - } - } - - return results; - } - - /// - /// PSv2CompletionCompleter implements the algorithm we use to complete cmdlet/file names in PowerShell v2. This class - /// exists for legacy purpose only. It is used only in a remote interactive session from Win8 to Win7. V3 and forward - /// uses completely different completers. - /// - /// - /// The implementation of file name completion is completely different on V2 and V3 for remote scenarios. On PSv3, the - /// CompletionResults are generated always on the target machine, and - /// - private static class PSv2CompletionCompleter - { - private const string CharsRequiringQuotedString = "`&@'#{}()$,;|<> \t"; - - private static readonly Regex s_cmdletTabRegex = new Regex(@"^[\w\*\?]+-[\w\*\?]*"); - - #region "Handle Command" - - /// - /// Used when remoting from a win8 machine to a win7 machine. - /// - /// - /// - /// - private static bool PSv2IsCommandLikeCmdlet(string lastWord, out bool isSnapinSpecified) - { - isSnapinSpecified = false; - - string[] cmdletParts = lastWord.Split('\\'); - if (cmdletParts.Length == 1) - { - return s_cmdletTabRegex.IsMatch(lastWord); - } - - if (cmdletParts.Length == 2) - { - isSnapinSpecified = PSSnapInInfo.IsPSSnapinIdValid(cmdletParts[0]); - if (isSnapinSpecified) - { - return s_cmdletTabRegex.IsMatch(cmdletParts[1]); - } - } - - return false; - } - - private readonly struct CommandAndName - { - internal readonly PSObject Command; - internal readonly PSSnapinQualifiedName CommandName; - - internal CommandAndName(PSObject command, PSSnapinQualifiedName commandName) - { - this.Command = command; - this.CommandName = commandName; - } - } - - /// - /// Used when remoting from a win8 machine to a win7 machine. Complete command names. - /// - /// - /// - /// - /// - /// - internal static List PSv2GenerateMatchSetOfCmdlets(PowerShellExecutionHelper helper, string lastWord, string quote, bool completingAtStartOfLine) - { - var results = new List(); - bool isSnapinSpecified; - - if (!PSv2IsCommandLikeCmdlet(lastWord, out isSnapinSpecified)) - return results; - - helper.CurrentPowerShell - .AddCommand("Get-Command") - .AddParameter("Name", lastWord + "*") - .AddCommand("Sort-Object") - .AddParameter("Property", "Name"); - - Exception exceptionThrown; - Collection commands = helper.ExecuteCurrentPowerShell(out exceptionThrown); - - if (commands != null && commands.Count > 0) - { - // convert the PSObjects into strings - CommandAndName[] cmdlets = new CommandAndName[commands.Count]; - // if the command causes cmdlets from multiple mshsnapin is returned, - // append the mshsnapin name to disambiguate the cmdlets. - for (int i = 0; i < commands.Count; ++i) - { - PSObject command = commands[i]; - string cmdletFullName = CmdletInfo.GetFullName(command); - cmdlets[i] = new CommandAndName(command, PSSnapinQualifiedName.GetInstance(cmdletFullName)); - } - - if (isSnapinSpecified) - { - foreach (CommandAndName cmdlet in cmdlets) - { - AddCommandResult(cmdlet, true, completingAtStartOfLine, quote, results); - } - } - else - { - PrependSnapInNameForSameCmdletNames(cmdlets, completingAtStartOfLine, quote, results); - } - } - - return results; - } - - private static void AddCommandResult(CommandAndName commandAndName, bool useFullName, bool completingAtStartOfLine, string quote, List results) - { - Diagnostics.Assert(results != null, "Caller needs to make sure the result list is not null"); - - string name = useFullName ? commandAndName.CommandName.FullName : commandAndName.CommandName.ShortName; - string quotedFileName = AddQuoteIfNecessary(name, quote, completingAtStartOfLine); - - var commandType = SafeGetProperty(commandAndName.Command, "CommandType"); - if (commandType == null) - { - return; - } - - string toolTip; - string displayName = SafeGetProperty(commandAndName.Command, "Name"); - - if (commandType.Value == CommandTypes.Cmdlet || commandType.Value == CommandTypes.Application) - { - toolTip = SafeGetProperty(commandAndName.Command, "Definition"); - } - else - { - toolTip = displayName; - } - - results.Add(new CompletionResult(quotedFileName, displayName, CompletionResultType.Command, toolTip)); - } - - private static void PrependSnapInNameForSameCmdletNames(CommandAndName[] cmdlets, bool completingAtStartOfLine, string quote, List results) - { - Diagnostics.Assert(cmdlets != null && cmdlets.Length > 0, - "HasMultiplePSSnapIns must be called with a non-empty collection of PSObject"); - - int i = 0; - bool previousMatched = false; - while (true) - { - CommandAndName commandAndName = cmdlets[i]; - - int lookAhead = i + 1; - if (lookAhead >= cmdlets.Length) - { - AddCommandResult(commandAndName, previousMatched, completingAtStartOfLine, quote, results); - break; - } - - CommandAndName nextCommandAndName = cmdlets[lookAhead]; - - if (string.Equals( - commandAndName.CommandName.ShortName, - nextCommandAndName.CommandName.ShortName, - StringComparison.OrdinalIgnoreCase)) - { - AddCommandResult(commandAndName, true, completingAtStartOfLine, quote, results); - previousMatched = true; - } - else - { - AddCommandResult(commandAndName, previousMatched, completingAtStartOfLine, quote, results); - previousMatched = false; - } - - i++; - } - } - - #endregion "Handle Command" - - #region "Handle File Names" - - internal static List PSv2GenerateMatchSetOfFiles(PowerShellExecutionHelper helper, string lastWord, bool completingAtStartOfLine, string quote) - { - var results = new List(); - - // lastWord is treated as an PSPath. The match set includes those items that match that - // path, namely, the union of: - // (S1) the sorted set of items matching the last word - // (S2) the sorted set of items matching the last word + * - // If the last word contains no wildcard characters, then S1 is the empty set. S1 is always - // a subset of S2, but we want to present S1 first, then (S2 - S1) next. The idea is that - // if the user typed some wildcard characters, they'd prefer to see those matches before - // all of the rest. - - // Determine if we need to quote the paths we parse - - lastWord ??= string.Empty; - bool isLastWordEmpty = string.IsNullOrEmpty(lastWord); - bool lastCharIsStar = !isLastWordEmpty && lastWord.EndsWith('*'); - bool containsGlobChars = WildcardPattern.ContainsWildcardCharacters(lastWord); - - string wildWord = lastWord + "*"; - bool shouldFullyQualifyPaths = PSv2ShouldFullyQualifyPathsPath(helper, lastWord); - - // NTRAID#Windows Out Of Band Releases-927933-2006/03/13-JeffJon - // Need to detect when the path is a provider-direct path and make sure - // to remove the provider-qualifier when the resolved path is returned. - bool isProviderDirectPath = lastWord.StartsWith(@"\\", StringComparison.Ordinal) || - lastWord.StartsWith("//", StringComparison.Ordinal); - - List s1 = null; - List s2 = null; - - if (containsGlobChars && !isLastWordEmpty) - { - s1 = PSv2FindMatches( - helper, - lastWord, - shouldFullyQualifyPaths); - } - - if (!lastCharIsStar) - { - s2 = PSv2FindMatches( - helper, - wildWord, - shouldFullyQualifyPaths); - } - - IEnumerable combinedMatches = CombineMatchSets(s1, s2); - - if (combinedMatches != null) - { - foreach (var combinedMatch in combinedMatches) - { - string combinedMatchPath = WildcardPattern.Escape(combinedMatch.Path); - string combinedMatchConvertedPath = WildcardPattern.Escape(combinedMatch.ConvertedPath); - string completionText = isProviderDirectPath ? combinedMatchConvertedPath : combinedMatchPath; - - completionText = AddQuoteIfNecessary(completionText, quote, completingAtStartOfLine); - - bool? isContainer = SafeGetProperty(combinedMatch.Item, "PSIsContainer"); - string childName = SafeGetProperty(combinedMatch.Item, "PSChildName"); - string toolTip = PowerShellExecutionHelper.SafeToString(combinedMatch.ConvertedPath); - - if (isContainer != null && childName != null && toolTip != null) - { - CompletionResultType resultType = isContainer.Value - ? CompletionResultType.ProviderContainer - : CompletionResultType.ProviderItem; - results.Add(new CompletionResult(completionText, childName, resultType, toolTip)); - } - } - } - - return results; - } - - private static string AddQuoteIfNecessary(string completionText, string quote, bool completingAtStartOfLine) - { - if (completionText.AsSpan().IndexOfAny(CharsRequiringQuotedString) >= 0) - { - bool needAmpersand = quote.Length == 0 && completingAtStartOfLine; - string quoteInUse = quote.Length == 0 ? "'" : quote; - completionText = quoteInUse == "'" ? completionText.Replace("'", "''") : completionText; - completionText = quoteInUse + completionText + quoteInUse; - completionText = needAmpersand ? "& " + completionText : completionText; - } - else - { - completionText = quote + completionText + quote; - } - - return completionText; - } - - private static IEnumerable CombineMatchSets(List s1, List s2) - { - if (s1 == null || s1.Count < 1) - { - // only s2 contains results; which may be null or empty - return s2; - } - - if (s2 == null || s2.Count < 1) - { - // only s1 contains results - return s1; - } - - // s1 and s2 contain results - Diagnostics.Assert(s1 != null && s1.Count > 0, "s1 should have results"); - Diagnostics.Assert(s2 != null && s2.Count > 0, "if s1 has results, s2 must also"); - Diagnostics.Assert(s1.Count <= s2.Count, "s2 should always be larger than s1"); - - var result = new List(); - - // we need to remove from s2 those items in s1. Since the results from FindMatches will be sorted, - // just copy out the unique elements from s2 and s1. We know that every element of S1 will be in S2, - // so the result set will be S1 + (S2 - S1), which is the same size as S2. - result.AddRange(s1); - for (int i = 0, j = 0; i < s2.Count; ++i) - { - if (j < s1.Count && string.Equals(s2[i].Path, s1[j].Path, StringComparison.CurrentCultureIgnoreCase)) - { - ++j; - continue; - } - - result.Add(s2[i]); - } - -#if DEBUG - Diagnostics.Assert(result.Count == s2.Count, "result should be the same size as s2, see the size comment above"); - for (int i = 0; i < s1.Count; ++i) - { - string path = result[i].Path; - int j = result.FindLastIndex(item => item.Path == path); - Diagnostics.Assert(j == i, "elements of s1 should only come at the start of the results"); - } -#endif - return result; - } - - private static T SafeGetProperty(PSObject psObject, string propertyName) - { - if (psObject == null) - { - return default(T); - } - - PSPropertyInfo property = psObject.Properties[propertyName]; - if (property == null) - { - return default(T); - } - - object propertyValue = property.Value; - if (propertyValue == null) - { - return default(T); - } - - T returnValue; - if (LanguagePrimitives.TryConvertTo(propertyValue, out returnValue)) - { - return returnValue; - } - - return default(T); - } - - private static bool PSv2ShouldFullyQualifyPathsPath(PowerShellExecutionHelper helper, string lastWord) - { - // These are special cases, as they represent cases where the user expects to - // see the full path. - if (lastWord.StartsWith('~') || - lastWord.StartsWith('\\') || - lastWord.StartsWith('/')) - { - return true; - } - - helper.CurrentPowerShell - .AddCommand("Split-Path") - .AddParameter("Path", lastWord) - .AddParameter("IsAbsolute", true); - - bool isAbsolute = helper.ExecuteCommandAndGetResultAsBool(); - return isAbsolute; - } - - private readonly struct PathItemAndConvertedPath - { - internal readonly string Path; - internal readonly PSObject Item; - internal readonly string ConvertedPath; - - internal PathItemAndConvertedPath(string path, PSObject item, string convertedPath) - { - this.Path = path; - this.Item = item; - this.ConvertedPath = convertedPath; - } - } - - private static List PSv2FindMatches(PowerShellExecutionHelper helper, string path, bool shouldFullyQualifyPaths) - { - Diagnostics.Assert(!string.IsNullOrEmpty(path), "path should have a value"); - var result = new List(); - - Exception exceptionThrown; - PowerShell powershell = helper.CurrentPowerShell; - - // It's OK to use script, since tab completion is useless when the remote Win7 machine is in nolanguage mode - if (!shouldFullyQualifyPaths) - { - powershell.AddScript(string.Format( - CultureInfo.InvariantCulture, - "& {{ trap {{ continue }} ; resolve-path {0} -Relative -WarningAction SilentlyContinue | ForEach-Object {{,($_,(get-item $_ -WarningAction SilentlyContinue),(convert-path $_ -WarningAction SilentlyContinue))}} }}", - path)); - } - else - { - powershell.AddScript(string.Format( - CultureInfo.InvariantCulture, - "& {{ trap {{ continue }} ; resolve-path {0} -WarningAction SilentlyContinue | ForEach-Object {{,($_,(get-item $_ -WarningAction SilentlyContinue),(convert-path $_ -WarningAction SilentlyContinue))}} }}", - path)); - } - - Collection paths = helper.ExecuteCurrentPowerShell(out exceptionThrown); - if (paths == null || paths.Count == 0) - { - return null; - } - - foreach (PSObject t in paths) - { - var pathsArray = t.BaseObject as IList; - if (pathsArray != null && pathsArray.Count == 3) - { - object objectPath = pathsArray[0]; - PSObject item = pathsArray[1] as PSObject; - object convertedPath = pathsArray[1]; - - if (objectPath == null || item == null || convertedPath == null) - { - continue; - } - - result.Add(new PathItemAndConvertedPath( - PowerShellExecutionHelper.SafeToString(objectPath), - item, - PowerShellExecutionHelper.SafeToString(convertedPath))); - } - } - - if (result.Count == 0) - { - return null; - } - - result.Sort((PathItemAndConvertedPath x, PathItemAndConvertedPath y) => - { - Diagnostics.Assert(x.Path != null && y.Path != null, "SafeToString always returns a non-null string"); - return string.Compare(x.Path, y.Path, StringComparison.CurrentCultureIgnoreCase); - }); - - return result; - } - - #endregion "Handle File Names" - } - - /// - /// LastWordFinder implements the algorithm we use to search for the last word in a line of input taken from the console. - /// This class exists for legacy purposes only - V3 and forward uses a slightly different interface. - /// - private sealed class LastWordFinder - { - internal static string FindLastWord(string sentence, out int replacementIndexOut, out char closingQuote) - { - return (new LastWordFinder(sentence)).FindLastWord(out replacementIndexOut, out closingQuote); - } - - private LastWordFinder(string sentence) - { - _replacementIndex = 0; - Diagnostics.Assert(sentence != null, "need to provide an instance"); - _sentence = sentence; - } - - /// - /// Locates the last "word" in a string of text. A word is a congruous sequence of characters that are not - /// whitespace, or a contiguous set grouped by single or double quotes. Can be called by at most 1 thread at a time - /// per LastWordFinder instance. - /// - /// - /// Receives the character index (from the front of the string) of the starting point of the located word, or 0 if - /// the word starts at the beginning of the sentence. - /// - /// - /// Receives the quote character that would be needed to end the sentence with a balanced pair of quotes. For - /// instance, if sentence is "foo then " is returned, if sentence if "foo" then nothing is returned, if sentence is - /// 'foo then ' is returned, if sentence is 'foo' then nothing is returned. - /// - /// The last word located, or the empty string if no word could be found. - private string FindLastWord(out int replacementIndexOut, out char closingQuote) - { - bool inSingleQuote = false; - bool inDoubleQuote = false; - - ReplacementIndex = 0; - - for (_sentenceIndex = 0; _sentenceIndex < _sentence.Length; ++_sentenceIndex) - { - Diagnostics.Assert(!(inSingleQuote && inDoubleQuote), - "Can't be in both single and double quotes"); - - char c = _sentence[_sentenceIndex]; - - // there are 3 possibilities: - // 1) a new sequence is starting, - // 2) a sequence is ending, or - // 3) a sequence is due to end on the next matching quote, end-of-sentence, or whitespace - - if (c == '\'') - { - HandleQuote(ref inSingleQuote, ref inDoubleQuote, c); - } - else if (c == '"') - { - HandleQuote(ref inDoubleQuote, ref inSingleQuote, c); - } - else if (c == '`') - { - Consume(c); - if (++_sentenceIndex < _sentence.Length) - { - Consume(_sentence[_sentenceIndex]); - } - } - else if (IsWhitespace(c)) - { - if (_sequenceDueToEnd) - { - // we skipped a quote earlier, now end that sequence - - _sequenceDueToEnd = false; - if (inSingleQuote) - { - inSingleQuote = false; - } - - if (inDoubleQuote) - { - inDoubleQuote = false; - } - - ReplacementIndex = _sentenceIndex + 1; - } - else if (inSingleQuote || inDoubleQuote) - { - // a sequence is started and we're in quotes - - Consume(c); - } - else - { - // no sequence is started, so ignore c - - ReplacementIndex = _sentenceIndex + 1; - } - } - else - { - // a sequence is started and we're in it - - Consume(c); - } - } - - string result = new string(_wordBuffer, 0, _wordBufferIndex); - - closingQuote = inSingleQuote ? '\'' : inDoubleQuote ? '"' : '\0'; - replacementIndexOut = ReplacementIndex; - return result; - } - - private void HandleQuote(ref bool inQuote, ref bool inOppositeQuote, char c) - { - if (inOppositeQuote) - { - // a sequence is started, and we're in it. - Consume(c); - return; - } - - if (inQuote) - { - if (_sequenceDueToEnd) - { - // I've ended a sequence and am starting another; don't consume c, update replacementIndex - ReplacementIndex = _sentenceIndex + 1; - } - - _sequenceDueToEnd = !_sequenceDueToEnd; - } - else - { - // I'm starting a sequence; don't consume c, update replacementIndex - inQuote = true; - ReplacementIndex = _sentenceIndex; - } - } - - private void Consume(char c) - { - Diagnostics.Assert(_wordBuffer != null, "wordBuffer is not initialized"); - Diagnostics.Assert(_wordBufferIndex < _wordBuffer.Length, "wordBufferIndex is out of range"); - - _wordBuffer[_wordBufferIndex++] = c; - } - - private int ReplacementIndex - { - get - { - return _replacementIndex; - } - - set - { - Diagnostics.Assert(value >= 0 && value < _sentence.Length + 1, "value out of range"); - - // when we set the replacement index, that means we're also resetting our word buffer. we know wordBuffer - // will never be longer than sentence. - - _wordBuffer = new char[_sentence.Length]; - _wordBufferIndex = 0; - _replacementIndex = value; - } - } - - private static bool IsWhitespace(char c) - { - return (c == ' ') || (c == '\x0009'); - } - - private readonly string _sentence; - private char[] _wordBuffer; - private int _wordBufferIndex; - private int _replacementIndex; - private int _sentenceIndex; - private bool _sequenceDueToEnd; - } - #endregion private methods } } diff --git a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 index 5a786e50e53..13b4286a2b0 100644 --- a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 +++ b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 @@ -1981,31 +1981,6 @@ dir -Recurse ` } } - Context "User-overridden TabExpansion implementations" { - It "Override TabExpansion with function" { - function TabExpansion ($line, $lastword) { - "Overridden-TabExpansion-Function" - } - - $inputStr = '$PID.' - $res = [System.Management.Automation.CommandCompletion]::CompleteInput($inputStr, $inputst.Length, $null) - $res.CompletionMatches | Should -HaveCount 1 - $res.CompletionMatches[0].CompletionText | Should -BeExactly 'Overridden-TabExpansion-Function' - } - - It "Override TabExpansion with alias" { - function OverrideTabExpansion ($line, $lastword) { - "Overridden-TabExpansion-Alias" - } - Set-Alias -Name TabExpansion -Value OverrideTabExpansion - - $inputStr = '$PID.' - $res = [System.Management.Automation.CommandCompletion]::CompleteInput($inputStr, $inputst.Length, $null) - $res.CompletionMatches | Should -HaveCount 1 - $res.CompletionMatches[0].CompletionText | Should -BeExactly "Overridden-TabExpansion-Alias" - } - } - Context "No tab completion tests" { BeforeAll { $testCases = @( From 05fbceb48c48c58cfe9d224c9487be54d31180ac Mon Sep 17 00:00:00 2001 From: Olivia Date: Wed, 3 May 2023 04:36:33 +1200 Subject: [PATCH 510/779] Fix `New-Item` to re-create `Junction` when `-Force` is specified (#18311) --- .../namespaces/FileSystemProvider.cs | 37 ++++++++----------- .../FileSystem.Tests.ps1 | 13 +++++++ 2 files changed, 29 insertions(+), 21 deletions(-) diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index 1db69c2a125..b8d8e6526af 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -2485,40 +2485,35 @@ protected override void NewItem( } // Junctions cannot have files - if (DirectoryInfoHasChildItems((DirectoryInfo)pathDirInfo)) + if (!Force && DirectoryInfoHasChildItems((DirectoryInfo)pathDirInfo)) { string message = StringUtil.Format(FileSystemProviderStrings.DirectoryNotEmpty, path); WriteError(new ErrorRecord(new IOException(message), "DirectoryNotEmpty", ErrorCategory.WriteError, path)); return; } - if (Force) + try { - try + pathDirInfo.Delete(); + } + catch (Exception exception) + { + if ((exception is DirectoryNotFoundException) || + (exception is UnauthorizedAccessException) || + (exception is System.Security.SecurityException) || + (exception is IOException)) { - pathDirInfo.Delete(); + WriteError(new ErrorRecord(exception, "NewItemDeleteIOError", ErrorCategory.WriteError, path)); } - catch (Exception exception) + else { - if ((exception is DirectoryNotFoundException) || - (exception is UnauthorizedAccessException) || - (exception is System.Security.SecurityException) || - (exception is IOException)) - { - WriteError(new ErrorRecord(exception, "NewItemDeleteIOError", ErrorCategory.WriteError, path)); - } - else - { - throw; - } + throw; } } } - else - { - CreateDirectory(path, false); - pathDirInfo = new DirectoryInfo(path); - } + + CreateDirectory(path, streamOutput: false); + pathDirInfo = new DirectoryInfo(path); try { diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/FileSystem.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/FileSystem.Tests.ps1 index 0f5222b3db5..5849d2ea9fb 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/FileSystem.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/FileSystem.Tests.ps1 @@ -550,6 +550,7 @@ Describe "Hard link and symbolic link tests" -Tags "CI", "RequireAdminOnWindows" $nonFile = Join-Path $TestPath "not-a-file" $fileContent = "some text" $realDir = Join-Path $TestPath "subdir" + $realDir2 = Join-Path $TestPath "second-subdir" $nonDir = Join-Path $TestPath "not-a-dir" $hardLinkToFile = Join-Path $TestPath "hard-to-file.txt" $symLinkToFile = Join-Path $TestPath "sym-link-to-file.txt" @@ -560,6 +561,7 @@ Describe "Hard link and symbolic link tests" -Tags "CI", "RequireAdminOnWindows" New-Item -ItemType File -Path $realFile -Value $fileContent > $null New-Item -ItemType Directory -Path $realDir > $null + New-Item -ItemType Directory -Path $realDir2 > $null } Context "New-Item and hard/symbolic links" { @@ -628,6 +630,17 @@ Describe "Hard link and symbolic link tests" -Tags "CI", "RequireAdminOnWindows" $i = New-Item -ItemType File -Path "$TestDrive\file.txt" -Force -ErrorAction Ignore { New-Item -ItemType HardLink -Path $i -Target $i -Force -ErrorAction Stop } | Should -Throw -ErrorId "TargetIsSameAsLink,Microsoft.PowerShell.Commands.NewItemCommand" } + + It "New-Item -Force can overwrite a junction" -Skip:(-Not $IsWindows){ + $rd2 = Get-Item -Path $realDir2 + New-Item -Name testfile.txt -ItemType file -Path $realDir + New-Item -ItemType Junction -Path $junctionToDir -Value $realDir > $null + Test-Path $junctionToDir | Should -BeTrue + { New-Item -ItemType Junction -Path $junctionToDir -Value $realDir -ErrorAction Stop > $null } | Should -Throw -ErrorId "DirectoryNotEmpty,Microsoft.PowerShell.Commands.NewItemCommand" + New-Item -ItemType Junction -Path $junctionToDir -Value $realDir2 -Force > $null + $Junction = Get-Item -Path $junctionToDir + $Junction.Target | Should -BeExactly $rd2.ToString() + } } Context "Get-ChildItem and symbolic links" { From 5d7b3fc453dd8ad1d679e36c07dbe187a6efe2c8 Mon Sep 17 00:00:00 2001 From: Ikko Eltociear Ashimine Date: Wed, 3 May 2023 01:41:27 +0900 Subject: [PATCH 511/779] Fix a typo in `serialization.cs` (#19598) --- src/System.Management.Automation/engine/serialization.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/System.Management.Automation/engine/serialization.cs b/src/System.Management.Automation/engine/serialization.cs index e885db41b65..4705d269607 100644 --- a/src/System.Management.Automation/engine/serialization.cs +++ b/src/System.Management.Automation/engine/serialization.cs @@ -5122,7 +5122,7 @@ internal TypeSerializationInfo(Type type, string itemTag, string propertyTag, Ty /// /// A class for identifying types which are treated as KnownType by Monad. - /// A KnownType is guranteed to be available on machine on which monad is + /// A KnownType is guaranteed to be available on machine on which monad is /// running. /// internal static class KnownTypes From a153446a015aec0c130c618fecd96bd2d6611f41 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Tue, 2 May 2023 10:54:39 -0700 Subject: [PATCH 512/779] Add `Get-SecureRandom` cmdlet (#19587) * Add `Get-SecureRandom` cmdlet * update comments * address Paul and Travis' comments * Update test/powershell/Modules/Microsoft.PowerShell.Utility/Get-SecureRandom.Tests.ps1 Co-authored-by: James Truher [MSFT] * address codefactor * address Ilya's feedback creating a base class for both cmdlets * remove unused `using` --------- Co-authored-by: James Truher [MSFT] --- .../commands/utility/GetRandomCommand.cs | 705 +---------------- .../commands/utility/GetRandomCommandBase.cs | 719 ++++++++++++++++++ .../utility/GetSecureRandomCommand.cs | 18 + .../Microsoft.PowerShell.Utility.psd1 | 2 +- .../Microsoft.PowerShell.Utility.psd1 | 2 +- .../Get-SecureRandom.Tests.ps1 | 183 +++++ .../engine/Basic/DefaultCommands.Tests.ps1 | 1 + 7 files changed, 927 insertions(+), 703 deletions(-) create mode 100644 src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRandomCommandBase.cs create mode 100644 src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetSecureRandomCommand.cs create mode 100644 test/powershell/Modules/Microsoft.PowerShell.Utility/Get-SecureRandom.Tests.ps1 diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRandomCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRandomCommand.cs index a8ad9deb22b..c77c25c5f4f 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRandomCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRandomCommand.cs @@ -1,199 +1,18 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Globalization; using System.Management.Automation; -using System.Management.Automation.Runspaces; -using System.Numerics; -using System.Security.Cryptography; -using System.Threading; - -using Debug = System.Management.Automation.Diagnostics; namespace Microsoft.PowerShell.Commands { /// - /// This class implements get-random cmdlet. + /// This class implements `Get-Random` cmdlet. /// - /// - [Cmdlet(VerbsCommon.Get, "Random", DefaultParameterSetName = GetRandomCommand.RandomNumberParameterSet, + [Cmdlet(VerbsCommon.Get, "Random", DefaultParameterSetName = GetRandomCommandBase.RandomNumberParameterSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097016", RemotingCapability = RemotingCapability.None)] [OutputType(typeof(int), typeof(long), typeof(double))] - public class GetRandomCommand : PSCmdlet + public sealed class GetRandomCommand : GetRandomCommandBase { - #region Parameter set handling - - private const string RandomNumberParameterSet = "RandomNumberParameterSet"; - private const string RandomListItemParameterSet = "RandomListItemParameterSet"; - private const string ShuffleParameterSet = "ShuffleParameterSet"; - - private static readonly object[] _nullInArray = new object[] { null }; - - private enum MyParameterSet - { - Unknown, - RandomNumber, - RandomListItem - } - - private MyParameterSet _effectiveParameterSet; - - private MyParameterSet EffectiveParameterSet - { - get - { - // cache MyParameterSet enum instead of doing string comparison every time - if (_effectiveParameterSet == MyParameterSet.Unknown) - { - if ((MyInvocation.ExpectingInput) && (Maximum == null) && (Minimum == null)) - { - _effectiveParameterSet = MyParameterSet.RandomListItem; - } - else if (ParameterSetName == GetRandomCommand.RandomListItemParameterSet - || ParameterSetName == GetRandomCommand.ShuffleParameterSet) - { - _effectiveParameterSet = MyParameterSet.RandomListItem; - } - else if (ParameterSetName.Equals(GetRandomCommand.RandomNumberParameterSet, StringComparison.OrdinalIgnoreCase)) - { - if ((Maximum != null) && (Maximum.GetType().IsArray)) - { - InputObject = (object[])Maximum; - _effectiveParameterSet = MyParameterSet.RandomListItem; - } - else - { - _effectiveParameterSet = MyParameterSet.RandomNumber; - } - } - else - { - Debug.Assert(false, "Unrecognized parameter set"); - } - } - - return _effectiveParameterSet; - } - } - - #endregion Parameter set handling - - #region Error handling - - private void ThrowMinGreaterThanOrEqualMax(object minValue, object maxValue) - { - if (minValue == null) - { - throw PSTraceSource.NewArgumentNullException("min"); - } - - if (maxValue == null) - { - throw PSTraceSource.NewArgumentNullException("max"); - } - - ErrorRecord errorRecord = new( - new ArgumentException(string.Format( - CultureInfo.InvariantCulture, GetRandomCommandStrings.MinGreaterThanOrEqualMax, minValue, maxValue)), - "MinGreaterThanOrEqualMax", - ErrorCategory.InvalidArgument, - null); - - ThrowTerminatingError(errorRecord); - } - - #endregion - - #region Random generator state - - private static readonly ReaderWriterLockSlim s_runspaceGeneratorMapLock = new(); - - // 1-to-1 mapping of runspaces and random number generators - private static readonly Dictionary s_runspaceGeneratorMap = new(); - - private static void CurrentRunspace_StateChanged(object sender, RunspaceStateEventArgs e) - { - switch (e.RunspaceStateInfo.State) - { - case RunspaceState.Broken: - case RunspaceState.Closed: - try - { - GetRandomCommand.s_runspaceGeneratorMapLock.EnterWriteLock(); - GetRandomCommand.s_runspaceGeneratorMap.Remove(((Runspace)sender).InstanceId); - } - finally - { - GetRandomCommand.s_runspaceGeneratorMapLock.ExitWriteLock(); - } - - break; - } - } - - private PolymorphicRandomNumberGenerator _generator; - - /// - /// Gets and sets generator associated with the current runspace. - /// - private PolymorphicRandomNumberGenerator Generator - { - get - { - if (_generator == null) - { - Guid runspaceId = Context.CurrentRunspace.InstanceId; - - bool needToInitialize = false; - try - { - GetRandomCommand.s_runspaceGeneratorMapLock.EnterReadLock(); - needToInitialize = !GetRandomCommand.s_runspaceGeneratorMap.TryGetValue(runspaceId, out _generator); - } - finally - { - GetRandomCommand.s_runspaceGeneratorMapLock.ExitReadLock(); - } - - if (needToInitialize) - { - Generator = new PolymorphicRandomNumberGenerator(); - } - } - - return _generator; - } - - set - { - _generator = value; - Runspace myRunspace = Context.CurrentRunspace; - - try - { - GetRandomCommand.s_runspaceGeneratorMapLock.EnterWriteLock(); - if (!GetRandomCommand.s_runspaceGeneratorMap.ContainsKey(myRunspace.InstanceId)) - { - // make sure we won't leave the generator around after runspace exits - myRunspace.StateChanged += CurrentRunspace_StateChanged; - } - - GetRandomCommand.s_runspaceGeneratorMap[myRunspace.InstanceId] = _generator; - } - finally - { - GetRandomCommand.s_runspaceGeneratorMapLock.ExitWriteLock(); - } - } - } - - #endregion - - #region Common parameters - /// /// Seed used to reinitialize random numbers generator. /// @@ -201,194 +20,6 @@ private PolymorphicRandomNumberGenerator Generator [ValidateNotNull] public int? SetSeed { get; set; } - #endregion Common parameters - - #region Parameters for RandomNumberParameterSet - - /// - /// Maximum number to generate. - /// - [Parameter(ParameterSetName = RandomNumberParameterSet, Position = 0)] - public object Maximum { get; set; } - - /// - /// Minimum number to generate. - /// - [Parameter(ParameterSetName = RandomNumberParameterSet)] - public object Minimum { get; set; } - - private static bool IsInt(object o) - { - if (o == null || o is int) - { - return true; - } - - return false; - } - - private static bool IsInt64(object o) - { - if (o == null || o is long) - { - return true; - } - - return false; - } - - private static object ProcessOperand(object o) - { - if (o == null) - { - return null; - } - - PSObject pso = PSObject.AsPSObject(o); - object baseObject = pso.BaseObject; - - if (baseObject is string) - { - // The type argument passed in does not decide the number type we want to convert to. ScanNumber will return - // int/long/double based on the string form number passed in. - baseObject = System.Management.Automation.Language.Parser.ScanNumber((string)baseObject, typeof(int)); - } - - return baseObject; - } - - private static double ConvertToDouble(object o, double defaultIfNull) - { - if (o == null) - { - return defaultIfNull; - } - - double result = (double)LanguagePrimitives.ConvertTo(o, typeof(double), CultureInfo.InvariantCulture); - return result; - } - - #endregion - - #region Parameters and variables for RandomListItemParameterSet - - private List _chosenListItems; - private int _numberOfProcessedListItems; - - /// - /// List from which random elements are chosen. - /// - [Parameter(ParameterSetName = RandomListItemParameterSet, ValueFromPipeline = true, Position = 0, Mandatory = true)] - [Parameter(ParameterSetName = ShuffleParameterSet, ValueFromPipeline = true, Position = 0, Mandatory = true)] - [System.Management.Automation.AllowNull] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public object[] InputObject { get; set; } - - /// - /// Number of items to output (number of list items or of numbers). - /// - [Parameter(ParameterSetName = RandomNumberParameterSet)] - [Parameter(ParameterSetName = RandomListItemParameterSet)] - [ValidateRange(1, int.MaxValue)] - public int Count { get; set; } = 1; - - #endregion - - #region Shuffle parameter - - /// - /// Gets or sets whether the command should return all input objects in randomized order. - /// - [Parameter(ParameterSetName = ShuffleParameterSet, Mandatory = true)] - public SwitchParameter Shuffle { get; set; } - - #endregion - - #region Cmdlet processing methods - - private double GetRandomDouble(double minValue, double maxValue) - { - double randomNumber; - double diff = maxValue - minValue; - - // I couldn't find a better fix for bug #216893 then - // to test and retry if a random number falls outside the bounds - // because of floating-point-arithmetic inaccuracies. - // - // Performance in the normal case is not impacted much. - // In low-precision situations we should converge to a solution quickly - // (diff gets smaller at a quick pace). - - if (double.IsInfinity(diff)) - { - do - { - double r = Generator.NextDouble(); - randomNumber = minValue + r * maxValue - r * minValue; - } - while (randomNumber >= maxValue); - } - else - { - do - { - double r = Generator.NextDouble(); - randomNumber = minValue + r * diff; - diff *= r; - } - while (randomNumber >= maxValue); - } - - return randomNumber; - } - - /// - /// Get a random Int64 type number. - /// - /// - /// - /// - private long GetRandomInt64(long minValue, long maxValue) - { - // Randomly generate eight bytes and convert the byte array to UInt64 - var buffer = new byte[sizeof(ulong)]; - ulong randomUint64; - - BigInteger bigIntegerDiff = (BigInteger)maxValue - (BigInteger)minValue; - - // When the difference is less than int.MaxValue, use Random.Next(int, int) - if (bigIntegerDiff <= int.MaxValue) - { - int randomDiff = Generator.Next(0, (int)(maxValue - minValue)); - return minValue + randomDiff; - } - - // The difference of two Int64 numbers would not exceed UInt64.MaxValue, so it can be represented by a UInt64 number. - ulong uint64Diff = (ulong)bigIntegerDiff; - - // Calculate the number of bits to represent the diff in type UInt64 - int bitsToRepresentDiff = 0; - ulong diffCopy = uint64Diff; - for (; diffCopy != 0; bitsToRepresentDiff++) - { - diffCopy >>= 1; - } - // Get the mask for the number of bits - ulong mask = (0xffffffffffffffff >> (64 - bitsToRepresentDiff)); - do - { - // Randomly fill the buffer - Generator.NextBytes(buffer); - randomUint64 = BitConverter.ToUInt64(buffer, 0); - - // Get the last 'bitsToRepresentDiff' number of random bits - randomUint64 &= mask; - } while (uint64Diff <= randomUint64); - - double randomNumber = minValue * 1.0 + randomUint64 * 1.0; - return (long)randomNumber; - } - /// /// This method implements the BeginProcessing method for get-random command. /// @@ -399,335 +30,7 @@ protected override void BeginProcessing() Generator = new PolymorphicRandomNumberGenerator(SetSeed.Value); } - if (EffectiveParameterSet == MyParameterSet.RandomNumber) - { - object maxOperand = ProcessOperand(Maximum); - object minOperand = ProcessOperand(Minimum); - - if (IsInt(maxOperand) && IsInt(minOperand)) - { - int minValue = minOperand != null ? (int)minOperand : 0; - int maxValue = maxOperand != null ? (int)maxOperand : int.MaxValue; - - if (minValue >= maxValue) - { - ThrowMinGreaterThanOrEqualMax(minValue, maxValue); - } - - for (int i = 0; i < Count; i++) - { - int randomNumber = Generator.Next(minValue, maxValue); - Debug.Assert(minValue <= randomNumber, "lower bound <= random number"); - Debug.Assert(randomNumber < maxValue, "random number < upper bound"); - - WriteObject(randomNumber); - } - } - else if ((IsInt64(maxOperand) || IsInt(maxOperand)) && (IsInt64(minOperand) || IsInt(minOperand))) - { - long minValue = minOperand != null ? ((minOperand is long) ? (long)minOperand : (int)minOperand) : 0; - long maxValue = maxOperand != null ? ((maxOperand is long) ? (long)maxOperand : (int)maxOperand) : long.MaxValue; - - if (minValue >= maxValue) - { - ThrowMinGreaterThanOrEqualMax(minValue, maxValue); - } - - for (int i = 0; i < Count; i++) - { - long randomNumber = GetRandomInt64(minValue, maxValue); - Debug.Assert(minValue <= randomNumber, "lower bound <= random number"); - Debug.Assert(randomNumber < maxValue, "random number < upper bound"); - - WriteObject(randomNumber); - } - } - else - { - double minValue = (minOperand is double) ? (double)minOperand : ConvertToDouble(Minimum, 0.0); - double maxValue = (maxOperand is double) ? (double)maxOperand : ConvertToDouble(Maximum, double.MaxValue); - - if (minValue >= maxValue) - { - ThrowMinGreaterThanOrEqualMax(minValue, maxValue); - } - - for (int i = 0; i < Count; i++) - { - double randomNumber = GetRandomDouble(minValue, maxValue); - Debug.Assert(minValue <= randomNumber, "lower bound <= random number"); - Debug.Assert(randomNumber < maxValue, "random number < upper bound"); - - WriteObject(randomNumber); - } - } - } - else if (EffectiveParameterSet == MyParameterSet.RandomListItem) - { - _chosenListItems = new List(); - _numberOfProcessedListItems = 0; - } - } - - // rough proof that when choosing random K items out of N items - // each item has got K/N probability of being included in the final list - // - // probability that a particular item in chosenListItems is NOT going to be replaced - // when processing I-th input item [assumes I > K]: - // P_one_step(I) = 1 - ((K / I) * ((K - 1) / K) + ((I - K) / I) = (I - 1) / I - // <--A--> <-----B-----> <-----C-----> - // A - probability that I-th element is going to be replacing an element from chosenListItems - // (see (1) in the code below) - // B - probability that a particular element from chosenListItems is NOT going to be replaced - // (see (2) in the code below) - // C - probability that I-th element is NOT going to be replacing an element from chosenListItems - // (see (1) in the code below) - // - // probability that a particular item in chosenListItems is NOT going to be replaced - // when processing input items J through N [assumes J > K] - // P_removal(J) = Multiply(for I = J to N) P(I) = - // = ((J - 1) / J) * (J / (J + 1)) * ... * ((N - 2) / (N - 1)) * ((N - 1) / N) = - // = (J - 1) / N - // - // probability that when processing an element it is going to be put into chosenListItems - // P_insertion(I) = 1.0 when I <= K - see (3) in the code below - // P_insertion(I) = K/N otherwise - see (1) in the code below - // - // probability that a given element is going to be a part of the final list - // P_final(I) = P_insertion(I) * P_removal(max(I + 1, K + 1)) - // [for I <= K] = 1.0 * ((K + 1) - 1) / N = K / N - // [otherwise] = (K / I) * ((I + 1) - 1) / N = K / N - // - // which proves that P_final(I) = K / N for all values of I. QED. - - /// - /// This method implements the ProcessRecord method for get-random command. - /// - protected override void ProcessRecord() - { - if (EffectiveParameterSet == MyParameterSet.RandomListItem) - { - if (ParameterSetName == ShuffleParameterSet) - { - // this allows for $null to be in an array passed to InputObject - foreach (object item in InputObject ?? _nullInArray) - { - _chosenListItems.Add(item); - } - } - else - { - foreach (object item in InputObject ?? _nullInArray) - { - // (3) - if (_numberOfProcessedListItems < Count) - { - Debug.Assert(_chosenListItems.Count == _numberOfProcessedListItems, "Initial K elements should all be included in chosenListItems"); - _chosenListItems.Add(item); - } - else - { - Debug.Assert(_chosenListItems.Count == Count, "After processing K initial elements, the length of chosenItems should stay equal to K"); - - // (1) - if (Generator.Next(_numberOfProcessedListItems + 1) < Count) - { - // (2) - int indexToReplace = Generator.Next(_chosenListItems.Count); - _chosenListItems[indexToReplace] = item; - } - } - - _numberOfProcessedListItems++; - } - } - } - } - - /// - /// This method implements the EndProcessing method for get-random command. - /// - protected override void EndProcessing() - { - if (EffectiveParameterSet == MyParameterSet.RandomListItem) - { - // make sure the order is truly random - // (all permutations with the same probability) - // O(n) time - int n = _chosenListItems.Count; - for (int i = 0; i < n; i++) - { - // randomly choose j from [i...n) - int j = Generator.Next(i, n); - - WriteObject(_chosenListItems[j]); - - // remove the output object from consideration in the next iteration. - if (i != j) - { - _chosenListItems[j] = _chosenListItems[i]; - } - } - } - } - - #endregion Processing methods - } - - /// - /// Provides an adapter API for random numbers that may be either cryptographically random, or - /// generated with the regular pseudo-random number generator. Re-implementations of - /// methods using the NextBytes() primitive based on the CLR implementation: - /// https://referencesource.microsoft.com/#mscorlib/system/random.cs. - /// - internal class PolymorphicRandomNumberGenerator - { - /// - /// Initializes a new instance of the class. - /// - public PolymorphicRandomNumberGenerator() - { - _cryptographicGenerator = RandomNumberGenerator.Create(); - _pseudoGenerator = null; - } - - internal PolymorphicRandomNumberGenerator(int seed) - { - _cryptographicGenerator = null; - _pseudoGenerator = new Random(seed); - } - - private readonly Random _pseudoGenerator = null; - private readonly RandomNumberGenerator _cryptographicGenerator = null; - - /// - /// Generates a random floating-point number that is greater than or equal to 0.0, and less than 1.0. - /// - /// A random floating-point number that is greater than or equal to 0.0, and less than 1.0. - internal double NextDouble() - { - // According to the CLR source: - // "Including this division at the end gives us significantly improved random number distribution." - return Next() * (1.0 / int.MaxValue); - } - - /// - /// Generates a non-negative random integer. - /// - /// A non-negative random integer. - internal int Next() - { - int randomNumber; - - // The CLR implementation just fudges - // Int32.MaxValue down to (Int32.MaxValue - 1). This implementation - // errs on the side of correctness. - do - { - randomNumber = InternalSample(); - } - while (randomNumber == int.MaxValue); - - if (randomNumber < 0) - { - randomNumber += int.MaxValue; - } - - return randomNumber; - } - - /// - /// Returns a random integer that is within a specified range. - /// - /// The exclusive upper bound of the random number returned. - /// - internal int Next(int maxValue) - { - if (maxValue < 0) - { - throw new ArgumentOutOfRangeException(nameof(maxValue), GetRandomCommandStrings.MaxMustBeGreaterThanZeroApi); - } - - return Next(0, maxValue); - } - - /// - /// Returns a random integer that is within a specified range. - /// - /// The inclusive lower bound of the random number returned. - /// The exclusive upper bound of the random number returned. maxValue must be greater than or equal to minValue. - /// - public int Next(int minValue, int maxValue) - { - if (minValue > maxValue) - { - throw new ArgumentOutOfRangeException(nameof(minValue), GetRandomCommandStrings.MinGreaterThanOrEqualMaxApi); - } - - int randomNumber = 0; - - long range = (long)maxValue - (long)minValue; - if (range <= int.MaxValue) - { - randomNumber = ((int)(NextDouble() * range) + minValue); - } - else - { - double largeSample = InternalSampleLargeRange() * (1.0 / (2 * ((uint)int.MaxValue))); - randomNumber = (int)((long)(largeSample * range) + minValue); - } - - return randomNumber; - } - - /// - /// Fills the elements of a specified array of bytes with random numbers. - /// - /// The array to be filled. - internal void NextBytes(byte[] buffer) - { - if (_cryptographicGenerator != null) - { - _cryptographicGenerator.GetBytes(buffer); - } - else - { - _pseudoGenerator.NextBytes(buffer); - } - } - - /// - /// Samples a random integer. - /// - /// A random integer, using the full range of Int32. - private int InternalSample() - { - int randomNumber; - byte[] data = new byte[sizeof(int)]; - - NextBytes(data); - randomNumber = BitConverter.ToInt32(data, 0); - - return randomNumber; - } - - /// - /// Samples a random int when the range is large. This does - /// not need to be in the range of -Double.MaxValue .. Double.MaxValue, - /// just 0.. (2 * Int32.MaxValue) - 1 . - /// - /// - private double InternalSampleLargeRange() - { - double randomNumber; - - do - { - randomNumber = InternalSample(); - } while (randomNumber == int.MaxValue); - - randomNumber += int.MaxValue; - return randomNumber; + base.BeginProcessing(); } } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRandomCommandBase.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRandomCommandBase.cs new file mode 100644 index 00000000000..7d6e4e71e67 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRandomCommandBase.cs @@ -0,0 +1,719 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Management.Automation; +using System.Management.Automation.Runspaces; +using System.Numerics; +using System.Reflection; +using System.Security.Cryptography; +using System.Threading; + +using Debug = System.Management.Automation.Diagnostics; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// This class implements base class for `Get-Random` and `Get-SecureRandom` cmdlets. + /// + public class GetRandomCommandBase : PSCmdlet + { + #region Parameter set handling + + internal const string RandomNumberParameterSet = "RandomNumberParameterSet"; + private const string RandomListItemParameterSet = "RandomListItemParameterSet"; + private const string ShuffleParameterSet = "ShuffleParameterSet"; + + private static readonly object[] _nullInArray = new object[] { null }; + + private enum MyParameterSet + { + Unknown, + RandomNumber, + RandomListItem + } + + private MyParameterSet _effectiveParameterSet; + + private MyParameterSet EffectiveParameterSet + { + get + { + // cache MyParameterSet enum instead of doing string comparison every time + if (_effectiveParameterSet == MyParameterSet.Unknown) + { + if (MyInvocation.ExpectingInput && (Maximum == null) && (Minimum == null)) + { + _effectiveParameterSet = MyParameterSet.RandomListItem; + } + else if (ParameterSetName == GetRandomCommandBase.RandomListItemParameterSet + || ParameterSetName == GetRandomCommandBase.ShuffleParameterSet) + { + _effectiveParameterSet = MyParameterSet.RandomListItem; + } + else if (ParameterSetName.Equals(GetRandomCommandBase.RandomNumberParameterSet, StringComparison.OrdinalIgnoreCase)) + { + if ((Maximum != null) && Maximum.GetType().IsArray) + { + InputObject = (object[])Maximum; + _effectiveParameterSet = MyParameterSet.RandomListItem; + } + else + { + _effectiveParameterSet = MyParameterSet.RandomNumber; + } + } + else + { + Debug.Assert(false, "Unrecognized parameter set"); + } + } + + return _effectiveParameterSet; + } + } + + #endregion Parameter set handling + + #region Error handling + + private void ThrowMinGreaterThanOrEqualMax(object minValue, object maxValue) + { + if (minValue == null) + { + throw PSTraceSource.NewArgumentNullException("min"); + } + + if (maxValue == null) + { + throw PSTraceSource.NewArgumentNullException("max"); + } + + ErrorRecord errorRecord = new( + new ArgumentException(string.Format( + CultureInfo.InvariantCulture, GetRandomCommandStrings.MinGreaterThanOrEqualMax, minValue, maxValue)), + "MinGreaterThanOrEqualMax", + ErrorCategory.InvalidArgument, + null); + + ThrowTerminatingError(errorRecord); + } + + #endregion + + #region Random generator state + + private static readonly ReaderWriterLockSlim s_runspaceGeneratorMapLock = new(); + + // 1-to-1 mapping of cmdlet + runspacesId and random number generators + private static readonly Dictionary s_runspaceGeneratorMap = new(); + + private static void CurrentRunspace_StateChanged(object sender, RunspaceStateEventArgs e) + { + switch (e.RunspaceStateInfo.State) + { + case RunspaceState.Broken: + case RunspaceState.Closed: + try + { + GetRandomCommandBase.s_runspaceGeneratorMapLock.EnterWriteLock(); + GetRandomCommandBase.s_runspaceGeneratorMap.Remove(MethodBase.GetCurrentMethod().DeclaringType.Name + ((Runspace)sender).InstanceId.ToString()); + } + finally + { + GetRandomCommandBase.s_runspaceGeneratorMapLock.ExitWriteLock(); + } + + break; + } + } + + private PolymorphicRandomNumberGenerator _generator; + + /// + /// Gets and sets generator associated with the current cmdlet and runspace. + /// + internal PolymorphicRandomNumberGenerator Generator + { + get + { + if (_generator == null) + { + string runspaceId = Context.CurrentRunspace.InstanceId.ToString(); + + bool needToInitialize = false; + try + { + GetRandomCommandBase.s_runspaceGeneratorMapLock.EnterReadLock(); + needToInitialize = !GetRandomCommandBase.s_runspaceGeneratorMap.TryGetValue(this.GetType().Name + runspaceId, out _generator); + } + finally + { + GetRandomCommandBase.s_runspaceGeneratorMapLock.ExitReadLock(); + } + + if (needToInitialize) + { + Generator = new PolymorphicRandomNumberGenerator(); + } + } + + return _generator; + } + + set + { + _generator = value; + Runspace myRunspace = Context.CurrentRunspace; + + try + { + GetRandomCommandBase.s_runspaceGeneratorMapLock.EnterWriteLock(); + if (!GetRandomCommandBase.s_runspaceGeneratorMap.ContainsKey(this.GetType().Name + myRunspace.InstanceId.ToString())) + { + // make sure we won't leave the generator around after runspace exits + myRunspace.StateChanged += CurrentRunspace_StateChanged; + } + + GetRandomCommandBase.s_runspaceGeneratorMap[this.GetType().Name + myRunspace.InstanceId.ToString()] = _generator; + } + finally + { + GetRandomCommandBase.s_runspaceGeneratorMapLock.ExitWriteLock(); + } + } + } + + #endregion + + #region Parameters for RandomNumberParameterSet + + /// + /// Gets or sets the maximum number to generate. + /// + [Parameter(ParameterSetName = RandomNumberParameterSet, Position = 0)] + public object Maximum { get; set; } + + /// + /// Gets or sets the minimum number to generate. + /// + [Parameter(ParameterSetName = RandomNumberParameterSet)] + public object Minimum { get; set; } + + private static bool IsInt(object o) + { + if (o == null || o is int) + { + return true; + } + + return false; + } + + private static bool IsInt64(object o) + { + if (o == null || o is long) + { + return true; + } + + return false; + } + + private static object ProcessOperand(object o) + { + if (o == null) + { + return null; + } + + PSObject pso = PSObject.AsPSObject(o); + object baseObject = pso.BaseObject; + + if (baseObject is string) + { + // The type argument passed in does not decide the number type we want to convert to. ScanNumber will return + // int/long/double based on the string form number passed in. + baseObject = System.Management.Automation.Language.Parser.ScanNumber((string)baseObject, typeof(int)); + } + + return baseObject; + } + + private static double ConvertToDouble(object o, double defaultIfNull) + { + if (o == null) + { + return defaultIfNull; + } + + double result = (double)LanguagePrimitives.ConvertTo(o, typeof(double), CultureInfo.InvariantCulture); + return result; + } + + #endregion + + #region Parameters and variables for RandomListItemParameterSet + + private List _chosenListItems; + private int _numberOfProcessedListItems; + + /// + /// Gets or sets the list from which random elements are chosen. + /// + [Parameter(ParameterSetName = RandomListItemParameterSet, ValueFromPipeline = true, Position = 0, Mandatory = true)] + [Parameter(ParameterSetName = ShuffleParameterSet, ValueFromPipeline = true, Position = 0, Mandatory = true)] + [System.Management.Automation.AllowNull] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public object[] InputObject { get; set; } + + /// + /// Gets or sets the number of items to output (number of list items or of numbers). + /// + [Parameter(ParameterSetName = RandomNumberParameterSet)] + [Parameter(ParameterSetName = RandomListItemParameterSet)] + [ValidateRange(1, int.MaxValue)] + public int Count { get; set; } = 1; + + #endregion + + #region Shuffle parameter + + /// + /// Gets or sets whether the command should return all input objects in randomized order. + /// + [Parameter(ParameterSetName = ShuffleParameterSet, Mandatory = true)] + public SwitchParameter Shuffle { get; set; } + + #endregion + + #region Cmdlet processing methods + + private double GetRandomDouble(double minValue, double maxValue) + { + double randomNumber; + double diff = maxValue - minValue; + + // I couldn't find a better fix for bug #216893 then + // to test and retry if a random number falls outside the bounds + // because of floating-point-arithmetic inaccuracies. + // + // Performance in the normal case is not impacted much. + // In low-precision situations we should converge to a solution quickly + // (diff gets smaller at a quick pace). + if (double.IsInfinity(diff)) + { + do + { + double r = Generator.NextDouble(); + randomNumber = minValue + (r * maxValue) - (r * minValue); + } + while (randomNumber >= maxValue); + } + else + { + do + { + double r = Generator.NextDouble(); + randomNumber = minValue + (r * diff); + diff *= r; + } + while (randomNumber >= maxValue); + } + + return randomNumber; + } + + /// + /// Get a random Int64 type number. + /// + /// Minimum value. + /// Maximum value. + /// Rnadom long. + private long GetRandomInt64(long minValue, long maxValue) + { + // Randomly generate eight bytes and convert the byte array to UInt64 + var buffer = new byte[sizeof(ulong)]; + ulong randomUint64; + + BigInteger bigIntegerDiff = (BigInteger)maxValue - (BigInteger)minValue; + + // When the difference is less than int.MaxValue, use Random.Next(int, int) + if (bigIntegerDiff <= int.MaxValue) + { + int randomDiff = Generator.Next(0, (int)(maxValue - minValue)); + return minValue + randomDiff; + } + + // The difference of two Int64 numbers would not exceed UInt64.MaxValue, so it can be represented by a UInt64 number. + ulong uint64Diff = (ulong)bigIntegerDiff; + + // Calculate the number of bits to represent the diff in type UInt64 + int bitsToRepresentDiff = 0; + ulong diffCopy = uint64Diff; + for (; diffCopy != 0; bitsToRepresentDiff++) + { + diffCopy >>= 1; + } + + // Get the mask for the number of bits + ulong mask = 0xffffffffffffffff >> (64 - bitsToRepresentDiff); + do + { + // Randomly fill the buffer + Generator.NextBytes(buffer); + randomUint64 = BitConverter.ToUInt64(buffer, 0); + + // Get the last 'bitsToRepresentDiff' number of random bits + randomUint64 &= mask; + } while (uint64Diff <= randomUint64); + + double randomNumber = (minValue * 1.0) + (randomUint64 * 1.0); + return (long)randomNumber; + } + + /// + /// This method implements the BeginProcessing method for derived cmdlets. + /// + protected override void BeginProcessing() + { + if (EffectiveParameterSet == MyParameterSet.RandomNumber) + { + object maxOperand = ProcessOperand(Maximum); + object minOperand = ProcessOperand(Minimum); + + if (IsInt(maxOperand) && IsInt(minOperand)) + { + int minValue = minOperand != null ? (int)minOperand : 0; + int maxValue = maxOperand != null ? (int)maxOperand : int.MaxValue; + + if (minValue >= maxValue) + { + ThrowMinGreaterThanOrEqualMax(minValue, maxValue); + } + + for (int i = 0; i < Count; i++) + { + int randomNumber = Generator.Next(minValue, maxValue); + Debug.Assert(minValue <= randomNumber, "lower bound <= random number"); + Debug.Assert(randomNumber < maxValue, "random number < upper bound"); + + WriteObject(randomNumber); + } + } + else if ((IsInt64(maxOperand) || IsInt(maxOperand)) && (IsInt64(minOperand) || IsInt(minOperand))) + { + long minValue = minOperand != null ? ((minOperand is long) ? (long)minOperand : (int)minOperand) : 0; + long maxValue = maxOperand != null ? ((maxOperand is long) ? (long)maxOperand : (int)maxOperand) : long.MaxValue; + + if (minValue >= maxValue) + { + ThrowMinGreaterThanOrEqualMax(minValue, maxValue); + } + + for (int i = 0; i < Count; i++) + { + long randomNumber = GetRandomInt64(minValue, maxValue); + Debug.Assert(minValue <= randomNumber, "lower bound <= random number"); + Debug.Assert(randomNumber < maxValue, "random number < upper bound"); + + WriteObject(randomNumber); + } + } + else + { + double minValue = (minOperand is double) ? (double)minOperand : ConvertToDouble(Minimum, 0.0); + double maxValue = (maxOperand is double) ? (double)maxOperand : ConvertToDouble(Maximum, double.MaxValue); + + if (minValue >= maxValue) + { + ThrowMinGreaterThanOrEqualMax(minValue, maxValue); + } + + for (int i = 0; i < Count; i++) + { + double randomNumber = GetRandomDouble(minValue, maxValue); + Debug.Assert(minValue <= randomNumber, "lower bound <= random number"); + Debug.Assert(randomNumber < maxValue, "random number < upper bound"); + + WriteObject(randomNumber); + } + } + } + else if (EffectiveParameterSet == MyParameterSet.RandomListItem) + { + _chosenListItems = new List(); + _numberOfProcessedListItems = 0; + } + } + + // rough proof that when choosing random K items out of N items + // each item has got K/N probability of being included in the final list + // + // probability that a particular item in chosenListItems is NOT going to be replaced + // when processing I-th input item [assumes I > K]: + // P_one_step(I) = 1 - ((K / I) * ((K - 1) / K) + ((I - K) / I) = (I - 1) / I + // <--A--> <-----B-----> <-----C-----> + // A - probability that I-th element is going to be replacing an element from chosenListItems + // (see (1) in the code below) + // B - probability that a particular element from chosenListItems is NOT going to be replaced + // (see (2) in the code below) + // C - probability that I-th element is NOT going to be replacing an element from chosenListItems + // (see (1) in the code below) + // + // probability that a particular item in chosenListItems is NOT going to be replaced + // when processing input items J through N [assumes J > K] + // P_removal(J) = Multiply(for I = J to N) P(I) = + // = ((J - 1) / J) * (J / (J + 1)) * ... * ((N - 2) / (N - 1)) * ((N - 1) / N) = + // = (J - 1) / N + // + // probability that when processing an element it is going to be put into chosenListItems + // P_insertion(I) = 1.0 when I <= K - see (3) in the code below + // P_insertion(I) = K/N otherwise - see (1) in the code below + // + // probability that a given element is going to be a part of the final list + // P_final(I) = P_insertion(I) * P_removal(max(I + 1, K + 1)) + // [for I <= K] = 1.0 * ((K + 1) - 1) / N = K / N + // [otherwise] = (K / I) * ((I + 1) - 1) / N = K / N + // + // which proves that P_final(I) = K / N for all values of I. QED. + + /// + /// This method implements the ProcessRecord method for derived cmdlets. + /// + protected override void ProcessRecord() + { + if (EffectiveParameterSet == MyParameterSet.RandomListItem) + { + if (ParameterSetName == ShuffleParameterSet) + { + // this allows for $null to be in an array passed to InputObject + foreach (object item in InputObject ?? _nullInArray) + { + _chosenListItems.Add(item); + } + } + else + { + foreach (object item in InputObject ?? _nullInArray) + { + // (3) + if (_numberOfProcessedListItems < Count) + { + Debug.Assert(_chosenListItems.Count == _numberOfProcessedListItems, "Initial K elements should all be included in chosenListItems"); + _chosenListItems.Add(item); + } + else + { + Debug.Assert(_chosenListItems.Count == Count, "After processing K initial elements, the length of chosenItems should stay equal to K"); + + // (1) + if (Generator.Next(_numberOfProcessedListItems + 1) < Count) + { + // (2) + int indexToReplace = Generator.Next(_chosenListItems.Count); + _chosenListItems[indexToReplace] = item; + } + } + + _numberOfProcessedListItems++; + } + } + } + } + + /// + /// This method implements the EndProcessing method for derived cmdlets. + /// + protected override void EndProcessing() + { + if (EffectiveParameterSet == MyParameterSet.RandomListItem) + { + // make sure the order is truly random + // (all permutations with the same probability) + // O(n) time + int n = _chosenListItems.Count; + for (int i = 0; i < n; i++) + { + // randomly choose j from [i...n) + int j = Generator.Next(i, n); + + WriteObject(_chosenListItems[j]); + + // remove the output object from consideration in the next iteration. + if (i != j) + { + _chosenListItems[j] = _chosenListItems[i]; + } + } + } + } + + #endregion Processing methods + } + + /// + /// Provides an adapter API for random numbers that may be either cryptographically random, or + /// generated with the regular pseudo-random number generator. Re-implementations of + /// methods using the NextBytes() primitive based on the CLR implementation: + /// https://referencesource.microsoft.com/#mscorlib/system/random.cs. + /// + internal class PolymorphicRandomNumberGenerator + { + /// + /// Initializes a new instance of the class. + /// + public PolymorphicRandomNumberGenerator() + { + _cryptographicGenerator = RandomNumberGenerator.Create(); + _pseudoGenerator = null; + } + + /// + /// Initializes a new instance of the using pseudorandom generator instead of the cryptographic one. + /// + /// The seed value. + internal PolymorphicRandomNumberGenerator(int seed) + { + _cryptographicGenerator = null; + _pseudoGenerator = new Random(seed); + } + + private readonly Random _pseudoGenerator = null; + private readonly RandomNumberGenerator _cryptographicGenerator = null; + + /// + /// Generates a random floating-point number that is greater than or equal to 0.0, and less than 1.0. + /// + /// A random floating-point number that is greater than or equal to 0.0, and less than 1.0. + internal double NextDouble() + { + // According to the CLR source: + // "Including this division at the end gives us significantly improved random number distribution." + return Next() * (1.0 / int.MaxValue); + } + + /// + /// Generates a non-negative random integer. + /// + /// A non-negative random integer. + internal int Next() + { + int randomNumber; + + // The CLR implementation just fudges + // Int32.MaxValue down to (Int32.MaxValue - 1). This implementation + // errs on the side of correctness. + do + { + randomNumber = InternalSample(); + } + while (randomNumber == int.MaxValue); + + if (randomNumber < 0) + { + randomNumber += int.MaxValue; + } + + return randomNumber; + } + + /// + /// Returns a random integer that is within a specified range. + /// + /// The exclusive upper bound of the random number returned. + /// Next random integer. + internal int Next(int maxValue) + { + if (maxValue < 0) + { + throw new ArgumentOutOfRangeException(nameof(maxValue), GetRandomCommandStrings.MaxMustBeGreaterThanZeroApi); + } + + return Next(0, maxValue); + } + + /// + /// Returns a random integer that is within a specified range. + /// + /// The inclusive lower bound of the random number returned. + /// The exclusive upper bound of the random number returned. maxValue must be greater than or equal to minValue. + /// Next random integer. + public int Next(int minValue, int maxValue) + { + if (minValue > maxValue) + { + throw new ArgumentOutOfRangeException(nameof(minValue), GetRandomCommandStrings.MinGreaterThanOrEqualMaxApi); + } + + int randomNumber = 0; + + long range = (long)maxValue - (long)minValue; + if (range <= int.MaxValue) + { + randomNumber = (int)(NextDouble() * range) + minValue; + } + else + { + double largeSample = InternalSampleLargeRange() * (1.0 / (2 * ((uint)int.MaxValue))); + randomNumber = (int)((long)(largeSample * range) + minValue); + } + + return randomNumber; + } + + /// + /// Fills the elements of a specified array of bytes with random numbers. + /// + /// The array to be filled. + internal void NextBytes(byte[] buffer) + { + if (_cryptographicGenerator != null) + { + _cryptographicGenerator.GetBytes(buffer); + } + else + { + _pseudoGenerator.NextBytes(buffer); + } + } + + /// + /// Samples a random integer. + /// + /// A random integer, using the full range of Int32. + private int InternalSample() + { + int randomNumber; + byte[] data = new byte[sizeof(int)]; + + NextBytes(data); + randomNumber = BitConverter.ToInt32(data, 0); + + return randomNumber; + } + + /// + /// Samples a random int when the range is large. This does + /// not need to be in the range of -Double.MaxValue .. Double.MaxValue, + /// just 0.. (2 * Int32.MaxValue) - 1 . + /// + /// A random double. + private double InternalSampleLargeRange() + { + double randomNumber; + + do + { + randomNumber = InternalSample(); + } + while (randomNumber == int.MaxValue); + + randomNumber += int.MaxValue; + return randomNumber; + } + } +} diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetSecureRandomCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetSecureRandomCommand.cs new file mode 100644 index 00000000000..e0ea7e68dbf --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetSecureRandomCommand.cs @@ -0,0 +1,18 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Management.Automation; + +namespace Microsoft.PowerShell.Commands +{ + /// + /// This class implements `Get-SecureRandom` cmdlet. + /// + [Cmdlet(VerbsCommon.Get, "SecureRandom", DefaultParameterSetName = GetRandomCommandBase.RandomNumberParameterSet, + HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2235055", RemotingCapability = RemotingCapability.None)] + [OutputType(typeof(int), typeof(long), typeof(double))] + public sealed class GetSecureRandomCommand : GetRandomCommandBase + { + // nothing unique from base class + } +} diff --git a/src/Modules/Unix/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1 b/src/Modules/Unix/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1 index 5761b3c745a..b17465abc5c 100644 --- a/src/Modules/Unix/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1 +++ b/src/Modules/Unix/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1 @@ -19,7 +19,7 @@ CmdletsToExport = @( 'New-Object', 'Select-Object', 'Sort-Object', 'Tee-Object', 'Register-ObjectEvent', 'Write-Output', 'Import-PowerShellDataFile', 'Write-Progress', 'Disable-PSBreakpoint', 'Enable-PSBreakpoint', 'Get-PSBreakpoint', 'Remove-PSBreakpoint', 'Set-PSBreakpoint', 'Get-PSCallStack', 'Export-PSSession', - 'Import-PSSession', 'Get-Random', 'Invoke-RestMethod', 'Debug-Runspace', 'Get-Runspace', + 'Import-PSSession', 'Get-Random', 'Get-SecureRandom', 'Invoke-RestMethod', 'Debug-Runspace', 'Get-Runspace', 'Disable-RunspaceDebug', 'Enable-RunspaceDebug', 'Get-RunspaceDebug', 'Start-Sleep', 'Join-String', 'Out-String', 'Select-String', 'ConvertFrom-StringData', 'Format-Table', 'New-TemporaryFile', 'New-TimeSpan', 'Get-TraceSource', 'Set-TraceSource', 'Add-Type', 'Get-TypeData', 'Remove-TypeData', 'Update-TypeData', diff --git a/src/Modules/Windows/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1 b/src/Modules/Windows/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1 index 7d0e7a91e11..396ed51a8fb 100644 --- a/src/Modules/Windows/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1 +++ b/src/Modules/Windows/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1 @@ -17,7 +17,7 @@ CmdletsToExport = @( 'Show-Markdown', 'Get-MarkdownOption', 'Set-MarkdownOption', 'Add-Member', 'Get-Member', 'Compare-Object', 'Group-Object', 'Measure-Object', 'New-Object', 'Select-Object', 'Sort-Object', 'Tee-Object', 'Register-ObjectEvent', 'Write-Output', 'Import-PowerShellDataFile', 'Write-Progress', 'Disable-PSBreakpoint', 'Enable-PSBreakpoint', 'Get-PSBreakpoint', - 'Remove-PSBreakpoint', 'Set-PSBreakpoint', 'Get-PSCallStack', 'Export-PSSession', 'Import-PSSession', 'Get-Random', + 'Remove-PSBreakpoint', 'Set-PSBreakpoint', 'Get-PSCallStack', 'Export-PSSession', 'Import-PSSession', 'Get-Random', 'Get-SecureRandom' 'Invoke-RestMethod', 'Debug-Runspace', 'Get-Runspace', 'Disable-RunspaceDebug', 'Enable-RunspaceDebug', 'Get-RunspaceDebug', 'ConvertFrom-SddlString', 'Start-Sleep', 'Join-String', 'Out-String', 'Select-String', 'ConvertFrom-StringData', 'Format-Table', 'New-TemporaryFile', 'New-TimeSpan', 'Get-TraceSource', 'Set-TraceSource', diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-SecureRandom.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-SecureRandom.Tests.ps1 new file mode 100644 index 00000000000..acc560abdb3 --- /dev/null +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-SecureRandom.Tests.ps1 @@ -0,0 +1,183 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +Describe "Get-SecureRandom DRT Unit Tests" -Tags "CI" { + $testData = @( + @{ Name = 'no params'; Maximum = $null; Minimum = $null; GreaterThan = -1; LessThan = ([int32]::MaxValue); Type = 'System.Int32' } + @{ Name = 'only positive maximum number'; Maximum = 100; Minimum = $null; GreaterThan = -1; LessThan = 100; Type = 'System.Int32' } + @{ Name = 'maximum set to 0, Minimum to a negative number'; Maximum = 0; Minimum = -100; GreaterThan = -101; LessThan = 0; Type = 'System.Int32' } + @{ Name = 'positive maximum, negative Minimum'; Maximum = 100; Minimum = -100; GreaterThan = -101; LessThan = 100; Type = 'System.Int32' } + @{ Name = 'both negative'; Maximum = -100; Minimum = -200; GreaterThan = -201; LessThan = -100; Type = 'System.Int32' } + @{ Name = 'both negative with parentheses'; Maximum = (-100); Minimum = (-200); GreaterThan = -201; LessThan = -100; Type = 'System.Int32' } + @{ Name = 'maximum enclosed in quote'; Maximum = '8'; Minimum = 5; GreaterThan = 4; LessThan = 8; Type = 'System.Int32' } + @{ Name = 'minimum enclosed in quote'; Maximum = 8; Minimum = '5'; GreaterThan = 4; LessThan = 8; Type = 'System.Int32' } + @{ Name = 'maximum with plus sign'; Maximum = +100; Minimum = 0; GreaterThan = -1; LessThan = 100; Type = 'System.Int32' } + @{ Name = 'maximum with plus sign and quote'; Maximum = '+100'; Minimum = 0; GreaterThan = -1; LessThan = 100; Type = 'System.Int32' } + @{ Name = 'both with quote'; Maximum = '+100'; Minimum = '-100'; GreaterThan = -101; LessThan = 100; Type = 'System.Int32' } + @{ Name = 'maximum set to kb'; Maximum = '1kb'; Minimum = 0; GreaterThan = -1; LessThan = 1024; Type = 'System.Int32' } + @{ Name = 'maximum is Int64.MaxValue'; Maximum = ([int64]::MaxValue); Minimum = $null; GreaterThan = ([int64]-1); LessThan = ([int64]::MaxValue); Type = 'System.Int64' } + @{ Name = 'maximum is a 64-bit integer'; Maximum = ([int64]100); Minimum = $null; GreaterThan = ([int64]-1); LessThan = ([int64]100); Type = 'System.Int64' } + @{ Name = 'maximum set to a large integer greater than int32.MaxValue'; Maximum = 100000000000; Minimum = $null; GreaterThan = ([int64]-1); LessThan = ([int64]100000000000); Type = 'System.Int64' } + @{ Name = 'maximum set to 0, Minimum set to a negative 64-bit integer'; Maximum = ([int64]0); Minimum = ([int64]-100); GreaterThan = ([int64]-101); LessThan = ([int64]0); Type = 'System.Int64' } + @{ Name = 'maximum set to positive 64-bit number, min set to negative 64-bit number'; Maximum = ([int64]100); Minimum = ([int64]-100); GreaterThan = ([int64]-101); LessThan = ([int64]100); Type = 'System.Int64' } + @{ Name = 'both are negative 64-bit number'; Maximum = ([int64]-100); Minimum = ([int64]-200); GreaterThan = ([int64]-201); LessThan = ([int64]-100); Type = 'System.Int64' } + @{ Name = 'both are negative 64-bit number with parentheses'; Maximum = ([int64](-100)); Minimum = ([int64](-200)); GreaterThan = ([int64]-201); LessThan = ([int64]-100); Type = 'System.Int64' } + @{ Name = 'max is 32-bit, min is 64-bit integer'; Maximum = '8'; Minimum = ([int64]5); GreaterThan = ([int64]4); LessThan = ([int64]8); Type = 'System.Int64' } + @{ Name = 'max is 64-bit, min is 32-bit integer'; Maximum = ([int64]8); Minimum = '5'; GreaterThan = ([int64]4); LessThan = ([int64]8); Type = 'System.Int64' } + @{ Name = 'max set to a 32-bit integer, min set to [int64]0'; Maximum = +100; Minimum = ([int64]0); GreaterThan = ([int64]-1); LessThan = ([int64]100); Type = 'System.Int64' } + @{ Name = 'max set to a 32-bit integer with quote'; Maximum = '+100'; Minimum = ([int64]0); GreaterThan = ([int64]-1); LessThan = ([int64]100); Type = 'System.Int64' } + @{ Name = 'max is [int64]0, min is a 32-bit integer'; Maximum = ([int64]0); Minimum = '-100'; GreaterThan = ([int64]-101); LessThan = ([int64]0); Type = 'System.Int64' } + @{ Name = 'min set to 1MB, max set to a 64-bit integer greater than min'; Maximum = ([int64]1048585); Minimum = '1mb'; GreaterThan = ([int64]1048575); LessThan = ([int64]1048585); Type = 'System.Int64' } + @{ Name = 'max set to 1tb, min set to 10 mb'; Maximum = '1tb'; Minimum = '10mb'; GreaterThan = ([int64]10485759); LessThan = ([int64]1099511627776); Type = 'System.Int64' } + @{ Name = 'max is int64.MaxValue, min is Int64.MinValue'; Maximum = ([int64]::MaxValue); Minimum = ([int64]::MinValue); GreaterThan = ([int64]::MinValue); LessThan = ([int64]::MaxValue); Type = 'System.Int64' } + @{ Name = 'both are int64.MaxValue plus a 32-bit integer'; Maximum = ([int64](([int]::MaxValue)+15)); Minimum = ([int64](([int]::MaxValue)+10)); GreaterThan = ([int64](([int]::MaxValue)+9)); LessThan = ([int64](([int]::MaxValue)+15)); Type = 'System.Int64' } + @{ Name = 'both are greater than int32.MaxValue without specified type, and max with quote'; Maximum = '100099000001'; Minimum = 100000000001; GreaterThan = ([int64]10000000000); LessThan = ([int64]100099000001); Type = 'System.Int64' } + @{ Name = 'both are greater than int32.MaxValue without specified type, and min with quote'; Maximum = 100000002230; Minimum = '100000002222'; GreaterThan = ([int64]100000002221); LessThan = ([int64]100000002230); Type = 'System.Int64' } + @{ Name = 'max is greater than int32.MaxValue without specified type'; Maximum = 90000000000; Minimum = 4; GreaterThan = ([int64]3); LessThan = ([int64]90000000000); Type = 'System.Int64' } + @{ Name = 'max is a double-precision number'; Maximum = 100.0; Minimum = $null; GreaterThan = -1.0; LessThan = 100.0; Type = 'System.Double' } + @{ Name = 'both are double-precision numbers, min is negative.'; Maximum = 0.0; Minimum = -100.0; GreaterThan = -101.0; LessThan = 0.0; Type = 'System.Double' } + @{ Name = 'both are double-precision number, max is positive, min is negative.'; Maximum = 100.0; Minimum = -100.0; GreaterThan = -101.0; LessThan = 100.0; Type = 'System.Double' } + @{ Name = 'max is a double-precision number, min is int32'; Maximum = 8.0; Minimum = 5; GreaterThan = 4.0; LessThan = 8.0; Type = 'System.Double' } + @{ Name = 'min is a double-precision number, max is int32'; Maximum = 8; Minimum = 5.0; GreaterThan = 4.0; LessThan = 8.0; Type = 'System.Double' } + @{ Name = 'max set to a special double number'; Maximum = 20.; Minimum = 0.0; GreaterThan = -1.0; LessThan = 20.0; Type = 'System.Double' } + @{ Name = 'max is double with quote'; Maximum = '20.'; Minimum = 0.0; GreaterThan = -1.0; LessThan = 20.0; Type = 'System.Double' } + @{ Name = 'max is double with plus sign'; Maximum = +100.0; Minimum = 0; GreaterThan = -1.0; LessThan = 100.0; Type = 'System.Double' } + @{ Name = 'max is double with plus sign and enclosed in quote'; Maximum = '+100.0'; Minimum = 0; GreaterThan = -1.0; LessThan = 100.0; Type = 'System.Double' } + @{ Name = 'both set to the special numbers as 1.0e+xx '; Maximum = $null; Minimum = 1.0e+100; GreaterThan = 1.0e+99; LessThan = ([double]::MaxValue); Type = 'System.Double' } + @{ Name = 'max is Double.MaxValue, min is Double.MinValue'; Maximum = ([double]::MaxValue); Minimum = ([double]::MinValue); GreaterThan = ([double]::MinValue); LessThan = ([double]::MaxValue); Type = 'System.Double' } + ) + + $testDataForError = @( + @{ Name = 'Min is greater than max and all are positive 32-bit integer'; Maximum = 10; Minimum = 20} + @{ Name = 'Min and Max are same and all are positive 32-bit integer'; Maximum = 20; Minimum = 20} + @{ Name = 'Min is greater than max and all are negative 32-bit integer'; Maximum = -20; Minimum = -10} + @{ Name = 'Min and Max are same and all are negative 32-bit integer'; Maximum = -20; Minimum = -20} + @{ Name = 'Min is greater than max and all are positive double-precision number'; Maximum = 10.0; Minimum = 20.0} + @{ Name = 'Min and Max are same and all are positive double-precision number'; Maximum = 20.0; Minimum = 20.0} + @{ Name = 'Min is greater than max and all are negative double-precision number'; Maximum = -20.0; Minimum = -10.0} + @{ Name = 'Min and Max are same and all are negative double-precision number'; Maximum = -20.0; Minimum = -20.0} + @{ Name = 'Max is a negative number, min is the default number '; Maximum = -10; Minimum = $null} + ) + + # minimum is always set to the actual low end of the range, details refer to closed issue #887. + It "Should return a correct random number for ''" -TestCases $testData { + param($maximum, $minimum, $greaterThan, $lessThan, $type) + + $result = Get-SecureRandom -Maximum $maximum -Minimum $minimum + $result | Should -BeGreaterThan $greaterThan + $result | Should -BeLessThan $lessThan + $result | Should -BeOfType $type + } + + It "Should return correct random numbers for '' with Count specified" -TestCases $testData { + param($maximum, $minimum, $greaterThan, $lessThan, $type) + + $result = Get-SecureRandom -Maximum $maximum -Minimum $minimum -Count 1 + $result | Should -BeGreaterThan $greaterThan + $result | Should -BeLessThan $lessThan + $result | Should -BeOfType $type + + $result = Get-SecureRandom -Maximum $maximum -Minimum $minimum -Count 3 + foreach ($randomNumber in $result) { + $randomNumber | Should -BeGreaterThan $greaterThan + $randomNumber | Should -BeLessThan $lessThan + $randomNumber | Should -BeOfType $type + } + } + + It "Should be able to throw error when ''" -TestCases $testDataForError { + param($maximum, $minimum) + { Get-SecureRandom -Minimum $minimum -Maximum $maximum } | Should -Throw -ErrorId "MinGreaterThanOrEqualMax,Microsoft.PowerShell.Commands.GetSecureRandomCommand" + } +} + +Describe "Get-SecureRandom" -Tags "CI" { + It "Should return a random number greater than -1" { + Get-SecureRandom | Should -BeGreaterThan -1 + } + + It "Should return a random number less than 100" { + Get-SecureRandom -Maximum 100 | Should -BeLessThan 100 + Get-SecureRandom -Maximum 100 | Should -BeGreaterThan -1 + } + + It "Should return a random number less than 100 and greater than -100 " { + $randomNumber = Get-SecureRandom -Minimum -100 -Maximum 100 + $randomNumber | Should -BeLessThan 100 + $randomNumber | Should -BeGreaterThan -101 + } + + It "Should return a random number less than 20.93 and greater than 10.7 " { + $randomNumber = Get-SecureRandom -Minimum 10.7 -Maximum 20.93 + $randomNumber | Should -BeLessThan 20.93 + $randomNumber | Should -BeGreaterThan 10.7 + } + + It "Should return a number from 1,2,3,5,8,13 " { + $randomNumber = Get-SecureRandom -InputObject 1, 2, 3, 5, 8, 13 + $randomNumber | Should -BeIn 1, 2, 3, 5, 8, 13 + } + + It "Should return an array " { + $randomNumber = Get-SecureRandom -InputObject 1, 2, 3, 5, 8, 13 -Count 3 + $randomNumber.Count | Should -Be 3 + ,$randomNumber | Should -BeOfType System.Array + } + + It "Should return three random numbers for array of 1,2,3,5,8,13 " { + $randomNumber = Get-SecureRandom -InputObject 1, 2, 3, 5, 8, 13 -Count 3 + $randomNumber.Count | Should -Be 3 + $randomNumber[0] | Should -BeIn 1, 2, 3, 5, 8, 13 + $randomNumber[1] | Should -BeIn 1, 2, 3, 5, 8, 13 + $randomNumber[2] | Should -BeIn 1, 2, 3, 5, 8, 13 + $randomNumber[3] | Should -BeNullOrEmpty + } + + It "Should return all the numbers for array of 1,2,3,5,8,13 in no particular order" { + $randomNumber = Get-SecureRandom -InputObject 1, 2, 3, 5, 8, 13 -Count ([int]::MaxValue) + $randomNumber.Count | Should -Be 6 + $randomNumber[0] | Should -BeIn 1, 2, 3, 5, 8, 13 + $randomNumber[1] | Should -BeIn 1, 2, 3, 5, 8, 13 + $randomNumber[2] | Should -BeIn 1, 2, 3, 5, 8, 13 + $randomNumber[3] | Should -BeIn 1, 2, 3, 5, 8, 13 + $randomNumber[4] | Should -BeIn 1, 2, 3, 5, 8, 13 + $randomNumber[5] | Should -BeIn 1, 2, 3, 5, 8, 13 + $randomNumber[6] | Should -BeNullOrEmpty + } + + It "Should return all the numbers for array of 1,2,3,5,8,13 in randomized order when the Shuffle switch is used" { + $randomNumber = Get-SecureRandom -InputObject 1, 2, 3, 5, 8, 13 -Shuffle + $randomNumber.Count | Should -Be 6 + $randomNumber | Should -BeIn 1, 2, 3, 5, 8, 13 + } + + It "Should return for a string collection " { + $randomNumber = Get-SecureRandom -InputObject "red", "yellow", "blue" + $randomNumber | Should -Be ("red" -or "yellow" -or "blue") + } + + It "Should return a number for hexadecimal " { + $randomNumber = Get-SecureRandom 0x07FFFFFFFFF + $randomNumber | Should -BeLessThan 549755813887 + $randomNumber | Should -BeGreaterThan 0 + } + + It "Should throw an error because the hexadecimal number is to large " { + { Get-SecureRandom 0x07FFFFFFFFFFFFFFFF } | Should -Throw "Value was either too large or too small for a UInt32" + } + + It "Should accept collection containing empty string for -InputObject" { + 1..10 | ForEach-Object { + Get-SecureRandom -InputObject @('a','b','') | Should -BeIn 'a','b','' + } + } + + It "Should accept `$null in collection for -InputObject" { + 1..10 | ForEach-Object { + Get-SecureRandom -InputObject @('a','b',$null) | Should -BeIn 'a','b',$null + } + } + + It 'Should not have a -SetSeed parameter' { + (Get-Command Get-SecureRandom).Parameters['SetSeed'] | Should -BeNullOrEmpty + } +} diff --git a/test/powershell/engine/Basic/DefaultCommands.Tests.ps1 b/test/powershell/engine/Basic/DefaultCommands.Tests.ps1 index 27be013ec6b..193b16cf2cb 100644 --- a/test/powershell/engine/Basic/DefaultCommands.Tests.ps1 +++ b/test/powershell/engine/Basic/DefaultCommands.Tests.ps1 @@ -333,6 +333,7 @@ Describe "Verify aliases and cmdlets" -Tags "CI" { "Cmdlet", "Get-Random", "", $($FullCLR -or $CoreWindows -or $CoreUnix), "", "", "None" "Cmdlet", "Get-Runspace", "", $($FullCLR -or $CoreWindows -or $CoreUnix), "", "", "None" "Cmdlet", "Get-RunspaceDebug", "", $($FullCLR -or $CoreWindows -or $CoreUnix), "", "", "None" +"Cmdlet", "Get-SecureRandom", "", $( $CoreWindows -or $CoreUnix), "", "", "None" "Cmdlet", "Get-Service", "", $($FullCLR -or $CoreWindows ), "", "", "None" "Cmdlet", "Get-TimeZone", "", $($FullCLR -or $CoreWindows -or $CoreUnix), "", "", "None" "Cmdlet", "Get-TraceSource", "", $($FullCLR -or $CoreWindows -or $CoreUnix), "", "", "None" From 81351678270c72985e05ebedf6e404416fba8c6d Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Tue, 2 May 2023 13:04:30 -0700 Subject: [PATCH 513/779] Fix constructing PSModulePath if a sub-path has trailing separator (#13147) * Fix constructing PSModulePath if a sub-path has trailing separator * skip test on Linux * Removed test as the system env var needs to be modified to repro * Add test * Fix test by comparing against incorrectly created path * Update test to be cross platform --- .../engine/Modules/ModuleIntrinsics.cs | 24 +++++++++---------- .../engine/Module/ModulePath.Tests.ps1 | 14 +++++++++++ 2 files changed, 26 insertions(+), 12 deletions(-) diff --git a/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs b/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs index e8b76de4837..cab7ed6c083 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs @@ -1139,7 +1139,7 @@ private static string AddToPath(string basePath, string pathToAdd, int insertPos int position = PathContainsSubstring(result.ToString(), subPathToAdd); // searching in effective 'result' value ensures that possible duplicates in pathsToAdd are handled correctly if (position == -1) // subPathToAdd not found - add it { - if (insertPosition == -1) // append subPathToAdd to the end + if (insertPosition == -1 || insertPosition > basePath.Length) // append subPathToAdd to the end { bool endsWithPathSeparator = false; if (result.Length > 0) @@ -1223,23 +1223,23 @@ public static string GetModulePath(string currentProcessModulePath, string hklmM // personalModulePath // sharedModulePath // systemModulePath - int insertIndex = 0; - if (!string.IsNullOrEmpty(personalModulePathToUse)) + currentProcessModulePath = AddToPath(currentProcessModulePath, personalModulePathToUse, 0); + int insertIndex = currentProcessModulePath.IndexOf(Path.PathSeparator, PathContainsSubstring(currentProcessModulePath, personalModulePathToUse)); + if (insertIndex != -1) { - currentProcessModulePath = AddToPath(currentProcessModulePath, personalModulePathToUse, insertIndex); - insertIndex = PathContainsSubstring(currentProcessModulePath, personalModulePathToUse) + personalModulePathToUse.Length + 1; + // advance past the path separator + insertIndex++; } - if (!string.IsNullOrEmpty(sharedModulePath)) + currentProcessModulePath = AddToPath(currentProcessModulePath, sharedModulePath, insertIndex); + insertIndex = currentProcessModulePath.IndexOf(Path.PathSeparator, PathContainsSubstring(currentProcessModulePath, sharedModulePath)); + if (insertIndex != -1) { - currentProcessModulePath = AddToPath(currentProcessModulePath, sharedModulePath, insertIndex); - insertIndex = PathContainsSubstring(currentProcessModulePath, sharedModulePath) + sharedModulePath.Length + 1; + // advance past the path separator + insertIndex++; } - if (!string.IsNullOrEmpty(systemModulePathToUse)) - { - currentProcessModulePath = AddToPath(currentProcessModulePath, systemModulePathToUse, insertIndex); - } + currentProcessModulePath = AddToPath(currentProcessModulePath, systemModulePathToUse, insertIndex); } return currentProcessModulePath; diff --git a/test/powershell/engine/Module/ModulePath.Tests.ps1 b/test/powershell/engine/Module/ModulePath.Tests.ps1 index b4dd5add437..a18b4fc3ffa 100644 --- a/test/powershell/engine/Module/ModulePath.Tests.ps1 +++ b/test/powershell/engine/Module/ModulePath.Tests.ps1 @@ -187,4 +187,18 @@ Describe "SxS Module Path Basic Tests" -tags "CI" { Remove-Item -Path $userConfigPath -Force } } + + It 'User PSModulePath has trailing separator' { + if ($IsWindows) { + $validation = "*\$env:SystemDrive\*" + } + else { + $validation = "*//*" + } + + $newUserPath = Join-Path $expectedUserPath ([System.IO.Path]::DirectorySeparatorChar) + $env:PSModulePath = $env:PSModulePath.Replace($expectedUserPath, $newUserPath).Replace($expectedSharedPath,"") + $out = & $powershell -noprofile -command '$env:PSModulePath' + $out.Split([System.IO.Path]::PathSeparator, [System.StringSplitOptions]::RemoveEmptyEntries) | Should -Not -BeLike $validation + } } From 07e041fe10d4c753dfccfa46008bdedebdfd3027 Mon Sep 17 00:00:00 2001 From: Armaan Mcleod Date: Wed, 3 May 2023 06:07:32 +1000 Subject: [PATCH 514/779] Allow combining of `-Skip` and `-SkipLast` parameters in `Select-Object` cmdlet. (#18849) * Added SkipLast parameter set to Skip parameter and updated tests * Using Should -BeExactly with string * Update test/powershell/Modules/Microsoft.PowerShell.Utility/Select-Object.Tests.ps1 --------- Co-authored-by: Travis Plunk Co-authored-by: Travis Plunk --- .../commands/utility/Select-Object.cs | 3 ++- .../Select-Object.Tests.ps1 | 23 +++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Select-Object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Select-Object.cs index b54873067ef..1c45fea699d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Select-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Select-Object.cs @@ -144,10 +144,11 @@ public int First private bool _firstOrLastSpecified; /// - /// Skips the specified number of items from top when used with First, from end when used with Last. + /// Skips the specified number of items from top when used with First, from end when used with Last or SkipLast. /// /// [Parameter(ParameterSetName = "DefaultParameter")] + [Parameter(ParameterSetName = "SkipLastParameter")] [ValidateRange(0, int.MaxValue)] public int Skip { get; set; } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Select-Object.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Select-Object.Tests.ps1 index 05885698392..04284453435 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Select-Object.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Select-Object.Tests.ps1 @@ -231,6 +231,29 @@ Describe "Select-Object DRT basic functionality" -Tags "CI" { $results[1] | Should -Be 3 } + It "Select-Object with SkipLast should work" { + $results = "1", "2", "3" | Select-Object -SkipLast 1 + $results.Count | Should -Be 2 + $results[0] | Should -BeExactly "1" + $results[1] | Should -BeExactly "2" + } + + It "Select-Object with Skip and SkipLast should work" { + $results = "1", "2", "3" | Select-Object -Skip 1 -SkipLast 1 + $results.Count | Should -Be 1 + $results[0] | Should -BeExactly "2" + } + + It "Select-Object with Skip and SkipLast should work with Skip overlapping SkipLast" { + $results = "1", "2" | Select-Object -Skip 2 -SkipLast 1 + $results. Count | Should -Be 0 + } + + It "Select-Object with Skip and SkipLast should work with skiplast overlapping skip" { + $results = "1", "2" | Select-Object -Skip 1 -SkipLast 2 + $results. Count | Should -Be 0 + } + It "Select-Object with Index should work" { $results = "1", "2", "3" | Select-Object -Index 2 $results.Count | Should -Be 1 From aa9a88fc331c801b9e13852129e6f06fc9ef956d Mon Sep 17 00:00:00 2001 From: PowerShell Team Bot <69177312+pwshBot@users.noreply.github.com> Date: Wed, 3 May 2023 14:36:06 -0700 Subject: [PATCH 515/779] Update to the latest NOTICES file (#19605) --- ThirdPartyNotices.txt | 48 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/ThirdPartyNotices.txt b/ThirdPartyNotices.txt index b36884e6c8a..2740296acca 100644 --- a/ThirdPartyNotices.txt +++ b/ThirdPartyNotices.txt @@ -2713,6 +2713,54 @@ SOFTWARE. System.Management 7.0.1 - MIT +(c) Microsoft Corporation +Copyright (c) Andrew Arnott +Copyright 2019 LLVM Project +Copyright 2018 Daniel Lemire +Copyright (c) .NET Foundation +Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson +Copyright (c) 1998 Microsoft. To +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2005-2020 Rich Felker +Copyright (c) Microsoft Corporation +Copyright (c) 2007 James Newton-King +Copyright (c) 2012-2014, Yann Collet +Copyright (c) 1991-2022 Unicode, Inc. +Copyright (c) 2013-2017, Alfred Klomp +Copyright 2012 the V8 project authors +Copyright (c) 1999 Lucent Technologies +Copyright (c) 2008-2016, Wojciech Mula +Copyright (c) 2011-2020 Microsoft Corp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2021 csFastFloat authors +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors +Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 +Portions (c) International Organization +Copyright (c) 2004-2006 Intel Corporation +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) +Copyright (c) .NET Foundation Contributors +Copyright (c) 2020 Mara Bos +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2008-2020 Advanced Micro Devices, Inc. +Copyright (c) 2019 Microsoft Corporation, Daan Leijen +Copyright (c) 2011 Novell, Inc (http://www.novell.com) +Copyright (c) 1995-2022 Jean-loup Gailly and Mark Adler +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors +Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright (c) 1980, 1986, 1993 The Regents of the University of California +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass. To The MIT License (MIT) From 1b248efb3f2f8a82e35c7f095ced799623379fff Mon Sep 17 00:00:00 2001 From: Greg Dennis Date: Thu, 4 May 2023 15:19:32 +1200 Subject: [PATCH 516/779] Test-Json: Use JsonSchema.Net (System.Text.Json) instead of NJsonSchema (Newtonsoft.Json) (#18141) Updates the Test-Json cmdlet to use JsonSchema.Net instead of NJsonSchema in order to: - use System.Text.Json instead of Newtonsoft - support the latest JSON Schema drafts (up to 2020-12) --- ...crosoft.PowerShell.Commands.Utility.csproj | 6 +- .../JsonSchemaReferenceResolutionException.cs | 27 ++++ .../commands/utility/TestJsonCommand.cs | 141 +++++++++++------- .../resources/TestJsonCmdletStrings.resx | 7 +- .../Test-Json.Tests.ps1 | 96 ++++++------ tools/packaging/boms/linux.json | 2 +- tools/packaging/boms/mac.json | 2 +- tools/packaging/boms/windows.json | 24 ++- 8 files changed, 182 insertions(+), 123 deletions(-) create mode 100644 src/Microsoft.PowerShell.Commands.Utility/commands/utility/JsonSchemaReferenceResolutionException.cs diff --git a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj index 085f7cf63bc..ea5e0bd22a1 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj +++ b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj @@ -35,11 +35,7 @@ - - - + diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/JsonSchemaReferenceResolutionException.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/JsonSchemaReferenceResolutionException.cs new file mode 100644 index 00000000000..ba664ccef1b --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/JsonSchemaReferenceResolutionException.cs @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System; + +namespace Microsoft.PowerShell.Commands; + +/// +/// Thrown during evaluation of when an attempt +/// to resolve a $ref or $dynamicRef fails. +/// +internal class JsonSchemaReferenceResolutionException : Exception +{ + /// + /// Initializes a new instance of the class. + /// + /// + /// The exception that is the cause of the current exception, or a null reference + /// (Nothing in Visual Basic) if no inner exception is specified. + /// + public JsonSchemaReferenceResolutionException(Exception innerException) + : base(message: null, innerException) + { + } +} diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/TestJsonCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/TestJsonCommand.cs index fc416d9772e..4a6e11a9633 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/TestJsonCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/TestJsonCommand.cs @@ -5,11 +5,11 @@ using System.Globalization; using System.IO; using System.Management.Automation; -using System.Reflection; -using System.Runtime.ExceptionServices; +using System.Net.Http; using System.Security; -using Newtonsoft.Json.Linq; -using NJsonSchema; +using System.Text.Json; +using System.Text.Json.Nodes; +using Json.Schema; namespace Microsoft.PowerShell.Commands { @@ -104,36 +104,50 @@ public string LiteralPath private bool _isLiteralPath = false; private JsonSchema _jschema; - /// - /// Process all exceptions in the AggregateException. - /// Unwrap TargetInvocationException if any and - /// rethrow inner exception without losing the stack trace. - /// - /// AggregateException to be unwrapped. - /// Return value is unreachable since we always rethrow. - private static bool UnwrapException(Exception e) - { - if (e.InnerException != null && e is TargetInvocationException) - { - ExceptionDispatchInfo.Capture(e.InnerException).Throw(); - } - else - { - ExceptionDispatchInfo.Capture(e).Throw(); - } - - return true; - } - #endregion - #region Protected Members - /// /// Prepare a JSON schema. /// protected override void BeginProcessing() { + // By default, a JSON Schema implementation isn't supposed to automatically fetch content. + // Instead JsonSchema.Net has been set up with a registry so that users can pre-register + // any schemas they may need to resolve. + // However, pre-registering schemas doesn't make sense in the context of a Powershell command, + // and automatically fetching referenced URIs is likely the preferred behavior. To do that, + // this property must be set with a method to retrieve and deserialize the content. + // For more information, see https://json-everything.net/json-schema#automatic-resolution + SchemaRegistry.Global.Fetch = static uri => + { + try + { + string text; + switch (uri.Scheme) + { + case "http": + case "https": + { + using var client = new HttpClient(); + text = client.GetStringAsync(uri).Result; + break; + } + case "file": + var filename = Uri.UnescapeDataString(uri.AbsolutePath); + text = File.ReadAllText(filename); + break; + default: + throw new FormatException(string.Format(TestJsonCmdletStrings.InvalidUriScheme, uri.Scheme)); + } + + return JsonSerializer.Deserialize(text); + } + catch (Exception e) + { + throw new JsonSchemaReferenceResolutionException(e); + } + }; + string resolvedpath = string.Empty; try @@ -142,13 +156,12 @@ protected override void BeginProcessing() { try { - _jschema = JsonSchema.FromJsonAsync(Schema).Result; + _jschema = JsonSchema.FromText(Schema); } - catch (AggregateException ae) + catch (JsonException e) { - // Even if only one exception is thrown, it is still wrapped in an AggregateException exception - // https://docs.microsoft.com/en-us/dotnet/standard/parallel-programming/exception-handling-task-parallel-library - ae.Handle(UnwrapException); + Exception exception = new(TestJsonCmdletStrings.InvalidJsonSchema, e); + WriteError(new ErrorRecord(exception, "InvalidJsonSchema", ErrorCategory.InvalidData, Schema)); } } else if (SchemaFile != null) @@ -156,11 +169,12 @@ protected override void BeginProcessing() try { resolvedpath = Context.SessionState.Path.GetUnresolvedProviderPathFromPSPath(SchemaFile); - _jschema = JsonSchema.FromFileAsync(resolvedpath).Result; + _jschema = JsonSchema.FromFile(resolvedpath); } - catch (AggregateException ae) + catch (JsonException e) { - ae.Handle(UnwrapException); + Exception exception = new(TestJsonCmdletStrings.InvalidJsonSchema, e); + WriteError(new ErrorRecord(exception, "InvalidJsonSchema", ErrorCategory.InvalidData, SchemaFile)); } } } @@ -194,6 +208,7 @@ e is SecurityException protected override void ProcessRecord() { bool result = true; + string jsonToParse = string.Empty; if (Json != null) @@ -217,45 +232,57 @@ protected override void ProcessRecord() jsonToParse = File.ReadAllText(resolvedPath); } - if (string.IsNullOrWhiteSpace(jsonToParse)) - { - WriteObject(false); - return; - } - try { - var parsedJson = JToken.Parse(jsonToParse); + + var parsedJson = JsonNode.Parse(jsonToParse); if (_jschema != null) { - var errorMessages = _jschema.Validate(parsedJson); - if (errorMessages != null && errorMessages.Count != 0) - { - result = false; - - Exception exception = new(TestJsonCmdletStrings.InvalidJsonAgainstSchema); - - foreach (var message in errorMessages) + var validationResults = _jschema.Validate(parsedJson, new ValidationOptions { OutputFormat = OutputFormat.Basic }); + result = validationResults.IsValid; + if (!result) { - ErrorRecord errorRecord = new(exception, "InvalidJsonAgainstSchema", ErrorCategory.InvalidData, null); - errorRecord.ErrorDetails = new ErrorDetails(message.ToString()); - WriteError(errorRecord); + if (validationResults.Message != null) + { + Exception exception = new(string.Format(TestJsonCmdletStrings.InvalidJsonAgainstSchemaDetailed, validationResults.Message, validationResults.InstanceLocation)); + ErrorRecord errorRecord = new(exception, "InvalidJsonAgainstSchemaDetailed", ErrorCategory.InvalidData, null); + WriteError(errorRecord); + } + + if (validationResults.HasNestedResults) + { + foreach (var nestedResult in validationResults.NestedResults) + { + if (nestedResult.Message == null) + { + continue; + } + + Exception exception = new(string.Format(TestJsonCmdletStrings.InvalidJsonAgainstSchemaDetailed, nestedResult.Message, nestedResult.InstanceLocation)); + ErrorRecord errorRecord = new(exception, "InvalidJsonAgainstSchemaDetailed", ErrorCategory.InvalidData, null); + WriteError(errorRecord); + } + } } - } } } + catch (JsonSchemaReferenceResolutionException jsonExc) + { + result = false; + + Exception exception = new(TestJsonCmdletStrings.InvalidJsonSchema, jsonExc); + WriteError(new ErrorRecord(exception, "InvalidJsonSchema", ErrorCategory.InvalidData, _jschema)); + } catch (Exception exc) { result = false; Exception exception = new(TestJsonCmdletStrings.InvalidJson, exc); - WriteError(new ErrorRecord(exception, "InvalidJson", ErrorCategory.InvalidData, jsonToParse)); + WriteError(new ErrorRecord(exception, "InvalidJson", ErrorCategory.InvalidData, Json)); } WriteObject(result); } - - #endregion } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/TestJsonCmdletStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/TestJsonCmdletStrings.resx index ab105e47fd3..eed85d28b3d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/TestJsonCmdletStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/TestJsonCmdletStrings.resx @@ -123,10 +123,13 @@ Cannot parse the JSON. - - The JSON is not valid with the schema. + + The JSON is not valid with the schema: {0} at {1} Can not open JSON schema file: {0} + + URI scheme '{0}' is not supported. Only HTTP(S) and local file system URIs are allowed. + diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Test-Json.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Test-Json.Tests.ps1 index 9e949e0215a..a5aa52e0296 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Test-Json.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Test-Json.Tests.ps1 @@ -9,62 +9,62 @@ Describe "Test-Json" -Tags "CI" { $missingSchemaJsonPath = Join-Path -Path $assetsPath -ChildPath no_such_file.json $missingJsonPath = Join-Path -Path $assetsPath -ChildPath no_such_file.json - $validSchemaJson = @" + $validSchemaJson = @' { - 'description': 'A person', - 'type': 'object', - 'properties': { - 'name': {'type': 'string'}, - 'hobbies': { - 'type': 'array', - 'items': {'type': 'string'} + "description": "A person", + "type": "object", + "properties": { + "name": {"type": "string"}, + "hobbies": { + "type": "array", + "items": {"type": "string"} } } } -"@ +'@ - $invalidSchemaJson = @" + $invalidSchemaJson = @' { - 'description', - 'type': 'object', - 'properties': { - 'name': {'type': 'string'}, - 'hobbies': { - 'type': 'array', - 'items': {'type': 'string'} + "description", + "type": "object", + "properties": { + "name": {"type": "string"}, + "hobbies": { + "type": "array", + "items": {"type": "string"} } } } -"@ +'@ - $validJson = @" + $validJson = @' { - 'name': 'James', - 'hobbies': ['.NET', 'Blogging', 'Reading', 'Xbox', 'LOLCATS'] + "name": "James", + "hobbies": [".NET", "Blogging", "Reading", "Xbox", "LOLCATS"] } -"@ +'@ - $invalidTypeInJson = @" + $invalidTypeInJson = @' { - 'name': 123, - 'hobbies': ['.NET', 'Blogging', 'Reading', 'Xbox', 'LOLCATS'] + "name": 123, + "hobbies": [".NET", "Blogging", "Reading", "Xbox", "LOLCATS"] } -"@ +'@ - $invalidTypeInJson2 = @" + $invalidTypeInJson2 = @' { - 'name': 123, - 'hobbies': [456, 'Blogging', 'Reading', 'Xbox', 'LOLCATS'] + "name": 123, + "hobbies": [456, "Blogging", "Reading", "Xbox", "LOLCATS"] } -"@ +'@ - $invalidNodeInJson = @" + $invalidNodeInJson = @' { - 'name': 'James', - 'hobbies': ['.NET', 'Blogging', 'Reading', 'Xbox', 'LOLCATS'] + "name": "James", + "hobbies": [".NET", "Blogging", "Reading", "Xbox", "LOLCATS"] errorNode } -"@ +'@ $validJsonPath = Join-Path -Path $TestDrive -ChildPath 'validJson.json' $validLiteralJsonPath = Join-Path -Path $TestDrive -ChildPath "[valid]Json.json" @@ -91,12 +91,10 @@ Describe "Test-Json" -Tags "CI" { It "Json is valid" { Test-Json -Json $validJson | Should -BeTrue - ($validJson | Test-Json) | Should -BeTrue } It "Json is valid against a valid schema from string" { Test-Json -Json $validJson -Schema $validSchemaJson | Should -BeTrue - ($validJson | Test-Json -Schema $validSchemaJson) | Should -BeTrue } It "Json is valid against a valid schema from file" { @@ -201,7 +199,7 @@ Describe "Test-Json" -Tags "CI" { } It "Test-Json write an error on invalid () Json against a valid schema from string" -TestCases @( - @{ name = "type"; json = $invalidTypeInJson; errorId = "InvalidJsonAgainstSchema,Microsoft.PowerShell.Commands.TestJsonCommand" } + @{ name = "type"; json = $invalidTypeInJson; errorId = "InvalidJsonAgainstSchemaDetailed,Microsoft.PowerShell.Commands.TestJsonCommand" } @{ name = "node"; json = $invalidNodeInJson; errorId = "InvalidJson,Microsoft.PowerShell.Commands.TestJsonCommand" } ) { param ($json, $errorId) @@ -213,7 +211,7 @@ Describe "Test-Json" -Tags "CI" { } It "Test-Json write an error on invalid () Json against a valid schema from file" -TestCases @( - @{ name = "type"; json = $invalidTypeInJson; errorId = "InvalidJsonAgainstSchema,Microsoft.PowerShell.Commands.TestJsonCommand" } + @{ name = "type"; json = $invalidTypeInJson; errorId = "InvalidJsonAgainstSchemaDetailed,Microsoft.PowerShell.Commands.TestJsonCommand" } @{ name = "node"; json = $invalidNodeInJson; errorId = "InvalidJson,Microsoft.PowerShell.Commands.TestJsonCommand" } ) { param ($json, $errorId) @@ -225,7 +223,7 @@ Describe "Test-Json" -Tags "CI" { } It "Test-Json write an error on invalid () Json file against a valid schema from string" -TestCases @( - @{ name = "type"; json = $invalidTypeInJsonPath; errorId = "InvalidJsonAgainstSchema,Microsoft.PowerShell.Commands.TestJsonCommand" } + @{ name = "type"; json = $invalidTypeInJsonPath; errorId = "InvalidJsonAgainstSchemaDetailed,Microsoft.PowerShell.Commands.TestJsonCommand" } @{ name = "node"; json = $invalidNodeInJsonPath; errorId = "InvalidJson,Microsoft.PowerShell.Commands.TestJsonCommand" } ) { param ($json, $errorId) @@ -237,7 +235,7 @@ Describe "Test-Json" -Tags "CI" { } It "Test-Json write an error on invalid () Json file against a valid schema from file" -TestCases @( - @{ name = "type"; json = $invalidTypeInJsonPath; errorId = "InvalidJsonAgainstSchema,Microsoft.PowerShell.Commands.TestJsonCommand" } + @{ name = "type"; json = $invalidTypeInJsonPath; errorId = "InvalidJsonAgainstSchemaDetailed,Microsoft.PowerShell.Commands.TestJsonCommand" } @{ name = "node"; json = $invalidNodeInJsonPath; errorId = "InvalidJson,Microsoft.PowerShell.Commands.TestJsonCommand" } ) { param ($json, $errorId) @@ -254,8 +252,8 @@ Describe "Test-Json" -Tags "CI" { # '$invalidTypeInJson2' contains two errors in property types. $errorVar.Count | Should -Be 2 - $errorVar[0].FullyQualifiedErrorId | Should -BeExactly "InvalidJsonAgainstSchema,Microsoft.PowerShell.Commands.TestJsonCommand" - $errorVar[1].FullyQualifiedErrorId | Should -BeExactly "InvalidJsonAgainstSchema,Microsoft.PowerShell.Commands.TestJsonCommand" + $errorVar[0].FullyQualifiedErrorId | Should -BeExactly "InvalidJsonAgainstSchemaDetailed,Microsoft.PowerShell.Commands.TestJsonCommand" + $errorVar[1].FullyQualifiedErrorId | Should -BeExactly "InvalidJsonAgainstSchemaDetailed,Microsoft.PowerShell.Commands.TestJsonCommand" } It "Test-Json return all errors when check invalid Json against a valid schema from file" { @@ -264,8 +262,8 @@ Describe "Test-Json" -Tags "CI" { # '$invalidTypeInJson2' contains two errors in property types. $errorVar.Count | Should -Be 2 - $errorVar[0].FullyQualifiedErrorId | Should -BeExactly "InvalidJsonAgainstSchema,Microsoft.PowerShell.Commands.TestJsonCommand" - $errorVar[1].FullyQualifiedErrorId | Should -BeExactly "InvalidJsonAgainstSchema,Microsoft.PowerShell.Commands.TestJsonCommand" + $errorVar[0].FullyQualifiedErrorId | Should -BeExactly "InvalidJsonAgainstSchemaDetailed,Microsoft.PowerShell.Commands.TestJsonCommand" + $errorVar[1].FullyQualifiedErrorId | Should -BeExactly "InvalidJsonAgainstSchemaDetailed,Microsoft.PowerShell.Commands.TestJsonCommand" } It "Test-Json return all errors when check invalid Json file against a valid schema from string" { @@ -274,8 +272,8 @@ Describe "Test-Json" -Tags "CI" { # '$invalidTypeInJson2Path' contains two errors in property types. $errorVar.Count | Should -Be 2 - $errorVar[0].FullyQualifiedErrorId | Should -BeExactly "InvalidJsonAgainstSchema,Microsoft.PowerShell.Commands.TestJsonCommand" - $errorVar[1].FullyQualifiedErrorId | Should -BeExactly "InvalidJsonAgainstSchema,Microsoft.PowerShell.Commands.TestJsonCommand" + $errorVar[0].FullyQualifiedErrorId | Should -BeExactly "InvalidJsonAgainstSchemaDetailed,Microsoft.PowerShell.Commands.TestJsonCommand" + $errorVar[1].FullyQualifiedErrorId | Should -BeExactly "InvalidJsonAgainstSchemaDetailed,Microsoft.PowerShell.Commands.TestJsonCommand" } It "Test-Json return all errors when check invalid Json file against a valid schema from file" { @@ -284,8 +282,8 @@ Describe "Test-Json" -Tags "CI" { # '$invalidTypeInJson2Path' contains two errors in property types. $errorVar.Count | Should -Be 2 - $errorVar[0].FullyQualifiedErrorId | Should -BeExactly "InvalidJsonAgainstSchema,Microsoft.PowerShell.Commands.TestJsonCommand" - $errorVar[1].FullyQualifiedErrorId | Should -BeExactly "InvalidJsonAgainstSchema,Microsoft.PowerShell.Commands.TestJsonCommand" + $errorVar[0].FullyQualifiedErrorId | Should -BeExactly "InvalidJsonAgainstSchemaDetailed,Microsoft.PowerShell.Commands.TestJsonCommand" + $errorVar[1].FullyQualifiedErrorId | Should -BeExactly "InvalidJsonAgainstSchemaDetailed,Microsoft.PowerShell.Commands.TestJsonCommand" } It 'Test-Json recognizes non-object types: ' -TestCases @( @@ -307,7 +305,7 @@ Describe "Test-Json" -Tags "CI" { # Exactly one type should match $types = 'string', 'number', 'boolean', 'null', 'array', 'object' $types | Where-Object { - $schema = "{ 'type': '$_' }" + $schema = "{ `"type`": `"$_`" }" Test-Json -Json $value -Schema $schema -ErrorAction SilentlyContinue } | Should -Be $expected } diff --git a/tools/packaging/boms/linux.json b/tools/packaging/boms/linux.json index b115e72b551..f735ea5cf1c 100644 --- a/tools/packaging/boms/linux.json +++ b/tools/packaging/boms/linux.json @@ -492,7 +492,7 @@ "FileType": "NonProduct" }, { - "Pattern": "NJsonSchema.dll", + "Pattern": "JsonSchema.Net.dll", "FileType": "NonProduct" }, { diff --git a/tools/packaging/boms/mac.json b/tools/packaging/boms/mac.json index 28593cdd142..29f2bb8532a 100644 --- a/tools/packaging/boms/mac.json +++ b/tools/packaging/boms/mac.json @@ -372,7 +372,7 @@ "FileType": "NonProduct" }, { - "Pattern": "NJsonSchema.dll", + "Pattern": "JsonSchema.Net.dll", "FileType": "NonProduct" }, { diff --git a/tools/packaging/boms/windows.json b/tools/packaging/boms/windows.json index dc4329e4751..747fa838b5d 100644 --- a/tools/packaging/boms/windows.json +++ b/tools/packaging/boms/windows.json @@ -555,6 +555,22 @@ "Pattern": "ja/WindowsFormsIntegration.resources.dll", "FileType": "NonProduct" }, + { + "Pattern": "JetBrains.Annotations.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Json.More.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "JsonPointer.Net.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "JsonSchema.Net.dll", + "FileType": "NonProduct" + }, { "Pattern": "ko/Microsoft.CodeAnalysis.CSharp.resources.dll", "FileType": "NonProduct" @@ -871,10 +887,6 @@ "Pattern": "msquic.dll", "FileType": "NonProduct" }, - { - "Pattern": "Namotion.Reflection.dll", - "FileType": "NonProduct" - }, { "Pattern": "netstandard.dll", "FileType": "NonProduct" @@ -883,10 +895,6 @@ "Pattern": "Newtonsoft.Json.dll", "FileType": "NonProduct" }, - { - "Pattern": "NJsonSchema.dll", - "FileType": "NonProduct" - }, { "Pattern": "PenImc_cor3.dll", "FileType": "NonProduct" From bfa6883f2ae6f2f9b704e937b89ebb48b8076344 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Thu, 4 May 2023 09:50:04 -0700 Subject: [PATCH 517/779] Add support of respecting `$PSStyle.OutputRendering` on the remote host (#19601) --- .../remoting/server/ServerRemoteHostUserInterface.cs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostUserInterface.cs b/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostUserInterface.cs index 314fc25587f..76265089677 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostUserInterface.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostUserInterface.cs @@ -122,6 +122,7 @@ public override Dictionary Prompt(string caption, string messa /// public override void Write(string message) { + message = GetOutputString(message, supportsVirtualTerminal: true); _serverMethodExecutor.ExecuteVoidMethod(RemoteHostMethodId.Write1, new object[] { message }); } @@ -130,6 +131,7 @@ public override void Write(string message) /// public override void Write(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string message) { + message = GetOutputString(message, supportsVirtualTerminal: true); _serverMethodExecutor.ExecuteVoidMethod(RemoteHostMethodId.Write2, new object[] { foregroundColor, backgroundColor, message }); } @@ -146,6 +148,7 @@ public override void WriteLine() /// public override void WriteLine(string message) { + message = GetOutputString(message, supportsVirtualTerminal: true); _serverMethodExecutor.ExecuteVoidMethod(RemoteHostMethodId.WriteLine2, new object[] { message }); } @@ -154,6 +157,7 @@ public override void WriteLine(string message) /// public override void WriteLine(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string message) { + message = GetOutputString(message, supportsVirtualTerminal: true); _serverMethodExecutor.ExecuteVoidMethod(RemoteHostMethodId.WriteLine3, new object[] { foregroundColor, backgroundColor, message }); } @@ -162,6 +166,7 @@ public override void WriteLine(ConsoleColor foregroundColor, ConsoleColor backgr /// public override void WriteErrorLine(string message) { + message = GetOutputString(message, supportsVirtualTerminal: true); _serverMethodExecutor.ExecuteVoidMethod(RemoteHostMethodId.WriteErrorLine, new object[] { message }); } @@ -170,6 +175,7 @@ public override void WriteErrorLine(string message) /// public override void WriteDebugLine(string message) { + message = GetOutputString(message, supportsVirtualTerminal: true); _serverMethodExecutor.ExecuteVoidMethod(RemoteHostMethodId.WriteDebugLine, new object[] { message }); } @@ -186,6 +192,7 @@ public override void WriteProgress(long sourceId, ProgressRecord record) /// public override void WriteVerboseLine(string message) { + message = GetOutputString(message, supportsVirtualTerminal: true); _serverMethodExecutor.ExecuteVoidMethod(RemoteHostMethodId.WriteVerboseLine, new object[] { message }); } @@ -194,6 +201,7 @@ public override void WriteVerboseLine(string message) /// public override void WriteWarningLine(string message) { + message = GetOutputString(message, supportsVirtualTerminal: true); _serverMethodExecutor.ExecuteVoidMethod(RemoteHostMethodId.WriteWarningLine, new object[] { message }); } From 9d36e139bce8a955b3b3ae18f3bee2bc1a6de982 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Thu, 4 May 2023 09:51:16 -0700 Subject: [PATCH 518/779] For Preview releases, add `pwsh-preview.exe` alias to MSIX package (#19602) * For Preview releases, add `pwsh-preview.exe` alias to MSIX package * add ability to produce private msix pkg for testing --- tools/packaging/packaging.psm1 | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/tools/packaging/packaging.psm1 b/tools/packaging/packaging.psm1 index ce4d3a95fb1..f0d5cf5290a 100644 --- a/tools/packaging/packaging.psm1 +++ b/tools/packaging/packaging.psm1 @@ -61,6 +61,8 @@ function Start-PSPackage { [ValidateScript({$Environment.IsMacOS})] [string] $MacOSRuntime, + [switch] $Private, + [Switch] $Force, [Switch] $SkipReleaseChecks, @@ -473,6 +475,7 @@ function Start-PSPackage { ProductVersion = $Version Architecture = $WindowsRuntime.Split('-')[1] Force = $Force + Private = $Private } if ($PSCmdlet.ShouldProcess("Create MSIX Package")) { @@ -3602,6 +3605,9 @@ function New-MSIXPackage [ValidateSet('x64','x86','arm','arm64')] [string] $Architecture, + # Produce private package for testing in Store + [Switch] $Private, + # Force overwrite of package [Switch] $Force, @@ -3630,13 +3636,20 @@ function New-MSIXPackage $ProductSemanticVersion = Get-PackageSemanticVersion -Version $ProductVersion $productSemanticVersionWithName = $ProductName + '-' + $ProductSemanticVersion $packageName = $productSemanticVersionWithName + if ($Private) { + $ProductNameSuffix = 'Private' + } + if ($ProductNameSuffix) { $packageName += "-$ProductNameSuffix" } $displayName = $productName - if ($ProductSemanticVersion.Contains('-')) { + if ($Private) { + $ProductName = 'PowerShell-Private' + $displayName = 'PowerShell-Private' + } elseif ($ProductSemanticVersion.Contains('-')) { $ProductName += 'Preview' $displayName += ' Preview' } @@ -3658,7 +3671,15 @@ function New-MSIXPackage $appxManifest = Get-Content "$RepoRoot\assets\AppxManifest.xml" -Raw $appxManifest = $appxManifest.Replace('$VERSION$', $ProductVersion).Replace('$ARCH$', $Architecture).Replace('$PRODUCTNAME$', $productName).Replace('$DISPLAYNAME$', $displayName).Replace('$PUBLISHER$', $releasePublisher) - Set-Content -Path "$ProductSourcePath\AppxManifest.xml" -Value $appxManifest -Force + $xml = [xml]$appxManifest + if ($isPreview) { + Write-Verbose -Verbose "Adding pwsh-preview.exe alias" + $aliasNode = $xml.Package.Applications.Application.Extensions.Extension.AppExecutionAlias.ExecutionAlias.Clone() + $aliasNode.alias = "pwsh-preview.exe" + $xml.Package.Applications.Application.Extensions.Extension.AppExecutionAlias.AppendChild($aliasNode) | Out-Null + } + $xml.Save("$ProductSourcePath\AppxManifest.xml") + # Necessary image assets need to be in source assets folder $assets = @( 'Square150x150Logo' From 16c6030f06f10a0bda3277b505981ffab3a589cf Mon Sep 17 00:00:00 2001 From: Patrick Meinecke Date: Thu, 4 May 2023 15:00:18 -0400 Subject: [PATCH 519/779] Fix the check when reading input in `NativeCommandProcessor` (#19614) --- .../engine/NativeCommandProcessor.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/System.Management.Automation/engine/NativeCommandProcessor.cs b/src/System.Management.Automation/engine/NativeCommandProcessor.cs index 3bb0fef21b9..2168365c747 100644 --- a/src/System.Management.Automation/engine/NativeCommandProcessor.cs +++ b/src/System.Management.Automation/engine/NativeCommandProcessor.cs @@ -435,8 +435,8 @@ internal override void ProcessRecord() { // If upstream is a native command it'll be writing directly to our stdin stream // so we can skip reading here. - if (ExperimentalFeature.IsEnabled(ExperimentalFeature.PSNativeCommandPreserveBytePipe) - && !UpstreamIsNativeCommand) + if (!ExperimentalFeature.IsEnabled(ExperimentalFeature.PSNativeCommandPreserveBytePipe) + || !UpstreamIsNativeCommand) { while (Read()) { From f179017adad0d8467be78989bdd757071e796f1a Mon Sep 17 00:00:00 2001 From: PowerShell Team Bot <69177312+pwshBot@users.noreply.github.com> Date: Thu, 4 May 2023 12:01:27 -0700 Subject: [PATCH 520/779] Update the `cgmanifest` file (#19613) --- tools/cgmanifest.json | 80 +++++++++++++++++++++++++++---------------- 1 file changed, 50 insertions(+), 30 deletions(-) diff --git a/tools/cgmanifest.json b/tools/cgmanifest.json index 2e1f79bbdd2..65f9bddd64c 100644 --- a/tools/cgmanifest.json +++ b/tools/cgmanifest.json @@ -20,6 +20,46 @@ }, "DevelopmentDependency": true }, + { + "Component": { + "Type": "nuget", + "Nuget": { + "Name": "JetBrains.Annotations", + "Version": "2021.2.0" + } + }, + "DevelopmentDependency": false + }, + { + "Component": { + "Type": "nuget", + "Nuget": { + "Name": "Json.More.Net", + "Version": "1.7.0" + } + }, + "DevelopmentDependency": false + }, + { + "Component": { + "Type": "nuget", + "Nuget": { + "Name": "JsonPointer.Net", + "Version": "2.2.1" + } + }, + "DevelopmentDependency": false + }, + { + "Component": { + "Type": "nuget", + "Nuget": { + "Name": "JsonSchema.Net", + "Version": "3.3.2" + } + }, + "DevelopmentDependency": false + }, { "Component": { "Type": "nuget", @@ -80,16 +120,6 @@ }, "DevelopmentDependency": false }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "Microsoft.CSharp", - "Version": "4.7.0" - } - }, - "DevelopmentDependency": false - }, { "Component": { "Type": "nuget", @@ -200,16 +230,6 @@ }, "DevelopmentDependency": false }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "Namotion.Reflection", - "Version": "2.1.0" - } - }, - "DevelopmentDependency": false - }, { "Component": { "Type": "nuget", @@ -220,16 +240,6 @@ }, "DevelopmentDependency": false }, - { - "Component": { - "Type": "nuget", - "Nuget": { - "Name": "NJsonSchema", - "Version": "10.8.0" - } - }, - "DevelopmentDependency": false - }, { "Component": { "Type": "nuget", @@ -780,6 +790,16 @@ }, "DevelopmentDependency": false }, + { + "Component": { + "Type": "nuget", + "Nuget": { + "Name": "System.Text.Json", + "Version": "6.0.2" + } + }, + "DevelopmentDependency": false + }, { "Component": { "Type": "nuget", From 9662f028f6c3fd17395ef77e5f26e65fb3fd1acb Mon Sep 17 00:00:00 2001 From: Sean Wheeler Date: Thu, 4 May 2023 13:23:11 -0700 Subject: [PATCH 521/779] Update `working-group-definitions.md` (#19561) --- .spelling | 1 + docs/community/working-group-definitions.md | 7 +++++-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/.spelling b/.spelling index 507ab9e16bd..9647f0c0448 100644 --- a/.spelling +++ b/.spelling @@ -1717,3 +1717,4 @@ dkattan preview.3.23178.7 PoolNames techguy16 +sdwheeler diff --git a/docs/community/working-group-definitions.md b/docs/community/working-group-definitions.md index 26f94d8c03e..d13d5a4910d 100644 --- a/docs/community/working-group-definitions.md +++ b/docs/community/working-group-definitions.md @@ -22,6 +22,7 @@ Today, DSC is integrated into the PowerShell language, and we need to manage it * @anmenaga * @gaelcolas * @michaeltlombardi +* @SteveL-MSFT ## Developer Experience @@ -83,10 +84,12 @@ These topics include (but are not limited to): ### Members +* @theJasonHelmick * @daxian-dbw (PSReadline / IntelliSense) * @adityapatwardhan (Markdown / help system) * @JamesWTruher (cmdlet design) * @SeeminglyScience +* @sdwheeler * @kilasuit ## Language @@ -115,7 +118,6 @@ Given the commonality of serialization boundaries, the Remoting WG should also f ### Members * @anmenaga -* @jborean93 * @PaulHigin * @TravisEz13 @@ -141,7 +143,8 @@ These modules include: ### Members -* PowerShell Committee as interim members +* @JamesWTruher +* @SteveL-MSFT * @jdhitsolutions * @TobiasPSP * @doctordns From 4584d2f77517f30cd2135cd1f25d77668c105517 Mon Sep 17 00:00:00 2001 From: PowerShell Team Bot <69177312+pwshBot@users.noreply.github.com> Date: Mon, 8 May 2023 09:09:28 -0700 Subject: [PATCH 522/779] Update to the latest NOTICES file (#19620) --- ThirdPartyNotices.txt | 328 ++++++++++++++++++++++++++++++------------ 1 file changed, 236 insertions(+), 92 deletions(-) diff --git a/ThirdPartyNotices.txt b/ThirdPartyNotices.txt index 2740296acca..93727a5bedc 100644 --- a/ThirdPartyNotices.txt +++ b/ThirdPartyNotices.txt @@ -149,6 +149,120 @@ Redistribution and use in source and binary forms, with or without modification, THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +--------------------------------------------------------- + +--------------------------------------------------------- + +JetBrains.Annotations 2021.2.0 - MIT + + +Copyright (c) 2016 JetBrains http://www.jetbrains.com + +MIT License + +Copyright (c) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--------------------------------------------------------- + +--------------------------------------------------------- + +Json.More.Net 1.7.0 - MIT + + + +MIT License + +Copyright (c) 2022 Greg Dennis + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +JsonPointer.Net 2.2.1 - MIT + + + +MIT License + +Copyright (c) 2020 Greg Dennis + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- + +--------------------------------------------------------- + +JsonSchema.Net 3.3.2 - MIT + + +(c) Microsoft 2022 +Copyright (c) 2022 Greg Dennis + +MIT License + +Copyright (c) 2022 Greg Dennis + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + --------------------------------------------------------- --------------------------------------------------------- @@ -278,59 +392,6 @@ The above copyright notice and this permission notice shall be included in all c THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ---------------------------------------------------------- - ---------------------------------------------------------- - -Microsoft.CSharp 4.7.0 - MIT - - -(c) Microsoft Corporation. -Copyright (c) .NET Foundation. -Copyright (c) 2011, Google Inc. -(c) 1997-2005 Sean Eron Anderson. -Copyright (c) 2007 James Newton-King -Copyright (c) 1991-2017 Unicode, Inc. -Copyright (c) 2013-2017, Alfred Klomp -Copyright (c) 2015-2017, Wojciech Mula -Copyright (c) 2005-2007, Nick Galbreath -Portions (c) International Organization -Copyright (c) 2015 The Chromium Authors. -Copyright (c) 2004-2006 Intel Corporation -Copyright (c) 2016-2017, Matthieu Darbois -Copyright (c) .NET Foundation Contributors -Copyright (c) .NET Foundation and Contributors -Copyright (c) 2011 Novell, Inc (http://www.novell.com) -Copyright (c) 1995-2017 Jean-loup Gailly and Mark Adler -Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) -Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors. -Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers THIS WORK IS PROVIDED AS - -The MIT License (MIT) - -Copyright (c) .NET Foundation and Contributors - -All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - - --------------------------------------------------------- --------------------------------------------------------- @@ -649,6 +710,54 @@ SOFTWARE. Microsoft.Windows.Compatibility 7.0.1 - MIT +(c) Microsoft Corporation +Copyright (c) Andrew Arnott +Copyright 2019 LLVM Project +Copyright 2018 Daniel Lemire +Copyright (c) .NET Foundation +Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson +Copyright (c) 1998 Microsoft. To +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2005-2020 Rich Felker +Copyright (c) Microsoft Corporation +Copyright (c) 2007 James Newton-King +Copyright (c) 2012-2014, Yann Collet +Copyright (c) 1991-2022 Unicode, Inc. +Copyright (c) 2013-2017, Alfred Klomp +Copyright 2012 the V8 project authors +Copyright (c) 1999 Lucent Technologies +Copyright (c) 2008-2016, Wojciech Mula +Copyright (c) 2011-2020 Microsoft Corp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2021 csFastFloat authors +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors +Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 +Portions (c) International Organization +Copyright (c) 2004-2006 Intel Corporation +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) +Copyright (c) .NET Foundation Contributors +Copyright (c) 2020 Mara Bos +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2008-2020 Advanced Micro Devices, Inc. +Copyright (c) 2019 Microsoft Corporation, Daan Leijen +Copyright (c) 2011 Novell, Inc (http://www.novell.com) +Copyright (c) 1995-2022 Jean-loup Gailly and Mark Adler +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors +Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright (c) 1980, 1986, 1993 The Regents of the University of California +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass. To The MIT License (MIT) @@ -675,24 +784,6 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ---------------------------------------------------------- - ---------------------------------------------------------- - -Namotion.Reflection 2.1.0 - MIT - - - -MIT License - -Copyright (c) - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - --------------------------------------------------------- --------------------------------------------------------- @@ -727,27 +818,6 @@ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ---------------------------------------------------------- - ---------------------------------------------------------- - -NJsonSchema 10.8.0 - MIT - - -Copyright Rico Suter, 2022 -Copyright (c) Rico Suter, 2022 -Copyright Rico Suter, 2022 4JSON Schema - -MIT License - -Copyright (c) - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - --------------------------------------------------------- --------------------------------------------------------- @@ -4317,6 +4387,80 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +--------------------------------------------------------- + +--------------------------------------------------------- + +System.Text.Json 6.0.2 - MIT + + +(c) Microsoft Corporation +Copyright (c) Andrew Arnott +Copyright 2018 Daniel Lemire +Copyright (c) .NET Foundation +Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson +Copyright (c) 1998 Microsoft. To +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2005-2020 Rich Felker +Copyright (c) Microsoft Corporation +Copyright (c) 2007 James Newton-King +Copyright (c) 2012-2014, Yann Collet +Copyright (c) 1991-2020 Unicode, Inc. +Copyright (c) 2013-2017, Alfred Klomp +Copyright 2012 the V8 project authors +Copyright (c) 2011-2020 Microsoft Corp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors +Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 +Portions (c) International Organization +Copyright (c) 2004-2006 Intel Corporation +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) +Copyright (c) .NET Foundation Contributors +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2019 Microsoft Corporation, Daan Leijen +Copyright (c) 2011 Novell, Inc (http://www.novell.com) +Copyright (c) 1995-2017 Jean-loup Gailly and Mark Adler +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors +Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass. To + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + --------------------------------------------------------- --------------------------------------------------------- From 4b261ecdb61aaccf4c224e1b936c084c6842547a Mon Sep 17 00:00:00 2001 From: Greg Dennis Date: Tue, 9 May 2023 05:25:10 +1200 Subject: [PATCH 523/779] Update `JsonSchema.Net` version to 4.1.0 (#19610) --- ...crosoft.PowerShell.Commands.Utility.csproj | 2 +- .../commands/utility/TestJsonCommand.cs | 47 ++++++++++--------- .../resources/TestJsonCmdletStrings.resx | 2 +- tools/packaging/boms/windows.json | 4 ++ 4 files changed, 31 insertions(+), 24 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj index ea5e0bd22a1..2972c210a60 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj +++ b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj @@ -35,7 +35,7 @@ - + diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/TestJsonCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/TestJsonCommand.cs index 4a6e11a9633..edb83a08413 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/TestJsonCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/TestJsonCommand.cs @@ -239,32 +239,20 @@ protected override void ProcessRecord() if (_jschema != null) { - var validationResults = _jschema.Validate(parsedJson, new ValidationOptions { OutputFormat = OutputFormat.Basic }); - result = validationResults.IsValid; - if (!result) - { - if (validationResults.Message != null) - { - Exception exception = new(string.Format(TestJsonCmdletStrings.InvalidJsonAgainstSchemaDetailed, validationResults.Message, validationResults.InstanceLocation)); - ErrorRecord errorRecord = new(exception, "InvalidJsonAgainstSchemaDetailed", ErrorCategory.InvalidData, null); - WriteError(errorRecord); - } + EvaluationResults evaluationResults = _jschema.Evaluate(parsedJson, new EvaluationOptions { OutputFormat = OutputFormat.List }); + result = evaluationResults.IsValid; + if (!result) + { + HandleValidationErrors(evaluationResults); - if (validationResults.HasNestedResults) + if (evaluationResults.HasDetails) + { + foreach (var nestedResult in evaluationResults.Details) { - foreach (var nestedResult in validationResults.NestedResults) - { - if (nestedResult.Message == null) - { - continue; - } - - Exception exception = new(string.Format(TestJsonCmdletStrings.InvalidJsonAgainstSchemaDetailed, nestedResult.Message, nestedResult.InstanceLocation)); - ErrorRecord errorRecord = new(exception, "InvalidJsonAgainstSchemaDetailed", ErrorCategory.InvalidData, null); - WriteError(errorRecord); - } + HandleValidationErrors(nestedResult); } } + } } } catch (JsonSchemaReferenceResolutionException jsonExc) @@ -284,5 +272,20 @@ protected override void ProcessRecord() WriteObject(result); } + + private void HandleValidationErrors(EvaluationResults evaluationResult) + { + if (!evaluationResult.HasErrors) + { + return; + } + + foreach (var error in evaluationResult.Errors!) + { + Exception exception = new(string.Format(TestJsonCmdletStrings.InvalidJsonAgainstSchemaDetailed, error.Value, evaluationResult.InstanceLocation)); + ErrorRecord errorRecord = new(exception, "InvalidJsonAgainstSchemaDetailed", ErrorCategory.InvalidData, null); + WriteError(errorRecord); + } + } } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/TestJsonCmdletStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/TestJsonCmdletStrings.resx index eed85d28b3d..cc607eda418 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/TestJsonCmdletStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/TestJsonCmdletStrings.resx @@ -124,7 +124,7 @@ Cannot parse the JSON. - The JSON is not valid with the schema: {0} at {1} + The JSON is not valid with the schema: {0} at '{1}' Can not open JSON schema file: {0} diff --git a/tools/packaging/boms/windows.json b/tools/packaging/boms/windows.json index 747fa838b5d..75b6ddf3266 100644 --- a/tools/packaging/boms/windows.json +++ b/tools/packaging/boms/windows.json @@ -287,6 +287,10 @@ "Pattern": "es/WindowsFormsIntegration.resources.dll", "FileType": "NonProduct" }, + { + "Pattern": "es\\JsonSchema.Net.resources.dll", + "FileType": "NonProduct" + }, { "Pattern": "fr/Microsoft.CodeAnalysis.CSharp.resources.dll", "FileType": "NonProduct" From 33dc1a8faef35f3e665d7c0cdfddde7b20410224 Mon Sep 17 00:00:00 2001 From: Staffan Gustafsson Date: Mon, 8 May 2023 20:56:01 +0200 Subject: [PATCH 524/779] Fixing structure typo in test setup (#17458) --- test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 index 13b4286a2b0..f5b2a573c06 100644 --- a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 +++ b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 @@ -1279,7 +1279,7 @@ class InheritedClassTest : System.Attribute ## if $PSHOME contains a space tabcompletion adds ' around the path @{ inputStr = 'cd $PSHOME\Modu'; expected = if($PSHOME.Contains(' ')) { "'$(Join-Path $PSHOME 'Modules')'" } else { Join-Path $PSHOME 'Modules' }; setup = $null } @{ inputStr = 'cd "$PSHOME\Modu"'; expected = "`"$(Join-Path $PSHOME 'Modules')`""; setup = $null } - @{ inputStr = '$PSHOME\System.Management.Au'; expected = if($PSHOME.Contains(' ')) { "`& '$(Join-Path $PSHOME 'System.Management.Automation.dll')'" } else { Join-Path $PSHOME 'System.Management.Automation.dll'; Setup = $null }} + @{ inputStr = '$PSHOME\System.Management.Au'; expected = if($PSHOME.Contains(' ')) { "`& '$(Join-Path $PSHOME 'System.Management.Automation.dll')'" } else { Join-Path $PSHOME 'System.Management.Automation.dll'}; Setup = $null } @{ inputStr = '"$PSHOME\System.Management.Au"'; expected = "`"$(Join-Path $PSHOME 'System.Management.Automation.dll')`""; setup = $null } @{ inputStr = '& "$PSHOME\System.Management.Au"'; expected = "`"$(Join-Path $PSHOME 'System.Management.Automation.dll')`""; setup = $null } ## tab completion AST-based tests From 19623357ad2834323f8a43171a7d51542d11adc2 Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Mon, 8 May 2023 20:37:42 +0100 Subject: [PATCH 525/779] Remove minor versions from `PSCompatibleVersions` (#18635) --- .../engine/PSVersionInfo.cs | 11 ++---- test/powershell/Host/PSVersionTable.Tests.ps1 | 35 +++++++++++++------ 2 files changed, 27 insertions(+), 19 deletions(-) diff --git a/src/System.Management.Automation/engine/PSVersionInfo.cs b/src/System.Management.Automation/engine/PSVersionInfo.cs index f1b86e7354f..c4202737330 100644 --- a/src/System.Management.Automation/engine/PSVersionInfo.cs +++ b/src/System.Management.Automation/engine/PSVersionInfo.cs @@ -70,13 +70,8 @@ private const int Version_Major private static readonly Version s_psV4Version = new(4, 0); private static readonly Version s_psV5Version = new(5, 0); private static readonly Version s_psV51Version = new(5, 1); - private static readonly Version s_psV6Version = new(6, 0, 0); - private static readonly Version s_psV61Version = new(6, 1, 0); - private static readonly Version s_psV62Version = new(6, 2, 0); - private static readonly Version s_psV7Version = new(7, 0, 0); - private static readonly Version s_psV71Version = new(7, 1, 0); - private static readonly Version s_psV72Version = new(7, 2, 0); - private static readonly Version s_psV73Version = new(7, 3, 0); + private static readonly Version s_psV6Version = new(6, 0); + private static readonly Version s_psV7Version = new(7, 0); private static readonly Version s_psVersion; private static readonly SemanticVersion s_psSemVersion; @@ -98,7 +93,7 @@ static PSVersionInfo() s_psVersionTable[PSVersionName] = s_psSemVersion; s_psVersionTable[PSEditionName] = PSEditionValue; s_psVersionTable[PSGitCommitIdName] = GitCommitId; - s_psVersionTable[PSCompatibleVersionsName] = new Version[] { s_psV1Version, s_psV2Version, s_psV3Version, s_psV4Version, s_psV5Version, s_psV51Version, s_psV6Version, s_psV61Version, s_psV62Version, s_psV7Version, s_psV71Version, s_psV72Version, s_psV73Version, s_psVersion }; + s_psVersionTable[PSCompatibleVersionsName] = new Version[] { s_psV1Version, s_psV2Version, s_psV3Version, s_psV4Version, s_psV5Version, s_psV51Version, s_psV6Version, s_psV7Version }; s_psVersionTable[SerializationVersionName] = new Version(InternalSerializer.DefaultVersion); s_psVersionTable[PSRemotingProtocolVersionName] = RemotingConstants.ProtocolVersion; s_psVersionTable[WSManStackVersionName] = GetWSManStackVersion(); diff --git a/test/powershell/Host/PSVersionTable.Tests.ps1 b/test/powershell/Host/PSVersionTable.Tests.ps1 index 173239fe9d4..777ccb6c132 100644 --- a/test/powershell/Host/PSVersionTable.Tests.ps1 +++ b/test/powershell/Host/PSVersionTable.Tests.ps1 @@ -3,6 +3,7 @@ Describe "PSVersionTable" -Tags "CI" { BeforeAll { + Set-StrictMode -Version 3 $sma = Get-Item (Join-Path $PSHOME "System.Management.Automation.dll") $formattedVersion = $sma.VersionInfo.ProductVersion @@ -22,10 +23,6 @@ Describe "PSVersionTable" -Tags "CI" { $expectedGitCommitIdPattern = "^$mainVersionPattern$" $unexpectectGitCommitIdPattern = $fullVersionPattern } - - $powerShellVersions = "1.0", "2.0", "3.0", "4.0", "5.0", "5.1", "6.0", "6.1", "6.2", "7.0", "7.1", "7.2", "7.3", "7.4" - $powerShellCompatibleVersions = $PSVersionTable.PSCompatibleVersions | - ForEach-Object {$_.ToString(2).SubString(0,3)} } It "Should have version table entries" { @@ -163,15 +160,31 @@ Describe "PSVersionTable" -Tags "CI" { } } - It "Verify PSCompatibleVersions has an entry for all known versions of PowerShell" { - foreach ($version in $powerShellVersions) { - $version | Should -BeIn $powerShellCompatibleVersions + Context "PSCompatibleVersions property" { + It "Is of type System.Version[]" { + Should -ActualValue $PSVersionTable.PSCompatibleVersions -BeOfType System.Version[] + } + + It "Is sorted in ascending order" { + $array = $PSVersionTable.PSCompatibleVersions + [array]::Sort($array) + + $PSVersionTable.PSCompatibleVersions | Should -Be $array } - } - It "Verify PSCompatibleVersions has no unknown PowerShell entries" { - foreach ($version in $powerShellCompatibleVersions) { - $version | Should -BeIn $powerShellVersions + It "Has no unexpected items present" { + $expectedItems = @( + [version]::new(1, 0) + [version]::new(2, 0) + [version]::new(3, 0) + [version]::new(4, 0) + [version]::new(5, 0) + [version]::new(5, 1) + [version]::new(6, 0) + [version]::new(7, 0) + ) + + Compare-Object $expectedItems $PSVersionTable.PSCompatibleVersions | Should -Be $null } } } From facbfd6a643e5c4e35ccd1d3315a1a716c116ed4 Mon Sep 17 00:00:00 2001 From: krishnayalavarthi Date: Tue, 9 May 2023 01:44:05 +0530 Subject: [PATCH 526/779] Runas format changed (#15434) * runas changed * Update assets/wix/Product.wxs --------- Co-authored-by: Krishna Yalavarthi Co-authored-by: Travis Plunk --- assets/wix/Product.wxs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/assets/wix/Product.wxs b/assets/wix/Product.wxs index d4c5e8a2960..976a12d1425 100644 --- a/assets/wix/Product.wxs +++ b/assets/wix/Product.wxs @@ -286,7 +286,7 @@ - + From 95029314938007317ad8938bc8bf977975093e2d Mon Sep 17 00:00:00 2001 From: mkht Date: Tue, 9 May 2023 07:57:27 +0900 Subject: [PATCH 527/779] Fix HTTP status from 409 to 429 for WebCmdlets to get retry interval from Retry-After header. (#19622) --- .../Common/WebRequestPSCmdlet.Common.cs | 2 +- .../WebCmdlets.Tests.ps1 | 64 +++++++++++++++++++ 2 files changed, 65 insertions(+), 1 deletion(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index 60ee931591a..7a53e22f6a1 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -1339,7 +1339,7 @@ internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestM // If the status code is 429 get the retry interval from the Headers. // Ignore broken header and its value. - if (response.StatusCode is HttpStatusCode.Conflict && response.Headers.TryGetValues(HttpKnownHeaderNames.RetryAfter, out IEnumerable retryAfter)) + if (response.StatusCode is HttpStatusCode.TooManyRequests && response.Headers.TryGetValues(HttpKnownHeaderNames.RetryAfter, out IEnumerable retryAfter)) { try { diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 index 2b2968ea3da..117d42ac203 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 @@ -2157,6 +2157,38 @@ Describe "Invoke-WebRequest tests" -Tags "Feature", "RequireAdminOnWindows" { $jsonResult = $result.output.Content | ConvertFrom-Json $jsonResult.SessionId | Should -BeExactly $sessionId } + + It "Invoke-WebRequest respects the Retry-After header value in 429 status" { + + $Query = @{ + statusCode = 429 + reposnsephrase = 'Too Many Requests' + contenttype = 'application/json' + body = '{"message":"oops"}' + headers = '{"Retry-After":"1"}' + } + $uri = Get-WebListenerUrl -Test 'Response' -Query $Query + $verboseFile = Join-Path $TestDrive -ChildPath verbose.txt + $result = Invoke-WebRequest -Uri $uri -MaximumRetryCount 1 -RetryIntervalSec 3 -SkipHttpErrorCheck -Verbose 4>$verbosefile + + $verboseFile | Should -FileContentMatch 'Retrying after interval of 1 seconds. Status code for previous attempt: TooManyRequests' + } + + It "Invoke-WebRequest ignores the Retry-After header value NOT in 429 status" { + + $Query = @{ + statusCode = 409 + reposnsephrase = 'Conflict' + contenttype = 'application/json' + body = '{"message":"oops"}' + headers = '{"Retry-After":"1"}' + } + $uri = Get-WebListenerUrl -Test 'Response' -Query $Query + $verboseFile = Join-Path $TestDrive -ChildPath verbose.txt + $result = Invoke-WebRequest -Uri $uri -MaximumRetryCount 1 -RetryIntervalSec 3 -SkipHttpErrorCheck -Verbose 4>$verbosefile + + $verboseFile | Should -FileContentMatch 'Retrying after interval of 3 seconds. Status code for previous attempt: Conflict' + } } Context "Regex Parsing" { @@ -4047,6 +4079,38 @@ Describe "Invoke-RestMethod tests" -Tags "Feature", "RequireAdminOnWindows" { $result.output.failureResponsesSent | Should -Be 1 $result.output.sessionId | Should -BeExactly $sessionId } + + It "Invoke-RestMethod respects the Retry-After header value in 429 status" { + + $Query = @{ + statusCode = 429 + reposnsephrase = 'Too Many Requests' + contenttype = 'application/json' + body = '{"message":"oops"}' + headers = '{"Retry-After":"1"}' + } + $uri = Get-WebListenerUrl -Test 'Response' -Query $Query + $verboseFile = Join-Path $TestDrive -ChildPath verbose.txt + $result = Invoke-RestMethod -Uri $uri -MaximumRetryCount 1 -RetryIntervalSec 3 -SkipHttpErrorCheck -Verbose 4>$verbosefile + + $verboseFile | Should -FileContentMatch 'Retrying after interval of 1 seconds. Status code for previous attempt: TooManyRequests' + } + + It "Invoke-RestMethod ignores the Retry-After header value NOT in 429 status" { + + $Query = @{ + statusCode = 409 + reposnsephrase = 'Conflict' + contenttype = 'application/json' + body = '{"message":"oops"}' + headers = '{"Retry-After":"1"}' + } + $uri = Get-WebListenerUrl -Test 'Response' -Query $Query + $verboseFile = Join-Path $TestDrive -ChildPath verbose.txt + $result = Invoke-RestMethod -Uri $uri -MaximumRetryCount 1 -RetryIntervalSec 3 -SkipHttpErrorCheck -Verbose 4>$verbosefile + + $verboseFile | Should -FileContentMatch 'Retrying after interval of 3 seconds. Status code for previous attempt: Conflict' + } } } From 0b078175da2564d8fd9b47f3fc6c8a089b582089 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Tue, 9 May 2023 01:00:04 +0200 Subject: [PATCH 528/779] Improve the verbose message of WebCmdlets to show correct HTTP version (#19616) --- .../utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs | 4 ++-- .../resources/WebCmdletStrings.resx | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index 7a53e22f6a1..ce878c1677b 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -568,8 +568,8 @@ protected override void ProcessRecord() string contentType = ContentHelper.GetContentType(response); long? contentLength = response.Content.Headers.ContentLength; string respVerboseMsg = contentLength is null - ? string.Format(CultureInfo.CurrentCulture, WebCmdletStrings.WebResponseNoSizeVerboseMsg, contentType) - : string.Format(CultureInfo.CurrentCulture, WebCmdletStrings.WebResponseVerboseMsg, contentLength, contentType); + ? string.Format(CultureInfo.CurrentCulture, WebCmdletStrings.WebResponseNoSizeVerboseMsg, response.Version, contentType) + : string.Format(CultureInfo.CurrentCulture, WebCmdletStrings.WebResponseVerboseMsg, response.Version, contentLength, contentType); WriteVerbose(respVerboseMsg); diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/WebCmdletStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/WebCmdletStrings.resx index 4236ba80791..6e73043747e 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/WebCmdletStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/WebCmdletStrings.resx @@ -235,16 +235,16 @@ Following rel link {0} - HTTP/{0} {1} with {2}-byte payload + Requested HTTP/{0} {1} with {2}-byte payload The remote server indicated it could not resume downloading. The local file will be overwritten. - received {0}-byte response of content type {1} + Received HTTP/{0} {1}-byte response of content type {2} - received response of content type {0} of unknown size + Received HTTP/{0} response of content type {1} of unknown size Retrying after interval of {0} seconds. Status code for previous attempt: {1} From 1c8b58c0b4aa1bb5f4924f03ca4cdbee5dd0f2f2 Mon Sep 17 00:00:00 2001 From: MartinGC94 <42123497+MartinGC94@users.noreply.github.com> Date: Tue, 9 May 2023 01:21:51 +0200 Subject: [PATCH 529/779] Fix array type parsing in generic types (#19205) --- .../engine/parser/Parser.cs | 10 ++++++---- test/powershell/Language/Parser/Parsing.Tests.ps1 | 8 ++++++++ 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/src/System.Management.Automation/engine/parser/Parser.cs b/src/System.Management.Automation/engine/parser/Parser.cs index e1788d5996f..09023536241 100644 --- a/src/System.Management.Automation/engine/parser/Parser.cs +++ b/src/System.Management.Automation/engine/parser/Parser.cs @@ -1346,7 +1346,7 @@ private ITypeName FinishTypeNameRule(Token typeName, bool unBracketedGenericArg case TokenKind.RBracket: case TokenKind.Comma: var elementType = new TypeName(typeName.Extent, typeName.Text); - return CompleteArrayTypeName(elementType, elementType, token); + return CompleteArrayTypeName(elementType, elementType, token, unBracketedGenericArg); case TokenKind.LBracket: case TokenKind.Identifier: @@ -1496,7 +1496,7 @@ private ITypeName GenericTypeNameRule(Token genericTypeName, Token firstToken, b if (token.Kind == TokenKind.LBracket) { SkipToken(); - return CompleteArrayTypeName(result, openGenericType, NextToken()); + return CompleteArrayTypeName(result, openGenericType, NextToken(), unbracketedGenericArg); } if (token.Kind == TokenKind.Comma && !unbracketedGenericArg) @@ -1519,7 +1519,7 @@ private ITypeName GenericTypeNameRule(Token genericTypeName, Token firstToken, b return result; } - private ITypeName CompleteArrayTypeName(ITypeName elementType, TypeName typeForAssemblyQualification, Token firstTokenAfterLBracket) + private ITypeName CompleteArrayTypeName(ITypeName elementType, TypeName typeForAssemblyQualification, Token firstTokenAfterLBracket, bool unBracketedGenericArg) { while (true) { @@ -1592,7 +1592,9 @@ private ITypeName CompleteArrayTypeName(ITypeName elementType, TypeName typeForA } token = PeekToken(); - if (token.Kind == TokenKind.Comma) + + // An array declared inside an unbracketed generic type argument cannot be assembly qualified + if (!unBracketedGenericArg && token.Kind == TokenKind.Comma) { SkipToken(); var assemblyName = _tokenizer.GetAssemblyNameSpec(); diff --git a/test/powershell/Language/Parser/Parsing.Tests.ps1 b/test/powershell/Language/Parser/Parsing.Tests.ps1 index 7b6cf0b69f8..77477a7afbe 100644 --- a/test/powershell/Language/Parser/Parsing.Tests.ps1 +++ b/test/powershell/Language/Parser/Parsing.Tests.ps1 @@ -664,3 +664,11 @@ Describe "Parsing using statement with alias and linebreak and comma" -Tag CI { } } } + +It "Should correctly parse array types that are used as arguments without brackets in generic type" { + $tks = $null + $ers = $null + $Script = '[System.Tuple[System.String[],System.Int32[]]]' + $result = [System.Management.Automation.Language.Parser]::ParseInput($Script, [ref]$tks, [ref]$ers) + $result.EndBlock.Statements[0].PipelineElements[0].Expression.TypeName.FullName | Should -Be 'System.Tuple[System.String[],System.Int32[]]' +} From d314b0b1c07dd41a3848fbdc305d7deebafc15ab Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Tue, 9 May 2023 01:12:07 +0100 Subject: [PATCH 530/779] Fix incorrect test cases in `ExecutionPolicy.Tests.ps1` (#19485) --- .../ExecutionPolicy.Tests.ps1 | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/test/powershell/Modules/Microsoft.PowerShell.Security/ExecutionPolicy.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Security/ExecutionPolicy.Tests.ps1 index 5a73055d41a..9bcc0143d34 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Security/ExecutionPolicy.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Security/ExecutionPolicy.Tests.ps1 @@ -67,9 +67,6 @@ try { Set-ExecutionPolicy -ExecutionPolicy Restricted -Force -ErrorAction Stop (Get-Help -Name Get-Disk -ErrorAction Stop).Name | Should -Be 'Get-Disk' } - catch { - $_.ToString | Should -Be null - } finally { Set-ExecutionPolicy $currentExecutionPolicy -Force @@ -532,10 +529,10 @@ ZoneId=$FileType Context "Prereq: Validate that 'Microsoft.PowerShell.Archive' is signed" { It "'Microsoft.PowerShell.Archive' should have a signature" { - $script:archiveAllCert | Should -Not -Be null + $script:archiveAllCert | Should -Not -Be $null } It "'Microsoft.PowerShell.Archive' should have a valid signature" { - $script:archiveCert | Should -Not -Be null + $script:archiveCert | Should -Not -Be $null } } From 7888196b8776acfe2cbf24e3d0b8cf9e0af18a45 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Tue, 9 May 2023 08:37:28 -0700 Subject: [PATCH 531/779] Add specific error message that creating Junctions requires absolute path (#19409) --- .../namespaces/FileSystemProvider.cs | 7 +++++++ .../resources/FileSystemProviderStrings.resx | 3 +++ .../FileSystem.Tests.ps1 | 11 +++++++++++ 3 files changed, 21 insertions(+) diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index b8d8e6526af..48cce0aeb75 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -2434,6 +2434,13 @@ protected override void NewItem( bool exists = false; + // junctions require an absolute path + if (!Path.IsPathRooted(strTargetPath)) + { + WriteError(new ErrorRecord(new ArgumentException(FileSystemProviderStrings.JunctionAbsolutePath), "NotAbsolutePath", ErrorCategory.InvalidArgument, strTargetPath)); + return; + } + try { exists = GetFileSystemInfo(strTargetPath, out isDirectory) != null; diff --git a/src/System.Management.Automation/resources/FileSystemProviderStrings.resx b/src/System.Management.Automation/resources/FileSystemProviderStrings.resx index 6ffbce6b884..d23ff660f09 100644 --- a/src/System.Management.Automation/resources/FileSystemProviderStrings.resx +++ b/src/System.Management.Automation/resources/FileSystemProviderStrings.resx @@ -345,4 +345,7 @@ {0} of {1} ({2:0.0} MB/s) + + Creating a junction requires an absolute path for the target. + diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/FileSystem.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/FileSystem.Tests.ps1 index 5849d2ea9fb..67cd1d18894 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/FileSystem.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/FileSystem.Tests.ps1 @@ -613,6 +613,17 @@ Describe "Hard link and symbolic link tests" -Tags "CI", "RequireAdminOnWindows" Test-Path $junctionToDir | Should -BeTrue } + It 'New-Item fails creating junction with relative path' -Skip:(!$IsWindows) { + try { + Push-Location $TestDrive + 1 > 1.txt + { New-Item -ItemType Junction -Path 2.txt -Target 1.txt -ErrorAction Stop } | Should -Throw -ErrorId "NotAbsolutePath,Microsoft.PowerShell.Commands.NewItemCommand" + } + finally { + Pop-Location + } + } + It 'New-Item can create hardlink with relative path' { try { Push-Location $TestDrive From 270f8f1be7cb5e1b0739ec82f45ffa43c2bda40c Mon Sep 17 00:00:00 2001 From: Dominik Kaszewski Date: Tue, 9 May 2023 18:46:59 +0200 Subject: [PATCH 532/779] Allow partial culture matching in `Update-Help` (#18037) --- .../engine/Utils.cs | 5 +- .../help/UpdatableHelpCommandBase.cs | 5 +- .../help/UpdatableHelpInfo.cs | 58 ++++++++++++++----- .../help/UpdatableHelpSystem.cs | 20 ++----- .../engine/Help/HelpSystem.Tests.ps1 | 53 ++++++++++++++++- 5 files changed, 108 insertions(+), 33 deletions(-) diff --git a/src/System.Management.Automation/engine/Utils.cs b/src/System.Management.Automation/engine/Utils.cs index a6642e81c55..c70eb34cdf5 100644 --- a/src/System.Management.Automation/engine/Utils.cs +++ b/src/System.Management.Automation/engine/Utils.cs @@ -1514,11 +1514,14 @@ public static class InternalTestHooks internal static bool UseDebugAmsiImplementation; internal static bool BypassAppLockerPolicyCaching; internal static bool BypassOnlineHelpRetrieval; - internal static bool ThrowHelpCultureNotSupported; internal static bool ForcePromptForChoiceDefaultOption; internal static bool NoPromptForPassword; internal static bool ForceFormatListFixedLabelWidth; + // Update-Help tests + internal static bool ThrowHelpCultureNotSupported; + internal static CultureInfo CurrentUICulture; + // Stop/Restart/Rename Computer tests internal static bool TestStopComputer; internal static bool TestWaitStopComputer; diff --git a/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs b/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs index b759a281bde..48e44bd3013 100644 --- a/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs +++ b/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs @@ -557,7 +557,8 @@ private void ProcessModule(UpdatableHelpModuleInfo module) #endif catch (UpdatableHelpSystemException e) { - if (e.FullyQualifiedErrorId == "HelpCultureNotSupported") + if (e.FullyQualifiedErrorId == "HelpCultureNotSupported" + || e.FullyQualifiedErrorId == "UnableToRetrieveHelpInfoXml") { installed = false; @@ -672,7 +673,7 @@ internal bool IsUpdateNecessary(UpdatableHelpModuleInfo module, UpdatableHelpInf } // Culture check - if (!newHelpInfo.IsCultureSupported(culture)) + if (!newHelpInfo.IsCultureSupported(culture.Name)) { throw new UpdatableHelpSystemException("HelpCultureNotSupported", StringUtil.Format(HelpDisplayStrings.HelpCultureNotSupported, diff --git a/src/System.Management.Automation/help/UpdatableHelpInfo.cs b/src/System.Management.Automation/help/UpdatableHelpInfo.cs index 5af3fd57b6d..8170de90654 100644 --- a/src/System.Management.Automation/help/UpdatableHelpInfo.cs +++ b/src/System.Management.Automation/help/UpdatableHelpInfo.cs @@ -1,9 +1,11 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Globalization; +using System.Linq; using System.Management.Automation.Internal; using System.Text; @@ -37,6 +39,44 @@ internal CultureSpecificUpdatableHelp(CultureInfo culture, Version version) /// Supported culture. /// internal CultureInfo Culture { get; set; } + + /// + /// Enumerates fallback chain (parents) of the culture, including itself. + /// + /// Culture to enumerate + /// + /// Examples: + /// en-GB => { en-GB, en } + /// zh-Hans-CN => { zh-Hans-CN, zh-Hans, zh }. + /// + /// An enumerable list of culture names. + internal static IEnumerable GetCultureFallbackChain(CultureInfo culture) + { + // We use just names instead because comparing two CultureInfo objects + // can fail if they are created using different means + while (culture != null) + { + if (string.IsNullOrEmpty(culture.Name)) + { + yield break; + } + + yield return culture.Name; + + culture = culture.Parent; + } + } + + /// + /// Checks if a culture is supported. + /// + /// Name of the culture to check. + /// True if supported, false if not. + internal bool IsCultureSupported(string cultureName) + { + Debug.Assert(cultureName != null, $"{nameof(cultureName)} may not be null"); + return GetCultureFallbackChain(Culture).Any(fallback => fallback == cultureName); + } } /// @@ -99,22 +139,12 @@ internal bool IsNewerVersion(UpdatableHelpInfo helpInfo, CultureInfo culture) /// /// Checks if a culture is supported. /// - /// Culture to check. + /// Name of the culture to check. /// True if supported, false if not. - internal bool IsCultureSupported(CultureInfo culture) + internal bool IsCultureSupported(string cultureName) { - Debug.Assert(culture != null); - - foreach (CultureSpecificUpdatableHelp updatableHelpItem in UpdatableHelpItems) - { - if (string.Equals(updatableHelpItem.Culture.Name, culture.Name, - StringComparison.OrdinalIgnoreCase)) - { - return true; - } - } - - return false; + Debug.Assert(cultureName != null, $"{nameof(cultureName)} may not be null"); + return UpdatableHelpItems.Any(item => item.IsCultureSupported(cultureName)); } /// diff --git a/src/System.Management.Automation/help/UpdatableHelpSystem.cs b/src/System.Management.Automation/help/UpdatableHelpSystem.cs index eb9796a2074..3a504a37fd2 100644 --- a/src/System.Management.Automation/help/UpdatableHelpSystem.cs +++ b/src/System.Management.Automation/help/UpdatableHelpSystem.cs @@ -294,19 +294,13 @@ internal IEnumerable GetCurrentUICulture() { CultureInfo culture = CultureInfo.CurrentUICulture; - while (culture != null) + // Allow tests to override system culture + if (InternalTestHooks.CurrentUICulture != null) { - if (string.IsNullOrEmpty(culture.Name)) - { - yield break; - } - - yield return culture.Name; - - culture = culture.Parent; + culture = InternalTestHooks.CurrentUICulture; } - yield break; + return CultureSpecificUpdatableHelp.GetCultureFallbackChain(culture); } #region Help Metadata Retrieval @@ -594,13 +588,9 @@ internal UpdatableHelpInfo CreateHelpInfo(string xml, string moduleName, Guid mo if (!string.IsNullOrEmpty(currentCulture)) { - IEnumerable patternList = SessionStateUtilities.CreateWildcardsFromStrings( - globPatterns: new[] { currentCulture }, - options: WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant); - for (int i = 0; i < updatableHelpItem.Length; i++) { - if (SessionStateUtilities.MatchesAnyWildcardPattern(updatableHelpItem[i].Culture.Name, patternList, true)) + if (updatableHelpItem[i].IsCultureSupported(currentCulture)) { helpInfo.HelpContentUriCollection.Add(new UpdatableHelpUri(moduleName, moduleGuid, updatableHelpItem[i].Culture, uri)); } diff --git a/test/powershell/engine/Help/HelpSystem.Tests.ps1 b/test/powershell/engine/Help/HelpSystem.Tests.ps1 index 2786e64ee0e..53ce9ad7494 100644 --- a/test/powershell/engine/Help/HelpSystem.Tests.ps1 +++ b/test/powershell/engine/Help/HelpSystem.Tests.ps1 @@ -30,7 +30,7 @@ function UpdateHelpFromLocalContentPath { throw "Unable to find help content at '$helpContentPath'" } - # Test files are 'en-US', set explicit culture so test does not help on non-US systems + # Test files are 'en-US', set explicit culture so test does not fail on non-US systems Update-Help -Module $ModuleName -SourcePath $helpContentPath -UICulture 'en-US' -Force -ErrorAction Stop -Scope $Scope } @@ -635,3 +635,54 @@ Describe 'help renders when using a PAGER with a space in the path' -Tags 'CI' { help Get-Command | Should -Be "R2V0LUNvbW1hbmQ=" } } + +Describe 'Update-Help allows partial culture matches' -Tags 'CI' { + BeforeAll { + function Test-UpdateHelpAux($UICulture, $Pass) + { + # If null (in system culture tests), omit entirely + $CultureArg = $UICulture ? @{ UICulture = $UICulture } : @{} + $Args = @{ + Module = 'Microsoft.PowerShell.Core' + SourcePath = Join-Path $PSScriptRoot 'assets' + Force = $true + ErrorAction = $Pass ? 'Stop' : 'SilentlyContinue' + ErrorVariable = 'ErrorVariable' + } + + Update-Help @Args @CultureArg + + if (-not $Pass) { + $ErrorVariable | Should -Match 'Failed to update Help for the module.*' + } + } + } + + AfterEach { + [System.Management.Automation.Internal.InternalTestHooks]::SetTestHook('CurrentUICulture', $null) + } + + It 'Checks culture match against en-US: ' -TestCases @( + @{ UICulture = 'en-US' } + @{ UICulture = 'en' } + @{ UICulture = 'en-GB'; Pass = $false } + @{ UICulture = 'de-DE'; Pass = $false } + ) { + param($UICulture, $Pass = $true) + + Test-UpdateHelpAux $UICulture $Pass + } + + # When using system culture, "en-GB" will use "en" as fallback, so passes + It 'Checks system culture match against en-US: ' -TestCases @( + @{ UICulture = 'en-US' } + @{ UICulture = 'en' } + @{ UICulture = 'en-GB' } + @{ UICulture = 'de-DE'; Pass = $false } + ) { + param($UICulture, $Pass = $true) + + [System.Management.Automation.Internal.InternalTestHooks]::SetTestHook('CurrentUICulture', [System.Globalization.CultureInfo]::new($UICulture)) + Test-UpdateHelpAux $null $Pass + } +} From da2a98cdadf97b475e73ce011c2fff8b0303bd33 Mon Sep 17 00:00:00 2001 From: PowerShell Team Bot <69177312+pwshBot@users.noreply.github.com> Date: Tue, 9 May 2023 12:57:43 -0700 Subject: [PATCH 533/779] Update the cgmanifest (#19631) --- tools/cgmanifest.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/tools/cgmanifest.json b/tools/cgmanifest.json index 65f9bddd64c..e6e9958452c 100644 --- a/tools/cgmanifest.json +++ b/tools/cgmanifest.json @@ -1,4 +1,5 @@ { + "$schema": "https://json.schemastore.org/component-detection-manifest.json", "Registrations": [ { "Component": { @@ -35,7 +36,7 @@ "Type": "nuget", "Nuget": { "Name": "Json.More.Net", - "Version": "1.7.0" + "Version": "1.8.0" } }, "DevelopmentDependency": false @@ -45,7 +46,7 @@ "Type": "nuget", "Nuget": { "Name": "JsonPointer.Net", - "Version": "2.2.1" + "Version": "3.0.1" } }, "DevelopmentDependency": false @@ -55,7 +56,7 @@ "Type": "nuget", "Nuget": { "Name": "JsonSchema.Net", - "Version": "3.3.2" + "Version": "4.1.1" } }, "DevelopmentDependency": false @@ -830,6 +831,5 @@ }, "DevelopmentDependency": false } - ], - "$schema": "https://json.schemastore.org/component-detection-manifest.json" + ] } From dc814918705ab9a78548d4068d240f1eb62c54c9 Mon Sep 17 00:00:00 2001 From: MartinGC94 <42123497+MartinGC94@users.noreply.github.com> Date: Wed, 10 May 2023 00:04:44 +0200 Subject: [PATCH 534/779] Improve variable completion performance (#19595) --- .../CommandCompletion/CompletionCompleters.cs | 511 ++++++++++++------ .../TabCompletion/TabCompletion.Tests.ps1 | 23 + 2 files changed, 362 insertions(+), 172 deletions(-) diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs index 1da684732dd..495cf4acea8 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs @@ -12,6 +12,7 @@ using System.Linq; using System.Management.Automation.Internal; using System.Management.Automation.Language; +using System.Management.Automation.Provider; using System.Management.Automation.Runspaces; using System.Reflection; using System.Runtime.InteropServices; @@ -4843,13 +4844,14 @@ public static IEnumerable CompleteVariable(string variableName internal static List CompleteVariable(CompletionContext context) { - HashSet hashedResults = new HashSet(StringComparer.OrdinalIgnoreCase); - List results = new List(); + HashSet hashedResults = new(StringComparer.OrdinalIgnoreCase); + List results = new(); + List tempResults = new(); var wordToComplete = context.WordToComplete; var colon = wordToComplete.IndexOf(':'); - var lastAst = context.RelatedAsts?.Last(); + var lastAst = context.RelatedAsts?[^1]; var variableAst = lastAst as VariableExpressionAst; var prefix = variableAst != null && variableAst.Splatted ? "@" : "$"; bool tokenAtCursorUsedBraces = context.TokenAtCursor is not null && context.TokenAtCursor.Text.StartsWith("${"); @@ -4857,10 +4859,15 @@ internal static List CompleteVariable(CompletionContext contex // Look for variables in the input (e.g. parameters, etc.) before checking session state - these // variables might not exist in session state yet. var wildcardPattern = WildcardPattern.Get(wordToComplete + "*", WildcardOptions.IgnoreCase); - if (lastAst != null) + if (lastAst is not null) { Ast parent = lastAst.Parent; - var findVariablesVisitor = new FindVariablesVisitor { CompletionVariableAst = lastAst }; + var findVariablesVisitor = new FindVariablesVisitor + { + CompletionVariableAst = lastAst, + StopSearchOffset = lastAst.Extent.StartOffset, + Context = context.TypeInferenceContext + }; while (parent != null) { if (parent is IParameterMetadataProvider) @@ -4872,95 +4879,56 @@ internal static List CompleteVariable(CompletionContext contex parent = parent.Parent; } - foreach (Tuple varAst in findVariablesVisitor.VariableSources) + foreach (string varName in findVariablesVisitor.FoundVariables) { - Ast astTarget = null; - string userPath = null; - - VariableExpressionAst variableDefinitionAst = varAst.Item2 as VariableExpressionAst; - if (variableDefinitionAst != null) - { - userPath = varAst.Item1; - astTarget = varAst.Item2.Parent; - } - else + if (!wildcardPattern.IsMatch(varName)) { - CommandAst commandParameterAst = varAst.Item2 as CommandAst; - if (commandParameterAst != null) - { - userPath = varAst.Item1; - astTarget = varAst.Item2; - } - } - - if (string.IsNullOrEmpty(userPath)) - { - Diagnostics.Assert(false, "Found a variable source but it was an unknown AST type."); + continue; } - if (wildcardPattern.IsMatch(userPath)) - { - var completedName = (userPath.IndexOfAny(s_charactersRequiringQuotes) == -1) - ? prefix + userPath - : prefix + "{" + userPath + "}"; - var tooltip = userPath; - var ast = astTarget; - - while (ast != null) - { - var parameterAst = ast as ParameterAst; - if (parameterAst != null) - { - var typeConstraint = parameterAst.Attributes.OfType().FirstOrDefault(); - if (typeConstraint != null) - { - tooltip = StringUtil.Format("{0}${1}", typeConstraint.Extent.Text, userPath); - } - - break; - } - - var assignmentAst = ast.Parent as AssignmentStatementAst; - if (assignmentAst != null) - { - if (assignmentAst.Left == ast) - { - tooltip = ast.Extent.Text; - } + var varInfo = findVariablesVisitor.VariableInfoTable[varName]; + var varType = varInfo.LastDeclaredConstraint ?? varInfo.LastAssignedType; + var toolTip = varType is null + ? varName + : StringUtil.Format("[{0}]${1}", ToStringCodeMethods.Type(varType, dropNamespaces: true), varName); - break; - } - - var commandAst = ast as CommandAst; - if (commandAst != null) - { - PSTypeName discoveredType = AstTypeInference.InferTypeOf(ast, context.TypeInferenceContext, TypeInferenceRuntimePermissions.AllowSafeEval).FirstOrDefault(); - if (discoveredType != null) - { - tooltip = StringUtil.Format("[{0}]${1}", discoveredType.Name, userPath); - } - - break; - } - - ast = ast.Parent; - } - - AddUniqueVariable(hashedResults, results, completedName, userPath, tooltip); - } + var completionText = !tokenAtCursorUsedBraces && varName.IndexOfAny(s_charactersRequiringQuotes) == -1 + ? prefix + varName + : prefix + "{" + varName + "}"; + AddUniqueVariable(hashedResults, results, completionText, varName, toolTip); } } - string pattern; - string provider; if (colon == -1) { - pattern = "variable:" + wordToComplete + "*"; - provider = string.Empty; + var allVariables = context.ExecutionContext.SessionState.Internal.GetVariableTable(); + foreach (var key in allVariables.Keys) + { + if (wildcardPattern.IsMatch(key)) + { + var variable = allVariables[key]; + var name = variable.Name; + var value = variable.Value; + var toolTip = value is null + ? key + : StringUtil.Format("[{0}]${1}", ToStringCodeMethods.Type(value.GetType(), dropNamespaces: true), key); + var completionText = !tokenAtCursorUsedBraces && name.IndexOfAny(s_charactersRequiringQuotes) == -1 + ? prefix + name + : prefix + "{" + name + "}"; + AddUniqueVariable(hashedResults, tempResults, completionText, key, key); + } + } + + if (tempResults.Count > 0) + { + results.AddRange(tempResults.OrderBy(item => item.ListItemText, StringComparer.OrdinalIgnoreCase)); + tempResults.Clear(); + } } else { - provider = wordToComplete.Substring(0, colon + 1); + string provider = wordToComplete.Substring(0, colon + 1); + string pattern; if (s_variableScopes.Contains(provider, StringComparer.OrdinalIgnoreCase)) { pattern = string.Concat("variable:", wordToComplete.AsSpan(colon + 1), "*"); @@ -4969,65 +4937,57 @@ internal static List CompleteVariable(CompletionContext contex { pattern = wordToComplete + "*"; } - } - var powerShellExecutionHelper = context.Helper; - powerShellExecutionHelper - .AddCommandWithPreferenceSetting("Microsoft.PowerShell.Management\\Get-Item").AddParameter("Path", pattern) - .AddCommandWithPreferenceSetting("Microsoft.PowerShell.Utility\\Sort-Object").AddParameter("Property", "Name"); + var powerShellExecutionHelper = context.Helper; + powerShellExecutionHelper + .AddCommandWithPreferenceSetting("Microsoft.PowerShell.Management\\Get-Item").AddParameter("Path", pattern) + .AddCommandWithPreferenceSetting("Microsoft.PowerShell.Utility\\Sort-Object").AddParameter("Property", "Name"); - Exception exceptionThrown; - var psobjs = powerShellExecutionHelper.ExecuteCurrentPowerShell(out exceptionThrown); - if (psobjs != null) - { - foreach (dynamic psobj in psobjs) + var psobjs = powerShellExecutionHelper.ExecuteCurrentPowerShell(out _); + + if (psobjs is not null) { - var name = psobj.Name as string; - if (!string.IsNullOrEmpty(name)) + foreach (dynamic psobj in psobjs) { - var tooltip = name; - var variable = PSObject.Base(psobj) as PSVariable; - if (variable != null) + var name = psobj.Name as string; + if (!string.IsNullOrEmpty(name)) { - var value = variable.Value; - if (value != null) + var tooltip = name; + var variable = PSObject.Base(psobj) as PSVariable; + if (variable != null) { - tooltip = StringUtil.Format("[{0}]${1}", - ToStringCodeMethods.Type(value.GetType(), - dropNamespaces: true), name); + var value = variable.Value; + if (value != null) + { + tooltip = StringUtil.Format("[{0}]${1}", + ToStringCodeMethods.Type(value.GetType(), + dropNamespaces: true), name); + } } - } - var completedName = (!tokenAtCursorUsedBraces && name.IndexOfAny(s_charactersRequiringQuotes) == -1) - ? prefix + provider + name - : prefix + "{" + provider + name + "}"; - AddUniqueVariable(hashedResults, results, completedName, name, tooltip); + var completedName = !tokenAtCursorUsedBraces && name.IndexOfAny(s_charactersRequiringQuotes) == -1 + ? prefix + provider + name + : prefix + "{" + provider + name + "}"; + AddUniqueVariable(hashedResults, results, completedName, name, tooltip); + } } } } if (colon == -1 && "env".StartsWith(wordToComplete, StringComparison.OrdinalIgnoreCase)) { - powerShellExecutionHelper - .AddCommandWithPreferenceSetting("Microsoft.PowerShell.Management\\Get-Item").AddParameter("Path", "env:*") - .AddCommandWithPreferenceSetting("Microsoft.PowerShell.Utility\\Sort-Object").AddParameter("Property", "Key"); - - psobjs = powerShellExecutionHelper.ExecuteCurrentPowerShell(out exceptionThrown); - if (psobjs != null) + var envVars = Environment.GetEnvironmentVariables(); + foreach (var key in envVars.Keys) { - foreach (dynamic psobj in psobjs) - { - var name = psobj.Name as string; - if (!string.IsNullOrEmpty(name)) - { - name = "env:" + name; - var completedName = (!tokenAtCursorUsedBraces && name.IndexOfAny(s_charactersRequiringQuotes) == -1) - ? prefix + name - : prefix + "{" + name + "}"; - AddUniqueVariable(hashedResults, results, completedName, name, "[string]" + name); - } - } + var name = "env:" + key; + var completedName = !tokenAtCursorUsedBraces && name.IndexOfAny(s_charactersRequiringQuotes) == -1 + ? prefix + name + : prefix + "{" + name + "}"; + AddUniqueVariable(hashedResults, tempResults, completedName, name, "[string]" + name); } + + results.AddRange(tempResults.OrderBy(item => item.ListItemText, StringComparer.OrdinalIgnoreCase)); + tempResults.Clear(); } // Return variables already in session state first, because we can sometimes give better information, @@ -5036,7 +4996,7 @@ internal static List CompleteVariable(CompletionContext contex { if (wildcardPattern.IsMatch(specialVariable)) { - var completedName = (!tokenAtCursorUsedBraces && specialVariable.IndexOfAny(s_charactersRequiringQuotes) == -1) + var completedName = !tokenAtCursorUsedBraces && specialVariable.IndexOfAny(s_charactersRequiringQuotes) == -1 ? prefix + specialVariable : prefix + "{" + specialVariable + "}"; @@ -5046,41 +5006,37 @@ internal static List CompleteVariable(CompletionContext contex if (colon == -1) { - // If no drive was specified, then look for matching drives/scopes - pattern = wordToComplete + "*"; - powerShellExecutionHelper - .AddCommandWithPreferenceSetting("Microsoft.PowerShell.Management\\Get-PSDrive").AddParameter("Name", pattern) - .AddCommandWithPreferenceSetting("Microsoft.PowerShell.Utility\\Sort-Object").AddParameter("Property", "Name"); - psobjs = powerShellExecutionHelper.ExecuteCurrentPowerShell(out exceptionThrown); - if (psobjs != null) + var allDrives = context.ExecutionContext.SessionState.Drive.GetAll(); + foreach (var drive in allDrives) { - foreach (var psobj in psobjs) + if (drive.Name.Length < 2 + || !wildcardPattern.IsMatch(drive.Name) + || !drive.Provider.ImplementingType.IsAssignableTo(typeof(IContentCmdletProvider))) { - var driveInfo = PSObject.Base(psobj) as PSDriveInfo; - if (driveInfo != null) - { - var name = driveInfo.Name; - if (name != null && !string.IsNullOrWhiteSpace(name) && name.Length > 1) - { - var completedName = (!tokenAtCursorUsedBraces && name.IndexOfAny(s_charactersRequiringQuotes) == -1) - ? prefix + name + ":" - : prefix + "{" + name + ":}"; - - var tooltip = string.IsNullOrEmpty(driveInfo.Description) ? name : driveInfo.Description; - AddUniqueVariable(hashedResults, results, completedName, name, tooltip); - } - } + continue; } + + var completedName = !tokenAtCursorUsedBraces && drive.Name.IndexOfAny(s_charactersRequiringQuotes) == -1 + ? prefix + drive.Name + ":" + : prefix + "{" + drive.Name + ":}"; + var tooltip = string.IsNullOrEmpty(drive.Description) + ? drive.Name + : drive.Description; + AddUniqueVariable(hashedResults, tempResults, completedName, drive.Name, tooltip); + } + + if (tempResults.Count > 0) + { + results.AddRange(tempResults.OrderBy(item => item.ListItemText, StringComparer.OrdinalIgnoreCase)); } - var scopePattern = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase); foreach (var scope in s_variableScopes) { - if (scopePattern.IsMatch(scope)) + if (wildcardPattern.IsMatch(scope)) { - var completedName = (!tokenAtCursorUsedBraces && scope.IndexOfAny(s_charactersRequiringQuotes) == -1) - ? prefix + scope - : prefix + "{" + scope + "}"; + var completedName = !tokenAtCursorUsedBraces && scope.IndexOfAny(s_charactersRequiringQuotes) == -1 + ? prefix + scope + : prefix + "{" + scope + "}"; AddUniqueVariable(hashedResults, results, completedName, scope, scope); } } @@ -5091,24 +5047,170 @@ internal static List CompleteVariable(CompletionContext contex private static void AddUniqueVariable(HashSet hashedResults, List results, string completionText, string listItemText, string tooltip) { - if (!hashedResults.Contains(completionText)) + if (hashedResults.Add(completionText)) { - hashedResults.Add(completionText); results.Add(new CompletionResult(completionText, listItemText, CompletionResultType.Variable, tooltip)); } } + private static readonly HashSet s_varModificationCommands = new(StringComparer.OrdinalIgnoreCase) + { + "New-Variable", + "nv", + "Set-Variable", + "set", + "sv" + }; + + private static readonly string[] s_varModificationParameters = new string[] + { + "Name", + "Value" + }; + + private static readonly string[] s_outVarParameters = new string[] + { + "ErrorVariable", + "ev", + "WarningVariable", + "wv", + "InformationVariable", + "iv", + "OutVariable", + "ov", + + }; + + private static readonly string[] s_pipelineVariableParameters = new string[] + { + "PipelineVariable", + "pv" + }; + + private sealed class VariableInfo + { + internal Type LastDeclaredConstraint; + internal Type LastAssignedType; + } + private sealed class FindVariablesVisitor : AstVisitor { internal Ast Top; internal Ast CompletionVariableAst; - internal readonly List> VariableSources = new List>(); + internal readonly List FoundVariables = new(); + internal readonly Dictionary VariableInfoTable = new(StringComparer.OrdinalIgnoreCase); + internal int StopSearchOffset; + internal TypeInferenceContext Context; + + private static Type GetInferredVarTypeFromAst(Ast ast) + { + Type type; + switch (ast) + { + case ConstantExpressionAst constant: + type = constant.StaticType; + break; + + case ExpandableStringExpressionAst: + type = typeof(string); + break; + + case ConvertExpressionAst convertExpression: + type = convertExpression.StaticType; + break; + + case HashtableAst: + type = typeof(Hashtable); + break; + + case ArrayExpressionAst: + case ArrayLiteralAst: + type = typeof(object[]); + break; + + case ScriptBlockExpressionAst: + type = typeof(ScriptBlock); + break; + + default: + type = null; + break; + } + + return type; + } + + private void SaveVariableInfo(string variableName, Type variableType, bool isConstraint) + { + VariableInfo varInfo; + if (VariableInfoTable.TryGetValue(variableName, out varInfo)) + { + if (isConstraint) + { + varInfo.LastDeclaredConstraint = variableType; + } + else + { + varInfo.LastAssignedType = variableType; + } + } + else + { + varInfo = isConstraint + ? new VariableInfo() { LastDeclaredConstraint = variableType } + : new VariableInfo() { LastAssignedType = variableType }; + VariableInfoTable.Add(variableName, varInfo); + FoundVariables.Add(variableName); + } + } - public override AstVisitAction VisitVariableExpression(VariableExpressionAst variableExpressionAst) + public override AstVisitAction DefaultVisit(Ast ast) { - if (variableExpressionAst != CompletionVariableAst) + if (ast.Extent.StartOffset > StopSearchOffset) + { + return AstVisitAction.StopVisit; + } + + return AstVisitAction.Continue; + } + + public override AstVisitAction VisitAssignmentStatement(AssignmentStatementAst assignmentStatementAst) + { + if (assignmentStatementAst.Extent.StartOffset > StopSearchOffset) + { + return AstVisitAction.StopVisit; + } + + if (assignmentStatementAst.Left is ConvertExpressionAst convertExpression) + { + if (convertExpression.Child is VariableExpressionAst variableExpression) + { + if (variableExpression == CompletionVariableAst || s_specialVariablesCache.Value.Contains(variableExpression.VariablePath.UserPath)) + { + return AstVisitAction.Continue; + } + + SaveVariableInfo(variableExpression.VariablePath.UserPath, convertExpression.StaticType, isConstraint: true); + } + } + else if (assignmentStatementAst.Left is VariableExpressionAst variableExpression) { - VariableSources.Add(new Tuple(variableExpressionAst.VariablePath.UserPath, variableExpressionAst)); + if (variableExpression == CompletionVariableAst || s_specialVariablesCache.Value.Contains(variableExpression.VariablePath.UserPath)) + { + return AstVisitAction.Continue; + } + + Type lastAssignedType; + if (assignmentStatementAst.Right is CommandExpressionAst commandExpression) + { + lastAssignedType = GetInferredVarTypeFromAst(commandExpression.Expression); + } + else + { + lastAssignedType = null; + } + + SaveVariableInfo(variableExpression.VariablePath.UserPath, lastAssignedType, isConstraint: false); } return AstVisitAction.Continue; @@ -5116,25 +5218,66 @@ public override AstVisitAction VisitVariableExpression(VariableExpressionAst var public override AstVisitAction VisitCommand(CommandAst commandAst) { - // MSFT: 784739 Stack overflow during tab completion of pipeline variable - // $null | % -pv p { $p -> In this case $p is pipelinevariable - // and is used in the same command. PipelineVariables are not available - // in the command they are assigned in. Hence the following code ignores - // if the variable being completed is in the command extent. - if ((commandAst != CompletionVariableAst) && (!CompletionVariableAst.Extent.IsWithin(commandAst.Extent))) + if (commandAst.Extent.StartOffset > StopSearchOffset) { - string[] desiredParameters = new string[] { "PV", "PipelineVariable", "OV", "OutVariable" }; + return AstVisitAction.StopVisit; + } + + var commandName = commandAst.GetCommandName(); + if (commandName is not null && s_varModificationCommands.Contains(commandName)) + { + StaticBindingResult bindingResult = StaticParameterBinder.BindCommand(commandAst, resolve: false, s_varModificationParameters); + if (bindingResult is not null + && bindingResult.BoundParameters.TryGetValue("Name", out ParameterBindingResult variableName)) + { + var nameValue = variableName.ConstantValue as string; + if (nameValue is not null) + { + Type variableType; + if (bindingResult.BoundParameters.TryGetValue("Value", out ParameterBindingResult variableValue)) + { + variableType = GetInferredVarTypeFromAst(variableValue.Value); + } + else + { + variableType = null; + } + + SaveVariableInfo(nameValue, variableType, isConstraint: false); + } + } + } - StaticBindingResult bindingResult = StaticParameterBinder.BindCommand(commandAst, false, desiredParameters); - if (bindingResult != null) + var bindResult = StaticParameterBinder.BindCommand(commandAst, resolve: false); + if (bindResult is not null) + { + foreach (var parameterName in s_outVarParameters) { - ParameterBindingResult parameterBindingResult; + if (bindResult.BoundParameters.TryGetValue(parameterName, out ParameterBindingResult outVarBind)) + { + var varName = outVarBind.ConstantValue as string; + if (varName is not null) + { + SaveVariableInfo(varName, typeof(ArrayList), isConstraint: false); + } + } + } - foreach (string commandVariableParameter in desiredParameters) + if (commandAst.Parent is PipelineAst pipeline && pipeline.Extent.EndOffset > CompletionVariableAst.Extent.StartOffset) + { + foreach (var parameterName in s_pipelineVariableParameters) { - if (bindingResult.BoundParameters.TryGetValue(commandVariableParameter, out parameterBindingResult)) + if (bindResult.BoundParameters.TryGetValue(parameterName, out ParameterBindingResult pipeVarBind)) { - VariableSources.Add(new Tuple((string)parameterBindingResult.ConstantValue, commandAst)); + var varName = pipeVarBind.ConstantValue as string; + if (varName is not null) + { + var inferredTypes = AstTypeInference.InferTypeOf(commandAst, Context, TypeInferenceRuntimePermissions.AllowSafeEval); + Type varType = inferredTypes.Count == 0 + ? null + : inferredTypes[0].Type; + SaveVariableInfo(varName, varType, isConstraint: false); + } } } } @@ -5143,6 +5286,30 @@ public override AstVisitAction VisitCommand(CommandAst commandAst) return AstVisitAction.Continue; } + public override AstVisitAction VisitParameter(ParameterAst parameterAst) + { + if (parameterAst.Extent.StartOffset > StopSearchOffset) + { + return AstVisitAction.StopVisit; + } + + VariableExpressionAst variableExpression = parameterAst.Name; + if (variableExpression == CompletionVariableAst) + { + return AstVisitAction.Continue; + } + + SaveVariableInfo(variableExpression.VariablePath.UserPath, parameterAst.StaticType, isConstraint: true); + + return AstVisitAction.Continue; + } + + public override AstVisitAction VisitAttribute(AttributeAst attributeAst) + { + // Attributes can't assign values to variables so they aren't interesting. + return AstVisitAction.SkipChildren; + } + public override AstVisitAction VisitFunctionDefinition(FunctionDefinitionAst functionDefinitionAst) { return functionDefinitionAst != Top ? AstVisitAction.SkipChildren : AstVisitAction.Continue; @@ -5163,7 +5330,7 @@ public override AstVisitAction VisitScriptBlock(ScriptBlockAst scriptBlockAst) private static SortedSet BuildSpecialVariablesCache() { - var result = new SortedSet(); + var result = new SortedSet(StringComparer.OrdinalIgnoreCase); foreach (var member in typeof(SpecialVariables).GetFields(BindingFlags.NonPublic | BindingFlags.Static)) { if (member.FieldType.Equals(typeof(string))) diff --git a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 index f5b2a573c06..0fbe72a0c00 100644 --- a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 +++ b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 @@ -695,6 +695,29 @@ ConstructorTestClass(int i, bool b) $res.CompletionMatches[0].CompletionText | Should -BeExactly 'CommandType' } + It 'Should not complete variables that appear after the cursor' { + $TestString = '$TestVar1 = 1; $TestVar^ ; $TestVar2 = 2' + $CursorIndex = $TestString.IndexOf('^') + $res = TabExpansion2 -cursorColumn $CursorIndex -inputScript $TestString.Remove($CursorIndex, 1) + $res | Should -HaveCount 1 + $res.CompletionMatches[0].CompletionText | Should -BeExactly '$TestVar1' + } + + It 'Should not complete pipeline variables outside the pipeline' { + $TestString = 'Get-ChildItem -PipelineVariable TestVar1;$TestVar^' + $CursorIndex = $TestString.IndexOf('^') + $res = TabExpansion2 -cursorColumn $CursorIndex -inputScript $TestString.Remove($CursorIndex, 1) + $res.CompletionMatches | Should -HaveCount 0 + } + + It 'Should complete pipeline variables inside the pipeline' { + $TestString = 'Get-ChildItem -PipelineVariable TestVar1 | ForEach-Object -Process {$TestVar^}' + $CursorIndex = $TestString.IndexOf('^') + $res = TabExpansion2 -cursorColumn $CursorIndex -inputScript $TestString.Remove($CursorIndex, 1) + $res | Should -HaveCount 1 + $res.CompletionMatches[0].CompletionText | Should -BeExactly '$TestVar1' + } + Context "Format cmdlet's View paramter completion" { BeforeAll { $viewDefinition = @' From 65327256bf53d1e91457f0cf28780c26b088eda8 Mon Sep 17 00:00:00 2001 From: Steven Bucher Date: Tue, 9 May 2023 16:16:06 -0700 Subject: [PATCH 535/779] Updated the public dashboard link (#19634) --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 879695d8d04..c66570eade2 100644 --- a/README.md +++ b/README.md @@ -137,7 +137,7 @@ To install a specific version, visit [releases](https://github.com/PowerShell/Po ## Community Dashboard -[Dashboard](https://aka.ms/psgithubbi) with visualizations for community contributions and project status using PowerShell, Azure, and PowerBI. +[Dashboard](https://aka.ms/PSPublicDashboard) with visualizations for community contributions and project status using PowerShell, Azure, and PowerBI. For more information on how and why we built this dashboard, check out this [blog post](https://devblogs.microsoft.com/powershell/powershell-open-source-community-dashboard/). From 7144ec707df7dfc531dd0ccbefa885e34c3b9d3f Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Tue, 9 May 2023 22:36:34 -0700 Subject: [PATCH 536/779] Add ProductCode in registry for MSI install (#19590) * Add ProductCode in registry for MSI install * Add test for validating ProductCode regkey is created * Add test better validation --- assets/wix/Product.wxs | 2 ++ test/packaging/windows/msi.tests.ps1 | 26 ++++++++++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/assets/wix/Product.wxs b/assets/wix/Product.wxs index 976a12d1425..30318916544 100644 --- a/assets/wix/Product.wxs +++ b/assets/wix/Product.wxs @@ -205,7 +205,9 @@ + + diff --git a/test/packaging/windows/msi.tests.ps1 b/test/packaging/windows/msi.tests.ps1 index 71254d287bc..93a56821003 100644 --- a/test/packaging/windows/msi.tests.ps1 +++ b/test/packaging/windows/msi.tests.ps1 @@ -144,27 +144,32 @@ Describe -Name "Windows MSI" -Fixture { Write-Verbose "cr-$channel-$runtime" -Verbose $pwshPath = Join-Path $env:ProgramFiles -ChildPath "PowerShell" $pwshx86Path = Join-Path ${env:ProgramFiles(x86)} -ChildPath "PowerShell" + $regKeyPath = "HKLM:\SOFTWARE\Microsoft\PowerShellCore\InstalledVersions" switch ("$channel-$runtime") { "preview-win7-x64" { $versionPath = Join-Path -Path $pwshPath -ChildPath '7-preview' $revisionRange = 0, 99 $msiUpgradeCode = '39243d76-adaf-42b1-94fb-16ecf83237c8' + $regKeyPath = Join-Path $regKeyPath -ChildPath $msiUpgradeCode } "stable-win7-x64" { $versionPath = Join-Path -Path $pwshPath -ChildPath '7' $revisionRange = 500, 500 $msiUpgradeCode = '31ab5147-9a97-4452-8443-d9709f0516e1' + $regKeyPath = Join-Path $regKeyPath -ChildPath $msiUpgradeCode } "preview-win7-x86" { $versionPath = Join-Path -Path $pwshx86Path -ChildPath '7-preview' $revisionRange = 0, 99 $msiUpgradeCode = '86abcfbd-1ccc-4a88-b8b2-0facfde29094' + $regKeyPath = Join-Path $regKeyPath -ChildPath $msiUpgradeCode } "stable-win7-x86" { $versionPath = Join-Path -Path $pwshx86Path -ChildPath '7' $revisionRange = 500, 500 $msiUpgradeCode = '1d00683b-0f84-4db8-a64f-2f98ad42fe06' + $regKeyPath = Join-Path $regKeyPath -ChildPath $msiUpgradeCode } default { throw "'$_' not a valid channel runtime combination" @@ -196,6 +201,27 @@ Describe -Name "Windows MSI" -Fixture { $version.Revision | Should -BeLessOrEqual $revisionRange[1] -Because "$channel revision should between $($revisionRange[0]) and $($revisionRange[1])" } + It 'MSI should add ProductCode in registry' -Skip:(!(Test-Elevated)) { + + $productCode = if ($msiUpgradeCode -eq '39243d76-adaf-42b1-94fb-16ecf83237c8' -or + $msiUpgradeCode -eq '31ab5147-9a97-4452-8443-d9709f0516e1') { + # x64 + $regKeyPath | Should -Exist + Get-ItemPropertyValue -Path $regKeyPath -Name 'ProductCode' + } elseif ($msiUpgradeCode -eq '86abcfbd-1ccc-4a88-b8b2-0facfde29094' -or + $msiUpgradeCode -eq '1d00683b-0f84-4db8-a64f-2f98ad42fe06') { + # x86 - need to open the 32bit reghive + $wow32RegKey = [Microsoft.Win32.RegistryKey]::OpenBaseKey([Microsoft.Win32.RegistryHive]::LocalMachine, [Microsoft.Win32.RegistryView]::Registry32) + $subKey = $wow32RegKey.OpenSubKey("Software\Microsoft\PowerShellCore\InstalledVersions\$msiUpgradeCode") + $subKey.GetValue("ProductCode") + } + + $productCode | Should -Not -BeNullOrEmpty + $productCodeGuid = [Guid]$productCode + $productCodeGuid | Should -BeOfType "Guid" + $productCodeGuid.Guid | Should -Not -Be $msiUpgradeCode + } + It "MSI should uninstall without error" -Skip:(!(Test-Elevated)) { { Invoke-MsiExec -Uninstall -MsiPath $msiX64Path From bb3c8a2819600a6c77e9f18b974a39795f88ec73 Mon Sep 17 00:00:00 2001 From: MartinGC94 <42123497+MartinGC94@users.noreply.github.com> Date: Wed, 10 May 2023 22:56:33 +0200 Subject: [PATCH 537/779] Fix an indexing out of bound error in `CompleteInput` for empty script input (#19501) --- .../engine/CommandCompletion/CommandCompletion.cs | 14 ++++++++++++-- .../engine/CommandCompletion/CompletionAnalysis.cs | 5 +++++ .../engine/InitialSessionState.cs | 3 ++- .../Host/TabCompletion/TabCompletion.Tests.ps1 | 8 ++++++++ 4 files changed, 27 insertions(+), 3 deletions(-) diff --git a/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs b/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs index c40e3bdc8fb..12ff1e05993 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs @@ -91,7 +91,7 @@ public static Tuple MapStringInputToParsedInput(s /// public static CommandCompletion CompleteInput(string input, int cursorIndex, Hashtable options) { - if (input == null) + if (input == null || input.Length == 0) { return s_emptyCommandCompletion; } @@ -124,6 +124,11 @@ public static CommandCompletion CompleteInput(Ast ast, Token[] tokens, IScriptPo throw PSTraceSource.NewArgumentNullException(nameof(positionOfCursor)); } + if (ast.Extent.Text.Length == 0) + { + return s_emptyCommandCompletion; + } + return CompleteInputImpl(ast, tokens, positionOfCursor, options); } @@ -138,7 +143,7 @@ public static CommandCompletion CompleteInput(Ast ast, Token[] tokens, IScriptPo [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "powershell")] public static CommandCompletion CompleteInput(string input, int cursorIndex, Hashtable options, PowerShell powershell) { - if (input == null) + if (input == null || input.Length == 0) { return s_emptyCommandCompletion; } @@ -221,6 +226,11 @@ public static CommandCompletion CompleteInput(Ast ast, Token[] tokens, IScriptPo throw PSTraceSource.NewArgumentNullException(nameof(powershell)); } + if (ast.Extent.Text.Length == 0) + { + return s_emptyCommandCompletion; + } + // If we are in a debugger stop, let the debugger do the command completion. var debugger = powershell.Runspace?.Debugger; if ((debugger != null) && debugger.InBreakpoint) diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs index 9315880138a..4f02f251623 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs @@ -155,6 +155,11 @@ internal static AstAnalysisContext ExtractAstContext(Ast inputAst, Token[] input ast => IsCursorWithinOrJustAfterExtent(positionForAstSearch, ast.Extent), searchNestedScriptBlocks: true).ToList(); + if (relatedAsts.Count == 0) + { + relatedAsts.Add(inputAst); + } + // If the last ast is an unnamed block that starts with "param" the cursor is inside a param block. // To avoid adding special handling to all the completers that look at the last ast, we remove it here because it's not useful for completion. if (relatedAsts[^1].Extent.Text.StartsWith("param", StringComparison.OrdinalIgnoreCase) diff --git a/src/System.Management.Automation/engine/InitialSessionState.cs b/src/System.Management.Automation/engine/InitialSessionState.cs index 4cf2bc44e35..d5cdfe1ebaa 100644 --- a/src/System.Management.Automation/engine/InitialSessionState.cs +++ b/src/System.Management.Automation/engine/InitialSessionState.cs @@ -4044,6 +4044,7 @@ internal void ImportCmdletsFromAssembly(Assembly assembly, PSModuleInfo module) [OutputType([System.Management.Automation.CommandCompletion])] Param( [Parameter(ParameterSetName = 'ScriptInputSet', Mandatory = $true, Position = 0)] + [AllowEmptyString()] [string] $inputScript, [Parameter(ParameterSetName = 'ScriptInputSet', Position = 1)] @@ -4081,7 +4082,7 @@ internal void ImportCmdletsFromAssembly(Assembly assembly, PSModuleInfo module) <#options#> $options) } } - "; +"; /// /// This is the default function to use for clear-host. diff --git a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 index 0fbe72a0c00..6dcc6964e9b 100644 --- a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 +++ b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 @@ -2050,6 +2050,14 @@ dir -Recurse ` param($inputStr, $expected) $inputStr | Should -Throw -ErrorId $expected } + + It "Should not throw errors in tab completion with empty input string" { + {[System.Management.Automation.CommandCompletion]::CompleteInput("", 0, $null)} | Should -Not -Throw + } + + It "Should not throw errors in tab completion with empty input ast" { + {[System.Management.Automation.CommandCompletion]::CompleteInput({}.Ast, @(), {}.Ast.Extent.StartScriptPosition, $null)} | Should -Not -Throw + } } Context "DSC tab completion tests" { From a533cefc8be51296444380b5e1ba98cb5c08d4b4 Mon Sep 17 00:00:00 2001 From: "James Truher [MSFT]" Date: Thu, 11 May 2023 14:07:56 -0700 Subject: [PATCH 538/779] Change logic for testing missing or extra cmdlets. (#19635) --- test/powershell/engine/Basic/DefaultCommands.Tests.ps1 | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/test/powershell/engine/Basic/DefaultCommands.Tests.ps1 b/test/powershell/engine/Basic/DefaultCommands.Tests.ps1 index 193b16cf2cb..065f960b0e0 100644 --- a/test/powershell/engine/Basic/DefaultCommands.Tests.ps1 +++ b/test/powershell/engine/Basic/DefaultCommands.Tests.ps1 @@ -613,9 +613,12 @@ Describe "Verify aliases and cmdlets" -Tags "CI" { } It "All approved Cmdlets present (no new Cmdlets added, no Cmdlets removed)" { - $observedCmdletNames = $currentCmdletList.ForEach({"{0}" -f $_.Name}) | Sort-Object - $expectedCmdletNames = $commandHashTableList.ForEach({"{0}" -f $_.Name}) | Sort-Object - $observedCmdletNames | Should -Be $expectedCmdletNames + $observedCmdletNames = $currentCmdletList.ForEach({"{0}" -f $_.Name}) + $expectedCmdletNames = $commandHashTableList.ForEach({"{0}" -f $_.Name}) + $extraCmds = $observedCmdletNames.Where({$expectedCmdletNames -notcontains $_}) + $missedCmds = $expectedCmdletNames.Where({$observedCmdletNames -notcontains $_}) + $extraCmds | Should -HaveCount 0 -Because "Extra cmdlets $($extraCmds -join ',')" + $missedCmds | Should -HaveCount 0 -Because "Missed cmdlets $($missedCmds -join ',')" } It "'' Cmdlet should have the correct ConfirmImpact ''" -TestCases $commandHashtableList { From fef05d1a9b480bee2a7fa0058774fb669c4241e1 Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Thu, 11 May 2023 15:50:29 -0700 Subject: [PATCH 539/779] Skip file signature tests on 2012R2 where PKI cmdlet do not work (#19643) --- .../engine/Security/FileSignature.Tests.ps1 | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/test/powershell/engine/Security/FileSignature.Tests.ps1 b/test/powershell/engine/Security/FileSignature.Tests.ps1 index 948ff4d1a8b..7a67d4ac513 100644 --- a/test/powershell/engine/Security/FileSignature.Tests.ps1 +++ b/test/powershell/engine/Security/FileSignature.Tests.ps1 @@ -22,9 +22,15 @@ Describe "Windows platform file signatures" -Tags 'Feature' { } Describe "Windows file content signatures" -Tags @('Feature', 'RequireAdminOnWindows') { - $PSDefaultParameterValues = @{ "It:Skip" = (-not $IsWindows) } + $shouldSkip = (-not $IsWindows) -or (Test-IsWinServer2012R2) + + $PSDefaultParameterValues = @{ "It:Skip" = $shouldSkip } BeforeAll { + if ($shouldSkip) { + return + } + $session = New-PSSession -UseWindowsPowerShell try { # New-SelfSignedCertificate runs in implicit remoting so do all the @@ -83,6 +89,11 @@ Describe "Windows file content signatures" -Tags @('Feature', 'RequireAdminOnWin } AfterAll { + + if ($shouldSkip) { + return + } + Remove-Item -Path Cert:\LocalMachine\Root\$caRootThumbprint -Force Remove-Item -Path Cert:\LocalMachine\TrustedPublisher\$signingThumbprint -Force Remove-Item -Path Cert:\CurrentUser\My\$signingThumbprint -Force From 6a05ccbef9fd8144a672020d638750373f1e38dc Mon Sep 17 00:00:00 2001 From: PowerShell Team Bot <69177312+pwshBot@users.noreply.github.com> Date: Sun, 14 May 2023 23:08:28 -0700 Subject: [PATCH 540/779] Update to the latest NOTICES file (#19644) --- ThirdPartyNotices.txt | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/ThirdPartyNotices.txt b/ThirdPartyNotices.txt index 93727a5bedc..c666d530bbb 100644 --- a/ThirdPartyNotices.txt +++ b/ThirdPartyNotices.txt @@ -172,9 +172,11 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI --------------------------------------------------------- -Json.More.Net 1.7.0 - MIT +Json.More.Net 1.8.0 - MIT +(c) Microsoft 2023 +Copyright (c) 2022 Greg Dennis MIT License @@ -203,13 +205,15 @@ SOFTWARE. --------------------------------------------------------- -JsonPointer.Net 2.2.1 - MIT +JsonPointer.Net 3.0.1 - MIT +(c) Microsoft 2023 +Copyright (c) 2022 Greg Dennis MIT License -Copyright (c) 2020 Greg Dennis +Copyright (c) 2022 Greg Dennis Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -234,10 +238,10 @@ SOFTWARE. --------------------------------------------------------- -JsonSchema.Net 3.3.2 - MIT +JsonSchema.Net 4.1.1 - MIT -(c) Microsoft 2022 +(c) Microsoft 2023 Copyright (c) 2022 Greg Dennis MIT License From 2e2b7db0924e6b6d37a2f57bdf2a2926e3bb8d77 Mon Sep 17 00:00:00 2001 From: MartinGC94 <42123497+MartinGC94@users.noreply.github.com> Date: Mon, 15 May 2023 19:15:05 +0200 Subject: [PATCH 541/779] Fix wildcard globing in root of device paths (#19442) --- .../engine/Utils.cs | 11 +++++- .../namespaces/FileSystemProvider.cs | 10 +++++ .../FileSystem.Tests.ps1 | 37 +++++++++++++++++++ 3 files changed, 57 insertions(+), 1 deletion(-) diff --git a/src/System.Management.Automation/engine/Utils.cs b/src/System.Management.Automation/engine/Utils.cs index c70eb34cdf5..f5af933e00f 100644 --- a/src/System.Management.Automation/engine/Utils.cs +++ b/src/System.Management.Automation/engine/Utils.cs @@ -1241,7 +1241,7 @@ internal static bool PathIsUnc(string path, bool networkOnly = false) } // handle special cases like '\\wsl$\ubuntu', '\\?\', and '\\.\pipe\' which aren't a UNC path, but we can say it is so the filesystemprovider can use it - if (!networkOnly && (path.StartsWith(WslRootPath, StringComparison.OrdinalIgnoreCase) || path.StartsWith("\\\\?\\") || path.StartsWith("\\\\.\\"))) + if (!networkOnly && (path.StartsWith(WslRootPath, StringComparison.OrdinalIgnoreCase) || PathIsDevicePath(path))) { return true; } @@ -1251,6 +1251,15 @@ internal static bool PathIsUnc(string path, bool networkOnly = false) #endif } + internal static bool PathIsDevicePath(string path) + { +#if UNIX + return false; +#else + return path.StartsWith(@"\\.\") || path.StartsWith(@"\\?\"); +#endif + } + internal static readonly string PowerShellAssemblyStrongNameFormat = "{0}, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index 48cce0aeb75..014db73e959 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -4915,7 +4915,17 @@ protected override string GetParentPath(string path, string root) // make sure we return two backslashes so it still results in a UNC path parentPath = "\\\\"; } + + if (!parentPath.EndsWith(StringLiterals.DefaultPathSeparator) + && Utils.PathIsDevicePath(parentPath) + && parentPath.Length - parentPath.Replace(StringLiterals.DefaultPathSeparatorString, string.Empty).Length == 3) + { + // Device paths start with either "\\.\" or "\\?\" + // When referring to the root, like: "\\.\CDROM0\" then it needs the trailing separator to be valid. + parentPath += StringLiterals.DefaultPathSeparator; + } #endif + s_tracer.WriteLine("GetParentPath returning '{0}'", parentPath); return parentPath; } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/FileSystem.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/FileSystem.Tests.ps1 index 67cd1d18894..f7c069f2453 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/FileSystem.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/FileSystem.Tests.ps1 @@ -529,6 +529,43 @@ Describe "Handling of globbing patterns" -Tags "CI" { Test-Path -LiteralPath $testPath2 | Should -BeTrue } } + + Context "Device paths" { + # The globber is overly greedy somewhere so you need to escape the escape backtick to preserve the question mark issue https://github.com/PowerShell/PowerShell/issues/19627 + It "Handle device paths: " -Skip:(!$IsWindows) -TestCases @( + @{ path = "\\.\${env:SystemDrive}\" } + @{ path = "\\.\${env:SystemDrive}\*" } + @{ path = "\\``?\${env:SystemDrive}\" } + @{ path = "\\``?\${env:SystemDrive}\*" } + ) { + param($path) + $expected = Get-ChildItem -Path ${env:SystemDrive}\ + $result = Get-ChildItem -Path $path + $result.Count | Should -Be $expected.Count + } + + It "Handle folders within a device path: " -Skip:(!$IsWindows) -TestCases @( + @{ path = "\\.\${env:SystemRoot}\" } + @{ path = "\\.\${env:SystemRoot}\*" } + @{ path = "\\``?\${env:SystemRoot}\" } + @{ path = "\\``?\${env:SystemRoot}\*" } + ) { + param($path) + $expected = Get-ChildItem -Path ${env:SystemRoot} + $result = Get-ChildItem -Path $path + $result.Count | Should -Be $expected.Count + } + + It "Fails for invalid device path: " -Skip:(!$IsWindows) -TestCases @( + @{ path = "\\.\INVALID0\" } + @{ path = "\\``?\INVALID0\" } + # @{ path = "\\.\INVALID0\*" } // problem in globber where this fails but is ignored issue https://github.com/PowerShell/PowerShell/issues/19626 + # @{ path = "\\``?\INVALID0\*" } + ) { + param($path) + { Get-ChildItem -Path $path -ErrorAction Stop } | Should -Throw -ErrorId 'PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand' + } + } } Describe "Hard link and symbolic link tests" -Tags "CI", "RequireAdminOnWindows" { From c444645b0941d73dc769f0bba6ab70d317bd51a9 Mon Sep 17 00:00:00 2001 From: "James Truher [MSFT]" Date: Mon, 15 May 2023 10:25:12 -0700 Subject: [PATCH 542/779] Change how 'isPreview' is determined for default cmdlets tests (#19650) --- test/powershell/engine/Basic/DefaultCommands.Tests.ps1 | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/test/powershell/engine/Basic/DefaultCommands.Tests.ps1 b/test/powershell/engine/Basic/DefaultCommands.Tests.ps1 index 065f960b0e0..6744bf0295c 100644 --- a/test/powershell/engine/Basic/DefaultCommands.Tests.ps1 +++ b/test/powershell/engine/Basic/DefaultCommands.Tests.ps1 @@ -18,7 +18,12 @@ Describe "Verify aliases and cmdlets" -Tags "CI" { $FullCLR = !$IsCoreCLR $CoreWindows = $IsCoreCLR -and $IsWindows $CoreUnix = $IsCoreCLR -and !$IsWindows - $isPreview = $PSVersionTable.GitCommitId.Contains("preview") + # If psversion can be converted to [version], then it is not a preview version. + # We can't just use '$psversiontable.psversion -as [version]' because pwsh + # will succeed with the conversion and add note properties to the version object. + $psVersionAsVersion = $psversiontable.psversion.tostring() -as [version] + $isRC = $psversiontable.psversion.tostring() -match "rc" + $isPreview = -not ($isRC -or $psVersionAsVersion) if ($IsWindows) { $configPath = Join-Path -Path $env:USERPROFILE -ChildPath 'Documents' -AdditionalChildPath 'PowerShell' } From 173d7061d8e29a7d0c1b9479e0448d6bce2aaf97 Mon Sep 17 00:00:00 2001 From: Aishat Adeladun Adewoyin <96025207+Aishat452@users.noreply.github.com> Date: Fri, 19 May 2023 17:41:03 +0100 Subject: [PATCH 543/779] Correct capitalization in readme (#19666) --- docs/learning-powershell/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/learning-powershell/README.md b/docs/learning-powershell/README.md index 17829d89df7..32a7dfb052f 100644 --- a/docs/learning-powershell/README.md +++ b/docs/learning-powershell/README.md @@ -2,7 +2,7 @@ Whether you're a Developer, a DevOps or an IT Professional, this doc will help you getting started with PowerShell. In this document we'll cover the following: -installing PowerShell, samples walkthrough, PowerShell editor, debugger, testing tools and a map book for experienced bash users to get started with PowerShell faster. +Installing PowerShell, samples walkthrough, PowerShell editor, debugger, testing tools and a map book for experienced bash users to get started with PowerShell faster. The exercises in this document are intended to give you a solid foundation in how to use PowerShell. You won't be a PowerShell guru at the end of reading this material but you will be well on your way with the right set of knowledge to start using PowerShell. From 371abc544212a774a26dfbf4ec72a4340a5c77f9 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Mon, 22 May 2023 06:02:01 +0200 Subject: [PATCH 544/779] Small cleanup Invoke-RestMethod (#19490) --- .../Common/InvokeRestMethodCommand.Common.cs | 32 ++++++++----------- 1 file changed, 14 insertions(+), 18 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs index a0ec902fb96..df1ef750529 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs @@ -84,7 +84,7 @@ internal override void ProcessResponse(HttpResponseMessage response) if (ShouldWriteToPipeline) { - using var responseStream = new BufferingStreamReader(baseResponseStream, _cancelToken.Token); + using BufferingStreamReader responseStream = new(baseResponseStream, _cancelToken.Token); // First see if it is an RSS / ATOM feed, in which case we can // stream it - unless the user has overridden it with a return type of "XML" @@ -94,37 +94,36 @@ internal override void ProcessResponse(HttpResponseMessage response) } else { - // Determine the response type - RestReturnType returnType = CheckReturnType(response); - // Try to get the response encoding from the ContentType header. string? characterSet = WebResponseHelper.GetCharacterSet(response); string str = StreamHelper.DecodeStream(responseStream, characterSet, out Encoding encoding, _cancelToken.Token); - object? obj = null; - Exception? ex = null; - string encodingVerboseName; try { - encodingVerboseName = string.IsNullOrEmpty(encoding.HeaderName) ? encoding.EncodingName : encoding.HeaderName; + encodingVerboseName = encoding.HeaderName; } - catch (NotSupportedException) + catch { - encodingVerboseName = encoding.EncodingName; + encodingVerboseName = string.Empty; } // NOTE: Tests use this verbose output to verify the encoding. WriteVerbose(string.Create(System.Globalization.CultureInfo.InvariantCulture, $"Content encoding: {encodingVerboseName}")); + // Determine the response type + RestReturnType returnType = CheckReturnType(response); + bool convertSuccess = false; + object? obj = null; + Exception? ex = null; if (returnType == RestReturnType.Json) { convertSuccess = TryConvertToJson(str, out obj, ref ex) || TryConvertToXml(str, out obj, ref ex); } - // default to try xml first since it's more common + // Default to try xml first since it's more common else { convertSuccess = TryConvertToXml(str, out obj, ref ex) || TryConvertToJson(str, out obj, ref ex); @@ -132,7 +131,7 @@ internal override void ProcessResponse(HttpResponseMessage response) if (!convertSuccess) { - // fallback to string + // Fallback to string obj = str; } @@ -171,11 +170,8 @@ private static RestReturnType CheckReturnType(HttpResponseMessage response) RestReturnType rt = RestReturnType.Detect; string? contentType = ContentHelper.GetContentType(response); - if (string.IsNullOrEmpty(contentType)) - { - rt = RestReturnType.Detect; - } - else if (ContentHelper.IsJson(contentType)) + + if (ContentHelper.IsJson(contentType)) { rt = RestReturnType.Json; } @@ -272,7 +268,7 @@ private static bool TryConvertToXml(string xml, [NotNullWhen(true)] out object? XmlReaderSettings settings = GetSecureXmlReaderSettings(); XmlReader xmlReader = XmlReader.Create(new StringReader(xml), settings); - var xmlDoc = new XmlDocument(); + XmlDocument xmlDoc = new(); xmlDoc.PreserveWhitespace = true; xmlDoc.Load(xmlReader); From 06ab3b189d6b46c2e46df87c863d5365a3ad25c7 Mon Sep 17 00:00:00 2001 From: MartinGC94 <42123497+MartinGC94@users.noreply.github.com> Date: Mon, 22 May 2023 20:10:59 +0200 Subject: [PATCH 545/779] Improve path completion (#19489) * Improve path completion * Update src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs Co-authored-by: Steve Lee * Address initial feedback from Steve and Paul * Apply suggestions from code review Co-authored-by: Paul Higinbotham * Apply suggestions from code review Co-authored-by: Ilya * Apply suggestions from iSazonov. * Add missing period to comment. * Add comment explaining limitations of current approach. * Correct some escaping issues and add tests --------- Co-authored-by: Steve Lee Co-authored-by: Paul Higinbotham Co-authored-by: Ilya --- .../CommandCompletion/CompletionCompleters.cs | 848 ++++++++++++------ .../engine/regex.cs | 37 + .../utils/PowerShellExecutionHelper.cs | 7 + .../TabCompletion/TabCompletion.Tests.ps1 | 51 +- 4 files changed, 656 insertions(+), 287 deletions(-) diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs index 495cf4acea8..1cf7082b3c1 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs @@ -4379,7 +4379,6 @@ internal static IEnumerable CompleteFilename(CompletionContext { var wordToComplete = context.WordToComplete; var quote = HandleDoubleAndSingleQuote(ref wordToComplete); - var results = new List(); // First, try to match \\server\share // support both / and \ when entering UNC paths for typing convenience (#17111) @@ -4391,6 +4390,12 @@ internal static IEnumerable CompleteFilename(CompletionContext var sharePattern = WildcardPattern.Get(shareMatch.Groups[2].Value + "*", WildcardOptions.IgnoreCase); var ignoreHidden = context.GetOption("IgnoreHiddenShares", @default: false); var shares = GetFileShares(server, ignoreHidden); + if (shares.Count == 0) + { + return CommandCompletion.EmptyCompletionResult; + } + + var shareResults = new List(shares.Count); foreach (var share in shares) { if (sharePattern.IsMatch(share)) @@ -4401,350 +4406,625 @@ internal static IEnumerable CompleteFilename(CompletionContext shareFullPath = quote + shareFullPath + quote; } - results.Add(new CompletionResult(shareFullPath, shareFullPath, CompletionResultType.ProviderContainer, shareFullPath)); + shareResults.Add(new CompletionResult(shareFullPath, shareFullPath, CompletionResultType.ProviderContainer, shareFullPath)); } } + + return shareResults; + } + + string filter; + string basePath; + int providerSeparatorIndex = -1; + bool defaultRelativePath = false; + bool inputUsedHomeChar = false; + + if (string.IsNullOrEmpty(wordToComplete)) + { + filter = "*"; + basePath = "."; + defaultRelativePath = true; } else { - // We want to prefer relative paths in a completion result unless the user has already - // specified a drive or portion of the path. - var executionContext = context.ExecutionContext; - var defaultRelative = string.IsNullOrWhiteSpace(wordToComplete) - || (wordToComplete.AsSpan().IndexOfAny('\\', '/') != 0 && - !Regex.Match(wordToComplete, @"^~[\\/]+.*").Success && - !executionContext.LocationGlobber.IsAbsolutePath(wordToComplete, out _)); - var relativePaths = context.GetOption("RelativePaths", @default: defaultRelative); - var useLiteralPath = context.GetOption("LiteralPaths", @default: false); + providerSeparatorIndex = wordToComplete.IndexOf("::", StringComparison.Ordinal); + int pathStartOffset = providerSeparatorIndex == -1 ? 0 : providerSeparatorIndex + 2; + inputUsedHomeChar = pathStartOffset + 2 <= wordToComplete.Length + && wordToComplete[pathStartOffset] is '~' + && wordToComplete[pathStartOffset + 1] is '/' or '\\'; - if (useLiteralPath && LocationGlobber.StringContainsGlobCharacters(wordToComplete)) + // This simple analysis is quick but doesn't handle scenarios where a separator character is not actually a separator + // For example "\" or ":" in *nix filenames. This is only a problem if it appears to be the last separator though. + int lastSeparatorIndex = wordToComplete.LastIndexOfAny(Utils.Separators.DirectoryOrDrive); + if (lastSeparatorIndex == -1) { - wordToComplete = WildcardPattern.Escape(wordToComplete, Utils.Separators.StarOrQuestion); + // Input is a simple word with no path separators like: "Program Files" + filter = $"{wordToComplete}*"; + basePath = "."; + defaultRelativePath = true; } - - if (!defaultRelative && wordToComplete.Length >= 2 && wordToComplete[1] == ':' && char.IsLetter(wordToComplete[0]) && executionContext != null) + else { - // We don't actually need the drive, but the drive must be "mounted" in PowerShell before completion - // can succeed. This call will mount the drive if it wasn't already. - executionContext.SessionState.Drive.GetAtScope(wordToComplete.Substring(0, 1), "global"); + if (lastSeparatorIndex + 1 == wordToComplete.Length) + { + // Input ends with a separator like: "./", "filesystem::" or "C:" + filter = "*"; + basePath = wordToComplete; + } + else + { + // Input contains a separator, but doesn't end with one like: "C:\Program Fil" or "Registry::HKEY_LOC" + filter = $"{wordToComplete.Substring(lastSeparatorIndex + 1)}*"; + basePath = wordToComplete.Substring(0, lastSeparatorIndex + 1); + } + + if (!inputUsedHomeChar && basePath[0] is not '/' and not '\\') + { + defaultRelativePath = !context.ExecutionContext.LocationGlobber.IsAbsolutePath(wordToComplete, out _); + } } + } - var powerShellExecutionHelper = context.Helper; - powerShellExecutionHelper - .AddCommandWithPreferenceSetting("Microsoft.PowerShell.Management\\Resolve-Path") - .AddParameter("Path", wordToComplete + "*"); + StringConstantType stringType; + switch (quote) + { + case "": + stringType = StringConstantType.BareWord; + break; - Exception exceptionThrown; - var psobjs = powerShellExecutionHelper.ExecuteCurrentPowerShell(out exceptionThrown); + case "\"": + stringType = StringConstantType.DoubleQuoted; + break; + + default: + stringType = StringConstantType.SingleQuoted; + break; + } + + var useLiteralPath = context.GetOption("LiteralPaths", @default: false); + if (useLiteralPath) + { + basePath = EscapePath(basePath, stringType, useLiteralPath, out _); + } + + _ = context.Helper + .AddCommandWithPreferenceSetting("Microsoft.PowerShell.Management\\Resolve-Path") + .AddParameter("Path", basePath); + + var resolvedPaths = context.Helper.ExecuteCurrentPowerShell(out _); + if (resolvedPaths is null || resolvedPaths.Count == 0) + { + return CommandCompletion.EmptyCompletionResult; + } + + var useRelativePath = context.GetOption("RelativePaths", @default: defaultRelativePath); + if (useRelativePath && providerSeparatorIndex != -1) + { + // User must have requested relative paths but that's not valid with provider paths. + return CommandCompletion.EmptyCompletionResult; + } + + var resolvedProvider = ((PathInfo)resolvedPaths[0].BaseObject).Provider; + string providerPrefix; + if (providerSeparatorIndex == -1) + { + providerPrefix = string.Empty; + } + else if (providerSeparatorIndex == resolvedProvider.Name.Length) + { + providerPrefix = $"{resolvedProvider.Name}::"; + } + else + { + providerPrefix = $"{resolvedProvider.ModuleName}\\{resolvedProvider.Name}::"; + } + + List results; + switch (resolvedProvider.Name) + { + case FileSystemProvider.ProviderName: + results = GetFileSystemProviderResults( + context, + resolvedProvider, + resolvedPaths, + filter, + extension, + containerOnly, + useRelativePath, + useLiteralPath, + inputUsedHomeChar, + providerPrefix, + stringType); + break; + + default: + results = GetDefaultProviderResults( + context, + resolvedProvider, + resolvedPaths, + filter, + containerOnly, + useRelativePath, + useLiteralPath, + inputUsedHomeChar, + providerPrefix, + stringType); + break; + } + + return results.OrderBy(x => x.ToolTip); + } + + /// + /// Helper method for generating path completion results for the file system provider. + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + private static List GetFileSystemProviderResults( + CompletionContext context, + ProviderInfo provider, + Collection resolvedPaths, + string filterText, + HashSet includedExtensions, + bool containersOnly, + bool relativePaths, + bool literalPaths, + bool inputUsedHome, + string providerPrefix, + StringConstantType stringType) + { +#if DEBUG + Diagnostics.Assert(provider.Name.Equals(FileSystemProvider.ProviderName), "Provider should be filesystem provider."); +#endif + var enumerationOptions = _enumerationOptions; + var results = new List(); + string homePath = inputUsedHome && !string.IsNullOrEmpty(provider.Home) ? provider.Home : null; + + WildcardPattern wildcardFilter; + if (WildcardPattern.ContainsRangeWildcard(filterText)) + { + wildcardFilter = WildcardPattern.Get(filterText, WildcardOptions.IgnoreCase); + filterText = "*"; + } + else + { + wildcardFilter = null; + } - if (psobjs != null) + foreach (var item in resolvedPaths) + { + var pathInfo = (PathInfo)item.BaseObject; + var dirInfo = new DirectoryInfo(pathInfo.ProviderPath); + + bool baseQuotesNeeded = false; + string basePath; + if (!relativePaths) + { + basePath = dirInfo.FullName.EndsWith(provider.ItemSeparator) + ? providerPrefix + dirInfo.FullName + : providerPrefix + dirInfo.FullName + provider.ItemSeparator; + basePath = RebuildPathWithVars(basePath, homePath, stringType, literalPaths, out baseQuotesNeeded); + } + else { - var isFileSystem = false; - var wordContainsProviderId = ProviderSpecified(wordToComplete); + basePath = null; + } + IEnumerable fileSystemObjects = containersOnly + ? dirInfo.EnumerateDirectories(filterText, enumerationOptions) + : dirInfo.EnumerateFileSystemInfos(filterText, enumerationOptions); - if (psobjs.Count > 0) + foreach (var entry in fileSystemObjects) + { + bool isContainer = entry.Attributes.HasFlag(FileAttributes.Directory); + if (!isContainer && includedExtensions is not null && !includedExtensions.Contains(entry.Extension)) { - dynamic firstObj = psobjs[0]; - var provider = firstObj.Provider as ProviderInfo; - isFileSystem = provider != null && - provider.Name.Equals(FileSystemProvider.ProviderName, - StringComparison.OrdinalIgnoreCase); + continue; } - else + + var entryName = entry.Name; + if (wildcardFilter is not null && !wildcardFilter.IsMatch(entryName)) { - try - { - ProviderInfo provider; - if (defaultRelative) - { - provider = executionContext.EngineSessionState.CurrentDrive.Provider; - } - else - { - executionContext.LocationGlobber.GetProviderPath(wordToComplete, out provider); - } + continue; + } - isFileSystem = provider != null && - provider.Name.Equals(FileSystemProvider.ProviderName, - StringComparison.OrdinalIgnoreCase); - } - catch (Exception) + if (basePath is null) + { + basePath = context.ExecutionContext.EngineSessionState.NormalizeRelativePath( + entry.FullName, + context.ExecutionContext.SessionState.Internal.CurrentLocation.ProviderPath); + if (!basePath.StartsWith($"..{provider.ItemSeparator}", StringComparison.Ordinal)) { + basePath = $".{provider.ItemSeparator}{basePath}"; } + + basePath = basePath.Remove(basePath.Length - entry.Name.Length); + basePath = RebuildPathWithVars(basePath, homePath, stringType, literalPaths, out baseQuotesNeeded); } - if (isFileSystem) - { - bool hiddenFilesAreHandled = false; + var resultType = isContainer + ? CompletionResultType.ProviderContainer + : CompletionResultType.ProviderItem; + + bool leafQuotesNeeded; + var completionText = NewPathCompletionText( + basePath, + EscapePath(entryName, stringType, literalPaths, out leafQuotesNeeded), + stringType, + containsNestedExpressions: false, + forceQuotes: baseQuotesNeeded || leafQuotesNeeded, + addAmpersand: false); + results.Add(new CompletionResult(completionText, entryName, resultType, entry.FullName)); + } + } - if (psobjs.Count > 0 && !LocationGlobber.StringContainsGlobCharacters(wordToComplete)) - { - string leaf = null; - string pathWithoutProvider = wordContainsProviderId - ? wordToComplete.Substring(wordToComplete.IndexOf(':') + 2) - : wordToComplete; + return results; + } - try - { - leaf = Path.GetFileName(pathWithoutProvider); - } - catch (Exception) - { - } + /// + /// Helper method for generating path completion results standard providers that don't need any special treatment. + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + private static List GetDefaultProviderResults( + CompletionContext context, + ProviderInfo provider, + Collection resolvedPaths, + string filterText, + bool containersOnly, + bool relativePaths, + bool literalPaths, + bool inputUsedHome, + string providerPrefix, + StringConstantType stringType) + { + string homePath = inputUsedHome && !string.IsNullOrEmpty(provider.Home) + ? provider.Home + : null; + + var pattern = WildcardPattern.Get(filterText, WildcardOptions.IgnoreCase); + var results = new List(); - var notHiddenEntries = new HashSet(StringComparer.OrdinalIgnoreCase); - string providerPath = null; + foreach (var item in resolvedPaths) + { + var pathInfo = (PathInfo)item.BaseObject; + string baseTooltip = pathInfo.ProviderPath.Equals(string.Empty, StringComparison.Ordinal) + ? pathInfo.Path + : pathInfo.ProviderPath; + if (baseTooltip[^1] is not '\\' and not '/' and not ':') + { + baseTooltip += provider.ItemSeparator; + } - foreach (dynamic entry in psobjs) - { - providerPath = entry.ProviderPath; - if (string.IsNullOrEmpty(providerPath)) - { - // This is unexpected. ProviderPath should never be null or an empty string - leaf = null; - break; - } + _ = context.Helper.CurrentPowerShell + .AddCommandWithPreferenceSetting("Microsoft.PowerShell.Management\\Get-ChildItem") + .AddParameter("LiteralPath", pathInfo.Path); - if (!notHiddenEntries.Contains(providerPath)) - { - notHiddenEntries.Add(providerPath); - } - } + bool hadErrors; + var childItemOutput = context.Helper.ExecuteCurrentPowerShell(out _, out hadErrors); - if (leaf != null) - { - leaf += "*"; - var parentPath = Path.GetDirectoryName(providerPath); + var childrenInfoTable = new Dictionary(childItemOutput.Count); + var childNameList = new List(childItemOutput.Count); - // ProviderPath should be absolute path for FileSystem entries - if (!string.IsNullOrEmpty(parentPath)) - { - string[] entries = null; - try - { - entries = Directory.GetFileSystemEntries(parentPath, leaf, _enumerationOptions); - } - catch (Exception) - { - } + if (hadErrors) + { + // Get-ChildItem failed to get some items (Access denied or something) + // Save relevant info and try again to get just the names. + foreach (dynamic child in childItemOutput) + { + childrenInfoTable.Add(GetChildNameFromPsObject(child, provider.ItemSeparator), child.PSIsContainer); + } - if (entries != null) - { - hiddenFilesAreHandled = true; + _ = context.Helper.CurrentPowerShell + .AddCommandWithPreferenceSetting("Microsoft.PowerShell.Management\\Get-ChildItem") + .AddParameter("LiteralPath", pathInfo.Path) + .AddParameter("Name"); + childItemOutput = context.Helper.ExecuteCurrentPowerShell(out _); + foreach (var child in childItemOutput) + { + var childName = (string)child.BaseObject; + childNameList.Add(childName); + } + } + else + { + foreach (dynamic child in childItemOutput) + { + var childName = GetChildNameFromPsObject(child, provider.ItemSeparator); + childrenInfoTable.Add(childName, child.PSIsContainer); + childNameList.Add(childName); + } + } - if (entries.Length > notHiddenEntries.Count) - { - // Do the iteration only if there are hidden files - foreach (var entry in entries) - { - if (notHiddenEntries.Contains(entry)) - continue; - - var fileInfo = new FileInfo(entry); - try - { - if ((fileInfo.Attributes & FileAttributes.Hidden) != 0) - { - PSObject wrapper = PSObject.AsPSObject(entry); - psobjs.Add(wrapper); - } - } - catch - { - // do nothing if can't get file attributes - } - } - } - } - } - } - } + if (childNameList.Count == 0) + { + return results; + } - if (!hiddenFilesAreHandled) - { - powerShellExecutionHelper - .AddCommandWithPreferenceSetting("Microsoft.PowerShell.Management\\Get-ChildItem") - .AddParameter("Path", wordToComplete + "*") - .AddParameter("Hidden", true); + string basePath = providerPrefix.Length > 0 + ? string.Concat(providerPrefix, pathInfo.Path.AsSpan(providerPrefix.Length)) + : pathInfo.Path; + if (basePath[^1] is not '\\' and not '/' and not ':') + { + basePath += provider.ItemSeparator; + } - var hiddenItems = powerShellExecutionHelper.ExecuteCurrentPowerShell(out exceptionThrown); - if (hiddenItems != null && hiddenItems.Count > 0) - { - foreach (var hiddenItem in hiddenItems) - { - psobjs.Add(hiddenItem); - } - } - } + if (relativePaths) + { + basePath = context.ExecutionContext.EngineSessionState.NormalizeRelativePath( + basePath + childNameList[0], context.ExecutionContext.SessionState.Internal.CurrentLocation.ProviderPath); + if (!basePath.StartsWith($"..{provider.ItemSeparator}", StringComparison.Ordinal)) + { + basePath = $".{provider.ItemSeparator}{basePath}"; } - // Sorting the results by the path - var sortedPsobjs = psobjs.Order(new ItemPathComparer()); + basePath = basePath.Remove(basePath.Length - childNameList[0].Length); + } + + bool baseQuotesNeeded; + basePath = RebuildPathWithVars(basePath, homePath, stringType, literalPaths, out baseQuotesNeeded); - foreach (PSObject psobj in sortedPsobjs) + foreach (var childName in childNameList) + { + if (!pattern.IsMatch(childName)) { - object baseObj = PSObject.Base(psobj); - string path = null, providerPath = null; + continue; + } - // Get the path, the PSObject could be: - // 1. a PathInfo object -- results of Resolve-Path - // 2. a FileSystemInfo Object -- results of Get-ChildItem - // 3. a string -- the path results return by the direct .NET API invocation - var baseObjAsPathInfo = baseObj as PathInfo; - if (baseObjAsPathInfo != null) - { - path = baseObjAsPathInfo.Path; - providerPath = baseObjAsPathInfo.ProviderPath; - } - else if (baseObj is FileSystemInfo) - { - // The target provider is the FileSystem - dynamic dirResult = psobj; - providerPath = dirResult.FullName; - path = wordContainsProviderId ? dirResult.PSPath : providerPath; - } - else + CompletionResultType resultType; + if (childrenInfoTable.TryGetValue(childName, out bool isContainer)) + { + if (containersOnly && !isContainer) { - var baseObjAsString = baseObj as string; - if (baseObjAsString != null) - { - // The target provider is the FileSystem - providerPath = baseObjAsString; - path = wordContainsProviderId - ? FileSystemProvider.ProviderName + "::" + baseObjAsString - : providerPath; - } + continue; } - if (path == null) continue; - if (isFileSystem && providerPath == null) continue; + resultType = isContainer + ? CompletionResultType.ProviderContainer + : CompletionResultType.ProviderItem; + } + else + { + resultType = CompletionResultType.Text; + } + + bool leafQuotesNeeded; + var completionText = NewPathCompletionText( + basePath, + EscapePath(childName, stringType, literalPaths, out leafQuotesNeeded), + stringType, + containsNestedExpressions: false, + forceQuotes: baseQuotesNeeded || leafQuotesNeeded, + addAmpersand: false); + results.Add(new CompletionResult(completionText, childName, resultType, baseTooltip + childName)); + } + } + + return results; + } + + private static string GetChildNameFromPsObject(dynamic psObject, char separator) + { + // The obvious solution would be to use the "PSChildName" property + // but some providers don't have it (like the Variable provider) + // So we use a substring of "PSPath" instead. + string childName = psObject.PSPath ?? string.Empty; + int ProviderSeparatorIndex = childName.IndexOf("::", StringComparison.Ordinal); + childName = childName.Substring(ProviderSeparatorIndex + 2); + int indexOfName = childName.LastIndexOf(separator); + if (indexOfName == -1 || indexOfName + 1 == childName.Length) + { + return childName; + } - string completionText; - if (relativePaths) + return childName.Substring(indexOfName + 1); + } + + /// + /// Takes a path and rebuilds it with the specified variable replacements. + /// Also escapes special characters as needed. + /// + private static string RebuildPathWithVars( + string path, + string homePath, + StringConstantType stringType, + bool literalPath, + out bool quotesAreNeeded) + { + var sb = new StringBuilder(path.Length); + int homeIndex = string.IsNullOrEmpty(homePath) + ? -1 + : path.IndexOf(homePath, StringComparison.OrdinalIgnoreCase); + quotesAreNeeded = false; + bool useSingleQuoteEscapeRules = stringType is StringConstantType.SingleQuoted or StringConstantType.BareWord; + + for (int i = 0; i < path.Length; i++) + { + if (i == homeIndex) + { + _ = sb.Append('~'); + i += homePath.Length - 1; + continue; + } + + EscapeCharIfNeeded(sb, path, i, stringType, literalPath, useSingleQuoteEscapeRules, ref quotesAreNeeded); + _ = sb.Append(path[i]); + } + + return sb.ToString(); + } + + private static string EscapePath(string path, StringConstantType stringType, bool literalPath, out bool quotesAreNeeded) + { + var sb = new StringBuilder(path.Length); + bool useSingleQuoteEscapeRules = stringType is StringConstantType.SingleQuoted or StringConstantType.BareWord; + quotesAreNeeded = false; + + for (int i = 0; i < path.Length; i++) + { + EscapeCharIfNeeded(sb, path, i, stringType, literalPath, useSingleQuoteEscapeRules, ref quotesAreNeeded); + _ = sb.Append(path[i]); + } + + return sb.ToString(); + } + + private static void EscapeCharIfNeeded( + StringBuilder sb, + string path, + int index, + StringConstantType stringType, + bool literalPath, + bool useSingleQuoteEscapeRules, + ref bool quotesAreNeeded) + { + switch (path[index]) + { + case '#': + case '-': + case '@': + if (index == 0 && stringType == StringConstantType.BareWord) + { + // Chars that would start a new token when used as the first char in a bareword argument. + quotesAreNeeded = true; + } + break; + + case ' ': + case ',': + case ';': + case '(': + case ')': + case '{': + case '}': + case '|': + case '&': + if (stringType == StringConstantType.BareWord) + { + // Chars that would start a new token when used anywhere in a bareword argument. + quotesAreNeeded = true; + } + break; + + case '[': + case ']': + if (!literalPath) + { + // Wildcard characters that need to be escaped. + int backtickCount; + if (useSingleQuoteEscapeRules) { - try - { - var sessionStateInternal = executionContext.EngineSessionState; - completionText = sessionStateInternal.NormalizeRelativePath(path, sessionStateInternal.CurrentLocation.ProviderPath); - string parentDirectory = ".." + StringLiterals.DefaultPathSeparator; - if (!completionText.StartsWith(parentDirectory, StringComparison.Ordinal)) - completionText = Path.Combine(".", completionText); - } - catch (Exception) - { - // The object at the specified path is not accessible, such as c:\hiberfil.sys (for hibernation) or c:\pagefile.sys (for paging) - // We ignore those files - continue; - } + backtickCount = 1; } else { - completionText = path; + backtickCount = sb[^1] == '`' ? 4 : 2; } - if (ProviderSpecified(completionText) && !wordContainsProviderId) - { - // Remove the provider id from the path: cd \\scratch2\scratch\dongbw - var index = completionText.IndexOf(':'); - completionText = completionText.Substring(index + 2); - } - - if (CompletionRequiresQuotes(completionText, !useLiteralPath)) - { - var quoteInUse = quote == string.Empty ? "'" : quote; - if (quoteInUse == "'") - { - completionText = completionText.Replace("'", "''"); - } - else - { - // When double quote is in use, we have to escape the backtip and '$' even when using literal path - // Get-Content -LiteralPath ".\a``g.txt" - completionText = completionText.Replace("`", "``"); - completionText = completionText.Replace("$", "`$"); - } - - if (!useLiteralPath) - { - if (quoteInUse == "'") - { - completionText = completionText.Replace("[", "`["); - completionText = completionText.Replace("]", "`]"); - } - else - { - completionText = completionText.Replace("[", "``["); - completionText = completionText.Replace("]", "``]"); - } - } + _ = sb.Append('`', backtickCount); + quotesAreNeeded = true; + } + break; - completionText = quoteInUse + completionText + quoteInUse; - } - else if (quote != string.Empty) + case '`': + // Literal backtick needs to be escaped to not be treated as an escape character + if (useSingleQuoteEscapeRules) + { + if (!literalPath) { - completionText = quote + completionText + quote; + _ = sb.Append('`'); } + } + else + { + int backtickCount = !literalPath && sb[^1] == '`' ? 3 : 1; + _ = sb.Append('`', backtickCount); + } - if (isFileSystem) - { - // Use .NET APIs directly to reduce the time overhead - var isContainer = Directory.Exists(providerPath); - if (containerOnly && !isContainer) - continue; + if (stringType is StringConstantType.BareWord or StringConstantType.DoubleQuoted) + { + quotesAreNeeded = true; + } + break; - if (!containerOnly && !isContainer && !CheckFileExtension(providerPath, extension)) - continue; + case '$': + // $ needs to be escaped so following chars are not parsed as a variable/subexpression + if (!useSingleQuoteEscapeRules) + { + _ = sb.Append('`'); + } - string tooltip = providerPath, listItemText = Path.GetFileName(providerPath); - results.Add(new CompletionResult(completionText, listItemText, - isContainer ? CompletionResultType.ProviderContainer : CompletionResultType.ProviderItem, - tooltip)); - } - else - { - powerShellExecutionHelper - .AddCommandWithPreferenceSetting("Microsoft.PowerShell.Management\\Get-Item") - .AddParameter("LiteralPath", path); - var items = powerShellExecutionHelper.ExecuteCurrentPowerShell(out exceptionThrown); - if (items != null && items.Count == 1) - { - dynamic item = items[0]; - var isContainer = LanguagePrimitives.ConvertTo(item.PSIsContainer); - - if (containerOnly && !isContainer) - continue; - - powerShellExecutionHelper - .AddCommandWithPreferenceSetting("Microsoft.PowerShell.Management\\Convert-Path") - .AddParameter("LiteralPath", item.PSPath); - var tooltips = powerShellExecutionHelper.ExecuteCurrentPowerShell(out exceptionThrown); - string tooltip = null, listItemText = item.PSChildName; - if (tooltips != null && tooltips.Count == 1) - { - tooltip = PSObject.Base(tooltips[0]) as string; - } + if (stringType is StringConstantType.BareWord or StringConstantType.DoubleQuoted) + { + quotesAreNeeded = true; + } + break; - if (string.IsNullOrEmpty(listItemText)) - { - // For provider items that don't have PSChildName values, such as variable::error - listItemText = item.Name; - } + default: + // Handle all the different quote types + if (useSingleQuoteEscapeRules && path[index].IsSingleQuote()) + { + _ = sb.Append('\''); + quotesAreNeeded = true; + } + else if (!useSingleQuoteEscapeRules && path[index].IsDoubleQuote()) + { + _ = sb.Append('`'); + quotesAreNeeded = true; + } + break; + } + } - results.Add(new CompletionResult(completionText, listItemText, - isContainer ? CompletionResultType.ProviderContainer : CompletionResultType.ProviderItem, - tooltip ?? path)); - } - else - { - // We can get here when get-item fails, perhaps due an acl or whatever. - results.Add(new CompletionResult(completionText)); - } - } + private static string NewPathCompletionText(string parent, string leaf, StringConstantType stringType, bool containsNestedExpressions, bool forceQuotes, bool addAmpersand) + { + string result; + if (stringType == StringConstantType.SingleQuoted) + { + result = addAmpersand ? $"& '{parent}{leaf}'" : $"'{parent}{leaf}'"; + } + else if (stringType == StringConstantType.DoubleQuoted) + { + result = addAmpersand ? $"& \"{parent}{leaf}\"" : $"\"{parent}{leaf}\""; + } + else + { + if (forceQuotes) + { + if (containsNestedExpressions) + { + result = addAmpersand ? $"& \"{parent}{leaf}\"" : $"\"{parent}{leaf}\""; + } + else + { + result = addAmpersand ? $"& '{parent}{leaf}'" : $"'{parent}{leaf}'"; } } + else + { + result = string.Concat(parent, leaf); + } } - return results; + return result; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] diff --git a/src/System.Management.Automation/engine/regex.cs b/src/System.Management.Automation/engine/regex.cs index 4efe1ff436a..5987ba80dcc 100644 --- a/src/System.Management.Automation/engine/regex.cs +++ b/src/System.Management.Automation/engine/regex.cs @@ -314,6 +314,43 @@ public static bool ContainsWildcardCharacters(string pattern) return result; } + /// + /// Checks if the string contains a left bracket "[" followed by a right bracket "]" after any number of characters. + /// + /// The string to check. + /// Returns true if the string contains both a left and right bracket "[" "]" and if the right bracket comes after the left bracket. + internal static bool ContainsRangeWildcard(string pattern) + { + if (string.IsNullOrEmpty(pattern)) + { + return false; + } + + bool foundStart = false; + bool result = false; + for (int index = 0; index < pattern.Length; ++index) + { + if (pattern[index] is '[') + { + foundStart = true; + continue; + } + + if (foundStart && pattern[index] is ']') + { + result = true; + break; + } + + if (pattern[index] == escapeChar) + { + ++index; + } + } + + return result; + } + /// /// Unescapes any escaped characters in the input string. /// diff --git a/src/System.Management.Automation/utils/PowerShellExecutionHelper.cs b/src/System.Management.Automation/utils/PowerShellExecutionHelper.cs index d30d759647a..632e1445ee4 100644 --- a/src/System.Management.Automation/utils/PowerShellExecutionHelper.cs +++ b/src/System.Management.Automation/utils/PowerShellExecutionHelper.cs @@ -61,12 +61,18 @@ internal bool ExecuteCommandAndGetResultAsBool() } internal Collection ExecuteCurrentPowerShell(out Exception exceptionThrown, IEnumerable input = null) + { + return ExecuteCurrentPowerShell(out exceptionThrown, out _, input); + } + + internal Collection ExecuteCurrentPowerShell(out Exception exceptionThrown, out bool hadErrors, IEnumerable input = null) { exceptionThrown = null; // This flag indicates a previous call to this method had its pipeline cancelled if (CancelTabCompletion) { + hadErrors = false; return new Collection(); } @@ -89,6 +95,7 @@ internal Collection ExecuteCurrentPowerShell(out Exception exceptionTh } finally { + hadErrors = CurrentPowerShell.HadErrors; CurrentPowerShell.Commands.Clear(); } diff --git a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 index 6dcc6964e9b..1016650db3e 100644 --- a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 +++ b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 @@ -1176,6 +1176,51 @@ class InheritedClassTest : System.Attribute $expectedPath = Join-Path $PSScriptRoot -ChildPath BugFix.Tests.ps1 $res.CompletionMatches[0].CompletionText | Should -Be "`"$expectedPath`"" } + + It "Should keep '~' in completiontext when it's used to refer to home in input" { + $res = TabExpansion2 -inputScript "~$separator" + $res.CompletionMatches[0].CompletionText | Should -BeLike "~$separator*" + } + + It "Should use '~' as relative filter text when not followed by separator" { + $TempDirName = "~TempDir" + $TempDirPath = Join-Path -Path $TestDrive -ChildPath "~TempDir" + $TempDir = New-Item -Path $TempDirPath -ItemType Directory -Force + Push-Location -Path $TestDrive + $res = TabExpansion2 -inputScript ~ + $res.CompletionMatches[0].CompletionText | Should -Be ".${separator}${TempDirName}" + } + + It 'Escapes backtick properly for path: ' -TestCases @( + @{LiteralPath = 'BacktickTest['; BacktickSingle = 1; BacktickDouble = 2; LiteralBacktickSingle = 0; LiteralBacktickDouble = 0} + @{LiteralPath = 'BacktickTest`['; BacktickSingle = 3; BacktickDouble = 6; LiteralBacktickSingle = 1; LiteralBacktickDouble = 2} + @{LiteralPath = 'BacktickTest``['; BacktickSingle = 5; BacktickDouble = 10; LiteralBacktickSingle = 2; LiteralBacktickDouble = 4} + @{LiteralPath = 'BacktickTest$'; BacktickSingle = 0; BacktickDouble = 1; LiteralBacktickSingle = 0; LiteralBacktickDouble = 1} + @{LiteralPath = 'BacktickTest`$'; BacktickSingle = 2; BacktickDouble = 3; LiteralBacktickSingle = 1; LiteralBacktickDouble = 3} + @{LiteralPath = 'BacktickTest``$'; BacktickSingle = 4; BacktickDouble = 7; LiteralBacktickSingle = 2; LiteralBacktickDouble = 5} + ) { + param($LiteralPath, $BacktickSingle, $BacktickDouble, $LiteralBacktickSingle, $LiteralBacktickDouble) + $NewPath = Join-Path -Path $TestDrive -ChildPath $LiteralPath + $null = New-Item -Path $NewPath -Force + Push-Location $TestDrive + + $InputText = "Get-ChildItem -Path {0}.${separator}BacktickTest" + $InputTextLiteral = "Get-ChildItem -LiteralPath {0}.${separator}BacktickTest" + + $Text = (TabExpansion2 -inputScript ($InputText -f "'")).CompletionMatches[0].CompletionText + $Text.Length - $Text.Replace('`','').Length | Should -Be $BacktickSingle + + $Text = (TabExpansion2 -inputScript ($InputText -f '"')).CompletionMatches[0].CompletionText + $Text.Length - $Text.Replace('`','').Length | Should -Be $BacktickDouble + + $Text = (TabExpansion2 -inputScript ($InputTextLiteral -f "'")).CompletionMatches[0].CompletionText + $Text.Length - $Text.Replace('`','').Length | Should -Be $LiteralBacktickSingle + + $Text = (TabExpansion2 -inputScript ($InputTextLiteral -f '"')).CompletionMatches[0].CompletionText + $Text.Length - $Text.Replace('`','').Length | Should -Be $LiteralBacktickDouble + + Remove-Item -LiteralPath $LiteralPath + } } Context "Cmdlet name completion" { @@ -1350,7 +1395,7 @@ class InheritedClassTest : System.Attribute It "Tab completion for registry" -Skip:(!$IsWindows) { $beforeTab = 'registry::HKEY_l' - $afterTab = 'registry::HKEY_LOCAL_MACHINE' + $afterTab = 'Registry::HKEY_LOCAL_MACHINE' $res = TabExpansion2 -inputScript $beforeTab -cursorColumn $beforeTab.Length $res.CompletionMatches | Should -HaveCount 1 $res.CompletionMatches[0].CompletionText | Should -BeExactly $afterTab @@ -1358,7 +1403,7 @@ class InheritedClassTest : System.Attribute It "Tab completion for wsman provider" -Skip:(!$IsWindows) { $beforeTab = 'wsman::localh' - $afterTab = 'wsman::localhost' + $afterTab = 'WSMan::localhost' $res = TabExpansion2 -inputScript $beforeTab -cursorColumn $beforeTab.Length $res.CompletionMatches | Should -HaveCount 1 $res.CompletionMatches[0].CompletionText | Should -BeExactly $afterTab @@ -1371,7 +1416,7 @@ class InheritedClassTest : System.Attribute New-Item -ItemType Directory -Path "$tempFolder/helloworld" > $null $tempFolder | Should -Exist $beforeTab = 'filesystem::{0}hello' -f $tempFolder - $afterTab = 'filesystem::{0}helloworld' -f $tempFolder + $afterTab = 'FileSystem::{0}helloworld' -f $tempFolder $res = TabExpansion2 -inputScript $beforeTab -cursorColumn $beforeTab.Length $res.CompletionMatches.Count | Should -BeGreaterThan 0 $res.CompletionMatches[0].CompletionText | Should -BeExactly $afterTab From c57ada217df8e576ba49534e5cf2c26948ad40c3 Mon Sep 17 00:00:00 2001 From: Frode Flaten <3436158+fflaten@users.noreply.github.com> Date: Mon, 22 May 2023 23:25:00 +0200 Subject: [PATCH 546/779] Filter completion for enum parameter against `ValidateRange` attributes (#17750) --- .../engine/Attributes.cs | 22 ++++++++++++++++ .../CommandCompletion/CompletionCompleters.cs | 26 ++++++++++++------- .../engine/LanguagePrimitives.cs | 8 ++++++ .../TabCompletion/TabCompletion.Tests.ps1 | 25 ++++++++++++++++++ 4 files changed, 72 insertions(+), 9 deletions(-) diff --git a/src/System.Management.Automation/engine/Attributes.cs b/src/System.Management.Automation/engine/Attributes.cs index e7b289418fc..5b00b9df42b 100644 --- a/src/System.Management.Automation/engine/Attributes.cs +++ b/src/System.Management.Automation/engine/Attributes.cs @@ -1311,6 +1311,28 @@ private static Type GetCommonType(Type minType, Type maxType) return resultType; } + + /// + /// Returns only the elements that passed the attribute's validation. + /// + /// The objects to validate. + internal IEnumerable GetValidatedElements(IEnumerable elementsToValidate) + { + foreach (var el in elementsToValidate) + { + try + { + ValidateElement(el); + } + catch (ValidationMetadataException) + { + // Element was not in range - drop + continue; + } + + yield return el; + } + } } /// diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs index 1cf7082b3c1..8dae46f3395 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs @@ -1796,9 +1796,16 @@ private static void ProcessParameter( { RemoveLastNullCompletionResult(result); - string enumString = LanguagePrimitives.EnumSingleTypeConverter.EnumValues(parameterType); - string separator = CultureInfo.CurrentUICulture.TextInfo.ListSeparator; - string[] enumArray = enumString.Split(separator, StringSplitOptions.RemoveEmptyEntries); + IEnumerable enumValues = LanguagePrimitives.EnumSingleTypeConverter.GetEnumValues(parameterType); + + // Exclude values not accepted by ValidateRange-attributes + foreach (ValidateArgumentsAttribute att in parameter.Parameter.ValidationAttributes) + { + if (att is ValidateRangeAttribute rangeAtt) + { + enumValues = rangeAtt.GetValidatedElements(enumValues); + } + } string wordToComplete = context.WordToComplete ?? string.Empty; string quote = HandleDoubleAndSingleQuote(ref wordToComplete); @@ -1806,18 +1813,19 @@ private static void ProcessParameter( var pattern = WildcardPattern.Get(wordToComplete + "*", WildcardOptions.IgnoreCase); var enumList = new List(); - foreach (string value in enumArray) + foreach (Enum value in enumValues) { - if (wordToComplete.Equals(value, StringComparison.OrdinalIgnoreCase)) + string name = value.ToString(); + if (wordToComplete.Equals(name, StringComparison.OrdinalIgnoreCase)) { - string completionText = quote == string.Empty ? value : quote + value + quote; - fullMatch = new CompletionResult(completionText, value, CompletionResultType.ParameterValue, value); + string completionText = quote == string.Empty ? name : quote + name + quote; + fullMatch = new CompletionResult(completionText, name, CompletionResultType.ParameterValue, name); continue; } - if (pattern.IsMatch(value)) + if (pattern.IsMatch(name)) { - enumList.Add(value); + enumList.Add(name); } } diff --git a/src/System.Management.Automation/engine/LanguagePrimitives.cs b/src/System.Management.Automation/engine/LanguagePrimitives.cs index ac3c1c1a70c..a93bd1658d5 100644 --- a/src/System.Management.Automation/engine/LanguagePrimitives.cs +++ b/src/System.Management.Automation/engine/LanguagePrimitives.cs @@ -2076,6 +2076,14 @@ internal static string EnumValues(Type enumType) return string.Join(CultureInfo.CurrentUICulture.TextInfo.ListSeparator, enumHashEntry.names); } + /// + /// Returns all values for the provided enum type. + /// + /// The enum type to retrieve values from. + /// Array of enum values for the specified type. + internal static Array GetEnumValues(Type enumType) + => EnumSingleTypeConverter.GetEnumHashEntry(enumType).values; + public override object ConvertFrom(object sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase) { return EnumSingleTypeConverter.BaseConvertFrom(sourceValue, destinationType, formatProvider, ignoreCase, false); diff --git a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 index 1016650db3e..fee6c8c0001 100644 --- a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 +++ b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 @@ -1597,6 +1597,31 @@ class InheritedClassTest : System.Attribute $res.CompletionMatches[1].CompletionText | Should -BeExactly 'Configuration' } + It 'Tab completion for enum parameter is filtered against ' -TestCases @( + @{ Name = 'ValidateRange with enum-values'; Attribute = '[ValidateRange([System.ConsoleColor]::Blue, [System.ConsoleColor]::Cyan)]' } + @{ Name = 'ValidateRange with int-values'; Attribute = '[ValidateRange(9, 11)]' } + @{ Name = 'multiple ValidateRange-attributes'; Attribute = '[ValidateRange([System.ConsoleColor]::Blue, [System.ConsoleColor]::Cyan)][ValidateRange([System.ConsoleColor]::Gray, [System.ConsoleColor]::Red)]' } + ) { + param($Name, $Attribute) + $functionDefinition = 'param ( {0}[consolecolor]$color )' -f $Attribute + Set-Item -Path function:baz -Value $functionDefinition + $inputStr = 'baz -color ' + $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length + $res.CompletionMatches | Should -HaveCount 3 + $res.CompletionMatches[0].CompletionText | Should -BeExactly 'Blue' + $res.CompletionMatches[1].CompletionText | Should -BeExactly 'Cyan' + $res.CompletionMatches[2].CompletionText | Should -BeExactly 'Green' + } + + It 'Tab completion for enum parameter is filtered with ValidateRange using rangekind' { + $functionDefinition = 'param ( [ValidateRange([System.Management.Automation.ValidateRangeKind]::NonPositive)][consolecolor]$color )' -f $Attribute + Set-Item -Path function:baz -Value $functionDefinition + $inputStr = 'baz -color ' + $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length + $res.CompletionMatches | Should -HaveCount 1 + $res.CompletionMatches[0].CompletionText | Should -BeExactly 'Black' # 0 = NonPositive + } + It "Test [CommandCompletion]::GetNextResult" { $inputStr = "Get-Command -Type Alias,c" $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length From b69cae01f862a4d373fae4c7d739a53331167a02 Mon Sep 17 00:00:00 2001 From: Christopher Yeleighton Date: Tue, 23 May 2023 01:34:53 +0200 Subject: [PATCH 547/779] Pass `-UserScope` as required by `RunUpdateHelpTests` (#13400) --- .../engine/Help/UpdatableHelpSystem.Tests.ps1 | 177 ++++++++---------- 1 file changed, 73 insertions(+), 104 deletions(-) diff --git a/test/powershell/engine/Help/UpdatableHelpSystem.Tests.ps1 b/test/powershell/engine/Help/UpdatableHelpSystem.Tests.ps1 index f767ff4ea7f..c1d01f6476b 100644 --- a/test/powershell/engine/Help/UpdatableHelpSystem.Tests.ps1 +++ b/test/powershell/engine/Help/UpdatableHelpSystem.Tests.ps1 @@ -5,7 +5,7 @@ Import-Module HelpersCommon # Test Settings: # This is the list of PowerShell modules for which we test update-help -$powershellCoreModules = @( +[string[]] $powershellCoreModules = @( "CimCmdlets" <# This scenario is broken due to issue # https://github.com/PowerShell/platyPS/issues/241 @@ -26,119 +26,127 @@ $powershellCoreModules = @( # The file extension for the help content on the Download Center. # For Linux we use zip, and on Windows we use $extension. -$extension = ".zip" +[string] $extension = ".zip" if ([System.Management.Automation.Platform]::IsWindows) { $extension = ".cab" } +[string] $userHelpRoot = $null + if([System.Management.Automation.Platform]::IsWindows) { - $userHelpRoot = Join-Path $HOME "Documents/PowerShell/Help/" + # To the reader: the explicit parameter names below are required by a brainless code checker. + $userHelpRoot = Join-Path -Path:$HOME -ChildPath:Documents -AdditionalChildPath:PowerShell, Help } else { - $userModulesRoot = [System.Management.Automation.Platform]::SelectProductNameForDirectory([System.Management.Automation.Platform+XDG_Type]::USER_MODULES) - $userHelpRoot = Join-Path $userModulesRoot -ChildPath ".." -AdditionalChildPath "Help" + [string] $userModulesRoot = [System.Management.Automation.Platform]::SelectProductNameForDirectory([System.Management.Automation.Platform+XDG_Type]::USER_MODULES) + $userHelpRoot = Join-Path -Path:$userModulesRoot -ChildPath:.. -AdditionalChildPath:Help } +# default values for system modules +[string] $myUICulture = 'en-US' +[string] $HelpInstallationPath = Join-Path $PSHOME $myUICulture +[string] $HelpInstallationPathHome = Join-Path $userHelpRoot $myUICulture + # This is the list of test cases -- each test case represents a PowerShell module. -$testCases = @{ +[hashtable] $testCases = @{ "CimCmdlets" = @{ HelpFiles = "Microsoft.Management.Infrastructure.CimCmdlets.dll-help.xml" HelpInfoFiles = "CimCmdlets_fb6cc51d-c096-4b38-b78d-0fed6277096a_HelpInfo.xml" CompressedFiles = "CimCmdlets_fb6cc51d-c096-4b38-b78d-0fed6277096a_en-US_HelpContent$extension" - HelpInstallationPath = "$PSHOME\Modules\CimCmdlets\en-US" - HelpInstallationPathHome = "$userHelpRoot\CimCmdlets\en-US" + HelpInstallationPath = Join-Path -Path:$PSHOME -ChildPath:Modules -AdditionalChildPath:CimCmdlets, $myUICulture + HelpInstallationPathHome = Join-Path -Path:$userHelpRoot -ChildPath:CimCmdlets -AdditionalChildPath:$myUICulture } "Microsoft.PowerShell.Archive" = @{ HelpFiles = "Microsoft.PowerShell.Archive-help.xml" HelpInfoFiles = "Microsoft.PowerShell.Archive_eb74e8da-9ae2-482a-a648-e96550fb8733_HelpInfo.xml" CompressedFiles = "Microsoft.PowerShell.Archive_eb74e8da-9ae2-482a-a648-e96550fb8733_en-US_HelpContent$extension" - HelpInstallationPath = "$PSHOME\Modules\Microsoft.PowerShell.Archive\en-US" + HelpInstallationPath = Join-Path -Path:$PSHOME -ChildPath:Modules -AdditionalChildPath:Microsoft.PowerShell.Archive, $myUICulture } "Microsoft.PowerShell.Core" = @{ HelpFiles = "System.Management.Automation.dll-help.xml" HelpInfoFiles = "Microsoft.PowerShell.Core_00000000-0000-0000-0000-000000000000_HelpInfo.xml" CompressedFiles = "Microsoft.PowerShell.Core_00000000-0000-0000-0000-000000000000_en-US_HelpContent$extension" - HelpInstallationPath = "$PSHOME\en-US" - HelpInstallationPathHome = "$userHelpRoot\en-US" + HelpInstallationPath = $HelpInstallationPath + HelpInstallationPathHome = $HelpInstallationPathHome } "Microsoft.PowerShell.Diagnostics" = @{ HelpFiles = "Microsoft.PowerShell.Commands.Diagnostics.dll-help.xml" HelpInfoFiles = "Microsoft.PowerShell.Diagnostics_ca046f10-ca64-4740-8ff9-2565dba61a4f_HelpInfo.xml" CompressedFiles = "Microsoft.PowerShell.Diagnostics_ca046f10-ca64-4740-8ff9-2565dba61a4f_en-US_helpcontent$extension" - HelpInstallationPath = "$PSHOME\en-US" - HelpInstallationPathHome = "$userHelpRoot\en-US" + HelpInstallationPath = $HelpInstallationPath + HelpInstallationPathHome = $HelpInstallationPathHome } "Microsoft.PowerShell.Host" = @{ HelpFiles = "Microsoft.PowerShell.ConsoleHost.dll-help.xml" HelpInfoFiles = "Microsoft.PowerShell.Host_56d66100-99a0-4ffc-a12d-eee9a6718aef_HelpInfo.xml" CompressedFiles = "Microsoft.PowerShell.Host_56d66100-99a0-4ffc-a12d-eee9a6718aef_en-US_helpcontent$extension" - HelpInstallationPath = "$PSHOME\en-US" - HelpInstallationPathHome = "$userHelpRoot\en-US" + HelpInstallationPath = $HelpInstallationPath + HelpInstallationPathHome = $HelpInstallationPathHome } "Microsoft.PowerShell.LocalAccounts" = @{ HelpFiles = "Microsoft.Powershell.LocalAccounts.dll-help.xml" HelpInfoFiles = "Microsoft.PowerShell.LocalAccounts_8e362604-2c0b-448f-a414-a6a690a644e2_HelpInfo.xml" CompressedFiles = "Microsoft.PowerShell.LocalAccounts_8e362604-2c0b-448f-a414-a6a690a644e2_en-US_HelpContent$extension" - HelpInstallationPath = "$PSHOME\Modules\Microsoft.PowerShell.LocalAccounts\en-US" - HelpInstallationPathHome = "$userHelpRoot\Microsoft.PowerShell.LocalAccounts\en-US" + HelpInstallationPath = Join-Path -Path:$PSHOME Modules Microsoft.PowerShell.LocalAccounts $myUICulture + HelpInstallationPathHome = Join-Path -Path:$userHelpRoot -ChildPath:Microsoft.PowerShell.LocalAccounts -AdditionalChildPath:$myUICulture } "Microsoft.PowerShell.Management" = @{ HelpFiles = "Microsoft.PowerShell.Commands.Management.dll-help.xml" HelpInfoFiles = "Microsoft.PowerShell.Management_eefcb906-b326-4e99-9f54-8b4bb6ef3c6d_HelpInfo.xml" CompressedFiles = "Microsoft.PowerShell.Management_eefcb906-b326-4e99-9f54-8b4bb6ef3c6d_en-US_helpcontent$extension" - HelpInstallationPath = "$PSHOME\en-US" - HelpInstallationPathHome = "$userHelpRoot\en-US" + HelpInstallationPath = $HelpInstallationPath + HelpInstallationPathHome = $HelpInstallationPathHome } "Microsoft.PowerShell.Security" = @{ HelpFiles = "Microsoft.PowerShell.Security.dll-help.xml" HelpInfoFiles = "Microsoft.PowerShell.Security_a94c8c7e-9810-47c0-b8af-65089c13a35a_HelpInfo.xml" CompressedFiles = "Microsoft.PowerShell.Security_a94c8c7e-9810-47c0-b8af-65089c13a35a_en-US_helpcontent$extension" - HelpInstallationPath = "$PSHOME\en-US" - HelpInstallationPathHome = "$userHelpRoot\en-US" + HelpInstallationPath = $HelpInstallationPath + HelpInstallationPathHome = $HelpInstallationPathHome } "Microsoft.PowerShell.Utility" = @{ HelpFiles = "Microsoft.PowerShell.Commands.Utility.dll-Help.xml", "Microsoft.PowerShell.Utility-help.xml" HelpInfoFiles = "Microsoft.PowerShell.Utility_1da87e53-152b-403e-98dc-74d7b4d63d59_HelpInfo.xml" CompressedFiles = "Microsoft.PowerShell.Utility_1da87e53-152b-403e-98dc-74d7b4d63d59_en-US_helpcontent$extension" - HelpInstallationPath = "$PSHOME\en-US" - HelpInstallationPathHome = "$userHelpRoot\en-US" + HelpInstallationPath = $HelpInstallationPath + HelpInstallationPathHome = $HelpInstallationPathHome } "Microsoft.WSMan.Management" = @{ HelpFiles = "Microsoft.WSMan.Management.dll-help.xml" HelpInfoFiles = "Microsoft.WsMan.Management_766204A6-330E-4263-A7AB-46C87AFC366C_HelpInfo.xml" CompressedFiles = "Microsoft.WsMan.Management_766204A6-330E-4263-A7AB-46C87AFC366C_en-US_helpcontent$extension" - HelpInstallationPath = "$PSHOME\en-US" - HelpInstallationPathHome = "$userHelpRoot\en-US" + HelpInstallationPath = $HelpInstallationPath + HelpInstallationPathHome = $HelpInstallationPathHome } "PackageManagement" = @{ HelpFiles = "Microsoft.PowerShell.PackageManagement.dll-help.xml" HelpInfoFiles = "PackageManagement_4ae9fd46-338a-459c-8186-07f910774cb8_HelpInfo.xml" CompressedFiles = "PackageManagement_4ae9fd46-338a-459c-8186-07f910774cb8_en-US_helpcontent$extension" - HelpInstallationPath = "$PSHOME\Modules\PackageManagement\en-US" - HelpInstallationPathHome = "$userHelpRoot\PackageManagement\en-US" + HelpInstallationPath = Join-Path -Path:$PSHOME -ChildPath:Modules -AdditionalChildPath:PackageManagement, $myUICulture + HelpInstallationPathHome = Join-Path -Path:$userHelpRoot -ChildPath:PackageManagement -AdditionalChildPath:$myUICulture } "PowershellGet" = @{ HelpFiles = "PSGet.psm1-help.xml" HelpInfoFiles = "PowershellGet_1d73a601-4a6c-43c5-ba3f-619b18bbb404_HelpInfo.xml" CompressedFiles = "PowershellGet_1d73a601-4a6c-43c5-ba3f-619b18bbb404_en-US_helpcontent$extension" - HelpInstallationPath = "$PSHOME\Modules\PowershellGet\en-US" - HelpInstallationPathHome = "$userHelpRoot\PackageManagement\en-US" + HelpInstallationPath = Join-Path -Path:$PSHOME -ChildPath:Modules -AdditionalChildPath:PowershellGet, $myUICulture + HelpInstallationPathHome = Join-Path -Path:$userHelpRoot -ChildPath:PackageManagement -AdditionalChildPath:$myUICulture } } @@ -166,23 +174,15 @@ function ValidateInstalledHelpContent [switch]$UserScope ) - if($UserScope) - { - $params = @{ Path = $testCases[$moduleName].HelpInstallationPathHome } - } - else - { - $params = @{ Path = $testCases[$moduleName].HelpInstallationPath } - } - - $helpFilesInstalled = @(GetFiles @params | ForEach-Object {Split-Path $_ -Leaf}) + [string] $pathProperty = $(if ($UserScope) { 'HelpInstallationPathHome' } else { 'HelpInstallationPath' }) + [System.IO.FileInfo[]] $helpFilesInstalled = Get-ChildItem -Path:($testCases[$moduleName][$pathProperty]) -Filter:*help.xml -Recurse - $expectedHelpFiles = @($testCases[$moduleName].HelpFiles) - $helpFilesInstalled.Count | Should -Be $expectedHelpFiles.Count + [string[]] $expectedHelpFiles = $testCases[$moduleName].HelpFiles + $helpFilesInstalled.Count | Should -Be ($expectedHelpFiles.Count) foreach ($fileName in $expectedHelpFiles) { - $helpFilesInstalled -contains $fileName | Should -BeTrue + [string[]] $helpFilesInstalled.Name -eq $fileName | Should -Be $fileName } } @@ -199,62 +199,31 @@ function RunUpdateHelpTests if ($powershellCoreModules -contains $moduleName) { - It "Validate Update-Help for module '$moduleName' with scope as '$userscope'" -Skip:(!(Test-CanWriteToPsHome) -and $userscope -eq $false) { - - if($userscope) - { - $params = @{Path = $testCases[$moduleName].HelpInstallationPathHome} - $updateScope = @{Scope = 'CurrentUser'} - } - else - { - $params = @{Path = $testCases[$moduleName].HelpInstallationPath} - $updateScope = @{Scope = 'AllUsers'} - } - - $commonParam = @{ - Include = @("*help.xml") - Recurse = $true - ErrorAction = 'SilentlyContinue' - } + [string] $moduleHelpPath = $null + [string] $updateScope = $null + if ($userscope) + { + $moduleHelpPath = $testCases[$moduleName]['HelpInstallationPathHome'] + $updateScope = 'CurrentUser' + } + else + { + $moduleHelpPath = $testCases[$moduleName]['HelpInstallationPath'] + $updateScope = 'AllUsers' + } - $params += $commonParam + It ('Validate Update-Help for module ''{0}'' in {1}' -F $moduleName, [PSCustomObject] $updateScope) -Skip:(!(Test-CanWriteToPsHome) -and $userscope -eq $false) { - # If the help file is already installed, delete it. - Get-ChildItem @params | - Remove-Item -Force -ErrorAction SilentlyContinue + # Delete the whole help directory + Remove-Item ($moduleHelpPath) -Recurse + + [hashtable] $UICultureParam = $(if ((Get-UICulture).Name -ne $myUICulture) { @{ UICulture = $myUICulture } } else { @{} }) + [hashtable] $sourcePathParam = $(if ($useSourcePath) { @{ SourcePath = Join-Path $PSScriptRoot assets } } else { @{} }) + Update-Help -Module:$moduleName -Force @UICultureParam @sourcePathParam -Scope:$updateScope - if ((Get-UICulture).Name -ne "en-Us") - { - if ($useSourcePath) - { - Update-Help -Module $moduleName -Force -UICulture en-US -SourcePath "$PSScriptRoot\assets" @updateScope - } - else - { - Update-Help -Module $moduleName -Force -UICulture en-US @updateScope - } - } - else - { - if ($useSourcePath) - { - Update-Help -Module $moduleName -Force -SourcePath "$PSScriptRoot\assets" @updateScope - } - else - { - Update-Help -Module $moduleName -Force @updateScope - } - } + [hashtable] $userScopeParam = $(if ($userscope) { @{ UserScope = $true } } else { @{} }) + ValidateInstalledHelpContent -moduleName:$moduleName @userScopeParam - if($userscope) - { - ValidateInstalledHelpContent -moduleName $moduleName -UserScope - } - else - { - ValidateInstalledHelpContent -moduleName $moduleName - } } if ($tag -eq "CI") @@ -289,9 +258,9 @@ function RunSaveHelpTests It "Validate Save-Help for the '$moduleName' module" -Pending:$pending { - if ((Get-UICulture).Name -ne "en-Us") + if ((Get-UICulture).Name -ne $myUICulture) { - Save-Help -Module $moduleName -Force -UICulture en-US -DestinationPath $saveHelpFolder + Save-Help -Module $moduleName -Force -UICulture $myUICulture -DestinationPath $saveHelpFolder } else { @@ -347,7 +316,7 @@ Describe "Validate Update-Help from the Web for one PowerShell module." -Tags @( $ProgressPreference = $SavedProgressPreference } - RunUpdateHelpTests -Tag "CI" -Scope 'AllUsers' + RunUpdateHelpTests -Tag "CI" } Describe "Validate Update-Help from the Web for one PowerShell module for user scope." -Tags @('CI', 'RequireAdminOnWindows', 'RequireSudoOnUnix') { @@ -359,7 +328,7 @@ Describe "Validate Update-Help from the Web for one PowerShell module for user s $ProgressPreference = $SavedProgressPreference } - RunUpdateHelpTests -Tag "CI" -Scope 'CurrentUser' + RunUpdateHelpTests -Tag "CI" -UserScope } Describe "Validate Update-Help from the Web for all PowerShell modules." -Tags @('Feature', 'RequireAdminOnWindows', 'RequireSudoOnUnix') { @@ -371,7 +340,7 @@ Describe "Validate Update-Help from the Web for all PowerShell modules." -Tags @ $ProgressPreference = $SavedProgressPreference } - RunUpdateHelpTests -Tag "Feature" -Scope 'AllUsers' + RunUpdateHelpTests -Tag "Feature" } Describe "Validate Update-Help from the Web for all PowerShell modules for user scope." -Tags @('Feature', 'RequireAdminOnWindows', 'RequireSudoOnUnix') { @@ -383,7 +352,7 @@ Describe "Validate Update-Help from the Web for all PowerShell modules for user $ProgressPreference = $SavedProgressPreference } - RunUpdateHelpTests -Tag "Feature" -Scope 'CurrentUser' + RunUpdateHelpTests -Tag "Feature" -UserScope } Describe "Validate Update-Help -SourcePath for one PowerShell module." -Tags @('CI', 'RequireAdminOnWindows', 'RequireSudoOnUnix') { @@ -395,7 +364,7 @@ Describe "Validate Update-Help -SourcePath for one PowerShell module." -Tags @(' $ProgressPreference = $SavedProgressPreference } - RunUpdateHelpTests -Tag "CI" -useSourcePath -Scope 'AllUsers' + RunUpdateHelpTests -Tag "CI" -useSourcePath } Describe "Validate Update-Help -SourcePath for one PowerShell module for user scope." -Tags @('CI', 'RequireAdminOnWindows', 'RequireSudoOnUnix') { @@ -407,7 +376,7 @@ Describe "Validate Update-Help -SourcePath for one PowerShell module for user sc $ProgressPreference = $SavedProgressPreference } - RunUpdateHelpTests -Tag "CI" -useSourcePath -Scope 'CurrentUser' + RunUpdateHelpTests -Tag "CI" -useSourcePath -UserScope } Describe "Validate Update-Help -SourcePath for all PowerShell modules." -Tags @('Feature', 'RequireAdminOnWindows', 'RequireSudoOnUnix') { @@ -419,7 +388,7 @@ Describe "Validate Update-Help -SourcePath for all PowerShell modules." -Tags @( $ProgressPreference = $SavedProgressPreference } - RunUpdateHelpTests -Tag "Feature" -useSourcePath -Scope 'AllUsers' + RunUpdateHelpTests -Tag "Feature" -useSourcePath } Describe "Validate Update-Help -SourcePath for all PowerShell modules for user scope." -Tags @('Feature', 'RequireAdminOnWindows', 'RequireSudoOnUnix') { @@ -431,7 +400,7 @@ Describe "Validate Update-Help -SourcePath for all PowerShell modules for user s $ProgressPreference = $SavedProgressPreference } - RunUpdateHelpTests -Tag "Feature" -useSourcePath -Scope 'CurrentUser' + RunUpdateHelpTests -Tag "Feature" -useSourcePath -UserScope } Describe "Validate 'Update-Help' shows 'HelpCultureNotSupported' when thrown" -Tags @('Feature') { From e5728b63bfcc92af73a43f9d55078fdb55059a01 Mon Sep 17 00:00:00 2001 From: Paul Higinbotham Date: Mon, 22 May 2023 16:40:55 -0700 Subject: [PATCH 548/779] Add WDAC Audit logging (#19641) --- .../commands/utility/AddType.cs | 25 ++- .../commands/utility/Import-LocalizedData.cs | 12 +- .../utility/InvokeExpressionCommand.cs | 11 ++ .../commands/utility/New-Object.cs | 65 +++++--- .../resources/AddTypeStrings.resx | 6 + .../resources/ImportLocalizedDataStrings.resx | 6 + .../resources/NewObjectStrings.resx | 12 ++ .../resources/UtilityCommonStrings.resx | 6 + .../host/msh/ConsoleHost.cs | 10 +- .../resources/ManagedEntranceStrings.resx | 3 + .../CoreCLR/CorePsStub.cs | 24 ++- .../engine/Attributes.cs | 21 ++- .../engine/CommandProcessor.cs | 3 +- .../engine/CommandProcessorBase.cs | 41 +++-- .../engine/CommandSearcher.cs | 19 ++- .../ExperimentalFeature.cs | 4 + .../engine/ExternalScriptInfo.cs | 33 +++- .../engine/InternalCommands.cs | 22 ++- .../engine/LanguagePrimitives.cs | 47 ++++-- .../Modules/ExportModuleMemberCommand.cs | 17 ++- .../engine/Modules/ModuleCmdletBase.cs | 143 ++++++++++++++---- .../engine/Modules/ModuleIntrinsics.cs | 13 -- .../engine/Modules/NewModuleCommand.cs | 26 +++- .../engine/ParameterBinderBase.cs | 5 +- .../engine/ScriptCommandProcessor.cs | 2 +- .../engine/SessionStateFunctionAPIs.cs | 3 +- .../engine/SessionStateScope.cs | 19 ++- .../engine/Utils.cs | 47 +++--- .../engine/debugger/debugger.cs | 33 ++++ .../engine/hostifaces/PSTask.cs | 19 ++- .../engine/parser/Parser.cs | 47 ++++-- .../engine/parser/SemanticChecks.cs | 22 ++- .../remoting/commands/PSRemotingCmdlet.cs | 2 +- .../engine/remoting/commands/StartJob.cs | 2 +- .../engine/remoting/common/PSETWTracer.cs | 4 +- .../engine/runtime/Binding/Binders.cs | 45 ++++-- .../engine/runtime/CompiledScriptBlock.cs | 24 ++- .../engine/runtime/Operations/MiscOps.cs | 38 ++++- .../logging/LogProvider.cs | 24 +++ .../resources/AutomationExceptions.resx | 6 + .../resources/CommandBaseStrings.resx | 12 ++ .../resources/ExtendedTypeSystem.resx | 12 ++ .../resources/InternalCommandStrings.resx | 6 + .../resources/Metadata.resx | 6 + .../resources/Modules.resx | 42 +++++ .../resources/ParameterBinderStrings.resx | 12 ++ .../resources/ParserStrings.resx | 30 ++++ .../resources/SecuritySupportStrings.resx | 6 + .../resources/SessionStateStrings.resx | 6 + .../security/wldpNativeMethods.cs | 106 ++++++++++--- .../utils/tracing/PSEtwLog.cs | 14 ++ .../utils/tracing/PSEtwLogProvider.cs | 14 ++ .../utils/tracing/PSSysLogProvider.cs | 14 ++ 53 files changed, 963 insertions(+), 228 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs index d7954178063..4ac0f4f3199 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs @@ -556,15 +556,24 @@ protected override void BeginProcessing() { // Prevent code compilation in ConstrainedLanguage mode, or NoLanguage mode under system lock down. if (SessionState.LanguageMode == PSLanguageMode.ConstrainedLanguage || - (SessionState.LanguageMode == PSLanguageMode.NoLanguage && - SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce)) + (SessionState.LanguageMode == PSLanguageMode.NoLanguage && SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce)) { - ThrowTerminatingError( - new ErrorRecord( - new PSNotSupportedException(AddTypeStrings.CannotDefineNewType), - nameof(AddTypeStrings.CannotDefineNewType), - ErrorCategory.PermissionDenied, - targetObject: null)); + if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Audit) + { + ThrowTerminatingError( + new ErrorRecord( + new PSNotSupportedException(AddTypeStrings.CannotDefineNewType), + nameof(AddTypeStrings.CannotDefineNewType), + ErrorCategory.PermissionDenied, + targetObject: null)); + } + + SystemPolicy.LogWDACAuditMessage( + context: Context, + title: AddTypeStrings.AddTypeLogTitle, + message: AddTypeStrings.AddTypeLogMessage, + fqid: "AddTypeCmdletDisabled", + dropIntoDebugger: true); } // 'ConsoleApplication' and 'WindowsApplication' types are currently not working in .NET Core diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Import-LocalizedData.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Import-LocalizedData.cs index 53ab8d32c2f..d69226babb1 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Import-LocalizedData.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Import-LocalizedData.cs @@ -7,6 +7,7 @@ using System.IO; using System.Management.Automation; using System.Management.Automation.Internal; +using System.Management.Automation.Security; namespace Microsoft.PowerShell.Commands { @@ -146,9 +147,9 @@ protected override void ProcessRecord() } // Prevent additional commands in ConstrainedLanguage mode - if (Context.LanguageMode == PSLanguageMode.ConstrainedLanguage) + if (_setSupportedCommand && Context.LanguageMode == PSLanguageMode.ConstrainedLanguage) { - if (_setSupportedCommand) + if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Audit) { NotSupportedException nse = PSTraceSource.NewNotSupportedException( @@ -156,6 +157,13 @@ protected override void ProcessRecord() ThrowTerminatingError( new ErrorRecord(nse, "CannotDefineSupportedCommand", ErrorCategory.PermissionDenied, null)); } + + SystemPolicy.LogWDACAuditMessage( + context: Context, + title: ImportLocalizedDataStrings.WDACLogTitle, + message: ImportLocalizedDataStrings.WDACLogMessage, + fqid: "SupportedCommandsDisabled", + dropIntoDebugger: true); } string script = GetScript(path); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/InvokeExpressionCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/InvokeExpressionCommand.cs index d51f20f8704..acbffeb66f4 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/InvokeExpressionCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/InvokeExpressionCommand.cs @@ -4,6 +4,7 @@ using System; using System.Management.Automation; using System.Management.Automation.Internal; +using System.Management.Automation.Security; namespace Microsoft.PowerShell.Commands { @@ -43,6 +44,16 @@ protected override void ProcessRecord() myScriptBlock.LanguageMode = PSLanguageMode.ConstrainedLanguage; } + if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Audit) + { + SystemPolicy.LogWDACAuditMessage( + context: Context, + title: UtilityCommonStrings.IEXWDACLogTitle, + message: UtilityCommonStrings.IEXWDACLogMessage, + fqid: "InvokeExpressionCmdletConstrained", + dropIntoDebugger: true); + } + var emptyArray = Array.Empty(); myScriptBlock.InvokeUsingCmdlet( contextCmdlet: this, diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/New-Object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/New-Object.cs index 370f4574b5c..f2c31faf400 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/New-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/New-Object.cs @@ -187,18 +187,30 @@ protected override void BeginProcessing() targetObject: null)); } - if (Context.LanguageMode == PSLanguageMode.ConstrainedLanguage) - { - if (!CoreTypes.Contains(type)) - { - ThrowTerminatingError( - new ErrorRecord( - new PSNotSupportedException(NewObjectStrings.CannotCreateTypeConstrainedLanguage), "CannotCreateTypeConstrainedLanguage", ErrorCategory.PermissionDenied, null)); - } - } - switch (Context.LanguageMode) { + case PSLanguageMode.ConstrainedLanguage: + if (!CoreTypes.Contains(type)) + { + if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Audit) + { + ThrowTerminatingError( + new ErrorRecord( + new PSNotSupportedException(NewObjectStrings.CannotCreateTypeConstrainedLanguage), + "CannotCreateTypeConstrainedLanguage", + ErrorCategory.PermissionDenied, + targetObject: null)); + } + + SystemPolicy.LogWDACAuditMessage( + context: Context, + title: NewObjectStrings.TypeWDACLogTitle, + message: StringUtil.Format(NewObjectStrings.TypeWDACLogMessage, type.FullName), + fqid: "NewObjectCmdletCannotCreateType", + dropIntoDebugger: true); + } + break; + case PSLanguageMode.NoLanguage: case PSLanguageMode.RestrictedLanguage: if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce @@ -212,8 +224,7 @@ protected override void BeginProcessing() ErrorCategory.PermissionDenied, targetObject: null)); } - - break; + break; } // WinRT does not support creating instances of attribute & delegate WinRT types. @@ -301,21 +312,31 @@ protected override void BeginProcessing() bool isAllowed = false; // If it's a system-wide lockdown, we may allow additional COM types - if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce) + var systemLockdownPolicy = SystemPolicy.GetSystemLockdownPolicy(); + if (systemLockdownPolicy == SystemEnforcementMode.Enforce || systemLockdownPolicy == SystemEnforcementMode.Audit) { - if ((result >= 0) && - SystemPolicy.IsClassInApprovedList(_comObjectClsId)) - { - isAllowed = true; - } + isAllowed = (result >= 0) && SystemPolicy.IsClassInApprovedList(_comObjectClsId); } if (!isAllowed) { - ThrowTerminatingError( - new ErrorRecord( - new PSNotSupportedException(NewObjectStrings.CannotCreateTypeConstrainedLanguage), "CannotCreateComTypeConstrainedLanguage", ErrorCategory.PermissionDenied, null)); - return; + if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Audit) + { + ThrowTerminatingError( + new ErrorRecord( + new PSNotSupportedException(NewObjectStrings.CannotCreateTypeConstrainedLanguage), + "CannotCreateComTypeConstrainedLanguage", + ErrorCategory.PermissionDenied, + targetObject: null)); + return; + } + + SystemPolicy.LogWDACAuditMessage( + context: Context, + title: NewObjectStrings.ComWDACLogTitle, + message: StringUtil.Format(NewObjectStrings.ComWDACLogMessage, ComObject ?? string.Empty), + fqid: "NewObjectCmdletCannotCreateCOM", + dropIntoDebugger: true); } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/AddTypeStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/AddTypeStrings.resx index ae80d7ded59..6b178fb85eb 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/AddTypeStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/AddTypeStrings.resx @@ -150,4 +150,10 @@ Both the assembly types 'ConsoleApplication' and 'WindowsApplication' are not currently supported. + + Add-Type Cmdlet + + + Add-Type cmdlet will not be allowed in ConstrainedLanguage mode. + diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ImportLocalizedDataStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ImportLocalizedDataStrings.resx index 8bd19d60ac3..cf792788c6f 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/ImportLocalizedDataStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ImportLocalizedDataStrings.resx @@ -143,4 +143,10 @@ The BindingVariable name '{0}' is invalid. + + Import-LocalizedData Cmdlet + + + Additional supported commands (via SupportedCommand parameter) will not be allowed in ConstrainedLanguage mode. + diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/NewObjectStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/NewObjectStrings.resx index 92437a76646..8c8d59034cc 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/NewObjectStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/NewObjectStrings.resx @@ -147,4 +147,16 @@ Cannot create type. Only core types are supported in {0} language mode on a policy locked down machine. + + New-Object Cmdlet Type Creation + + + The type '{0}' will not be created in ConstrainedLanguage mode. + + + New-Object Cmdlet COM Object Creation + + + The COM object '{0}' will not be created in ConstrainedLanguage mode. + diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/UtilityCommonStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/UtilityCommonStrings.resx index b3abafdd04f..0eedd2d38d2 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/UtilityCommonStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/UtilityCommonStrings.resx @@ -168,4 +168,10 @@ Cannot construct a security descriptor from the given SDDL due to the following error: {0} + + Invoke-Expression Cmdlet + + + Invoke-Expression cmdlet script block will be run in ConstrainedLanguage mode. + diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs index 409869cd79e..6e48f2e3338 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs @@ -16,6 +16,7 @@ using System.Management.Automation.Remoting; using System.Management.Automation.Remoting.Server; using System.Management.Automation.Runspaces; +using System.Management.Automation.Security; using System.Management.Automation.Subsystem.Feedback; using System.Management.Automation.Tracing; using System.Reflection; @@ -1855,7 +1856,14 @@ private void DoRunspaceInitialization(RunspaceCreationEventArgs args) switch (languageMode) { case PSLanguageMode.ConstrainedLanguage: - s_theConsoleHost.UI.WriteLine(ManagedEntranceStrings.ShellBannerCLMode); + if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Audit) + { + s_theConsoleHost.UI.WriteLine(ManagedEntranceStrings.ShellBannerCLMode); + } + else + { + s_theConsoleHost.UI.WriteLine(ManagedEntranceStrings.ShellBannerCLAuditMode); + } break; case PSLanguageMode.NoLanguage: diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/ManagedEntranceStrings.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/ManagedEntranceStrings.resx index e435f7662cc..40f02e7a37f 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/resources/ManagedEntranceStrings.resx +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/ManagedEntranceStrings.resx @@ -123,6 +123,9 @@ [Constrained Language Mode] + + [Constrained Language AUDIT Mode : No Restrictions] + [No Language Mode] diff --git a/src/System.Management.Automation/CoreCLR/CorePsStub.cs b/src/System.Management.Automation/CoreCLR/CorePsStub.cs index 122eadce990..6f94acbc389 100644 --- a/src/System.Management.Automation/CoreCLR/CorePsStub.cs +++ b/src/System.Management.Automation/CoreCLR/CorePsStub.cs @@ -435,6 +435,23 @@ internal sealed class SystemPolicy { private SystemPolicy() { } + /// + /// Writes to PowerShell WDAC Audit mode ETW log. + /// + /// Current execution context. + /// Audit message title. + /// Audit message message. + /// Fully Qualified ID. + /// Stops code execution and goes into debugger mode. + internal static void LogWDACAuditMessage( + ExecutionContext context, + string title, + string message, + string fqid, + bool dropIntoDebugger = false) + { + } + /// /// Gets the system lockdown policy. /// @@ -511,7 +528,12 @@ public enum SystemScriptFileEnforcement /// /// Script file is allowed to run in ConstrainedLanguage mode only. /// - AllowConstrained = 3 + AllowConstrained = 3, + + /// + /// Script file is allowed to run in FullLanguage mode but will emit ConstrainedLanguage restriction audit logs. + /// + AllowConstrainedAudit = 4 } } diff --git a/src/System.Management.Automation/engine/Attributes.cs b/src/System.Management.Automation/engine/Attributes.cs index 5b00b9df42b..3e4d848faa2 100644 --- a/src/System.Management.Automation/engine/Attributes.cs +++ b/src/System.Management.Automation/engine/Attributes.cs @@ -9,6 +9,7 @@ using System.Linq; using System.Management.Automation.Internal; using System.Management.Automation.Language; +using System.Management.Automation.Security; using System.Runtime.CompilerServices; using System.Text.RegularExpressions; using System.Threading.Tasks; @@ -1851,11 +1852,21 @@ protected override void Validate(object arguments, EngineIntrinsics engineIntrin { if (ExecutionContext.IsMarkedAsUntrusted(arguments)) { - throw new ValidationMetadataException( - "ValidateTrustedDataFailure", - null, - Metadata.ValidateTrustedDataFailure, - arguments); + if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Audit) + { + throw new ValidationMetadataException( + "ValidateTrustedDataFailure", + null, + Metadata.ValidateTrustedDataFailure, + arguments); + } + + SystemPolicy.LogWDACAuditMessage( + context: null, + title: Metadata.WDACParameterArgNotTrustedLogTitle, + message: StringUtil.Format(Metadata.WDACParameterArgNotTrustedMessage, arguments), + fqid: "ParameterArgumentNotTrusted", + dropIntoDebugger: true); } } } diff --git a/src/System.Management.Automation/engine/CommandProcessor.cs b/src/System.Management.Automation/engine/CommandProcessor.cs index 53c0b688570..d9758cea2fa 100644 --- a/src/System.Management.Automation/engine/CommandProcessor.cs +++ b/src/System.Management.Automation/engine/CommandProcessor.cs @@ -227,6 +227,7 @@ internal override void Prepare(IDictionary psDefaultParameterValues) Context.LanguageMode = scriptCmdletInfo.ScriptBlock.LanguageMode.Value; // If it's from ConstrainedLanguage to FullLanguage, indicate the transition before parameter binding takes place. + // When transitioning to FullLanguage mode, we don't want any ConstrainedLanguage restrictions or incorrect Audit messages. if (oldLanguageMode == PSLanguageMode.ConstrainedLanguage && Context.LanguageMode == PSLanguageMode.FullLanguage) { oldLangModeTransitionStatus = Context.LanguageModeTransitionInParameterBinding; @@ -779,7 +780,7 @@ private void Init(IScriptCommandInfo scriptCommandInfo) // If the script has been dotted, throw an error if it's from a different language mode. if (!this.UseLocalScope) { - ValidateCompatibleLanguageMode(scriptCommandInfo.ScriptBlock, _context.LanguageMode, Command.MyInvocation); + ValidateCompatibleLanguageMode(scriptCommandInfo.ScriptBlock, _context, Command.MyInvocation); } } diff --git a/src/System.Management.Automation/engine/CommandProcessorBase.cs b/src/System.Management.Automation/engine/CommandProcessorBase.cs index 1d0128a8b38..ddadf9f7516 100644 --- a/src/System.Management.Automation/engine/CommandProcessorBase.cs +++ b/src/System.Management.Automation/engine/CommandProcessorBase.cs @@ -4,7 +4,7 @@ using System.Collections; using System.Collections.ObjectModel; using System.Management.Automation.Internal; -using System.Management.Automation.Language; +using System.Management.Automation.Security; using System.Runtime.InteropServices; namespace System.Management.Automation @@ -194,11 +194,11 @@ internal bool UseLocalScope /// be used when a script block is being dotted. /// /// The script block being dotted. - /// The current language mode. + /// The current execution context. /// The invocation info about the command. protected static void ValidateCompatibleLanguageMode( ScriptBlock scriptBlock, - PSLanguageMode languageMode, + ExecutionContext context, InvocationInfo invocationInfo) { // If we are in a constrained language mode (Core or Restricted), block it. @@ -207,10 +207,11 @@ protected static void ValidateCompatibleLanguageMode( // functions that were never designed to handle untrusted data. // This function won't be called for NoLanguage mode so the only direction checked is trusted // (FullLanguage mode) script running in a constrained/restricted session. - if ((scriptBlock.LanguageMode.HasValue) && - (scriptBlock.LanguageMode != languageMode) && - ((languageMode == PSLanguageMode.RestrictedLanguage) || - (languageMode == PSLanguageMode.ConstrainedLanguage))) + var languageMode = context.LanguageMode; + if (scriptBlock.LanguageMode.HasValue && + scriptBlock.LanguageMode != languageMode && + (languageMode == PSLanguageMode.RestrictedLanguage || + languageMode == PSLanguageMode.ConstrainedLanguage)) { // Finally check if script block is really just PowerShell commands plus parameters. // If so then it is safe to dot source across language mode boundaries. @@ -226,14 +227,24 @@ protected static void ValidateCompatibleLanguageMode( if (!isSafeToDotSource) { - ErrorRecord errorRecord = new ErrorRecord( - new NotSupportedException( - DiscoveryExceptions.DotSourceNotSupported), - "DotSourceNotSupported", - ErrorCategory.InvalidOperation, - null); - errorRecord.SetInvocationInfo(invocationInfo); - throw new CmdletInvocationException(errorRecord); + if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Audit) + { + ErrorRecord errorRecord = new ErrorRecord( + new NotSupportedException(DiscoveryExceptions.DotSourceNotSupported), + "DotSourceNotSupported", + ErrorCategory.InvalidOperation, + targetObject: null); + errorRecord.SetInvocationInfo(invocationInfo); + throw new CmdletInvocationException(errorRecord); + } + + string scriptBlockId = scriptBlock.GetFileName() ?? string.Empty; + SystemPolicy.LogWDACAuditMessage( + context: context, + title: CommandBaseStrings.WDACLogTitle, + message: StringUtil.Format(CommandBaseStrings.WDACLogMessage, scriptBlockId, scriptBlock.LanguageMode, languageMode), + fqid: "ScriptBlockDotSourceNotAllowed", + dropIntoDebugger: true); } } } diff --git a/src/System.Management.Automation/engine/CommandSearcher.cs b/src/System.Management.Automation/engine/CommandSearcher.cs index 63bc666e123..9acbae68ad0 100644 --- a/src/System.Management.Automation/engine/CommandSearcher.cs +++ b/src/System.Management.Automation/engine/CommandSearcher.cs @@ -9,6 +9,7 @@ using System.Diagnostics.CodeAnalysis; using System.IO; using System.Management.Automation.Internal; +using System.Management.Automation.Security; using Dbg = System.Management.Automation.Diagnostics; @@ -839,11 +840,21 @@ private static bool ShouldSkipCommandResolutionForConstrainedLanguage(CommandInf return false; } - // Don't return untrusted commands to trusted functions - if ((result.DefiningLanguageMode == PSLanguageMode.ConstrainedLanguage) && - (executionContext.LanguageMode == PSLanguageMode.FullLanguage)) + // Don't return untrusted commands to trusted functions. + if (result.DefiningLanguageMode == PSLanguageMode.ConstrainedLanguage && executionContext.LanguageMode == PSLanguageMode.FullLanguage) { - return true; + if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Audit) + { + return true; + } + + // This audit log message is to inform the user that an expected command will not be available because it is not trusted + // when the machine is in policy enforcement mode. + SystemPolicy.LogWDACAuditMessage( + context: executionContext, + title: CommandBaseStrings.SearcherWDACLogTitle, + message: StringUtil.Format(CommandBaseStrings.SearcherWDACLogMessage, result.Name, result.ModuleName ?? string.Empty), + fqid: "CommandSearchFailureForUntrustedCommand"); } // Don't allow invocation of trusted functions from debug breakpoints. diff --git a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs index bc826fa2780..44646ef1289 100644 --- a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs +++ b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs @@ -27,6 +27,7 @@ public class ExperimentalFeature internal const string PSCustomTableHeaderLabelDecoration = "PSCustomTableHeaderLabelDecoration"; internal const string PSFeedbackProvider = "PSFeedbackProvider"; internal const string PSCommandWithArgs = "PSCommandWithArgs"; + internal const string PSConstrainedAuditLogging = "PSConstrainedAuditLogging"; #endregion @@ -136,6 +137,9 @@ static ExperimentalFeature() new ExperimentalFeature( name: PSCommandWithArgs, description: "Enable `-CommandWithArgs` parameter for pwsh"), + new ExperimentalFeature( + name: PSConstrainedAuditLogging, + description: "PowerShell restriction logging when WDAC (Windows Defender Application Control) Code Integrity policy is set to Audit mode.") }; EngineExperimentalFeatures = new ReadOnlyCollection(engineFeatures); diff --git a/src/System.Management.Automation/engine/ExternalScriptInfo.cs b/src/System.Management.Automation/engine/ExternalScriptInfo.cs index 8e0938605ac..fe23b1b85ce 100644 --- a/src/System.Management.Automation/engine/ExternalScriptInfo.cs +++ b/src/System.Management.Automation/engine/ExternalScriptInfo.cs @@ -103,14 +103,21 @@ private void CommonInitialization() // Get the lock down policy with no handle. This only impacts command discovery, // as the real language mode assignment will be done when we read the script // contents. - SystemEnforcementMode scriptSpecificPolicy = SystemPolicy.GetLockdownPolicy(_path, null); - if (scriptSpecificPolicy != SystemEnforcementMode.Enforce) + switch (SystemPolicy.GetLockdownPolicy(_path, null)) { - this.DefiningLanguageMode = PSLanguageMode.FullLanguage; - } - else - { - this.DefiningLanguageMode = PSLanguageMode.ConstrainedLanguage; + case SystemEnforcementMode.None: + DefiningLanguageMode = PSLanguageMode.FullLanguage; + break; + + case SystemEnforcementMode.Audit: + // For policy audit mode, language mode is set to CL but audit messages are emitted to log + // instead of applying restrictions. + DefiningLanguageMode = PSLanguageMode.ConstrainedLanguage; + break; + + case SystemEnforcementMode.Enforce: + DefiningLanguageMode = PSLanguageMode.ConstrainedLanguage; + break; } } } @@ -523,7 +530,6 @@ private void ReadScriptContents() { DefiningLanguageMode = Context.LanguageMode; } - break; case SystemScriptFileEnforcement.Allow: @@ -534,6 +540,17 @@ private void ReadScriptContents() DefiningLanguageMode = PSLanguageMode.ConstrainedLanguage; break; + case SystemScriptFileEnforcement.AllowConstrainedAudit: + SystemPolicy.LogWDACAuditMessage( + context: Context, + title: SecuritySupportStrings.ExternalScriptWDACLogTitle, + message: string.Format(Globalization.CultureInfo.CurrentUICulture, SecuritySupportStrings.ExternalScriptWDACLogMessage, _path), + fqid: "ScriptFileNotTrustedByPolicy"); + // We set the language mode to Constrained Language, even though in policy audit mode no restrictions are applied + // and instead an audit log message is generated wherever a restriction would be applied. + DefiningLanguageMode = PSLanguageMode.ConstrainedLanguage; + break; + case SystemScriptFileEnforcement.Block: throw new PSSecurityException( string.Format( diff --git a/src/System.Management.Automation/engine/InternalCommands.cs b/src/System.Management.Automation/engine/InternalCommands.cs index 4f13089811d..10739b18960 100644 --- a/src/System.Management.Automation/engine/InternalCommands.cs +++ b/src/System.Management.Automation/engine/InternalCommands.cs @@ -11,6 +11,7 @@ using System.Management.Automation.Internal; using System.Management.Automation.Language; using System.Management.Automation.PSTasks; +using System.Management.Automation.Security; using System.Runtime.CompilerServices; using System.Text; using System.Threading; @@ -1205,14 +1206,25 @@ private bool BlockMethodInLanguageMode(object inputObject) if (Context.LanguageMode == PSLanguageMode.ConstrainedLanguage) { object baseObject = PSObject.Base(inputObject); + var objectType = baseObject.GetType(); - if (!CoreTypes.Contains(baseObject.GetType())) + if (!CoreTypes.Contains(objectType)) { - PSInvalidOperationException exception = - new PSInvalidOperationException(ParserStrings.InvokeMethodConstrainedLanguage); + if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Audit) + { + PSInvalidOperationException exception = + new PSInvalidOperationException(ParserStrings.InvokeMethodConstrainedLanguage); - WriteError(new ErrorRecord(exception, "MethodInvocationNotSupportedInConstrainedLanguage", ErrorCategory.InvalidOperation, null)); - return true; + WriteError(new ErrorRecord(exception, "MethodInvocationNotSupportedInConstrainedLanguage", ErrorCategory.InvalidOperation, null)); + return true; + } + + SystemPolicy.LogWDACAuditMessage( + context: Context, + title: InternalCommandStrings.WDACLogTitle, + message: StringUtil.Format(InternalCommandStrings.WDACLogMessage, objectType.FullName), + fqid: "ForEachObjectCmdletMethodInvocationNotAllowed", + dropIntoDebugger: true); } } diff --git a/src/System.Management.Automation/engine/LanguagePrimitives.cs b/src/System.Management.Automation/engine/LanguagePrimitives.cs index a93bd1658d5..9979d7433e5 100644 --- a/src/System.Management.Automation/engine/LanguagePrimitives.cs +++ b/src/System.Management.Automation/engine/LanguagePrimitives.cs @@ -13,6 +13,7 @@ using System.Management.Automation.Internal; using System.Management.Automation.Language; using System.Management.Automation.Runspaces; +using System.Management.Automation.Security; using System.Numerics; using System.Reflection; using System.Reflection.Emit; @@ -25,7 +26,6 @@ using MethodCacheEntry = System.Management.Automation.DotNetAdapter.MethodCacheEntry; #if !UNIX using System.DirectoryServices; -using System.Management; #endif #pragma warning disable 1634, 1691 // Stops compiler from warning about unknown warnings @@ -4006,9 +4006,21 @@ internal object Convert(object valueToConvert, } else { - RuntimeException rte = InterpreterError.NewInterpreterException(valueToConvert, typeof(RuntimeException), null, - "HashtableToObjectConversionNotSupportedInDataSection", ParserStrings.HashtableToObjectConversionNotSupportedInDataSection, resultType.ToString()); - throw rte; + if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Audit) + { + SystemPolicy.LogWDACAuditMessage( + context: ecFromTLS, + title: ExtendedTypeSystem.WDACHashTypeLogTitle, + message: StringUtil.Format(ExtendedTypeSystem.WDACHashTypeLogMessage, resultType.FullName), + fqid: "LanguageHashtableConversionNotAllowed", + dropIntoDebugger: true); + } + else + { + RuntimeException rte = InterpreterError.NewInterpreterException(valueToConvert, typeof(RuntimeException), null, + "HashtableToObjectConversionNotSupportedInDataSection", ParserStrings.HashtableToObjectConversionNotSupportedInDataSection, resultType.ToString()); + throw rte; + } } return result; @@ -5645,20 +5657,29 @@ internal static IConversionData FigureConversion(Type fromType, Type toType) PSConverter converter = null; ConversionRank rank = ConversionRank.None; - // If we've ever used ConstrainedLanguage, check if the target type is allowed + // If we've ever used ConstrainedLanguage, check if the target type is allowed. if (ExecutionContext.HasEverUsedConstrainedLanguage) { var context = LocalPipeline.GetExecutionContextFromTLS(); - - if ((context != null) && (context.LanguageMode == PSLanguageMode.ConstrainedLanguage)) + if (context?.LanguageMode == PSLanguageMode.ConstrainedLanguage) { - if ((toType != typeof(object)) && - (toType != typeof(object[])) && - (!CoreTypes.Contains(toType))) + if (toType != typeof(object) && + toType != typeof(object[]) && + !CoreTypes.Contains(toType)) { - converter = ConvertNotSupportedConversion; - rank = ConversionRank.None; - return CacheConversion(fromType, toType, converter, rank); + if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Audit) + { + converter = ConvertNotSupportedConversion; + rank = ConversionRank.None; + return CacheConversion(fromType, toType, converter, rank); + } + + SystemPolicy.LogWDACAuditMessage( + context: context, + title: ExtendedTypeSystem.WDACTypeConversionLogTitle, + message: StringUtil.Format(ExtendedTypeSystem.WDACTypeConversionLogMessage, fromType.FullName, toType.FullName), + fqid: "LanguageTypeConversionNotAllowed", + dropIntoDebugger: true); } } } diff --git a/src/System.Management.Automation/engine/Modules/ExportModuleMemberCommand.cs b/src/System.Management.Automation/engine/Modules/ExportModuleMemberCommand.cs index 8520e39258b..3b47bc37f10 100644 --- a/src/System.Management.Automation/engine/Modules/ExportModuleMemberCommand.cs +++ b/src/System.Management.Automation/engine/Modules/ExportModuleMemberCommand.cs @@ -6,6 +6,7 @@ using System.Diagnostics.CodeAnalysis; using System.Management.Automation; using System.Management.Automation.Internal; +using System.Management.Automation.Security; // // Now define the set of commands for manipulating modules. @@ -167,9 +168,19 @@ protected override void ProcessRecord() if (Context.EngineSessionState.Module?.LanguageMode != null && Context.LanguageMode != Context.EngineSessionState.Module.LanguageMode) { - var se = new PSSecurityException(Modules.CannotExportMembersAccrossLanguageBoundaries); - var er = new ErrorRecord(se, "Modules_CannotExportMembersAccrossLanguageBoundaries", ErrorCategory.SecurityError, this); - ThrowTerminatingError(er); + if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Audit) + { + var se = new PSSecurityException(Modules.CannotExportMembersAccrossLanguageBoundaries); + var er = new ErrorRecord(se, "Modules_CannotExportMembersAccrossLanguageBoundaries", ErrorCategory.SecurityError, this); + ThrowTerminatingError(er); + } + + SystemPolicy.LogWDACAuditMessage( + context: Context, + title: Modules.WDACExportModuleCommandLogTitle, + message: StringUtil.Format(Modules.WDACExportModuleCommandLogMessage, Context.EngineSessionState.Module.Name, Context.EngineSessionState.Module.LanguageMode, Context.LanguageMode), + fqid: "ExportModuleMemberCmdletNotAllowed", + dropIntoDebugger: true); } ModuleIntrinsics.ExportModuleMembers(this, diff --git a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs index f476fe6eb82..48b68574f54 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs @@ -890,11 +890,21 @@ private PSModuleInfo LoadModuleNamedInManifest( // Constrained Language session. if (module.LanguageMode != manifestLanguageMode) { - var languageModeError = PSTraceSource.NewInvalidOperationException( - Modules.MismatchedLanguageModes, - module.Name, manifestLanguageMode, module.LanguageMode); - languageModeError.SetErrorId("Modules_MismatchedLanguageModes"); - throw languageModeError; + if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Audit) + { + var languageModeError = PSTraceSource.NewInvalidOperationException( + Modules.MismatchedLanguageModes, + module.Name, manifestLanguageMode, module.LanguageMode); + languageModeError.SetErrorId("Modules_MismatchedLanguageModes"); + throw languageModeError; + } + + SystemPolicy.LogWDACAuditMessage( + context: Context, + title: Modules.WDACMismatchedLanguageModesTitle, + message: Modules.WDACMismatchedLanguageModesMessage, + fqid: "ModulesMismatchedLanguageModes", + dropIntoDebugger: true); } } @@ -3419,13 +3429,25 @@ internal PSModuleInfo LoadModuleManifest( if ((ss != null) && (!ss.Internal.UseExportList)) { // For cross language boundaries, implicitly import all functions only if - // this manifest *does* exort functions explicitly. + // this manifest *does* export functions explicitly. List fnMatchPattern = ( (manifestScriptInfo.DefiningLanguageMode == PSLanguageMode.FullLanguage) && (Context.LanguageMode != PSLanguageMode.FullLanguage) && (exportedFunctions == null) ) ? null : MatchAll; + // If the system is in WDAC policy AUDIT mode, then an export functions restriction should be reported but not applied. + if (fnMatchPattern == null && SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Audit) + { + SystemPolicy.LogWDACAuditMessage( + context: Context, + title: Modules.WDACImplicitFunctionExportLogTitle, + message: StringUtil.Format(Modules.WDACImplicitFunctionExportLogMessage, manifestScriptInfo.ModuleName), + fqid: "ModuleImplicitFunctionExportNotAllowed", + dropIntoDebugger: true); + fnMatchPattern = MatchAll; + } + ModuleIntrinsics.ExportModuleMembers(cmdlet: this, sessionState: ss.Internal, functionPatterns: fnMatchPattern, @@ -5631,12 +5653,23 @@ internal PSModuleInfo LoadModule(PSModuleInfo parentModule, string fileName, str PSModuleInfo module = null; // Block ps1 files from being imported in constrained language. - if (Context.LanguageMode == PSLanguageMode.ConstrainedLanguage && ext.Equals(StringLiterals.PowerShellScriptFileExtension, StringComparison.OrdinalIgnoreCase)) + if (Context.LanguageMode == PSLanguageMode.ConstrainedLanguage && + ext.Equals(StringLiterals.PowerShellScriptFileExtension, StringComparison.OrdinalIgnoreCase)) { - InvalidOperationException invalidOp = new InvalidOperationException(Modules.ImportPSFileNotAllowedInConstrainedLanguage); - ErrorRecord er = new ErrorRecord(invalidOp, "Modules_ImportPSFileNotAllowedInConstrainedLanguage", - ErrorCategory.PermissionDenied, null); - ThrowTerminatingError(er); + if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Audit) + { + InvalidOperationException invalidOp = new InvalidOperationException(Modules.ImportPSFileNotAllowedInConstrainedLanguage); + ErrorRecord er = new ErrorRecord(invalidOp, "Modules_ImportPSFileNotAllowedInConstrainedLanguage", + ErrorCategory.PermissionDenied, null); + ThrowTerminatingError(er); + } + + SystemPolicy.LogWDACAuditMessage( + context: Context, + title: Modules.WDACScriptFileImportLogTitle, + message: StringUtil.Format(Modules.WDACScriptFileImportLogMessage, fileName), + fqid: "ModuleImportScriptFilesNotAllowed", + dropIntoDebugger: true); } // If MinimumVersion/RequiredVersion/MaximumVersion has been specified, then only try to process manifest modules... @@ -5720,19 +5753,31 @@ internal PSModuleInfo LoadModule(PSModuleInfo parentModule, string fileName, str // If the script didn't call Export-ModuleMember explicitly, then // implicitly export functions and cmdlets. + var systemLockdownPolicy = SystemPolicy.GetSystemLockdownPolicy(); if (!module.SessionState.Internal.UseExportList) { // For cross language boundaries don't implicitly export all functions, unless they are allowed nested modules. // Implicit function export is allowed when any of the following is true: // - Nested modules are allowed by module manifest // - The import context language mode is FullLanguage - // - This script module not running as trusted (FullLanguage) + // - This script module is not running as trusted (FullLanguage) module.ModuleAutoExportsAllFunctions = options.AllowNestedModuleFunctionsToExport || Context.LanguageMode == PSLanguageMode.FullLanguage || psm1ScriptInfo.DefiningLanguageMode != PSLanguageMode.FullLanguage; - List fnMatchPattern = module.ModuleAutoExportsAllFunctions ? MatchAll : null; + // If the system is in WDAC policy AUDIT mode, then an export functions restriction should be reported but not applied. + if (fnMatchPattern == null && systemLockdownPolicy == SystemEnforcementMode.Audit) + { + SystemPolicy.LogWDACAuditMessage( + context: Context, + title: Modules.WDACImplicitFunctionExportLogTitle, + message: StringUtil.Format(Modules.WDACImplicitFunctionExportLogMessage, module.Name), + fqid: "ModuleImplicitFunctionExportNotAllowed", + dropIntoDebugger: true); + fnMatchPattern = MatchAll; + } + ModuleIntrinsics.ExportModuleMembers( cmdlet: this, sessionState: module.SessionState.Internal, @@ -5742,8 +5787,8 @@ internal PSModuleInfo LoadModule(PSModuleInfo parentModule, string fileName, str variablePatterns: null, doNotExportCmdlets: null); } - else if ((SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce) && - (module.LanguageMode == PSLanguageMode.FullLanguage) && + else if ((systemLockdownPolicy == SystemEnforcementMode.Enforce || systemLockdownPolicy == SystemEnforcementMode.Audit) && + module.LanguageMode == PSLanguageMode.FullLanguage && module.SessionState.Internal.FunctionsExportedWithWildcard && !module.SessionState.Internal.ManifestWithExplicitFunctionExport) { @@ -5751,10 +5796,10 @@ internal PSModuleInfo LoadModule(PSModuleInfo parentModule, string fileName, str // exported functions only come from this module and not from any imported nested modules. // Unless there is a parent manifest that explicitly filters all exported functions (no wildcards). // This prevents unintended public exposure of imported functions running in FullLanguage. - ModuleIntrinsics.RemoveNestedModuleFunctions(module); + RemoveNestedModuleFunctions(Context, module, systemLockdownPolicy); } - CheckForDisallowedDotSourcing(module.SessionState, psm1ScriptInfo, options); + CheckForDisallowedDotSourcing(module, psm1ScriptInfo, options); // Add it to the all module tables ImportModuleMembers(module, prefix, options); @@ -5908,7 +5953,7 @@ internal PSModuleInfo LoadModule(PSModuleInfo parentModule, string fileName, str if (module != null) { - CheckForDisallowedDotSourcing(module.SessionState, psd1ScriptInfo, options); + CheckForDisallowedDotSourcing(module, psd1ScriptInfo, options); if (importingModule) { @@ -6073,25 +6118,28 @@ internal PSModuleInfo LoadModule(PSModuleInfo parentModule, string fileName, str } private void CheckForDisallowedDotSourcing( - SessionState ss, + PSModuleInfo moduleInfo, ExternalScriptInfo scriptInfo, ImportModuleOptions options) { - if (ss == null || ss.Internal == null) - { return; } + if (moduleInfo.SessionState == null || moduleInfo.SessionState.Internal == null) + { + return; + } // A manifest with explicit function export is detected through a shared session state or the nested module options, because nested // module processing does not use a shared session state. - var manifestWithExplicitFunctionExport = ss.Internal.ManifestWithExplicitFunctionExport || options.AllowNestedModuleFunctionsToExport; + var manifestWithExplicitFunctionExport = moduleInfo.SessionState.Internal.ManifestWithExplicitFunctionExport || options.AllowNestedModuleFunctionsToExport; // If system is in lock down mode, we disallow trusted modules that use the dotsource operator while simultaneously using // wild cards for exporting module functions, unless there is an overriding manifest that explicitly exports functions // without wild cards. // This is because dotsourcing brings functions into module scope and it is too easy to inadvertently or maliciously // expose harmful private functions that run in trusted (FullLanguage) mode. - if (!manifestWithExplicitFunctionExport && ss.Internal.FunctionsExportedWithWildcard && - (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce) && - (scriptInfo.DefiningLanguageMode == PSLanguageMode.FullLanguage)) + var systemLockdownPolicy = SystemPolicy.GetSystemLockdownPolicy(); + if (!manifestWithExplicitFunctionExport && moduleInfo.SessionState.Internal.FunctionsExportedWithWildcard && + (systemLockdownPolicy == SystemEnforcementMode.Enforce || systemLockdownPolicy == SystemEnforcementMode.Audit) && + scriptInfo.DefiningLanguageMode == PSLanguageMode.FullLanguage) { var dotSourceOperator = scriptInfo.GetScriptBlockAst().FindAll(ast => { @@ -6102,14 +6150,49 @@ private void CheckForDisallowedDotSourcing( if (dotSourceOperator != null) { - var errorRecord = new ErrorRecord( - new PSSecurityException(Modules.CannotUseDotSourceWithWildCardFunctionExport), - "Modules_SystemLockDown_CannotUseDotSourceWithWildCardFunctionExport", - ErrorCategory.SecurityError, null); - ThrowTerminatingError(errorRecord); + if (systemLockdownPolicy != SystemEnforcementMode.Audit) + { + var errorRecord = new ErrorRecord( + new PSSecurityException(Modules.CannotUseDotSourceWithWildCardFunctionExport), + "Modules_SystemLockDown_CannotUseDotSourceWithWildCardFunctionExport", + ErrorCategory.SecurityError, null); + ThrowTerminatingError(errorRecord); + } + + SystemPolicy.LogWDACAuditMessage( + context: Context, + title: Modules.WDACModuleDotSourceLogTitle, + message: StringUtil.Format(Modules.WDACModuleDotSourceLogMessage, moduleInfo.Name), + fqid: "ModuleImportDotSourceNotAllowed", + dropIntoDebugger: true); } } } + + private static void RemoveNestedModuleFunctions( + ExecutionContext context, + PSModuleInfo module, + SystemEnforcementMode systemLockdownPolicy) + { + var input = module.SessionState?.Internal?.ExportedFunctions; + if (input == null || input.Count == 0) + { + return; + } + + if (systemLockdownPolicy != SystemEnforcementMode.Audit) + { + input.RemoveAll(fnInfo => !module.Name.Equals(fnInfo.ModuleName, StringComparison.OrdinalIgnoreCase)); + return; + } + + SystemPolicy.LogWDACAuditMessage( + context: context, + title: Modules.WDACModuleFnExportWithNestedModulesLogTitle, + message: StringUtil.Format(Modules.WDACModuleFnExportWithNestedModulesLogMessage, module.Name), + fqid: "ModuleExportWithWildcardCharactersNotAllowed", + dropIntoDebugger: true); + } private static bool ShouldProcessScriptModule(PSModuleInfo parentModule, ref bool found) { diff --git a/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs b/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs index cab7ed6c083..e2c446f5ac9 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs @@ -1446,19 +1446,6 @@ private static string ProcessOneModulePath(ExecutionContext context, string envP return null; } - /// - /// Removes all functions not belonging to the parent module. - /// - /// Parent module. - internal static void RemoveNestedModuleFunctions(PSModuleInfo module) - { - var input = module.SessionState?.Internal?.ExportedFunctions; - if ((input == null) || (input.Count == 0)) - { return; } - - input.RemoveAll(fnInfo => !module.Name.Equals(fnInfo.ModuleName, StringComparison.OrdinalIgnoreCase)); - } - #nullable enable private static void SortAndRemoveDuplicates(List input, Func keyGetter) { diff --git a/src/System.Management.Automation/engine/Modules/NewModuleCommand.cs b/src/System.Management.Automation/engine/Modules/NewModuleCommand.cs index d47681166a0..ceb5dd3c2e3 100644 --- a/src/System.Management.Automation/engine/Modules/NewModuleCommand.cs +++ b/src/System.Management.Automation/engine/Modules/NewModuleCommand.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Management.Automation; +using System.Management.Automation.Security; // // Now define the set of commands for manipulating modules. @@ -168,15 +169,24 @@ protected override void EndProcessing() { // Check ScriptBlock language mode. If it is different than the context language mode // then throw error since private trusted script functions may be exposed. - if (Context.LanguageMode == PSLanguageMode.ConstrainedLanguage && - _scriptBlock.LanguageMode == PSLanguageMode.FullLanguage) + if (Context.LanguageMode == PSLanguageMode.ConstrainedLanguage && _scriptBlock.LanguageMode == PSLanguageMode.FullLanguage) { - this.ThrowTerminatingError( - new ErrorRecord( - new PSSecurityException(Modules.CannotCreateModuleWithScriptBlock), - "Modules_CannotCreateModuleWithFullLanguageScriptBlock", - ErrorCategory.SecurityError, - null)); + if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Audit) + { + this.ThrowTerminatingError( + new ErrorRecord( + new PSSecurityException(Modules.CannotCreateModuleWithScriptBlock), + "Modules_CannotCreateModuleWithFullLanguageScriptBlock", + ErrorCategory.SecurityError, + targetObject: null)); + } + + SystemPolicy.LogWDACAuditMessage( + context: Context, + title: Modules.WDACNewModuleCommandLogTitle, + message: Modules.WDACNewModuleCommandLogMessage, + fqid: "NewModuleCmdletWitFullLanguageScriptblockNotAllowed", + dropIntoDebugger: true); } string gs = System.Guid.NewGuid().ToString(); diff --git a/src/System.Management.Automation/engine/ParameterBinderBase.cs b/src/System.Management.Automation/engine/ParameterBinderBase.cs index af2dca4aee4..21868b1a28d 100644 --- a/src/System.Management.Automation/engine/ParameterBinderBase.cs +++ b/src/System.Management.Automation/engine/ParameterBinderBase.cs @@ -1244,8 +1244,9 @@ private object CoerceTypeAsNeeded( // However, we don't allow Hashtable-to-Object conversion (PSObject and IDictionary) because // those can lead to property setters that probably aren't expected. This is enforced by // setting 'Context.LanguageModeTransitionInParameterBinding' to true before the conversion. + var currentLanguageMode = Context.LanguageMode; bool changeLanguageModeForTrustedCommand = - Context.LanguageMode == PSLanguageMode.ConstrainedLanguage && + currentLanguageMode == PSLanguageMode.ConstrainedLanguage && this.Command.CommandInfo.DefiningLanguageMode == PSLanguageMode.FullLanguage; bool oldLangModeTransitionStatus = Context.LanguageModeTransitionInParameterBinding; @@ -1263,7 +1264,7 @@ private object CoerceTypeAsNeeded( { if (changeLanguageModeForTrustedCommand) { - Context.LanguageMode = PSLanguageMode.ConstrainedLanguage; + Context.LanguageMode = currentLanguageMode; Context.LanguageModeTransitionInParameterBinding = oldLangModeTransitionStatus; } } diff --git a/src/System.Management.Automation/engine/ScriptCommandProcessor.cs b/src/System.Management.Automation/engine/ScriptCommandProcessor.cs index 3fcb66f3180..32bec9fd5a9 100644 --- a/src/System.Management.Automation/engine/ScriptCommandProcessor.cs +++ b/src/System.Management.Automation/engine/ScriptCommandProcessor.cs @@ -122,7 +122,7 @@ protected void CommonInitialization(ScriptBlock scriptBlock, ExecutionContext co // language modes (getting internal functions in the user's state) isn't a danger if ((!this.UseLocalScope) && (!this._rethrowExitException)) { - ValidateCompatibleLanguageMode(_scriptBlock, context.LanguageMode, Command.MyInvocation); + ValidateCompatibleLanguageMode(_scriptBlock, context, Command.MyInvocation); } } diff --git a/src/System.Management.Automation/engine/SessionStateFunctionAPIs.cs b/src/System.Management.Automation/engine/SessionStateFunctionAPIs.cs index f444f46d2c3..5ef285ddcec 100644 --- a/src/System.Management.Automation/engine/SessionStateFunctionAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateFunctionAPIs.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.Management.Automation.Language; using System.Management.Automation.Runspaces; +using System.Management.Automation.Security; using Dbg = System.Management.Automation.Diagnostics; @@ -184,7 +185,7 @@ private bool IsFunctionVisibleInDebugger(FunctionInfo fnInfo, CommandOrigin orig // Early out. // Always allow built-in functions needed for command line debugging. - if ((this.ExecutionContext.LanguageMode == PSLanguageMode.FullLanguage) || + if (this.ExecutionContext.LanguageMode == PSLanguageMode.FullLanguage || (fnInfo == null) || (fnInfo.Name.Equals("prompt", StringComparison.OrdinalIgnoreCase)) || (fnInfo.Name.Equals("TabExpansion2", StringComparison.OrdinalIgnoreCase)) || diff --git a/src/System.Management.Automation/engine/SessionStateScope.cs b/src/System.Management.Automation/engine/SessionStateScope.cs index 6a13e2f8d0b..03ab9bdfb4b 100644 --- a/src/System.Management.Automation/engine/SessionStateScope.cs +++ b/src/System.Management.Automation/engine/SessionStateScope.cs @@ -6,6 +6,7 @@ using System.Linq; using System.Management.Automation.Internal; using System.Management.Automation.Runspaces; +using System.Management.Automation.Security; namespace System.Management.Automation { @@ -1984,11 +1985,21 @@ private void CheckVariableChangeInConstrainedLanguage(PSVariable variable) var context = LocalPipeline.GetExecutionContextFromTLS(); if (context?.LanguageMode == PSLanguageMode.ConstrainedLanguage) { - if ((variable.Options & ScopedItemOptions.AllScope) == ScopedItemOptions.AllScope) + if (variable.Options.HasFlag(ScopedItemOptions.AllScope)) { - // Don't let people set AllScope variables in ConstrainedLanguage, as they can be used to - // interfere with the session state of trusted commands. - throw new PSNotSupportedException(); + if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Audit) + { + // Don't let people set AllScope variables in ConstrainedLanguage, as they can be used to + // interfere with the session state of trusted commands. + throw new PSNotSupportedException(); + } + + SystemPolicy.LogWDACAuditMessage( + context: context, + title: SessionStateStrings.WDACSessionStateVarLogTitle, + message: StringUtil.Format(SessionStateStrings.WDACSessionStateVarLogMessage, variable.Name), + fqid: "AllScopeVariableNotAllowed", + dropIntoDebugger: true); } // Mark untrusted values for assignments to 'Global:' variables, and 'Script:' variables in diff --git a/src/System.Management.Automation/engine/Utils.cs b/src/System.Management.Automation/engine/Utils.cs index f5af933e00f..680d03e2c6e 100644 --- a/src/System.Management.Automation/engine/Utils.cs +++ b/src/System.Management.Automation/engine/Utils.cs @@ -1469,27 +1469,40 @@ internal static bool IsComObject(object obj) /// The current ExecutionContext language mode. internal static PSLanguageMode EnforceSystemLockDownLanguageMode(ExecutionContext context) { - if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce) + switch (SystemPolicy.GetSystemLockdownPolicy()) { - switch (context.LanguageMode) - { - case PSLanguageMode.FullLanguage: - context.LanguageMode = PSLanguageMode.ConstrainedLanguage; - break; + case SystemEnforcementMode.Enforce: + switch (context.LanguageMode) + { + case PSLanguageMode.FullLanguage: + context.LanguageMode = PSLanguageMode.ConstrainedLanguage; + break; - case PSLanguageMode.RestrictedLanguage: - context.LanguageMode = PSLanguageMode.NoLanguage; - break; + case PSLanguageMode.RestrictedLanguage: + context.LanguageMode = PSLanguageMode.NoLanguage; + break; - case PSLanguageMode.ConstrainedLanguage: - case PSLanguageMode.NoLanguage: - break; + case PSLanguageMode.ConstrainedLanguage: + case PSLanguageMode.NoLanguage: + break; - default: - Diagnostics.Assert(false, "Unexpected PSLanguageMode"); - context.LanguageMode = PSLanguageMode.NoLanguage; - break; - } + default: + Diagnostics.Assert(false, "Unexpected PSLanguageMode"); + context.LanguageMode = PSLanguageMode.NoLanguage; + break; + } + break; + + case SystemEnforcementMode.Audit: + switch (context.LanguageMode) + { + case PSLanguageMode.FullLanguage: + // Set to ConstrainedLanguage mode. But no restrictions are applied in audit mode + // and only audit messages will be emitted to logs. + context.LanguageMode = PSLanguageMode.ConstrainedLanguage; + break; + } + break; } return context.LanguageMode; diff --git a/src/System.Management.Automation/engine/debugger/debugger.cs b/src/System.Management.Automation/engine/debugger/debugger.cs index 2d154bec0f2..3d8d3f24658 100644 --- a/src/System.Management.Automation/engine/debugger/debugger.cs +++ b/src/System.Management.Automation/engine/debugger/debugger.cs @@ -790,6 +790,16 @@ internal virtual void Break(object triggerObject = null) throw new PSNotImplementedException(); } + /// + /// Returns script position message of current execution stack item. + /// This is used for WDAC audit mode logging for script information enhancement. + /// + /// Script position message string. + internal virtual string GetCurrentScriptPosition() + { + throw new PSNotImplementedException(); + } + /// /// Passes the debugger command to the internal script debugger command processor. This /// is used internally to handle debugger commands such as list, help, etc. @@ -2519,6 +2529,29 @@ internal override void Break(object triggerObject = null) } } + /// + /// Returns script position message of current execution stack item. + /// This is used for WDAC audit mode logging for script information enhancement. + /// + /// Script position message string. + internal override string GetCurrentScriptPosition() + { + using (IEnumerator enumerator = GetCallStack().GetEnumerator()) + { + if (enumerator.MoveNext()) + { + var functionContext = enumerator.Current.FunctionContext; + if (functionContext is not null) + { + var invocationInfo = new InvocationInfo(commandInfo: null, functionContext.CurrentPosition, _context); + return $"\n{invocationInfo.PositionMessage}"; + } + } + } + + return null; + } + /// /// Passes the debugger command to the internal script debugger command processor. This /// is used internally to handle debugger commands such as list, help, etc. diff --git a/src/System.Management.Automation/engine/hostifaces/PSTask.cs b/src/System.Management.Automation/engine/hostifaces/PSTask.cs index 5a1cef70602..c56225f3bb7 100644 --- a/src/System.Management.Automation/engine/hostifaces/PSTask.cs +++ b/src/System.Management.Automation/engine/hostifaces/PSTask.cs @@ -936,8 +936,23 @@ private Runspace GetRunspace(int taskId) // Create and initialize a new Runspace var iss = InitialSessionState.CreateDefault2(); - iss.LanguageMode = (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce) - ? PSLanguageMode.ConstrainedLanguage : PSLanguageMode.FullLanguage; + switch (SystemPolicy.GetSystemLockdownPolicy()) + { + case SystemEnforcementMode.Enforce: + iss.LanguageMode = PSLanguageMode.ConstrainedLanguage; + break; + + case SystemEnforcementMode.Audit: + // In audit mode, CL restrictions are not enforced and instead audit + // log entries are created. + iss.LanguageMode = PSLanguageMode.ConstrainedLanguage; + break; + + case SystemEnforcementMode.None: + iss.LanguageMode = PSLanguageMode.FullLanguage; + break; + } + runspace = RunspaceFactory.CreateRunspace(iss); runspace.Name = runspaceName; _activeRunspaces.TryAdd(runspace.Id, runspace); diff --git a/src/System.Management.Automation/engine/parser/Parser.cs b/src/System.Management.Automation/engine/parser/Parser.cs index 09023536241..610fcba18ad 100644 --- a/src/System.Management.Automation/engine/parser/Parser.cs +++ b/src/System.Management.Automation/engine/parser/Parser.cs @@ -9,11 +9,12 @@ using System.IO; using System.Linq; using System.Management.Automation.Runspaces; +using System.Management.Automation.Security; +using System.Management.Automation.Subsystem; +using System.Management.Automation.Subsystem.DSC; using System.Reflection; using System.Runtime.CompilerServices; using System.Threading.Tasks; -using System.Management.Automation.Subsystem; -using System.Management.Automation.Subsystem.DSC; using Dsc = Microsoft.PowerShell.DesiredStateConfiguration.Internal; namespace System.Management.Automation.Language @@ -2984,13 +2985,23 @@ private StatementAst ConfigurationStatementRule(IEnumerable custom } // Configuration is not supported on ARM or in ConstrainedLanguage - if (PsUtils.IsRunningOnProcessorArchitectureARM() || Runspace.DefaultRunspace.ExecutionContext.LanguageMode == PSLanguageMode.ConstrainedLanguage) + if (PsUtils.IsRunningOnProcessorArchitectureARM() || Runspace.DefaultRunspace?.ExecutionContext?.LanguageMode == PSLanguageMode.ConstrainedLanguage) { - ReportError(configurationToken.Extent, - nameof(ParserStrings.ConfigurationNotAllowedInConstrainedLanguage), - ParserStrings.ConfigurationNotAllowedInConstrainedLanguage, - configurationToken.Kind.Text()); - return null; + if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Audit) + { + ReportError(configurationToken.Extent, + nameof(ParserStrings.ConfigurationNotAllowedInConstrainedLanguage), + ParserStrings.ConfigurationNotAllowedInConstrainedLanguage, + configurationToken.Kind.Text()); + return null; + } + + SystemPolicy.LogWDACAuditMessage( + context: Runspace.DefaultRunspace?.ExecutionContext, + title: ParserStrings.WDACParserConfigKeywordLogTitle, + message: ParserStrings.WDACParserConfigKeywordLogMessage, + fqid: "ConfigurationLanguageKeywordNotAllowed", + dropIntoDebugger: true); } // Configuration is not supported on WinPE @@ -4203,12 +4214,22 @@ private StatementAst ClassDefinitionRule(List customAttributes // PowerShell classes are not supported in ConstrainedLanguage if (Runspace.DefaultRunspace?.ExecutionContext?.LanguageMode == PSLanguageMode.ConstrainedLanguage) { - ReportError(classToken.Extent, - nameof(ParserStrings.ClassesNotAllowedInConstrainedLanguage), - ParserStrings.ClassesNotAllowedInConstrainedLanguage, - classToken.Kind.Text()); + if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Audit) + { + ReportError(classToken.Extent, + nameof(ParserStrings.ClassesNotAllowedInConstrainedLanguage), + ParserStrings.ClassesNotAllowedInConstrainedLanguage, + classToken.Kind.Text()); - return null; + return null; + } + + SystemPolicy.LogWDACAuditMessage( + context: Runspace.DefaultRunspace?.ExecutionContext, + title: ParserStrings.WDACParserClassKeywordLogTitle, + message: ParserStrings.WDACParserClassKeywordLogMessage, + fqid: "ClassLanguageKeywordNotAllowed", + dropIntoDebugger: true); } SkipNewlines(); diff --git a/src/System.Management.Automation/engine/parser/SemanticChecks.cs b/src/System.Management.Automation/engine/parser/SemanticChecks.cs index b8853ab16a8..6201e9a9382 100644 --- a/src/System.Management.Automation/engine/parser/SemanticChecks.cs +++ b/src/System.Management.Automation/engine/parser/SemanticChecks.cs @@ -5,12 +5,12 @@ using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Linq; -using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; using Microsoft.PowerShell; +using System.Management.Automation.Security; using System.Management.Automation.Subsystem; using System.Management.Automation.Subsystem.DSC; using Microsoft.PowerShell.DesiredStateConfiguration.Internal; @@ -1832,11 +1832,21 @@ internal static void CheckDataStatementLanguageModeAtRuntime(DataStatementAst da // we only need to check the language mode. if (executionContext.LanguageMode == PSLanguageMode.ConstrainedLanguage) { - var parser = new Parser(); - parser.ReportError(dataStatementAst.CommandsAllowed[0].Extent, - nameof(ParserStrings.DataSectionAllowedCommandDisallowed), - ParserStrings.DataSectionAllowedCommandDisallowed); - throw new ParseException(parser.ErrorList.ToArray()); + if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Audit) + { + var parser = new Parser(); + parser.ReportError(dataStatementAst.CommandsAllowed[0].Extent, + nameof(ParserStrings.DataSectionAllowedCommandDisallowed), + ParserStrings.DataSectionAllowedCommandDisallowed); + throw new ParseException(parser.ErrorList.ToArray()); + } + + SystemPolicy.LogWDACAuditMessage( + context: executionContext, + title: ParserStrings.WDACParserDSSupportedCommandLogTitle, + message: ParserStrings.WDACParserDSSupportedCommandLogMessage, + fqid: "SupportedCommandInDataSectionNotSupported", + dropIntoDebugger: true); } } diff --git a/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs b/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs index ff86e894e82..7c32733bb1f 100644 --- a/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs +++ b/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs @@ -2332,7 +2332,7 @@ private System.Management.Automation.PowerShell ConvertToPowerShell() try { // This is trusted input as long as we're in FullLanguage mode - bool isTrustedInput = (Context.LanguageMode == PSLanguageMode.FullLanguage); + bool isTrustedInput = Context.LanguageMode == PSLanguageMode.FullLanguage; powershell = _scriptBlock.GetPowerShell(isTrustedInput, _args); } catch (ScriptBlockToPowerShellNotSupportedException) diff --git a/src/System.Management.Automation/engine/remoting/commands/StartJob.cs b/src/System.Management.Automation/engine/remoting/commands/StartJob.cs index 3a2f5d6d55d..fba57ee2101 100644 --- a/src/System.Management.Automation/engine/remoting/commands/StartJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/StartJob.cs @@ -646,7 +646,7 @@ protected override void CreateHelpersForSpecifiedComputerNames() { // If we're in ConstrainedLanguage mode and the system is in lockdown mode, // ensure that they haven't specified a ScriptBlock or InitScript - as - // we can't protect that boundary + // we can't protect that boundary. if ((Context.LanguageMode == PSLanguageMode.ConstrainedLanguage) && (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Enforce) && ((ScriptBlock != null) || (InitializationScript != null))) diff --git a/src/System.Management.Automation/engine/remoting/common/PSETWTracer.cs b/src/System.Management.Automation/engine/remoting/common/PSETWTracer.cs index b9c599d53e5..2fd2dc0a913 100644 --- a/src/System.Management.Automation/engine/remoting/common/PSETWTracer.cs +++ b/src/System.Management.Automation/engine/remoting/common/PSETWTracer.cs @@ -160,6 +160,7 @@ internal enum PSEventId : int Engine_Trace = 0x1F06, Amsi_Init = 0x4001, WDAC_Query = 0x4002, + WDAC_Audit = 0x4003, // Experimental Features ExperimentalFeature_InvalidName = 0x3001, @@ -243,7 +244,8 @@ internal enum PSTask : int NamedPipe = 0x6F, ISEOperation = 0x78, Amsi = 0X82, - WDAC = 0x83 + WDAC = 0x83, + WDACAudit = 0x84 } /// diff --git a/src/System.Management.Automation/engine/runtime/Binding/Binders.cs b/src/System.Management.Automation/engine/runtime/Binding/Binders.cs index d5517443a62..e3ea3d0b44b 100644 --- a/src/System.Management.Automation/engine/runtime/Binding/Binders.cs +++ b/src/System.Management.Automation/engine/runtime/Binding/Binders.cs @@ -12,6 +12,7 @@ using System.Linq.Expressions; using System.Management.Automation.Internal; using System.Management.Automation.Runspaces; +using System.Management.Automation.Security; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -5506,15 +5507,30 @@ private Expression ThrowPropertyNotFoundStrict() new object[] { Name }); } - internal static DynamicMetaObject EnsureAllowedInLanguageMode(ExecutionContext context, DynamicMetaObject target, object targetValue, + internal static DynamicMetaObject EnsureAllowedInLanguageMode(DynamicMetaObject target, object targetValue, string name, bool isStatic, DynamicMetaObject[] args, BindingRestrictions moreTests, string errorID, string resourceString) { - if (context != null && context.LanguageMode == PSLanguageMode.ConstrainedLanguage) + var context = LocalPipeline.GetExecutionContextFromTLS(); + if (context == null) + { + return null; + } + + if (context.LanguageMode == PSLanguageMode.ConstrainedLanguage && + !IsAllowedInConstrainedLanguage(targetValue, name, isStatic)) { - if (!IsAllowedInConstrainedLanguage(targetValue, name, isStatic)) + if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Audit) { return target.ThrowRuntimeError(args, moreTests, errorID, resourceString); } + + string targetName = (targetValue as Type)?.FullName; + SystemPolicy.LogWDACAuditMessage( + context: context, + title: ParameterBinderStrings.WDACBinderInvocationLogTitle, + message: StringUtil.Format(ParameterBinderStrings.WDACBinderInvocationLogMessage, name, targetName ?? string.Empty), + fqid: "MethodOrPropertyInvocationNotAllowed", + dropIntoDebugger: true); } return null; @@ -6168,10 +6184,9 @@ public override DynamicMetaObject FallbackSetMember(DynamicMetaObject target, Dy { restrictions = restrictions.Merge(BinderUtils.GetLanguageModeCheckIfHasEverUsedConstrainedLanguage()); - // Validate that this is allowed in the current language mode - var context = LocalPipeline.GetExecutionContextFromTLS(); + // Validate that this is allowed in the current language mode. DynamicMetaObject runtimeError = PSGetMemberBinder.EnsureAllowedInLanguageMode( - context, target, targetValue, Name, _static, new[] { value }, restrictions, + target, targetValue, Name, _static, new[] { value }, restrictions, "PropertySetterNotSupportedInConstrainedLanguage", ParserStrings.PropertySetConstrainedLanguage); if (runtimeError != null) { @@ -6721,10 +6736,9 @@ public override DynamicMetaObject FallbackInvokeMember(DynamicMetaObject target, { restrictions = restrictions.Merge(BinderUtils.GetLanguageModeCheckIfHasEverUsedConstrainedLanguage()); - // Validate that this is allowed in the current language mode - var context = LocalPipeline.GetExecutionContextFromTLS(); + // Validate that this is allowed in the current language mode. DynamicMetaObject runtimeError = PSGetMemberBinder.EnsureAllowedInLanguageMode( - context, target, targetValue, Name, _static, args, restrictions, + target, targetValue, Name, _static, args, restrictions, "MethodInvocationNotSupportedInConstrainedLanguage", ParserStrings.InvokeMethodConstrainedLanguage); if (runtimeError != null) { @@ -7678,7 +7692,18 @@ public override DynamicMetaObject FallbackCreateInstance(DynamicMetaObject targe var context = LocalPipeline.GetExecutionContextFromTLS(); if (context != null && context.LanguageMode == PSLanguageMode.ConstrainedLanguage && !CoreTypes.Contains(instanceType)) { - return target.ThrowRuntimeError(restrictions, "CannotCreateTypeConstrainedLanguage", ParserStrings.CannotCreateTypeConstrainedLanguage).WriteToDebugLog(this); + if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Audit) + { + return target.ThrowRuntimeError(restrictions, "CannotCreateTypeConstrainedLanguage", ParserStrings.CannotCreateTypeConstrainedLanguage).WriteToDebugLog(this); + } + + string targetName = instanceType?.FullName; + SystemPolicy.LogWDACAuditMessage( + context: context, + title: ParameterBinderStrings.WDACBinderTypeCreationLogTitle, + message: StringUtil.Format(ParameterBinderStrings.WDACBinderTypeCreationLogMessage, targetName ?? string.Empty), + fqid: "TypeCreationNotAllowed", + dropIntoDebugger: true); } restrictions = args.Aggregate(restrictions, static (current, arg) => current.Merge(arg.PSGetMethodArgumentRestriction())); diff --git a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs index d62c58b4bca..3088667f6b2 100644 --- a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs +++ b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs @@ -10,6 +10,7 @@ using System.Management.Automation.Internal; using System.Management.Automation.Language; using System.Management.Automation.Runspaces; +using System.Management.Automation.Security; using System.Management.Automation.Tracing; using System.Reflection; using System.Runtime.Serialization; @@ -1051,12 +1052,11 @@ internal void InvokeWithPipeImpl( var oldScopeOrigin = context.EngineSessionState.CurrentScope.ScopeOrigin; var oldSessionState = context.EngineSessionState; - // If the script block has a different language mode than the current, + // If the script block has a different language mode than the current context, // change the language mode. PSLanguageMode? oldLanguageMode = null; PSLanguageMode? newLanguageMode = null; - if (this.LanguageMode.HasValue - && this.LanguageMode != context.LanguageMode) + if (this.LanguageMode.HasValue && this.LanguageMode != context.LanguageMode) { // Don't allow context: ConstrainedLanguage -> FullLanguage transition if // this is dot sourcing into the current scope, unless it is within a trusted module scope. @@ -1067,6 +1067,20 @@ internal void InvokeWithPipeImpl( oldLanguageMode = context.LanguageMode; newLanguageMode = this.LanguageMode; } + else if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Audit) + { + string scriptBlockId = this.GetFileName() ?? string.Empty; + SystemPolicy.LogWDACAuditMessage( + context: context, + title: AutomationExceptions.WDACCompiledScriptBlockLogTitle, + message: StringUtil.Format(AutomationExceptions.WDACCompiledScriptBlockLogMessage, scriptBlockId, this.LanguageMode, context.LanguageMode), + fqid: "ScriptBlockDotSourceNotAllowed", + dropIntoDebugger: true); + + // Since we are in audit mode, go ahead and allow the language transition. + oldLanguageMode = context.LanguageMode; + newLanguageMode = this.LanguageMode; + } } Dictionary backupWhenDotting = null; @@ -2360,8 +2374,8 @@ private void RunClause(Action clause, object dollarUnderbar, ob // change the language mode. PSLanguageMode? oldLanguageMode = null; PSLanguageMode? newLanguageMode = null; - if (_scriptBlock.LanguageMode.HasValue - && _scriptBlock.LanguageMode != Context.LanguageMode) + if (_scriptBlock.LanguageMode.HasValue && + _scriptBlock.LanguageMode != Context.LanguageMode) { oldLanguageMode = Context.LanguageMode; newLanguageMode = _scriptBlock.LanguageMode; diff --git a/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs b/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs index 152fb289145..583288905c2 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs @@ -13,6 +13,7 @@ using System.Management.Automation.Internal.Host; using System.Management.Automation.Language; using System.Management.Automation.Runspaces; +using System.Management.Automation.Security; using System.Numerics; using System.Reflection; using System.Runtime.CompilerServices; @@ -54,13 +55,24 @@ private static CommandProcessorBase AddCommand(PipelineProcessor pipe, throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException), null, "CantInvokeInNonImportedModule", ParserStrings.CantInvokeInNonImportedModule, mi.Name); } - else if (((invocationToken == TokenKind.Ampersand) || (invocationToken == TokenKind.Dot)) && (mi.LanguageMode != context.LanguageMode)) + else if ((invocationToken == TokenKind.Ampersand || invocationToken == TokenKind.Dot) && mi.LanguageMode != context.LanguageMode) { - // Disallow FullLanguage "& (Get-Module MyModule) MyPrivateFn" from ConstrainedLanguage because it always - // runs "internal" origin and so has access to all functions, including non-exported functions. - // Otherwise we end up leaking non-exported functions that run in FullLanguage. - throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException), null, - "CantInvokeCallOperatorAcrossLanguageBoundaries", ParserStrings.CantInvokeCallOperatorAcrossLanguageBoundaries); + if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Audit) + { + // Disallow FullLanguage "& (Get-Module MyModule) MyPrivateFn" from ConstrainedLanguage because it always + // runs "internal" origin and so has access to all functions, including non-exported functions. + // Otherwise we end up leaking non-exported functions that run in FullLanguage. + throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException), null, + "CantInvokeCallOperatorAcrossLanguageBoundaries", ParserStrings.CantInvokeCallOperatorAcrossLanguageBoundaries); + } + + // In audit mode, report but don't enforce. + SystemPolicy.LogWDACAuditMessage( + context: context, + title: ParserStrings.WDACParserModuleScopeCallOperatorLogTitle, + message: ParserStrings.WDACParserModuleScopeCallOperatorLogMessage, + fqid: "ModuleScopeCallOperatorNotAllowed", + dropIntoDebugger: true); } commandSessionState = mi.SessionState.Internal; @@ -3025,8 +3037,18 @@ internal static object ForEach(IEnumerator enumerator, object expression, object { if (!CoreTypes.Contains(basedCurrent.GetType())) { - throw InterpreterError.NewInterpreterException(current, typeof(PSInvalidOperationException), - null, "MethodInvocationNotSupportedInConstrainedLanguage", ParserStrings.InvokeMethodConstrainedLanguage); + if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Audit) + { + throw InterpreterError.NewInterpreterException(current, typeof(PSInvalidOperationException), + null, "MethodInvocationNotSupportedInConstrainedLanguage", ParserStrings.InvokeMethodConstrainedLanguage); + } + + SystemPolicy.LogWDACAuditMessage( + context: context, + title: ParserStrings.WDACParserForEachOperatorLogTitle, + message: StringUtil.Format(ParserStrings.WDACParserForEachOperatorLogMessage, method.Name ?? string.Empty), + fqid: "ForEachOperatorMethodInvocationNotAllowed", + dropIntoDebugger: true); } } diff --git a/src/System.Management.Automation/logging/LogProvider.cs b/src/System.Management.Automation/logging/LogProvider.cs index b7de1f60b4e..6bcc2b7c132 100644 --- a/src/System.Management.Automation/logging/LogProvider.cs +++ b/src/System.Management.Automation/logging/LogProvider.cs @@ -122,6 +122,17 @@ internal abstract void LogWDACQueryEvent( int querySuccess, int queryResult); + /// + /// Provider interface function for logging WDAC audit event. + /// + /// Title of WDAC audit event. + /// WDAC audit event message. + /// FullyQualifiedId of WDAC audit event. + internal abstract void LogWDACAuditEvent( + string title, + string message, + string fqid); + /// /// True if the log provider needs to use logging variables. /// @@ -414,6 +425,19 @@ internal override void LogWDACQueryEvent( { } + /// + /// Provider interface function for logging WDAC audit event. + /// + /// Title of WDAC audit event. + /// WDAC audit event message. + /// FullyQualifiedId of WDAC audit event. + internal override void LogWDACAuditEvent( + string title, + string message, + string fqid) + { + } + #endregion } } diff --git a/src/System.Management.Automation/resources/AutomationExceptions.resx b/src/System.Management.Automation/resources/AutomationExceptions.resx index 6c4c8fe0d92..899d9e57ac8 100644 --- a/src/System.Management.Automation/resources/AutomationExceptions.resx +++ b/src/System.Management.Automation/resources/AutomationExceptions.resx @@ -201,4 +201,10 @@ Cannot get the value of the Using expression '{0}' in the specified variable dictionary. When creating a PowerShell instance from a script block, the Using expression cannot contain an indexing operation or member-accessing operation. + + Compiled Script Block Dot Source + + + Script block '{0}' invocation into current scope will be disallowed in Constrained Language mode. Script language mode: {1}, Context language mode: {2}. + diff --git a/src/System.Management.Automation/resources/CommandBaseStrings.resx b/src/System.Management.Automation/resources/CommandBaseStrings.resx index abb918adb16..0ff1aac4716 100644 --- a/src/System.Management.Automation/resources/CommandBaseStrings.resx +++ b/src/System.Management.Automation/resources/CommandBaseStrings.resx @@ -228,4 +228,16 @@ Reviewed by TArcher on 2010-07-20 Command '{0}' was not found. The specified command must be an executable. + + Script Block Processing Dot-Source Check + + + Dot-Source processing for script block '{0}' will fail in Constrained Language mode because its language mode '{1}' does not match the current language mode '{2}'. + + + Command Searcher + + + Command '{0}' in module '{1}' is untrusted and will not be accessible in ConstrainedLanguage mode. + diff --git a/src/System.Management.Automation/resources/ExtendedTypeSystem.resx b/src/System.Management.Automation/resources/ExtendedTypeSystem.resx index 3a84b103102..195fdbb7a1b 100644 --- a/src/System.Management.Automation/resources/ExtendedTypeSystem.resx +++ b/src/System.Management.Automation/resources/ExtendedTypeSystem.resx @@ -388,4 +388,16 @@ PS> [System.Collections.Generic.Comparer``1]::get_Default() Cannot create an instance of the ByRef-like type "{0}". ByRef-like types are not supported in PowerShell. + + Extended Type System Hashtable Conversion + + + Type conversion from HashTable to '{0}' will not be allowed in ConstrainedLanguage mode. + + + Extended Type System Hashtable Conversion + + + Type conversion from '{0}' to '{1}' will not be allowed in ConstrainedLanguage mode. + diff --git a/src/System.Management.Automation/resources/InternalCommandStrings.resx b/src/System.Management.Automation/resources/InternalCommandStrings.resx index 4f2705670bc..81658d60d4a 100644 --- a/src/System.Management.Automation/resources/InternalCommandStrings.resx +++ b/src/System.Management.Automation/resources/InternalCommandStrings.resx @@ -184,4 +184,10 @@ ErrorAction, WarningAction, InformationAction, PipelineVariable An unexpected error has occurred while processing ForEach-Object -Parallel input. This may mean that some of the piped input did not get processed. Error: {0}. + + ForEach-Object Cmdlet + + + Method invocation on type '{0}' will not be allowed when run in Constrained Language mode. + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/Metadata.resx b/src/System.Management.Automation/resources/Metadata.resx index 4aac4753bcb..de0a30f77e2 100644 --- a/src/System.Management.Automation/resources/Metadata.resx +++ b/src/System.Management.Automation/resources/Metadata.resx @@ -258,4 +258,10 @@ Cannot process input. The argument "{0}" is not trusted. + + ValidateTrustedData Attribute Check Failure + + + The parameter argument '{0}' is not trusted and will fail the ValidateTrustedData parameter attribute check in Constrained Language mode. + diff --git a/src/System.Management.Automation/resources/Modules.resx b/src/System.Management.Automation/resources/Modules.resx index 2e50a3c5317..b6cc75d6fa7 100644 --- a/src/System.Management.Automation/resources/Modules.resx +++ b/src/System.Management.Automation/resources/Modules.resx @@ -627,4 +627,46 @@ Cannot find the built-in module '{0}' that is compatible with the 'Core' edition. Please make sure the PowerShell built-in modules are available. They usually come with the PowerShell package under the $PSHOME module path, and are required for PowerShell to function properly. + + Export-ModuleMember Cmdlet + + + Export of module members will fail in Constrained Language mode because module '{0}', has a language mode '{1}' that is different from the current session '{2}'. + + + Module Implicit Function Export + + + Implicit function export for module '{0}' will be denied because it is trusted (runs in Full Language mode) but the session is not trusted (runs in Constrained Language mode). It is best practice to always export module functions individually by full name. + + + Importing Script File as Module + + + Importing the script file '{0}' as a module will be disallowed in ConstrainedLanguage mode. + + + Module Contains Dot-Source Operator + + + Module '{0}' import will in fail Constrained Language mode because it exports functions using wildcard characters while also using the dot-source operator. + + + "Module Exporting Functions + + + Module '{0}' exports functions using name wildcard characters. Any nested module function names will be removed when running in Constrained Language mode. + + + "New-Module Cmdlet + + + A new module from an untrusted Constrained Language session will be blocked from providing the FullLanguage script block. + + + "Module Mismatched Language Modes + + + A dependent module is being loaded that has a different language mode than the parent. This will be disallowed when in Constrained Language mode. + diff --git a/src/System.Management.Automation/resources/ParameterBinderStrings.resx b/src/System.Management.Automation/resources/ParameterBinderStrings.resx index 88cb8cade8d..5dc76271e35 100644 --- a/src/System.Management.Automation/resources/ParameterBinderStrings.resx +++ b/src/System.Management.Automation/resources/ParameterBinderStrings.resx @@ -246,4 +246,16 @@ The key '{0}' has already been added to the dictionary. + + Method or Property Invocation Not Allowed + + + Invocation of Method or Property '{0}' on type '{1}' will not be allowed in Constrained Language mode for untrusted scripts. + + + Type Creation Not Allowed + + + Creation of Type '{0}' will not be allowed during parameter binding in Constrained Language mode for untrusted scripts. + diff --git a/src/System.Management.Automation/resources/ParserStrings.resx b/src/System.Management.Automation/resources/ParserStrings.resx index 75618a7dec7..f59f7428995 100644 --- a/src/System.Management.Automation/resources/ParserStrings.resx +++ b/src/System.Management.Automation/resources/ParserStrings.resx @@ -1328,4 +1328,34 @@ ModuleVersion : Version of module to import. If used, ModuleName must represent Directly invoking the 'clean' block of a script block is not supported. + + Parser Configuration Keyword + + + The Configuration keyword will not be allowed in Constrained Language mode for untrusted script. + + + Parser Class Keyword + + + The Class keyword will not be allowed in Constrained Language mode for untrusted script. + + + Parser Data Section SupportedCommand + + + The Data Section that includes the SupportedCommand parameter would be disallowed in Constrained Language mode for untrusted script. + + + Module Scope Call Operator + + + The module scope call operator will be denied in Constrained Language mode. + + + ForEach Keyword Method Invocation + + + The ForEach keyword will fail '{0}' iteration item method invocation when run in Constrained Language mode. + diff --git a/src/System.Management.Automation/resources/SecuritySupportStrings.resx b/src/System.Management.Automation/resources/SecuritySupportStrings.resx index cf1ca357cc4..c49261af24c 100644 --- a/src/System.Management.Automation/resources/SecuritySupportStrings.resx +++ b/src/System.Management.Automation/resources/SecuritySupportStrings.resx @@ -159,4 +159,10 @@ An unknown script file policy enforcement value was returned: {0}. + + Script File Read + + + Script file '{0}' is not trusted by policy and will run in ConstrainedLanguage mode. + diff --git a/src/System.Management.Automation/resources/SessionStateStrings.resx b/src/System.Management.Automation/resources/SessionStateStrings.resx index 72af3dfea4c..e597fa665b6 100644 --- a/src/System.Management.Automation/resources/SessionStateStrings.resx +++ b/src/System.Management.Automation/resources/SessionStateStrings.resx @@ -648,4 +648,10 @@ '{0}' parameter cannot be null or empty. + + Session State Variables + + + Changing or creating the variable '{0}' scope to AllScope will be prevented in ConstrainedLanguage mode. + diff --git a/src/System.Management.Automation/security/wldpNativeMethods.cs b/src/System.Management.Automation/security/wldpNativeMethods.cs index 2fadcedb06b..a95a78dbdbe 100644 --- a/src/System.Management.Automation/security/wldpNativeMethods.cs +++ b/src/System.Management.Automation/security/wldpNativeMethods.cs @@ -36,7 +36,12 @@ public enum SystemScriptFileEnforcement /// /// Script file is allowed to run in ConstrainedLanguage mode only. /// - AllowConstrained = 3 + AllowConstrained = 3, + + /// + /// Script file is allowed to run in FullLanguage mode but will emit ConstrainedLanguage restriction audit logs. + /// + AllowConstrainedAudit = 4 } /// @@ -68,6 +73,65 @@ private SystemPolicy() { } + /// + /// Writes to PowerShell WDAC Audit mode ETW log. + /// + /// Current execution context. + /// Audit message title. + /// Audit message message. + /// Fully Qualified ID. + /// Stops code execution and goes into debugger mode. + internal static void LogWDACAuditMessage( + ExecutionContext context, + string title, + string message, + string fqid, + bool dropIntoDebugger = false) + { + string messageToWrite = message; + + // Augment the log message with current script information from the script debugger, if available. + context ??= System.Management.Automation.Runspaces.LocalPipeline.GetExecutionContextFromTLS(); + bool debuggerAvailable = context is not null && + context._debugger is not null && + context._debugger is ScriptDebugger; + + if (debuggerAvailable) + { + var scriptPosMessage = context._debugger.GetCurrentScriptPosition(); + if (!string.IsNullOrEmpty(scriptPosMessage)) + { + messageToWrite = message + scriptPosMessage; + } + } + + PSEtwLog.LogWDACAuditEvent(title, messageToWrite, fqid); + + // We drop into the debugger only if requested and we are running in the interactive host session runspace (Id == 1). + if (debuggerAvailable && + dropIntoDebugger is true && + context._debugger.DebugMode.HasFlag(DebugModes.LocalScript) && + System.Management.Automation.Runspaces.Runspace.DefaultRunspace.Id == 1 && + context.DebugPreferenceVariable.HasFlag(ActionPreference.Break) && + context.InternalHost?.UI is not null) + { + try + { + context.InternalHost.UI.WriteLine(); + context.InternalHost.UI.WriteLine("WDAC Audit Log:"); + context.InternalHost.UI.WriteLine($"Title: {title}"); + context.InternalHost.UI.WriteLine($"Message: {message}"); + context.InternalHost.UI.WriteLine($"FullyQualifedId: {fqid}"); + context.InternalHost.UI.WriteLine("Stopping script execution in debugger..."); + context.InternalHost.UI.WriteLine(); + + context._debugger.Break(); + } + catch + { } + } + } + /// /// Gets the system lockdown policy. /// @@ -109,10 +173,12 @@ public static SystemScriptFileEnforcement GetFilePolicyEnforcement( System.IO.FileStream fileStream) { SafeHandle fileHandle = fileStream.SafeFileHandle; + var systemLockdownPolicy = SystemPolicy.GetSystemLockdownPolicy(); - // First check latest WDAC APIs if available. Also revert to legacy APIs if debug hook is in effect. + // First check latest WDAC APIs if available. + // Revert to legacy APIs if system policy is in AUDIT mode or debug hook is in effect. Exception errorException = null; - if (s_wldpCanExecuteAvailable && !s_allowDebugOverridePolicy) + if (s_wldpCanExecuteAvailable && systemLockdownPolicy == SystemEnforcementMode.Enforce) { try { @@ -170,24 +236,30 @@ public static SystemScriptFileEnforcement GetFilePolicyEnforcement( } // Original (legacy) WDAC and AppLocker system checks. - if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.None) + if (systemLockdownPolicy == SystemEnforcementMode.None) { - switch (SystemPolicy.GetLockdownPolicy(filePath, fileHandle)) - { - case SystemEnforcementMode.Enforce: - return SystemScriptFileEnforcement.AllowConstrained; + return SystemScriptFileEnforcement.None; + } - case SystemEnforcementMode.None: - case SystemEnforcementMode.Audit: - return SystemScriptFileEnforcement.Allow; + // Check policy for file. + switch (SystemPolicy.GetLockdownPolicy(filePath, fileHandle)) + { + case SystemEnforcementMode.Enforce: + // File is not allowed by policy enforcement and must run in CL mode. + return SystemScriptFileEnforcement.AllowConstrained; - default: - System.Diagnostics.Debug.Assert(false, "GetFilePolicyEnforcement: Unknown SystemEnforcementMode."); - return SystemScriptFileEnforcement.Block; - } - } + case SystemEnforcementMode.Audit: + // File is allowed but would be run in CL mode if policy was enforced and not audit. + return SystemScriptFileEnforcement.AllowConstrainedAudit; + + case SystemEnforcementMode.None: + // No restrictions, file will run in FL mode. + return SystemScriptFileEnforcement.Allow; - return SystemScriptFileEnforcement.None; + default: + System.Diagnostics.Debug.Assert(false, "GetFilePolicyEnforcement: Unknown SystemEnforcementMode."); + return SystemScriptFileEnforcement.Block; + } } /// diff --git a/src/System.Management.Automation/utils/tracing/PSEtwLog.cs b/src/System.Management.Automation/utils/tracing/PSEtwLog.cs index 706073cff9a..6ec720566d5 100644 --- a/src/System.Management.Automation/utils/tracing/PSEtwLog.cs +++ b/src/System.Management.Automation/utils/tracing/PSEtwLog.cs @@ -144,6 +144,20 @@ internal static void LogWDACQueryEvent( provider.LogWDACQueryEvent(queryName, fileName, querySuccess, queryResult); } + /// + /// Provider interface function for logging WDAC audit event. + /// + /// Title of WDAC audit event. + /// WDAC audit event message. + /// FullyQualifiedId of WDAC audit event. + internal static void LogWDACAuditEvent( + string title, + string message, + string fqid) + { + provider.LogWDACAuditEvent(title, message, fqid); + } + /// /// Provider interface function for logging settings event. /// diff --git a/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs b/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs index 586082a0d43..f90bd92c6ed 100755 --- a/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs +++ b/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs @@ -218,6 +218,20 @@ internal override void LogWDACQueryEvent( WriteEvent(PSEventId.WDAC_Query, PSChannel.Analytic, PSOpcode.Method, PSLevel.Informational, PSTask.WDAC, (PSKeyword)0x0, queryName, fileName, querySuccess, queryResult); } + /// + /// Provider interface function for logging WDAC audit event. + /// + /// Title of WDAC audit event. + /// WDAC audit event message. + /// FullyQualifiedId of WDAC audit event. + internal override void LogWDACAuditEvent( + string title, + string message, + string fqid) + { + WriteEvent(PSEventId.WDAC_Audit, PSChannel.Operational, PSOpcode.Method, PSLevel.Informational, PSTask.WDACAudit, (PSKeyword)0x0, title, message, fqid); + } + /// /// Provider interface function for logging provider lifecycle event. /// diff --git a/src/System.Management.Automation/utils/tracing/PSSysLogProvider.cs b/src/System.Management.Automation/utils/tracing/PSSysLogProvider.cs index e7accd6978c..ffd5b30fceb 100755 --- a/src/System.Management.Automation/utils/tracing/PSSysLogProvider.cs +++ b/src/System.Management.Automation/utils/tracing/PSSysLogProvider.cs @@ -118,6 +118,20 @@ internal override void LogWDACQueryEvent( WriteEvent(PSEventId.WDAC_Query, PSChannel.Analytic, PSOpcode.Method, PSLevel.Informational, PSTask.WDAC, (PSKeyword)0x0, queryName, fileName, querySuccess, queryResult); } + /// + /// Provider interface function for logging WDAC audit event. + /// + /// Title of WDAC audit event. + /// WDAC audit event message. + /// FullyQualifiedId of WDAC audit event. + internal override void LogWDACAuditEvent( + string title, + string message, + string fqid) + { + WriteEvent(PSEventId.WDAC_Audit, PSChannel.Operational, PSOpcode.Method, PSLevel.Informational, PSTask.WDAC, (PSKeyword)0x0, title, message, fqid); + } + /// /// Provider interface function for logging engine lifecycle event. /// From d9697f07ba379a1aff937cc03eaa24db72593a54 Mon Sep 17 00:00:00 2001 From: "James Truher [MSFT]" Date: Mon, 22 May 2023 17:02:31 -0700 Subject: [PATCH 549/779] Add a public API for getting locations of `PSModulePath` elements (#19422) --- .../engine/Modules/ModuleIntrinsics.cs | 36 ++++++++++++++ .../engine/Module/ModulePath.Tests.ps1 | 45 ++++++++++++++++++ .../assets/PowerShell.TestPackage.3.2.1.nupkg | Bin 0 -> 3225 bytes 3 files changed, 81 insertions(+) create mode 100644 test/powershell/engine/Module/assets/PowerShell.TestPackage.3.2.1.nupkg diff --git a/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs b/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs index e2c446f5ac9..fde3618e568 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs @@ -1172,6 +1172,42 @@ private static string AddToPath(string basePath, string pathToAdd, int insertPos return result.ToString(); } + /// + /// The available module path scopes. + /// + public enum PSModulePathScope + { + /// The users module path. + User, + + /// The Builtin module path. This is where PowerShell is installed (PSHOME). + Builtin, + + /// The machine module path. This is the shared location for all users of the system. + Machine + } + + /// + /// Retrieve the current PSModulePath for the specified scope. + /// + /// The scope of module path to retrieve. This can be User, Builtin, or Machine. + /// The string representing the requested module path type. + public static string GetPSModulePath(PSModulePathScope scope) + { + if (scope == PSModulePathScope.User) + { + return GetPersonalModulePath(); + } + else if (scope == PSModulePathScope.Builtin) + { + return GetPSHomeModulePath(); + } + else + { + return GetSharedModulePath(); + } + } + /// /// Checks the various PSModulePath environment string and returns PSModulePath string as appropriate. /// diff --git a/test/powershell/engine/Module/ModulePath.Tests.ps1 b/test/powershell/engine/Module/ModulePath.Tests.ps1 index a18b4fc3ffa..aabbb289500 100644 --- a/test/powershell/engine/Module/ModulePath.Tests.ps1 +++ b/test/powershell/engine/Module/ModulePath.Tests.ps1 @@ -202,3 +202,48 @@ Describe "SxS Module Path Basic Tests" -tags "CI" { $out.Split([System.IO.Path]::PathSeparator, [System.StringSplitOptions]::RemoveEmptyEntries) | Should -Not -BeLike $validation } } + +Describe "ModuleIntrinsics.GetPSModulePath API tests" -tag @('CI', 'RequireAdminOnWindows', 'RequireSudoOnUnix') { + BeforeAll { + # create a local repostory and install a module + $localSourceName = [Guid]::NewGuid().ToString("n") + $localSourceLocation = Join-Path $PSScriptRoot assets + Register-PSRepository -Name $localSourceName -SourceLocation $localSourceLocation -InstallationPolicy Trusted -ErrorAction SilentlyContinue + Install-Module -Force -Scope AllUsers -Name PowerShell.TestPackage -Repository $localSourceName -ErrorAction SilentlyContinue + Install-Module -Force -Scope CurrentUser -Name PowerShell.TestPackage -Repository $localSourceName -ErrorAction SilentlyContinue + + $testCases = @( + @{ Name = "User" ; Expected = $IsWindows ? + (Resolve-Path ([Environment]::GetFolderPath("Personal") + "\PowerShell\Modules")).Path : + (Resolve-Path ([System.Management.Automation.Platform]::SelectProductNameForDirectory("USER_MODULES"))).Path + } + @{ Name = "Machine" ; Expected = $IsWindows ? + [Environment]::GetFolderPath("ProgramFiles") + "\PowerShell\Modules" : + (Resolve-Path ([System.Management.Automation.Platform]::SelectProductNameForDirectory("SHARED_MODULES"))).Path + } + @{ Name = "Builtin" ; Expected = (Resolve-Path (Join-Path $PSHOME Modules)).Path } + ) + # resolve the paths to ensure they are in the correct format + $currentModulePathElements = $env:PSModulePath -split [System.IO.Path]::PathSeparator | Foreach-Object { (Resolve-Path $_).Path } + } + + AfterAll { + Unregister-PSRepository -Name $localSourceName -ErrorAction SilentlyContinue + } + + It "The value '' should return the proper value" -testcase $testCases { + param ( $Name, $Expected ) + $result = [System.Management.Automation.ModuleIntrinsics]::GetPSModulePath($name) + $result | Should -not -BeNullOrEmpty + # spot check pshome, the user and shared paths may not be present + if ( $name -eq "PSHOME") { + $result | Should -Be $Expected + } + } + + It "The current module path should contain the expected paths for ''" -testcase $testCases { + param ( $Name, $Expected ) + $mPath = (Resolve-Path ([System.Management.Automation.ModuleIntrinsics]::GetPSModulePath($name))).Path + $currentModulePathElements | Should -Contain $mPath + } +} diff --git a/test/powershell/engine/Module/assets/PowerShell.TestPackage.3.2.1.nupkg b/test/powershell/engine/Module/assets/PowerShell.TestPackage.3.2.1.nupkg new file mode 100644 index 0000000000000000000000000000000000000000..bc3a6d9b094ff479b0acef2b1e54415e559c339d GIT binary patch literal 3225 zcmb_ecU03$8Vy}Rib(Y-hy|1qLMMWvB1ixUH7cTzgh&ku5K10B5I{sB5E1DmAWe9R zG=b1jKp@ha5D^fh3ZW=%;}OPy%i-QxuE{WeVYXO~9FDJpd^KrOxNN-$ey%!- zH3Sp7h?IU#-7+t?w=i&xG zlPCCL*gB$my5C|Hadqhsqa@*~u25Qp@S*PLDoD&Gmf(MT)2#f8r@9?E)VVO?EK5Z{8>^YVoiy zf-Gr%^FcdgD4Ihh(d#8?re&Q~Ys^7VA_RRVOT*%n$ROEiC2?5uHY=LChVI*888>G?N zV*DHQ%R99iO-q+5UQ{?waxMEUZ?938H)}T&V}?s5E#e}rLF(#}1Lr78-yN)*X26S5T^VRtg0&M73oM$Uf zEP`j7v|gIb2yspT@I+$L_zSy#eqtg)TR6TyxP(3NiFNktk)xGJsjkAbWpN=moBl0F z=R(OoWWgKs;DHz1@016Mw|81An%?n-t&zui4DqLHi8c#xXV)vAT8?~@A5rMB)h@c% zM|$^`mPdOPr|^YPwR}8_|EA{ms1OHmuA=tF=_bMLnFkD3XZQj}@eZVlC;REa8Lt1B3Mzb3nOLKSSQ$}Z1&UcK=^0)cTY5GNvBd!EJ=%Llf z;bE&9XX>QBdD1Ooq@B^vTy4_4^eh4$pb33Da;8>$KEXvjhe;9yGS-MW^v%mws2Elh*_8zF+K*6IQi=TC3aA(=b(CyRA+R@7HCm0onI-XfBOj zA_}E5kh*Yu<8w=e+p;`k1F)&~x*)%C-81?$dAFPba3Qa5<_tTGXcS;Kmw@I_k}I(c zwd&8edeXUNtuU%Cd}BBGMjxx~t12mMtTTIYMSl0Kq`AsKJMq8|YVUHwt*|9;Yab*u z?9N7i&2?uPo2Yptrvs}ypSdwZoi*6|zB`BE>B|Bo7|J$VznEPTK{$MgsPI#FqptMk z3q9ED+Ptp;Gi0P~y!rwe1eYUL3W9G~uZ|gA47K&$P4&HBn((oTS{(`P0P1UDb8Xh} zXQT6)zQjg#J9A~j&Iv4{`jUMVS-uNapv%Hy%P? zH=BIipFjWly}5d!L9DrwXY@njb<;r@iMz$-Yx`%FYK&whsdnT2Z`p%gH99~9<#T{` z4uj))o#N3MEN>{aCKQzMIR@#A^tjE^APot-g&OTXzrWWKh1j!uBvX?4|&ZcCrs=K zx(lw>#kTG^3teLn&}foJ4>Ck`Rp8AP=*P%8+R3V(aYdiUcKsRa@WHde={)Bs^9mMO z?f?sbBG2!o5K7=&eE$A1={qSbGkmi$bc@V_cQ2x%R1IwO)AdfXx!;-cK5WGJri9al zb(5M_a$<-F++A&24+)qNbHmq_pRO)gyx8RtlQ^lm@vuHf40+(xsWq<#+de@9Tdu7I zvGy6frEHT?&1mS$H}C4Z$y$14R=zyV(h6-!Lio*--8PhpEbU~?)QB#hxU{P&HQHs$ z3!MI+9FijT;)*Dd3pPvU?r)CmDg|3LJwjnsR=YD|FfkRoeMcSiah7Qq5tuEa|8S77 z@I_y!Z`VHFym7y`{hEYY?Eah?ZQ^J3x;#;C*2{c;JDBRllsCX_U5pzJ<%YAh#A8vO zcYwZV*A&tPwgjLlx#&$l!vzy66L9gM&aQ0a2#9_iSa-wU_CHc zln2gg} zN8fR4u}8D)#x>1cino*z{);1}&u=+F{9+d;cp^0)V$gNByU)~u6O#Oc*V>chBOS#A zK#hhd?^~vyyuHQ8rs6Gca>+T!Ve{(aVfH)bQSw8lU`DM4BTmjA9zhx|=^o^~@W8Q| zKzcwo+%L(vra$w(kkqfri=Ir=;BShotnk&a~CI{tMs;1uFx-ndI)QD&Gpj5t)(Z}FyuW#+@^Z`Fwl2CmIITg-kMG!Ty z8Y&0b1`uPn(<|xmN?lhj_E%$-8tB!o$;Qq~I3RTZiY@F}yYoiBc7 zZ-sd!2*t`Suo#P6OGf)w8B|8c^F)dcGS)Ls%zFdlv>-F8#>43=koLe5^Sy)rx?~ns zA-4Z)c$qi-&yN!FBmA5FH8uKq;ja$w&t(7rCB%T4HUHJ`{RH(luIDePAZGIYZx8en w9y4`+E#JTJI1l`7G5-qiYwrIAz|Exb|6U2EMjV_!w%}kkGLyVz?jOB>0Jg-hYybcN literal 0 HcmV?d00001 From 86ed508be2e68e0ddb26d9dea77d508a1380d7a0 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 22 May 2023 17:07:32 -0700 Subject: [PATCH 550/779] Bump Microsoft.NET.Test.Sdk from 17.5.0 to 17.6.0 (#19668) --- test/xUnit/xUnit.tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/xUnit/xUnit.tests.csproj b/test/xUnit/xUnit.tests.csproj index 272f21675a8..848958f6b9a 100644 --- a/test/xUnit/xUnit.tests.csproj +++ b/test/xUnit/xUnit.tests.csproj @@ -27,7 +27,7 @@ - + From e1aacd7bdd20b7c22b84f3978e04fe22e1641289 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 22 May 2023 17:08:03 -0700 Subject: [PATCH 551/779] Bump Microsoft.CodeAnalysis.CSharp from 4.6.0-1.final to 4.6.0 (#19667) --- .../Microsoft.PowerShell.Commands.Utility.csproj | 2 +- .../PSVersionInfoGenerator/PSVersionInfoGenerator.csproj | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj index 2972c210a60..5b15de0e2ca 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj +++ b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj @@ -32,7 +32,7 @@ - + diff --git a/src/System.Management.Automation/SourceGenerators/PSVersionInfoGenerator/PSVersionInfoGenerator.csproj b/src/System.Management.Automation/SourceGenerators/PSVersionInfoGenerator/PSVersionInfoGenerator.csproj index be1ad33448e..344ef48674c 100644 --- a/src/System.Management.Automation/SourceGenerators/PSVersionInfoGenerator/PSVersionInfoGenerator.csproj +++ b/src/System.Management.Automation/SourceGenerators/PSVersionInfoGenerator/PSVersionInfoGenerator.csproj @@ -13,7 +13,7 @@ - + From d8decdc1944444efa811d465747c6e9b91b86b82 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Tue, 23 May 2023 02:11:53 +0200 Subject: [PATCH 552/779] Fix slow execution when many breakpoints are used (#14953) --- .../engine/debugger/Breakpoint.cs | 9 +- .../engine/debugger/debugger.cs | 109 ++++++++++++------ .../engine/parser/Compiler.cs | 2 +- 3 files changed, 76 insertions(+), 44 deletions(-) diff --git a/src/System.Management.Automation/engine/debugger/Breakpoint.cs b/src/System.Management.Automation/engine/debugger/Breakpoint.cs index e51d79f4afa..c4b699bd152 100644 --- a/src/System.Management.Automation/engine/debugger/Breakpoint.cs +++ b/src/System.Management.Automation/engine/debugger/Breakpoint.cs @@ -482,9 +482,6 @@ internal bool TrySetBreakpoint(string scriptFile, FunctionContext functionContex { Diagnostics.Assert(SequencePointIndex == -1, "shouldn't be trying to set on a pending breakpoint"); - if (!scriptFile.Equals(this.Script, StringComparison.OrdinalIgnoreCase)) - return false; - // A quick check to see if the breakpoint is within the scriptblock. bool couldBeInNestedScriptBlock; var scriptBlock = functionContext._scriptBlock; @@ -595,11 +592,11 @@ internal override bool RemoveSelf(ScriptDebugger debugger) var boundBreakPoints = debugger.GetBoundBreakpoints(this.SequencePoints); if (boundBreakPoints != null) { - Diagnostics.Assert(boundBreakPoints.Contains(this), + Diagnostics.Assert(boundBreakPoints[this.SequencePointIndex].Contains(this), "If we set _scriptBlock, we should have also added the breakpoint to the bound breakpoint list"); - boundBreakPoints.Remove(this); + boundBreakPoints[this.SequencePointIndex].Remove(this); - if (boundBreakPoints.All(breakpoint => breakpoint.SequencePointIndex != this.SequencePointIndex)) + if (boundBreakPoints[this.SequencePointIndex].All(breakpoint => breakpoint.SequencePointIndex != this.SequencePointIndex)) { // No other line breakpoints are at the same sequence point, so disable the breakpoint so // we don't go looking for breakpoints the next time we hit the sequence point. diff --git a/src/System.Management.Automation/engine/debugger/debugger.cs b/src/System.Management.Automation/engine/debugger/debugger.cs index 3d8d3f24658..c91092772bc 100644 --- a/src/System.Management.Automation/engine/debugger/debugger.cs +++ b/src/System.Management.Automation/engine/debugger/debugger.cs @@ -981,7 +981,8 @@ internal ScriptDebugger(ExecutionContext context) _context = context; _inBreakpoint = false; _idToBreakpoint = new ConcurrentDictionary(); - _pendingBreakpoints = new ConcurrentDictionary(); + // The string key is function context file path. The int key is sequencePoint index. + _pendingBreakpoints = new ConcurrentDictionary>(); _boundBreakpoints = new ConcurrentDictionary>>(StringComparer.OrdinalIgnoreCase); _commandBreakpoints = new ConcurrentDictionary(); _variableBreakpoints = new ConcurrentDictionary>(StringComparer.OrdinalIgnoreCase); @@ -1184,7 +1185,7 @@ internal void EnterScriptFunction(FunctionContext functionContext) private void SetupBreakpoints(FunctionContext functionContext) { var scriptDebugData = _mapScriptToBreakpoints.GetValue(functionContext._sequencePoints, - _ => Tuple.Create(new List(), + _ => Tuple.Create(new Dictionary>(), new BitArray(functionContext._sequencePoints.Length))); functionContext._boundBreakpoints = scriptDebugData.Item1; functionContext._breakPoints = scriptDebugData.Item2; @@ -1264,10 +1265,19 @@ private CommandBreakpoint AddCommandBreakpoint(CommandBreakpoint breakpoint) private LineBreakpoint AddLineBreakpoint(LineBreakpoint breakpoint) { AddBreakpointCommon(breakpoint); - _pendingBreakpoints[breakpoint.Id] = breakpoint; + AddPendingBreakpoint(breakpoint); + return breakpoint; } + private void AddPendingBreakpoint(LineBreakpoint breakpoint) + { + _pendingBreakpoints.AddOrUpdate( + breakpoint.Script, + new ConcurrentDictionary { [breakpoint.Id] = breakpoint }, + (_, dictionary) => { dictionary.TryAdd(breakpoint.Id, breakpoint); return dictionary; }); + } + private void AddNewBreakpoint(Breakpoint breakpoint) { LineBreakpoint lineBreakpoint = breakpoint as LineBreakpoint; @@ -1320,13 +1330,9 @@ private void UpdateBreakpoints(FunctionContext functionContext) return; } - foreach ((int breakpointId, LineBreakpoint item) in _pendingBreakpoints) + if (_pendingBreakpoints.TryGetValue(functionContext._file, out var dictionary) && !dictionary.IsEmpty) { - if (item.IsScriptBreakpoint && item.Script.Equals(functionContext._file, StringComparison.OrdinalIgnoreCase)) - { - SetPendingBreakpoints(functionContext); - break; - } + SetPendingBreakpoints(functionContext); } } } @@ -1352,7 +1358,11 @@ internal bool RemoveCommandBreakpoint(CommandBreakpoint breakpoint) => internal bool RemoveLineBreakpoint(LineBreakpoint breakpoint) { - bool removed = _pendingBreakpoints.Remove(breakpoint.Id, out _); + bool removed = false; + if (_pendingBreakpoints.TryGetValue(breakpoint.Script, out var dictionary)) + { + removed = dictionary.Remove(breakpoint.Id, out _); + } Tuple> value; if (_boundBreakpoints.TryGetValue(breakpoint.Script, out value)) @@ -1370,8 +1380,8 @@ internal bool RemoveLineBreakpoint(LineBreakpoint breakpoint) // The bit array is used to detect if a breakpoint is set or not for a given scriptblock. This bit array // is checked when hitting sequence points. Enabling/disabling a line breakpoint is as simple as flipping // the bit. - private readonly ConditionalWeakTable, BitArray>> _mapScriptToBreakpoints = - new ConditionalWeakTable, BitArray>>(); + private readonly ConditionalWeakTable>, BitArray>> _mapScriptToBreakpoints = + new ConditionalWeakTable>, BitArray>>(); /// /// Checks for command breakpoints. @@ -1472,9 +1482,9 @@ internal void TriggerVariableBreakpoints(List breakpoints) // Return the line breakpoints bound in a specific script block (used when a sequence point // is hit, to find which breakpoints are set on that sequence point.) - internal List GetBoundBreakpoints(IScriptExtent[] sequencePoints) + internal Dictionary> GetBoundBreakpoints(IScriptExtent[] sequencePoints) { - Tuple, BitArray> tuple; + Tuple>, BitArray> tuple; if (_mapScriptToBreakpoints.TryGetValue(sequencePoints, out tuple)) { return tuple.Item1; @@ -1560,16 +1570,25 @@ internal void OnSequencePointHit(FunctionContext functionContext) { if (functionContext._breakPoints[functionContext._currentSequencePointIndex]) { - var breakpoints = (from breakpoint in functionContext._boundBreakpoints - where - breakpoint.SequencePointIndex == functionContext._currentSequencePointIndex && - breakpoint.Enabled - select breakpoint).ToList(); - - breakpoints = TriggerBreakpoints(breakpoints); - if (breakpoints.Count > 0) + if (functionContext._boundBreakpoints.TryGetValue(functionContext._currentSequencePointIndex, out var sequencePointBreakpoints)) { - StopOnSequencePoint(functionContext, breakpoints); + var enabledBreakpoints = new List(); + foreach (Breakpoint breakpoint in sequencePointBreakpoints) + { + if (breakpoint.Enabled) + { + enabledBreakpoints.Add(breakpoint); + } + } + + if (enabledBreakpoints.Count > 0) + { + enabledBreakpoints = TriggerBreakpoints(enabledBreakpoints); + if (enabledBreakpoints.Count > 0) + { + StopOnSequencePoint(functionContext, enabledBreakpoints); + } + } } } } @@ -1683,7 +1702,7 @@ internal void Clear() } private readonly ExecutionContext _context; - private ConcurrentDictionary _pendingBreakpoints; + private readonly ConcurrentDictionary> _pendingBreakpoints; private readonly ConcurrentDictionary>> _boundBreakpoints; private readonly ConcurrentDictionary _commandBreakpoints; private readonly ConcurrentDictionary> _variableBreakpoints; @@ -1991,16 +2010,20 @@ private void UnbindBoundBreakpoints(List boundBreakpoints) foreach (var breakpoint in boundBreakpoints) { // Also remove unbound breakpoints from the script to breakpoint map. - Tuple, BitArray> lineBreakTuple; + Tuple>, BitArray> lineBreakTuple; if (_mapScriptToBreakpoints.TryGetValue(breakpoint.SequencePoints, out lineBreakTuple)) { - lineBreakTuple.Item1.Remove(breakpoint); + if (lineBreakTuple.Item1.TryGetValue(breakpoint.SequencePointIndex, out var lineBreakList)) + { + lineBreakList.Remove(breakpoint); + } } breakpoint.SequencePoints = null; breakpoint.SequencePointIndex = -1; breakpoint.BreakpointBitArray = null; - _pendingBreakpoints[breakpoint.Id] = breakpoint; + + AddPendingBreakpoint(breakpoint); } boundBreakpoints.Clear(); @@ -2008,23 +2031,24 @@ private void UnbindBoundBreakpoints(List boundBreakpoints) private void SetPendingBreakpoints(FunctionContext functionContext) { - if (_pendingBreakpoints.IsEmpty) - return; - - var newPendingBreakpoints = new Dictionary(); var currentScriptFile = functionContext._file; // If we're not in a file, we can't have any line breakpoints. if (currentScriptFile == null) return; + if (!_pendingBreakpoints.TryGetValue(currentScriptFile, out var breakpoints) || breakpoints.IsEmpty) + { + return; + } + // Normally we register a script file when the script is run or the module is imported, // but if there weren't any breakpoints when the script was run and the script was dotted, // we will end up here with pending breakpoints, but we won't have cached the list of // breakpoints in the script. RegisterScriptFile(currentScriptFile, functionContext.CurrentPosition.StartScriptPosition.GetFullScript()); - Tuple, BitArray> tuple; + Tuple>, BitArray> tuple; if (!_mapScriptToBreakpoints.TryGetValue(functionContext._sequencePoints, out tuple)) { Diagnostics.Assert(false, "If the script block is still alive, the entry should not be collected."); @@ -2032,7 +2056,7 @@ private void SetPendingBreakpoints(FunctionContext functionContext) Diagnostics.Assert(tuple.Item1 == functionContext._boundBreakpoints, "What's up?"); - foreach ((int breakpointId, LineBreakpoint breakpoint) in _pendingBreakpoints) + foreach ((int breakpointId, LineBreakpoint breakpoint) in breakpoints) { bool bound = false; if (breakpoint.TrySetBreakpoint(currentScriptFile, functionContext)) @@ -2043,21 +2067,32 @@ private void SetPendingBreakpoints(FunctionContext functionContext) } bound = true; - tuple.Item1.Add(breakpoint); + if (tuple.Item1.TryGetValue(breakpoint.SequencePointIndex, out var list)) + { + list.Add(breakpoint); + } + else + { + tuple.Item1.Add(breakpoint.SequencePointIndex, new List { breakpoint }); + } + // We need to keep track of any breakpoints that are bound in each script because they may // need to be rebound if the script changes. var boundBreakpoints = _boundBreakpoints[currentScriptFile].Item2; boundBreakpoints[breakpoint.Id] = breakpoint; } - if (!bound) + if (bound) { - newPendingBreakpoints.Add(breakpoint.Id, breakpoint); + breakpoints.TryRemove(breakpointId, out _); } } - _pendingBreakpoints = new ConcurrentDictionary(newPendingBreakpoints); + // Here could check if all breakpoints for the current functionContext were bound, but because there is no atomic + // api for conditional removal we either need to lock, or do some trickery that has possibility of race conditions. + // Instead we keep the item in the dictionary with 0 breakpoint count. This should not be a big issue, + // because it is single entry per file that had breakpoints, so there won't be thousands of files in a session. } private void StopOnSequencePoint(FunctionContext functionContext, List breakpoints) diff --git a/src/System.Management.Automation/engine/parser/Compiler.cs b/src/System.Management.Automation/engine/parser/Compiler.cs index 99b38a3fa06..3fac9de74f6 100644 --- a/src/System.Management.Automation/engine/parser/Compiler.cs +++ b/src/System.Management.Automation/engine/parser/Compiler.cs @@ -782,7 +782,7 @@ internal class FunctionContext internal ExecutionContext _executionContext; internal Pipe _outputPipe; internal BitArray _breakPoints; - internal List _boundBreakpoints; + internal Dictionary> _boundBreakpoints; internal int _currentSequencePointIndex; internal MutableTuple _localsTuple; internal List[], Type[]>> _traps = new List[], Type[]>>(); From fbc64e481830b73bb8a998783b3e7ee7d9ada46b Mon Sep 17 00:00:00 2001 From: PowerShell Team Bot <69177312+pwshBot@users.noreply.github.com> Date: Tue, 23 May 2023 11:21:27 -0700 Subject: [PATCH 553/779] Update experimental-feature json files (#19698) --- experimental-feature-linux.json | 1 + experimental-feature-windows.json | 1 + 2 files changed, 2 insertions(+) diff --git a/experimental-feature-linux.json b/experimental-feature-linux.json index 3c588657a18..22b2f93977e 100644 --- a/experimental-feature-linux.json +++ b/experimental-feature-linux.json @@ -1,6 +1,7 @@ [ "PSCommandNotFoundSuggestion", "PSCommandWithArgs", + "PSConstrainedAuditLogging", "PSCustomTableHeaderLabelDecoration", "PSFeedbackProvider", "PSLoadAssemblyFromNativeCode", diff --git a/experimental-feature-windows.json b/experimental-feature-windows.json index 3c588657a18..22b2f93977e 100644 --- a/experimental-feature-windows.json +++ b/experimental-feature-windows.json @@ -1,6 +1,7 @@ [ "PSCommandNotFoundSuggestion", "PSCommandWithArgs", + "PSConstrainedAuditLogging", "PSCustomTableHeaderLabelDecoration", "PSFeedbackProvider", "PSLoadAssemblyFromNativeCode", From 368a1ea3720b5ee6ef4ac4443a11d8ed1264251e Mon Sep 17 00:00:00 2001 From: Dmitry Volodin Date: Wed, 24 May 2023 16:23:23 +0400 Subject: [PATCH 554/779] Apply IDE0019: InlineAsTypeCheck in Microsoft.PowerShell folder (#19689) --- .../host/msh/ConsoleHost.cs | 27 ++-- .../host/msh/ConsoleHostRawUserInterface.cs | 3 +- .../host/msh/Executor.cs | 9 +- .../DotNetCode/Eventing/EventProvider.cs | 3 +- .../security/AclCommands.cs | 6 +- .../security/CertificateProvider.cs | 129 +++++++----------- 6 files changed, 67 insertions(+), 110 deletions(-) diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs index 6e48f2e3338..cd9c682d1b2 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs @@ -2149,9 +2149,7 @@ private void ReportException(Exception e, Executor exec) // NTRAID#Windows OS Bugs-1143621-2005/04/08-sburns - IContainsErrorRecord icer = e as IContainsErrorRecord; - - if (icer != null) + if (e is IContainsErrorRecord icer) { error = icer.ErrorRecord; } @@ -2208,8 +2206,7 @@ private void ReportExceptionFallback(Exception e, string header) // See if the exception has an error record attached to it... ErrorRecord er = null; - IContainsErrorRecord icer = e as IContainsErrorRecord; - if (icer != null) + if (e is IContainsErrorRecord icer) er = icer.ErrorRecord; if (e is PSRemotingTransportException) @@ -2744,8 +2741,7 @@ e is RemoteException || internal void BlockCommandOutput() { - RemotePipeline rCmdPipeline = _parent.runningCmd as RemotePipeline; - if (rCmdPipeline != null) + if (_parent.runningCmd is RemotePipeline rCmdPipeline) { rCmdPipeline.DrainIncomingData(); rCmdPipeline.SuspendIncomingData(); @@ -2758,8 +2754,7 @@ internal void BlockCommandOutput() internal void ResumeCommandOutput() { - RemotePipeline rCmdPipeline = _parent.runningCmd as RemotePipeline; - if (rCmdPipeline != null) + if (_parent.runningCmd is RemotePipeline rCmdPipeline) { rCmdPipeline.ResumeIncomingData(); } @@ -2849,8 +2844,7 @@ private static bool IsIncompleteParseException(Exception e) } // If it is remote exception ferret out the real exception. - RemoteException remoteException = e as RemoteException; - if (remoteException == null || remoteException.ErrorRecord == null) + if (e is not RemoteException remoteException || remoteException.ErrorRecord == null) { return false; } @@ -2931,8 +2925,7 @@ private string EvaluatePrompt() // Check for the pushed runspace scenario. if (_isRunspacePushed) { - RemoteRunspace remoteRunspace = _parent.Runspace as RemoteRunspace; - if (remoteRunspace != null) + if (_parent.Runspace is RemoteRunspace remoteRunspace) { promptString = HostUtilities.GetRemotePrompt(remoteRunspace, promptString, _parent._inPushedConfiguredSession); } @@ -2966,13 +2959,9 @@ private string EvaluateDebugPrompt() PSObject prompt = output.ReadAndRemoveAt0(); string promptString = (prompt != null) ? (prompt.BaseObject as string) : null; - if (promptString != null) + if (promptString != null && _parent.Runspace is RemoteRunspace remoteRunspace) { - RemoteRunspace remoteRunspace = _parent.Runspace as RemoteRunspace; - if (remoteRunspace != null) - { - promptString = HostUtilities.GetRemotePrompt(remoteRunspace, promptString, _parent._inPushedConfiguredSession); - } + promptString = HostUtilities.GetRemotePrompt(remoteRunspace, promptString, _parent._inPushedConfiguredSession); } return promptString; diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs index a0d654759b7..58630f5b3c0 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs @@ -354,8 +354,7 @@ public override } catch (HostException e) { - Win32Exception win32exception = e.InnerException as Win32Exception; - if (win32exception != null && + if (e.InnerException is Win32Exception win32exception && win32exception.NativeErrorCode == 0x57) { throw PSTraceSource.NewArgumentOutOfRangeException("value", value, diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/Executor.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/Executor.cs index 013281d2209..43cd165cc87 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/Executor.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/Executor.cs @@ -107,8 +107,7 @@ private void ErrorObjectStreamHandler(object sender, EventArgs e) private void AsyncPipelineFailureHandler(Exception ex) { ErrorRecord er = null; - IContainsErrorRecord cer = ex as IContainsErrorRecord; - if (cer != null) + if (ex is IContainsErrorRecord cer) { er = cer.ErrorRecord; // Exception inside the error record is ParentContainsErrorRecordException which @@ -483,8 +482,7 @@ internal string ExecuteCommandAndGetResultAsString(string command, out Exception // And convert the base object into a string. We can't use the proxied // ToString() on the PSObject because there is no default runspace // available. - PSObject msho = streamResults[0] as PSObject; - if (msho != null) + if (streamResults[0] is PSObject msho) result = msho.BaseObject.ToString(); else result = streamResults[0].ToString(); @@ -585,8 +583,7 @@ private void Cancel() internal void BlockCommandOutput() { - RemotePipeline remotePipeline = _pipeline as RemotePipeline; - if (remotePipeline != null) + if (_pipeline is RemotePipeline remotePipeline) { // Waits until queued data is handled. remotePipeline.DrainIncomingData(); diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs index af32014ab9d..32ce9993cfb 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs @@ -294,8 +294,7 @@ to fill the passed in ETW data descriptor. { dataDescriptor->Reserved = 0; - string sRet = data as string; - if (sRet != null) + if (data is string sRet) { dataDescriptor->Size = (uint)((sRet.Length + 1) * 2); return sRet; diff --git a/src/Microsoft.PowerShell.Security/security/AclCommands.cs b/src/Microsoft.PowerShell.Security/security/AclCommands.cs index c0994a57a53..8cff78e1bfc 100644 --- a/src/Microsoft.PowerShell.Security/security/AclCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/AclCommands.cs @@ -291,8 +291,7 @@ public static AuthorizationRuleCollection GetAccess(PSObject instance) } // Get DACL - CommonObjectSecurity cos = sd as CommonObjectSecurity; - if (cos != null) + if (sd is CommonObjectSecurity cos) { return cos.GetAccessRules(true, true, typeof(NTAccount)); } @@ -326,8 +325,7 @@ public static AuthorizationRuleCollection GetAudit(PSObject instance) PSTraceSource.NewArgumentException(nameof(instance)); } - CommonObjectSecurity cos = sd as CommonObjectSecurity; - if (cos != null) + if (sd is CommonObjectSecurity cos) { return cos.GetAuditRules(true, true, typeof(NTAccount)); } diff --git a/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs b/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs index 7644f3de620..527bf6be675 100644 --- a/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs +++ b/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs @@ -724,16 +724,11 @@ protected override void RemoveItem( ThrowInvalidOperation(errorId, message); } - if (DynamicParameters != null) + if (DynamicParameters != null && DynamicParameters is ProviderRemoveItemDynamicParameters dp) { - ProviderRemoveItemDynamicParameters dp = - DynamicParameters as ProviderRemoveItemDynamicParameters; - if (dp != null) + if (dp.DeleteKey) { - if (dp.DeleteKey) - { - fDeleteKey = true; - } + fDeleteKey = true; } } @@ -888,9 +883,8 @@ protected override void MoveItem( object store = GetItemAtPath(destination, false, out isDestContainer); X509Certificate2 certificate = cert as X509Certificate2; - X509NativeStore certstore = store as X509NativeStore; - if (certstore != null) + if (store is X509NativeStore certstore) { certstore.Open(true); @@ -1068,23 +1062,18 @@ protected override bool HasChildItems(string path) if ((item != null) && isContainer) { - X509StoreLocation storeLocation = item as X509StoreLocation; - if (storeLocation != null) + if (item is X509StoreLocation storeLocation) { result = storeLocation.StoreNames.Count > 0; } - else + else if (item is X509NativeStore store) { - X509NativeStore store = item as X509NativeStore; - if (store != null) + store.Open(IncludeArchivedCerts()); + IntPtr certContext = store.GetFirstCert(); + if (certContext != IntPtr.Zero) { - store.Open(IncludeArchivedCerts()); - IntPtr certContext = store.GetFirstCert(); - if (certContext != IntPtr.Zero) - { - store.FreeCert(certContext); - result = true; - } + store.FreeCert(certContext); + result = true; } } } @@ -1259,20 +1248,15 @@ protected override void GetItem(string path) return; } - X509StoreLocation storeLocation = item as X509StoreLocation; - if (storeLocation != null) // store location + if (item is X509StoreLocation storeLocation) // store location { WriteItemObject(item, path, isContainer); } - else // store + else if (item is X509NativeStore store) // store { - X509NativeStore store = item as X509NativeStore; - if (store != null) - { - // create X509Store - X509Store outStore = new(store.StoreName, store.Location.Location); - WriteItemObject(outStore, path, isContainer); - } + // create X509Store + X509Store outStore = new(store.StoreName, store.Location.Location); + WriteItemObject(outStore, path, isContainer); } } } @@ -2644,51 +2628,46 @@ private CertificateFilterInfo GetFilter() { CertificateFilterInfo filter = null; - if (DynamicParameters != null) + if (DynamicParameters != null && DynamicParameters is CertificateProviderDynamicParameters dp) { - CertificateProviderDynamicParameters dp = - DynamicParameters as CertificateProviderDynamicParameters; - if (dp != null) + if (dp.CodeSigningCert) { - if (dp.CodeSigningCert) - { - filter = new CertificateFilterInfo(); - filter.Purpose = CertificatePurpose.CodeSigning; - } + filter = new CertificateFilterInfo(); + filter.Purpose = CertificatePurpose.CodeSigning; + } - if (dp.DocumentEncryptionCert) - { - filter ??= new CertificateFilterInfo(); - filter.Purpose = CertificatePurpose.DocumentEncryption; - } + if (dp.DocumentEncryptionCert) + { + filter ??= new CertificateFilterInfo(); + filter.Purpose = CertificatePurpose.DocumentEncryption; + } - if (dp.DnsName != null) - { - filter ??= new CertificateFilterInfo(); - filter.DnsName = new WildcardPattern(dp.DnsName, WildcardOptions.IgnoreCase); - } + if (dp.DnsName != null) + { + filter ??= new CertificateFilterInfo(); + filter.DnsName = new WildcardPattern(dp.DnsName, WildcardOptions.IgnoreCase); + } - if (dp.Eku != null) + if (dp.Eku != null) + { + filter ??= new CertificateFilterInfo(); + filter.Eku = new List(); + foreach (var pattern in dp.Eku) { - filter ??= new CertificateFilterInfo(); - filter.Eku = new List(); - foreach (var pattern in dp.Eku) - { - filter.Eku.Add(new WildcardPattern(pattern, WildcardOptions.IgnoreCase)); - } + filter.Eku.Add(new WildcardPattern(pattern, WildcardOptions.IgnoreCase)); } + } - if (dp.ExpiringInDays >= 0) - { - filter ??= new CertificateFilterInfo(); - filter.Expiring = DateTime.Now.AddDays(dp.ExpiringInDays); - } + if (dp.ExpiringInDays >= 0) + { + filter ??= new CertificateFilterInfo(); + filter.Expiring = DateTime.Now.AddDays(dp.ExpiringInDays); + } - if (dp.SSLServerAuthentication) - { - filter ??= new CertificateFilterInfo(); - filter.SSLServerAuthentication = true; - } + if (dp.SSLServerAuthentication) + { + filter ??= new CertificateFilterInfo(); + filter.SSLServerAuthentication = true; } } @@ -3311,17 +3290,13 @@ public EnhancedKeyUsageProperty(X509Certificate2 cert) foreach (X509Extension extension in cert.Extensions) { // Filter to the OID for EKU - if (extension.Oid.Value == "2.5.29.37") + if (extension.Oid.Value == "2.5.29.37" && extension is X509EnhancedKeyUsageExtension ext) { - X509EnhancedKeyUsageExtension ext = extension as X509EnhancedKeyUsageExtension; - if (ext != null) + OidCollection oids = ext.EnhancedKeyUsages; + foreach (Oid oid in oids) { - OidCollection oids = ext.EnhancedKeyUsages; - foreach (Oid oid in oids) - { - EnhancedKeyUsageRepresentation ekuString = new(oid.FriendlyName, oid.Value); - _ekuList.Add(ekuString); - } + EnhancedKeyUsageRepresentation ekuString = new(oid.FriendlyName, oid.Value); + _ekuList.Add(ekuString); } } } From 1c55e02df443a4523df4705a82b460c50b1fdd8d Mon Sep 17 00:00:00 2001 From: Dmitry Volodin Date: Wed, 24 May 2023 16:26:40 +0400 Subject: [PATCH 555/779] Apply IDE0019: InlineAsTypeCheck in Microsoft.Management (#19687) --- .../CimAsyncOperation.cs | 12 ++++-------- .../CimGetInstance.cs | 6 ++---- .../CimIndicationWatcher.cs | 9 +++------ .../CimNewCimInstance.cs | 6 ++---- .../CimRegisterCimIndication.cs | 9 +++------ .../CimResultObserver.cs | 6 ++---- .../CimWriteError.cs | 6 ++---- .../CmdletOperation.cs | 3 +-- .../NewCimSessionCommand.cs | 3 +-- 9 files changed, 20 insertions(+), 40 deletions(-) diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimAsyncOperation.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimAsyncOperation.cs index e5f31f385fc..023bf652b1d 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimAsyncOperation.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimAsyncOperation.cs @@ -344,16 +344,14 @@ protected virtual void SubscribeToCimSessionProxyEvent(CimSessionProxy proxy) /// protected object GetBaseObject(object value) { - PSObject psObject = value as PSObject; - if (psObject == null) + if (value is not PSObject psObject) { return value; } else { object baseObject = psObject.BaseObject; - var arrayObject = baseObject as object[]; - if (arrayObject == null) + if (baseObject is not object[] arrayObject) { return baseObject; } @@ -380,8 +378,7 @@ protected object GetBaseObject(object value) /// The object. protected object GetReferenceOrReferenceArrayObject(object value, ref CimType referenceType) { - PSReference cimReference = value as PSReference; - if (cimReference != null) + if (value is PSReference cimReference) { object baseObject = GetBaseObject(cimReference.Value); if (!(baseObject is CimInstance cimInstance)) @@ -394,8 +391,7 @@ protected object GetReferenceOrReferenceArrayObject(object value, ref CimType re } else { - object[] cimReferenceArray = value as object[]; - if (cimReferenceArray == null) + if (value is not object[] cimReferenceArray) { return null; } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetInstance.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetInstance.cs index 25400514401..371b06d9356 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetInstance.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetInstance.cs @@ -284,8 +284,7 @@ protected static string GetQuery(CimBaseCommand cmdlet) internal static bool IsClassNameQuerySet(CimBaseCommand cmdlet) { DebugHelper.WriteLogEx(); - GetCimInstanceCommand cmd = cmdlet as GetCimInstanceCommand; - if (cmd != null) + if (cmdlet is GetCimInstanceCommand cmd) { if (cmd.QueryDialect != null || cmd.SelectProperties != null || cmd.Filter != null) { @@ -299,8 +298,7 @@ internal static bool IsClassNameQuerySet(CimBaseCommand cmdlet) protected static string CreateQuery(CimBaseCommand cmdlet) { DebugHelper.WriteLogEx(); - GetCimInstanceCommand cmd = cmdlet as GetCimInstanceCommand; - if (cmd != null) + if (cmdlet is GetCimInstanceCommand cmd) { StringBuilder propertyList = new(); if (cmd.SelectProperties == null) diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimIndicationWatcher.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimIndicationWatcher.cs index cb5cfc27056..eb69ba67392 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimIndicationWatcher.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimIndicationWatcher.cs @@ -221,14 +221,11 @@ private void NewSubscriptionResultHandler(object src, CimSubscriptionEventArgs a if (temp != null) { // raise the event - CimSubscriptionResultEventArgs resultArgs = args as CimSubscriptionResultEventArgs; - if (resultArgs != null) + if (args is CimSubscriptionResultEventArgs resultArgs) temp(this, new CimIndicationEventInstanceEventArgs(resultArgs.Result)); - else + else if (args is CimSubscriptionExceptionEventArgs exceptionArgs) { - CimSubscriptionExceptionEventArgs exceptionArgs = args as CimSubscriptionExceptionEventArgs; - if (exceptionArgs != null) - temp(this, new CimIndicationEventExceptionEventArgs(exceptionArgs.Exception)); + temp(this, new CimIndicationEventExceptionEventArgs(exceptionArgs.Exception)); } } } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimNewCimInstance.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimNewCimInstance.cs index 176cb1828e2..beb3e551d33 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimNewCimInstance.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimNewCimInstance.cs @@ -179,8 +179,7 @@ internal void GetCimInstance(CimInstance cimInstance, XOperationContextBase cont { DebugHelper.WriteLogEx(); - CimNewCimInstanceContext newCimInstanceContext = context as CimNewCimInstanceContext; - if (newCimInstanceContext == null) + if (context is not CimNewCimInstanceContext newCimInstanceContext) { DebugHelper.WriteLog("Invalid (null) CimNewCimInstanceContext", 1); return; @@ -295,8 +294,7 @@ private CimInstance CreateCimInstance( DebugHelper.WriteLog("Create and add new property to ciminstance: name = {0}; value = {1}; flags = {2}", 5, propertyName, propertyValue, flag); - PSReference cimReference = propertyValue as PSReference; - if (cimReference != null) + if (propertyValue is PSReference cimReference) { CimProperty newProperty = CimProperty.Create(propertyName, GetBaseObject(cimReference.Value), CimType.Reference, flag); cimInstance.CimInstanceProperties.Add(newProperty); diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRegisterCimIndication.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRegisterCimIndication.cs index c08fa0c44ea..692a5f123e8 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRegisterCimIndication.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRegisterCimIndication.cs @@ -196,8 +196,7 @@ private void CimIndicationHandler(object cimSession, CmdletActionEventArgs actio } // NOTES: should move after this.Disposed, but need to log the exception - CimWriteError cimWriteError = actionArgs.Action as CimWriteError; - if (cimWriteError != null) + if (actionArgs.Action is CimWriteError cimWriteError) { this.Exception = cimWriteError.Exception; if (!this.ackedEvent.IsSet) @@ -219,11 +218,9 @@ private void CimIndicationHandler(object cimSession, CmdletActionEventArgs actio DebugHelper.WriteLog("Got an exception: {0}", 2, Exception); } - CimWriteResultObject cimWriteResultObject = actionArgs.Action as CimWriteResultObject; - if (cimWriteResultObject != null) + if (actionArgs.Action is CimWriteResultObject cimWriteResultObject) { - CimSubscriptionResult result = cimWriteResultObject.Result as CimSubscriptionResult; - if (result != null) + if (cimWriteResultObject.Result is CimSubscriptionResult result) { EventHandler temp = this.OnNewSubscriptionResult; if (temp != null) diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimResultObserver.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimResultObserver.cs index c27c7493ddb..389c45c8314 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimResultObserver.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimResultObserver.cs @@ -419,8 +419,7 @@ public override void OnNext(CimMethodResultBase value) string resultObjectPSType = null; PSObject resultObject = null; - CimMethodResult methodResult = value as CimMethodResult; - if (methodResult != null) + if (value is CimMethodResult methodResult) { resultObjectPSType = PSTypeCimMethodResult; resultObject = new PSObject(); @@ -431,8 +430,7 @@ public override void OnNext(CimMethodResultBase value) } else { - CimMethodStreamedResult methodStreamedResult = value as CimMethodStreamedResult; - if (methodStreamedResult != null) + if (value is CimMethodStreamedResult methodStreamedResult) { resultObjectPSType = PSTypeCimMethodStreamedResult; resultObject = new PSObject(); diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteError.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteError.cs index d3ae3419fa4..f1ebe911603 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteError.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteError.cs @@ -39,14 +39,12 @@ internal static ErrorRecord ErrorRecordFromAnyException( { Debug.Assert(inner != null, "Caller should verify inner != null"); - CimException cimException = inner as CimException; - if (cimException != null) + if (inner is CimException cimException) { return CreateFromCimException(context, cimException, cimResultContext); } - var containsErrorRecord = inner as IContainsErrorRecord; - if (containsErrorRecord != null) + if (inner is IContainsErrorRecord containsErrorRecord) { return InitializeErrorRecord(context, exception: inner, diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CmdletOperation.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CmdletOperation.cs index 03db6967aef..bd1a2751622 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CmdletOperation.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CmdletOperation.cs @@ -232,8 +232,7 @@ public override void WriteObject(object sendToPipeline, XOperationContextBase co if (sendToPipeline is CimInstance) { - CimSetCimInstanceContext setContext = context as CimSetCimInstanceContext; - if (setContext != null) + if (context is CimSetCimInstanceContext setContext) { if (string.Equals(setContext.ParameterSetName, CimBaseCommand.QueryComputerSet, StringComparison.OrdinalIgnoreCase) || string.Equals(setContext.ParameterSetName, CimBaseCommand.QuerySessionSet, StringComparison.OrdinalIgnoreCase)) diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionCommand.cs index f048a22a9f6..56ce967b426 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionCommand.cs @@ -234,8 +234,7 @@ internal void BuildSessionOptions(out CimSessionOptions outputOptions, out CimCr outputCredential = null; if (options != null) { - DComSessionOptions dcomOptions = options as DComSessionOptions; - if (dcomOptions != null) + if (options is DComSessionOptions dcomOptions) { bool conflict = false; string parameterName = string.Empty; From 9e16fc8cf6031ca7712674793df02459a432b5b1 Mon Sep 17 00:00:00 2001 From: PowerShell Team Bot <69177312+pwshBot@users.noreply.github.com> Date: Wed, 24 May 2023 11:24:30 -0700 Subject: [PATCH 556/779] Update the cgmanifest (#19697) --- tools/cgmanifest.json | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tools/cgmanifest.json b/tools/cgmanifest.json index e6e9958452c..3b45a6cb048 100644 --- a/tools/cgmanifest.json +++ b/tools/cgmanifest.json @@ -106,7 +106,7 @@ "Type": "nuget", "Nuget": { "Name": "Microsoft.CodeAnalysis.Common", - "Version": "4.5.0" + "Version": "4.6.0" } }, "DevelopmentDependency": false @@ -116,7 +116,7 @@ "Type": "nuget", "Nuget": { "Name": "Microsoft.CodeAnalysis.CSharp", - "Version": "4.5.0" + "Version": "4.6.0" } }, "DevelopmentDependency": false @@ -376,7 +376,7 @@ "Type": "nuget", "Nuget": { "Name": "System.Collections.Immutable", - "Version": "6.0.0" + "Version": "7.0.0" } }, "DevelopmentDependency": false @@ -606,7 +606,7 @@ "Type": "nuget", "Nuget": { "Name": "System.Reflection.Metadata", - "Version": "6.0.1" + "Version": "7.0.0" } }, "DevelopmentDependency": false From 51da40a9fdc0da7fbc5e81cc1691e577580de349 Mon Sep 17 00:00:00 2001 From: Dmitry Volodin Date: Thu, 25 May 2023 07:19:14 +0400 Subject: [PATCH 557/779] Apply IDE0019: InlineAsTypeCheck in Microsoft.WSMan folder (#19690) --- .../ConfigProvider.cs | 34 +++++++------------ 1 file changed, 12 insertions(+), 22 deletions(-) diff --git a/src/Microsoft.WSMan.Management/ConfigProvider.cs b/src/Microsoft.WSMan.Management/ConfigProvider.cs index 701e6db510d..7af916e6250 100644 --- a/src/Microsoft.WSMan.Management/ConfigProvider.cs +++ b/src/Microsoft.WSMan.Management/ConfigProvider.cs @@ -1024,20 +1024,15 @@ protected override void SetItem(string path, object value) strPathChk = strPathChk + WSManStringLiterals.containerPlugin + WSManStringLiterals.DefaultPathSeparator; if (path.EndsWith(strPathChk + currentpluginname, StringComparison.OrdinalIgnoreCase)) { - if (WSManStringLiterals.ConfigRunAsUserName.Equals(ChildName, StringComparison.OrdinalIgnoreCase)) + if (WSManStringLiterals.ConfigRunAsUserName.Equals(ChildName, StringComparison.OrdinalIgnoreCase) && value is PSCredential runAsCredentials) { - PSCredential runAsCredentials = value as PSCredential; + // UserName + value = runAsCredentials.UserName; - if (runAsCredentials != null) - { - // UserName - value = runAsCredentials.UserName; - - pluginConfiguration.UpdateOneConfiguration( - ".", - WSManStringLiterals.ConfigRunAsPasswordName, - GetStringFromSecureString(runAsCredentials.Password)); - } + pluginConfiguration.UpdateOneConfiguration( + ".", + WSManStringLiterals.ConfigRunAsPasswordName, + GetStringFromSecureString(runAsCredentials.Password)); } if (WSManStringLiterals.ConfigRunAsPasswordName.Equals(ChildName, StringComparison.OrdinalIgnoreCase)) @@ -1304,8 +1299,7 @@ protected override void SetItem(string path, object value) } } - WSManProviderSetItemDynamicParameters dynParams = DynamicParameters as WSManProviderSetItemDynamicParameters; - if (dynParams != null) + if (DynamicParameters is WSManProviderSetItemDynamicParameters dynParams) { if (dynParams.Concatenate) { @@ -1968,9 +1962,8 @@ protected override object NewItemDynamicParameters(string path, string itemTypeN private void NewItemCreateComputerConnection(string Name) { helper = new WSManHelper(this); - WSManProviderNewItemComputerParameters dynParams = DynamicParameters as WSManProviderNewItemComputerParameters; string parametersetName = "ComputerName"; - if (dynParams != null) + if (DynamicParameters is WSManProviderNewItemComputerParameters dynParams) { if (dynParams.ConnectionURI != null) { @@ -2067,8 +2060,7 @@ private void NewItemPluginOrPluginChild(object sessionobj, string path, string h // to create a new plugin if (path.EndsWith(strPathChk, StringComparison.OrdinalIgnoreCase)) { - WSManProviderNewItemPluginParameters niParams = DynamicParameters as WSManProviderNewItemPluginParameters; - if (niParams != null) + if (DynamicParameters is WSManProviderNewItemPluginParameters niParams) { if (string.IsNullOrEmpty(niParams.File)) { @@ -2158,8 +2150,7 @@ private void NewItemPluginOrPluginChild(object sessionobj, string path, string h strPathChk += WSManStringLiterals.containerResources; if (path.EndsWith(strPathChk, StringComparison.OrdinalIgnoreCase)) { - WSManProviderNewItemResourceParameters niParams = DynamicParameters as WSManProviderNewItemResourceParameters; - if (niParams != null) + if (DynamicParameters is WSManProviderNewItemResourceParameters niParams) { mshObj.Properties.Add(new PSNoteProperty("Resource", niParams.ResourceUri)); mshObj.Properties.Add(new PSNoteProperty("Capability", niParams.Capability)); @@ -5193,10 +5184,9 @@ private object ValidateAndGetUserObject(string configurationName, object value) /// Value to append. private static string GetStringFromSecureString(object propertyValue) { - SecureString value = propertyValue as SecureString; string passwordValueToAdd = string.Empty; - if (value != null) + if (propertyValue is SecureString value) { IntPtr ptr = Marshal.SecureStringToBSTR(value); passwordValueToAdd = Marshal.PtrToStringAuto(ptr); From fa64ecba709a9c1d518ebb49946c552aae36bc6e Mon Sep 17 00:00:00 2001 From: Dmitry Volodin Date: Thu, 25 May 2023 08:28:59 +0400 Subject: [PATCH 558/779] Apply IDE0019: InlineAsTypeCheck in Microsoft.PowerShell.Commands (#19688) --- .../GetEventCommand.cs | 21 ++++------- .../cmdletization/SessionBasedWrapper.cs | 3 +- .../cmdletization/cim/CimJobException.cs | 9 ++--- .../cim/ExtrinsicMethodInvocationJob.cs | 12 +++---- .../cim/TerminatingErrorTracker.cs | 3 +- .../cmdletization/cim/cimChildJobBase.cs | 6 ++-- .../cmdletization/cim/clientSideQuery.cs | 9 ++--- .../commands/management/Service.cs | 13 +++---- .../commands/utility/AddMember.cs | 3 +- .../commands/utility/ConvertTo-Html.cs | 12 +++---- .../commands/utility/CustomSerialization.cs | 3 +- .../commands/utility/DebugRunspaceCommand.cs | 15 +++----- .../OutGridView/OriginalColumnInfo.cs | 6 ++-- .../OutGridView/OutGridViewCommand.cs | 3 +- .../OutGridView/OutWindowProxy.cs | 3 +- .../FormatAndOutput/OutGridView/TableView.cs | 6 ++-- .../common/GetFormatDataCommand.cs | 9 ++--- .../commands/utility/GetMember.cs | 3 +- .../utility/ImplicitRemotingCommands.cs | 36 +++++++------------ .../commands/utility/WebCmdlet/JsonObject.cs | 9 ++--- .../commands/utility/Write.cs | 27 ++++---------- .../commands/utility/WriteConsoleCmdlet.cs | 6 ++-- .../commands/utility/XmlCommands.cs | 6 ++-- .../utility/trace/TraceExpressionCommand.cs | 6 ++-- 24 files changed, 74 insertions(+), 155 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs index 8f7e42dd9ae..3aec30c9e4c 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs @@ -1187,8 +1187,7 @@ private string BuildStructuredQueryFromHashTable(EventLogSession eventLogSession // // Build xpath for // - Hashtable suppresshash = hash[hashkey_supress_lc] as Hashtable; - if (suppresshash != null) + if (hash[hashkey_supress_lc] is Hashtable suppresshash) { xpathStringSuppress = BuildXPathFromHashTable(suppresshash); } @@ -1255,8 +1254,7 @@ private string BuildStructuredQueryFromHashTable(EventLogSession eventLogSession private static string HandleEventIdHashValue(object value) { StringBuilder ret = new(); - Array idsArray = value as Array; - if (idsArray != null) + if (value is Array idsArray) { ret.Append('('); for (int i = 0; i < idsArray.Length; i++) @@ -1285,8 +1283,7 @@ private static string HandleEventIdHashValue(object value) private static string HandleLevelHashValue(object value) { StringBuilder ret = new(); - Array levelsArray = value as Array; - if (levelsArray != null) + if (value is Array levelsArray) { ret.Append('('); for (int i = 0; i < levelsArray.Length; i++) @@ -1317,8 +1314,7 @@ private string HandleKeywordHashValue(object value) long keywordsMask = 0; long keywordLong = 0; - Array keywordArray = value as Array; - if (keywordArray != null) + if (value is Array keywordArray) { foreach (object keyword in keywordArray) { @@ -1473,8 +1469,7 @@ private string HandleEndTimeHashValue(object value, Hashtable hash) private static string HandleDataHashValue(object value) { StringBuilder ret = new(); - Array dataArray = value as Array; - if (dataArray != null) + if (value is Array dataArray) { ret.Append('('); for (int i = 0; i < dataArray.Length; i++) @@ -1504,8 +1499,7 @@ private static string HandleDataHashValue(object value) private static string HandleNamedDataHashValue(string key, object value) { StringBuilder ret = new(); - Array dataArray = value as Array; - if (dataArray != null) + if (value is Array dataArray) { ret.Append('('); for (int i = 0; i < dataArray.Length; i++) @@ -1752,8 +1746,7 @@ private void CheckHashTablesForNullValues() } else { - Array eltArray = value as Array; - if (eltArray != null) + if (value is Array eltArray) { foreach (object elt in eltArray) { diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs index 8da4d7f4c78..3e26b2e2e98 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs @@ -491,8 +491,7 @@ private IEnumerable GetSessionsToActAgainst(QueryBuilder queryBuilder) return this.Session; } - var sessionBoundQueryBuilder = queryBuilder as ISessionBoundQueryBuilder; - if (sessionBoundQueryBuilder != null) + if (queryBuilder is ISessionBoundQueryBuilder sessionBoundQueryBuilder) { TSession sessionOfTheQueryBuilder = sessionBoundQueryBuilder.GetTargetSession(); if (sessionOfTheQueryBuilder != null) diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs index 4ad6ecc9698..b4d4a7bbbe7 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs @@ -98,16 +98,14 @@ internal static CimJobException CreateFromAnyException( Dbg.Assert(jobContext != null, "Caller should verify jobContext != null"); Dbg.Assert(inner != null, "Caller should verify inner != null"); - CimException cimException = inner as CimException; - if (cimException != null) + if (inner is CimException cimException) { return CreateFromCimException(jobDescription, jobContext, cimException); } string message = BuildErrorMessage(jobDescription, jobContext, inner.Message); CimJobException cimJobException = new(message, inner); - var containsErrorRecord = inner as IContainsErrorRecord; - if (containsErrorRecord != null) + if (inner is IContainsErrorRecord containsErrorRecord) { cimJobException.InitializeErrorRecord( jobContext, @@ -356,8 +354,7 @@ internal bool IsTerminatingError { get { - var cimException = this.InnerException as CimException; - if ((cimException == null) || (cimException.ErrorData == null)) + if ((this.InnerException is not CimException cimException) || (cimException.ErrorData == null)) { return false; } diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ExtrinsicMethodInvocationJob.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ExtrinsicMethodInvocationJob.cs index 9aa254212a6..9eaac2b3d7f 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ExtrinsicMethodInvocationJob.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ExtrinsicMethodInvocationJob.cs @@ -66,8 +66,7 @@ private void ProcessOutParameter(CimMethodResult methodResult, MethodParameter m methodParameter.Value = dotNetValue; cmdletOutput.Add(methodParameter.Name, methodParameter); - var cimInstances = dotNetValue as CimInstance[]; - if (cimInstances != null) + if (dotNetValue is CimInstance[] cimInstances) { foreach (var instance in cimInstances) { @@ -75,8 +74,7 @@ private void ProcessOutParameter(CimMethodResult methodResult, MethodParameter m } } - var cimInstance = dotNetValue as CimInstance; - if (cimInstance != null) + if (dotNetValue is CimInstance cimInstance) { CimCmdletAdapter.AssociateSessionOfOriginWithInstance(cimInstance, this.JobContext.Session); } @@ -191,15 +189,13 @@ public override void OnNext(CimMethodResultBase item) this.ExceptionSafeWrapper( delegate { - var methodResult = item as CimMethodResult; - if (methodResult != null) + if (item is CimMethodResult methodResult) { this.OnNext(methodResult); return; } - var streamedResult = item as CimMethodStreamedResult; - if (streamedResult != null) + if (item is CimMethodStreamedResult streamedResult) { this.OnNext(streamedResult); return; diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/TerminatingErrorTracker.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/TerminatingErrorTracker.cs index deb3a0ff103..6b716fa5501 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/TerminatingErrorTracker.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/TerminatingErrorTracker.cs @@ -53,8 +53,7 @@ private static int GetNumberOfSessions(InvocationInfo invocationInfo) int maxNumberOfSessionsIndicatedByCimInstanceArguments = 1; foreach (object cmdletArgument in invocationInfo.BoundParameters.Values) { - CimInstance[] array = cmdletArgument as CimInstance[]; - if (array != null) + if (cmdletArgument is CimInstance[] array) { int numberOfSessionsAssociatedWithArgument = array .Select(CimCmdletAdapter.GetSessionOfOriginFromCimInstance) diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimChildJobBase.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimChildJobBase.cs index 8a973c7af64..d787389e9f0 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimChildJobBase.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimChildJobBase.cs @@ -623,8 +623,7 @@ internal void ReportJobFailure(IContainsErrorRecord exception) } else { - CimJobException cje = exception as CimJobException; - if ((cje != null) && (cje.IsTerminatingError)) + if ((exception is CimJobException cje) && (cje.IsTerminatingError)) { terminatingErrorTracker.MarkSessionAsTerminated(this.JobContext.Session, out sessionWasAlreadyTerminated); isThisTerminatingError = true; @@ -1013,8 +1012,7 @@ internal static bool IsShowComputerNameMarkerPresent(CimInstance cimInstance) internal static void AddShowComputerNameMarker(PSObject pso) { - PSPropertyInfo psShowComputerNameProperty = pso.InstanceMembers[RemotingConstants.ShowComputerNameNoteProperty] as PSPropertyInfo; - if (psShowComputerNameProperty != null) + if (pso.InstanceMembers[RemotingConstants.ShowComputerNameNoteProperty] is PSPropertyInfo psShowComputerNameProperty) { psShowComputerNameProperty.Value = true; } diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/clientSideQuery.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/clientSideQuery.cs index 731007eb618..e8e4d46e075 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/clientSideQuery.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/clientSideQuery.cs @@ -36,8 +36,7 @@ public NotFoundError(string propertyName, object propertyValue, bool wildcardsEn if (wildcardsEnabled) { - var propertyValueAsString = propertyValue as string; - if ((propertyValueAsString != null) && (WildcardPattern.ContainsWildcardCharacters(propertyValueAsString))) + if ((propertyValue is string propertyValueAsString) && (WildcardPattern.ContainsWildcardCharacters(propertyValueAsString))) { this.ErrorMessageGenerator = (queryDescription, className) => GetErrorMessageForNotFound_ForWildcard(this.PropertyName, this.PropertyValue, className); @@ -466,8 +465,7 @@ protected override BehaviorOnNoMatch GetDefaultBehaviorWhenNoMatchesFound(object } else { - string expectedPropertyValueAsString = cimTypedExpectedPropertyValue as string; - if (expectedPropertyValueAsString != null && WildcardPattern.ContainsWildcardCharacters(expectedPropertyValueAsString)) + if (cimTypedExpectedPropertyValue is string expectedPropertyValueAsString && WildcardPattern.ContainsWildcardCharacters(expectedPropertyValueAsString)) { return BehaviorOnNoMatch.SilentlyContinue; } @@ -504,8 +502,7 @@ private static bool NonWildcardEqual(string propertyName, object actualPropertyV actualPropertyValue = actualPropertyValue.ToString(); } - var expectedPropertyValueAsString = expectedPropertyValue as string; - if (expectedPropertyValueAsString != null) + if (expectedPropertyValue is string expectedPropertyValueAsString) { var actualPropertyValueAsString = (string)actualPropertyValue; return actualPropertyValueAsString.Equals(expectedPropertyValueAsString, StringComparison.OrdinalIgnoreCase); diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs index 0253cee5e39..a9cba537a5a 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs @@ -903,8 +903,7 @@ internal bool DoStartService(ServiceController serviceController) } catch (InvalidOperationException e) { - Win32Exception eInner = e.InnerException as Win32Exception; - if (eInner == null + if (e.InnerException is not Win32Exception eInner || eInner.NativeErrorCode != NativeMethods.ERROR_SERVICE_ALREADY_RUNNING) { exception = e; @@ -1020,9 +1019,7 @@ internal List DoStopService(ServiceController serviceControll } catch (InvalidOperationException e) { - Win32Exception eInner = - e.InnerException as Win32Exception; - if (eInner == null + if (e.InnerException is not Win32Exception eInner || eInner.NativeErrorCode != NativeMethods.ERROR_SERVICE_NOT_ACTIVE) { exception = e; @@ -1117,8 +1114,7 @@ internal bool DoPauseService(ServiceController serviceController) } catch (InvalidOperationException e) { - Win32Exception eInner = e.InnerException as Win32Exception; - if (eInner != null + if (e.InnerException is Win32Exception eInner && eInner.NativeErrorCode == NativeMethods.ERROR_SERVICE_NOT_ACTIVE) { serviceNotRunning = true; @@ -1198,8 +1194,7 @@ internal bool DoResumeService(ServiceController serviceController) } catch (InvalidOperationException e) { - Win32Exception eInner = e.InnerException as Win32Exception; - if (eInner != null + if (e.InnerException is Win32Exception eInner && eInner.NativeErrorCode == NativeMethods.ERROR_SERVICE_NOT_ACTIVE) { serviceNotRunning = true; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddMember.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddMember.cs index 8ddd95e6b82..29aa870fd1e 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddMember.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddMember.cs @@ -560,9 +560,8 @@ private sealed class ValidateNotePropertyNameAttribute : ValidateArgumentsAttrib { protected override void Validate(object arguments, EngineIntrinsics engineIntrinsics) { - string notePropertyName = arguments as string; PSMemberTypes memberType; - if (notePropertyName != null && LanguagePrimitives.TryConvertTo(notePropertyName, out memberType)) + if (arguments is string notePropertyName && LanguagePrimitives.TryConvertTo(notePropertyName, out memberType)) { switch (memberType) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertTo-Html.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertTo-Html.cs index 2f1e5cca314..2c530a8ab93 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertTo-Html.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertTo-Html.cs @@ -502,9 +502,8 @@ protected override void BeginProcessing() MshCommandRuntime mshCommandRuntime = this.CommandRuntime as MshCommandRuntime; string Message = StringUtil.Format(ConvertHTMLStrings.MetaPropertyNotFound, s, _meta[s]); WarningRecord record = new(Message); - InvocationInfo invocationInfo = GetVariableValue(SpecialVariables.MyInvocation) as InvocationInfo; - if (invocationInfo != null) + if (GetVariableValue(SpecialVariables.MyInvocation) is InvocationInfo invocationInfo) { record.SetInvocationInfo(invocationInfo); } @@ -553,16 +552,14 @@ private void WriteColumns(List mshParams) foreach (MshParameter p in mshParams) { COLTag.Append(" reader = sender as PipelineReader; - if (reader != null && reader.IsOpen) + if (sender is PipelineReader reader && reader.IsOpen) { WritePipelineCollection(reader.NonBlockingRead(), PSStreamObjectType.Output); } @@ -447,8 +445,7 @@ private void HandlePipelineOutputDataReady(object sender, EventArgs e) private void HandlePipelineErrorDataReady(object sender, EventArgs e) { - PipelineReader reader = sender as PipelineReader; - if (reader != null && reader.IsOpen) + if (sender is PipelineReader reader && reader.IsOpen) { WritePipelineCollection(reader.NonBlockingRead(), PSStreamObjectType.Error); } @@ -538,8 +535,7 @@ private void EnableHostDebugger(Runspace runspace, bool enabled) // Only enable and disable the host's runspace if we are in process attach mode. if (_debugger is ServerRemoteDebugger) { - LocalRunspace localRunspace = runspace as LocalRunspace; - if ((localRunspace != null) && (localRunspace.ExecutionContext != null) && (localRunspace.ExecutionContext.EngineHostInterface != null)) + if ((runspace is LocalRunspace localRunspace) && (localRunspace.ExecutionContext != null) && (localRunspace.ExecutionContext.EngineHostInterface != null)) { try { @@ -552,8 +548,7 @@ private void EnableHostDebugger(Runspace runspace, bool enabled) private static void SetLocalMode(System.Management.Automation.Debugger debugger, bool localMode) { - ServerRemoteDebugger remoteDebugger = debugger as ServerRemoteDebugger; - if (remoteDebugger != null) + if (debugger is ServerRemoteDebugger remoteDebugger) { remoteDebugger.LocalDebugMode = localMode; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OriginalColumnInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OriginalColumnInfo.cs index 3db37f3528e..974188c2f74 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OriginalColumnInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OriginalColumnInfo.cs @@ -33,15 +33,13 @@ internal override object GetValue(PSObject liveObject) // The live object has the liveObjectPropertyName property. object liveObjectValue = propertyInfo.Value; - ICollection collectionValue = liveObjectValue as ICollection; - if (collectionValue != null) + if (liveObjectValue is ICollection collectionValue) { liveObjectValue = _parentCmdlet.ConvertToString(PSObjectHelper.AsPSObject(propertyInfo.Value)); } else { - PSObject psObjectValue = liveObjectValue as PSObject; - if (psObjectValue != null) + if (liveObjectValue is PSObject psObjectValue) { // Since PSObject implements IComparable there is a need to verify if its BaseObject actually implements IComparable. if (psObjectValue.BaseObject is IComparable) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutGridViewCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutGridViewCommand.cs index 5f231780055..43e24e8b5b6 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutGridViewCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutGridViewCommand.cs @@ -180,8 +180,7 @@ protected override void ProcessRecord() return; } - IDictionary dictionary = InputObject.BaseObject as IDictionary; - if (dictionary != null) + if (InputObject.BaseObject is IDictionary dictionary) { // Dictionaries should be enumerated through because the pipeline does not enumerate through them. foreach (DictionaryEntry entry in dictionary) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutWindowProxy.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutWindowProxy.cs index d9de50ef52c..b406c2bc78c 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutWindowProxy.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutWindowProxy.cs @@ -71,8 +71,7 @@ internal void AddColumns(string[] propertyNames, string[] displayNames, Type[] t catch (TargetInvocationException ex) { // Verify if this is an error loading the System.Core dll. - FileNotFoundException fileNotFoundEx = ex.InnerException as FileNotFoundException; - if (fileNotFoundEx != null && fileNotFoundEx.FileName.Contains("System.Core")) + if (ex.InnerException is FileNotFoundException fileNotFoundEx && fileNotFoundEx.FileName.Contains("System.Core")) { _parentCmdlet.ThrowTerminatingError( new ErrorRecord(new InvalidOperationException( diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/TableView.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/TableView.cs index 25b18dfd80e..9213484d332 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/TableView.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/TableView.cs @@ -69,8 +69,7 @@ internal HeaderInfo GenerateHeaderInfo(PSObject input, TableControlBody tableBod if (token != null) { - FieldPropertyToken fpt = token as FieldPropertyToken; - if (fpt != null) + if (token is FieldPropertyToken fpt) { // If Database does not provide a label(DisplayName) for the current property, use the expression value instead. displayName ??= fpt.expression.expressionValue; @@ -98,8 +97,7 @@ internal HeaderInfo GenerateHeaderInfo(PSObject input, TableControlBody tableBod } else { - TextToken tt = token as TextToken; - if (tt != null) + if (token is TextToken tt) { displayName = _typeInfoDatabase.displayResourceManagerCache.GetTextTokenString(tt); columnInfo = new OriginalColumnInfo(tt.text, displayName, tt.text, parentCmdlet); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/GetFormatDataCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/GetFormatDataCommand.cs index 21c078648f2..2ba36f5faf2 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/GetFormatDataCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/GetFormatDataCommand.cs @@ -139,22 +139,19 @@ protected override void ProcessRecord() PSControl control; - var tableControlBody = definition.mainControl as TableControlBody; - if (tableControlBody != null) + if (definition.mainControl is TableControlBody tableControlBody) { control = new TableControl(tableControlBody, definition); } else { - var listControlBody = definition.mainControl as ListControlBody; - if (listControlBody != null) + if (definition.mainControl is ListControlBody listControlBody) { control = new ListControl(listControlBody, definition); } else { - var wideControlBody = definition.mainControl as WideControlBody; - if (wideControlBody != null) + if (definition.mainControl is WideControlBody wideControlBody) { control = new WideControl(wideControlBody, definition); if (writeOldWay) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetMember.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetMember.cs index cfd380853b9..0b11af84200 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetMember.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetMember.cs @@ -230,8 +230,7 @@ protected override void ProcessRecord() { if (!Force) { - PSMethod memberAsPSMethod = member as PSMethod; - if ((memberAsPSMethod != null) && (memberAsPSMethod.IsSpecial)) + if ((member is PSMethod memberAsPSMethod) && (memberAsPSMethod.IsSpecial)) { continue; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs index 003b1bf1e3d..1631bb18762 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs @@ -726,8 +726,7 @@ private ErrorRecord GetErrorFromRemoteCommand(string commandName, RuntimeExcepti // // handle recognized types of exceptions first // - RemoteException remoteException = runtimeException as RemoteException; - if ((remoteException != null) && (remoteException.SerializedRemoteException != null)) + if ((runtimeException is RemoteException remoteException) && (remoteException.SerializedRemoteException != null)) { if (Deserializer.IsInstanceOfType(remoteException.SerializedRemoteException, typeof(CommandNotFoundException))) { @@ -1575,8 +1574,7 @@ private PowerShell BuildPowerShellForGetFormatData() powerShell.AddParameter("TypeName", this.FormatTypeName); // For remote PS version 5.1 and greater, we need to include the new -PowerShellVersion parameter - RemoteRunspace remoteRunspace = Session.Runspace as RemoteRunspace; - if ((remoteRunspace != null) && (remoteRunspace.ServerVersion != null) && + if ((Session.Runspace is RemoteRunspace remoteRunspace) && (remoteRunspace.ServerVersion != null) && (remoteRunspace.ServerVersion >= new Version(5, 1))) { powerShell.AddParameter("PowerShellVersion", PSVersionInfo.PSVersion); @@ -1942,20 +1940,17 @@ internal ImplicitRemotingCodeGenerator( /// Connection URI associated with the remote runspace. private string GetConnectionString() { - WSManConnectionInfo connectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as WSManConnectionInfo; - if (connectionInfo != null) + if (_remoteRunspaceInfo.Runspace.ConnectionInfo is WSManConnectionInfo connectionInfo) { return connectionInfo.ConnectionUri.ToString(); } - VMConnectionInfo vmConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as VMConnectionInfo; - if (vmConnectionInfo != null) + if (_remoteRunspaceInfo.Runspace.ConnectionInfo is VMConnectionInfo vmConnectionInfo) { return vmConnectionInfo.ComputerName; } - ContainerConnectionInfo containerConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as ContainerConnectionInfo; - if (containerConnectionInfo != null) + if (_remoteRunspaceInfo.Runspace.ConnectionInfo is ContainerConnectionInfo containerConnectionInfo) { return containerConnectionInfo.ComputerName; } @@ -2244,8 +2239,7 @@ private string GenerateNewPSSessionOption() { StringBuilder result = new("& $script:NewPSSessionOption "); - RunspaceConnectionInfo runspaceConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as RunspaceConnectionInfo; - if (runspaceConnectionInfo != null) + if (_remoteRunspaceInfo.Runspace.ConnectionInfo is RunspaceConnectionInfo runspaceConnectionInfo) { result.Append(null, $"-Culture '{CodeGeneration.EscapeSingleQuotedStringContent(runspaceConnectionInfo.Culture.ToString())}' "); result.Append(null, $"-UICulture '{CodeGeneration.EscapeSingleQuotedStringContent(runspaceConnectionInfo.UICulture.ToString())}' "); @@ -2256,8 +2250,7 @@ private string GenerateNewPSSessionOption() result.Append(null, $"-OperationTimeOut {runspaceConnectionInfo.OperationTimeout} "); } - WSManConnectionInfo wsmanConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as WSManConnectionInfo; - if (wsmanConnectionInfo != null) + if (_remoteRunspaceInfo.Runspace.ConnectionInfo is WSManConnectionInfo wsmanConnectionInfo) { if (!wsmanConnectionInfo.UseCompression) { @@ -2522,8 +2515,7 @@ private string GenerateReimportingOfModules() private string GenerateNewRunspaceExpression() { - VMConnectionInfo vmConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as VMConnectionInfo; - if (vmConnectionInfo != null) + if (_remoteRunspaceInfo.Runspace.ConnectionInfo is VMConnectionInfo vmConnectionInfo) { string vmConfigurationName = vmConnectionInfo.ConfigurationName; return string.Format( @@ -2535,8 +2527,7 @@ private string GenerateNewRunspaceExpression() } else { - ContainerConnectionInfo containerConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as ContainerConnectionInfo; - if (containerConnectionInfo != null) + if (_remoteRunspaceInfo.Runspace.ConnectionInfo is ContainerConnectionInfo containerConnectionInfo) { string containerConfigurationName = containerConnectionInfo.ContainerProc.ConfigurationName; return string.Format( @@ -2578,19 +2569,16 @@ private string GenerateNewRunspaceExpression() /// private string GenerateConnectionStringForNewRunspace() { - WSManConnectionInfo connectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as WSManConnectionInfo; - if (connectionInfo == null) + if (_remoteRunspaceInfo.Runspace.ConnectionInfo is not WSManConnectionInfo connectionInfo) { - VMConnectionInfo vmConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as VMConnectionInfo; - if (vmConnectionInfo != null) + if (_remoteRunspaceInfo.Runspace.ConnectionInfo is VMConnectionInfo vmConnectionInfo) { return string.Format(CultureInfo.InvariantCulture, VMIdParameterTemplate, CodeGeneration.EscapeSingleQuotedStringContent(vmConnectionInfo.VMGuid.ToString())); } - ContainerConnectionInfo containerConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as ContainerConnectionInfo; - if (containerConnectionInfo != null) + if (_remoteRunspaceInfo.Runspace.ConnectionInfo is ContainerConnectionInfo containerConnectionInfo) { return string.Format(CultureInfo.InvariantCulture, ContainerIdParameterTemplate, diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs index c9f99c524fa..f08c3a64aec 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs @@ -571,15 +571,13 @@ private static object ProcessValue(object obj, int currentDepth, in ConvertToJso } else { - IDictionary dict = obj as IDictionary; - if (dict != null) + if (obj is IDictionary dict) { rv = ProcessDictionary(dict, currentDepth, in context); } else { - IEnumerable enumerable = obj as IEnumerable; - if (enumerable != null) + if (obj is IEnumerable enumerable) { rv = ProcessEnumerable(enumerable, currentDepth, in context); } @@ -626,9 +624,8 @@ private static object AddPsProperties(object psObj, object obj, int depth, bool } bool wasDictionary = true; - IDictionary dict = obj as IDictionary; - if (dict == null) + if (obj is not IDictionary dict) { wasDictionary = false; dict = new Dictionary(); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write.cs index 55e98260779..b75c6be8735 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write.cs @@ -33,15 +33,11 @@ protected override void ProcessRecord() // so we create the DebugRecord here and fill it up with the appropriate InvocationInfo; // then, we call the command runtime directly and pass this record to WriteDebug(). // - MshCommandRuntime mshCommandRuntime = this.CommandRuntime as MshCommandRuntime; - - if (mshCommandRuntime != null) + if (this.CommandRuntime is MshCommandRuntime mshCommandRuntime) { DebugRecord record = new(Message); - InvocationInfo invocationInfo = GetVariableValue(SpecialVariables.MyInvocation) as InvocationInfo; - - if (invocationInfo != null) + if (GetVariableValue(SpecialVariables.MyInvocation) is InvocationInfo invocationInfo) { record.SetInvocationInfo(invocationInfo); } @@ -81,15 +77,11 @@ protected override void ProcessRecord() // so we create the VerboseRecord here and fill it up with the appropriate InvocationInfo; // then, we call the command runtime directly and pass this record to WriteVerbose(). // - MshCommandRuntime mshCommandRuntime = this.CommandRuntime as MshCommandRuntime; - - if (mshCommandRuntime != null) + if (this.CommandRuntime is MshCommandRuntime mshCommandRuntime) { VerboseRecord record = new(Message); - InvocationInfo invocationInfo = GetVariableValue(SpecialVariables.MyInvocation) as InvocationInfo; - - if (invocationInfo != null) + if (GetVariableValue(SpecialVariables.MyInvocation) is InvocationInfo invocationInfo) { record.SetInvocationInfo(invocationInfo); } @@ -129,15 +121,11 @@ protected override void ProcessRecord() // so we create the WarningRecord here and fill it up with the appropriate InvocationInfo; // then, we call the command runtime directly and pass this record to WriteWarning(). // - MshCommandRuntime mshCommandRuntime = this.CommandRuntime as MshCommandRuntime; - - if (mshCommandRuntime != null) + if (this.CommandRuntime is MshCommandRuntime mshCommandRuntime) { WarningRecord record = new(Message); - InvocationInfo invocationInfo = GetVariableValue(SpecialVariables.MyInvocation) as InvocationInfo; - - if (invocationInfo != null) + if (GetVariableValue(SpecialVariables.MyInvocation) is InvocationInfo invocationInfo) { record.SetInvocationInfo(invocationInfo); } @@ -361,8 +349,7 @@ protected override void ProcessRecord() // 2005/07/14-913791 "write-error output is confusing and misleading" // set InvocationInfo to the script not the command - InvocationInfo myInvocation = GetVariableValue(SpecialVariables.MyInvocation) as InvocationInfo; - if (myInvocation != null) + if (GetVariableValue(SpecialVariables.MyInvocation) is InvocationInfo myInvocation) { errorRecord.SetInvocationInfo(myInvocation); errorRecord.PreserveInvocationInfoOnce = true; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteConsoleCmdlet.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteConsoleCmdlet.cs index 2d2009e56bc..b9c4e2d454a 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteConsoleCmdlet.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteConsoleCmdlet.cs @@ -51,9 +51,7 @@ private string ProcessObject(object o) { if (o != null) { - string s = o as string; - IEnumerable enumerable = null; - if (s != null) + if (o is string s) { // strings are IEnumerable, so we special case them if (s.Length > 0) @@ -61,7 +59,7 @@ private string ProcessObject(object o) return s; } } - else if ((enumerable = o as IEnumerable) != null) + else if (o is IEnumerable enumerable) { // unroll enumerables, including arrays. diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs index 0cd748c6139..5b0af6473f4 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs @@ -764,12 +764,10 @@ internal void Import() while (!_deserializer.Done() && count < first) { object result = _deserializer.Deserialize(); - PSObject psObject = result as PSObject; - if (psObject != null) + if (result is PSObject psObject) { - ICollection c = psObject.BaseObject as ICollection; - if (c != null) + if (psObject.BaseObject is ICollection c) { foreach (object o in c) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs index d73df70a97a..91cb0d46abc 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs @@ -512,8 +512,7 @@ public override int Write(object obj, bool enumerateCollection) private static ErrorRecord ConvertToErrorRecord(object obj) { ErrorRecord result = null; - PSObject mshobj = obj as PSObject; - if (mshobj != null) + if (obj is PSObject mshobj) { object baseObject = mshobj.BaseObject; if (baseObject is not PSCustomObject) @@ -522,8 +521,7 @@ private static ErrorRecord ConvertToErrorRecord(object obj) } } - ErrorRecord errorRecordResult = obj as ErrorRecord; - if (errorRecordResult != null) + if (obj is ErrorRecord errorRecordResult) { result = errorRecordResult; } From 0b42d92d4d341ad5a71a576e8d416e4646acab81 Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Thu, 25 May 2023 19:12:42 +0200 Subject: [PATCH 559/779] six files (#19695) --- .../HelpWindow/ParagraphBuilder.cs | 22 ++++--------------- .../cmdletization/cim/cimConverter.cs | 12 +++------- .../commands/utility/MatchString.cs | 13 +++-------- .../engine/ProgressRecord.cs | 11 ++-------- .../engine/TypeTable_Types_Ps1Xml.cs | 5 +---- .../engine/runtime/Operations/StringOps.cs | 7 ++---- 6 files changed, 15 insertions(+), 55 deletions(-) diff --git a/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphBuilder.cs b/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphBuilder.cs index 79c53d04ced..5ca98664aa8 100644 --- a/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphBuilder.cs +++ b/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphBuilder.cs @@ -276,15 +276,8 @@ private static void MoveSpanToPosition(ref int currentSpanIndex, ref TextSpan? c /// Highlight length. private void AddHighlight(int start, int length) { - if (start < 0) - { - throw new ArgumentOutOfRangeException("start"); - } - - if (start + length > this.textBuilder.Length) - { - throw new ArgumentOutOfRangeException("length"); - } + ArgumentOutOfRangeException.ThrowIfNegative(start); + ArgumentOutOfRangeException.ThrowIfGreaterThan(this.textBuilder.Length, start + length, nameof(length)); this.highlightedSpans.Add(new TextSpan(start, length)); } @@ -324,15 +317,8 @@ internal struct TextSpan /// Index of the last character in the span. internal TextSpan(int start, int length) { - if (start < 0) - { - throw new ArgumentOutOfRangeException("start"); - } - - if (length < 1) - { - throw new ArgumentOutOfRangeException("length"); - } + ArgumentOutOfRangeException.ThrowIfNegative(start); + ArgumentOutOfRangeException.ThrowIfLessThan(1, length); this.start = start; this.end = start + length - 1; diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimConverter.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimConverter.cs index 7a3eb0ce326..8c59b551c82 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimConverter.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimConverter.cs @@ -50,15 +50,9 @@ internal SensitiveString(int numberOfCharacters) private unsafe void Copy(char* source, int offset, int charsToCopy) { - if ((offset < 0) || (offset >= _string.Length)) - { - throw new ArgumentOutOfRangeException(nameof(offset)); - } - - if (offset + charsToCopy > _string.Length) - { - throw new ArgumentOutOfRangeException(nameof(charsToCopy)); - } + ArgumentOutOfRangeException.ThrowIfNegative(offset); + ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(_string.Length, offset); + ArgumentOutOfRangeException.ThrowIfGreaterThan(_string.Length, offset + charsToCopy, nameof(charsToCopy)); fixed (char* target = _string) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs index c1643218ce1..9b9fe1aff13 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs @@ -428,10 +428,7 @@ private sealed class CircularBuffer : ICollection /// If is negative. public CircularBuffer(int capacity) { - if (capacity < 0) - { - throw new ArgumentOutOfRangeException(nameof(capacity)); - } + ArgumentOutOfRangeException.ThrowIfNegative(capacity); _items = new T[capacity]; Clear(); @@ -532,12 +529,8 @@ public bool Contains(T item) public void CopyTo(T[] array, int arrayIndex) { - ArgumentNullException.ThrowIfNull(array); - - if (arrayIndex < 0) - { - throw new ArgumentOutOfRangeException(nameof(arrayIndex)); - } + ArgumentNullException.ThrowIfNull(array); + ArgumentOutOfRangeException.ThrowIfNegative(arrayIndex); if (Count > (array.Length - arrayIndex)) { diff --git a/src/System.Management.Automation/engine/ProgressRecord.cs b/src/System.Management.Automation/engine/ProgressRecord.cs index cd5b33107aa..559c4ade73f 100644 --- a/src/System.Management.Automation/engine/ProgressRecord.cs +++ b/src/System.Management.Automation/engine/ProgressRecord.cs @@ -360,15 +360,8 @@ internal static int GetPercentageComplete(DateTime startTime, TimeSpan expectedD startTime.Kind == DateTimeKind.Utc, "DateTime arithmetic should always be done in utc mode [to avoid problems when some operands are calculated right before and right after switching to /from a daylight saving time"); - if (startTime > now) - { - throw new ArgumentOutOfRangeException(nameof(startTime)); - } - - if (expectedDuration <= TimeSpan.Zero) - { - throw new ArgumentOutOfRangeException(nameof(expectedDuration)); - } + ArgumentOutOfRangeException.ThrowIfGreaterThan(now, startTime); + ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(TimeSpan.Zero, expectedDuration); /* * According to the spec of Checkpoint-Computer diff --git a/src/System.Management.Automation/engine/TypeTable_Types_Ps1Xml.cs b/src/System.Management.Automation/engine/TypeTable_Types_Ps1Xml.cs index 22bdd8bcd35..c1a134cdfbf 100644 --- a/src/System.Management.Automation/engine/TypeTable_Types_Ps1Xml.cs +++ b/src/System.Management.Automation/engine/TypeTable_Types_Ps1Xml.cs @@ -17,10 +17,7 @@ public sealed partial class TypeTable private static Func> GetValueFactoryBasedOnInitCapacity(int capacity) { - if (capacity <= 0) - { - throw new ArgumentOutOfRangeException(nameof(capacity)); - } + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(capacity); if (capacity > ValueFactoryCacheCount) { diff --git a/src/System.Management.Automation/engine/runtime/Operations/StringOps.cs b/src/System.Management.Automation/engine/runtime/Operations/StringOps.cs index 0c4658cc14d..0ac1db53ff9 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/StringOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/StringOps.cs @@ -28,11 +28,8 @@ internal static string Multiply(string s, int times) { Diagnostics.Assert(s != null, "caller to verify argument is not null"); - if (times < 0) - { - // TODO: this should be a runtime error. - throw new ArgumentOutOfRangeException(nameof(times)); - } + // TODO: this should be a runtime error. + ArgumentOutOfRangeException.ThrowIfNegative(times); if (times == 0 || s.Length == 0) { From 31dd6483b2655fb156428f34cb841d8d8c43600d Mon Sep 17 00:00:00 2001 From: MartinGC94 <42123497+MartinGC94@users.noreply.github.com> Date: Wed, 31 May 2023 06:39:38 +0200 Subject: [PATCH 560/779] Fix incorrect string to type conversion (#19560) Fixes incorrect string to type conversions like: [Type] 'int]whatever' so they are no longer parsed as types. This was fixed by adding a check for ScanType to also check that the parsed type name matches the input type name. --- src/System.Management.Automation/engine/parser/Parser.cs | 2 +- test/powershell/Language/Parser/Conversions.Tests.ps1 | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/src/System.Management.Automation/engine/parser/Parser.cs b/src/System.Management.Automation/engine/parser/Parser.cs index 610fcba18ad..bfb3ed86b9f 100644 --- a/src/System.Management.Automation/engine/parser/Parser.cs +++ b/src/System.Management.Automation/engine/parser/Parser.cs @@ -281,7 +281,7 @@ internal static ITypeName ScanType(string typename, bool ignoreErrors) var result = parser.TypeNameRule(allowAssemblyQualifiedNames: true, firstTypeNameToken: out _); SemanticChecks.CheckArrayTypeNameDepth(result, PositionUtilities.EmptyExtent, parser); - if (!ignoreErrors && parser.ErrorList.Count > 0) + if (!ignoreErrors && result is not null && (parser.ErrorList.Count > 0 || !result.Extent.Text.Equals(typename, StringComparison.OrdinalIgnoreCase))) { result = null; } diff --git a/test/powershell/Language/Parser/Conversions.Tests.ps1 b/test/powershell/Language/Parser/Conversions.Tests.ps1 index 119f74d9a8a..f6874b1db93 100644 --- a/test/powershell/Language/Parser/Conversions.Tests.ps1 +++ b/test/powershell/Language/Parser/Conversions.Tests.ps1 @@ -78,6 +78,14 @@ Describe 'conversion syntax' -Tags "CI" { $result -join ";" | Should -Be ($Elements -join ";") } } + + It 'Should not convert invalid strings to type name using -as operator' { + 'int]whatever' -as [type] | Should -Be $null + } + + It 'Should not convert invalid strings to type name using left-hand side operator' { + {[Type] 'int]whatever'} | Should -Throw + } } Describe "Type resolution should prefer assemblies in powershell assembly cache" -Tags "Feature" { From ef3e63dc89a9bfdced5e0876f96c785bfc95e95f Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Thu, 1 Jun 2023 16:13:55 -0700 Subject: [PATCH 561/779] Disable SBOM signing for CI and add extra files for packaging tests (#19729) --- .vsts-ci/windows/templates/windows-packaging.yml | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/.vsts-ci/windows/templates/windows-packaging.yml b/.vsts-ci/windows/templates/windows-packaging.yml index 90655ee6298..3961214c86f 100644 --- a/.vsts-ci/windows/templates/windows-packaging.yml +++ b/.vsts-ci/windows/templates/windows-packaging.yml @@ -70,6 +70,7 @@ jobs: Build_Repository_Uri: $(build.repository.uri) displayName: SBOM sourceScanPath: '$(repoPath)\tools' + signSBOM: false # This is needed as SBOM task removed the installed .NET and installs .NET 3.1 - pwsh: | @@ -79,6 +80,18 @@ jobs: condition: succeeded() workingDirectory: $(repoPath) + - pwsh: | + $manifestFolder = Join-Path -Path '$(System.ArtifactsDirectory)/mainBuild' -ChildPath '_manifest' + + if (-not (Test-Path $manifestFolder)) { + throw "_manifest folder does not exist under $(System.ArtifactsDirectory)/mainBuild" + } + + $null = New-Item -Path "$manifestFolder/spdx_2.2/bsi.json" -Verbose -Force + $null = New-Item -Path "$manifestFolder/spdx_2.2/manifest.cat" -Verbose -Force + + displayName: Create fake SBOM manifest signed files + - pwsh: | Import-Module .\tools\ci.psm1 New-CodeCoverageAndTestPackage From 1f02772fd97fea7395fbb7b68e2befd5790db392 Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Thu, 1 Jun 2023 16:49:11 -0700 Subject: [PATCH 562/779] Update `windows.json` packaging BOM (#19728) --- tools/packaging/boms/windows.json | 48 ++++++++++++++++++------------- 1 file changed, 28 insertions(+), 20 deletions(-) diff --git a/tools/packaging/boms/windows.json b/tools/packaging/boms/windows.json index 75b6ddf3266..8b3ac660f42 100644 --- a/tools/packaging/boms/windows.json +++ b/tools/packaging/boms/windows.json @@ -1,4 +1,12 @@ [ + { + "Pattern": "_manifest\\spdx_2.2\\bsi.json", + "FileType": "NonProduct" + }, + { + "Pattern": "_manifest\\spdx_2.2\\manifest.cat", + "FileType": "NonProduct" + }, { "Pattern": "Accessibility.dll", "FileType": "NonProduct" @@ -868,11 +876,11 @@ "FileType": "NonProduct" }, { - "Pattern": "mscordaccore_*.dll", + "Pattern": "mscordaccore.dll", "FileType": "NonProduct" }, { - "Pattern": "mscordaccore.dll", + "Pattern": "mscordaccore_*.dll", "FileType": "NonProduct" }, { @@ -1012,51 +1020,51 @@ "FileType": "NonProduct" }, { - "Pattern": "PresentationFramework-SystemCore.dll", + "Pattern": "PresentationFramework.Aero.dll", "FileType": "NonProduct" }, { - "Pattern": "PresentationFramework-SystemData.dll", + "Pattern": "PresentationFramework.Aero2.dll", "FileType": "NonProduct" }, { - "Pattern": "PresentationFramework-SystemDrawing.dll", + "Pattern": "PresentationFramework.AeroLite.dll", "FileType": "NonProduct" }, { - "Pattern": "PresentationFramework-SystemXml.dll", + "Pattern": "PresentationFramework.Classic.dll", "FileType": "NonProduct" }, { - "Pattern": "PresentationFramework-SystemXmlLinq.dll", + "Pattern": "PresentationFramework.dll", "FileType": "NonProduct" }, { - "Pattern": "PresentationFramework.Aero.dll", + "Pattern": "PresentationFramework.Luna.dll", "FileType": "NonProduct" }, { - "Pattern": "PresentationFramework.Aero2.dll", + "Pattern": "PresentationFramework.Royale.dll", "FileType": "NonProduct" }, { - "Pattern": "PresentationFramework.AeroLite.dll", + "Pattern": "PresentationFramework-SystemCore.dll", "FileType": "NonProduct" }, { - "Pattern": "PresentationFramework.Classic.dll", + "Pattern": "PresentationFramework-SystemData.dll", "FileType": "NonProduct" }, { - "Pattern": "PresentationFramework.dll", + "Pattern": "PresentationFramework-SystemDrawing.dll", "FileType": "NonProduct" }, { - "Pattern": "PresentationFramework.Luna.dll", + "Pattern": "PresentationFramework-SystemXml.dll", "FileType": "NonProduct" }, { - "Pattern": "PresentationFramework.Royale.dll", + "Pattern": "PresentationFramework-SystemXmlLinq.dll", "FileType": "NonProduct" }, { @@ -2056,27 +2064,27 @@ "FileType": "NonProduct" }, { - "Pattern": "Schemas/PSMaml/Maml_HTML_Style.xsl", + "Pattern": "Schemas/PSMaml/Maml.rld", "FileType": "NonProduct" }, { - "Pattern": "Schemas/PSMaml/Maml_HTML.xsl", + "Pattern": "Schemas/PSMaml/Maml.tbr", "FileType": "NonProduct" }, { - "Pattern": "Schemas/PSMaml/Maml.rld", + "Pattern": "Schemas/PSMaml/Maml.xsd", "FileType": "NonProduct" }, { - "Pattern": "Schemas/PSMaml/Maml.tbr", + "Pattern": "Schemas/PSMaml/Maml.xsx", "FileType": "NonProduct" }, { - "Pattern": "Schemas/PSMaml/Maml.xsd", + "Pattern": "Schemas/PSMaml/Maml_HTML.xsl", "FileType": "NonProduct" }, { - "Pattern": "Schemas/PSMaml/Maml.xsx", + "Pattern": "Schemas/PSMaml/Maml_HTML_Style.xsl", "FileType": "NonProduct" }, { From 6c4eb383642a73159515a07e9920dbede35daf5f Mon Sep 17 00:00:00 2001 From: "James Truher [MSFT]" Date: Mon, 5 Jun 2023 11:07:05 -0700 Subject: [PATCH 563/779] Update syslog parser to handle modern formats. (#19737) Co-authored-by: James Truher --- test/tools/Modules/PSSysLog/PSSysLog.psm1 | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/test/tools/Modules/PSSysLog/PSSysLog.psm1 b/test/tools/Modules/PSSysLog/PSSysLog.psm1 index 4dd0da0ade2..634e0903109 100644 --- a/test/tools/Modules/PSSysLog/PSSysLog.psm1 +++ b/test/tools/Modules/PSSysLog/PSSysLog.psm1 @@ -218,8 +218,22 @@ class PSLogItem In those cases, a single message is logged in the following format MMM dd HH:MM:SS machinename id[PID]: message repeated NNN times: [(commitid:TID:CHANNEL) [EventName] Message] + + Alternatively, more recent syslog daemons may change the message format to: + + 2023-06-02T22:49:50.513735+00:00 machinename id[PID]: message repeated NNN times: [(commitid:TID:CHANNEL) [EventName] Message] + + the first element of the line may be converted to a datetime, which we can use to convert the input to the expected string. #> + $firstToken = $content.split()[0] + $dt = $firstToken -as [DateTime] + if ($dt) + { + $replacement = "{0:MMM} {0:dd} {0:hh}:{0:mm}:{0:ss}" -f $dt + $content = $content.replace($firstToken,$replacement) + } + # split contents into separate space delimited tokens (first 7) and leave the rest as the message. [string[]] $parts = $content.Split(' ', 8, [System.StringSplitOptions]::RemoveEmptyEntries) From ddd150dc241cbecf5524102d3ff1e726c820d0c1 Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Mon, 5 Jun 2023 11:14:42 -0700 Subject: [PATCH 564/779] Delete symbols on Linux as well (#19735) --- tools/packaging/packaging.psm1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/packaging/packaging.psm1 b/tools/packaging/packaging.psm1 index f0d5cf5290a..e3ef1e0ed49 100644 --- a/tools/packaging/packaging.psm1 +++ b/tools/packaging/packaging.psm1 @@ -839,7 +839,7 @@ function Update-PSSignedBuildFolder [string]$BuildPath, [Parameter(Mandatory)] [string]$SignedFilesPath, - [string[]] $RemoveFilter = ('*.pdb', '*.zip') + [string[]] $RemoveFilter = ('*.pdb', '*.zip', '*.r2rmap') ) # Replace unsigned binaries with signed From 6520c05949da65756253909fa64a4d3fa1a55396 Mon Sep 17 00:00:00 2001 From: MartinGC94 <42123497+MartinGC94@users.noreply.github.com> Date: Mon, 5 Jun 2023 23:10:03 +0200 Subject: [PATCH 565/779] Fix parsing for array literals in index expressions in method calls (#19224) --- .../engine/parser/Parser.cs | 13 ++++++++++++- test/powershell/Language/Parser/Parsing.Tests.ps1 | 9 +++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/src/System.Management.Automation/engine/parser/Parser.cs b/src/System.Management.Automation/engine/parser/Parser.cs index bfb3ed86b9f..a21fcc1aafa 100644 --- a/src/System.Management.Automation/engine/parser/Parser.cs +++ b/src/System.Management.Automation/engine/parser/Parser.cs @@ -7962,7 +7962,18 @@ private ExpressionAst ElementAccessRule(ExpressionAst primaryExpression, Token l // G primary-expression '[' new-lines:opt expression new-lines:opt ']' SkipNewlines(); - ExpressionAst indexExpr = ExpressionRule(); + bool oldDisableCommaOperator = _disableCommaOperator; + _disableCommaOperator = false; + ExpressionAst indexExpr = null; + try + { + indexExpr = ExpressionRule(); + } + finally + { + _disableCommaOperator = oldDisableCommaOperator; + } + if (indexExpr == null) { // ErrorRecovery: hope we see a closing bracket. If we don't, we'll pretend we saw diff --git a/test/powershell/Language/Parser/Parsing.Tests.ps1 b/test/powershell/Language/Parser/Parsing.Tests.ps1 index 77477a7afbe..2bd717becda 100644 --- a/test/powershell/Language/Parser/Parsing.Tests.ps1 +++ b/test/powershell/Language/Parser/Parsing.Tests.ps1 @@ -665,6 +665,15 @@ Describe "Parsing using statement with alias and linebreak and comma" -Tag CI { } } +It "Should correctly parse array literals for index expressions in method calls" { + $tks = $null + $ers = $null + $Script = '[string]::join(" ", (0, 1, 2)[0, 1])' + $result = [System.Management.Automation.Language.Parser]::ParseInput($Script, [ref]$tks, [ref]$ers) + $result.EndBlock.Statements[0].PipelineElements[0].Expression.Arguments[1].Index.Elements.Count | Should -Be 2 + $ers.Count | Should -Be 0 +} + It "Should correctly parse array types that are used as arguments without brackets in generic type" { $tks = $null $ers = $null From 22fdbbda0b4deb3137800be77217bb1da3b790d9 Mon Sep 17 00:00:00 2001 From: "James Truher [MSFT]" Date: Mon, 5 Jun 2023 16:36:59 -0700 Subject: [PATCH 566/779] Re-enable `Get-ComputerInfo` pending tests (#19746) --- .../Get-ComputerInfo.Tests.ps1 | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Get-ComputerInfo.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Get-ComputerInfo.Tests.ps1 index 8962cdc6179..824de391020 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Get-ComputerInfo.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Get-ComputerInfo.Tests.ps1 @@ -7,6 +7,11 @@ $computerInfoAll = $null $testStartTime = Get-Date +$excludedProperties = @( + "CsPhysicallyInstalledMemory", + "OsServerLevel" +) + function Get-ComputerInfoForTest { # NOTE: $forceRefresh only applies to the case where $properties is null @@ -1041,8 +1046,13 @@ try { # easier to debug the problem if we know *all* the failures # issue: https://github.com/PowerShell/PowerShell/issues/4762 # CsPhysicallyInstalledMemory not available when run in nightly builds - It "Test 01. Standard Property test - all properties ()" -testcase $testCases -Pending { + It "Test 01. Standard Property test - all properties ()" -testcase $testCases { param ( $property ) + + if ($excludedProperties -contains $property) { + Set-ItResult -Pending -Because "'$property' is not available in nightly builds" + } + $specialProperties = "CsNetworkAdapters","CsProcessors","OsHotFixes" if ( $specialProperties -contains $property ) { From b77d51062fa573e7dcc0b2195de4c1949e05a4d2 Mon Sep 17 00:00:00 2001 From: PowerShell Team Bot <69177312+pwshBot@users.noreply.github.com> Date: Mon, 5 Jun 2023 16:40:08 -0700 Subject: [PATCH 567/779] Update to the latest NOTICES file (#19720) --- ThirdPartyNotices.txt | 99 +++++++++++++++++++++++++++++++++---------- 1 file changed, 76 insertions(+), 23 deletions(-) diff --git a/ThirdPartyNotices.txt b/ThirdPartyNotices.txt index c666d530bbb..39670201432 100644 --- a/ThirdPartyNotices.txt +++ b/ThirdPartyNotices.txt @@ -358,11 +358,9 @@ SOFTWARE. --------------------------------------------------------- -Microsoft.CodeAnalysis.Common 4.5.0 - MIT +Microsoft.CodeAnalysis.Common 4.6.0 - MIT -(c) Microsoft Corporation -Copyright (c) .NET Foundation and Contributors MIT License @@ -378,13 +376,9 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI --------------------------------------------------------- -Microsoft.CodeAnalysis.CSharp 4.5.0 - MIT +Microsoft.CodeAnalysis.CSharp 4.6.0 - MIT -(c) Microsoft Corporation -Copyright (c) Microsoft Corporation -Copyright (c) .NET Foundation and Contributors -Copyright (c) Microsoft Corporation. Alle Rechte MIT License @@ -1446,45 +1440,56 @@ SOFTWARE. --------------------------------------------------------- -System.Collections.Immutable 6.0.0 - MIT +System.Collections.Immutable 7.0.0 - MIT -(c) Microsoft Corporation. +(c) Microsoft Corporation Copyright (c) Andrew Arnott +Copyright 2019 LLVM Project Copyright 2018 Daniel Lemire -Copyright 2012 the V8 project -Copyright (c) .NET Foundation. +Copyright (c) .NET Foundation Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson Copyright (c) 1998 Microsoft. To -(c) 1997-2005 Sean Eron Anderson. Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2005-2020 Rich Felker Copyright (c) Microsoft Corporation Copyright (c) 2007 James Newton-King Copyright (c) 2012-2014, Yann Collet +Copyright (c) 1991-2022 Unicode, Inc. Copyright (c) 2013-2017, Alfred Klomp +Copyright 2012 the V8 project authors +Copyright (c) 1999 Lucent Technologies +Copyright (c) 2008-2016, Wojciech Mula +Copyright (c) 2011-2020 Microsoft Corp Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2021 csFastFloat authors Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 Portions (c) International Organization -Copyright (c) 2015 The Chromium Authors. -Copyright (c) The Internet Society 1997. Copyright (c) 2004-2006 Intel Corporation Copyright (c) 2013-2017, Milosz Krajewski Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) Copyright (c) .NET Foundation Contributors -Copyright (c) The Internet Society (2003). +Copyright (c) 2020 Mara Bos Copyright (c) .NET Foundation and Contributors +Copyright (c) 2008-2020 Advanced Micro Devices, Inc. Copyright (c) 2019 Microsoft Corporation, Daan Leijen Copyright (c) 2011 Novell, Inc (http://www.novell.com) -Copyright (c) 1995-2017 Jean-loup Gailly and Mark Adler +Copyright (c) 1995-2022 Jean-loup Gailly and Mark Adler Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) -Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors. +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. -Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip. -Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers THIS WORK IS PROVIDED AS -Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California. -Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass. +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright (c) 1980, 1986, 1993 The Regents of the University of California +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass. To The MIT License (MIT) @@ -3163,9 +3168,57 @@ SOFTWARE. --------------------------------------------------------- -System.Reflection.Metadata 6.0.1 - MIT +System.Reflection.Metadata 7.0.0 - MIT +(c) Microsoft Corporation +Copyright (c) Andrew Arnott +Copyright 2019 LLVM Project +Copyright 2018 Daniel Lemire +Copyright (c) .NET Foundation +Copyright (c) 2011, Google Inc. +Copyright (c) 2020 Dan Shechter +(c) 1997-2005 Sean Eron Anderson +Copyright (c) 1998 Microsoft. To +Copyright (c) 2017 Yoshifumi Kawai +Copyright (c) 2005-2020 Rich Felker +Copyright (c) Microsoft Corporation +Copyright (c) 2007 James Newton-King +Copyright (c) 2012-2014, Yann Collet +Copyright (c) 1991-2022 Unicode, Inc. +Copyright (c) 2013-2017, Alfred Klomp +Copyright 2012 the V8 project authors +Copyright (c) 1999 Lucent Technologies +Copyright (c) 2008-2016, Wojciech Mula +Copyright (c) 2011-2020 Microsoft Corp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2021 csFastFloat authors +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2015 The Chromium Authors +Copyright (c) 2018 Alexander Chermyanin +Copyright (c) The Internet Society 1997 +Portions (c) International Organization +Copyright (c) 2004-2006 Intel Corporation +Copyright (c) 2013-2017, Milosz Krajewski +Copyright (c) 2016-2017, Matthieu Darbois +Copyright (c) The Internet Society (2003) +Copyright (c) .NET Foundation Contributors +Copyright (c) 2020 Mara Bos +Copyright (c) .NET Foundation and Contributors +Copyright (c) 2008-2020 Advanced Micro Devices, Inc. +Copyright (c) 2019 Microsoft Corporation, Daan Leijen +Copyright (c) 2011 Novell, Inc (http://www.novell.com) +Copyright (c) 1995-2022 Jean-loup Gailly and Mark Adler +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors +Copyright (c) 2014 Ryan Juckett http://www.ryanjuckett.com +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers +Copyright (c) 2015 THL A29 Limited, a Tencent company, and Milo Yip +Copyright (c) 1980, 1986, 1993 The Regents of the University of California +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the University of California +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & Digital Equipment Corporation, Maynard, Mass. To The MIT License (MIT) From cc05fdead253b67b7a88fcc34fe5e1e71e6e46a0 Mon Sep 17 00:00:00 2001 From: Patrick Meinecke Date: Mon, 5 Jun 2023 19:45:11 -0400 Subject: [PATCH 568/779] Remove the property disabling optimization (#19701) --- PowerShell.Common.props | 8 -------- .../CoreCLR/CorePsPlatform.cs | 8 +++++--- 2 files changed, 5 insertions(+), 11 deletions(-) diff --git a/PowerShell.Common.props b/PowerShell.Common.props index cf9f792f99c..72fbf3c86a8 100644 --- a/PowerShell.Common.props +++ b/PowerShell.Common.props @@ -185,14 +185,6 @@ full - - - - false - - strict diff --git a/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs b/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs index 25b1624c6cf..783afe62915 100644 --- a/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs +++ b/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs @@ -932,8 +932,10 @@ internal static partial class NativeMethods [LibraryImport(psLib)] internal static partial int WaitPid(int pid, [MarshalAs(UnmanagedType.Bool)] bool nohang); - // This is a struct tm from . - [StructLayout(LayoutKind.Sequential)] + // This is the struct `private_tm` from setdate.h in libpsl-native. + // Packing is set to 4 to match the unmanaged declaration. + // https://github.com/PowerShell/PowerShell-Native/blob/c5575ceb064e60355b9fee33eabae6c6d2708d14/src/libpsl-native/src/setdate.h#L23 + [StructLayout(LayoutKind.Sequential, Pack = 4)] internal unsafe struct UnixTm { /// Seconds (0-60). @@ -980,7 +982,7 @@ internal static UnixTm DateTimeToUnixTm(DateTime date) return tm; } - [LibraryImport(psLib)] + [LibraryImport(psLib, SetLastError = true)] internal static unsafe partial int SetDate(UnixTm* tm); [LibraryImport(psLib, StringMarshalling = StringMarshalling.Utf8)] From 79d99b501bf5e871b67ef1d01564b0edf7b2efe9 Mon Sep 17 00:00:00 2001 From: MartinGC94 <42123497+MartinGC94@users.noreply.github.com> Date: Tue, 6 Jun 2023 02:04:19 +0200 Subject: [PATCH 569/779] Fix member completion for PowerShell Enum class (#19740) --- .../engine/parser/TypeInferenceVisitor.cs | 17 ++++++++++++++++- .../Host/TabCompletion/TabCompletion.Tests.ps1 | 6 ++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs index be3b045f703..de6375bfdbf 100644 --- a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs +++ b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs @@ -364,7 +364,22 @@ internal void AddMembersByInferredTypeDefinitionAst( filterToCall = filter; } - results.AddRange(GetMembersByInferredType(new PSTypeName(typeof(object)), isStatic, filterToCall)); + PSTypeName baseMembersType; + if (typename.TypeDefinitionAst.IsEnum) + { + if (!isStatic) + { + results.Add(new PSInferredProperty("value__", new PSTypeName(typeof(int)))); + } + + baseMembersType = new PSTypeName(typeof(Enum)); + } + else + { + baseMembersType = new PSTypeName(typeof(object)); + } + + results.AddRange(GetMembersByInferredType(baseMembersType, isStatic, filterToCall)); } internal void AddMembersByInferredTypeCimType(PSTypeName typename, List results, Func filterToCall) diff --git a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 index fee6c8c0001..a9cc9801d0e 100644 --- a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 +++ b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 @@ -961,6 +961,12 @@ class InheritedClassTest : System.Attribute $res.CompletionMatches.CompletionText | Should -Contain '-ProgressAction' } + it 'Should complete enum class members for Enums in script text' { + $res = TabExpansion2 -inputScript 'enum Test1 {Val1};([Test1]"").' + $res.CompletionMatches.CompletionText[0] | Should -Be 'value__' + $res.CompletionMatches.CompletionText | Should -Contain 'HasFlag(' + } + Context "Script name completion" { BeforeAll { Setup -f 'install-powershell.ps1' -Content "" From b09ee1689b764bd95d5e3c5d4d87828c2e32f5e7 Mon Sep 17 00:00:00 2001 From: Sean Wheeler Date: Mon, 5 Jun 2023 19:19:49 -0500 Subject: [PATCH 570/779] Add `ParameterSetName` for the `-Detailed` parameter (#19727) --- .../commands/management/TestConnectionCommand.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/TestConnectionCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/TestConnectionCommand.cs index 3e9bbedc605..1f497e5dd2c 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/TestConnectionCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/TestConnectionCommand.cs @@ -188,7 +188,7 @@ public class TestConnectionCommand : PSCmdlet, IDisposable /// Gets or sets whether to enable detailed output mode while running a TCP connection test. /// Without this flag, the TCP test will return a boolean result. /// - [Parameter] + [Parameter(ParameterSetName = TcpPortParameterSet)] public SwitchParameter Detailed; /// From f5b7fd894d8d8dca17e9357f24cc8c188f6f95f5 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 5 Jun 2023 21:55:16 -0700 Subject: [PATCH 571/779] Bump Microsoft.NET.Test.Sdk from 17.6.0 to 17.6.1 (#19733) --- test/xUnit/xUnit.tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/xUnit/xUnit.tests.csproj b/test/xUnit/xUnit.tests.csproj index 848958f6b9a..f5330a68370 100644 --- a/test/xUnit/xUnit.tests.csproj +++ b/test/xUnit/xUnit.tests.csproj @@ -27,7 +27,7 @@ - + From 8363a122d2a8c3456bb294fe7f1bf700ee3a2549 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 6 Jun 2023 09:17:16 -0700 Subject: [PATCH 572/779] Bump Microsoft.PowerShell.MarkdownRender from 7.2.0 to 7.2.1 (#19752) --- .../Microsoft.PowerShell.Commands.Utility.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj index 5b15de0e2ca..d48faa5c565 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj +++ b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj @@ -9,7 +9,7 @@ - + From 9e7cb7240e655fd3584ea85093fa6990b43e3132 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 6 Jun 2023 11:04:25 -0700 Subject: [PATCH 573/779] Bump `Microsoft.PowerShell.MarkdownRender` (#19751) --- .../Microsoft.PowerShell.Commands.Utility.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/packaging/projects/reference/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj b/tools/packaging/projects/reference/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj index 038045f904b..64875719138 100644 --- a/tools/packaging/projects/reference/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj +++ b/tools/packaging/projects/reference/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj @@ -15,6 +15,6 @@ - + From e73a5d2d7121d14898dc49122e5d51de35a5f334 Mon Sep 17 00:00:00 2001 From: PowerShell Team Bot <69177312+pwshBot@users.noreply.github.com> Date: Wed, 7 Jun 2023 10:30:30 -0700 Subject: [PATCH 574/779] Update the cgmanifest (#19763) --- tools/cgmanifest.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tools/cgmanifest.json b/tools/cgmanifest.json index 3b45a6cb048..d1255cbde79 100644 --- a/tools/cgmanifest.json +++ b/tools/cgmanifest.json @@ -1,5 +1,4 @@ { - "$schema": "https://json.schemastore.org/component-detection-manifest.json", "Registrations": [ { "Component": { @@ -166,7 +165,7 @@ "Type": "nuget", "Nuget": { "Name": "Microsoft.PowerShell.MarkdownRender", - "Version": "7.2.0" + "Version": "7.2.1" } }, "DevelopmentDependency": false @@ -831,5 +830,6 @@ }, "DevelopmentDependency": false } - ] + ], + "$schema": "https://json.schemastore.org/component-detection-manifest.json" } From 592e2f0d1953a96d9bc1559112f45241f79e2129 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 7 Jun 2023 10:30:48 -0700 Subject: [PATCH 575/779] Bump Microsoft.NET.Test.Sdk from 17.6.1 to 17.6.2 (#19762) --- test/xUnit/xUnit.tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/xUnit/xUnit.tests.csproj b/test/xUnit/xUnit.tests.csproj index f5330a68370..5471c3e28a5 100644 --- a/test/xUnit/xUnit.tests.csproj +++ b/test/xUnit/xUnit.tests.csproj @@ -27,7 +27,7 @@ - + From b159db3be1cb63e770f280407e97d862b20be119 Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Wed, 7 Jun 2023 11:22:11 -0700 Subject: [PATCH 576/779] Add retry on failure for all upload tasks in Azure Pipelines (#19761) --- .vsts-ci/linux/templates/packaging.yml | 1 + tools/releaseBuild/azureDevOps/releaseBuild.yml | 1 + .../azureDevOps/templates/compliance/apiscan.yml | 1 + .../templates/compliance/generateNotice.yml | 2 ++ .../azureDevOps/templates/linux-packaging.yml | 6 ++++++ tools/releaseBuild/azureDevOps/templates/linux.yml | 14 ++++++++++++++ .../azureDevOps/templates/mac-package-build.yml | 2 ++ .../azureDevOps/templates/mac-package-signing.yml | 2 ++ tools/releaseBuild/azureDevOps/templates/nuget.yml | 2 ++ .../azureDevOps/templates/release-BuildJson.yml | 3 +++ .../templates/release-UpdateDepsJson.yml | 1 + .../azureDevOps/templates/sign-build-file.yml | 4 ++++ .../azureDevOps/templates/signBuildFiles.yml | 2 ++ .../azureDevOps/templates/upload-final-results.yml | 2 ++ .../releaseBuild/azureDevOps/templates/upload.yml | 4 ++++ .../azureDevOps/templates/windows-packaging.yml | 6 ++++++ 16 files changed, 53 insertions(+) diff --git a/.vsts-ci/linux/templates/packaging.yml b/.vsts-ci/linux/templates/packaging.yml index 74a234aff78..fab2e1101fa 100644 --- a/.vsts-ci/linux/templates/packaging.yml +++ b/.vsts-ci/linux/templates/packaging.yml @@ -90,3 +90,4 @@ jobs: Write-Host "##vso[artifact.upload containerfolder=rpm;artifactname=rpm]$packagePath" } displayName: Upload packages + retryCountOnTaskFailure: 2 diff --git a/tools/releaseBuild/azureDevOps/releaseBuild.yml b/tools/releaseBuild/azureDevOps/releaseBuild.yml index 1e979e8c587..be7ce29d2ca 100644 --- a/tools/releaseBuild/azureDevOps/releaseBuild.yml +++ b/tools/releaseBuild/azureDevOps/releaseBuild.yml @@ -369,5 +369,6 @@ stages: Get-Content "$(Build.StagingDirectory)\release.json" Write-Host "##vso[artifact.upload containerfolder=metadata;artifactname=metadata]$(Build.StagingDirectory)\release.json" displayName: Create and upload release.json file to build artifact + retryCountOnTaskFailure: 2 - template: /tools/releaseBuild/azureDevOps/templates/step/finalize.yml diff --git a/tools/releaseBuild/azureDevOps/templates/compliance/apiscan.yml b/tools/releaseBuild/azureDevOps/templates/compliance/apiscan.yml index cae5e0e0231..207bdf0d297 100644 --- a/tools/releaseBuild/azureDevOps/templates/compliance/apiscan.yml +++ b/tools/releaseBuild/azureDevOps/templates/compliance/apiscan.yml @@ -99,6 +99,7 @@ jobs: inputs: pathToPublish: '$(Build.SourcesDirectory)/ReleaseFileHash.csv' artifactName: ReleaseFilesHash + retryCountOnTaskFailure: 2 - task: securedevelopmentteam.vss-secure-development-tools.build-task-apiscan.APIScan@2 displayName: 'Run APIScan' diff --git a/tools/releaseBuild/azureDevOps/templates/compliance/generateNotice.yml b/tools/releaseBuild/azureDevOps/templates/compliance/generateNotice.yml index 2431ded7448..45bb52ae9c7 100644 --- a/tools/releaseBuild/azureDevOps/templates/compliance/generateNotice.yml +++ b/tools/releaseBuild/azureDevOps/templates/compliance/generateNotice.yml @@ -80,6 +80,7 @@ jobs: storage: '$(StorageAccount)' ContainerName: $(tpnContainer) resourceGroup: '$(StorageResourceGroup)' + retryCountOnTaskFailure: 2 - task: PublishPipelineArtifact@1 inputs: @@ -87,3 +88,4 @@ jobs: artifactName: notice displayName: Publish notice artifacts condition: always() + retryCountOnTaskFailure: 2 diff --git a/tools/releaseBuild/azureDevOps/templates/linux-packaging.yml b/tools/releaseBuild/azureDevOps/templates/linux-packaging.yml index 1d6925c737c..67decc43ce6 100644 --- a/tools/releaseBuild/azureDevOps/templates/linux-packaging.yml +++ b/tools/releaseBuild/azureDevOps/templates/linux-packaging.yml @@ -254,6 +254,8 @@ jobs: displayName: Publish artifacts condition: and(succeeded(), ne(variables['SkipBuild'], 'true')) workingDirectory: $(PowerShellRoot) + retryCountOnTaskFailure: 2 + - template: /tools/releaseBuild/azureDevOps/templates/step/finalize.yml @@ -388,6 +390,7 @@ jobs: Destination: AzureBlob storage: '$(StorageAccount)' ContainerName: '$(AzureVersion)' + retryCountOnTaskFailure: 2 - template: upload-final-results.yml parameters: @@ -403,6 +406,7 @@ jobs: storage: '$(StorageAccount)' ContainerName: '$(AzureVersion)-gc' condition: and(eq(variables['buildName'], 'DEB'), succeeded()) + retryCountOnTaskFailure: 2 - template: upload-final-results.yml parameters: @@ -419,6 +423,7 @@ jobs: storage: '$(StorageAccount)' ContainerName: '$(AzureVersion)' condition: and(and(succeeded(), ne(variables['SHOULD_SIGN'], 'true')),eq(variables['buildName'], 'RPM')) + retryCountOnTaskFailure: 2 # requires windows - task: AzureFileCopy@4 @@ -430,6 +435,7 @@ jobs: storage: '$(StorageAccount)' ContainerName: '$(AzureVersion)' condition: and(and(succeeded(), eq(variables['SHOULD_SIGN'], 'true')),eq(variables['buildName'], 'RPM')) + retryCountOnTaskFailure: 2 - template: upload-final-results.yml parameters: diff --git a/tools/releaseBuild/azureDevOps/templates/linux.yml b/tools/releaseBuild/azureDevOps/templates/linux.yml index 03358e2a5ec..3c8a738efc1 100644 --- a/tools/releaseBuild/azureDevOps/templates/linux.yml +++ b/tools/releaseBuild/azureDevOps/templates/linux.yml @@ -160,81 +160,95 @@ jobs: inputs: path: '$(System.ArtifactsDirectory)/pwshLinuxBuild.tar.gz' artifactName: pwshLinuxBuild.tar.gz + retryCountOnTaskFailure: 2 - ${{ if eq(variables.build,'deb') }} : - task: PublishPipelineArtifact@1 inputs: path: '$(System.ArtifactsDirectory)/pwshLinuxBuild-meta' artifactName: pwshLinuxBuild-meta + retryCountOnTaskFailure: 2 - ${{ if eq(variables.build,'deb') }} : - task: PublishPipelineArtifact@1 inputs: path: '$(System.ArtifactsDirectory)/pwshLinuxBuildMinSize.tar.gz' artifactName: pwshLinuxBuildMinSize.tar.gz + retryCountOnTaskFailure: 2 - ${{ if eq(variables.build,'deb') }} : - task: PublishPipelineArtifact@1 inputs: path: '$(System.ArtifactsDirectory)/pwshLinuxBuildMinSize-meta' artifactName: pwshLinuxBuildMinSize-meta + retryCountOnTaskFailure: 2 - ${{ if eq(variables.build,'deb') }} : - task: PublishPipelineArtifact@1 inputs: path: '$(System.ArtifactsDirectory)/pwshLinuxBuildArm32.tar.gz' artifactName: pwshLinuxBuildArm32.tar.gz + retryCountOnTaskFailure: 2 - ${{ if eq(variables.build,'deb') }} : - task: PublishPipelineArtifact@1 inputs: path: '$(System.ArtifactsDirectory)/pwshLinuxBuildArm32-meta' artifactName: pwshLinuxBuildArm32-meta + retryCountOnTaskFailure: 2 - ${{ if eq(variables.build,'deb') }} : - task: PublishPipelineArtifact@1 inputs: path: '$(System.ArtifactsDirectory)/pwshLinuxBuildArm64.tar.gz' artifactName: pwshLinuxBuildArm64.tar.gz + retryCountOnTaskFailure: 2 - ${{ if eq(variables.build,'deb') }} : - task: PublishPipelineArtifact@1 inputs: path: '$(System.ArtifactsDirectory)/pwshLinuxBuildArm64-meta' artifactName: pwshLinuxBuildArm64-meta + retryCountOnTaskFailure: 2 - ${{ if eq(variables.build,'rpm') }} : - task: PublishPipelineArtifact@1 inputs: path: '$(System.ArtifactsDirectory)/pwshMarinerBuildAmd64.tar.gz' artifactName: pwshMarinerBuildAmd64.tar.gz + retryCountOnTaskFailure: 2 - ${{ if eq(variables.build,'rpm') }} : - task: PublishPipelineArtifact@1 inputs: path: '$(System.ArtifactsDirectory)/pwshMarinerBuildAmd64-meta' artifactName: pwshMarinerBuildAmd64-meta + retryCountOnTaskFailure: 2 - ${{ if eq(variables.build,'alpine') }} : - task: PublishPipelineArtifact@1 inputs: path: '$(System.ArtifactsDirectory)/pwshLinuxBuild.tar.gz' artifactName: pwshLinuxBuildAlpine.tar.gz + retryCountOnTaskFailure: 2 - ${{ if eq(variables.build,'alpine') }} : - task: PublishPipelineArtifact@1 inputs: path: '$(System.ArtifactsDirectory)/pwshLinuxBuild-meta' artifactName: pwshLinuxBuildAlpine-meta + retryCountOnTaskFailure: 2 - ${{ if eq(variables.build,'fxdependent') }} : - task: PublishPipelineArtifact@1 inputs: path: '$(System.ArtifactsDirectory)/pwshLinuxBuild.tar.gz' artifactName: pwshLinuxBuildFxdependent.tar.gz + retryCountOnTaskFailure: 2 - ${{ if eq(variables.build,'fxdependent') }} : - task: PublishPipelineArtifact@1 inputs: path: '$(System.ArtifactsDirectory)/pwshLinuxBuild-meta' artifactName: pwshLinuxBuildFxdependent-meta + retryCountOnTaskFailure: 2 diff --git a/tools/releaseBuild/azureDevOps/templates/mac-package-build.yml b/tools/releaseBuild/azureDevOps/templates/mac-package-build.yml index fc5c638c268..cce35c61e95 100644 --- a/tools/releaseBuild/azureDevOps/templates/mac-package-build.yml +++ b/tools/releaseBuild/azureDevOps/templates/mac-package-build.yml @@ -107,6 +107,8 @@ jobs: Write-Host ("sending " + $vstsCommandString) Write-Host "##$vstsCommandString" displayName: Compress signed files + retryCountOnTaskFailure: 2 + - pwsh: | try { diff --git a/tools/releaseBuild/azureDevOps/templates/mac-package-signing.yml b/tools/releaseBuild/azureDevOps/templates/mac-package-signing.yml index b4b6f05821b..d4901580b0b 100644 --- a/tools/releaseBuild/azureDevOps/templates/mac-package-signing.yml +++ b/tools/releaseBuild/azureDevOps/templates/mac-package-signing.yml @@ -113,6 +113,7 @@ jobs: storage: '$(StorageAccount)' ContainerName: '$(AzureVersion)' condition: and(succeeded(), ne(variables['SHOULD_SIGN'], 'true')) + retryCountOnTaskFailure: 2 - task: AzureFileCopy@4 displayName: 'AzureBlob File Copy - signed' @@ -123,6 +124,7 @@ jobs: storage: '$(StorageAccount)' ContainerName: '$(AzureVersion)' condition: and(succeeded(), eq(variables['SHOULD_SIGN'], 'true')) + retryCountOnTaskFailure: 2 - task: ms.vss-governance-buildtask.governance-build-task-component-detection.ComponentGovernanceComponentDetection@0 displayName: 'Component Detection' diff --git a/tools/releaseBuild/azureDevOps/templates/nuget.yml b/tools/releaseBuild/azureDevOps/templates/nuget.yml index ddff73d3511..5202c40b6b6 100644 --- a/tools/releaseBuild/azureDevOps/templates/nuget.yml +++ b/tools/releaseBuild/azureDevOps/templates/nuget.yml @@ -261,6 +261,7 @@ jobs: storage: '$(StorageAccount)' ContainerName: '$(AzureVersion)-nuget' condition: and(succeeded(), eq(variables['SHOULD_SIGN'], 'true')) + retryCountOnTaskFailure: 2 - task: AzureFileCopy@4 displayName: 'Upload global tool packages to Azure' @@ -272,6 +273,7 @@ jobs: ContainerName: 'tool' blobPrefix: '$(Version)' condition: and(succeeded(), eq(variables['SHOULD_SIGN'], 'true')) + retryCountOnTaskFailure: 2 - task: ms.vss-governance-buildtask.governance-build-task-component-detection.ComponentGovernanceComponentDetection@0 displayName: 'Component Detection' diff --git a/tools/releaseBuild/azureDevOps/templates/release-BuildJson.yml b/tools/releaseBuild/azureDevOps/templates/release-BuildJson.yml index e5e5572eb84..d183601a06c 100644 --- a/tools/releaseBuild/azureDevOps/templates/release-BuildJson.yml +++ b/tools/releaseBuild/azureDevOps/templates/release-BuildJson.yml @@ -77,6 +77,7 @@ steps: storage: '$(StorageAccount)' ContainerName: BuildInfo condition: and(succeeded(), eq(variables['CopyMainBuildInfo'], 'YES')) + retryCountOnTaskFailure: 2 - task: AzureFileCopy@4 displayName: 'AzureBlob build info ''lts.json'' Copy when needed' @@ -87,6 +88,7 @@ steps: storage: '$(StorageAccount)' ContainerName: BuildInfo condition: and(succeeded(), eq(variables['CopyLTSBuildInfo'], 'YES')) + retryCountOnTaskFailure: 2 - task: AzureFileCopy@4 displayName: 'AzureBlob build info ''Major-Minor.json'' Copy when needed' @@ -97,3 +99,4 @@ steps: storage: '$(StorageAccount)' ContainerName: BuildInfo condition: and(succeeded(), eq(variables['CopyVersionBuildInfo'], 'YES')) + retryCountOnTaskFailure: 2 diff --git a/tools/releaseBuild/azureDevOps/templates/release-UpdateDepsJson.yml b/tools/releaseBuild/azureDevOps/templates/release-UpdateDepsJson.yml index 31a9715299e..fa42064602e 100644 --- a/tools/releaseBuild/azureDevOps/templates/release-UpdateDepsJson.yml +++ b/tools/releaseBuild/azureDevOps/templates/release-UpdateDepsJson.yml @@ -68,3 +68,4 @@ jobs: storage: '$(StorageAccount)' ContainerName: ps-deps-json blobPrefix: '$(BlobPrefix)' + retryCountOnTaskFailure: 2 diff --git a/tools/releaseBuild/azureDevOps/templates/sign-build-file.yml b/tools/releaseBuild/azureDevOps/templates/sign-build-file.yml index cfa172796d8..a584e15e27c 100644 --- a/tools/releaseBuild/azureDevOps/templates/sign-build-file.yml +++ b/tools/releaseBuild/azureDevOps/templates/sign-build-file.yml @@ -304,6 +304,8 @@ steps: Write-Host "##vso[artifact.upload containerfolder=$containerName;artifactname=$containerName]$uploadTarFilePath" displayName: Upload signed tar.gz files to artifacts condition: eq(variables['ArtifactPlatform'], 'linux') + retryCountOnTaskFailure: 2 + - pwsh: | $uploadFolder = '$(BinPath)' @@ -320,5 +322,7 @@ steps: Write-Host "##vso[artifact.upload containerfolder=$containerName;artifactname=$containerName]$uploadZipFilePath" displayName: Upload signed zip files to artifacts condition: eq(variables['ArtifactPlatform'], 'windows') + retryCountOnTaskFailure: 2 + - template: /tools/releaseBuild/azureDevOps/templates/step/finalize.yml diff --git a/tools/releaseBuild/azureDevOps/templates/signBuildFiles.yml b/tools/releaseBuild/azureDevOps/templates/signBuildFiles.yml index f8a252da21c..a7c7c640ce7 100644 --- a/tools/releaseBuild/azureDevOps/templates/signBuildFiles.yml +++ b/tools/releaseBuild/azureDevOps/templates/signBuildFiles.yml @@ -185,3 +185,5 @@ steps: Write-Host "##vso[artifact.upload containerfolder=$containerName;artifactname=$containerName]$uploadTarFilePath" displayName: ${{ parameters.buildPrefixName }} - Upload signed files to artifacts + retryCountOnTaskFailure: 2 + diff --git a/tools/releaseBuild/azureDevOps/templates/upload-final-results.yml b/tools/releaseBuild/azureDevOps/templates/upload-final-results.yml index 07db5c6b3b8..596b61fb6ed 100644 --- a/tools/releaseBuild/azureDevOps/templates/upload-final-results.yml +++ b/tools/releaseBuild/azureDevOps/templates/upload-final-results.yml @@ -13,3 +13,5 @@ steps: } displayName: Upload ${{ parameters.artifactName }} Artifacts ${{ parameters.artifactFilter }} from ${{ parameters.artifactPath }} condition: ${{ parameters.condition }} + retryCountOnTaskFailure: 2 + diff --git a/tools/releaseBuild/azureDevOps/templates/upload.yml b/tools/releaseBuild/azureDevOps/templates/upload.yml index 3f121e2f51f..c745a02c2a4 100644 --- a/tools/releaseBuild/azureDevOps/templates/upload.yml +++ b/tools/releaseBuild/azureDevOps/templates/upload.yml @@ -21,6 +21,7 @@ steps: ContainerName: '$(AzureVersion)' resourceGroup: '$(StorageResourceGroup)' condition: succeeded() + retryCountOnTaskFailure: 2 - task: AzureFileCopy@4 displayName: 'upload signed min-size package (for Guest Config) to Azure - ${{ parameters.architecture }}' @@ -32,6 +33,7 @@ steps: ContainerName: '$(AzureVersion)-gc' resourceGroup: '$(StorageResourceGroup)' condition: and(eq('${{ parameters.architecture }}', 'x64'), succeeded()) + retryCountOnTaskFailure: 2 - template: upload-final-results.yml parameters: @@ -49,6 +51,7 @@ steps: ContainerName: '$(AzureVersion)-private' resourceGroup: '$(StorageResourceGroup)' condition: and(succeeded(), eq('${{ parameters.msi }}', 'yes')) + retryCountOnTaskFailure: 2 # Disable upload task as the symbols package is not currently used and we want to avoid publishing this in releases #- task: AzureFileCopy@4 @@ -77,3 +80,4 @@ steps: ContainerName: '$(AzureVersion)-private' resourceGroup: '$(StorageResourceGroup)' condition: and(succeeded(), eq('${{ parameters.msix }}', 'yes'), eq(variables['SHOULD_SIGN'], 'true')) + retryCountOnTaskFailure: 2 diff --git a/tools/releaseBuild/azureDevOps/templates/windows-packaging.yml b/tools/releaseBuild/azureDevOps/templates/windows-packaging.yml index f0b1e10bbbb..1ebb0be033a 100644 --- a/tools/releaseBuild/azureDevOps/templates/windows-packaging.yml +++ b/tools/releaseBuild/azureDevOps/templates/windows-packaging.yml @@ -235,6 +235,8 @@ jobs: Write-Host ("sending " + $vstsCommandString) Write-Host "##$vstsCommandString" displayName: Compress signed files + retryCountOnTaskFailure: 2 + - pwsh: | $runtime = switch ($env:Architecture) @@ -268,6 +270,7 @@ jobs: Write-Host "##vso[artifact.upload containerfolder=signed;artifactname=signed]$packagePath" } displayName: Upload unsigned packages + retryCountOnTaskFailure: 2 - ${{ if and(ne(variables['BuildConfiguration'],'minSize'), in(variables['Architecture'], 'x64', 'x86')) }}: - template: EsrpSign.yml@ComplianceRepo @@ -289,6 +292,7 @@ jobs: Write-Host "##vso[artifact.upload containerfolder=finalResults;artifactname=finalResults]$packagePath" } displayName: Upload signed MSI to finalResults + retryCountOnTaskFailure: 2 - task: AzureFileCopy@4 displayName: 'upload signed msi to Azure - ${{ parameters.architecture }}' @@ -299,6 +303,7 @@ jobs: storage: '$(StorageAccount)' ContainerName: '$(AzureVersion)' resourceGroup: '$(StorageResourceGroup)' + retryCountOnTaskFailure: 2 - pwsh: | cd $(PowerShellRoot) @@ -345,6 +350,7 @@ jobs: Write-Host "##vso[artifact.upload containerfolder=signed;artifactname=signed]$packagePath" } displayName: Upload unsigned exe + retryCountOnTaskFailure: 2 - task: ms.vss-governance-buildtask.governance-build-task-component-detection.ComponentGovernanceComponentDetection@0 displayName: 'Component Detection' From 96e72fb48be656e34a4ed9a9745ce80be60386f3 Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Wed, 7 Jun 2023 13:19:37 -0700 Subject: [PATCH 577/779] Update group to assign PRs in `fabricbot.json` (#19759) --- .github/fabricbot.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/fabricbot.json b/.github/fabricbot.json index 6cff68d8c2b..3fcf27f06dd 100644 --- a/.github/fabricbot.json +++ b/.github/fabricbot.json @@ -1128,7 +1128,7 @@ { "name": "assignToGitHubUserGroup", "parameters": { - "groupId": "5dd8713b90bf2e113c0e885e", + "groupId": "wr87plQOBSdssuPwnMk9T", "skipOpener": true } } @@ -1165,7 +1165,7 @@ { "name": "assignToGitHubUserGroup", "parameters": { - "groupId": "5dd8713b90bf2e113c0e885e" + "groupId": "wr87plQOBSdssuPwnMk9T" } } ] From 2e3aabd3f7f8236fe7d652b6957e16405458d7fb Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Thu, 8 Jun 2023 13:57:49 -0700 Subject: [PATCH 578/779] Update `working-group.md` to add section about reporting working group members (#19758) --- docs/community/working-group.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/docs/community/working-group.md b/docs/community/working-group.md index 54bbcadf014..8b9caea2857 100644 --- a/docs/community/working-group.md +++ b/docs/community/working-group.md @@ -188,3 +188,10 @@ firmer guidelines around when PRs should be merged as experimental. Experiments should be complete to the extent that they serve as reasonable indicators of the user experience. In the case that breaking changes are required of the feature, the break should be made in the prototype so that users can experiment with whether or not the break has a significant negative effect. + +#### Reporting Working Group members abuse + +Working group members are individuals and in many cases volunteers. +There may be situations where a working group member might exhibit behavior that is objectionable, +exceed the authority defined in this document or violate the [Code of Conduct](../../CODE_OF_CONDUCT.md). +We recommend to report such issues by using the [Report Content](https://docs.github.com/communities/maintaining-your-safety-on-github/reporting-abuse-or-spam) mechanism to bring it to the attention of the maintainers to review. From 6d57d048b17c98f920b61890625fbfd6b17db020 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 9 Jun 2023 08:05:40 +0500 Subject: [PATCH 579/779] Bump JsonSchema.Net from 4.1.1 to 4.1.2 (#19768) Bumps [JsonSchema.Net](https://github.com/gregsdennis/json-everything) from 4.1.1 to 4.1.2. - [Commits](https://github.com/gregsdennis/json-everything/compare/schema-v4.1.1...schema-v4.1.2) --- updated-dependencies: - dependency-name: JsonSchema.Net dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .../Microsoft.PowerShell.Commands.Utility.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj index d48faa5c565..26bba98503b 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj +++ b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj @@ -35,7 +35,7 @@ - + From 0355d2f4df6ba3dec123f51475277bbf1fc0b37d Mon Sep 17 00:00:00 2001 From: PowerShell Team Bot <69177312+pwshBot@users.noreply.github.com> Date: Fri, 9 Jun 2023 09:42:24 -0700 Subject: [PATCH 580/779] Update the cgmanifest (#19776) --- tools/cgmanifest.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tools/cgmanifest.json b/tools/cgmanifest.json index d1255cbde79..6b60dd4e0e8 100644 --- a/tools/cgmanifest.json +++ b/tools/cgmanifest.json @@ -1,4 +1,5 @@ { + "$schema": "https://json.schemastore.org/component-detection-manifest.json", "Registrations": [ { "Component": { @@ -55,7 +56,7 @@ "Type": "nuget", "Nuget": { "Name": "JsonSchema.Net", - "Version": "4.1.1" + "Version": "4.1.2" } }, "DevelopmentDependency": false @@ -830,6 +831,5 @@ }, "DevelopmentDependency": false } - ], - "$schema": "https://json.schemastore.org/component-detection-manifest.json" + ] } From 1822ad73737956d64d71465c2f874f8899ed4fec Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Mon, 12 Jun 2023 18:55:32 +0200 Subject: [PATCH 581/779] Add `FileNameStar` to `MultipartFileContent` in WebCmdlets (#19467) --- .../Common/WebRequestPSCmdlet.Common.cs | 12 ++---- .../WebCmdlets.Tests.ps1 | 43 +++++++++++++++++++ 2 files changed, 47 insertions(+), 8 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index ce878c1677b..f7b6f3e270c 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -1720,9 +1720,7 @@ private void AddMultipartContent(object fieldName, object fieldValue, MultipartF private static StringContent GetMultipartStringContent(object fieldName, object fieldValue) { ContentDispositionHeaderValue contentDisposition = new("form-data"); - - // .NET does not enclose field names in quotes, however, modern browsers and curl do. - contentDisposition.Name = "\"" + LanguagePrimitives.ConvertTo(fieldName) + "\""; + contentDisposition.Name = LanguagePrimitives.ConvertTo(fieldName); StringContent result = new(LanguagePrimitives.ConvertTo(fieldValue)); result.Headers.ContentDisposition = contentDisposition; @@ -1738,9 +1736,7 @@ private static StringContent GetMultipartStringContent(object fieldName, object private static StreamContent GetMultipartStreamContent(object fieldName, Stream stream) { ContentDispositionHeaderValue contentDisposition = new("form-data"); - - // .NET does not enclose field names in quotes, however, modern browsers and curl do. - contentDisposition.Name = "\"" + LanguagePrimitives.ConvertTo(fieldName) + "\""; + contentDisposition.Name = LanguagePrimitives.ConvertTo(fieldName); StreamContent result = new(stream); result.Headers.ContentDisposition = contentDisposition; @@ -1758,8 +1754,8 @@ private static StreamContent GetMultipartFileContent(object fieldName, FileInfo { StreamContent result = GetMultipartStreamContent(fieldName: fieldName, stream: new FileStream(file.FullName, FileMode.Open)); - // .NET does not enclose field names in quotes, however, modern browsers and curl do. - result.Headers.ContentDisposition.FileName = "\"" + file.Name + "\""; + result.Headers.ContentDisposition.FileName = file.Name; + result.Headers.ContentDisposition.FileNameStar = file.Name; return result; } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 index 117d42ac203..da7a395ff28 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 @@ -1590,6 +1590,11 @@ Describe "Invoke-WebRequest tests" -Tags "Feature", "RequireAdminOnWindows" { $file2Path = Join-Path $testdrive $file2Name $file2Contents = "Test456" $file2Contents | Set-Content $file2Path -Force + + $file3Name = "Kündigung_Mustermann_Max.TTA_2023_01_30.txt" + $file3Path = Join-Path $testdrive $file3Name + $file3Contents = "Test789" + $file3Contents | Set-Content $file3Path -Force } It "Verifies Invoke-WebRequest Supports Multipart String Values" { @@ -1665,6 +1670,23 @@ Describe "Invoke-WebRequest tests" -Tags "Feature", "RequireAdminOnWindows" { $result.Files[0].Content | Should -Match $file1Contents } + It "Verifies Invoke-WebRequest -Form sets Content-Disposition FileName and FileNameStar." { + $ContentDisposition = [System.Net.Http.Headers.ContentDispositionHeaderValue]::new("attachment") + $ContentDisposition.FileName = $fileName + $ContentDisposition.FileNameStar = $fileName + + $form = @{TestFile = [System.IO.FileInfo]$file3Path} + $uri = Get-WebListenerUrl -Test 'Multipart' + $response = Invoke-WebRequest -Uri $uri -Form $form -Method 'POST' + $result = $response.Content | ConvertFrom-Json + + $result.Headers.'Content-Type' | Should -Match 'multipart/form-data' + $result.Files.Count | Should -Be 1 + + $result.Files[0].ContentDisposition.FileName | Should -Be $ContentDisposition.FileName + $result.Files[0].ContentDisposition.FileNameStar | Should -Be $ContentDisposition.FileNameStar + } + It "Verifies Invoke-WebRequest -Form supports a collection of file values" { $form = @{TestFiles = [System.IO.FileInfo]$file1Path, [System.IO.FileInfo]$file2Path} $uri = Get-WebListenerUrl -Test 'Multipart' @@ -3362,6 +3384,11 @@ Describe "Invoke-RestMethod tests" -Tags "Feature", "RequireAdminOnWindows" { $file2Path = Join-Path $testdrive $file2Name $file2Contents = "Test456" $file2Contents | Set-Content $file2Path -Force + + $file3Name = "Kündigung_Mustermann_Max.TTA_2023_01_30.txt" + $file3Path = Join-Path $testdrive $file3Name + $file3Contents = "Test789" + $file3Contents | Set-Content $file3Path -Force } It "Verifies Invoke-RestMethod Supports Multipart String Values" { @@ -3431,6 +3458,22 @@ Describe "Invoke-RestMethod tests" -Tags "Feature", "RequireAdminOnWindows" { $result.Files[0].Content | Should -Match $file1Contents } + It "Verifies Invoke-RestMethod -Form sets Content-Disposition FileName and FileNameStar." { + $ContentDisposition = [System.Net.Http.Headers.ContentDispositionHeaderValue]::new("attachment") + $ContentDisposition.FileName = $fileName + $ContentDisposition.FileNameStar = $fileName + + $form = @{TestFile = [System.IO.FileInfo]$file3Path} + $uri = Get-WebListenerUrl -Test 'Multipart' + $result = Invoke-RestMethod -Uri $uri -Form $form -Method 'POST' + + $result.Headers.'Content-Type' | Should -Match 'multipart/form-data' + $result.Files.Count | Should -Be 1 + + $result.Files[0].ContentDisposition.FileName | Should -Be $ContentDisposition.FileName + $result.Files[0].ContentDisposition.FileNameStar | Should -Be $ContentDisposition.FileNameStar + } + It "Verifies Invoke-RestMethod -Form supports a collection of file values" { $form = @{TestFiles = [System.IO.FileInfo]$file1Path, [System.IO.FileInfo]$file2Path} $uri = Get-WebListenerUrl -Test 'Multipart' From f093f538fa6a1c21e0d4b53c1b514571ad148d46 Mon Sep 17 00:00:00 2001 From: MartinGC94 <42123497+MartinGC94@users.noreply.github.com> Date: Mon, 12 Jun 2023 19:38:17 +0200 Subject: [PATCH 582/779] Fix variable type inference precedence (#18691) --- .../engine/parser/TypeInferenceVisitor.cs | 12 ++++-------- .../engine/Api/TypeInference.Tests.ps1 | 18 ++++++++++++++++++ 2 files changed, 22 insertions(+), 8 deletions(-) diff --git a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs index de6375bfdbf..1e1ff771ac5 100644 --- a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs +++ b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs @@ -2121,11 +2121,6 @@ private void InferTypeFrom(VariableExpressionAst variableExpressionAst, List)AstSearcher.FindAll( parent, @@ -2165,9 +2160,9 @@ private void InferTypeFrom(VariableExpressionAst variableExpressionAst, List= 0; i--) { - if (assignAst.Left is ConvertExpressionAst lhsConvert) + if (assignAsts[i].Left is ConvertExpressionAst lhsConvert) { inferredTypes.Add(new PSTypeName(lhsConvert.Type.TypeName)); return; @@ -2592,7 +2587,8 @@ public static bool AstAssignsToSameVariable(this VariableExpressionAst variableA if (parameterAst != null) { return variableAstVariablePath.IsUnscopedVariable && - parameterAst.Name.VariablePath.UnqualifiedPath.Equals(variableAstVariablePath.UnqualifiedPath, StringComparison.OrdinalIgnoreCase); + parameterAst.Name.VariablePath.UnqualifiedPath.Equals(variableAstVariablePath.UnqualifiedPath, StringComparison.OrdinalIgnoreCase) && + parameterAst.Parent.Parent.Extent.EndOffset > variableAst.Extent.StartOffset; } if (ast is ForEachStatementAst foreachAst) diff --git a/test/powershell/engine/Api/TypeInference.Tests.ps1 b/test/powershell/engine/Api/TypeInference.Tests.ps1 index 14e3a3b0868..69817f6290d 100644 --- a/test/powershell/engine/Api/TypeInference.Tests.ps1 +++ b/test/powershell/engine/Api/TypeInference.Tests.ps1 @@ -1385,6 +1385,24 @@ Describe "Type inference Tests" -tags "CI" { $res.Name -join ' ' | Should -Be "System.IO.FileInfo System.IO.DirectoryInfo" } + It 'Infers closest variable type' { + $res = [AstTypeInference]::InferTypeOf( { [string]$TestVar = "";[hashtable]$TestVar = @{};$TestVar }.Ast) + $res.Name | Select-Object -Last 1 | Should -Be "System.Collections.Hashtable" + } + + It 'Infers closest variable type and ignores unrelated param blocks' { + $res = [AstTypeInference]::InferTypeOf( { + [hashtable]$ParameterName=@{} + function Verb-Noun { + param + ( + [string]$ParameterName + ) + } + $ParameterName }.Ast) + $res.Name | Should -Be "System.Collections.Hashtable" + } + It 'Infers type of $null after variable assignment' { $res = [AstTypeInference]::InferTypeOf( { $null = "Hello";$null }.Ast) $res.Count | Should -Be 0 From 96903c7079a66e1fa98b3bd39e5601a9f1719e76 Mon Sep 17 00:00:00 2001 From: PowerShell Team Bot <69177312+pwshBot@users.noreply.github.com> Date: Mon, 12 Jun 2023 10:51:44 -0700 Subject: [PATCH 583/779] Update to the latest NOTICES file (#19784) --- ThirdPartyNotices.txt | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/ThirdPartyNotices.txt b/ThirdPartyNotices.txt index 39670201432..52fa655072a 100644 --- a/ThirdPartyNotices.txt +++ b/ThirdPartyNotices.txt @@ -238,7 +238,7 @@ SOFTWARE. --------------------------------------------------------- -JsonSchema.Net 4.1.1 - MIT +JsonSchema.Net 4.1.2 - MIT (c) Microsoft 2023 @@ -361,6 +361,8 @@ SOFTWARE. Microsoft.CodeAnalysis.Common 4.6.0 - MIT +(c) Microsoft Corporation +Copyright (c) .NET Foundation and Contributors MIT License @@ -379,6 +381,10 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI Microsoft.CodeAnalysis.CSharp 4.6.0 - MIT +(c) Microsoft Corporation +Copyright (c) Microsoft Corporation +Copyright (c) .NET Foundation and Contributors +Copyright (c) Microsoft Corporation. Alle Rechte MIT License @@ -432,10 +438,10 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI --------------------------------------------------------- -Microsoft.PowerShell.MarkdownRender 7.2.0 - MIT +Microsoft.PowerShell.MarkdownRender 7.2.1 - MIT -(c) Microsoft Corporation. +(c) Microsoft Corporation (c) Microsoft Corporation. PowerShell's Markdown Rendering project PowerShell Markdown Renderer MIT License From da35b7c18069749befb55337f12e4d942cc80771 Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Mon, 12 Jun 2023 17:00:56 -0700 Subject: [PATCH 584/779] Update JsonSchema.Net from 4.1.2 to 4.1.3 (#19788) --- ...crosoft.PowerShell.Commands.Utility.csproj | 2 +- tools/packaging/boms/windows.json | 56 +++++++++++-------- 2 files changed, 33 insertions(+), 25 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj index 26bba98503b..ca841d9beb7 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj +++ b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj @@ -35,7 +35,7 @@ - + diff --git a/tools/packaging/boms/windows.json b/tools/packaging/boms/windows.json index 8b3ac660f42..308342e8f10 100644 --- a/tools/packaging/boms/windows.json +++ b/tools/packaging/boms/windows.json @@ -211,6 +211,10 @@ "Pattern": "en-US/default.help.txt", "FileType": "NonProduct" }, + { + "Pattern": "es-ES\\JsonSchema.Net.resources.dll", + "FileType": "NonProduct" + }, { "Pattern": "es/Microsoft.CodeAnalysis.CSharp.resources.dll", "FileType": "NonProduct" @@ -295,10 +299,6 @@ "Pattern": "es/WindowsFormsIntegration.resources.dll", "FileType": "NonProduct" }, - { - "Pattern": "es\\JsonSchema.Net.resources.dll", - "FileType": "NonProduct" - }, { "Pattern": "fr/Microsoft.CodeAnalysis.CSharp.resources.dll", "FileType": "NonProduct" @@ -876,11 +876,11 @@ "FileType": "NonProduct" }, { - "Pattern": "mscordaccore.dll", + "Pattern": "mscordaccore_*.dll", "FileType": "NonProduct" }, { - "Pattern": "mscordaccore_*.dll", + "Pattern": "mscordaccore.dll", "FileType": "NonProduct" }, { @@ -899,6 +899,10 @@ "Pattern": "msquic.dll", "FileType": "NonProduct" }, + { + "Pattern": "nb-NO\\JsonSchema.Net.resources.dll", + "FileType": "NonProduct" + }, { "Pattern": "netstandard.dll", "FileType": "NonProduct" @@ -1020,51 +1024,51 @@ "FileType": "NonProduct" }, { - "Pattern": "PresentationFramework.Aero.dll", + "Pattern": "PresentationFramework-SystemCore.dll", "FileType": "NonProduct" }, { - "Pattern": "PresentationFramework.Aero2.dll", + "Pattern": "PresentationFramework-SystemData.dll", "FileType": "NonProduct" }, { - "Pattern": "PresentationFramework.AeroLite.dll", + "Pattern": "PresentationFramework-SystemDrawing.dll", "FileType": "NonProduct" }, { - "Pattern": "PresentationFramework.Classic.dll", + "Pattern": "PresentationFramework-SystemXml.dll", "FileType": "NonProduct" }, { - "Pattern": "PresentationFramework.dll", + "Pattern": "PresentationFramework-SystemXmlLinq.dll", "FileType": "NonProduct" }, { - "Pattern": "PresentationFramework.Luna.dll", + "Pattern": "PresentationFramework.Aero.dll", "FileType": "NonProduct" }, { - "Pattern": "PresentationFramework.Royale.dll", + "Pattern": "PresentationFramework.Aero2.dll", "FileType": "NonProduct" }, { - "Pattern": "PresentationFramework-SystemCore.dll", + "Pattern": "PresentationFramework.AeroLite.dll", "FileType": "NonProduct" }, { - "Pattern": "PresentationFramework-SystemData.dll", + "Pattern": "PresentationFramework.Classic.dll", "FileType": "NonProduct" }, { - "Pattern": "PresentationFramework-SystemDrawing.dll", + "Pattern": "PresentationFramework.dll", "FileType": "NonProduct" }, { - "Pattern": "PresentationFramework-SystemXml.dll", + "Pattern": "PresentationFramework.Luna.dll", "FileType": "NonProduct" }, { - "Pattern": "PresentationFramework-SystemXmlLinq.dll", + "Pattern": "PresentationFramework.Royale.dll", "FileType": "NonProduct" }, { @@ -2064,27 +2068,27 @@ "FileType": "NonProduct" }, { - "Pattern": "Schemas/PSMaml/Maml.rld", + "Pattern": "Schemas/PSMaml/Maml_HTML_Style.xsl", "FileType": "NonProduct" }, { - "Pattern": "Schemas/PSMaml/Maml.tbr", + "Pattern": "Schemas/PSMaml/Maml_HTML.xsl", "FileType": "NonProduct" }, { - "Pattern": "Schemas/PSMaml/Maml.xsd", + "Pattern": "Schemas/PSMaml/Maml.rld", "FileType": "NonProduct" }, { - "Pattern": "Schemas/PSMaml/Maml.xsx", + "Pattern": "Schemas/PSMaml/Maml.tbr", "FileType": "NonProduct" }, { - "Pattern": "Schemas/PSMaml/Maml_HTML.xsl", + "Pattern": "Schemas/PSMaml/Maml.xsd", "FileType": "NonProduct" }, { - "Pattern": "Schemas/PSMaml/Maml_HTML_Style.xsl", + "Pattern": "Schemas/PSMaml/Maml.xsx", "FileType": "NonProduct" }, { @@ -2139,6 +2143,10 @@ "Pattern": "sni.dll", "FileType": "NonProduct" }, + { + "Pattern": "sv-SE\\JsonSchema.Net.resources.dll", + "FileType": "NonProduct" + }, { "Pattern": "System.AppContext.dll", "FileType": "NonProduct" From ba0de3b4fe1d99102bb49991b3b9c17488087286 Mon Sep 17 00:00:00 2001 From: "James Truher [MSFT]" Date: Mon, 12 Jun 2023 17:03:53 -0700 Subject: [PATCH 585/779] Add some debugging to the transcript test for `SilentlyContinue` (#19770) --- test/powershell/Host/Logging.Tests.ps1 | 12 ++++++++ .../Get-Counter.Tests.ps1 | 2 +- .../Start-Transcript.Tests.ps1 | 5 ++-- .../PackageManagement.Tests.ps1 | 28 +++++++++++++------ test/tools/Modules/PSSysLog/PSSysLog.psm1 | 11 ++++---- 5 files changed, 41 insertions(+), 17 deletions(-) diff --git a/test/powershell/Host/Logging.Tests.ps1 b/test/powershell/Host/Logging.Tests.ps1 index 628bd8ac95e..52d10c36dee 100644 --- a/test/powershell/Host/Logging.Tests.ps1 +++ b/test/powershell/Host/Logging.Tests.ps1 @@ -269,6 +269,9 @@ Describe 'Basic os_log tests on MacOS' -Tag @('CI','RequireSudoOnUnix') { [bool] $IsSupportedEnvironment = $IsMacOS [bool] $persistenceEnabled = $false + $currentWarningPreference = $WarningPreference + $WarningPreference = "SilentlyContinue" + if ($IsSupportedEnvironment) { # Check the current state. @@ -306,6 +309,7 @@ Path:.* } AfterAll { + $WarningPreference = $currentWarningPreference if ($IsSupportedEnvironment -and !$persistenceEnabled) { # disable persistence if it wasn't enabled @@ -444,6 +448,10 @@ Describe 'Basic EventLog tests on Windows' -Tag @('CI','RequireAdminOnWindows') BeforeAll { [bool] $IsSupportedEnvironment = $IsWindows [string] $powershell = Join-Path -Path $PSHOME -ChildPath 'pwsh' + + $currentWarningPreference = $WarningPreference + $WarningPreference = "SilentlyContinue" + $scriptBlockLoggingCases = @( @{ name = 'normal script block' @@ -463,6 +471,10 @@ Describe 'Basic EventLog tests on Windows' -Tag @('CI','RequireAdminOnWindows') } } + AfterAll { + $WarningPreference = $currentWarningPreference + } + BeforeEach { if ($IsSupportedEnvironment) { diff --git a/test/powershell/Modules/Microsoft.PowerShell.Diagnostics/Get-Counter.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Diagnostics/Get-Counter.Tests.ps1 index 675cb11488f..57760b848ea 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Diagnostics/Get-Counter.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Diagnostics/Get-Counter.Tests.ps1 @@ -173,7 +173,7 @@ Describe "Feature tests for Get-Counter cmdlet" -Tags "Feature" { $counterData = Get-Counter -Counter $counterPath -SampleInterval $sampleInterval -MaxSamples $counterCount $endTime = Get-Date $counterData.Length | Should -Be $counterCount - ($endTime - $startTime).TotalSeconds | Should -Not -BeLessThan ($counterCount * $sampleInterval) + ($endTime - $startTime).TotalSeconds -as [int] | Should -Not -BeLessThan ($counterCount * $sampleInterval) } It "Can process array of counter names" -Skip:$(SkipCounterTests) { diff --git a/test/powershell/Modules/Microsoft.Powershell.Host/Start-Transcript.Tests.ps1 b/test/powershell/Modules/Microsoft.Powershell.Host/Start-Transcript.Tests.ps1 index d350c44d80c..3e398a0fa70 100644 --- a/test/powershell/Modules/Microsoft.Powershell.Host/Start-Transcript.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.Powershell.Host/Start-Transcript.Tests.ps1 @@ -187,9 +187,10 @@ Describe "Start-Transcript, Stop-Transcript tests" -tags "CI" { It "Transcription should not record Write-Information output when InformationAction is set to SilentlyContinue" { [String]$message = New-Guid + $traceData = Join-Path $TESTDRIVE tracedata.txt $script = { Start-Transcript -Path $transcriptFilePath - Write-Information -Message $message -InformationAction SilentlyContinue + Trace-Command -File $traceData -Name param* { Write-Information -Message $message -InformationAction SilentlyContinue } Stop-Transcript } @@ -197,7 +198,7 @@ Describe "Start-Transcript, Stop-Transcript tests" -tags "CI" { $transcriptFilePath | Should -Exist $transcriptFilePath | Should -Not -FileContentMatch "INFO: " - $transcriptFilePath | Should -Not -FileContentMatch $message + $transcriptFilePath | Should -Not -FileContentMatch $message -Because (get-content $transcriptFilePath,$traceData) } It "Transcription should not record Write-Information output when InformationAction is set to Ignore" { diff --git a/test/powershell/Modules/PackageManagement/PackageManagement.Tests.ps1 b/test/powershell/Modules/PackageManagement/PackageManagement.Tests.ps1 index bd4d0218f5d..01b4d4738a6 100644 --- a/test/powershell/Modules/PackageManagement/PackageManagement.Tests.ps1 +++ b/test/powershell/Modules/PackageManagement/PackageManagement.Tests.ps1 @@ -22,15 +22,25 @@ Describe "PackageManagement Acceptance Test" -Tags "Feature" { # register the asset directory $localSourceName = [Guid]::NewGuid().ToString("n") $localSourceLocation = Join-Path $PSScriptRoot assets - Register-PackageSource -Name $localSourceName -provider NuGet -Location $localSourceLocation -Force -Trusted + $newSourceResult = Register-PackageSource -Name $localSourceName -provider NuGet -Location $localSourceLocation -Force -Trusted + Write-Verbose -Verbose -Message "Register-PackageSource -Name $localSourceName -provider NuGet -Location $localSourceLocation -Force -Trusted" + $newSourceResult | Out-String -Stream | Write-Verbose -Verbose + + $skipPackageTests = $false + if ($newSourceResult.Location -ne $localSourceLocation) { + $skipPackageTests = $true + } # register the gallery location $galleryLocation = "https://www.powershellgallery.com/api/v2" $gallerySourceName = [Guid]::newGuid().ToString("n") + # this is expected to fail as there should already be a source pointing to the gallery url Register-PackageSource -Name $gallerySourceName -Location $galleryLocation -ProviderName 'PowerShellGet' -Trusted -ErrorAction SilentlyContinue $SavedProgressPreference = $ProgressPreference $ProgressPreference = "SilentlyContinue" + + Get-PackageSource | Out-String -Stream | Write-Verbose -Verbose } AfterAll { @@ -64,27 +74,27 @@ Describe "PackageManagement Acceptance Test" -Tags "Feature" { $ipp | Should -Contain "NanoServerPackage" } - It "Find-package" { + It "Find-package" -skip:$skipPackageTests { $f = Find-Package -ProviderName NuGet -Name $packageName -Source $localSourceName - $f.Name | Should -Contain "$packageName" + $f.Name | Should -Contain "$packageName" -Because "PackageSource $localSourceLocation not created" } - It "Install-package" { + It "Install-package" -skip:$skipPackageTests { $i = Install-Package -ProviderName NuGet -Name $packageName -Force -Source $localSourceName -Scope CurrentUser - $i.Name | Should -Contain "$packageName" + $i.Name | Should -Contain "$packageName" -Because "PackageSource $localSourceLocation not created" } - It "Get-package" { + It "Get-package" -skip:$skipPackageTests { $g = Get-Package -ProviderName NuGet -Name $packageName $g.Name | Should -Contain "$packageName" } - It "save-package" { + It "save-package" -skip:$skipPackageTests { $s = Save-Package -ProviderName NuGet -Name $packageName -Path $TestDrive -Force -Source $localSourceName - $s.Name | Should -Contain "$packageName" + $s.Name | Should -Contain "$packageName" -Because (Get-ChildItem $TestDrive) } - It "uninstall-package" { + It "uninstall-package" -skip:$skipPackageTests { $u = Uninstall-Package -ProviderName NuGet -Name $packageName $u.Name | Should -Contain "$packageName" } diff --git a/test/tools/Modules/PSSysLog/PSSysLog.psm1 b/test/tools/Modules/PSSysLog/PSSysLog.psm1 index 634e0903109..7289a1b8406 100644 --- a/test/tools/Modules/PSSysLog/PSSysLog.psm1 +++ b/test/tools/Modules/PSSysLog/PSSysLog.psm1 @@ -182,6 +182,7 @@ class PSLogItem [string] $EventId = [string]::Empty [string] $Message = [string]::Empty [int] $Count = 1 + [System.Collections.Generic.List[String]]$ParseErrors = [System.Collections.Generic.List[string]]::new() hidden static $monthNames = @('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun','Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec') @@ -316,7 +317,7 @@ class PSLogItem } else { - Write-Warning -Message "Could not split EventId $($item.EventId) on '[] ' Count:$($subparts.Count) -> $content" + $item.ParseErrors.Add("Could not split EventId $($item.EventId) on '[] ' Count:$($subparts.Count) -> $content") } # (commitid:TID:ChannelID) @@ -331,7 +332,7 @@ class PSLogItem } else { - Write-Warning -Message "Could not split CommitId $($item.CommitId) on '(): ' Count:$($subparts.Count) -> $content" + $item.ParseErrors.Add("Could not split CommitId $($item.CommitId) on '(): ' Count:$($subparts.Count) -> $content") } # nameid[PID] @@ -345,7 +346,7 @@ class PSLogItem } else { - Write-Warning -Message "Could not split LogId $($item.LogId) on '[]:' Count:$($subparts.Count) -> $content" + $item.ParseErrors.Add("Could not split LogId $($item.LogId) on '[]:' Count:$($subparts.Count) -> $content") } return $item @@ -465,7 +466,7 @@ class PSLogItem } else { - Write-Warning -Message "Could not split CommitId $($item.CommitId) on '(): ' Count:$($subparts.Count)" + $item.ParseErrors.Add("Could not split CommitId $($item.CommitId) on '(): ' Count:$($subparts.Count)") } # [EventId] @@ -478,7 +479,7 @@ class PSLogItem } else { - Write-Warning -Message "Could not split EventId $($item.EventId) on '[] ' Count:$($subparts.Count)" + $item.ParseErrors.Add("Could not split EventId $($item.EventId) on '[] ' Count:$($subparts.Count)") } $result = $item From 0f53e8033588fcad14af69d2c665fdbb73b5be5d Mon Sep 17 00:00:00 2001 From: Berkan Diler Date: Tue, 13 Jun 2023 02:31:04 +0200 Subject: [PATCH 586/779] Make use of the new `Random.Shared` property (#18417) --- .../commands/management/Computer.cs | 2 +- .../engine/hostifaces/MshHostUserInterface.cs | 2 +- .../engine/runtime/CompiledScriptBlock.cs | 2 +- .../help/UpdatableHelpCommandBase.cs | 4 +--- 4 files changed, 4 insertions(+), 6 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs index 126596818af..e24c49b63f7 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs @@ -797,7 +797,7 @@ protected override void BeginProcessing() if (Wait) { - _activityId = (new Random()).Next(); + _activityId = Random.Shared.Next(); if (_timeout == -1 || _timeout >= int.MaxValue / 1000) { _timeoutInMilliseconds = int.MaxValue; diff --git a/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs index 3e4c082e101..ddc6fce782d 100644 --- a/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs @@ -892,7 +892,7 @@ private void FlushPendingOutput() { // System transcripts can have high contention. Do exponential back-off on writing // if needed. - int delay = new Random().Next(10) + 1; + int delay = Random.Shared.Next(10) + 1; bool written = false; while (!written) diff --git a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs index 3088667f6b2..dc4850b9208 100644 --- a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs +++ b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs @@ -1466,7 +1466,7 @@ internal static void LogScriptBlockCreation(ScriptBlock scriptBlock, bool force) // But split the segments into random sizes (10k + between 0 and 10kb extra) // so that attackers can't creatively force their scripts to span well-known // segments (making simple rules less reliable). - int segmentSize = 10000 + (new Random()).Next(10000); + int segmentSize = 10000 + Random.Shared.Next(10000); int segments = (int)Math.Floor((double)(scriptBlockText.Length / segmentSize)) + 1; int currentLocation = 0; int currentSegmentSize = 0; diff --git a/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs b/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs index 48e44bd3013..21d0609a353 100644 --- a/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs +++ b/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs @@ -210,9 +210,7 @@ internal UpdatableHelpCommandBase(UpdatableHelpCommandType commandType) _exceptions = new Dictionary(); _helpSystem.OnProgressChanged += HandleProgressChanged; - Random rand = new Random(); - - activityId = rand.Next(); + activityId = Random.Shared.Next(); } #endregion From 9a358f26f0dd80044513ed2651fff0311f301fcf Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 13 Jun 2023 14:50:41 +0500 Subject: [PATCH 587/779] Bump JsonSchema.Net from 4.1.3 to 4.1.5 (#19790) Bumps [JsonSchema.Net](https://github.com/gregsdennis/json-everything) from 4.1.3 to 4.1.5. - [Commits](https://github.com/gregsdennis/json-everything/commits) --- updated-dependencies: - dependency-name: JsonSchema.Net dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .../Microsoft.PowerShell.Commands.Utility.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj index ca841d9beb7..403df5d5cb8 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj +++ b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj @@ -35,7 +35,7 @@ - + From 00ce2a47dc704a5aa27316032322e0e41cc6c03a Mon Sep 17 00:00:00 2001 From: PowerShell Team Bot <69177312+pwshBot@users.noreply.github.com> Date: Tue, 13 Jun 2023 10:41:35 -0700 Subject: [PATCH 588/779] Update the cgmanifest (#19792) --- tools/cgmanifest.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/cgmanifest.json b/tools/cgmanifest.json index 6b60dd4e0e8..f92d6cd2084 100644 --- a/tools/cgmanifest.json +++ b/tools/cgmanifest.json @@ -56,7 +56,7 @@ "Type": "nuget", "Nuget": { "Name": "JsonSchema.Net", - "Version": "4.1.2" + "Version": "4.1.5" } }, "DevelopmentDependency": false From 71c123cd53d1cde539888403c5dd93fd3af713b3 Mon Sep 17 00:00:00 2001 From: PowerShell Team Bot <69177312+pwshBot@users.noreply.github.com> Date: Wed, 14 Jun 2023 10:06:58 -0700 Subject: [PATCH 589/779] Update the cgmanifest (#19800) --- tools/cgmanifest.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/tools/cgmanifest.json b/tools/cgmanifest.json index f92d6cd2084..50b091be068 100644 --- a/tools/cgmanifest.json +++ b/tools/cgmanifest.json @@ -226,7 +226,7 @@ "Type": "nuget", "Nuget": { "Name": "Microsoft.Windows.Compatibility", - "Version": "7.0.1" + "Version": "7.0.3" } }, "DevelopmentDependency": false @@ -486,7 +486,7 @@ "Type": "nuget", "Nuget": { "Name": "System.DirectoryServices.Protocols", - "Version": "7.0.0" + "Version": "7.0.1" } }, "DevelopmentDependency": false @@ -546,7 +546,7 @@ "Type": "nuget", "Nuget": { "Name": "System.Management", - "Version": "7.0.1" + "Version": "7.0.2" } }, "DevelopmentDependency": false @@ -646,7 +646,7 @@ "Type": "nuget", "Nuget": { "Name": "System.Security.Cryptography.Pkcs", - "Version": "7.0.1" + "Version": "7.0.2" } }, "DevelopmentDependency": false @@ -756,7 +756,7 @@ "Type": "nuget", "Nuget": { "Name": "System.ServiceProcess.ServiceController", - "Version": "7.0.0" + "Version": "7.0.1" } }, "DevelopmentDependency": false From c43beccaa2f0d6295aac1e977f56f5bd50c73f3e Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Fri, 16 Jun 2023 16:16:34 -0700 Subject: [PATCH 590/779] Add reference to PSResourceGet (#19597) --- src/Modules/PSGalleryModules.csproj | 1 + ...crosoft.PowerShell.PSResourceGet.Tests.ps1 | 215 ++++++++++++++++++ .../PowerShellGet/PowerShellGet.Tests.ps1 | 7 +- tools/packaging/boms/linux.json | 28 +++ tools/packaging/boms/mac.json | 28 +++ tools/packaging/boms/windows.json | 32 +++ 6 files changed, 305 insertions(+), 6 deletions(-) create mode 100644 test/powershell/Modules/Microsoft.PowerShell.PSResourceGet/Microsoft.PowerShell.PSResourceGet.Tests.ps1 diff --git a/src/Modules/PSGalleryModules.csproj b/src/Modules/PSGalleryModules.csproj index 82a9db7e533..ae56290cfb3 100644 --- a/src/Modules/PSGalleryModules.csproj +++ b/src/Modules/PSGalleryModules.csproj @@ -13,6 +13,7 @@ + diff --git a/test/powershell/Modules/Microsoft.PowerShell.PSResourceGet/Microsoft.PowerShell.PSResourceGet.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.PSResourceGet/Microsoft.PowerShell.PSResourceGet.Tests.ps1 new file mode 100644 index 00000000000..9a6a7715786 --- /dev/null +++ b/test/powershell/Modules/Microsoft.PowerShell.PSResourceGet/Microsoft.PowerShell.PSResourceGet.Tests.ps1 @@ -0,0 +1,215 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +# no progress output during these tests +$ProgressPreference = "SilentlyContinue" + +$RepositoryName = 'PSGallery' +$TestModule = 'newTestModule' +$TestScript = 'TestTestScript' +$Initialized = $false + +#region Install locations for modules and scripts + +if($IsWindows) { + $script:ProgramFilesPSPath = Microsoft.PowerShell.Management\Join-Path -Path $env:ProgramFiles -ChildPath 'PowerShell' +} +else { + $script:ProgramFilesPSPath = Split-Path -Path ([System.Management.Automation.Platform]::SelectProductNameForDirectory('SHARED_MODULES')) -Parent +} + +try +{ + $script:MyDocumentsFolderPath = [Environment]::GetFolderPath("MyDocuments") +} +catch +{ + $script:MyDocumentsFolderPath = $null +} + + +if($IsWindows) +{ + $script:MyDocumentsPSPath = if($script:MyDocumentsFolderPath) + { + Microsoft.PowerShell.Management\Join-Path -Path $script:MyDocumentsFolderPath -ChildPath 'PowerShell' + } + else + { + Microsoft.PowerShell.Management\Join-Path -Path $HOME -ChildPath "Documents\PowerShell" + } +} +else +{ + $script:MyDocumentsPSPath = Split-Path -Path ([System.Management.Automation.Platform]::SelectProductNameForDirectory('USER_MODULES')) -Parent +} + + +$script:ProgramFilesModulesPath = Microsoft.PowerShell.Management\Join-Path -Path $script:ProgramFilesPSPath -ChildPath 'Modules' +$script:MyDocumentsModulesPath = Microsoft.PowerShell.Management\Join-Path -Path $script:MyDocumentsPSPath -ChildPath 'Modules' + +$script:ProgramFilesScriptsPath = Microsoft.PowerShell.Management\Join-Path -Path $script:ProgramFilesPSPath -ChildPath 'Scripts' +$script:MyDocumentsScriptsPath = Microsoft.PowerShell.Management\Join-Path -Path $script:MyDocumentsPSPath -ChildPath 'Scripts' + +$script:ProgramFilesScriptsInfoPath = Microsoft.PowerShell.Management\Join-Path -Path $script:ProgramFilesScriptsPath -ChildPath 'InstalledScriptInfos' +$script:MyDocumentsScriptsInfoPath = Microsoft.PowerShell.Management\Join-Path -Path $script:MyDocumentsScriptsPath -ChildPath 'InstalledScriptInfos' + +if (!(Test-Path $script:ProgramFilesScriptsInfoPath)) { + New-Item -Path $script:ProgramFilesScriptsInfoPath -ItemType Directory +} + +if (!(Test-Path $script:MyDocumentsScriptsPath)) { + New-Item -Path $script:MyDocumentsScriptsInfoPath -ItemType Directory +} + +#endregion + +#region Register a test repository + +function Initialize +{ + $repo = Get-PSResourceRepository $RepositoryName -ErrorAction SilentlyContinue + if($repo) + { + Set-PSResourceRepository -Name $repo.Name -Trusted + } + else + { + Register-PSResourceRepository -PSGallery -Trusted + } +} + +#endregion + +function Remove-InstalledModules +{ + Get-InstalledPSResource -Name $TestModule -Version '*' -ErrorAction SilentlyContinue | Microsoft.PowerShell.PSResourceGet\Uninstall-PSResource +} + +Describe "PSResourceGet - Module tests" -tags "Feature" { + + BeforeAll { + if ($script:Initialized -eq $false) { + Initialize + $script:Initialized = $true + } + } + + BeforeEach { + Remove-InstalledModules + } + + It "Should find a module correctly" { + $psgetModuleInfo = Find-PSResource -Name $TestModule -Repository $RepositoryName + $psgetModuleInfo.Name | Should -Be $TestModule + $psgetModuleInfo.Repository | Should -Be $RepositoryName + } + + It "Should install a module correctly to the required location with default CurrentUser scope" { + Install-PSResource -Name $TestModule -Repository $RepositoryName + $installedModuleInfo = Get-InstalledPSResource -Name $TestModule + + if (!$IsMacOS) { + $installedModuleInfo | Should -Not -BeNullOrEmpty + $installedModuleInfo.Name | Should -Be $TestModule + $installedModuleInfo.InstalledLocation.StartsWith($script:MyDocumentsModulesPath, [System.StringComparison]::OrdinalIgnoreCase) | Should -BeTrue + + $module = Get-Module $TestModule -ListAvailable + $module.Name | Should -Be $TestModule + $module.ModuleBase.StartsWith($script:MyDocumentsModulesPath, [System.StringComparison]::OrdinalIgnoreCase) | Should -BeTrue + } + } + + AfterAll { + Remove-InstalledModules + } +} + +Describe "PSResourceGet - Module tests (Admin)" -Tags @('Feature', 'RequireAdminOnWindows', 'RequireSudoOnUnix') { + + BeforeAll { + if ($script:Initialized -eq $false) { + Initialize + $script:Initialized = $true + } + } + + BeforeEach { + Remove-InstalledModules + } + + It "Should install a module correctly to the required location with AllUsers scope" { + Install-PSResource -Name $TestModule -Repository $RepositoryName -Scope AllUsers + + $module = Get-Module $TestModule -ListAvailable + $module.Name | Should -Be $TestModule + $module.ModuleBase.StartsWith($script:programFilesModulesPath, [System.StringComparison]::OrdinalIgnoreCase) | Should -BeTrue + } + + AfterAll { + Remove-InstalledModules + } +} + +function Remove-InstalledScripts +{ + Get-InstalledPSResource -Name $TestScript -ErrorAction SilentlyContinue | Uninstall-PSResource +} + +Describe "PSResourceGet - Script tests" -tags "Feature" { + + BeforeAll { + if ($script:Initialized -eq $false) { + Initialize + $script:Initialized = $true + } + } + + BeforeEach { + Remove-InstalledScripts + } + + It "Should find a script correctly" { + $psgetScriptInfo = Find-PSResource -Name $TestScript -Repository $RepositoryName + $psgetScriptInfo.Name | Should -Be $TestScript + $psgetScriptInfo.Repository | Should -Be $RepositoryName + } + + It "Should install a script correctly to the required location with default CurrentUser scope" { + Install-PSResource -Name $TestScript -Repository $RepositoryName -Verbose + $installedScriptInfo = Get-InstalledPSResource -Name $TestScript + + if (!$IsMacOS) + { + $installedScriptInfo | Should -Not -BeNullOrEmpty + $installedScriptInfo.Name | Should -Be $TestScript + $installedScriptInfo.InstalledLocation.StartsWith($script:MyDocumentsScriptsPath, [System.StringComparison]::OrdinalIgnoreCase) | Should -BeTrue + } + } + + AfterAll { + Remove-InstalledScripts + } +} + +Describe "PSResourceGet - Script tests (Admin)" -Tags @('Feature', 'RequireAdminOnWindows', 'RequireSudoOnUnix') { + + BeforeAll { + if ($script:Initialized -eq $false) { + Initialize + $script:Initialized = $true + } + } + + BeforeEach { + Remove-InstalledScripts + } + + It "Should install a script correctly to the required location with AllUsers scope" { + Install-PSResource -Name $TestScript -Repository $RepositoryName -Scope AllUsers + } + + AfterAll { + Remove-InstalledScripts + } +} diff --git a/test/powershell/Modules/PowerShellGet/PowerShellGet.Tests.ps1 b/test/powershell/Modules/PowerShellGet/PowerShellGet.Tests.ps1 index 1186c0f9601..ef9eec8a0c2 100644 --- a/test/powershell/Modules/PowerShellGet/PowerShellGet.Tests.ps1 +++ b/test/powershell/Modules/PowerShellGet/PowerShellGet.Tests.ps1 @@ -159,15 +159,10 @@ Describe "PowerShellGet - Module tests (Admin)" -Tags @('Feature', 'RequireAdmin It "Should install a module correctly to the required location with AllUsers scope" { Install-Module -Name $TestModule -Repository $RepositoryName -Scope AllUsers - $installedModuleInfo = Get-InstalledModule -Name $TestModule - - $installedModuleInfo | Should -Not -BeNullOrEmpty - $installedModuleInfo.Name | Should -Be $TestModule - $installedModuleInfo.InstalledLocation.StartsWith($script:programFilesModulesPath, [System.StringComparison]::OrdinalIgnoreCase) | Should -BeTrue $module = Get-Module $TestModule -ListAvailable $module.Name | Should -Be $TestModule - $module.ModuleBase | Should -Be $installedModuleInfo.InstalledLocation + $module.ModuleBase.StartsWith($script:programFilesModulesPath, [System.StringComparison]::OrdinalIgnoreCase) | Should -BeTrue } AfterAll { diff --git a/tools/packaging/boms/linux.json b/tools/packaging/boms/linux.json index f735ea5cf1c..9f5f886a4ca 100644 --- a/tools/packaging/boms/linux.json +++ b/tools/packaging/boms/linux.json @@ -467,6 +467,34 @@ "Pattern": "Modules/PSReadLine/*.txt", "FileType": "NonProduct" }, + { + "Pattern": "Modules/PSResourceGet/*.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/PSResourceGet/*.ps?1", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/PSResourceGet/*.ps1xml", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/PSResourceGet/LICENSE", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/PSResourceGet/Notice.txt", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/PSResourceGet/_manifest/spdx_2.2/*.json*", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/PSResourceGet/_manifest/spdx_2.2/*.cat", + "FileType": "NonProduct" + }, { "Pattern": "Modules/ThreadJob/*.dll", "FileType": "NonProduct" diff --git a/tools/packaging/boms/mac.json b/tools/packaging/boms/mac.json index 29f2bb8532a..a4b5bc2bffb 100644 --- a/tools/packaging/boms/mac.json +++ b/tools/packaging/boms/mac.json @@ -347,6 +347,34 @@ "Pattern": "Modules/PSReadLine/*.txt", "FileType": "NonProduct" }, + { + "Pattern": "Modules/PSResourceGet/*.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/PSResourceGet/*.ps?1", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/PSResourceGet/*.ps1xml", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/PSResourceGet/LICENSE", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/PSResourceGet/Notice.txt", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/PSResourceGet/_manifest/spdx_2.2/*.json*", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/PSResourceGet/_manifest/spdx_2.2/*.cat", + "FileType": "NonProduct" + }, { "Pattern": "Modules/ThreadJob/*.dll", "FileType": "NonProduct" diff --git a/tools/packaging/boms/windows.json b/tools/packaging/boms/windows.json index 308342e8f10..39c0679891f 100644 --- a/tools/packaging/boms/windows.json +++ b/tools/packaging/boms/windows.json @@ -875,6 +875,38 @@ "Pattern": "Modules/ThreadJob/*.psd1", "FileType": "NonProduct" }, + { + "Pattern": "Modules/Microsoft.PowerShell.PSResourceGet/_manifest/spdx_2.2/manifest.cat", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/Microsoft.PowerShell.PSResourceGet/LICENSE", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/Microsoft.PowerShell.PSResourceGet/Notice.txt", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/Microsoft.PowerShell.PSResourceGet/dependencies/*.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/Microsoft.PowerShell.PSResourceGet/Microsoft.PowerShell.PSResourceGet.dll", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/Microsoft.PowerShell.PSResourceGet/Microsoft.PowerShell.PSResourceGet.psd1", + "FileType": "NonProduct" + }, + { + "Pattern": "Modules/Microsoft.PowerShell.PSResourceGet/PSGet.Format.ps1xml", + "FileType": "NonProduct" + }, + { + "Pattern": "mscordaccore_*.dll", + "FileType": "NonProduct" + }, { "Pattern": "mscordaccore_*.dll", "FileType": "NonProduct" From e3b4f379daa6af813b835b4f99e2b62ad247fc5d Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Mon, 19 Jun 2023 09:19:56 -0700 Subject: [PATCH 591/779] Update `working-group-definitions.md` (#19809) --- docs/community/working-group-definitions.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/docs/community/working-group-definitions.md b/docs/community/working-group-definitions.md index d13d5a4910d..1b03901d460 100644 --- a/docs/community/working-group-definitions.md +++ b/docs/community/working-group-definitions.md @@ -147,8 +147,6 @@ These modules include: * @SteveL-MSFT * @jdhitsolutions * @TobiasPSP -* @doctordns -* @jhoneill ## Security From 48d245628b7ae0547c546af0c4974fa1de74d74b Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Mon, 19 Jun 2023 09:21:25 -0700 Subject: [PATCH 592/779] Update `CONTRIBUTING.md` to include Code of Conduct enforcement (#19810) --- .github/CONTRIBUTING.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index 04346dd9abb..ce87c469d22 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -381,6 +381,14 @@ When your pull request is created, it is checked by the CLA bot. If you have signed the CLA, the status check will be set to `passing`. Otherwise, it will stay at `pending`. Once you sign a CLA, all your existing and future pull requests will have the status check automatically set at `passing`. +## Code of Conduct Enforcement + +Reports of abuse will be reviewed by the PS-Committee and if it has been determined that violations of the +Code of Conduct has occurred, then a temporary ban may be imposed. +The duration of the temporary ban will depend on the impact and/or severity of the infraction. +This can vary from 1 day, a few days, a week, and up to 30 days. +Repeat offenses may result in a permanent ban from the PowerShell org. + [testing-guidelines]: ../docs/testing-guidelines/testing-guidelines.md [running-tests-outside-of-ci]: ../docs/testing-guidelines/testing-guidelines.md#running-tests-outside-of-ci [issue-management]: ../docs/maintainers/issue-management.md From f86bf28554e80c2c2547aa231ca225ee964bf13a Mon Sep 17 00:00:00 2001 From: PowerShell Team Bot <69177312+pwshBot@users.noreply.github.com> Date: Mon, 19 Jun 2023 09:21:57 -0700 Subject: [PATCH 593/779] Update to the latest NOTICES file (#19820) --- ThirdPartyNotices.txt | 35 ++++++++++------------------------- 1 file changed, 10 insertions(+), 25 deletions(-) diff --git a/ThirdPartyNotices.txt b/ThirdPartyNotices.txt index 52fa655072a..c68f35d92fe 100644 --- a/ThirdPartyNotices.txt +++ b/ThirdPartyNotices.txt @@ -238,34 +238,19 @@ SOFTWARE. --------------------------------------------------------- -JsonSchema.Net 4.1.2 - MIT +JsonSchema.Net 4.1.5 - MIT -(c) Microsoft 2023 -Copyright (c) 2022 Greg Dennis MIT License -Copyright (c) 2022 Greg Dennis - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: +Copyright (c) -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --------------------------------------------------------- @@ -711,7 +696,7 @@ SOFTWARE. --------------------------------------------------------- -Microsoft.Windows.Compatibility 7.0.1 - MIT +Microsoft.Windows.Compatibility 7.0.3 - MIT (c) Microsoft Corporation @@ -2390,7 +2375,7 @@ SOFTWARE. --------------------------------------------------------- -System.DirectoryServices.Protocols 7.0.0 - MIT +System.DirectoryServices.Protocols 7.0.1 - MIT (c) Microsoft Corporation @@ -2795,7 +2780,7 @@ SOFTWARE. --------------------------------------------------------- -System.Management 7.0.1 - MIT +System.Management 7.0.2 - MIT (c) Microsoft Corporation @@ -3476,7 +3461,7 @@ SOFTWARE. --------------------------------------------------------- -System.Security.Cryptography.Pkcs 7.0.1 - MIT +System.Security.Cryptography.Pkcs 7.0.2 - MIT (c) Microsoft Corporation @@ -4130,7 +4115,7 @@ SOFTWARE. --------------------------------------------------------- -System.ServiceProcess.ServiceController 7.0.0 - MIT +System.ServiceProcess.ServiceController 7.0.1 - MIT (c) Microsoft Corporation From 8b2de76eff43e2a0861bcde9296e84c7173c0f98 Mon Sep 17 00:00:00 2001 From: MartinGC94 <42123497+MartinGC94@users.noreply.github.com> Date: Mon, 19 Jun 2023 19:20:13 +0200 Subject: [PATCH 594/779] Fix completion of the foreach-statement variable (#19814) --- .../engine/CommandCompletion/CompletionCompleters.cs | 11 +++++++++++ .../Host/TabCompletion/TabCompletion.Tests.ps1 | 5 +++++ 2 files changed, 16 insertions(+) diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs index 8dae46f3395..1d69925f4ea 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs @@ -5592,6 +5592,17 @@ public override AstVisitAction VisitParameter(ParameterAst parameterAst) return AstVisitAction.Continue; } + public override AstVisitAction VisitForEachStatement(ForEachStatementAst forEachStatementAst) + { + if (forEachStatementAst.Extent.StartOffset > StopSearchOffset || forEachStatementAst.Variable == CompletionVariableAst) + { + return AstVisitAction.StopVisit; + } + + SaveVariableInfo(forEachStatementAst.Variable.VariablePath.UserPath, variableType: null, isConstraint: false); + return AstVisitAction.Continue; + } + public override AstVisitAction VisitAttribute(AttributeAst attributeAst) { // Attributes can't assign values to variables so they aren't interesting. diff --git a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 index a9cc9801d0e..2981f583ebb 100644 --- a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 +++ b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 @@ -74,6 +74,11 @@ Describe "TabCompletion" -Tags CI { $res.CompletionMatches[0].CompletionText | Should -BeExactly 'pscustomobject' } + It 'Should complete foreach variable' { + $res = TabExpansion2 -inputScript 'foreach ($CurrentItem in 1..10){$CurrentIt' + $res.CompletionMatches[0].CompletionText | Should -BeExactly '$CurrentItem' + } + foreach ($Operator in [System.Management.Automation.CompletionCompleters]::CompleteOperator("")) { It "Should complete $($Operator.CompletionText)" { From 133acc19619a739ee4af9a4d1a8ed06f229cc3e1 Mon Sep 17 00:00:00 2001 From: "James Truher [MSFT]" Date: Mon, 19 Jun 2023 10:26:38 -0700 Subject: [PATCH 595/779] Fix logic for `Import-CliXml` test (#19805) --- .../XMLCommand.Tests.ps1 | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/XMLCommand.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/XMLCommand.Tests.ps1 index ea631d7f6f9..53e4fbf8d7d 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/XMLCommand.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/XMLCommand.Tests.ps1 @@ -244,11 +244,15 @@ Describe "XmlCommand DRT basic functionality Tests" -Tags "CI" { } It "Import-Clixml StopProcessing should succeed" { - 1,2,3 | Export-Clixml -Path $testfile + # create a file to use for import. It should have some complexity + Get-Process -Id $PID | Export-Clixml -Path $testfile + # create a large number of files to import + $script = '$f = ,"' + $testfile + '" * 1000' $ps = [PowerShell]::Create() - $ps.AddCommand("Get-Process") - $ps.AddCommand("Import-CliXml") - $ps.AddParameter("Path", $testfile) + $ps.AddScript($script) + $ps.Invoke() + $ps.Commands.Clear() + $ps.AddScript('$null = Import-CliXml -Path $f') $ps.BeginInvoke() $ps.Stop() $ps.InvocationStateInfo.State | Should -Be "Stopped" From 2403e78b1e663f90843df6019d272c8bfc8c0f47 Mon Sep 17 00:00:00 2001 From: Armaan Mcleod Date: Tue, 20 Jun 2023 03:46:08 +1000 Subject: [PATCH 596/779] Rename file from `PingPathCommand.cs` to `TestPathCommand.cs` (#19782) --- .../management/{PingPathCommand.cs => TestPathCommand.cs} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename src/Microsoft.PowerShell.Commands.Management/commands/management/{PingPathCommand.cs => TestPathCommand.cs} (100%) diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/PingPathCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/TestPathCommand.cs similarity index 100% rename from src/Microsoft.PowerShell.Commands.Management/commands/management/PingPathCommand.cs rename to src/Microsoft.PowerShell.Commands.Management/commands/management/TestPathCommand.cs From b9b5136f0e195627a3b755ff76f8bd0b6690b20c Mon Sep 17 00:00:00 2001 From: "James Truher [MSFT]" Date: Mon, 19 Jun 2023 11:26:14 -0700 Subject: [PATCH 597/779] Avoid checking screen scraping on non-Windows platforms before launching native app (#19812) --- .../engine/NativeCommandProcessor.cs | 4 +++ .../NativeCommandProcessor.Tests.ps1 | 25 +++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/src/System.Management.Automation/engine/NativeCommandProcessor.cs b/src/System.Management.Automation/engine/NativeCommandProcessor.cs index 2168365c747..a5cc7874a6b 100644 --- a/src/System.Management.Automation/engine/NativeCommandProcessor.cs +++ b/src/System.Management.Automation/engine/NativeCommandProcessor.cs @@ -1693,6 +1693,9 @@ private void CalculateIORedirection(bool isWindowsApplication, out bool redirect { if (s_supportScreenScrape == null) { +#if UNIX + s_supportScreenScrape = false; +#else try { _startPosition = this.Command.Context.EngineHostInterface.UI.RawUI.CursorPosition; @@ -1704,6 +1707,7 @@ private void CalculateIORedirection(bool isWindowsApplication, out bool redirect { s_supportScreenScrape = false; } +#endif } // if screen scraping isn't supported, we enable redirection so that the output is still transcribed diff --git a/test/powershell/Language/Scripting/NativeExecution/NativeCommandProcessor.Tests.ps1 b/test/powershell/Language/Scripting/NativeExecution/NativeCommandProcessor.Tests.ps1 index 41e3f3cebcf..9542aafe368 100644 --- a/test/powershell/Language/Scripting/NativeExecution/NativeCommandProcessor.Tests.ps1 +++ b/test/powershell/Language/Scripting/NativeExecution/NativeCommandProcessor.Tests.ps1 @@ -366,3 +366,28 @@ Describe "Run native command from a mounted FAT-format VHD" -tags @("Feature", " $result | Should -BeExactly $expected } } + +Describe "Native application invocation and getting cursor position" -Tags 'CI' { + It "Invoking a native application should not collect the cursor position" -Skip:($IsWindows) { + $expectCmd = Get-Command expect -Type Application -ErrorAction Ignore + $dateCmd = Get-Command date -Type Application -ErrorAction Ignore + # if date or expect are missing mark the test as pending + # test setup will need to ensure that these programs are present. + $missing = @() + if ($null -eq $expectCmd) { + $missing += "expect" + } + if ($null -eq $dateCmd) { + $missing += "date" + } + if ($missing.count -ne 0) { + $message = "missing command(s) {0}" -f ($missing -join ", ") + Set-ItResult -Pending -Because $message + } + + $powershell = Join-Path -Path $PSHOME -ChildPath "pwsh" + $commandString = "spawn $powershell -nopro -c /bin/date; expect eof" + [string]$result = expect -c $commandString + $result.IndexOf("`e[6n") | Should -Be -1 -Because $result.replace("`e","``e").replace("`u{7}","") + } +} From 0cbcf7b4d6583cc2f976c93c038e3fc9e1ed1561 Mon Sep 17 00:00:00 2001 From: MartinGC94 <42123497+MartinGC94@users.noreply.github.com> Date: Mon, 19 Jun 2023 22:30:39 +0200 Subject: [PATCH 598/779] Enable completion of variables across ScriptBlock scopes (#19819) --- .../CommandCompletion/CompletionCompleters.cs | 43 ++++++++++++++++--- .../TabCompletion/TabCompletion.Tests.ps1 | 15 +++++++ 2 files changed, 53 insertions(+), 5 deletions(-) diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs index 1d69925f4ea..9dec8bcb3a5 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs @@ -5375,6 +5375,20 @@ private static void AddUniqueVariable(HashSet hashedResults, List s_localScopeCommandNames = new(StringComparer.OrdinalIgnoreCase) + { + "Microsoft.PowerShell.Core\\ForEach-Object", + "ForEach-Object", + "foreach", + "%", + "Microsoft.PowerShell.Core\\Where-Object", + "Where-Object", + "where", + "?", + "BeforeAll", + "BeforeEach" + }; + private sealed class VariableInfo { internal Type LastDeclaredConstraint; @@ -5616,12 +5630,31 @@ public override AstVisitAction VisitFunctionDefinition(FunctionDefinitionAst fun public override AstVisitAction VisitScriptBlockExpression(ScriptBlockExpressionAst scriptBlockExpressionAst) { - return scriptBlockExpressionAst != Top ? AstVisitAction.SkipChildren : AstVisitAction.Continue; - } + if (scriptBlockExpressionAst == Top) + { + return AstVisitAction.Continue; + } - public override AstVisitAction VisitScriptBlock(ScriptBlockAst scriptBlockAst) - { - return scriptBlockAst != Top ? AstVisitAction.SkipChildren : AstVisitAction.Continue; + Ast parent = scriptBlockExpressionAst.Parent; + // This loop checks if the scriptblock is used as a command, or an argument for a command, eg: ForEach-Object -Process {$Var1 = "Hello"}, {Var2 = $true} + while (true) + { + if (parent is CommandAst cmdAst) + { + string cmdName = cmdAst.GetCommandName(); + return s_localScopeCommandNames.Contains(cmdName) + || (cmdAst.CommandElements[0] is ScriptBlockExpressionAst && cmdAst.InvocationOperator == TokenKind.Dot) + ? AstVisitAction.Continue + : AstVisitAction.SkipChildren; + } + + if (parent is not CommandExpressionAst and not PipelineAst and not StatementBlockAst and not ArrayExpressionAst and not ArrayLiteralAst) + { + return AstVisitAction.SkipChildren; + } + + parent = parent.Parent; + } } } diff --git a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 index 2981f583ebb..41131001000 100644 --- a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 +++ b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 @@ -274,6 +274,21 @@ switch ($x) $completionText -join ' ' | Should -BeExactly 'Ascending Descending Expression' } + It 'Should complete variable assigned in other scriptblock' { + $res = TabExpansion2 -inputScript 'ForEach-Object -Begin {$Test1 = "Hello"} -Process {$Test' + $res.CompletionMatches[0].CompletionText | Should -Be '$Test1' + } + + It 'Should complete variable assigned in an array of scriptblocks' { + $res = TabExpansion2 -inputScript 'ForEach-Object -Process @({"Block1"},{$Test1="Hello"});$Test' + $res.CompletionMatches[0].CompletionText | Should -Be '$Test1' + } + + It 'Should not complete variable assigned in an ampersand executed scriptblock' { + $res = TabExpansion2 -inputScript '& {$AmpeersandVarCompletionTest = "Hello"};$AmpeersandVarCompletionTes' + $res.CompletionMatches.Count | Should -Be 0 + } + context TypeConstructionWithHashtable { BeforeAll { class RandomTestType { From d614858550bc8fadda047bc706798121ddf099ea Mon Sep 17 00:00:00 2001 From: stevenebutler Date: Tue, 20 Jun 2023 08:07:16 +1000 Subject: [PATCH 599/779] WebCmdlets: Rename `-TimeoutSec` to `-ConnectionTimeoutSeconds` (with alias) and add `-OperationTimeoutSeconds` (#19558) --- .../BasicHtmlWebResponseObject.Common.cs | 9 +- .../Common/InvokeRestMethodCommand.Common.cs | 16 +- .../Common/WebRequestPSCmdlet.Common.cs | 63 ++++++- .../Common/WebResponseObject.Common.cs | 18 +- .../InvokeWebRequestCommand.CoreClr.cs | 8 +- .../utility/WebCmdlet/StreamHelper.cs | 175 +++++++++++++----- .../utility/WebCmdlet/WebRequestSession.cs | 6 +- .../WebCmdlets.Tests.ps1 | 120 +++++++++++- .../Controllers/DelayController.cs | 59 ++++-- 9 files changed, 374 insertions(+), 100 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/BasicHtmlWebResponseObject.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/BasicHtmlWebResponseObject.Common.cs index 75775428bc9..9bd76f99413 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/BasicHtmlWebResponseObject.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/BasicHtmlWebResponseObject.Common.cs @@ -3,6 +3,7 @@ #nullable enable +using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; @@ -26,8 +27,9 @@ public class BasicHtmlWebResponseObject : WebResponseObject /// Initializes a new instance of the class. /// /// The response. + /// Time permitted between reads or Timeout.InfiniteTimeSpan for no timeout. /// Cancellation token. - public BasicHtmlWebResponseObject(HttpResponseMessage response, CancellationToken cancellationToken) : this(response, null, cancellationToken) { } + public BasicHtmlWebResponseObject(HttpResponseMessage response, TimeSpan perReadTimeout, CancellationToken cancellationToken) : this(response, null, perReadTimeout, cancellationToken) { } /// /// Initializes a new instance of the class @@ -35,8 +37,9 @@ public BasicHtmlWebResponseObject(HttpResponseMessage response, CancellationToke /// /// The response. /// The content stream associated with the response. + /// Time permitted between reads or Timeout.InfiniteTimeSpan for no timeout. /// Cancellation token. - public BasicHtmlWebResponseObject(HttpResponseMessage response, Stream? contentStream, CancellationToken cancellationToken) : base(response, contentStream, cancellationToken) + public BasicHtmlWebResponseObject(HttpResponseMessage response, Stream? contentStream, TimeSpan perReadTimeout, CancellationToken cancellationToken) : base(response, contentStream, perReadTimeout, cancellationToken) { InitializeContent(cancellationToken); InitializeRawContent(response); @@ -157,7 +160,7 @@ protected void InitializeContent(CancellationToken cancellationToken) // Fill the Content buffer string? characterSet = WebResponseHelper.GetCharacterSet(BaseResponse); - Content = StreamHelper.DecodeStream(RawContentStream, characterSet, out Encoding encoding, cancellationToken); + Content = StreamHelper.DecodeStream(RawContentStream, characterSet, out Encoding encoding, perReadTimeout, cancellationToken); Encoding = encoding; } else diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs index df1ef750529..ca78ff370b2 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs @@ -80,11 +80,12 @@ internal override void ProcessResponse(HttpResponseMessage response) ArgumentNullException.ThrowIfNull(response); ArgumentNullException.ThrowIfNull(_cancelToken); + TimeSpan perReadTimeout = ConvertTimeoutSecondsToTimeSpan(OperationTimeoutSeconds); Stream baseResponseStream = StreamHelper.GetResponseStream(response, _cancelToken.Token); if (ShouldWriteToPipeline) { - using BufferingStreamReader responseStream = new(baseResponseStream, _cancelToken.Token); + using BufferingStreamReader responseStream = new(baseResponseStream, perReadTimeout, _cancelToken.Token); // First see if it is an RSS / ATOM feed, in which case we can // stream it - unless the user has overridden it with a return type of "XML" @@ -96,8 +97,7 @@ internal override void ProcessResponse(HttpResponseMessage response) { // Try to get the response encoding from the ContentType header. string? characterSet = WebResponseHelper.GetCharacterSet(response); - - string str = StreamHelper.DecodeStream(responseStream, characterSet, out Encoding encoding, _cancelToken.Token); + string str = StreamHelper.DecodeStream(responseStream, characterSet, out Encoding encoding, perReadTimeout, _cancelToken.Token); string encodingVerboseName; try @@ -139,12 +139,12 @@ internal override void ProcessResponse(HttpResponseMessage response) } } else if (ShouldSaveToOutFile) - { + { string outFilePath = WebResponseHelper.GetOutFilePath(response, _qualifiedOutFile); WriteVerbose(string.Create(System.Globalization.CultureInfo.InvariantCulture, $"File Name: {Path.GetFileName(_qualifiedOutFile)}")); - StreamHelper.SaveStreamToFile(baseResponseStream, outFilePath, this, response.Content.Headers.ContentLength.GetValueOrDefault(), _cancelToken.Token); + StreamHelper.SaveStreamToFile(baseResponseStream, outFilePath, this, response.Content.Headers.ContentLength.GetValueOrDefault(), perReadTimeout, _cancelToken.Token); } if (!string.IsNullOrEmpty(StatusCodeVariable)) @@ -349,18 +349,20 @@ public enum RestReturnType internal class BufferingStreamReader : Stream { - internal BufferingStreamReader(Stream baseStream, CancellationToken cancellationToken) + internal BufferingStreamReader(Stream baseStream, TimeSpan perReadTimeout, CancellationToken cancellationToken) { _baseStream = baseStream; _streamBuffer = new MemoryStream(); _length = long.MaxValue; _copyBuffer = new byte[4096]; + _perReadTimeout = perReadTimeout; _cancellationToken = cancellationToken; } private readonly Stream _baseStream; private readonly MemoryStream _streamBuffer; private readonly byte[] _copyBuffer; + private readonly TimeSpan _perReadTimeout; private readonly CancellationToken _cancellationToken; public override bool CanRead => true; @@ -395,7 +397,7 @@ public override int Read(byte[] buffer, int offset, int count) // If we don't have enough data to fill this from memory, cache more. // We try to read 4096 bytes from base stream every time, so at most we // may cache 4095 bytes more than what is required by the Read operation. - int bytesRead = _baseStream.ReadAsync(_copyBuffer, 0, _copyBuffer.Length, _cancellationToken).GetAwaiter().GetResult(); + int bytesRead = _baseStream.ReadAsync(_copyBuffer.AsMemory(), _perReadTimeout, _cancellationToken).GetAwaiter().GetResult(); if (_streamBuffer.Position < _streamBuffer.Length) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index f7b6f3e270c..ba7d66bb9a9 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -266,11 +266,25 @@ public abstract class WebRequestPSCmdlet : PSCmdlet, IDisposable public virtual SwitchParameter DisableKeepAlive { get; set; } /// - /// Gets or sets the TimeOut property. + /// Gets or sets the ConnectionTimeoutSeconds property. /// + /// + /// This property applies to sending the request and receiving the response headers only. + /// + [Alias("TimeoutSec")] [Parameter] [ValidateRange(0, int.MaxValue)] - public virtual int TimeoutSec { get; set; } + public virtual int ConnectionTimeoutSeconds { get; set; } + + /// + /// Gets or sets the OperationTimeoutSeconds property. + /// + /// + /// This property applies to each read operation when receiving the response body. + /// + [Parameter] + [ValidateRange(0, int.MaxValue)] + public virtual int OperationTimeoutSeconds { get; set; } /// /// Gets or sets the Headers property. @@ -570,7 +584,7 @@ protected override void ProcessRecord() string respVerboseMsg = contentLength is null ? string.Format(CultureInfo.CurrentCulture, WebCmdletStrings.WebResponseNoSizeVerboseMsg, response.Version, contentType) : string.Format(CultureInfo.CurrentCulture, WebCmdletStrings.WebResponseVerboseMsg, response.Version, contentLength, contentType); - + WriteVerbose(respVerboseMsg); bool _isSuccess = response.IsSuccessStatusCode; @@ -621,12 +635,19 @@ protected override void ProcessRecord() string detailMsg = string.Empty; try { - string error = StreamHelper.GetResponseString(response, _cancelToken.Token); + // We can't use ReadAsStringAsync because it doesn't have per read timeouts + TimeSpan perReadTimeout = ConvertTimeoutSecondsToTimeSpan(OperationTimeoutSeconds); + string characterSet = WebResponseHelper.GetCharacterSet(response); + var responseStream = StreamHelper.GetResponseStream(response, _cancelToken.Token); + int initialCapacity = (int)Math.Min(contentLength ?? StreamHelper.DefaultReadBuffer, StreamHelper.DefaultReadBuffer); + var bufferedStream = new WebResponseContentMemoryStream(responseStream, initialCapacity, this, contentLength, perReadTimeout, _cancelToken.Token); + string error = StreamHelper.DecodeStream(bufferedStream, characterSet, out Encoding encoding, perReadTimeout, _cancelToken.Token); detailMsg = FormatErrorMessage(error, contentType); } - catch + catch (Exception ex) { // Catch all + er.ErrorDetails = new ErrorDetails(ex.ToString()); } if (!string.IsNullOrEmpty(detailMsg)) @@ -656,6 +677,11 @@ protected override void ProcessRecord() WriteError(er); } } + catch (TimeoutException ex) + { + ErrorRecord er = new(ex, "OperationTimeoutReached", ErrorCategory.OperationTimeout, null); + ThrowTerminatingError(er); + } catch (HttpRequestException ex) { ErrorRecord er = new(ex, "WebCmdletWebResponseException", ErrorCategory.InvalidOperation, request); @@ -666,7 +692,7 @@ protected override void ProcessRecord() ThrowTerminatingError(er); } - finally + finally { _cancelToken?.Dispose(); _cancelToken = null; @@ -970,7 +996,7 @@ internal virtual void PrepareSession() } else { - webProxy.UseDefaultCredentials = ProxyUseDefaultCredentials; + webProxy.UseDefaultCredentials = ProxyUseDefaultCredentials; } // We don't want to update the WebSession unless the proxies are different @@ -1020,7 +1046,7 @@ internal virtual void PrepareSession() WebSession.RetryIntervalInSeconds = RetryIntervalSec; } - WebSession.TimeoutSec = TimeoutSec; + WebSession.ConnectionTimeout = ConvertTimeoutSecondsToTimeSpan(ConnectionTimeoutSeconds); } internal virtual HttpClient GetHttpClient(bool handleRedirect) @@ -1263,8 +1289,24 @@ internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestM Uri currentUri = currentRequest.RequestUri; _cancelToken = new CancellationTokenSource(); - response = client.SendAsync(currentRequest, HttpCompletionOption.ResponseHeadersRead, _cancelToken.Token).GetAwaiter().GetResult(); + try + { + response = client.SendAsync(currentRequest, HttpCompletionOption.ResponseHeadersRead, _cancelToken.Token).GetAwaiter().GetResult(); + } + catch (TaskCanceledException ex) + { + if (ex.InnerException is TimeoutException) + { + // HTTP Request timed out + ErrorRecord er = new(ex, "ConnectionTimeoutReached", ErrorCategory.OperationTimeout, null); + ThrowTerminatingError(er); + } + else + { + throw; + } + } if (handleRedirect && _maximumRedirection is not 0 && IsRedirectCode(response.StatusCode) @@ -1388,6 +1430,9 @@ internal virtual void UpdateSession(HttpResponseMessage response) #endregion Virtual Methods #region Helper Methods + + internal static TimeSpan ConvertTimeoutSecondsToTimeSpan(int timeout) => timeout > 0 ? TimeSpan.FromSeconds(timeout) : Timeout.InfiniteTimeSpan; + private Uri PrepareUri(Uri uri) { uri = CheckProtocol(uri); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebResponseObject.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebResponseObject.Common.cs index 5b89a2352fe..81bd4f13c62 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebResponseObject.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebResponseObject.Common.cs @@ -72,14 +72,24 @@ public class WebResponseObject #endregion Properties + #region Protected Fields + + /// + /// Time permitted between reads or Timeout.InfiniteTimeSpan for no timeout. + /// + protected TimeSpan perReadTimeout; + + #endregion Protected Fields + #region Constructors /// /// Initializes a new instance of the class. /// /// The Http response. + /// Time permitted between reads or Timeout.InfiniteTimeSpan for no timeout. /// The cancellation token. - public WebResponseObject(HttpResponseMessage response, CancellationToken cancellationToken) : this(response, null, cancellationToken) { } + public WebResponseObject(HttpResponseMessage response, TimeSpan perReadTimeout, CancellationToken cancellationToken) : this(response, null, perReadTimeout, cancellationToken) { } /// /// Initializes a new instance of the class @@ -87,9 +97,11 @@ public WebResponseObject(HttpResponseMessage response, CancellationToken cancell /// /// Http response. /// The http content stream. + /// Time permitted between reads or Timeout.InfiniteTimeSpan for no timeout. /// The cancellation token. - public WebResponseObject(HttpResponseMessage response, Stream? contentStream, CancellationToken cancellationToken) + public WebResponseObject(HttpResponseMessage response, Stream? contentStream, TimeSpan perReadTimeout, CancellationToken cancellationToken) { + this.perReadTimeout = perReadTimeout; SetResponse(response, contentStream, cancellationToken); InitializeContent(); InitializeRawContent(response); @@ -149,7 +161,7 @@ private void SetResponse(HttpResponseMessage response, Stream? contentStream, Ca } int initialCapacity = (int)Math.Min(contentLength, StreamHelper.DefaultReadBuffer); - RawContentStream = new WebResponseContentMemoryStream(st, initialCapacity, cmdlet: null, response.Content.Headers.ContentLength.GetValueOrDefault(), cancellationToken); + RawContentStream = new WebResponseContentMemoryStream(st, initialCapacity, cmdlet: null, response.Content.Headers.ContentLength.GetValueOrDefault(), perReadTimeout, cancellationToken); } // Set the position of the content stream to the beginning diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/InvokeWebRequestCommand.CoreClr.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/InvokeWebRequestCommand.CoreClr.cs index 1e66157ef0c..026bbe866e5 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/InvokeWebRequestCommand.CoreClr.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/InvokeWebRequestCommand.CoreClr.cs @@ -7,6 +7,7 @@ using System.IO; using System.Management.Automation; using System.Net.Http; +using System.Threading; namespace Microsoft.PowerShell.Commands { @@ -35,7 +36,7 @@ public InvokeWebRequestCommand() : base() internal override void ProcessResponse(HttpResponseMessage response) { ArgumentNullException.ThrowIfNull(response); - + TimeSpan perReadTimeout = ConvertTimeoutSecondsToTimeSpan(OperationTimeoutSeconds); Stream responseStream = StreamHelper.GetResponseStream(response, _cancelToken.Token); if (ShouldWriteToPipeline) { @@ -45,8 +46,9 @@ internal override void ProcessResponse(HttpResponseMessage response) StreamHelper.ChunkSize, this, response.Content.Headers.ContentLength.GetValueOrDefault(), + perReadTimeout, _cancelToken.Token); - WebResponseObject ro = WebResponseHelper.IsText(response) ? new BasicHtmlWebResponseObject(response, responseStream, _cancelToken.Token) : new WebResponseObject(response, responseStream, _cancelToken.Token); + WebResponseObject ro = WebResponseHelper.IsText(response) ? new BasicHtmlWebResponseObject(response, responseStream, perReadTimeout, _cancelToken.Token) : new WebResponseObject(response, responseStream, perReadTimeout, _cancelToken.Token); ro.RelationLink = _relationLink; WriteObject(ro); @@ -63,7 +65,7 @@ internal override void ProcessResponse(HttpResponseMessage response) WriteVerbose(string.Create(System.Globalization.CultureInfo.InvariantCulture, $"File Name: {Path.GetFileName(_qualifiedOutFile)}")); - StreamHelper.SaveStreamToFile(responseStream, outFilePath, this, response.Content.Headers.ContentLength.GetValueOrDefault(), _cancelToken.Token); + StreamHelper.SaveStreamToFile(responseStream, outFilePath, this, response.Content.Headers.ContentLength.GetValueOrDefault(), perReadTimeout, _cancelToken.Token); } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs index 6d217cdc909..d03debf3fc0 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs @@ -4,6 +4,7 @@ #nullable enable using System; +using System.Buffers; using System.IO; using System.Management.Automation; using System.Management.Automation.Internal; @@ -29,6 +30,7 @@ internal class WebResponseContentMemoryStream : MemoryStream private readonly Stream _originalStreamToProxy; private readonly Cmdlet? _ownerCmdlet; private readonly CancellationToken _cancellationToken; + private readonly TimeSpan _perReadTimeout; private bool _isInitialized = false; #endregion Data @@ -41,13 +43,15 @@ internal class WebResponseContentMemoryStream : MemoryStream /// Presize the memory stream. /// Owner cmdlet if any. /// Expected download size in Bytes. + /// Time permitted between reads or Timeout.InfiniteTimeSpan for no timeout. /// Cancellation token. - internal WebResponseContentMemoryStream(Stream stream, int initialCapacity, Cmdlet? cmdlet, long? contentLength, CancellationToken cancellationToken) : base(initialCapacity) + internal WebResponseContentMemoryStream(Stream stream, int initialCapacity, Cmdlet? cmdlet, long? contentLength, TimeSpan perReadTimeout, CancellationToken cancellationToken) : base(initialCapacity) { this._contentLength = contentLength; _originalStreamToProxy = stream; _ownerCmdlet = cmdlet; _cancellationToken = cancellationToken; + _perReadTimeout = perReadTimeout; } #endregion Constructors @@ -228,7 +232,7 @@ private void Initialize(CancellationToken cancellationToken = default) } } - read = _originalStreamToProxy.ReadAsync(buffer, 0, buffer.Length, cancellationToken).GetAwaiter().GetResult(); + read = _originalStreamToProxy.ReadAsync(buffer.AsMemory(), _perReadTimeout, cancellationToken).GetAwaiter().GetResult(); if (read > 0) { @@ -255,6 +259,84 @@ private void Initialize(CancellationToken cancellationToken = default) } } + internal static class StreamTimeoutExtensions + { + internal static async Task ReadAsync(this Stream stream, Memory buffer, TimeSpan readTimeout, CancellationToken cancellationToken) + { + if (readTimeout == Timeout.InfiniteTimeSpan) + { + return await stream.ReadAsync(buffer, cancellationToken); + } + + using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + try + { + cts.CancelAfter(readTimeout); + return await stream.ReadAsync(buffer, cts.Token).ConfigureAwait(false); + } + catch (TaskCanceledException ex) + { + if (cts.IsCancellationRequested) + { + throw new TimeoutException($"The request was canceled due to the configured OperationTimeout of {readTimeout.TotalSeconds} seconds elapsing", ex); + } + else + { + throw; + } + } + } + + internal static async Task CopyToAsync(this Stream source, Stream destination, TimeSpan perReadTimeout, CancellationToken cancellationToken) + { + if (perReadTimeout == Timeout.InfiniteTimeSpan) + { + // No timeout - use fast path + await source.CopyToAsync(destination, cancellationToken); + return; + } + + byte[] buffer = ArrayPool.Shared.Rent(StreamHelper.ChunkSize); + CancellationTokenSource cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + try + { + while (true) + { + if (!cts.TryReset()) + { + cts.Dispose(); + cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + } + + cts.CancelAfter(perReadTimeout); + int bytesRead = await source.ReadAsync(buffer, cts.Token).ConfigureAwait(false); + if (bytesRead == 0) + { + break; + } + + await destination.WriteAsync(buffer.AsMemory(0, bytesRead), cancellationToken).ConfigureAwait(false); + } + } + catch (TaskCanceledException ex) + { + if (cts.IsCancellationRequested) + { + throw new TimeoutException($"The request was canceled due to the configured OperationTimeout of {perReadTimeout.TotalSeconds} seconds elapsing", ex); + } + else + { + throw; + } + } + finally + { + cts.Dispose(); + ArrayPool.Shared.Return(buffer); + } + } + } + internal static class StreamHelper { #region Constants @@ -270,11 +352,11 @@ internal static class StreamHelper #region Static Methods - internal static void WriteToStream(Stream input, Stream output, PSCmdlet cmdlet, long? contentLength, CancellationToken cancellationToken) + internal static void WriteToStream(Stream input, Stream output, PSCmdlet cmdlet, long? contentLength, TimeSpan perReadTimeout, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(cmdlet); - Task copyTask = input.CopyToAsync(output, cancellationToken); + Task copyTask = input.CopyToAsync(output, perReadTimeout, cancellationToken); bool wroteProgress = false; ProgressRecord record = new( @@ -328,16 +410,17 @@ internal static void WriteToStream(Stream input, Stream output, PSCmdlet cmdlet, /// Output file name. /// Current cmdlet (Invoke-WebRequest or Invoke-RestMethod). /// Expected download size in Bytes. + /// Time permitted between reads or Timeout.InfiniteTimeSpan for no timeout. /// CancellationToken to track the cmdlet cancellation. - internal static void SaveStreamToFile(Stream stream, string filePath, PSCmdlet cmdlet, long? contentLength, CancellationToken cancellationToken) + internal static void SaveStreamToFile(Stream stream, string filePath, PSCmdlet cmdlet, long? contentLength, TimeSpan perReadTimeout, CancellationToken cancellationToken) { // If the web cmdlet should resume, append the file instead of overwriting. FileMode fileMode = cmdlet is WebRequestPSCmdlet webCmdlet && webCmdlet.ShouldResume ? FileMode.Append : FileMode.Create; using FileStream output = new(filePath, fileMode, FileAccess.Write, FileShare.Read); - WriteToStream(stream, output, cmdlet, contentLength, cancellationToken); + WriteToStream(stream, output, cmdlet, contentLength, perReadTimeout, cancellationToken); } - private static string StreamToString(Stream stream, Encoding encoding, CancellationToken cancellationToken) + private static string StreamToString(Stream stream, Encoding encoding, TimeSpan perReadTimeout, CancellationToken cancellationToken) { StringBuilder result = new(capacity: ChunkSize); Decoder decoder = encoding.GetDecoder(); @@ -348,51 +431,59 @@ private static string StreamToString(Stream stream, Encoding encoding, Cancellat useBufferSize = encoding.GetMaxCharCount(10); } - char[] chars = new char[useBufferSize]; - byte[] bytes = new byte[useBufferSize * 4]; - int bytesRead = 0; - do + char[] chars = ArrayPool.Shared.Rent(useBufferSize); + byte[] bytes = ArrayPool.Shared.Rent(useBufferSize * 4); + try { - // Read at most the number of bytes that will fit in the input buffer. The - // return value is the actual number of bytes read, or zero if no bytes remain. - bytesRead = stream.ReadAsync(bytes, 0, useBufferSize * 4, cancellationToken).GetAwaiter().GetResult(); + int bytesRead = 0; + do + { + // Read at most the number of bytes that will fit in the input buffer. The + // return value is the actual number of bytes read, or zero if no bytes remain. + bytesRead = stream.ReadAsync(bytes.AsMemory(), perReadTimeout, cancellationToken).GetAwaiter().GetResult(); - bool completed = false; - int byteIndex = 0; + bool completed = false; + int byteIndex = 0; - while (!completed) - { - // If this is the last input data, flush the decoder's internal buffer and state. - bool flush = bytesRead is 0; - decoder.Convert(bytes, byteIndex, bytesRead - byteIndex, chars, 0, useBufferSize, flush, out int bytesUsed, out int charsUsed, out completed); - - // The conversion produced the number of characters indicated by charsUsed. Write that number - // of characters to our result buffer - result.Append(chars, 0, charsUsed); - - // Increment byteIndex to the next block of bytes in the input buffer, if any, to convert. - byteIndex += bytesUsed; - - // The behavior of decoder.Convert changed start .NET 3.1-preview2. - // The change was made in https://github.com/dotnet/coreclr/pull/27229 - // The recommendation from .NET team is to not check for 'completed' if 'flush' is false. - // Break out of the loop if all bytes have been read. - if (!flush && bytesRead == byteIndex) + while (!completed) { - break; + // If this is the last input data, flush the decoder's internal buffer and state. + bool flush = bytesRead is 0; + decoder.Convert(bytes, byteIndex, bytesRead - byteIndex, chars, 0, useBufferSize, flush, out int bytesUsed, out int charsUsed, out completed); + + // The conversion produced the number of characters indicated by charsUsed. Write that number + // of characters to our result buffer + result.Append(chars, 0, charsUsed); + + // Increment byteIndex to the next block of bytes in the input buffer, if any, to convert. + byteIndex += bytesUsed; + + // The behavior of decoder.Convert changed start .NET 3.1-preview2. + // The change was made in https://github.com/dotnet/coreclr/pull/27229 + // The recommendation from .NET team is to not check for 'completed' if 'flush' is false. + // Break out of the loop if all bytes have been read. + if (!flush && bytesRead == byteIndex) + { + break; + } } } - } - while (bytesRead != 0); + while (bytesRead != 0); - return result.ToString(); + return result.ToString(); + } + finally + { + ArrayPool.Shared.Return(chars); + ArrayPool.Shared.Return(bytes); + } } - internal static string DecodeStream(Stream stream, string? characterSet, out Encoding encoding, CancellationToken cancellationToken) + internal static string DecodeStream(Stream stream, string? characterSet, out Encoding encoding, TimeSpan perReadTimeout, CancellationToken cancellationToken) { bool isDefaultEncoding = !TryGetEncoding(characterSet, out encoding); - string content = StreamToString(stream, encoding, cancellationToken); + string content = StreamToString(stream, encoding, perReadTimeout, cancellationToken); if (isDefaultEncoding) { // We only look within the first 1k characters as the meta element and @@ -415,7 +506,7 @@ internal static string DecodeStream(Stream stream, string? characterSet, out Enc if (TryGetEncoding(characterSet, out Encoding localEncoding)) { stream.Seek(0, SeekOrigin.Begin); - content = StreamToString(stream, localEncoding, cancellationToken); + content = StreamToString(stream, localEncoding, perReadTimeout, cancellationToken); encoding = localEncoding; } } @@ -459,8 +550,6 @@ internal static byte[] EncodeToBytes(string str, Encoding encoding) return encoding.GetBytes(str); } - internal static string GetResponseString(HttpResponseMessage response, CancellationToken cancellationToken) => response.Content.ReadAsStringAsync(cancellationToken).GetAwaiter().GetResult(); - internal static Stream GetResponseStream(HttpResponseMessage response, CancellationToken cancellationToken) => response.Content.ReadAsStreamAsync(cancellationToken).GetAwaiter().GetResult(); #endregion Static Methods diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestSession.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestSession.cs index d4a9a5cc48b..a55a7dde387 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestSession.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestSession.cs @@ -32,7 +32,7 @@ public class WebRequestSession : IDisposable private bool _skipCertificateCheck; private bool _noProxy; private bool _disposed; - private int _timeoutSec; + private TimeSpan _connectionTimeout; /// /// Contains true if an existing HttpClient had to be disposed and recreated since the WebSession was last used. @@ -142,7 +142,7 @@ public WebRequestSession() internal bool SkipCertificateCheck { set => SetStructVar(ref _skipCertificateCheck, value); } - internal int TimeoutSec { set => SetStructVar(ref _timeoutSec, value); } + internal TimeSpan ConnectionTimeout { set => SetStructVar(ref _connectionTimeout, value); } internal bool NoProxy { @@ -240,7 +240,7 @@ private HttpClient CreateHttpClient() // Check timeout setting (in seconds instead of milliseconds as in HttpWebRequest) return new HttpClient(handler) { - Timeout = _timeoutSec is 0 ? TimeSpan.FromMilliseconds(Timeout.Infinite) : TimeSpan.FromSeconds(_timeoutSec) + Timeout = _connectionTimeout }; } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 index da7a395ff28..21b28949e77 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 @@ -241,10 +241,10 @@ function ExecuteRequestWithCustomUserAgent { try { $Params = @{ - Uri = $Uri - TimeoutSec = 5 - UserAgent = $UserAgent - SkipHeaderValidation = $SkipHeaderValidation.IsPresent + Uri = $Uri + ConnectionTimeoutSeconds = 5 + UserAgent = $UserAgent + SkipHeaderValidation = $SkipHeaderValidation.IsPresent } if ($Cmdlet -eq 'Invoke-WebRequest') { $result.Output = Invoke-WebRequest @Params @@ -608,12 +608,20 @@ Describe "Invoke-WebRequest tests" -Tags "Feature", "RequireAdminOnWindows" { $Result.Output.Content | Should -Match '测试123' } - It "Invoke-WebRequest validate timeout option" { + It "Invoke-WebRequest validate ConnectionTimeoutSeconds option" { + $uri = Get-WebListenerUrl -Test 'Delay' -TestValue '5' + $command = "Invoke-WebRequest -Uri '$uri' -ConnectionTimeoutSeconds 2" + + $result = ExecuteWebCommand -command $command + $result.Error.FullyQualifiedErrorId | Should -Be "ConnectionTimeoutReached,Microsoft.PowerShell.Commands.InvokeWebRequestCommand" + } + + It "Invoke-WebRequest validate TimeoutSec alias" { $uri = Get-WebListenerUrl -Test 'Delay' -TestValue '5' $command = "Invoke-WebRequest -Uri '$uri' -TimeoutSec 2" $result = ExecuteWebCommand -command $command - $result.Error.FullyQualifiedErrorId | Should -Be "System.Threading.Tasks.TaskCanceledException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand" + $result.Error.FullyQualifiedErrorId | Should -Be "ConnectionTimeoutReached,Microsoft.PowerShell.Commands.InvokeWebRequestCommand" } It "Validate Invoke-WebRequest error with -Proxy and -NoProxy option" { @@ -2650,12 +2658,20 @@ Describe "Invoke-RestMethod tests" -Tags "Feature", "RequireAdminOnWindows" { $Result.Output | Should -Match '测试123' } - It "Invoke-RestMethod validate timeout option" { + It "Invoke-RestMethod validate ConnectionTimeoutSeconds option" { + $uri = Get-WebListenerUrl -Test 'Delay' -TestValue '5' + $command = "Invoke-RestMethod -Uri '$uri' -ConnectionTimeoutSeconds 2" + + $result = ExecuteWebCommand -command $command + $result.Error.FullyQualifiedErrorId | Should -Be "ConnectionTimeoutReached,Microsoft.PowerShell.Commands.InvokeRestMethodCommand" + } + + It "Invoke-RestMethod validate TimeoutSec alias" { $uri = Get-WebListenerUrl -Test 'Delay' -TestValue '5' $command = "Invoke-RestMethod -Uri '$uri' -TimeoutSec 2" $result = ExecuteWebCommand -command $command - $result.Error.FullyQualifiedErrorId | Should -Be "System.Threading.Tasks.TaskCanceledException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand" + $result.Error.FullyQualifiedErrorId | Should -Be "ConnectionTimeoutReached,Microsoft.PowerShell.Commands.InvokeRestMethodCommand" } It "Validate Invoke-RestMethod error with -Proxy and -NoProxy option" { @@ -4373,7 +4389,12 @@ Describe 'Invoke-WebRequest and Invoke-RestMethod support Cancellation through C RunWithCancellation -Uri $uri } - It 'Invoke-WebRequest: Defalate Compression CTRL-C Cancels request after request headers' { + It 'Invoke-WebRequest: Gzip Compression CTRL-C Cancels request after request headers with Content-Length' { + $uri = Get-WebListenerUrl -Test StallGzip -TestValue '30/application%2fjson' -Query @{ contentLength = $true } + RunWithCancellation -Uri $uri + } + + It 'Invoke-WebRequest: Deflate Compression CTRL-C Cancels request after request headers' { $uri = Get-WebListenerUrl -Test StallDeflate -TestValue '30/application%2fjson' RunWithCancellation -Uri $uri } @@ -4388,7 +4409,7 @@ Describe 'Invoke-WebRequest and Invoke-RestMethod support Cancellation through C RunWithCancellation -Uri $uri -Arguments '-SkipCertificateCheck' } - It 'Invoke-WebRequest: HTTPS with Defalte compression CTRL-C Cancels request after request headers' { + It 'Invoke-WebRequest: HTTPS with Deflate compression CTRL-C Cancels request after request headers' { $uri = Get-WebListenerUrl -Https -Test StallDeflate -TestValue '30/application%2fjson' RunWithCancellation -Uri $uri -Arguments '-SkipCertificateCheck' } @@ -4443,3 +4464,82 @@ Describe 'Invoke-WebRequest and Invoke-RestMethod support Cancellation through C RunWithCancellation -Command 'Invoke-RestMethod' -Uri $uri } } + +Describe 'Invoke-WebRequest and Invoke-RestMethod support OperationTimeoutSeconds' -Tags "CI", "RequireAdminOnWindows" { + BeforeAll { + $oldProgress = $ProgressPreference + $ProgressPreference = 'SilentlyContinue' + $WebListener = Start-WebListener + } + + AfterAll { + $ProgressPreference = $oldProgress + } + + function RunWithNetworkTimeout { + param( + [ValidateSet('Invoke-WebRequest', 'Invoke-RestMethod')] + [string]$Command = 'Invoke-WebRequest', + [string]$Arguments = '', + [uri]$Uri, + [int]$OperationTimeoutSeconds, + [switch]$WillTimeout + ) + + $invoke = "$Command -Uri `"$Uri`" $Arguments" + if ($PSBoundParameters.ContainsKey('OperationTimeoutSeconds')) { + $invoke = "$invoke -OperationTimeoutSeconds $OperationTimeoutSeconds" + } + + $result = ExecuteWebCommand -command $invoke + if ($WillTimeout) { + $result.Error | Should -Not -BeNullOrEmpty + $fqErrorClass = if ($Command -eq 'Invoke-WebRequest') { 'InvokeWebRequestCommand'} else { 'InvokeRestMethodCommand'} + $result.Error.FullyQualifiedErrorId | Should -Be "OperationTimeoutReached,Microsoft.PowerShell.Commands.$fqErrorClass" + $result.Output | Should -BeNullOrEmpty + } else { + $result.Error | Should -BeNullOrEmpty + $result.Output | Should -Not -BeNullOrEmpty + } + } + + It 'Invoke-WebRequest: OperationTimeoutSeconds does not cancel if stalls shorter than timeout but download takes longer than timeout' { + $uri = Get-WebListenerUrl -Test Stall -TestValue '2' -Query @{ chunks = 5 } + RunWithNetworkTimeout -Uri $uri -OperationTimeoutSeconds 4 + } + + It 'Invoke-WebRequest: OperationTimeoutSeconds cancels if stall lasts longer than OperationTimeoutSeconds value' { + $uri = Get-WebListenerUrl -Test Stall -TestValue 30 + RunWithNetworkTimeout -Uri $uri -OperationTimeoutSeconds 3 -WillTimeout + } + + It 'Invoke-WebRequest: OperationTimeoutSeconds cancels if stall lasts longer than OperationTimeoutSeconds value for HTTPS/gzip compression' { + $uri = Get-WebListenerUrl -Https -Test StallGzip -TestValue 30 + RunWithNetworkTimeout -Uri $uri -OperationTimeoutSeconds 3 -WillTimeout -Arguments '-SkipCertificateCheck' + } + + It 'Invoke-RestMethod: OperationTimeoutSeconds does not cancel if stalls shorter than timeout but download takes longer than timeout' { + $uri = Get-WebListenerUrl -Test Stall -TestValue '2' -Query @{ chunks = 5 } + RunWithNetworkTimeout -Command Invoke-RestMethod -Uri $uri -OperationTimeoutSeconds 4 + } + + It 'Invoke-RestMethod: OperationTimeoutSeconds cancels if stall lasts longer than OperationTimeoutSeconds value' { + $uri = Get-WebListenerUrl -Test Stall -TestValue 30 + RunWithNetworkTimeout -Command Invoke-RestMethod -Uri $uri -OperationTimeoutSeconds 2 -WillTimeout + } + + It 'Invoke-RestMethod: OperationTimeoutSeconds cancels when doing XML atom processing' { + $uri = Get-WebListenerUrl -Test Stall -TestValue '30/application%2fxml' + RunWithNetworkTimeout -Command Invoke-RestMethod -Uri $uri -OperationTimeoutSeconds 2 -WillTimeout + } + + It 'Invoke-RestMethod: OperationTimeoutSeconds cancels when doing JSON processing' { + $uri = Get-WebListenerUrl -Test Stall -TestValue '30/application%2fjson' + RunWithNetworkTimeout -Command Invoke-RestMethod -Uri $uri -OperationTimeoutSeconds 2 -WillTimeout + } + + It 'Invoke-RestMethod: OperationTimeoutSeconds cancels when doing XML atom processing for HTTPS/gzip compression' { + $uri = Get-WebListenerUrl -Https -Test StallGzip -TestValue 30/application%2fXML + RunWithNetworkTimeout -Command Invoke-RestMethod -Uri $uri -OperationTimeoutSeconds 2 -WillTimeout -Arguments '-SkipCertificateCheck' + } +} diff --git a/test/tools/WebListener/Controllers/DelayController.cs b/test/tools/WebListener/Controllers/DelayController.cs index 5ab081d580d..5fdd9051d3d 100644 --- a/test/tools/WebListener/Controllers/DelayController.cs +++ b/test/tools/WebListener/Controllers/DelayController.cs @@ -54,33 +54,33 @@ public JsonResult Index(int seconds) return getController.Index(); } - public async Task Stall(int seconds, string contentType, CancellationToken cancellationToken) + public async Task Stall(int seconds, string contentType, int chunks, bool contentLength, CancellationToken cancellationToken) { - await WriteStallResponse(seconds, contentType, null, null, cancellationToken); + await WriteStallResponse(seconds, contentType, chunks, contentLength, null, null, cancellationToken); } - public async Task StallBrotli(int seconds, string contentType, CancellationToken cancellationToken) + public async Task StallBrotli(int seconds, string contentType, int chunks, bool contentLength, CancellationToken cancellationToken) { using var memStream = new MemoryStream(); using var compressedStream = new BrotliStream(memStream, CompressionLevel.Fastest); Response.Headers.ContentEncoding = "br"; - await WriteStallResponse(seconds, contentType, compressedStream, memStream, cancellationToken); + await WriteStallResponse(seconds, contentType, chunks, contentLength, compressedStream, memStream, cancellationToken); } - public async Task StallDeflate(int seconds, string contentType, CancellationToken cancellationToken) + public async Task StallDeflate(int seconds, string contentType, int chunks, bool contentLength, CancellationToken cancellationToken) { using var memStream = new MemoryStream(); using var compressedStream = new DeflateStream(memStream, CompressionLevel.Fastest); Response.Headers.ContentEncoding = "deflate"; - await WriteStallResponse(seconds, contentType, compressedStream, memStream, cancellationToken); + await WriteStallResponse(seconds, contentType, chunks, contentLength, compressedStream, memStream, cancellationToken); } - public async Task StallGZip(int seconds, string contentType, CancellationToken cancellationToken) + public async Task StallGZip(int seconds, string contentType, int chunks, bool contentLength, CancellationToken cancellationToken) { using var memStream = new MemoryStream(); using var compressedStream = new GZipStream(memStream, CompressionLevel.Fastest); Response.Headers.ContentEncoding = "gzip"; - await WriteStallResponse(seconds, contentType, compressedStream, memStream, cancellationToken); + await WriteStallResponse(seconds, contentType, chunks, contentLength, compressedStream, memStream, cancellationToken); } public IActionResult Error() @@ -88,7 +88,7 @@ public IActionResult Error() return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } - private async Task WriteStallResponse(int seconds, string contentType, Stream stream, MemoryStream memStream, CancellationToken cancellationToken) + private async Task WriteStallResponse(int seconds, string contentType, int chunks, bool contentLength, Stream stream, MemoryStream memStream, CancellationToken cancellationToken) { if (string.IsNullOrWhiteSpace(contentType)) { @@ -124,20 +124,41 @@ private async Task WriteStallResponse(int seconds, string contentType, Stream st stream.Close(); response = memStream.ToArray(); } - int midPoint = response.Length / 2; - - // Start writing approx half the content, including headers and then delay before writing the rest. - await Response.Body.WriteAsync(response, 0, midPoint, cancellationToken); - await Response.Body.FlushAsync(cancellationToken); + if (chunks < 2) + { + chunks = 2; + } + if (chunks > response.Length) + { + throw new InvalidDataException($"Response message is not big enough to break into {chunks} chunks. (Size {response.Length} bytes)."); + } - if (seconds > 0) + if (contentLength) { - int milliseconds = seconds * 1000; - await Task.Delay(milliseconds); + Response.ContentLength = response.Length; } + int chunkSize = response.Length / chunks; + int currentPos = 0; - await Response.Body.WriteAsync(response, midPoint, response.Length - midPoint, cancellationToken); - await Response.Body.FlushAsync(cancellationToken); + // Write each of the content chunks followed by a delay + // The last segment makes up the remainder of the content if + // it doesn't divide neatly into the required chunks + for (int i = 0; i < chunks; i++) + { + if (i == chunks - 1) + { + chunkSize = response.Length - currentPos; + seconds = 0; + } + await Response.Body.WriteAsync(response, currentPos, chunkSize, cancellationToken); + await Response.Body.FlushAsync(cancellationToken); + currentPos += chunkSize; + if (seconds > 0) + { + int milliseconds = seconds * 1000; + await Task.Delay(milliseconds); + } + } } } } From 994e43b1bf59422ebc99a53987776f0262348d31 Mon Sep 17 00:00:00 2001 From: MartinGC94 <42123497+MartinGC94@users.noreply.github.com> Date: Tue, 20 Jun 2023 00:48:59 +0200 Subject: [PATCH 600/779] Fix `TabExpansion2` variable leak when completing variables (#18763) --- .../CommandCompletion/CommandCompletion.cs | 39 +++++-------------- .../TabCompletion/TabCompletion.Tests.ps1 | 5 +++ 2 files changed, 15 insertions(+), 29 deletions(-) diff --git a/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs b/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs index 12ff1e05993..8071679d63c 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs @@ -513,43 +513,25 @@ private static CommandCompletion CompleteInputImpl(Ast ast, Token[] tokens, IScr List results = null; { - /* BROKEN code commented out, fix sometime // If we were invoked from TabExpansion2, we want to "remove" TabExpansion2 and anything it calls // from our results. We do this by faking out the session so that TabExpansion2 isn't anywhere to be found. - MutableTuple tupleForFrameToSkipPast = null; - foreach (var stackEntry in context.Debugger.GetCallStack()) + SessionStateScope scopeToRestore; + if (context.CurrentCommandProcessor.Command.CommandInfo.Name.Equals("TabExpansion2", StringComparison.OrdinalIgnoreCase) + && context.CurrentCommandProcessor.UseLocalScope + && context.EngineSessionState.CurrentScope.Parent is not null) { - dynamic stackEntryAsPSObj = PSObject.AsPSObject(stackEntry); - if (stackEntryAsPSObj.Command.Equals("TabExpansion2", StringComparison.OrdinalIgnoreCase)) - { - tupleForFrameToSkipPast = stackEntry.FunctionContext._localsTuple; - break; - } + scopeToRestore = context.EngineSessionState.CurrentScope; + context.EngineSessionState.CurrentScope = scopeToRestore.Parent; } - - SessionStateScope scopeToRestore = null; - if (tupleForFrameToSkipPast != null) + else { - // Find this tuple in the scope stack. - scopeToRestore = context.EngineSessionState.CurrentScope; - var scope = context.EngineSessionState.CurrentScope; - while (scope != null && scope.LocalsTuple != tupleForFrameToSkipPast) - { - scope = scope.Parent; - } - - if (scope != null) - { - context.EngineSessionState.CurrentScope = scope.Parent; - } + scopeToRestore = null; } try { - */ - var completionAnalysis = new CompletionAnalysis(ast, tokens, positionOfCursor, options); - results = completionAnalysis.GetResults(powershell, out replacementIndex, out replacementLength); - /* + var completionAnalysis = new CompletionAnalysis(ast, tokens, positionOfCursor, options); + results = completionAnalysis.GetResults(powershell, out replacementIndex, out replacementLength); } finally { @@ -558,7 +540,6 @@ private static CommandCompletion CompleteInputImpl(Ast ast, Token[] tokens, IScr context.EngineSessionState.CurrentScope = scopeToRestore; } } - */ } var completionResults = results ?? EmptyCompletionResult; diff --git a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 index 41131001000..ca159b798c3 100644 --- a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 +++ b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 @@ -952,6 +952,11 @@ Verb-Noun -Param1 Hello ^ $res.CompletionMatches[0].CompletionText | Should -Be "Get-ChildItem" } + it 'Should not complete TabExpansion2 variables' { + $res = TabExpansion2 -inputScript '$' -cursorColumn 1 + $res.CompletionMatches.CompletionText | Should -Not -Contain '$positionOfCursor' + } + it 'Should prefer the default parameterset when completing positional parameters' { $ScriptInput = 'Get-ChildItem | Where-Object ' $res = TabExpansion2 -inputScript $ScriptInput -cursorColumn $ScriptInput.Length From 15213d84944e32f6503b463f7cf0c8a836f3626a Mon Sep 17 00:00:00 2001 From: MartinGC94 <42123497+MartinGC94@users.noreply.github.com> Date: Tue, 20 Jun 2023 01:20:08 +0200 Subject: [PATCH 601/779] Do not require activity when creating a completed progress record (#18474) --- .../commands/utility/WriteProgressCmdlet.cs | 25 +++++++++++++++-- .../engine/ProgressRecord.cs | 27 +++++++++++++++++-- .../Write-Progress.Tests.ps1 | 8 +++--- 3 files changed, 52 insertions(+), 8 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteProgressCmdlet.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteProgressCmdlet.cs index fd5476751ad..0751954c54e 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteProgressCmdlet.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteProgressCmdlet.cs @@ -17,7 +17,6 @@ public sealed class WriteProgressCommand : PSCmdlet /// [Parameter( Position = 0, - Mandatory = true, HelpMessageBaseName = HelpMessageBaseName, HelpMessageResourceId = "ActivityParameterHelpMessage")] public string Activity { get; set; } @@ -96,7 +95,29 @@ protected override void ProcessRecord() { - ProgressRecord pr = new(Id, Activity, Status); + ProgressRecord pr; + if (string.IsNullOrEmpty(Activity)) + { + if (!Completed) + { + ThrowTerminatingError(new ErrorRecord( + new ArgumentException("Missing value for mandatory parameter.", nameof(Activity)), + "MissingActivity", + ErrorCategory.InvalidArgument, + Activity)); + return; + } + else + { + pr = new(Id); + pr.StatusDescription = Status; + } + } + else + { + pr = new(Id, Activity, Status); + } + pr.ParentActivityId = ParentId; pr.PercentComplete = PercentComplete; pr.SecondsRemaining = SecondsRemaining; diff --git a/src/System.Management.Automation/engine/ProgressRecord.cs b/src/System.Management.Automation/engine/ProgressRecord.cs index 559c4ade73f..7e45e022ab2 100644 --- a/src/System.Management.Automation/engine/ProgressRecord.cs +++ b/src/System.Management.Automation/engine/ProgressRecord.cs @@ -59,6 +59,25 @@ class ProgressRecord this.status = statusDescription; } + /// + /// Initializes a new instance of the ProgressRecord class and defines the activity Id. + /// + /// + /// A unique numeric key that identifies the activity to which this record applies. + /// + public + ProgressRecord(int activityId) + { + if (activityId < 0) + { + // negative Ids are reserved to indicate "no id" for parent Ids. + + throw PSTraceSource.NewArgumentOutOfRangeException(nameof(activityId), activityId, ProgressRecordStrings.ArgMayNotBeNegative, "activityId"); + } + + this.id = activityId; + } + /// /// Cloning constructor (all fields are value types - can treat our implementation of cloning as "deep" copy) /// @@ -481,9 +500,13 @@ internal static ProgressRecord FromPSObjectForRemoting(PSObject progressAsPSObje /// This object as a PSObject property bag. internal PSObject ToPSObjectForRemoting() { - PSObject progressAsPSObject = RemotingEncoder.CreateEmptyPSObject(); + // Activity used to be mandatory but that's no longer the case. + // We ensure the string has a value to maintain compatibility with older versions. + string activity = string.IsNullOrEmpty(Activity) ? " " : Activity; - progressAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.ProgressRecord_Activity, this.Activity)); + PSObject progressAsPSObject = RemotingEncoder.CreateEmptyPSObject(); + + progressAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.ProgressRecord_Activity, activity)); progressAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.ProgressRecord_ActivityId, this.ActivityId)); progressAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.ProgressRecord_StatusDescription, this.StatusDescription)); diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Write-Progress.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Write-Progress.Tests.ps1 index 97fd19da1b8..25770eb9a67 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Write-Progress.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Write-Progress.Tests.ps1 @@ -1,10 +1,6 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. Describe "Write-Progress DRT Unit Tests" -Tags "CI" { - It "Should be able to throw exception when missing mandatory parameters" { - { Write-Progress $null } | Should -Throw -ErrorId 'ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.WriteProgressCommand' - } - It "Should be able to throw exception when running Write-Progress with bad percentage" { { Write-Progress -Activity 'myactivity' -Status 'mystatus' -percent 101 } | Should -Throw -ErrorId 'ParameterArgumentValidationError,Microsoft.PowerShell.Commands.WriteProgressCommand' @@ -33,4 +29,8 @@ Describe "Write-Progress DRT Unit Tests" -Tags "CI" { { Write-Progress -Activity $activity -Status ('b' * ([console]::WindowWidth + 1)) -Id 1 } | Should -Not -Throw Write-Progress -Activity $activity -Id 1 -Completed } + + It 'Should be able to complete a progress record with no activity specified' { + { Write-Progress -Completed } | Should -Not -Throw + } } From 5437f387cc938cd32dcdc8f51eb5c1de046f006b Mon Sep 17 00:00:00 2001 From: "James Truher [MSFT]" Date: Mon, 19 Jun 2023 16:31:56 -0700 Subject: [PATCH 602/779] Add a new experimental feature to control native argument passing style on Windows (#18706) --- .../ExperimentalFeature.cs | 6 ++++- .../engine/InitialSessionState.cs | 22 ++++++++++++++++++- .../engine/NativeCommandProcessor.cs | 5 +++++ .../NativeCommandArguments.Tests.ps1 | 7 +++++- 4 files changed, 37 insertions(+), 3 deletions(-) diff --git a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs index 44646ef1289..45f8c98e7a0 100644 --- a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs +++ b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs @@ -28,6 +28,7 @@ public class ExperimentalFeature internal const string PSFeedbackProvider = "PSFeedbackProvider"; internal const string PSCommandWithArgs = "PSCommandWithArgs"; internal const string PSConstrainedAuditLogging = "PSConstrainedAuditLogging"; + internal const string PSWindowsNativeCommandArgPassing = "PSWindowsNativeCommandArgPassing"; #endregion @@ -139,7 +140,10 @@ static ExperimentalFeature() description: "Enable `-CommandWithArgs` parameter for pwsh"), new ExperimentalFeature( name: PSConstrainedAuditLogging, - description: "PowerShell restriction logging when WDAC (Windows Defender Application Control) Code Integrity policy is set to Audit mode.") + description: "PowerShell restriction logging when WDAC (Windows Defender Application Control) Code Integrity policy is set to Audit mode."), + new ExperimentalFeature( + name: "PSWindowsNativeCommandArgPassing", + description: "Enable 'Windows' as the native command argument passing mode"), }; EngineExperimentalFeatures = new ReadOnlyCollection(engineFeatures); diff --git a/src/System.Management.Automation/engine/InitialSessionState.cs b/src/System.Management.Automation/engine/InitialSessionState.cs index d5cdfe1ebaa..6e5d26dd168 100644 --- a/src/System.Management.Automation/engine/InitialSessionState.cs +++ b/src/System.Management.Automation/engine/InitialSessionState.cs @@ -4534,7 +4534,7 @@ static InitialSessionState() builtinVariables.Add( new SessionStateVariableEntry( SpecialVariables.NativeArgumentPassing, - Platform.IsWindows ? NativeArgumentPassingStyle.Windows : NativeArgumentPassingStyle.Standard, + GetPassingStyle(), RunspaceInit.NativeCommandArgumentPassingDescription, ScopedItemOptions.None, new ArgumentTypeConverterAttribute(typeof(NativeArgumentPassingStyle)))); @@ -4542,6 +4542,26 @@ static InitialSessionState() BuiltInVariables = builtinVariables.ToArray(); } + /// + /// Assigns the default behavior for native argument passing. + /// If the system is non-Windows, we will return Standard. + /// If the experimental feature is enabled, we will return Windows. + /// Otherwise, we will return Legacy. + /// + private static NativeArgumentPassingStyle GetPassingStyle() + { +#if UNIX + return NativeArgumentPassingStyle.Standard; +#else + if (ExperimentalFeature.IsEnabled(ExperimentalFeature.PSWindowsNativeCommandArgPassing)) + { + return NativeArgumentPassingStyle.Windows; + } + + return NativeArgumentPassingStyle.Legacy; +#endif + } + internal static readonly SessionStateVariableEntry[] BuiltInVariables; /// diff --git a/src/System.Management.Automation/engine/NativeCommandProcessor.cs b/src/System.Management.Automation/engine/NativeCommandProcessor.cs index a5cc7874a6b..117360e21ea 100644 --- a/src/System.Management.Automation/engine/NativeCommandProcessor.cs +++ b/src/System.Management.Automation/engine/NativeCommandProcessor.cs @@ -583,6 +583,11 @@ private void InitNativeProcess() // Get the start info for the process. ProcessStartInfo startInfo = GetProcessStartInfo(redirectOutput, redirectError, redirectInput, soloCommand); + // Send Telemetry indicating what argument passing mode we are in. + ApplicationInsightsTelemetry.SendExperimentalUseData( + ExperimentalFeature.PSWindowsNativeCommandArgPassing, + NativeParameterBinderController.ArgumentPassingStyle.ToString()); + #if !UNIX string commandPath = this.Path.ToLowerInvariant(); if (commandPath.EndsWith("powershell.exe") || commandPath.EndsWith("powershell_ise.exe")) diff --git a/test/powershell/Language/Scripting/NativeExecution/NativeCommandArguments.Tests.ps1 b/test/powershell/Language/Scripting/NativeExecution/NativeCommandArguments.Tests.ps1 index 9cf10e8c901..8e09df9b699 100644 --- a/test/powershell/Language/Scripting/NativeExecution/NativeCommandArguments.Tests.ps1 +++ b/test/powershell/Language/Scripting/NativeExecution/NativeCommandArguments.Tests.ps1 @@ -5,7 +5,12 @@ param() Describe "Behavior is specific for each platform" -tags "CI" { It "PSNativeCommandArgumentPassing is set to 'Windows' on Windows systems" -skip:(-not $IsWindows) { - $PSNativeCommandArgumentPassing | Should -Be "Windows" + if ([Version]::TryParse($PSVersiontable.PSVersion.ToString(), [ref]$null)) { + $PSNativeCommandArgumentPassing | Should -BeExactly "Legacy" + } + else { + $PSNativeCommandArgumentPassing | Should -BeExactly "Windows" + } } It "PSNativeCommandArgumentPassing is set to 'Standard' on non-Windows systems" -skip:($IsWindows) { $PSNativeCommandArgumentPassing | Should -Be "Standard" From 16558c94146e44422f9e5b4f0f917775def51087 Mon Sep 17 00:00:00 2001 From: josea Date: Tue, 20 Jun 2023 12:49:46 -0400 Subject: [PATCH 603/779] Make `Update-Help` throw proper error when current culture is not associated with a language (#19765) --- .../help/UpdateHelpCommand.cs | 11 +++++++++++ .../resources/HelpDisplayStrings.resx | 3 +++ .../engine/Help/UpdatableHelpSystem.Tests.ps1 | 6 ++++++ 3 files changed, 20 insertions(+) diff --git a/src/System.Management.Automation/help/UpdateHelpCommand.cs b/src/System.Management.Automation/help/UpdateHelpCommand.cs index 236ec2877db..9df82699a32 100644 --- a/src/System.Management.Automation/help/UpdateHelpCommand.cs +++ b/src/System.Management.Automation/help/UpdateHelpCommand.cs @@ -7,6 +7,7 @@ using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; +using System.Linq; using System.Management.Automation; using System.Management.Automation.Help; using System.Management.Automation.Internal; @@ -181,6 +182,16 @@ protected override void ProcessRecord() _isInitialized = true; } + + // check if there is an UI, if not Throw out terminating error. + var cultures = _language ?? _helpSystem.GetCurrentUICulture(); + if (!cultures.Any()) + { + string cultureString = string.IsNullOrEmpty(CultureInfo.CurrentCulture.Name) ? CultureInfo.CurrentCulture.DisplayName : CultureInfo.CurrentCulture.Name; + string errMsg = StringUtil.Format(HelpDisplayStrings.FailedToUpdateHelpWithLocaleNoUICulture, cultureString); + ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "FailedToUpdateHelpWithLocaleNoUICulture", ErrorCategory.InvalidOperation, targetObject: null); + ThrowTerminatingError(error); + } base.Process(_module, FullyQualifiedModule); diff --git a/src/System.Management.Automation/resources/HelpDisplayStrings.resx b/src/System.Management.Automation/resources/HelpDisplayStrings.resx index 8656518d531..1bacf906961 100644 --- a/src/System.Management.Automation/resources/HelpDisplayStrings.resx +++ b/src/System.Management.Automation/resources/HelpDisplayStrings.resx @@ -392,6 +392,9 @@ English-US help content is available and can be saved using: Save-Help -UICultur Failed to update Help for the module(s) '{0}' with UI culture(s) {{{1}}} : {2}. English-US help content is available and can be installed using: Update-Help -UICulture en-US. + + Your current culture is ({0}), which is not associated with any language, consider changing your system culture or install the English-US help content using: Update-Help -UICulture en-US. + false diff --git a/test/powershell/engine/Help/UpdatableHelpSystem.Tests.ps1 b/test/powershell/engine/Help/UpdatableHelpSystem.Tests.ps1 index c1d01f6476b..439dc3be989 100644 --- a/test/powershell/engine/Help/UpdatableHelpSystem.Tests.ps1 +++ b/test/powershell/engine/Help/UpdatableHelpSystem.Tests.ps1 @@ -417,6 +417,12 @@ Describe "Validate 'Update-Help' shows 'HelpCultureNotSupported' when thrown" -T @{ 'name' = 'explicit culture de-DE'; 'culture' = 'de-DE' } ) { param ($name, $culture) + + # if running in Linux as an invariant culture => force Spanish + if ($IsLinux && $culture -eq $null && (Get-Culture).LCID -eq 127 ){ + $culture = 'es-ES' + } + # Cannot pass null, have to splat to skip argument entirely $cultureArg = $culture ? @{ 'UICulture' = $culture } : @{} $cultureUsed = $culture ?? (Get-Culture) From bdf21cc448d97704324f860d504d0adac45ae2ce Mon Sep 17 00:00:00 2001 From: PowerShell Team Bot <69177312+pwshBot@users.noreply.github.com> Date: Tue, 20 Jun 2023 10:13:21 -0700 Subject: [PATCH 604/779] Update experimental-feature json files (#19828) --- experimental-feature-linux.json | 3 ++- experimental-feature-windows.json | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/experimental-feature-linux.json b/experimental-feature-linux.json index 22b2f93977e..4e413efbfc9 100644 --- a/experimental-feature-linux.json +++ b/experimental-feature-linux.json @@ -8,5 +8,6 @@ "PSModuleAutoLoadSkipOfflineFiles", "PSNativeCommandErrorActionPreference", "PSNativeCommandPreserveBytePipe", - "PSSubsystemPluginModel" + "PSSubsystemPluginModel", + "PSWindowsNativeCommandArgPassing" ] diff --git a/experimental-feature-windows.json b/experimental-feature-windows.json index 22b2f93977e..4e413efbfc9 100644 --- a/experimental-feature-windows.json +++ b/experimental-feature-windows.json @@ -8,5 +8,6 @@ "PSModuleAutoLoadSkipOfflineFiles", "PSNativeCommandErrorActionPreference", "PSNativeCommandPreserveBytePipe", - "PSSubsystemPluginModel" + "PSSubsystemPluginModel", + "PSWindowsNativeCommandArgPassing" ] From cb2848c19bf3bc29b12d2fca8a864427e7e63fff Mon Sep 17 00:00:00 2001 From: CarloToso <105941898+CarloToso@users.noreply.github.com> Date: Wed, 21 Jun 2023 18:35:18 +0200 Subject: [PATCH 605/779] Code cleanup for `Get-Content` to make `-Head` and `-Tail` disallow negative values (#19715) --- .../commands/management/GetContentCommand.cs | 169 +++++++----------- .../Get-Content.Tests.ps1 | 12 ++ 2 files changed, 75 insertions(+), 106 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetContentCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetContentCommand.cs index f2e4598c1bc..4e83eda905f 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetContentCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetContentCommand.cs @@ -31,48 +31,20 @@ public class GetContentCommand : ContentCommandBase public long ReadCount { get; set; } = 1; /// - /// The number of content items to retrieve. By default this - /// value is -1 which means read all the content. + /// The number of content items to retrieve. /// [Parameter(ValueFromPipelineByPropertyName = true)] + [ValidateRange(0, long.MaxValue)] [Alias("First", "Head")] - public long TotalCount - { - get - { - return _totalCount; - } - - set - { - _totalCount = value; - _totalCountSpecified = true; - } - } - - private bool _totalCountSpecified = false; + public long TotalCount { get; set; } = -1; /// /// The number of content items to retrieve from the back of the file. /// [Parameter(ValueFromPipelineByPropertyName = true)] + [ValidateRange(0, int.MaxValue)] [Alias("Last")] - public int Tail - { - get - { - return _backCount; - } - - set - { - _backCount = value; - _tailSpecified = true; - } - } - - private int _backCount = -1; - private bool _tailSpecified = false; + public int Tail { get; set; } = -1; /// /// A virtual method for retrieving the dynamic parameters for a cmdlet. Derived cmdlets @@ -98,15 +70,6 @@ internal override object GetDynamicParameters(CmdletProviderContext context) #endregion Parameters - #region parameter data - - /// - /// The number of content items to retrieve. - /// - private long _totalCount = -1; - - #endregion parameter data - #region Command code /// @@ -116,7 +79,7 @@ protected override void ProcessRecord() { // TotalCount and Tail should not be specified at the same time. // Throw out terminating error if this is the case. - if (_totalCountSpecified && _tailSpecified) + if (TotalCount != -1 && Tail != -1) { string errMsg = StringUtil.Format(SessionStateStrings.GetContent_TailAndHeadCannotCoexist, "TotalCount", "Tail"); ErrorRecord error = new(new InvalidOperationException(errMsg), "TailAndHeadCannotCoexist", ErrorCategory.InvalidOperation, null); @@ -124,7 +87,7 @@ protected override void ProcessRecord() return; } - if (TotalCount == 0) + if (TotalCount == 0 || Tail == 0) { // Don't read anything return; @@ -141,11 +104,9 @@ protected override void ProcessRecord() { long countRead = 0; - Dbg.Diagnostics.Assert( - holder.Reader != null, - "All holders should have a reader assigned"); + Dbg.Diagnostics.Assert(holder.Reader != null, "All holders should have a reader assigned"); - if (_tailSpecified && holder.Reader is not FileSystemContentReaderWriter) + if (Tail != -1 && holder.Reader is not FileSystemContentReaderWriter) { string errMsg = SessionStateStrings.GetContent_TailNotSupported; ErrorRecord error = new(new InvalidOperationException(errMsg), "TailNotSupported", ErrorCategory.InvalidOperation, Tail); @@ -153,11 +114,11 @@ protected override void ProcessRecord() continue; } - // If Tail is negative, we are supposed to read all content out. This is same + // If Tail is -1, we are supposed to read all content out. This is same // as reading forwards. So we read forwards in this case. // If Tail is positive, we seek the right position. Or, if the seek failed // because of an unsupported encoding, we scan forward to get the tail content. - if (Tail >= 0) + if (Tail > 0) { bool seekSuccess = false; @@ -197,72 +158,61 @@ protected override void ProcessRecord() } } - if (TotalCount != 0) + IList results = null; + + do { - IList results = null; + long countToRead = ReadCount; - do + // Make sure we only ask for the amount the user wanted + // I am using TotalCount - countToRead so that I don't + // have to worry about overflow + if (TotalCount > 0 && (countToRead == 0 || TotalCount - countToRead < countRead)) { - long countToRead = ReadCount; + countToRead = TotalCount - countRead; + } - // Make sure we only ask for the amount the user wanted - // I am using TotalCount - countToRead so that I don't - // have to worry about overflow + try + { + results = holder.Reader.Read(countToRead); + } + catch (Exception e) // Catch-all OK. 3rd party callout + { + ProviderInvocationException providerException = + new( + "ProviderContentReadError", + SessionStateStrings.ProviderContentReadError, + holder.PathInfo.Provider, + holder.PathInfo.Path, + e); - if ((TotalCount > 0) && (countToRead == 0 || (TotalCount - countToRead < countRead))) - { - countToRead = TotalCount - countRead; - } + // Log a provider health event + MshLog.LogProviderHealthEvent(this.Context, holder.PathInfo.Provider.Name, providerException, Severity.Warning); + WriteError(new ErrorRecord(providerException.ErrorRecord, providerException)); - try - { - results = holder.Reader.Read(countToRead); - } - catch (Exception e) // Catch-all OK. 3rd party callout + break; + } + + if (results != null && results.Count > 0) + { + countRead += results.Count; + if (ReadCount == 1) { - ProviderInvocationException providerException = - new( - "ProviderContentReadError", - SessionStateStrings.ProviderContentReadError, - holder.PathInfo.Provider, - holder.PathInfo.Path, - e); - - // Log a provider health event - MshLog.LogProviderHealthEvent( - this.Context, - holder.PathInfo.Provider.Name, - providerException, - Severity.Warning); - - WriteError(new ErrorRecord( - providerException.ErrorRecord, - providerException)); - - break; + // Write out the content as a single object + WriteContentObject(results[0], countRead, holder.PathInfo, currentContext); } - - if (results != null && results.Count > 0) + else { - countRead += results.Count; - if (ReadCount == 1) - { - // Write out the content as a single object - WriteContentObject(results[0], countRead, holder.PathInfo, currentContext); - } - else - { - // Write out the content as an array of objects - WriteContentObject(results, countRead, holder.PathInfo, currentContext); - } + // Write out the content as an array of objects + WriteContentObject(results, countRead, holder.PathInfo, currentContext); } - } while (results != null && results.Count > 0 && ((TotalCount < 0) || countRead < TotalCount)); - } + } + } while (results != null && results.Count > 0 && (TotalCount == -1 || countRead < TotalCount)); } } finally { - // close all the content readers + // Close all the content readers CloseContent(contentStreams, false); @@ -284,7 +234,7 @@ private bool ScanForwardsForTail(in ContentHolder holder, CmdletProviderContext { var fsReader = holder.Reader as FileSystemContentReaderWriter; Dbg.Diagnostics.Assert(fsReader != null, "Tail is only supported for FileSystemContentReaderWriter"); - var tailResultQueue = new Queue(); + Queue tailResultQueue = new(); IList results = null; ErrorRecord error = null; @@ -327,7 +277,10 @@ private bool ScanForwardsForTail(in ContentHolder holder, CmdletProviderContext foreach (object entry in results) { if (tailResultQueue.Count == Tail) + { tailResultQueue.Dequeue(); + } + tailResultQueue.Enqueue(entry); } } @@ -349,21 +302,25 @@ private bool ScanForwardsForTail(in ContentHolder holder, CmdletProviderContext { // Write out the content as single object while (tailResultQueue.Count > 0) + { WriteContentObject(tailResultQueue.Dequeue(), count++, holder.PathInfo, currentContext); + } } else // ReadCount < Queue.Count { while (tailResultQueue.Count >= ReadCount) { - var outputList = new List((int)ReadCount); + List outputList = new((int)ReadCount); for (int idx = 0; idx < ReadCount; idx++, count++) + { outputList.Add(tailResultQueue.Dequeue()); + } + // Write out the content as an array of objects WriteContentObject(outputList.ToArray(), count, holder.PathInfo, currentContext); } - int remainder = tailResultQueue.Count; - if (remainder > 0) + if (tailResultQueue.Count > 0) { // Write out the content as an array of objects WriteContentObject(tailResultQueue.ToArray(), count, holder.PathInfo, currentContext); diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Content.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Content.Tests.ps1 index 9f42be74149..5e8e258b85a 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Content.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Content.Tests.ps1 @@ -72,6 +72,14 @@ Describe "Get-Content" -Tags "CI" { Get-Content -Path $testPath2 -Last 1 | Should -BeExactly $fifthline } + It 'Verifies -TotalCount reports a ParameterArgumentValidationError error for negative values' { + {Get-Content -Path $testPath2 -TotalCount -2} | Should -Throw -ErrorId 'ParameterArgumentValidationError,Microsoft.PowerShell.Commands.GetContentCommand' + } + + It 'Verifies -Tail reports a ParameterArgumentValidationError error for negative values' { + {Get-Content -Path $testPath2 -Tail -2} | Should -Throw -ErrorId 'ParameterArgumentValidationError,Microsoft.PowerShell.Commands.GetContentCommand' + } + It "Should be able to get content within a different drive" { Push-Location env: $expectedoutput = [Environment]::GetEnvironmentVariable("PATH"); @@ -271,6 +279,10 @@ Describe "Get-Content" -Tags "CI" { Get-Content -Path $testPath -TotalCount 0 | Should -BeNullOrEmpty } + It "Should return no content when -Tail value is 0" { + Get-Content -Path $testPath -Tail 0 | Should -BeNullOrEmpty + } + It "Should throw TailAndHeadCannotCoexist when both -Tail and -TotalCount are used" { { Get-Content -Path $testPath -Tail 1 -TotalCount 1 -ErrorAction Stop From ebe0b543408e61bc746258698d566fd95a7036a8 Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Wed, 21 Jun 2023 15:17:22 -0700 Subject: [PATCH 606/779] Update to .NET 8 Preview 4 (#19696) --- DotnetRuntimeMetadata.json | 6 +- global.json | 2 +- nuget.config | 2 +- .../ManagementList/Common/StateDescriptor.cs | 1 - .../FilterRules/ComparableValueFilterRule.cs | 1 - .../FilterRules/DoesNotEqualFilterRule.cs | 1 - .../FilterRules/EqualsFilterRule.cs | 1 - .../FilterCore/FilterRules/FilterRule.cs | 6 - .../FilterRules/FilterRuleExtensions.cs | 26 +-- .../FilterRules/IsBetweenFilterRule.cs | 1 - .../FilterRules/IsEmptyFilterRule.cs | 1 - .../FilterRules/IsGreaterThanFilterRule.cs | 1 - .../FilterRules/IsLessThanFilterRule.cs | 1 - .../FilterRules/IsNotEmptyFilterRule.cs | 1 - .../FilterRules/IsNotEmptyValidationRule.cs | 1 - .../PropertiesTextContainsFilterRule.cs | 1 - .../PropertyValueSelectorFilterRule.cs | 1 - .../FilterRules/SelectorFilterRule.cs | 1 - .../SingleValueComparableValueFilterRule.cs | 1 - .../FilterRules/TextContainsFilterRule.cs | 1 - .../TextDoesNotContainFilterRule.cs | 1 - .../FilterRules/TextDoesNotEqualFilterRule.cs | 1 - .../FilterRules/TextEndsWithFilterRule.cs | 1 - .../FilterRules/TextEqualsFilterRule.cs | 1 - .../FilterCore/FilterRules/TextFilterRule.cs | 1 - .../FilterRules/TextStartsWithFilterRule.cs | 1 - .../FilterCore/ValidatingSelectorValue.cs | 6 - .../FilterCore/ValidatingValue.cs | 1 - .../FilterCore/ValidatingValueBase.cs | 1 - .../DataErrorInfoValidationRule.cs | 1 - .../FilterRuleToDisplayNameConverter.cs | 1 - .../ManagementListStateDescriptor.cs | 3 - ...oft.PowerShell.Commands.Diagnostics.csproj | 2 +- ...soft.PowerShell.Commands.Management.csproj | 2 +- .../cmdletization/cim/CimJobException.cs | 21 +-- .../commands/management/Computer.cs | 45 ----- .../commands/management/Process.cs | 19 +-- .../commands/management/Service.cs | 18 +- ...crosoft.PowerShell.Commands.Utility.csproj | 6 +- .../commands/utility/Write.cs | 6 +- .../host/msh/ConsoleHost.cs | 9 - ...crosoft.PowerShell.CoreCLR.Eventing.csproj | 2 +- .../Microsoft.PowerShell.SDK.csproj | 8 +- .../ScheduledJob.cs | 5 - .../ScheduledJobDefinition.cs | 2 - .../ScheduledJobTrigger.cs | 1 - .../security/certificateproviderexceptions.cs | 78 ++++----- .../Microsoft.WSMan.Management.csproj | 2 +- .../common/DisplayDatabase/FormatTable.cs | 48 +----- .../System.Management.Automation.csproj | 16 +- .../engine/ErrorPackage.cs | 2 - .../engine/ExtendedTypeSystemException.cs | 58 ++----- .../engine/ExternalScriptInfo.cs | 1 - .../engine/Modules/ScriptAnalysis.cs | 2 - .../engine/MshObject.cs | 1 - .../engine/MshSecurityException.cs | 13 +- .../engine/NativeCommandProcessor.cs | 42 +---- .../engine/OrderedHashtable.cs | 10 -- .../engine/PseudoParameters.cs | 1 - .../engine/TypeTable.cs | 47 +----- .../engine/hostifaces/Connection.cs | 4 +- .../engine/hostifaces/LocalConnection.cs | 23 +-- .../engine/hostifaces/PSDataCollection.cs | 1 - .../engine/hostifaces/Pipeline.cs | 4 +- .../engine/hostifaces/PowerShell.cs | 4 +- .../engine/hostifaces/RunspacePool.cs | 4 +- .../engine/interpreter/LightCompiler.cs | 2 - .../engine/lang/parserutils.cs | 26 --- .../engine/lang/scriptblock.cs | 4 +- .../engine/regex.cs | 4 +- .../engine/remoting/client/Job.cs | 4 +- .../engine/remoting/client/Job2.cs | 21 +-- .../remoting/client/JobSourceAdapter.cs | 2 - .../remoting/client/RemotingErrorRecord.cs | 25 +-- .../WireDataFormat/RemoteHostEncoder.cs | 3 +- .../remoting/common/remotingexceptions.cs | 65 +------- .../engine/remoting/fanin/PSPrincipal.cs | 1 - .../engine/runtime/CompiledScriptBlock.cs | 51 +----- .../engine/serialization.cs | 1 - .../help/HelpCategoryInvalidException.cs | 26 +-- .../help/HelpNotFoundException.cs | 26 +-- .../help/UpdatableHelpSystem.cs | 1 - .../config/MshConsoleLoadException.cs | 1 - .../config/MshSnapinLoadException.cs | 26 +-- .../utils/CommandDiscoveryExceptions.cs | 65 +------- .../utils/CommandProcessorExceptions.cs | 4 +- .../utils/CryptoUtils.cs | 26 +-- .../utils/ExecutionExceptions.cs | 156 ++++-------------- .../utils/HostInterfacesExceptions.cs | 10 +- .../utils/MetadataExceptions.cs | 26 ++- .../utils/MshArgumentException.cs | 22 +-- .../utils/MshArgumentNullException.cs | 25 +-- .../utils/MshArgumentOutOfRangeException.cs | 22 +-- .../utils/MshInvalidOperationException.cs | 21 +-- .../utils/MshNotImplementedException.cs | 23 +-- .../utils/MshNotSupportedException.cs | 22 +-- .../utils/MshObjectDisposedException.cs | 23 +-- .../utils/ParameterBinderExceptions.cs | 47 ++---- .../utils/ParserException.cs | 23 +-- .../utils/RuntimeException.cs | 25 +-- .../utils/SessionStateExceptions.cs | 92 +++-------- .../Basic/StandardLibraryTypes.Tests.ps1 | 1 - ...soft.PowerShell.NamedPipeConnection.csproj | 2 +- test/tools/TestService/TestService.csproj | 2 +- test/tools/WebListener/WebListener.csproj | 4 +- tools/packaging/boms/windows.json | 62 +++---- 106 files changed, 293 insertions(+), 1282 deletions(-) diff --git a/DotnetRuntimeMetadata.json b/DotnetRuntimeMetadata.json index e5d2c716694..ec1bbd6bdd5 100644 --- a/DotnetRuntimeMetadata.json +++ b/DotnetRuntimeMetadata.json @@ -1,11 +1,11 @@ { "sdk": { - "channel": "8.0.1xx-preview3", + "channel": "8.0.1xx-preview4", "quality": "daily", "qualityFallback": "preview", - "packageVersionPattern": "8.0.0-preview.3", + "packageVersionPattern": "8.0.0-preview.4", "sdkImageVersion": "8.0.100", - "nextChannel": "8.0.1xx-preview3", + "nextChannel": "8.0.1xx-preview4", "azureFeed": "", "sdkImageOverride": "" }, diff --git a/global.json b/global.json index 1a6ad4fbb96..8f4a0391bfd 100644 --- a/global.json +++ b/global.json @@ -1,5 +1,5 @@ { "sdk": { - "version": "8.0.100-preview.3.23178.7" + "version": "8.0.100-preview.4.23260.5" } } diff --git a/nuget.config b/nuget.config index b81fddb0e30..5137d0c33d6 100644 --- a/nuget.config +++ b/nuget.config @@ -2,7 +2,7 @@ - + diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/StateDescriptor.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/StateDescriptor.cs index be8cc841757..b1a82c0d079 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/StateDescriptor.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/StateDescriptor.cs @@ -12,7 +12,6 @@ namespace Microsoft.Management.UI.Internal /// Base proxy class for other classes which wish to have save and restore functionality. /// /// There are no restrictions on T. - [Serializable] [SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public abstract class StateDescriptor { diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/ComparableValueFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/ComparableValueFilterRule.cs index e75cd59f17a..1c689643f54 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/ComparableValueFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/ComparableValueFilterRule.cs @@ -12,7 +12,6 @@ namespace Microsoft.Management.UI.Internal /// /// The generic parameter. /// - [Serializable] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public abstract class ComparableValueFilterRule : FilterRule where T : IComparable { diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/DoesNotEqualFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/DoesNotEqualFilterRule.cs index ea74ee062f9..636e76e5c86 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/DoesNotEqualFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/DoesNotEqualFilterRule.cs @@ -12,7 +12,6 @@ namespace Microsoft.Management.UI.Internal /// /// The generic parameter. /// - [Serializable] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public class DoesNotEqualFilterRule : EqualsFilterRule where T : IComparable { diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/EqualsFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/EqualsFilterRule.cs index 5f21f57292b..1661b11d9fb 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/EqualsFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/EqualsFilterRule.cs @@ -13,7 +13,6 @@ namespace Microsoft.Management.UI.Internal /// /// The generic parameter. /// - [Serializable] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public class EqualsFilterRule : SingleValueComparableValueFilterRule where T : IComparable { diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/FilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/FilterRule.cs index 89b31449ba6..3309f33f4a0 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/FilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/FilterRule.cs @@ -9,7 +9,6 @@ namespace Microsoft.Management.UI.Internal /// /// The base class for all filtering rules. /// - [Serializable] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public abstract class FilterRule : IEvaluate { @@ -39,11 +38,6 @@ public string DisplayName /// protected FilterRule() { - // HACK : Is there a way to statically enforce this? No... not ISerializable... - if (!this.GetType().IsSerializable) - { - throw new InvalidOperationException("FilterRules must be serializable."); - } } /// diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/FilterRuleExtensions.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/FilterRuleExtensions.cs index ce8728c873e..76f10f0e22c 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/FilterRuleExtensions.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/FilterRuleExtensions.cs @@ -27,31 +27,7 @@ public static class FilterRuleExtensions /// public static FilterRule DeepCopy(this FilterRule rule) { - ArgumentNullException.ThrowIfNull(rule); - - Debug.Assert(rule.GetType().IsSerializable, "rule is serializable"); - - BinaryFormatter formatter = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.Clone)); - MemoryStream ms = new MemoryStream(); - - FilterRule copy = null; - try - { -#pragma warning disable SYSLIB0011 - formatter.Serialize(ms, rule); -#pragma warning restore SYSLIB0011 - - ms.Position = 0; -#pragma warning disable SYSLIB0011 - copy = (FilterRule)formatter.Deserialize(ms); -#pragma warning restore SYSLIB0011 - } - finally - { - ms.Close(); - } - - return copy; + throw new NotSupportedException(); } } } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsBetweenFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsBetweenFilterRule.cs index b54508157a6..3acced159c7 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsBetweenFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsBetweenFilterRule.cs @@ -15,7 +15,6 @@ namespace Microsoft.Management.UI.Internal /// /// The generic parameter. /// - [Serializable] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public class IsBetweenFilterRule : ComparableValueFilterRule where T : IComparable { diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsEmptyFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsEmptyFilterRule.cs index 8e8b91087ef..21b78e4e161 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsEmptyFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsEmptyFilterRule.cs @@ -9,7 +9,6 @@ namespace Microsoft.Management.UI.Internal /// The IsEmptyFilterRule evaluates an item to determine whether it /// is empty or not. /// - [Serializable] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public class IsEmptyFilterRule : FilterRule { diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsGreaterThanFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsGreaterThanFilterRule.cs index bd9af169e82..94b3170c5a1 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsGreaterThanFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsGreaterThanFilterRule.cs @@ -13,7 +13,6 @@ namespace Microsoft.Management.UI.Internal /// /// The generic parameter. /// - [Serializable] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public class IsGreaterThanFilterRule : SingleValueComparableValueFilterRule where T : IComparable { diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsLessThanFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsLessThanFilterRule.cs index db3bc01f810..7fc732ebbd7 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsLessThanFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsLessThanFilterRule.cs @@ -13,7 +13,6 @@ namespace Microsoft.Management.UI.Internal /// /// The generic parameter. /// - [Serializable] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public class IsLessThanFilterRule : SingleValueComparableValueFilterRule where T : IComparable { diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsNotEmptyFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsNotEmptyFilterRule.cs index c9bfc7519a0..1811e18bcdd 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsNotEmptyFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsNotEmptyFilterRule.cs @@ -9,7 +9,6 @@ namespace Microsoft.Management.UI.Internal /// The IsNotEmptyFilterRule evaluates an item to determine whether it /// is empty or not. /// - [Serializable] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public class IsNotEmptyFilterRule : IsEmptyFilterRule { diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsNotEmptyValidationRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsNotEmptyValidationRule.cs index 924ffc02af8..83734f42f76 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsNotEmptyValidationRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsNotEmptyValidationRule.cs @@ -8,7 +8,6 @@ namespace Microsoft.Management.UI.Internal /// /// The IsNotEmptyValidationRule checks a value to see if a value is not empty. /// - [Serializable] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public class IsNotEmptyValidationRule : DataErrorInfoValidationRule { diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/PropertiesTextContainsFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/PropertiesTextContainsFilterRule.cs index c29715419ce..d9992cd626a 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/PropertiesTextContainsFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/PropertiesTextContainsFilterRule.cs @@ -11,7 +11,6 @@ namespace Microsoft.Management.UI.Internal /// /// Represents a filter rule that searches for text within properties on an object. /// - [Serializable] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public class PropertiesTextContainsFilterRule : TextFilterRule { diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/PropertyValueSelectorFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/PropertyValueSelectorFilterRule.cs index 9143336aa4c..74b8d2a8695 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/PropertyValueSelectorFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/PropertyValueSelectorFilterRule.cs @@ -15,7 +15,6 @@ namespace Microsoft.Management.UI.Internal /// /// The generic parameter. /// - [Serializable] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public class PropertyValueSelectorFilterRule : SelectorFilterRule where T : IComparable { diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/SelectorFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/SelectorFilterRule.cs index c67b1c993e5..e2430dde6db 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/SelectorFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/SelectorFilterRule.cs @@ -9,7 +9,6 @@ namespace Microsoft.Management.UI.Internal /// /// The SelectorFilterRule represents a rule composed of other rules. /// - [Serializable] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public class SelectorFilterRule : FilterRule { diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/SingleValueComparableValueFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/SingleValueComparableValueFilterRule.cs index 5aaabe58bfb..526f53f8613 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/SingleValueComparableValueFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/SingleValueComparableValueFilterRule.cs @@ -12,7 +12,6 @@ namespace Microsoft.Management.UI.Internal /// that take a single input and evaluate against IComparable values. /// /// The generic parameter. - [Serializable] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public abstract class SingleValueComparableValueFilterRule : ComparableValueFilterRule where T : IComparable { diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextContainsFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextContainsFilterRule.cs index 9186827c5f5..b41cc901857 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextContainsFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextContainsFilterRule.cs @@ -10,7 +10,6 @@ namespace Microsoft.Management.UI.Internal /// The TextContainsFilterRule class evaluates a string item to /// check if it is contains the rule's value within it. /// - [Serializable] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public class TextContainsFilterRule : TextFilterRule { diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextDoesNotContainFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextDoesNotContainFilterRule.cs index dcfeabff4c4..dc077f6a2b4 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextDoesNotContainFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextDoesNotContainFilterRule.cs @@ -9,7 +9,6 @@ namespace Microsoft.Management.UI.Internal /// The TextDoesNotContainFilterRule class evaluates a string item to /// check if it is does not contain the rule's value within it. /// - [Serializable] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public class TextDoesNotContainFilterRule : TextContainsFilterRule { diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextDoesNotEqualFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextDoesNotEqualFilterRule.cs index 3666b17c2de..c211c6d9d1c 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextDoesNotEqualFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextDoesNotEqualFilterRule.cs @@ -9,7 +9,6 @@ namespace Microsoft.Management.UI.Internal /// The TextDoesNotEqualFilterRule class evaluates a string item to /// check if it is not equal to the rule's value. /// - [Serializable] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public class TextDoesNotEqualFilterRule : TextEqualsFilterRule { diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextEndsWithFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextEndsWithFilterRule.cs index 45a9dd85386..e369a1dbcc7 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextEndsWithFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextEndsWithFilterRule.cs @@ -10,7 +10,6 @@ namespace Microsoft.Management.UI.Internal /// The TextEndsWithFilterRule class evaluates a string item to /// check if it ends with the rule's value. /// - [Serializable] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public class TextEndsWithFilterRule : TextFilterRule { diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextEqualsFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextEqualsFilterRule.cs index 6401506bf1d..fdf8cc09163 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextEqualsFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextEqualsFilterRule.cs @@ -10,7 +10,6 @@ namespace Microsoft.Management.UI.Internal /// The TextEqualsFilterRule class evaluates a string item to /// check if it is equal to the rule's value. /// - [Serializable] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public class TextEqualsFilterRule : TextFilterRule { diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextFilterRule.cs index ad1f2949972..ef08d644dcf 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextFilterRule.cs @@ -13,7 +13,6 @@ namespace Microsoft.Management.UI.Internal /// The TextFilterRule class supports derived rules by offering services for /// evaluating string operations. /// - [Serializable] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public abstract class TextFilterRule : SingleValueComparableValueFilterRule { diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextStartsWithFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextStartsWithFilterRule.cs index 8cfdc7960d8..db9bb5d5610 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextStartsWithFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextStartsWithFilterRule.cs @@ -10,7 +10,6 @@ namespace Microsoft.Management.UI.Internal /// The TextStartsWithFilterRule class evaluates a string item to /// check if it starts with the rule's value. /// - [Serializable] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public class TextStartsWithFilterRule : TextFilterRule { diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingSelectorValue.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingSelectorValue.cs index 9b72d5848ec..5f21c186bee 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingSelectorValue.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingSelectorValue.cs @@ -16,7 +16,6 @@ namespace Microsoft.Management.UI.Internal /// /// The generic parameter. /// - [Serializable] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public class ValidatingSelectorValue : ValidatingValueBase { @@ -131,11 +130,6 @@ public IValueConverter DisplayNameConverter set { - if (value != null && !value.GetType().IsSerializable) - { - throw new ArgumentException("The DisplayNameConverter must be serializable.", "value"); - } - this.displayNameConverter = value; } } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValue.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValue.cs index beb139b0131..49f16407318 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValue.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValue.cs @@ -14,7 +14,6 @@ namespace Microsoft.Management.UI.Internal /// /// The generic parameter. /// - [Serializable] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public class ValidatingValue : ValidatingValueBase { diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValueBase.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValueBase.cs index fc2b331f583..0ead40919da 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValueBase.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValueBase.cs @@ -15,7 +15,6 @@ namespace Microsoft.Management.UI.Internal /// The ValidatingValueBase class provides basic services for base /// classes to support validation via the IDataErrorInfo interface. /// - [Serializable] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public abstract class ValidatingValueBase : IDataErrorInfo, INotifyPropertyChanged { diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidationRules/DataErrorInfoValidationRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidationRules/DataErrorInfoValidationRule.cs index 9b4a2b23d0d..162de593a88 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidationRules/DataErrorInfoValidationRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidationRules/DataErrorInfoValidationRule.cs @@ -8,7 +8,6 @@ namespace Microsoft.Management.UI.Internal /// /// Provides a way to create a custom rule in order to check the validity of user input. /// - [Serializable] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public abstract class DataErrorInfoValidationRule { diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRuleToDisplayNameConverter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRuleToDisplayNameConverter.cs index 07a4ed58f8b..972c19080e0 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRuleToDisplayNameConverter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRuleToDisplayNameConverter.cs @@ -11,7 +11,6 @@ namespace Microsoft.Management.UI.Internal /// The FilterRuleToDisplayNameConverter is responsible for converting /// a FilterRule value to its DisplayName. /// - [Serializable] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public class FilterRuleToDisplayNameConverter : IValueConverter { diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ManagementListStateDescriptor.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ManagementListStateDescriptor.cs index 93e035f7bc5..9798804bd80 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ManagementListStateDescriptor.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ManagementListStateDescriptor.cs @@ -15,7 +15,6 @@ namespace Microsoft.Management.UI.Internal /// /// Allows the state of the ManagementList to be saved and restored. /// - [Serializable] [SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public class ManagementListStateDescriptor : StateDescriptor { @@ -465,7 +464,6 @@ private static void SetColumnWidth(GridViewColumn ilc, double width) #region Helper Classes - [Serializable] internal class ColumnStateDescriptor { private int index; @@ -510,7 +508,6 @@ public double Width } } - [Serializable] internal class RuleStateDescriptor { /// diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/Microsoft.PowerShell.Commands.Diagnostics.csproj b/src/Microsoft.PowerShell.Commands.Diagnostics/Microsoft.PowerShell.Commands.Diagnostics.csproj index 46f8b45199c..65e3f593709 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/Microsoft.PowerShell.Commands.Diagnostics.csproj +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/Microsoft.PowerShell.Commands.Diagnostics.csproj @@ -8,7 +8,7 @@ - + diff --git a/src/Microsoft.PowerShell.Commands.Management/Microsoft.PowerShell.Commands.Management.csproj b/src/Microsoft.PowerShell.Commands.Management/Microsoft.PowerShell.Commands.Management.csproj index d5325a78bbc..9a44cc58573 100644 --- a/src/Microsoft.PowerShell.Commands.Management/Microsoft.PowerShell.Commands.Management.csproj +++ b/src/Microsoft.PowerShell.Commands.Management/Microsoft.PowerShell.Commands.Management.csproj @@ -47,7 +47,7 @@ - + diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs index b4d4a7bbbe7..675c6c71404 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs @@ -15,7 +15,6 @@ namespace Microsoft.PowerShell.Cmdletization.Cim /// /// Represents an error during execution of a CIM job. /// - [Serializable] public class CimJobException : SystemException, IContainsErrorRecord { #region Standard constructors and methods required for all exceptions @@ -50,26 +49,12 @@ public CimJobException(string message, Exception inner) : base(message, inner) /// /// The that holds the serialized object data about the exception being thrown. /// The that contains contextual information about the source or destination. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected CimJobException( SerializationInfo info, - StreamingContext context) : base(info, context) + StreamingContext context) { - ArgumentNullException.ThrowIfNull(info); - - _errorRecord = (ErrorRecord)info.GetValue("errorRecord", typeof(ErrorRecord)); - } - - /// - /// Sets the SerializationInfo with information about the exception. - /// - /// The that holds the serialized object data about the exception being thrown. - /// The that contains contextual information about the source or destination. - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - ArgumentNullException.ThrowIfNull(info); - - base.GetObjectData(info, context); - info.AddValue("errorRecord", _errorRecord); + throw new NotSupportedException(); } #endregion diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs index e24c49b63f7..2203c920c1e 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs @@ -35,7 +35,6 @@ namespace Microsoft.PowerShell.Commands /// /// This exception is thrown when the timeout expires before a computer finishes restarting. /// - [Serializable] public sealed class RestartComputerTimeoutException : RuntimeException { /// @@ -87,50 +86,6 @@ public RestartComputerTimeoutException(string message) : base(message) { } /// An exception that led to this exception. /// public RestartComputerTimeoutException(string message, Exception innerException) : base(message, innerException) { } - - #region Serialization - /// - /// Serialization constructor for class RestartComputerTimeoutException. - /// - /// - /// serialization information - /// - /// - /// streaming context - /// - private RestartComputerTimeoutException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - if (info == null) - { - throw new PSArgumentNullException(nameof(info)); - } - - ComputerName = info.GetString("ComputerName"); - Timeout = info.GetInt32("Timeout"); - } - - /// - /// Serializes the RestartComputerTimeoutException. - /// - /// - /// serialization information - /// - /// - /// streaming context - /// - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw new PSArgumentNullException(nameof(info)); - } - - base.GetObjectData(info, context); - info.AddValue("ComputerName", ComputerName); - info.AddValue("Timeout", Timeout); - } - #endregion Serialization } /// diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs index 047aada0edd..73f18cea9e3 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs @@ -2952,7 +2952,6 @@ protected override bool ReleaseHandle() /// /// Non-terminating errors occurring in the process noun commands. /// - [Serializable] public class ProcessCommandException : SystemException { #region ctors @@ -2992,28 +2991,14 @@ public ProcessCommandException(string message, Exception innerException) /// /// /// Constructed object. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected ProcessCommandException( SerializationInfo info, StreamingContext context) - : base(info, context) { - _processName = info.GetString("ProcessName"); + throw new NotSupportedException(); } - /// - /// Serializer. - /// - /// Serialization information. - /// Streaming context. - public override void GetObjectData( - SerializationInfo info, - StreamingContext context) - { - base.GetObjectData(info, context); - - ArgumentNullException.ThrowIfNull(info); - info.AddValue("ProcessName", _processName); - } #endregion Serialization #region Properties diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs index a9cba537a5a..1d007e6dac0 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs @@ -2519,7 +2519,6 @@ protected override void ProcessRecord() /// /// Non-terminating errors occurring in the service noun commands. /// - [Serializable] public class ServiceCommandException : SystemException { #region ctors @@ -2561,25 +2560,12 @@ public ServiceCommandException(string message, Exception innerException) /// /// /// Constructed object. + [Obsolete("Legacy serialization support is deprecated since .NET 8, hence this method is now marked as obsolete", DiagnosticId = "SYSLIB0051")] protected ServiceCommandException(SerializationInfo info, StreamingContext context) - : base(info, context) { - ArgumentNullException.ThrowIfNull(info); - - _serviceName = info.GetString("ServiceName"); + throw new NotSupportedException(); } - /// - /// Serializer. - /// - /// Serialization information. - /// Streaming context. - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - ArgumentNullException.ThrowIfNull(info); - base.GetObjectData(info, context); - info.AddValue("ServiceName", _serviceName); - } #endregion Serialization #region Properties diff --git a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj index 403df5d5cb8..5afbfea5a35 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj +++ b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj @@ -32,9 +32,9 @@ - - - + + + diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write.cs index b75c6be8735..d20d7d8712b 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write.cs @@ -222,7 +222,7 @@ public class WriteOrThrowErrorCommand : PSCmdlet /// [Parameter(Position = 0, ParameterSetName = "ErrorRecord", Mandatory = true)] public ErrorRecord ErrorRecord { get; set; } - + /// /// ErrorRecord.CategoryInfo.Category. /// @@ -409,7 +409,6 @@ public ThrowErrorCommand() /// when the user only specifies a string and not /// an Exception or ErrorRecord. /// - [Serializable] public class WriteErrorException : SystemException { #region ctor @@ -452,10 +451,11 @@ public WriteErrorException(string message, /// Serialization information. /// Streaming context. /// Constructed object. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected WriteErrorException(SerializationInfo info, StreamingContext context) - : base(info, context) { + throw new NotSupportedException(); } #endregion Serialization } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs index cd9c682d1b2..67912e1a387 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs @@ -2984,7 +2984,6 @@ private string EvaluateDebugPrompt() private static readonly Stack s_instanceStack = new Stack(); } - [Serializable] [SuppressMessage("Microsoft.Design", "CA1064:ExceptionsShouldBePublic", Justification = "This exception cannot be used outside of the console host application. It is not thrown by a library routine, only by an application.")] private sealed class ConsoleHostStartupException : Exception @@ -3001,14 +3000,6 @@ private sealed class ConsoleHostStartupException : Exception { } - private - ConsoleHostStartupException( - System.Runtime.Serialization.SerializationInfo info, - System.Runtime.Serialization.StreamingContext context) - : base(info, context) - { - } - internal ConsoleHostStartupException(string message, Exception innerException) : base(message, innerException) diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/Microsoft.PowerShell.CoreCLR.Eventing.csproj b/src/Microsoft.PowerShell.CoreCLR.Eventing/Microsoft.PowerShell.CoreCLR.Eventing.csproj index c4c4e4ed923..2e1be837d86 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/Microsoft.PowerShell.CoreCLR.Eventing.csproj +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/Microsoft.PowerShell.CoreCLR.Eventing.csproj @@ -8,7 +8,7 @@ - + diff --git a/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj b/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj index 5767001acac..c821b97de3e 100644 --- a/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj +++ b/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj @@ -19,9 +19,9 @@ - - - + + + @@ -30,7 +30,7 @@ - + diff --git a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJob.cs b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJob.cs index 59403d88520..05208e1cbab 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJob.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJob.cs @@ -24,7 +24,6 @@ namespace Microsoft.PowerShell.ScheduledJob /// the scheduled job and so can run an instance of the scheduled /// job and optionally save results to file. /// - [Serializable] public sealed class ScheduledJob : Job2, ISerializable { #region Private Members @@ -957,8 +956,6 @@ private void RemoveSetShouldExitFromHost() #endregion #region Private ResultsInfo class - - [Serializable] private sealed class ResultsInfo : ISerializable { // Private Members @@ -1112,8 +1109,6 @@ public void GetObjectData( } #region Internal StatusInfo Class - - [Serializable] internal class StatusInfo : ISerializable { // Private Members diff --git a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobDefinition.cs b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobDefinition.cs index ecb4fc9caa6..bfe2e87f6ee 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobDefinition.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobDefinition.cs @@ -20,7 +20,6 @@ namespace Microsoft.PowerShell.ScheduledJob /// can be scheduled to run through either stand-alone or through the Windows /// Task Scheduler. /// - [Serializable] public sealed class ScheduledJobDefinition : ISerializable, IDisposable { #region Private Members @@ -2241,7 +2240,6 @@ public void Clear() /// /// Exception thrown for errors in Scheduled Jobs. /// - [Serializable] public class ScheduledJobException : SystemException { /// diff --git a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobTrigger.cs b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobTrigger.cs index 7bb4977b79d..0f40ded9f95 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobTrigger.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobTrigger.cs @@ -19,7 +19,6 @@ namespace Microsoft.PowerShell.ScheduledJob /// This class contains parameters used to define how/when a PowerShell job is /// run via the Windows Task Scheduler (WTS). /// - [Serializable] public sealed class ScheduledJobTrigger : ISerializable { #region Private Members diff --git a/src/Microsoft.PowerShell.Security/security/certificateproviderexceptions.cs b/src/Microsoft.PowerShell.Security/security/certificateproviderexceptions.cs index efd205e5769..6d602d2d99f 100644 --- a/src/Microsoft.PowerShell.Security/security/certificateproviderexceptions.cs +++ b/src/Microsoft.PowerShell.Security/security/certificateproviderexceptions.cs @@ -12,7 +12,6 @@ namespace Microsoft.PowerShell.Commands /// Defines the base class for exceptions thrown by the /// certificate provider when the specified item cannot be located. /// - [Serializable] public class CertificateProviderItemNotFoundException : SystemException { /// @@ -60,10 +59,11 @@ public CertificateProviderItemNotFoundException(string message, /// /// The streaming context. /// + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected CertificateProviderItemNotFoundException(SerializationInfo info, - StreamingContext context) - : base(info, context) + StreamingContext context) { + throw new NotSupportedException(); } /// @@ -83,7 +83,6 @@ internal CertificateProviderItemNotFoundException(Exception innerException) /// Defines the exception thrown by the certificate provider /// when the specified X509 certificate cannot be located. /// - [Serializable] public class CertificateNotFoundException : CertificateProviderItemNotFoundException { @@ -134,10 +133,11 @@ public CertificateNotFoundException(string message, /// /// The streaming context. /// + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected CertificateNotFoundException(SerializationInfo info, StreamingContext context) - : base(info, context) { + throw new NotSupportedException(); } /// @@ -157,7 +157,6 @@ internal CertificateNotFoundException(Exception innerException) /// Defines the exception thrown by the certificate provider /// when the specified X509 store cannot be located. /// - [Serializable] public class CertificateStoreNotFoundException : CertificateProviderItemNotFoundException { @@ -170,6 +169,23 @@ public CertificateStoreNotFoundException() { } + /// + /// Initializes a new instance of the CertificateStoreNotFoundException + /// class with the specified serialization information, and context. + /// + /// + /// The serialization information. + /// + /// + /// The streaming context. + /// + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] + protected CertificateStoreNotFoundException(SerializationInfo info, + StreamingContext context) + { + throw new NotSupportedException(); + } + /// /// Initializes a new instance of the CertificateStoreNotFoundException /// class with the specified message. @@ -198,22 +214,6 @@ public CertificateStoreNotFoundException(string message, { } - /// - /// Initializes a new instance of the CertificateStoreNotFoundException - /// class with the specified serialization information, and context. - /// - /// - /// The serialization information. - /// - /// - /// The streaming context. - /// - protected CertificateStoreNotFoundException(SerializationInfo info, - StreamingContext context) - : base(info, context) - { - } - /// /// Initializes a new instance of the CertificateStoreNotFoundException /// class with the specified inner exception. @@ -231,7 +231,6 @@ internal CertificateStoreNotFoundException(Exception innerException) /// Defines the exception thrown by the certificate provider /// when the specified X509 store location cannot be located. /// - [Serializable] public class CertificateStoreLocationNotFoundException : CertificateProviderItemNotFoundException { @@ -244,6 +243,23 @@ public CertificateStoreLocationNotFoundException() { } + /// + /// Initializes a new instance of the CertificateStoreLocationNotFoundException + /// class with the specified serialization information, and context. + /// + /// + /// The serialization information. + /// + /// + /// The streaming context. + /// + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] + protected CertificateStoreLocationNotFoundException(SerializationInfo info, + StreamingContext context) + { + throw new NotSupportedException(); + } + /// /// Initializes a new instance of the CertificateStoreLocationNotFoundException /// class with the specified message. @@ -272,22 +288,6 @@ public CertificateStoreLocationNotFoundException(string message, { } - /// - /// Initializes a new instance of the CertificateStoreLocationNotFoundException - /// class with the specified serialization information, and context. - /// - /// - /// The serialization information. - /// - /// - /// The streaming context. - /// - protected CertificateStoreLocationNotFoundException(SerializationInfo info, - StreamingContext context) - : base(info, context) - { - } - /// /// Initializes a new instance of the CertificateStoreLocationNotFoundException /// class with the specified inner exception. diff --git a/src/Microsoft.WSMan.Management/Microsoft.WSMan.Management.csproj b/src/Microsoft.WSMan.Management/Microsoft.WSMan.Management.csproj index 50ad75c44ac..350095fee95 100644 --- a/src/Microsoft.WSMan.Management/Microsoft.WSMan.Management.csproj +++ b/src/Microsoft.WSMan.Management/Microsoft.WSMan.Management.csproj @@ -10,7 +10,7 @@ - + diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/FormatTable.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/FormatTable.cs index a3959a14cd3..a1e34424950 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/FormatTable.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/FormatTable.cs @@ -20,8 +20,7 @@ namespace System.Management.Automation.Runspaces /// /// This exception is used by Formattable constructor to indicate errors /// occurred during construction time. - /// - [Serializable] + /// [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "FormatTable")] public class FormatTableLoadException : RuntimeException { @@ -84,55 +83,14 @@ internal FormatTableLoadException(ConcurrentBag loadErrors) /// /// /// + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected FormatTableLoadException(SerializationInfo info, StreamingContext context) - : base(info, context) { - if (info == null) - { - throw new PSArgumentNullException(nameof(info)); - } - - int errorCount = info.GetInt32("ErrorCount"); - if (errorCount > 0) - { - _errors = new Collection(); - for (int index = 0; index < errorCount; index++) - { - string key = string.Create(CultureInfo.InvariantCulture, $"Error{index}"); - _errors.Add(info.GetString(key)); - } - } + throw new NotSupportedException(); } #endregion Constructors - /// - /// Serializes the exception data. - /// - /// Serialization information. - /// Streaming context. - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw new PSArgumentNullException(nameof(info)); - } - - base.GetObjectData(info, context); - // If there are simple fields, serialize them with info.AddValue - if (_errors != null) - { - int errorCount = _errors.Count; - info.AddValue("ErrorCount", errorCount); - - for (int index = 0; index < errorCount; index++) - { - string key = string.Create(CultureInfo.InvariantCulture, $"Error{index}"); - info.AddValue(key, _errors[index]); - } - } - } - /// /// Set the default ErrorRecord. /// diff --git a/src/System.Management.Automation/System.Management.Automation.csproj b/src/System.Management.Automation/System.Management.Automation.csproj index bff75e77480..7e6121f4163 100644 --- a/src/System.Management.Automation/System.Management.Automation.csproj +++ b/src/System.Management.Automation/System.Management.Automation.csproj @@ -34,16 +34,16 @@ - - - - + + + + - + - - - + + + diff --git a/src/System.Management.Automation/engine/ErrorPackage.cs b/src/System.Management.Automation/engine/ErrorPackage.cs index e802d376a14..2bca96372a7 100644 --- a/src/System.Management.Automation/engine/ErrorPackage.cs +++ b/src/System.Management.Automation/engine/ErrorPackage.cs @@ -523,7 +523,6 @@ internal static string Ellipsize(CultureInfo uiCultureInfo, string original) /// It is permitted to subclass /// but there is no established scenario for doing this, nor has it been tested. /// - [Serializable] public class ErrorDetails : ISerializable { #region Constructor @@ -982,7 +981,6 @@ private string BuildMessage( /// . /// rather than the actual exception, to avoid the mutual references. /// - [Serializable] public class ErrorRecord : ISerializable { #region Constructor diff --git a/src/System.Management.Automation/engine/ExtendedTypeSystemException.cs b/src/System.Management.Automation/engine/ExtendedTypeSystemException.cs index 854482e3f6f..06271728e00 100644 --- a/src/System.Management.Automation/engine/ExtendedTypeSystemException.cs +++ b/src/System.Management.Automation/engine/ExtendedTypeSystemException.cs @@ -10,7 +10,6 @@ namespace System.Management.Automation /// /// Defines the exception thrown for all Extended type system related errors. /// - [Serializable] public class ExtendedTypeSystemException : RuntimeException { #region ctor @@ -67,8 +66,9 @@ internal ExtendedTypeSystemException( /// /// Serialization information. /// Streaming context. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected ExtendedTypeSystemException(SerializationInfo info, StreamingContext context) - : base(info, context) + : base(info, context) { } #endregion Serialization @@ -80,7 +80,6 @@ protected ExtendedTypeSystemException(SerializationInfo info, StreamingContext c /// /// Defines the exception thrown for Method related errors. /// - [Serializable] public class MethodException : ExtendedTypeSystemException { internal const string MethodArgumentCountExceptionMsg = "MethodArgumentCountException"; @@ -140,9 +139,10 @@ internal MethodException( /// /// Serialization information. /// Streaming context. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected MethodException(SerializationInfo info, StreamingContext context) - : base(info, context) { + throw new NotSupportedException(); } #endregion Serialization @@ -153,7 +153,6 @@ protected MethodException(SerializationInfo info, StreamingContext context) /// /// Defines the exception thrown for Method invocation exceptions. /// - [Serializable] public class MethodInvocationException : MethodException { internal const string MethodInvocationExceptionMsg = "MethodInvocationException"; @@ -211,9 +210,10 @@ internal MethodInvocationException( /// /// Serialization information. /// Streaming context. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected MethodInvocationException(SerializationInfo info, StreamingContext context) - : base(info, context) { + throw new NotSupportedException(); } #endregion Serialization @@ -224,7 +224,6 @@ protected MethodInvocationException(SerializationInfo info, StreamingContext con /// /// Defines the exception thrown for errors getting the value of properties. /// - [Serializable] public class GetValueException : ExtendedTypeSystemException { internal const string GetWithoutGetterExceptionMsg = "GetWithoutGetterException"; @@ -280,9 +279,10 @@ internal GetValueException( /// /// Serialization information. /// Streaming context. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected GetValueException(SerializationInfo info, StreamingContext context) - : base(info, context) { + throw new NotSupportedException(); } #endregion Serialization @@ -293,7 +293,6 @@ protected GetValueException(SerializationInfo info, StreamingContext context) /// /// Defines the exception thrown for errors getting the value of properties. /// - [Serializable] public class PropertyNotFoundException : ExtendedTypeSystemException { #region ctor @@ -347,12 +346,12 @@ internal PropertyNotFoundException( /// /// Serialization information. /// Streaming context. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected PropertyNotFoundException(SerializationInfo info, StreamingContext context) - : base(info, context) { + throw new NotSupportedException(); } #endregion Serialization - #endregion ctor } @@ -360,7 +359,6 @@ protected PropertyNotFoundException(SerializationInfo info, StreamingContext con /// /// Defines the exception thrown for exceptions thrown by property getters. /// - [Serializable] public class GetValueInvocationException : GetValueException { internal const string ExceptionWhenGettingMsg = "ExceptionWhenGetting"; @@ -416,9 +414,10 @@ internal GetValueInvocationException( /// /// Serialization information. /// Streaming context. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected GetValueInvocationException(SerializationInfo info, StreamingContext context) - : base(info, context) { + throw new NotSupportedException(); } #endregion Serialization @@ -429,7 +428,6 @@ protected GetValueInvocationException(SerializationInfo info, StreamingContext c /// /// Defines the exception thrown for errors setting the value of properties. /// - [Serializable] public class SetValueException : ExtendedTypeSystemException { #region ctor @@ -483,9 +481,10 @@ internal SetValueException( /// /// Serialization information. /// Streaming context. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected SetValueException(SerializationInfo info, StreamingContext context) - : base(info, context) { + throw new NotSupportedException(); } #endregion Serialization @@ -496,7 +495,6 @@ protected SetValueException(SerializationInfo info, StreamingContext context) /// /// Defines the exception thrown for exceptions thrown by property setters. /// - [Serializable] public class SetValueInvocationException : SetValueException { #region ctor @@ -550,9 +548,10 @@ internal SetValueInvocationException( /// /// Serialization information. /// Streaming context. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected SetValueInvocationException(SerializationInfo info, StreamingContext context) - : base(info, context) { + throw new NotSupportedException(); } #endregion Serialization @@ -563,40 +562,19 @@ protected SetValueInvocationException(SerializationInfo info, StreamingContext c /// /// Defines the exception thrown for type conversion errors. /// - [Serializable] public class PSInvalidCastException : InvalidCastException, IContainsErrorRecord { - #region Serialization - - /// - /// Populates a with the - /// data needed to serialize the PSInvalidCastException object. - /// - /// The to populate with data. - /// The destination for this serialization. - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw new PSArgumentNullException(nameof(info)); - } - - base.GetObjectData(info, context); - info.AddValue("ErrorId", _errorId); - } /// /// Initializes a new instance of PSInvalidCastException with serialization parameters. /// /// Serialization information. /// Streaming context. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected PSInvalidCastException(SerializationInfo info, StreamingContext context) - : base(info, context) { - _errorId = info.GetString("ErrorId"); + throw new NotSupportedException(); } - #endregion Serialization - /// /// Initializes a new instance of PSInvalidCastException with the message set /// to typeof(PSInvalidCastException).FullName. diff --git a/src/System.Management.Automation/engine/ExternalScriptInfo.cs b/src/System.Management.Automation/engine/ExternalScriptInfo.cs index fe23b1b85ce..e8c8c2b1d54 100644 --- a/src/System.Management.Automation/engine/ExternalScriptInfo.cs +++ b/src/System.Management.Automation/engine/ExternalScriptInfo.cs @@ -611,7 +611,6 @@ internal ScriptRequiresSyntaxException(string message) /// /// Defines the name and version tuple of a PSSnapin. /// - [Serializable] public class PSSnapInSpecification { internal PSSnapInSpecification(string psSnapinName) diff --git a/src/System.Management.Automation/engine/Modules/ScriptAnalysis.cs b/src/System.Management.Automation/engine/Modules/ScriptAnalysis.cs index 591e29f657f..5b11966ff84 100644 --- a/src/System.Management.Automation/engine/Modules/ScriptAnalysis.cs +++ b/src/System.Management.Automation/engine/Modules/ScriptAnalysis.cs @@ -14,7 +14,6 @@ namespace System.Management.Automation /// /// Class describing a PowerShell module... /// - [Serializable] internal class ScriptAnalysis { internal static ScriptAnalysis Analyze(string path, ExecutionContext context) @@ -573,7 +572,6 @@ private struct ParameterInfo // Class to keep track of modules we need to import, and commands that should // be filtered out of them. - [Serializable] internal class RequiredModuleInfo { internal string Name { get; set; } diff --git a/src/System.Management.Automation/engine/MshObject.cs b/src/System.Management.Automation/engine/MshObject.cs index 018daeed5bb..8303058759d 100644 --- a/src/System.Management.Automation/engine/MshObject.cs +++ b/src/System.Management.Automation/engine/MshObject.cs @@ -44,7 +44,6 @@ namespace System.Management.Automation /// but there is no established scenario for doing this, nor has it been tested. /// [TypeDescriptionProvider(typeof(PSObjectTypeDescriptionProvider))] - [Serializable] public class PSObject : IFormattable, IComparable, ISerializable, IDynamicMetaObjectProvider { #region constructors diff --git a/src/System.Management.Automation/engine/MshSecurityException.cs b/src/System.Management.Automation/engine/MshSecurityException.cs index 490de14be02..07c70ec7317 100644 --- a/src/System.Management.Automation/engine/MshSecurityException.cs +++ b/src/System.Management.Automation/engine/MshSecurityException.cs @@ -8,7 +8,6 @@ namespace System.Management.Automation /// /// This is a wrapper for exception class SecurityException. /// - [Serializable] public class PSSecurityException : RuntimeException { #region ctor @@ -34,19 +33,11 @@ public PSSecurityException() /// Serialization information. /// Streaming context. /// Constructed object. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected PSSecurityException(SerializationInfo info, StreamingContext context) - : base(info, context) { - _errorRecord = new ErrorRecord( - new ParentContainsErrorRecordException(this), - "UnauthorizedAccess", - ErrorCategory.SecurityError, - null); - _errorRecord.ErrorDetails = new ErrorDetails(SessionStateStrings.CanNotRun); - _message = _errorRecord.ErrorDetails.Message; - // no fields, nothing more to serialize - // no need for a GetObjectData implementation + throw new NotSupportedException(); } /// diff --git a/src/System.Management.Automation/engine/NativeCommandProcessor.cs b/src/System.Management.Automation/engine/NativeCommandProcessor.cs index 117360e21ea..10c4dda1e5c 100644 --- a/src/System.Management.Automation/engine/NativeCommandProcessor.cs +++ b/src/System.Management.Automation/engine/NativeCommandProcessor.cs @@ -138,7 +138,6 @@ internal ProcessOutputObject(object data, MinishellStream stream) /// This exception is used by the NativeCommandProcessor to indicate an error /// when a native command retuns a non-zero exit code. /// - [Serializable] public sealed class NativeCommandExitException : RuntimeException { // NOTE: @@ -170,45 +169,8 @@ internal NativeCommandExitException(string path, int exitCode, int processId, st ProcessId = processId; } - /// - /// Initializes a new instance of the class with serialized data. - /// - /// - /// - private NativeCommandExitException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - if (info is null) - { - throw new PSArgumentNullException(nameof(info)); - } - - Path = info.GetString(nameof(Path)); - ExitCode = info.GetInt32(nameof(ExitCode)); - ProcessId = info.GetInt32(nameof(ProcessId)); - } - #endregion Constructors - /// - /// Serializes the exception data. - /// - /// Serialization information. - /// Streaming context. - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info is null) - { - throw new PSArgumentNullException(nameof(info)); - } - - base.GetObjectData(info, context); - - info.AddValue(nameof(Path), Path); - info.AddValue(nameof(ExitCode), ExitCode); - info.AddValue(nameof(ProcessId), ProcessId); - } - /// /// Gets the path of the native command. /// @@ -2354,7 +2316,6 @@ internal static bool AllocateHiddenConsole() /// This remote instance of PowerShell can be in a separate process, /// appdomain or machine. /// - [Serializable] [SuppressMessage("Microsoft.Usage", "CA2240:ImplementISerializableCorrectly")] public class RemoteException : RuntimeException { @@ -2431,9 +2392,10 @@ PSObject serializedRemoteInvocationInfo /// The that contains contextual information /// about the source or destination. /// + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected RemoteException(SerializationInfo info, StreamingContext context) - : base(info, context) { + throw new NotSupportedException(); } #endregion diff --git a/src/System.Management.Automation/engine/OrderedHashtable.cs b/src/System.Management.Automation/engine/OrderedHashtable.cs index d14d3dc2449..fd41d0b3ffd 100644 --- a/src/System.Management.Automation/engine/OrderedHashtable.cs +++ b/src/System.Management.Automation/engine/OrderedHashtable.cs @@ -224,16 +224,6 @@ IEnumerator IEnumerable.GetEnumerator() return GetEnumerator(); } - /// - /// Returns the data needed to seralize the Hashtable. - /// - /// The serialization info. - /// The serialization context. - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - _orderedDictionary.GetObjectData(info, context); - } - /// /// Removes the specified key from the hashtable. /// diff --git a/src/System.Management.Automation/engine/PseudoParameters.cs b/src/System.Management.Automation/engine/PseudoParameters.cs index 261e8ee6c51..a3703a63d90 100644 --- a/src/System.Management.Automation/engine/PseudoParameters.cs +++ b/src/System.Management.Automation/engine/PseudoParameters.cs @@ -214,7 +214,6 @@ internal bool IsDisabled() /// /// /// - [Serializable] public class RuntimeDefinedParameterDictionary : Dictionary { /// diff --git a/src/System.Management.Automation/engine/TypeTable.cs b/src/System.Management.Automation/engine/TypeTable.cs index 502258485c0..df1e817b6a4 100644 --- a/src/System.Management.Automation/engine/TypeTable.cs +++ b/src/System.Management.Automation/engine/TypeTable.cs @@ -1743,7 +1743,6 @@ internal void AddError(string typeName, int errorLineNumber, string resourceStri /// This exception is used by TypeTable constructor to indicate errors /// occurred during construction time. /// - [Serializable] public class TypeTableLoadException : RuntimeException { private readonly Collection _errors; @@ -1805,56 +1804,14 @@ internal TypeTableLoadException(ConcurrentBag loadErrors) /// /// /// + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected TypeTableLoadException(SerializationInfo info, StreamingContext context) - : base(info, context) { - if (info == null) - { - throw new PSArgumentNullException(nameof(info)); - } - - int errorCount = info.GetInt32("ErrorCount"); - if (errorCount > 0) - { - _errors = new Collection(); - for (int index = 0; index < errorCount; index++) - { - string key = string.Create(CultureInfo.InvariantCulture, $"Error{index}"); - _errors.Add(info.GetString(key)); - } - } + throw new NotSupportedException(); } #endregion Constructors - /// - /// Serializes the exception data. - /// - /// Serialization information. - /// Streaming context. - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw new PSArgumentNullException(nameof(info)); - } - - base.GetObjectData(info, context); - - // If there are simple fields, serialize them with info.AddValue - if (_errors != null) - { - int errorCount = _errors.Count; - info.AddValue("ErrorCount", errorCount); - - for (int index = 0; index < errorCount; index++) - { - string key = string.Create(CultureInfo.InvariantCulture, $"Error{index}"); - info.AddValue(key, _errors[index]); - } - } - } - /// /// Set the default ErrorRecord. /// diff --git a/src/System.Management.Automation/engine/hostifaces/Connection.cs b/src/System.Management.Automation/engine/hostifaces/Connection.cs index 50c7e49f92d..5f0f8e036db 100644 --- a/src/System.Management.Automation/engine/hostifaces/Connection.cs +++ b/src/System.Management.Automation/engine/hostifaces/Connection.cs @@ -19,7 +19,6 @@ namespace System.Management.Automation.Runspaces /// Exception thrown when state of the runspace is different from /// expected state of runspace. /// - [Serializable] public class InvalidRunspaceStateException : SystemException { /// @@ -96,9 +95,10 @@ RunspaceState expectedState /// The that contains contextual information /// about the source or destination. /// + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected InvalidRunspaceStateException(SerializationInfo info, StreamingContext context) - : base(info, context) { + throw new NotSupportedException(); } #endregion diff --git a/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs b/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs index b88a466623d..5dcc43ce2a7 100644 --- a/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs +++ b/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs @@ -1491,7 +1491,6 @@ private void RaiseOperationCompleteEvent() /// Defines the exception thrown an error loading modules occurs while opening the runspace. It /// contains a list of all of the module errors that have occurred. /// - [Serializable] public class RunspaceOpenModuleLoadException : RuntimeException { #region ctor @@ -1558,27 +1557,11 @@ public PSDataCollection ErrorRecords /// /// Serialization information. /// Streaming context. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected RunspaceOpenModuleLoadException(SerializationInfo info, StreamingContext context) - : base(info, context) { - } - - /// - /// Populates a with the - /// data needed to serialize the RunspaceOpenModuleLoadException object. - /// - /// The to populate with data. - /// The destination for this serialization. - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw new PSArgumentNullException(nameof(info)); - } - - base.GetObjectData(info, context); - } - + throw new NotSupportedException(); + } #endregion Serialization } diff --git a/src/System.Management.Automation/engine/hostifaces/PSDataCollection.cs b/src/System.Management.Automation/engine/hostifaces/PSDataCollection.cs index 90512b51768..eb1a796d0e7 100644 --- a/src/System.Management.Automation/engine/hostifaces/PSDataCollection.cs +++ b/src/System.Management.Automation/engine/hostifaces/PSDataCollection.cs @@ -116,7 +116,6 @@ internal DataAddingEventArgs(Guid psInstanceId, object itemAdded) /// build /// Thread Safe buffer used with PowerShell Hosting interfaces. /// - [Serializable] public class PSDataCollection : IList, ICollection, IEnumerable, IList, ICollection, IEnumerable, IDisposable, ISerializable { #region Private Data diff --git a/src/System.Management.Automation/engine/hostifaces/Pipeline.cs b/src/System.Management.Automation/engine/hostifaces/Pipeline.cs index c7b962b7668..66ebf7d0287 100644 --- a/src/System.Management.Automation/engine/hostifaces/Pipeline.cs +++ b/src/System.Management.Automation/engine/hostifaces/Pipeline.cs @@ -16,7 +16,6 @@ namespace System.Management.Automation.Runspaces /// Defines exception which is thrown when state of the pipeline is different /// from expected state. /// - [Serializable] public class InvalidPipelineStateException : SystemException { /// @@ -86,9 +85,10 @@ internal InvalidPipelineStateException(string message, PipelineState currentStat /// The that contains contextual information /// about the source or destination. /// + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] private InvalidPipelineStateException(SerializationInfo info, StreamingContext context) - : base(info, context) { + throw new NotSupportedException(); } #endregion diff --git a/src/System.Management.Automation/engine/hostifaces/PowerShell.cs b/src/System.Management.Automation/engine/hostifaces/PowerShell.cs index 1dace005fa7..73bdbdb7c49 100644 --- a/src/System.Management.Automation/engine/hostifaces/PowerShell.cs +++ b/src/System.Management.Automation/engine/hostifaces/PowerShell.cs @@ -31,7 +31,6 @@ namespace System.Management.Automation /// Defines exception which is thrown when state of the PowerShell is different /// from the expected state. /// - [Serializable] public class InvalidPowerShellStateException : SystemException { /// @@ -97,10 +96,11 @@ internal InvalidPowerShellStateException(PSInvocationState currentState) /// The that contains contextual information /// about the source or destination. /// + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected InvalidPowerShellStateException(SerializationInfo info, StreamingContext context) - : base(info, context) { + throw new NotSupportedException(); } #endregion diff --git a/src/System.Management.Automation/engine/hostifaces/RunspacePool.cs b/src/System.Management.Automation/engine/hostifaces/RunspacePool.cs index 46f4799aaa5..e7457e2c53d 100644 --- a/src/System.Management.Automation/engine/hostifaces/RunspacePool.cs +++ b/src/System.Management.Automation/engine/hostifaces/RunspacePool.cs @@ -16,7 +16,6 @@ namespace System.Management.Automation.Runspaces /// Exception thrown when state of the runspace pool is different from /// expected state of runspace pool. /// - [Serializable] public class InvalidRunspacePoolStateException : SystemException { /// @@ -91,10 +90,11 @@ RunspacePoolState expectedState /// The that contains /// contextual information about the source or destination. /// + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected InvalidRunspacePoolStateException(SerializationInfo info, StreamingContext context) - : base(info, context) { + throw new NotSupportedException(); } #endregion diff --git a/src/System.Management.Automation/engine/interpreter/LightCompiler.cs b/src/System.Management.Automation/engine/interpreter/LightCompiler.cs index e037d23fbf0..e95fa2e3f30 100644 --- a/src/System.Management.Automation/engine/interpreter/LightCompiler.cs +++ b/src/System.Management.Automation/engine/interpreter/LightCompiler.cs @@ -187,7 +187,6 @@ internal sealed class RethrowException : SystemException { } - [Serializable] internal class DebugInfo { // TODO: readonly @@ -248,7 +247,6 @@ public override string ToString() // TODO: [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes")] - [Serializable] internal readonly struct InterpretedFrameInfo { public readonly string MethodName; diff --git a/src/System.Management.Automation/engine/lang/parserutils.cs b/src/System.Management.Automation/engine/lang/parserutils.cs index e9970684810..eb438a8a057 100644 --- a/src/System.Management.Automation/engine/lang/parserutils.cs +++ b/src/System.Management.Automation/engine/lang/parserutils.cs @@ -28,11 +28,6 @@ namespace System.Management.Automation public abstract class FlowControlException : SystemException { internal FlowControlException() { } - - internal FlowControlException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } /// @@ -45,11 +40,6 @@ internal LoopFlowException(string label) this.Label = label ?? string.Empty; } - internal LoopFlowException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } - internal LoopFlowException() { } /// @@ -95,11 +85,6 @@ internal BreakException(string label, Exception innerException) : base(label) { } - - private BreakException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } /// @@ -121,11 +106,6 @@ internal ContinueException(string label, Exception innerException) : base(label) { } - - private ContinueException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } internal class ReturnException : FlowControlException @@ -156,12 +136,6 @@ internal ExitException(object argument) [SuppressMessage("Microsoft.Design", "CA1032:ImplementStandardExceptionConstructors", Justification = "This exception should only be thrown from SMA.dll")] internal ExitException() { } - - [SuppressMessage("Microsoft.Design", "CA1032:ImplementStandardExceptionConstructors", Justification = "This exception should only be thrown from SMA.dll")] - private ExitException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } /// diff --git a/src/System.Management.Automation/engine/lang/scriptblock.cs b/src/System.Management.Automation/engine/lang/scriptblock.cs index fdc5bcdb326..8321d01319d 100644 --- a/src/System.Management.Automation/engine/lang/scriptblock.cs +++ b/src/System.Management.Automation/engine/lang/scriptblock.cs @@ -1333,7 +1333,6 @@ public void Dispose() /// Defines the exception thrown when conversion from ScriptBlock to PowerShell is forbidden /// (i.e. when the script block has undeclared variables or more than one statement) /// - [Serializable] public class ScriptBlockToPowerShellNotSupportedException : RuntimeException { #region ctor @@ -1387,9 +1386,10 @@ internal ScriptBlockToPowerShellNotSupportedException( /// /// Serialization information. /// Streaming context. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected ScriptBlockToPowerShellNotSupportedException(SerializationInfo info, StreamingContext context) - : base(info, context) { + throw new NotSupportedException(); } #endregion Serialization diff --git a/src/System.Management.Automation/engine/regex.cs b/src/System.Management.Automation/engine/regex.cs index 5987ba80dcc..4ca21bd1310 100644 --- a/src/System.Management.Automation/engine/regex.cs +++ b/src/System.Management.Automation/engine/regex.cs @@ -469,7 +469,6 @@ public string ToWql() /// /// Thrown when a wildcard pattern is invalid. /// - [Serializable] public class WildcardPatternException : RuntimeException { /// @@ -525,10 +524,11 @@ public WildcardPatternException(string message, /// /// Serialization information. /// Streaming context. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected WildcardPatternException(SerializationInfo info, StreamingContext context) - : base(info, context) { + throw new NotSupportedException(); } } diff --git a/src/System.Management.Automation/engine/remoting/client/Job.cs b/src/System.Management.Automation/engine/remoting/client/Job.cs index 3d276278eb9..b3a0135afc7 100644 --- a/src/System.Management.Automation/engine/remoting/client/Job.cs +++ b/src/System.Management.Automation/engine/remoting/client/Job.cs @@ -93,7 +93,6 @@ public enum JobState /// Defines exception which is thrown when state of the PSJob is different /// from the expected state. /// - [Serializable] public class InvalidJobStateException : SystemException { /// @@ -191,10 +190,11 @@ internal InvalidJobStateException(JobState currentState) /// The that contains contextual information /// about the source or destination. /// + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected InvalidJobStateException(SerializationInfo info, StreamingContext context) - : base(info, context) { + throw new NotSupportedException(); } #endregion diff --git a/src/System.Management.Automation/engine/remoting/client/Job2.cs b/src/System.Management.Automation/engine/remoting/client/Job2.cs index 3f9c025d954..a5ac9e5ec0b 100644 --- a/src/System.Management.Automation/engine/remoting/client/Job2.cs +++ b/src/System.Management.Automation/engine/remoting/client/Job2.cs @@ -2106,7 +2106,6 @@ private void UnregisterAllJobEvents() /// Container exception for jobs that can map errors and exceptions /// to specific lines in their input. /// - [Serializable] public class JobFailedException : SystemException { /// @@ -2151,11 +2150,10 @@ public JobFailedException(Exception innerException, ScriptExtent displayScriptPo /// /// Serialization info. /// Streaming context. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected JobFailedException(SerializationInfo serializationInfo, StreamingContext streamingContext) - : base(serializationInfo, streamingContext) { - _reason = (Exception)serializationInfo.GetValue("Reason", typeof(Exception)); - _displayScriptPosition = (ScriptExtent)serializationInfo.GetValue("DisplayScriptPosition", typeof(ScriptExtent)); + throw new NotSupportedException(); } /// @@ -2172,21 +2170,6 @@ protected JobFailedException(SerializationInfo serializationInfo, StreamingConte private readonly ScriptExtent _displayScriptPosition; - /// - /// Gets the information for serialization. - /// - /// The standard SerializationInfo. - /// The standard StreaminContext. - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - ArgumentNullException.ThrowIfNull(info); - - base.GetObjectData(info, context); - - info.AddValue("Reason", _reason); - info.AddValue("DisplayScriptPosition", _displayScriptPosition); - } - /// /// Returns the reason for this exception. /// diff --git a/src/System.Management.Automation/engine/remoting/client/JobSourceAdapter.cs b/src/System.Management.Automation/engine/remoting/client/JobSourceAdapter.cs index 0ffcab271bc..9f6297fbfab 100644 --- a/src/System.Management.Automation/engine/remoting/client/JobSourceAdapter.cs +++ b/src/System.Management.Automation/engine/remoting/client/JobSourceAdapter.cs @@ -20,7 +20,6 @@ namespace System.Management.Automation /// /// The actual implementation of this class will /// happen in M2 - [Serializable] public class JobDefinition : ISerializable { private string _name; @@ -172,7 +171,6 @@ public virtual void GetObjectData(SerializationInfo info, StreamingContext conte /// CommandParameterCollection adds a public /// constructor.The actual implementation of /// this class will happen in M2 - [Serializable] public class JobInvocationInfo : ISerializable { /// diff --git a/src/System.Management.Automation/engine/remoting/client/RemotingErrorRecord.cs b/src/System.Management.Automation/engine/remoting/client/RemotingErrorRecord.cs index cf37aa7bb33..07dfd9db8a1 100644 --- a/src/System.Management.Automation/engine/remoting/client/RemotingErrorRecord.cs +++ b/src/System.Management.Automation/engine/remoting/client/RemotingErrorRecord.cs @@ -11,7 +11,6 @@ namespace System.Management.Automation.Runspaces /// /// Error record in remoting cases. /// - [Serializable] public class RemotingErrorRecord : ErrorRecord { /// @@ -57,32 +56,15 @@ private RemotingErrorRecord( #region ISerializable implementation - /// - /// Serializer method for class. - /// - /// Serializer information. - /// Streaming context. - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw PSTraceSource.NewArgumentNullException(nameof(info)); - } - - base.GetObjectData(info, context); - - info.AddValue("RemoteErrorRecord_OriginInfo", _originInfo); - } - /// /// Deserializer constructor. /// /// Serializer information. /// Streaming context. - protected RemotingErrorRecord(SerializationInfo info, StreamingContext context) - : base(info, context) + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] + protected RemotingErrorRecord(SerializationInfo info, StreamingContext context) : base(info, context) { - _originInfo = (OriginInfo)info.GetValue("RemoteErrorRecord_OriginInfo", typeof(OriginInfo)); + throw new NotSupportedException(); } #endregion @@ -294,7 +276,6 @@ namespace System.Management.Automation.Remoting /// In case of output objects, the information /// should directly be added to the object as /// properties - [Serializable] [DataContract()] public class OriginInfo { diff --git a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteHostEncoder.cs b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteHostEncoder.cs index 3ffc278a817..cdaceda1610 100644 --- a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteHostEncoder.cs +++ b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteHostEncoder.cs @@ -7,6 +7,7 @@ using System.Globalization; using System.Management.Automation.Host; using System.Reflection; +using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Security; @@ -87,7 +88,7 @@ private static PSObject EncodeClassOrStruct(object obj) /// private static object DecodeClassOrStruct(PSObject psObject, Type type) { - object obj = FormatterServices.GetUninitializedObject(type); + object obj = RuntimeHelpers.GetUninitializedObject(type); // Field values cannot be null - because for null fields we simply don't transport them. foreach (PSPropertyInfo propertyInfo in psObject.Properties) diff --git a/src/System.Management.Automation/engine/remoting/common/remotingexceptions.cs b/src/System.Management.Automation/engine/remoting/common/remotingexceptions.cs index fbecd29a6f0..c7a2c561bd4 100644 --- a/src/System.Management.Automation/engine/remoting/common/remotingexceptions.cs +++ b/src/System.Management.Automation/engine/remoting/common/remotingexceptions.cs @@ -282,7 +282,6 @@ internal static string FormatResourceString(string resourceString, params object /// /// This exception is used by remoting code to indicated a data structure handler related error. /// - [Serializable] public class PSRemotingDataStructureException : RuntimeException { #region Constructors @@ -361,9 +360,10 @@ internal PSRemotingDataStructureException(Exception innerException, string resou /// /// /// + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected PSRemotingDataStructureException(SerializationInfo info, StreamingContext context) - : base(info, context) { + throw new NotSupportedException(); } #endregion Constructors @@ -381,7 +381,6 @@ private void SetDefaultErrorRecord() /// /// This exception is used by remoting code to indicate an error condition in network operations. /// - [Serializable] public class PSRemotingTransportException : RuntimeException { private int _errorCode; @@ -470,38 +469,14 @@ internal PSRemotingTransportException(Exception innerException, string resourceS /// /// 1. info is null. /// + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected PSRemotingTransportException(SerializationInfo info, StreamingContext context) - : base(info, context) { - if (info == null) - { - throw new PSArgumentNullException(nameof(info)); - } - - _errorCode = info.GetInt32("ErrorCode"); - _transportMessage = info.GetString("TransportMessage"); + throw new NotSupportedException(); } #endregion Constructors - /// - /// Serializes the exception data. - /// - /// Serialization information. - /// Streaming context. - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw new PSArgumentNullException(nameof(info)); - } - - base.GetObjectData(info, context); - // If there are simple fields, serialize them with info.AddValue - info.AddValue("ErrorCode", _errorCode); - info.AddValue("TransportMessage", _transportMessage); - } - /// /// Set the default ErrorRecord. /// @@ -548,7 +523,6 @@ public string TransportMessage /// This exception is used by PowerShell's remoting infrastructure to notify a URI redirection /// exception. /// - [Serializable] public class PSRemotingTransportRedirectException : PSRemotingTransportException { #region Constructor @@ -612,15 +586,10 @@ internal PSRemotingTransportRedirectException(Exception innerException, string r /// /// 1. info is null. /// + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected PSRemotingTransportRedirectException(SerializationInfo info, StreamingContext context) - : base(info, context) { - if (info == null) - { - throw new PSArgumentNullException(nameof(info)); - } - - RedirectLocation = info.GetString("RedirectLocation"); + throw new NotSupportedException(); } /// @@ -646,27 +615,6 @@ internal PSRemotingTransportRedirectException(string redirectLocation, PSRemotin #endregion - #region Public overrides - - /// - /// Serializes the exception data. - /// - /// Serialization information. - /// Streaming context. - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw new PSArgumentNullException(nameof(info)); - } - - base.GetObjectData(info, context); - // If there are simple fields, serialize them with info.AddValue - info.AddValue("RedirectLocation", RedirectLocation); - } - - #endregion - #region Properties /// /// String specifying a redirect location. @@ -679,7 +627,6 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont /// /// This exception is used by PowerShell Direct errors. /// - [Serializable] public class PSDirectException : RuntimeException { #region Constructor diff --git a/src/System.Management.Automation/engine/remoting/fanin/PSPrincipal.cs b/src/System.Management.Automation/engine/remoting/fanin/PSPrincipal.cs index 67a5ff4e80d..b6a3f212b33 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/PSPrincipal.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/PSPrincipal.cs @@ -21,7 +21,6 @@ namespace System.Management.Automation.Remoting /// (a) Connecting User information /// (b) Connection String used by the user to connect to the server. /// - [Serializable] public sealed class PSSenderInfo : ISerializable { #region Private Data diff --git a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs index dc4850b9208..2569dd3a492 100644 --- a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs +++ b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs @@ -539,8 +539,7 @@ public override string ToString() } } - [Serializable] - public partial class ScriptBlock : ISerializable + public partial class ScriptBlock { private readonly CompiledScriptBlockData _scriptBlockData; @@ -573,6 +572,7 @@ private ScriptBlock(CompiledScriptBlockData scriptBlockData) /// /// Protected constructor to support ISerializable. /// + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected ScriptBlock(SerializationInfo info, StreamingContext context) { } @@ -712,21 +712,6 @@ internal string ToStringWithDollarUsingHandling( return sbText; } - /// - /// Support for . - /// - public virtual void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw PSTraceSource.NewArgumentNullException(nameof(info)); - } - - string serializedContent = this.ToString(); - info.AddValue("ScriptText", serializedContent); - info.SetType(typeof(ScriptBlockSerializationHelper)); - } - internal PowerShell GetPowerShellImpl( ExecutionContext context, Dictionary variables, @@ -2191,38 +2176,6 @@ internal static void LogScriptBlockEnd(ScriptBlock scriptBlock, Guid runspaceId) internal bool HasCleanBlock { get => AstInternal.Body.CleanBlock != null; } } - [Serializable] - internal class ScriptBlockSerializationHelper : ISerializable, IObjectReference - { - private readonly string _scriptText; - - private ScriptBlockSerializationHelper(SerializationInfo info, StreamingContext context) - { - ArgumentNullException.ThrowIfNull(info); - - _scriptText = info.GetValue("ScriptText", typeof(string)) as string; - if (_scriptText == null) - { - throw PSTraceSource.NewArgumentNullException(nameof(info)); - } - } - - /// - /// Returns a script block that corresponds to the version deserialized. - /// - /// The streaming context for this instance. - /// A script block that corresponds to the version deserialized. - public object GetRealObject(StreamingContext context) => ScriptBlock.Create(_scriptText); - - /// - /// Implements the ISerializable contract for serializing a scriptblock. - /// - /// Serialization information for this instance. - /// The streaming context for this instance. - public virtual void GetObjectData(SerializationInfo info, StreamingContext context) - => throw new NotSupportedException(); - } - internal sealed class PSScriptCmdlet : PSCmdlet, IDynamicParameters, IDisposable { private readonly ArrayList _input = new ArrayList(); diff --git a/src/System.Management.Automation/engine/serialization.cs b/src/System.Management.Automation/engine/serialization.cs index 4705d269607..d0c4a30bf3c 100644 --- a/src/System.Management.Automation/engine/serialization.cs +++ b/src/System.Management.Automation/engine/serialization.cs @@ -5910,7 +5910,6 @@ IEnumerator IEnumerable.GetEnumerator() /// 2) values that can be serialized and deserialized during PowerShell remoting handshake /// (in major-version compatible versions of PowerShell remoting) /// - [Serializable] public sealed class PSPrimitiveDictionary : Hashtable { #region Constructors diff --git a/src/System.Management.Automation/help/HelpCategoryInvalidException.cs b/src/System.Management.Automation/help/HelpCategoryInvalidException.cs index d9ccee7bae6..8ab4fa37ca6 100644 --- a/src/System.Management.Automation/help/HelpCategoryInvalidException.cs +++ b/src/System.Management.Automation/help/HelpCategoryInvalidException.cs @@ -16,7 +16,6 @@ namespace Microsoft.PowerShell.Commands /// The exception that is thrown when there is no help category matching /// a specific input string. /// - [Serializable] public class HelpCategoryInvalidException : ArgumentException, IContainsErrorRecord { /// @@ -113,30 +112,11 @@ public override string Message /// /// Serialization information. /// Streaming context. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected HelpCategoryInvalidException(SerializationInfo info, - StreamingContext context) - : base(info, context) + StreamingContext context) { - _helpCategory = info.GetString("HelpCategory"); - CreateErrorRecord(); - } - - /// - /// Populates a with the - /// data needed to serialize the HelpCategoryInvalidException object. - /// - /// The to populate with data. - /// The destination for this serialization. - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw PSTraceSource.NewArgumentNullException(nameof(info)); - } - - base.GetObjectData(info, context); - - info.AddValue("HelpCategory", this._helpCategory); + throw new NotSupportedException(); } #endregion Serialization diff --git a/src/System.Management.Automation/help/HelpNotFoundException.cs b/src/System.Management.Automation/help/HelpNotFoundException.cs index 6008b4afbc1..109cd21dbd9 100644 --- a/src/System.Management.Automation/help/HelpNotFoundException.cs +++ b/src/System.Management.Automation/help/HelpNotFoundException.cs @@ -15,7 +15,6 @@ namespace Microsoft.PowerShell.Commands /// /// The exception that is thrown when there is no help found for a topic. /// - [Serializable] public class HelpNotFoundException : SystemException, IContainsErrorRecord { /// @@ -119,32 +118,13 @@ public override string Message /// /// Serialization information. /// Streaming context. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected HelpNotFoundException(SerializationInfo info, StreamingContext context) - : base(info, context) { - _helpTopic = info.GetString("HelpTopic"); - CreateErrorRecord(); + throw new NotSupportedException(); } - - /// - /// Populates a with the - /// data needed to serialize the HelpNotFoundException object. - /// - /// The to populate with data. - /// The destination for this serialization. - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw PSTraceSource.NewArgumentNullException(nameof(info)); - } - - base.GetObjectData(info, context); - - info.AddValue("HelpTopic", this._helpTopic); - } - + #endregion Serialization } } diff --git a/src/System.Management.Automation/help/UpdatableHelpSystem.cs b/src/System.Management.Automation/help/UpdatableHelpSystem.cs index 3a504a37fd2..6ab8d469a97 100644 --- a/src/System.Management.Automation/help/UpdatableHelpSystem.cs +++ b/src/System.Management.Automation/help/UpdatableHelpSystem.cs @@ -28,7 +28,6 @@ namespace System.Management.Automation.Help /// /// Updatable help system exception. /// - [Serializable] internal class UpdatableHelpSystemException : Exception { /// diff --git a/src/System.Management.Automation/singleshell/config/MshConsoleLoadException.cs b/src/System.Management.Automation/singleshell/config/MshConsoleLoadException.cs index 291914614f5..be4fa6c2edb 100644 --- a/src/System.Management.Automation/singleshell/config/MshConsoleLoadException.cs +++ b/src/System.Management.Automation/singleshell/config/MshConsoleLoadException.cs @@ -20,7 +20,6 @@ namespace System.Management.Automation.Runspaces /// 1. PSSnapin name /// 2. Inner exception. /// --> - [Serializable] public class PSConsoleLoadException : SystemException, IContainsErrorRecord { /// diff --git a/src/System.Management.Automation/singleshell/config/MshSnapinLoadException.cs b/src/System.Management.Automation/singleshell/config/MshSnapinLoadException.cs index 05c30ea82c2..f0e61f01a9e 100644 --- a/src/System.Management.Automation/singleshell/config/MshSnapinLoadException.cs +++ b/src/System.Management.Automation/singleshell/config/MshSnapinLoadException.cs @@ -19,7 +19,6 @@ namespace System.Management.Automation.Runspaces /// 1. PSSnapin name /// 2. Inner exception. /// --> - [Serializable] public class PSSnapInException : RuntimeException { /// @@ -172,32 +171,11 @@ public override string Message /// /// Serialization information. /// Streaming context. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected PSSnapInException(SerializationInfo info, StreamingContext context) - : base(info, context) { - _PSSnapin = info.GetString("PSSnapIn"); - _reason = info.GetString("Reason"); - - CreateErrorRecord(); - } - - /// - /// Get object data from serialization information. - /// - /// Serialization information. - /// Streaming context. - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw PSTraceSource.NewArgumentNullException(nameof(info)); - } - - base.GetObjectData(info, context); - - info.AddValue("PSSnapIn", _PSSnapin); - info.AddValue("Reason", _reason); + throw new NotSupportedException(); } #endregion Serialization diff --git a/src/System.Management.Automation/utils/CommandDiscoveryExceptions.cs b/src/System.Management.Automation/utils/CommandDiscoveryExceptions.cs index 4ce3568cf5a..6c2380023ca 100644 --- a/src/System.Management.Automation/utils/CommandDiscoveryExceptions.cs +++ b/src/System.Management.Automation/utils/CommandDiscoveryExceptions.cs @@ -11,7 +11,6 @@ namespace System.Management.Automation /// /// This exception is thrown when a command cannot be found. /// - [Serializable] public class CommandNotFoundException : RuntimeException { /// @@ -70,7 +69,6 @@ public CommandNotFoundException(string message) : base(message) { } /// public CommandNotFoundException(string message, Exception innerException) : base(message, innerException) { } - #region Serialization /// /// Serialization constructor for class CommandNotFoundException. /// @@ -80,38 +78,12 @@ public CommandNotFoundException(string message, Exception innerException) : base /// /// streaming context /// + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected CommandNotFoundException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - if (info == null) - { - throw new PSArgumentNullException(nameof(info)); - } - - _commandName = info.GetString("CommandName"); - } - - /// - /// Serializes the CommandNotFoundException. - /// - /// - /// serialization information - /// - /// - /// streaming context - /// - public override void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info == null) - { - throw new PSArgumentNullException(nameof(info)); - } - - base.GetObjectData(info, context); - info.AddValue("CommandName", _commandName); + throw new NotSupportedException(); } - #endregion Serialization #region Properties /// @@ -178,7 +150,6 @@ params object[] messageArgs /// Defines the exception thrown when a script's requirements to run specified by the #requires /// statements are not met. /// - [Serializable] public class ScriptRequiresException : RuntimeException { /// @@ -365,39 +336,13 @@ public ScriptRequiresException(string message, Exception innerException) : base( /// /// streaming context /// + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected ScriptRequiresException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - _commandName = info.GetString("CommandName"); - _requiresPSVersion = (Version)info.GetValue("RequiresPSVersion", typeof(Version)); - _missingPSSnapIns = (ReadOnlyCollection)info.GetValue("MissingPSSnapIns", typeof(ReadOnlyCollection)); - _requiresShellId = info.GetString("RequiresShellId"); - _requiresShellPath = info.GetString("RequiresShellPath"); - } - /// - /// Gets the serialized data for the exception. - /// - /// - /// serialization information - /// - /// - /// streaming context - /// - public override void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info == null) - { - throw new PSArgumentNullException(nameof(info)); - } - - base.GetObjectData(info, context); - info.AddValue("CommandName", _commandName); - info.AddValue("RequiresPSVersion", _requiresPSVersion, typeof(Version)); - info.AddValue("MissingPSSnapIns", _missingPSSnapIns, typeof(ReadOnlyCollection)); - info.AddValue("RequiresShellId", _requiresShellId); - info.AddValue("RequiresShellPath", _requiresShellPath); + throw new NotSupportedException(); } + #endregion Serialization #region Properties diff --git a/src/System.Management.Automation/utils/CommandProcessorExceptions.cs b/src/System.Management.Automation/utils/CommandProcessorExceptions.cs index 4aebe05af59..f63ff69bd2c 100644 --- a/src/System.Management.Automation/utils/CommandProcessorExceptions.cs +++ b/src/System.Management.Automation/utils/CommandProcessorExceptions.cs @@ -8,7 +8,6 @@ namespace System.Management.Automation /// /// Defines the exception that is thrown if a native command fails. /// - [Serializable] public class ApplicationFailedException : RuntimeException { #region private @@ -25,10 +24,11 @@ public class ApplicationFailedException : RuntimeException /// The serialization information to use when initializing this object. /// The streaming context to use when initializing this object. /// Constructed object. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected ApplicationFailedException(SerializationInfo info, StreamingContext context) - : base(info, context) { + throw new NotSupportedException(); } #endregion Serialization diff --git a/src/System.Management.Automation/utils/CryptoUtils.cs b/src/System.Management.Automation/utils/CryptoUtils.cs index ca68766d12b..c2139680ab0 100644 --- a/src/System.Management.Automation/utils/CryptoUtils.cs +++ b/src/System.Management.Automation/utils/CryptoUtils.cs @@ -235,9 +235,9 @@ internal static byte[] ToCapiSimpleKeyBlob(byte[] encryptedKey) // [2], [3] // RESERVED - Always 0 blob[4] = (byte)CALG_AES_256; // AES-256 algo id (0x10) blob[5] = 0x66; // ?? - // [6], [7], [8] // 0x00 + // [6], [7], [8] // 0x00 blob[9] = (byte)CALG_RSA_KEYX; // 0xa4 - // [10], [11] // 0x00 + // [10], [11] // 0x00 // create a reversed copy and add the encrypted key byte[] reversedKey = CreateReverseByteArray(encryptedKey); @@ -258,7 +258,6 @@ internal static byte[] ToCapiSimpleKeyBlob(byte[] encryptedKey) /// to the user when something fails on the remote end, then this /// can be turned public [SuppressMessage("Microsoft.Design", "CA1064:ExceptionsShouldBePublic")] - [Serializable] internal class PSCryptoException : Exception { #region Private Members @@ -329,26 +328,13 @@ public PSCryptoException(string message, Exception innerException) /// Context in which this constructor is called. /// Currently no custom type-specific serialization logic is /// implemented + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected PSCryptoException(SerializationInfo info, StreamingContext context) - : base(info, context) { - _errorCode = unchecked(0xFFFFFFF); - Dbg.Assert(false, "type-specific serialization logic not implemented and so this constructor should not be called"); + throw new NotSupportedException(); } #endregion Constructors - - #region ISerializable Overrides - /// - /// Returns base implementation. - /// - /// Serialization info. - /// Context. - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - base.GetObjectData(info, context); - } - #endregion ISerializable Overrides } /// @@ -365,7 +351,7 @@ internal sealed class PSRSACryptoServiceProvider : IDisposable // handle to the AES provider object (houses session key and iv) private readonly Aes _aes; - // this flag indicates that this class has a key imported from the + // this flag indicates that this class has a key imported from the // remote end and so can be used for encryption private bool _canEncrypt; @@ -423,7 +409,7 @@ internal void GenerateSessionKey() { if (!_sessionKeyGenerated) { - // Aes object gens key automatically on construction, so this is somewhat redundant, + // Aes object gens key automatically on construction, so this is somewhat redundant, // but at least the actionable key will not be in-memory until it's requested fwiw. _aes.GenerateKey(); _sessionKeyGenerated = true; diff --git a/src/System.Management.Automation/utils/ExecutionExceptions.cs b/src/System.Management.Automation/utils/ExecutionExceptions.cs index cd642683b18..460a98c5cd8 100644 --- a/src/System.Management.Automation/utils/ExecutionExceptions.cs +++ b/src/System.Management.Automation/utils/ExecutionExceptions.cs @@ -19,7 +19,6 @@ namespace System.Management.Automation /// /// InnerException is the error which the cmdlet hit. /// - [Serializable] public class CmdletInvocationException : RuntimeException { #region ctor @@ -116,33 +115,12 @@ public CmdletInvocationException(string message, /// Serialization information. /// Streaming context. /// Constructed object. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected CmdletInvocationException(SerializationInfo info, StreamingContext context) - : base(info, context) { - bool hasErrorRecord = info.GetBoolean("HasErrorRecord"); - if (hasErrorRecord) - _errorRecord = (ErrorRecord)info.GetValue("ErrorRecord", typeof(ErrorRecord)); - } - - /// - /// Serializer for - /// - /// Serialization information. - /// Streaming context. - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw new PSArgumentNullException(nameof(info)); - } - - base.GetObjectData(info, context); - bool hasErrorRecord = (_errorRecord != null); - info.AddValue("HasErrorRecord", hasErrorRecord); - if (hasErrorRecord) - info.AddValue("ErrorRecord", _errorRecord); - } + throw new NotSupportedException(); + } #endregion Serialization #endregion ctor @@ -177,8 +155,7 @@ public override ErrorRecord ErrorRecord /// . /// This is generally reported from the standard provider navigation cmdlets /// such as get-childitem. - /// - [Serializable] + /// public class CmdletProviderInvocationException : CmdletInvocationException { #region ctor @@ -217,11 +194,11 @@ public CmdletProviderInvocationException() /// Serialization information. /// Streaming context. /// Constructed object. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected CmdletProviderInvocationException(SerializationInfo info, StreamingContext context) - : base(info, context) { - _providerInvocationException = InnerException as ProviderInvocationException; + throw new NotSupportedException(); } /// @@ -305,8 +282,7 @@ private static Exception GetInnerException(Exception e) /// Catching this exception is optional; if the cmdlet or providers chooses not to /// handle PipelineStoppedException and instead allow it to propagate to the /// PowerShell Engine's call to ProcessRecord, the PowerShell Engine will handle it properly. - /// - [Serializable] + /// public class PipelineStoppedException : RuntimeException { #region ctor @@ -329,12 +305,11 @@ public PipelineStoppedException() /// Serialization information. /// Streaming context. /// Constructed object. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected PipelineStoppedException(SerializationInfo info, StreamingContext context) - : base(info, context) { - // no properties, nothing more to serialize - // no need for a GetObjectData implementation + throw new NotSupportedException(); } /// @@ -368,8 +343,7 @@ public PipelineStoppedException(string message, /// to an asynchronous pipeline source and the pipeline has already /// been stopped. /// - /// - [Serializable] + /// public class PipelineClosedException : RuntimeException { #region ctor @@ -414,10 +388,11 @@ public PipelineClosedException(string message, /// Serialization information. /// Streaming context. /// Constructed object. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected PipelineClosedException(SerializationInfo info, StreamingContext context) - : base(info, context) { + throw new NotSupportedException(); } #endregion Serialization } @@ -431,8 +406,7 @@ protected PipelineClosedException(SerializationInfo info, /// /// For example, if $WarningPreference is "Stop", the command will fail with /// this error if a cmdlet calls WriteWarning. - /// - [Serializable] + /// public class ActionPreferenceStopException : RuntimeException { #region ctor @@ -494,47 +468,12 @@ internal ActionPreferenceStopException(InvocationInfo invocationInfo, /// Serialization information. /// Streaming context. /// Constructed object. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected ActionPreferenceStopException(SerializationInfo info, StreamingContext context) - : base(info, context) { - bool hasErrorRecord = info.GetBoolean("HasErrorRecord"); - if (hasErrorRecord) - _errorRecord = (ErrorRecord)info.GetValue("ErrorRecord", typeof(ErrorRecord)); - - // fix for BUG: Windows Out Of Band Releases: 906263 and 906264 - // The interpreter prompt CommandBaseStrings:InquireHalt - // should be suppressed when this flag is set. This will be set - // when this prompt has already occurred and Break was chosen, - // or for ActionPreferenceStopException in all cases. - this.SuppressPromptInInterpreter = true; - } - - /// - /// Serializer for - /// - /// Serialization information. - /// Streaming context. - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - base.GetObjectData(info, context); - if (info != null) - { - bool hasErrorRecord = (_errorRecord != null); - info.AddValue("HasErrorRecord", hasErrorRecord); - if (hasErrorRecord) - { - info.AddValue("ErrorRecord", _errorRecord); - } - } - - // fix for BUG: Windows Out Of Band Releases: 906263 and 906264 - // The interpreter prompt CommandBaseStrings:InquireHalt - // should be suppressed when this flag is set. This will be set - // when this prompt has already occurred and Break was chosen, - // or for ActionPreferenceStopException in all cases. - this.SuppressPromptInInterpreter = true; - } + throw new NotSupportedException(); + } #endregion Serialization /// @@ -609,7 +548,6 @@ public override ErrorRecord ErrorRecord /// so that there is not a recursive "containment" relationship /// between the PowerShell engine exception and its ErrorRecord. /// - [Serializable] public class ParentContainsErrorRecordException : SystemException { #region Constructors @@ -675,11 +613,11 @@ public ParentContainsErrorRecordException(string message, /// Streaming context. /// Doesn't return. /// Always. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected ParentContainsErrorRecordException( SerializationInfo info, StreamingContext context) - : base(info, context) { - _message = info.GetString("ParentContainsErrorRecordException_Message"); + throw new NotSupportedException(); } #endregion Serialization /// @@ -693,22 +631,6 @@ public override string Message } } - /// - /// Serializer for - /// - /// Serialization information. - /// Context. - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw new PSArgumentNullException(nameof(info)); - } - - base.GetObjectData(info, context); - info.AddValue("ParentContainsErrorRecordException_Message", this.Message); - } - #region Private Data private readonly Exception _wrapperException; @@ -727,8 +649,7 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont /// The redirected object is available as /// /// in the ErrorRecord which contains this exception. - /// - [Serializable] + /// public class RedirectedException : RuntimeException { #region constructors @@ -777,10 +698,11 @@ public RedirectedException(string message, /// Serialization information. /// Streaming context. /// Constructed object. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected RedirectedException(SerializationInfo info, StreamingContext context) - : base(info, context) { + throw new NotSupportedException(); } #endregion constructors } @@ -798,8 +720,7 @@ protected RedirectedException(SerializationInfo info, /// call depth to prevent stack overflows. The maximum call depth is configurable /// but generally high enough that scripts which are not deeply recursive /// should not have a problem. - /// - [Serializable] + /// public class ScriptCallDepthException : SystemException, IContainsErrorRecord { #region ctor @@ -845,19 +766,11 @@ public ScriptCallDepthException(string message, /// Serialization information. /// Streaming context. /// Constructed object. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected ScriptCallDepthException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } - /// - /// Serializer for - /// - /// Serialization information. - /// Context. - public override void GetObjectData(SerializationInfo info, StreamingContext context) { - base.GetObjectData(info, context); + throw new NotSupportedException(); } #endregion Serialization @@ -904,7 +817,6 @@ public int CallDepth /// /// /// - [Serializable] public class PipelineDepthException : SystemException, IContainsErrorRecord { #region ctor @@ -949,19 +861,11 @@ public PipelineDepthException(string message, /// Serialization information. /// Streaming context. /// Constructed object. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected PipelineDepthException(SerializationInfo info, - StreamingContext context) - : base(info, context) + StreamingContext context) { - } - /// - /// Serializer for - /// - /// Serialization information. - /// Context. - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - base.GetObjectData(info, context); + throw new NotSupportedException(); } #endregion Serialization @@ -1015,8 +919,7 @@ public int CallDepth /// /// Note that HaltCommandException does not define IContainsErrorRecord. /// This is because it is not reported to the user. - /// - [Serializable] + /// public class HaltCommandException : SystemException { #region ctor @@ -1061,10 +964,11 @@ public HaltCommandException(string message, /// Serialization information. /// Streaming context. /// Constructed object. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected HaltCommandException(SerializationInfo info, StreamingContext context) - : base(info, context) { + throw new NotSupportedException(); } #endregion Serialization } diff --git a/src/System.Management.Automation/utils/HostInterfacesExceptions.cs b/src/System.Management.Automation/utils/HostInterfacesExceptions.cs index 91e742fa3c5..362a1448207 100644 --- a/src/System.Management.Automation/utils/HostInterfacesExceptions.cs +++ b/src/System.Management.Automation/utils/HostInterfacesExceptions.cs @@ -10,7 +10,6 @@ namespace System.Management.Automation.Host /// Defines the exception thrown when the Host cannot complete an operation /// such as checking whether there is any input available. /// - [Serializable] public class HostException : RuntimeException { @@ -101,10 +100,11 @@ class HostException : RuntimeException /// /// The contextual information about the source or destination. /// + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected HostException(SerializationInfo info, StreamingContext context) - : base(info, context) { + throw new NotSupportedException(); } #endregion @@ -120,8 +120,7 @@ private void SetDefaultErrorRecord() /// /// Defines the exception thrown when an error occurs from prompting for a command parameter. - /// - [Serializable] + /// public class PromptingException : HostException { @@ -210,10 +209,11 @@ class PromptingException : HostException /// /// The contextual information about the source or destination. /// + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected PromptingException(SerializationInfo info, StreamingContext context) - : base(info, context) { + throw new NotSupportedException(); } #endregion diff --git a/src/System.Management.Automation/utils/MetadataExceptions.cs b/src/System.Management.Automation/utils/MetadataExceptions.cs index 21e499ce5e4..f2c4ace8647 100644 --- a/src/System.Management.Automation/utils/MetadataExceptions.cs +++ b/src/System.Management.Automation/utils/MetadataExceptions.cs @@ -10,7 +10,6 @@ namespace System.Management.Automation /// /// Defines the exception thrown for all Metadata errors. /// - [Serializable] public class MetadataException : RuntimeException { internal const string MetadataMemberInitialization = "MetadataMemberInitialization"; @@ -21,9 +20,10 @@ public class MetadataException : RuntimeException /// /// Serialization information. /// Streaming context. - protected MetadataException(SerializationInfo info, StreamingContext context) : base(info, context) + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] + protected MetadataException(SerializationInfo info, StreamingContext context) { - SetErrorCategory(ErrorCategory.MetadataError); + throw new NotSupportedException(); } /// @@ -71,7 +71,6 @@ internal MetadataException( /// /// Defines the exception thrown for all Validate attributes. /// - [Serializable] [SuppressMessage("Microsoft.Usage", "CA2240:ImplementISerializableCorrectly")] public class ValidationMetadataException : MetadataException { @@ -109,7 +108,12 @@ public class ValidationMetadataException : MetadataException /// /// Serialization information. /// Streaming context. - protected ValidationMetadataException(SerializationInfo info, StreamingContext context) : base(info, context) { } + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] + protected ValidationMetadataException(SerializationInfo info, StreamingContext context) + { + throw new NotSupportedException(); + } + /// /// Initializes a new instance of ValidationMetadataException with the message set /// to typeof(ValidationMetadataException).FullName. @@ -167,7 +171,6 @@ internal bool SwallowException /// /// Defines the exception thrown for all ArgumentTransformation attributes. /// - [Serializable] public class ArgumentTransformationMetadataException : MetadataException { internal const string ArgumentTransformationArgumentsShouldBeStrings = "ArgumentTransformationArgumentsShouldBeStrings"; @@ -177,8 +180,11 @@ public class ArgumentTransformationMetadataException : MetadataException /// /// Serialization information. /// Streaming context. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected ArgumentTransformationMetadataException(SerializationInfo info, StreamingContext context) - : base(info, context) { } + { + throw new NotSupportedException(); + } /// /// Initializes a new instance of ArgumentTransformationMetadataException with the message set @@ -215,7 +221,6 @@ internal ArgumentTransformationMetadataException( /// /// Defines the exception thrown for all parameter binding exceptions related to metadata attributes. /// - [Serializable] public class ParsingMetadataException : MetadataException { internal const string ParsingTooManyParameterSets = "ParsingTooManyParameterSets"; @@ -225,8 +230,11 @@ public class ParsingMetadataException : MetadataException /// /// Serialization information. /// Streaming context. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected ParsingMetadataException(SerializationInfo info, StreamingContext context) - : base(info, context) { } + { + throw new NotSupportedException(); + } /// /// Initializes a new instance of ParsingMetadataException with the message set diff --git a/src/System.Management.Automation/utils/MshArgumentException.cs b/src/System.Management.Automation/utils/MshArgumentException.cs index d1e14a92f3b..baa3f8c3163 100644 --- a/src/System.Management.Automation/utils/MshArgumentException.cs +++ b/src/System.Management.Automation/utils/MshArgumentException.cs @@ -16,7 +16,6 @@ namespace System.Management.Automation /// PowerShell Engine. It is unusual for code outside the PowerShell Engine /// to create an instance of this class. /// - [Serializable] public class PSArgumentException : ArgumentException, IContainsErrorRecord { @@ -69,30 +68,13 @@ public PSArgumentException(string message, string paramName) /// Serialization information. /// Streaming context. /// Constructed object. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected PSArgumentException(SerializationInfo info, StreamingContext context) - : base(info, context) { - _errorId = info.GetString("ErrorId"); - _message = info.GetString("PSArgumentException_MessageOverride"); + throw new NotSupportedException(); } - /// - /// Serializer for - /// - /// Serialization information. - /// Streaming context. - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw new PSArgumentNullException(nameof(info)); - } - - base.GetObjectData(info, context); - info.AddValue("ErrorId", _errorId); - info.AddValue("PSArgumentException_MessageOverride", _message); - } #endregion Serialization /// diff --git a/src/System.Management.Automation/utils/MshArgumentNullException.cs b/src/System.Management.Automation/utils/MshArgumentNullException.cs index 66f0a35dbbf..a4f50256e44 100644 --- a/src/System.Management.Automation/utils/MshArgumentNullException.cs +++ b/src/System.Management.Automation/utils/MshArgumentNullException.cs @@ -16,7 +16,6 @@ namespace System.Management.Automation /// PowerShell Engine. It is unusual for code outside the PowerShell Engine /// to create an instance of this class. /// - [Serializable] public class PSArgumentNullException : ArgumentNullException, IContainsErrorRecord { @@ -80,30 +79,12 @@ public PSArgumentNullException(string paramName, string message) /// Serialization information. /// Streaming context. /// Constructed object. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected PSArgumentNullException(SerializationInfo info, StreamingContext context) - : base(info, context) { - _errorId = info.GetString("ErrorId"); - _message = info.GetString("PSArgumentNullException_MessageOverride"); - } - - /// - /// Serializer for - /// - /// Serialization information. - /// Streaming context. - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw new PSArgumentNullException(nameof(info)); - } - - base.GetObjectData(info, context); - info.AddValue("ErrorId", _errorId); - info.AddValue("PSArgumentNullException_MessageOverride", _message); - } + throw new NotSupportedException(); + } #endregion Serialization #endregion ctor diff --git a/src/System.Management.Automation/utils/MshArgumentOutOfRangeException.cs b/src/System.Management.Automation/utils/MshArgumentOutOfRangeException.cs index 955d5009256..8d666778a4f 100644 --- a/src/System.Management.Automation/utils/MshArgumentOutOfRangeException.cs +++ b/src/System.Management.Automation/utils/MshArgumentOutOfRangeException.cs @@ -16,7 +16,6 @@ namespace System.Management.Automation /// PowerShell Engine. It is unusual for code outside the PowerShell Engine /// to create an instance of this class. /// - [Serializable] public class PSArgumentOutOfRangeException : ArgumentOutOfRangeException, IContainsErrorRecord { @@ -68,28 +67,13 @@ public PSArgumentOutOfRangeException(string paramName, object actualValue, strin /// Serialization information. /// Streaming context. /// Constructed object. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected PSArgumentOutOfRangeException(SerializationInfo info, StreamingContext context) - : base(info, context) { - _errorId = info.GetString("ErrorId"); - } - - /// - /// Serializer for - /// - /// Serialization information. - /// Streaming context. - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw new PSArgumentNullException(nameof(info)); - } - - base.GetObjectData(info, context); - info.AddValue("ErrorId", _errorId); + throw new NotSupportedException(); } + #endregion Serialization /// diff --git a/src/System.Management.Automation/utils/MshInvalidOperationException.cs b/src/System.Management.Automation/utils/MshInvalidOperationException.cs index 520818cb405..f398e4a2e99 100644 --- a/src/System.Management.Automation/utils/MshInvalidOperationException.cs +++ b/src/System.Management.Automation/utils/MshInvalidOperationException.cs @@ -16,7 +16,6 @@ namespace System.Management.Automation /// PowerShell Engine. It is unusual for code outside the PowerShell Engine /// to create an instance of this class. /// - [Serializable] public class PSInvalidOperationException : InvalidOperationException, IContainsErrorRecord { @@ -39,27 +38,11 @@ public PSInvalidOperationException() /// Serialization information. /// Streaming context. /// Constructed object. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected PSInvalidOperationException(SerializationInfo info, StreamingContext context) - : base(info, context) { - _errorId = info.GetString("ErrorId"); - } - - /// - /// Serializer for - /// - /// Serialization information. - /// Streaming context. - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw new PSArgumentNullException(nameof(info)); - } - - base.GetObjectData(info, context); - info.AddValue("ErrorId", _errorId); + throw new NotSupportedException(); } #endregion Serialization diff --git a/src/System.Management.Automation/utils/MshNotImplementedException.cs b/src/System.Management.Automation/utils/MshNotImplementedException.cs index e939c593842..7d1082bf747 100644 --- a/src/System.Management.Automation/utils/MshNotImplementedException.cs +++ b/src/System.Management.Automation/utils/MshNotImplementedException.cs @@ -16,7 +16,6 @@ namespace System.Management.Automation /// PowerShell Engine. It is unusual for code outside the PowerShell Engine /// to create an instance of this class. /// - [Serializable] public class PSNotImplementedException : NotImplementedException, IContainsErrorRecord { @@ -39,28 +38,12 @@ public PSNotImplementedException() /// Serialization information. /// Streaming context. /// Constructed object. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected PSNotImplementedException(SerializationInfo info, StreamingContext context) - : base(info, context) { - _errorId = info.GetString("ErrorId"); - } - - /// - /// Serializer for - /// - /// Serialization information. - /// Streaming context. - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw new PSArgumentNullException(nameof(info)); - } - - base.GetObjectData(info, context); - info.AddValue("ErrorId", _errorId); - } + throw new NotSupportedException(); + } #endregion Serialization /// diff --git a/src/System.Management.Automation/utils/MshNotSupportedException.cs b/src/System.Management.Automation/utils/MshNotSupportedException.cs index 8c878660ba4..1268636742b 100644 --- a/src/System.Management.Automation/utils/MshNotSupportedException.cs +++ b/src/System.Management.Automation/utils/MshNotSupportedException.cs @@ -16,7 +16,6 @@ namespace System.Management.Automation /// PowerShell Engine. It is unusual for code outside the PowerShell Engine /// to create an instance of this class. /// - [Serializable] public class PSNotSupportedException : NotSupportedException, IContainsErrorRecord { @@ -39,28 +38,13 @@ public PSNotSupportedException() /// Serialization information. /// Streaming context. /// Constructed object. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected PSNotSupportedException(SerializationInfo info, StreamingContext context) - : base(info, context) { - _errorId = info.GetString("ErrorId"); - } - - /// - /// Serializer for - /// - /// Serialization information. - /// Streaming context. - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw new PSArgumentNullException(nameof(info)); - } - - base.GetObjectData(info, context); - info.AddValue("ErrorId", _errorId); + throw new NotSupportedException(); } + #endregion Serialization /// diff --git a/src/System.Management.Automation/utils/MshObjectDisposedException.cs b/src/System.Management.Automation/utils/MshObjectDisposedException.cs index af2658ed25d..1bbf1f846d4 100644 --- a/src/System.Management.Automation/utils/MshObjectDisposedException.cs +++ b/src/System.Management.Automation/utils/MshObjectDisposedException.cs @@ -16,7 +16,6 @@ namespace System.Management.Automation /// PowerShell Engine. It is unusual for code outside the PowerShell Engine /// to create an instance of this class. /// - [Serializable] public class PSObjectDisposedException : ObjectDisposedException, IContainsErrorRecord { @@ -67,28 +66,12 @@ public PSObjectDisposedException(string message, Exception innerException) /// Serialization information. /// Streaming context. /// Constructed object. - protected PSObjectDisposedException(SerializationInfo info, - StreamingContext context) - : base(info, context) + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] + protected PSObjectDisposedException(SerializationInfo info, StreamingContext context) : base(info, context) { - _errorId = info.GetString("ErrorId"); + throw new NotSupportedException(); } - /// - /// Serializer for - /// - /// Serialization information. - /// Streaming context. - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw new PSArgumentNullException(nameof(info)); - } - - base.GetObjectData(info, context); - info.AddValue("ErrorId", _errorId); - } #endregion Serialization #endregion ctor diff --git a/src/System.Management.Automation/utils/ParameterBinderExceptions.cs b/src/System.Management.Automation/utils/ParameterBinderExceptions.cs index fcb10737d35..2f9a15d4dd2 100644 --- a/src/System.Management.Automation/utils/ParameterBinderExceptions.cs +++ b/src/System.Management.Automation/utils/ParameterBinderExceptions.cs @@ -10,7 +10,6 @@ namespace System.Management.Automation /// /// The exception thrown if the specified value can not be bound parameter of a command. /// - [Serializable] public class ParameterBindingException : RuntimeException { #region Constructors @@ -298,38 +297,12 @@ internal ParameterBindingException( /// /// streaming context /// + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected ParameterBindingException( SerializationInfo info, StreamingContext context) - : base(info, context) { - _message = info.GetString("ParameterBindingException_Message"); - _parameterName = info.GetString("ParameterName"); - _line = info.GetInt64("Line"); - _offset = info.GetInt64("Offset"); - } - - /// - /// Serializes the exception. - /// - /// - /// serialization information - /// - /// - /// streaming context - /// - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw new PSArgumentNullException(nameof(info)); - } - - base.GetObjectData(info, context); - info.AddValue("ParameterBindingException_Message", this.Message); - info.AddValue("ParameterName", _parameterName); - info.AddValue("Line", _line); - info.AddValue("Offset", _offset); + throw new NotSupportedException(); } #endregion serialization @@ -513,8 +486,7 @@ private string BuildMessage() #endregion Private } - - [Serializable] + internal class ParameterBindingValidationException : ParameterBindingException { #region Preferred constructors @@ -683,11 +655,12 @@ internal ParameterBindingValidationException( /// /// streaming context /// + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected ParameterBindingValidationException( SerializationInfo info, StreamingContext context) - : base(info, context) { + throw new NotSupportedException(); } #endregion serialization @@ -710,7 +683,6 @@ internal bool SwallowException #endregion Property } - [Serializable] internal class ParameterBindingArgumentTransformationException : ParameterBindingException { #region Preferred constructors @@ -873,17 +845,17 @@ internal ParameterBindingArgumentTransformationException( /// /// streaming context /// + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected ParameterBindingArgumentTransformationException( SerializationInfo info, StreamingContext context) - : base(info, context) { + throw new NotSupportedException(); } #endregion serialization } - - [Serializable] + internal class ParameterBindingParameterDefaultValueException : ParameterBindingException { #region Preferred constructors @@ -1047,11 +1019,12 @@ internal ParameterBindingParameterDefaultValueException( /// /// streaming context /// + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected ParameterBindingParameterDefaultValueException( SerializationInfo info, StreamingContext context) - : base(info, context) { + throw new NotSupportedException(); } #endregion serialization diff --git a/src/System.Management.Automation/utils/ParserException.cs b/src/System.Management.Automation/utils/ParserException.cs index 4070fa7e7f1..aadf52490b4 100644 --- a/src/System.Management.Automation/utils/ParserException.cs +++ b/src/System.Management.Automation/utils/ParserException.cs @@ -11,7 +11,6 @@ namespace System.Management.Automation /// /// Defines the exception thrown when a syntax error occurs while parsing PowerShell script text. /// - [Serializable] public class ParseException : RuntimeException { private const string errorIdString = "Parse"; @@ -34,25 +33,11 @@ public ParseError[] Errors /// The serialization information to use when initializing this object. /// The streaming context to use when initializing this object. /// Constructed object. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected ParseException(SerializationInfo info, StreamingContext context) - : base(info, context) { - _errors = (ParseError[])info.GetValue("Errors", typeof(ParseError[])); - } - - /// - /// Add private data for serialization. - /// - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw new PSArgumentNullException(nameof(info)); - } - - base.GetObjectData(info, context); - info.AddValue("Errors", _errors); + throw new NotSupportedException(); } #endregion Serialization @@ -175,7 +160,6 @@ public override string Message /// rather than irrecoverably wrong. A host can catch this exception and then prompt for additional /// input to complete the parse. /// - [Serializable] public class IncompleteParseException : ParseException { @@ -193,10 +177,11 @@ public class IncompleteParseException /// The serialization information to use when initializing this object. /// The streaming context to use when initializing this object. /// Constructed object. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected IncompleteParseException(SerializationInfo info, StreamingContext context) - : base(info, context) { + throw new NotSupportedException(); } #endregion Serialization diff --git a/src/System.Management.Automation/utils/RuntimeException.cs b/src/System.Management.Automation/utils/RuntimeException.cs index 4ee2e1916b5..8c0bcee5f1d 100644 --- a/src/System.Management.Automation/utils/RuntimeException.cs +++ b/src/System.Management.Automation/utils/RuntimeException.cs @@ -18,7 +18,6 @@ namespace System.Management.Automation /// PowerShell Engine. It is unusual for code outside the PowerShell Engine /// to create an instance of this class. /// - [Serializable] public class RuntimeException : SystemException, IContainsErrorRecord { @@ -41,30 +40,12 @@ public RuntimeException() /// Serialization information. /// Streaming context. /// Constructed object. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected RuntimeException(SerializationInfo info, StreamingContext context) - : base(info, context) { - _errorId = info.GetString("ErrorId"); - _errorCategory = (ErrorCategory)info.GetInt32("ErrorCategory"); - } - - /// - /// Serializer for - /// - /// Serialization information. - /// Streaming context. - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw new PSArgumentNullException(nameof(info)); - } - - base.GetObjectData(info, context); - info.AddValue("ErrorId", _errorId); - info.AddValue("ErrorCategory", (int)_errorCategory); - } + throw new NotSupportedException(); + } #endregion Serialization /// diff --git a/src/System.Management.Automation/utils/SessionStateExceptions.cs b/src/System.Management.Automation/utils/SessionStateExceptions.cs index 5734fbc6269..dd15e9ad463 100644 --- a/src/System.Management.Automation/utils/SessionStateExceptions.cs +++ b/src/System.Management.Automation/utils/SessionStateExceptions.cs @@ -12,7 +12,6 @@ namespace System.Management.Automation /// callers of the provider APIs to be able to catch a single exception no matter /// what any of the various providers may have thrown. /// - [Serializable] public class ProviderInvocationException : RuntimeException { #region Constructors @@ -32,11 +31,12 @@ public ProviderInvocationException() : base() /// /// streaming context /// + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected ProviderInvocationException( SerializationInfo info, StreamingContext context) - : base(info, context) { + throw new NotSupportedException(); } /// @@ -382,7 +382,6 @@ public enum SessionStateCategory /// session state objects: variables, aliases, functions, filters, /// drives, or providers. /// - [Serializable] public class SessionStateException : RuntimeException { #region ctor @@ -451,37 +450,17 @@ public SessionStateException(string message, { } #endregion ctor - - #region Serialization - /// +/// /// Constructs a SessionStateException using serialized data. /// /// Serialization information. /// Streaming context. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected SessionStateException(SerializationInfo info, StreamingContext context) - : base(info, context) { - _sessionStateCategory = (SessionStateCategory)info.GetInt32("SessionStateCategory"); // CODEWORK test this - } - - /// - /// Serializes the exception data. - /// - /// Serialization information. - /// Streaming context. - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw new PSArgumentNullException(nameof(info)); - } - - base.GetObjectData(info, context); - // If there are simple fields, serialize them with info.AddValue - info.AddValue("SessionStateCategory", (int)_sessionStateCategory); + throw new NotSupportedException(); } - #endregion Serialization #region Properties /// @@ -558,7 +537,6 @@ private static string BuildMessage( /// an object which is declared constant cannot be removed /// or made non-constant. /// - [Serializable] public class SessionStateUnauthorizedAccessException : SessionStateException { #region ctor @@ -592,6 +570,19 @@ string resourceStr { } + /// + /// Constructs a SessionStateUnauthorizedAccessException using serialized data. + /// + /// Serialization information. + /// Streaming context. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] + protected SessionStateUnauthorizedAccessException( + SerializationInfo info, + StreamingContext context) + { + throw new NotSupportedException(); + } + /// /// Constructs a SessionStateUnauthorizedAccessException. /// @@ -626,27 +617,12 @@ public SessionStateUnauthorizedAccessException(string message, { } #endregion ctor - - #region Serialization - /// - /// Constructs a SessionStateUnauthorizedAccessException using serialized data. - /// - /// Serialization information. - /// Streaming context. - protected SessionStateUnauthorizedAccessException( - SerializationInfo info, - StreamingContext context) - : base(info, context) - { - } - #endregion Serialization } /// /// ProviderNotFoundException occurs when no provider can be found /// with the specified name. /// - [Serializable] public class ProviderNotFoundException : SessionStateException { #region ctor @@ -720,27 +696,12 @@ public ProviderNotFoundException(string message, { } #endregion ctor - - #region Serialization - /// - /// Constructs a ProviderNotFoundException using serialized data. - /// - /// Serialization information. - /// Streaming context. - protected ProviderNotFoundException( - SerializationInfo info, - StreamingContext context) - : base(info, context) - { - } - #endregion Serialization } /// /// ProviderNameAmbiguousException occurs when more than one provider exists /// for a given name and the request did not contain the PSSnapin name qualifier. /// - [Serializable] public class ProviderNameAmbiguousException : ProviderNotFoundException { #region ctor @@ -816,19 +777,18 @@ public ProviderNameAmbiguousException(string message, } #endregion ctor - #region Serialization /// /// Constructs a ProviderNameAmbiguousException using serialized data. /// /// Serialization information. /// Streaming context. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected ProviderNameAmbiguousException( SerializationInfo info, StreamingContext context) - : base(info, context) { + throw new NotSupportedException(); } - #endregion Serialization #region public properties @@ -853,7 +813,6 @@ public ReadOnlyCollection PossibleMatches /// DriveNotFoundException occurs when no drive can be found /// with the specified name. /// - [Serializable] public class DriveNotFoundException : SessionStateException { #region ctor @@ -916,26 +875,24 @@ public DriveNotFoundException(string message, } #endregion ctor - #region Serialization /// /// Constructs a DriveNotFoundException using serialized data. /// /// Serialization information. /// Streaming context. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected DriveNotFoundException( SerializationInfo info, StreamingContext context) - : base(info, context) { + throw new NotSupportedException(); } - #endregion Serialization } /// /// ItemNotFoundException occurs when the path contained no wildcard characters /// and an item at that path could not be found. /// - [Serializable] public class ItemNotFoundException : SessionStateException { #region ctor @@ -1000,18 +957,17 @@ public ItemNotFoundException(string message, } #endregion ctor - #region Serialization /// /// Constructs a ItemNotFoundException using serialized data. /// /// Serialization information. /// Streaming context. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected ItemNotFoundException( SerializationInfo info, StreamingContext context) - : base(info, context) { + throw new NotSupportedException(); } - #endregion Serialization } } diff --git a/test/powershell/engine/Basic/StandardLibraryTypes.Tests.ps1 b/test/powershell/engine/Basic/StandardLibraryTypes.Tests.ps1 index 18dc449039d..51191f49764 100644 --- a/test/powershell/engine/Basic/StandardLibraryTypes.Tests.ps1 +++ b/test/powershell/engine/Basic/StandardLibraryTypes.Tests.ps1 @@ -53,7 +53,6 @@ Describe "Types referenced by PowerShell Standard should not be missing" -Tags "IsPrimitive", "IsValueType", "IsSignatureType", - "IsSerializable", "IsVisible" $tests = Import-Csv $assets | ForEach-Object { diff --git a/test/tools/NamedPipeConnection/src/code/Microsoft.PowerShell.NamedPipeConnection.csproj b/test/tools/NamedPipeConnection/src/code/Microsoft.PowerShell.NamedPipeConnection.csproj index 3959c584e8c..85913be6abe 100644 --- a/test/tools/NamedPipeConnection/src/code/Microsoft.PowerShell.NamedPipeConnection.csproj +++ b/test/tools/NamedPipeConnection/src/code/Microsoft.PowerShell.NamedPipeConnection.csproj @@ -15,6 +15,6 @@ - + diff --git a/test/tools/TestService/TestService.csproj b/test/tools/TestService/TestService.csproj index 1e25fb6b580..45b457de6ef 100644 --- a/test/tools/TestService/TestService.csproj +++ b/test/tools/TestService/TestService.csproj @@ -13,7 +13,7 @@ - + diff --git a/test/tools/WebListener/WebListener.csproj b/test/tools/WebListener/WebListener.csproj index 2bc28b42845..aec3e13f507 100644 --- a/test/tools/WebListener/WebListener.csproj +++ b/test/tools/WebListener/WebListener.csproj @@ -7,8 +7,8 @@ - - + + diff --git a/tools/packaging/boms/windows.json b/tools/packaging/boms/windows.json index 39c0679891f..8f47f13768e 100644 --- a/tools/packaging/boms/windows.json +++ b/tools/packaging/boms/windows.json @@ -211,10 +211,6 @@ "Pattern": "en-US/default.help.txt", "FileType": "NonProduct" }, - { - "Pattern": "es-ES\\JsonSchema.Net.resources.dll", - "FileType": "NonProduct" - }, { "Pattern": "es/Microsoft.CodeAnalysis.CSharp.resources.dll", "FileType": "NonProduct" @@ -812,99 +808,95 @@ "FileType": "NonProduct" }, { - "Pattern": "Modules/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1", - "FileType": "NonProduct" - }, - { - "Pattern": "Modules/PackageManagement/*.dll", + "Pattern": "Modules/Microsoft.PowerShell.PSResourceGet/_manifest/spdx_2.2/manifest.cat", "FileType": "NonProduct" }, { - "Pattern": "Modules/PackageManagement/*.mof", + "Pattern": "Modules/Microsoft.PowerShell.PSResourceGet/dependencies/*.dll", "FileType": "NonProduct" }, { - "Pattern": "Modules/PackageManagement/*.ps?1", + "Pattern": "Modules/Microsoft.PowerShell.PSResourceGet/LICENSE", "FileType": "NonProduct" }, { - "Pattern": "Modules/PackageManagement/*.ps1xml", + "Pattern": "Modules/Microsoft.PowerShell.PSResourceGet/Microsoft.PowerShell.PSResourceGet.dll", "FileType": "NonProduct" }, { - "Pattern": "Modules/PowerShellGet/*.mfl", + "Pattern": "Modules/Microsoft.PowerShell.PSResourceGet/Microsoft.PowerShell.PSResourceGet.psd1", "FileType": "NonProduct" }, { - "Pattern": "Modules/PowerShellGet/*.mof", + "Pattern": "Modules/Microsoft.PowerShell.PSResourceGet/Notice.txt", "FileType": "NonProduct" }, { - "Pattern": "Modules/PowerShellGet/*.ps?1", + "Pattern": "Modules/Microsoft.PowerShell.PSResourceGet/PSGet.Format.ps1xml", "FileType": "NonProduct" }, { - "Pattern": "Modules/PowerShellGet/*.ps1xml", + "Pattern": "Modules/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1", "FileType": "NonProduct" }, { - "Pattern": "Modules/PSReadLine/*.dll", + "Pattern": "Modules/PackageManagement/*.dll", "FileType": "NonProduct" }, { - "Pattern": "Modules/PSReadLine/*.ps?1", + "Pattern": "Modules/PackageManagement/*.mof", "FileType": "NonProduct" }, { - "Pattern": "Modules/PSReadLine/*.ps1", + "Pattern": "Modules/PackageManagement/*.ps?1", "FileType": "NonProduct" }, { - "Pattern": "Modules/PSReadLine/*.ps1xml", + "Pattern": "Modules/PackageManagement/*.ps1xml", "FileType": "NonProduct" }, { - "Pattern": "Modules/PSReadLine/*.txt", + "Pattern": "Modules/PowerShellGet/*.mfl", "FileType": "NonProduct" }, { - "Pattern": "Modules/ThreadJob/*.dll", + "Pattern": "Modules/PowerShellGet/*.mof", "FileType": "NonProduct" }, { - "Pattern": "Modules/ThreadJob/*.psd1", + "Pattern": "Modules/PowerShellGet/*.ps?1", "FileType": "NonProduct" }, { - "Pattern": "Modules/Microsoft.PowerShell.PSResourceGet/_manifest/spdx_2.2/manifest.cat", + "Pattern": "Modules/PowerShellGet/*.ps1xml", "FileType": "NonProduct" }, { - "Pattern": "Modules/Microsoft.PowerShell.PSResourceGet/LICENSE", + "Pattern": "Modules/PSReadLine/*.dll", "FileType": "NonProduct" }, { - "Pattern": "Modules/Microsoft.PowerShell.PSResourceGet/Notice.txt", + "Pattern": "Modules/PSReadLine/*.ps?1", "FileType": "NonProduct" }, { - "Pattern": "Modules/Microsoft.PowerShell.PSResourceGet/dependencies/*.dll", + "Pattern": "Modules/PSReadLine/*.ps1", "FileType": "NonProduct" }, { - "Pattern": "Modules/Microsoft.PowerShell.PSResourceGet/Microsoft.PowerShell.PSResourceGet.dll", + "Pattern": "Modules/PSReadLine/*.ps1xml", "FileType": "NonProduct" }, { - "Pattern": "Modules/Microsoft.PowerShell.PSResourceGet/Microsoft.PowerShell.PSResourceGet.psd1", + "Pattern": "Modules/PSReadLine/*.txt", "FileType": "NonProduct" }, { - "Pattern": "Modules/Microsoft.PowerShell.PSResourceGet/PSGet.Format.ps1xml", + "Pattern": "Modules/ThreadJob/*.dll", "FileType": "NonProduct" }, { - "Pattern": "mscordaccore_*.dll", + "Pattern": "Modules/ThreadJob/*.psd1", "FileType": "NonProduct" }, { @@ -931,10 +923,6 @@ "Pattern": "msquic.dll", "FileType": "NonProduct" }, - { - "Pattern": "nb-NO\\JsonSchema.Net.resources.dll", - "FileType": "NonProduct" - }, { "Pattern": "netstandard.dll", "FileType": "NonProduct" @@ -2175,10 +2163,6 @@ "Pattern": "sni.dll", "FileType": "NonProduct" }, - { - "Pattern": "sv-SE\\JsonSchema.Net.resources.dll", - "FileType": "NonProduct" - }, { "Pattern": "System.AppContext.dll", "FileType": "NonProduct" From 5cfe77f000da00b038c19ca25cd384d89c2e233e Mon Sep 17 00:00:00 2001 From: PowerShell Team Bot <69177312+pwshBot@users.noreply.github.com> Date: Thu, 22 Jun 2023 10:20:59 -0700 Subject: [PATCH 607/779] Update the cgmanifest (#19839) --- tools/cgmanifest.json | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tools/cgmanifest.json b/tools/cgmanifest.json index 50b091be068..513dd7c7b77 100644 --- a/tools/cgmanifest.json +++ b/tools/cgmanifest.json @@ -1,5 +1,4 @@ { - "$schema": "https://json.schemastore.org/component-detection-manifest.json", "Registrations": [ { "Component": { @@ -346,7 +345,7 @@ "Type": "nuget", "Nuget": { "Name": "StyleCop.Analyzers.Unstable", - "Version": "1.2.0.435" + "Version": "1.2.0.507" } }, "DevelopmentDependency": true @@ -816,7 +815,7 @@ "Type": "nuget", "Nuget": { "Name": "System.Web.Services.Description", - "Version": "4.9.0" + "Version": "4.10.0" } }, "DevelopmentDependency": false @@ -831,5 +830,6 @@ }, "DevelopmentDependency": false } - ] + ], + "$schema": "https://json.schemastore.org/component-detection-manifest.json" } From 9ca01729c27258ffd2531cba7f39615329e70f6d Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 22 Jun 2023 10:21:35 -0700 Subject: [PATCH 608/779] Bump Microsoft.CodeAnalysis.CSharp from 4.6.0 to 4.7.0-2.final (#19838) --- .../Microsoft.PowerShell.Commands.Utility.csproj | 2 +- .../PSVersionInfoGenerator/PSVersionInfoGenerator.csproj | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj index 5afbfea5a35..0eb0a781f19 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj +++ b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj @@ -32,7 +32,7 @@ - + diff --git a/src/System.Management.Automation/SourceGenerators/PSVersionInfoGenerator/PSVersionInfoGenerator.csproj b/src/System.Management.Automation/SourceGenerators/PSVersionInfoGenerator/PSVersionInfoGenerator.csproj index 344ef48674c..c7971775068 100644 --- a/src/System.Management.Automation/SourceGenerators/PSVersionInfoGenerator/PSVersionInfoGenerator.csproj +++ b/src/System.Management.Automation/SourceGenerators/PSVersionInfoGenerator/PSVersionInfoGenerator.csproj @@ -13,7 +13,7 @@ - + From 04f503a3b7a1b6e493d86839efd70c542563bd3c Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 22 Jun 2023 10:22:04 -0700 Subject: [PATCH 609/779] Bump StyleCop.Analyzers from 1.2.0-beta.406 to 1.2.0-beta.507 (#19837) --- Analyzers.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Analyzers.props b/Analyzers.props index 6988cf57f5d..2608f972630 100644 --- a/Analyzers.props +++ b/Analyzers.props @@ -1,6 +1,6 @@ - + From 066d7bff2cacba973ba81bbb57355da72c7735f2 Mon Sep 17 00:00:00 2001 From: Patrick Meinecke Date: Fri, 23 Jun 2023 15:16:18 -0400 Subject: [PATCH 610/779] Fix native executables not redirecting to file (#19842) --- .../engine/NativeCommandProcessor.cs | 14 ++++++++++---- .../engine/Basic/NativeCommandBytePiping.Tests.ps1 | 14 ++++++++++++++ 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/src/System.Management.Automation/engine/NativeCommandProcessor.cs b/src/System.Management.Automation/engine/NativeCommandProcessor.cs index 10c4dda1e5c..b511054a051 100644 --- a/src/System.Management.Automation/engine/NativeCommandProcessor.cs +++ b/src/System.Management.Automation/engine/NativeCommandProcessor.cs @@ -1594,15 +1594,19 @@ private void CalculateIORedirection(bool isWindowsApplication, out bool redirect // $powershell.AddScript('ipconfig.exe') // $powershell.AddCommand('Out-Default') // $powershell.Invoke()) - // we should not count it as a redirection. - if (IsDownstreamOutDefault(this.commandRuntime.OutputPipe)) + // we should not count it as a redirection. Unless the native command has its stdout redirected + // for example: + // cmd.exe /c "echo test" > somefile.log + // in that case we want to keep output redirection even though Out-Default is the only + // downstream command. + if (IsDownstreamOutDefault(this.commandRuntime.OutputPipe) && StdOutDestination is null) { redirectOutput = false; } } // See if the error output stream has been redirected, either through an explicit 2> foo.txt or - // my merging error into output through 2>&1. + // by merging error into output through 2>&1. if (CommandRuntime.ErrorMergeTo != MshCommandRuntime.MergeDataStream.Output) { // If the error output pipe is the default outputter, for example, calling the native command from command-line host, @@ -1612,7 +1616,9 @@ private void CalculateIORedirection(bool isWindowsApplication, out bool redirect // $powershell.AddScript('ipconfig.exe') // $powershell.AddCommand('Out-Default') // $powershell.Invoke()) - // we should not count that as a redirection. + // we should not count that as a redirection. We do not need to worry + // about StdOutDestination here as if error is redirected then it's assumed + // to be text based and Out-File will be added to the pipeline instead. if (IsDownstreamOutDefault(this.commandRuntime.ErrorOutputPipe)) { redirectError = false; diff --git a/test/powershell/engine/Basic/NativeCommandBytePiping.Tests.ps1 b/test/powershell/engine/Basic/NativeCommandBytePiping.Tests.ps1 index 8126c08473f..1e645df9030 100644 --- a/test/powershell/engine/Basic/NativeCommandBytePiping.Tests.ps1 +++ b/test/powershell/engine/Basic/NativeCommandBytePiping.Tests.ps1 @@ -63,4 +63,18 @@ Describe 'Native command byte piping tests' -Tags 'CI' { ($pipe)?.Dispose() } } + + It 'Bytes are retained when redirecting to a file' { + testexe -writebytes FF > $TestDrive/content.bin | Should -BeNullOrEmpty + Get-Content -LiteralPath $TestDrive/content.bin -AsByteStream | Should -Be 0xFFuy + } + + It 'Bytes are retained when redirecting to a file and Out-Default is downstream' { + testexe -writebytes FF > $TestDrive/content2.bin | Out-Default + Get-Content -LiteralPath $TestDrive/content2.bin -AsByteStream | Should -Be 0xFFuy + } + + It 'Redirecting to $null should emit no output' { + testexe -writebytes FF > $null | Should -BeNullOrEmpty + } } From f504ae44317fb5f6670c55b72283dd63b54db688 Mon Sep 17 00:00:00 2001 From: PowerShell Team Bot <69177312+pwshBot@users.noreply.github.com> Date: Fri, 23 Jun 2023 12:27:42 -0700 Subject: [PATCH 611/779] Update the cgmanifest (#19847) --- tools/cgmanifest.json | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tools/cgmanifest.json b/tools/cgmanifest.json index 513dd7c7b77..7686a5581fb 100644 --- a/tools/cgmanifest.json +++ b/tools/cgmanifest.json @@ -1,4 +1,5 @@ { + "$schema": "https://json.schemastore.org/component-detection-manifest.json", "Registrations": [ { "Component": { @@ -225,7 +226,7 @@ "Type": "nuget", "Nuget": { "Name": "Microsoft.Windows.Compatibility", - "Version": "7.0.3" + "Version": "7.0.4" } }, "DevelopmentDependency": false @@ -645,7 +646,7 @@ "Type": "nuget", "Nuget": { "Name": "System.Security.Cryptography.Pkcs", - "Version": "7.0.2" + "Version": "7.0.3" } }, "DevelopmentDependency": false @@ -830,6 +831,5 @@ }, "DevelopmentDependency": false } - ], - "$schema": "https://json.schemastore.org/component-detection-manifest.json" + ] } From fd586faa9854512e57f600da198d7a6ea7557c36 Mon Sep 17 00:00:00 2001 From: Sean Wheeler Date: Fri, 23 Jun 2023 14:49:40 -0500 Subject: [PATCH 612/779] Update message to use the actual parameter name (#19851) --- .../resources/SessionStateStrings.resx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/System.Management.Automation/resources/SessionStateStrings.resx b/src/System.Management.Automation/resources/SessionStateStrings.resx index e597fa665b6..35bcd936435 100644 --- a/src/System.Management.Automation/resources/SessionStateStrings.resx +++ b/src/System.Management.Automation/resources/SessionStateStrings.resx @@ -592,7 +592,7 @@ Drive that maps to the temporary directory path for the current user - Link '{0}' cannot be created because Target was not specified. + Link '{0}' cannot be created because the target Value was not specified. References to the null variable always return the null value. Assignments have no effect. From 26f621952910e33840efb0c539fbef1e2a467a0d Mon Sep 17 00:00:00 2001 From: Ikko Eltociear Ashimine Date: Sat, 24 Jun 2023 04:51:55 +0900 Subject: [PATCH 613/779] Fix typo in `NativeCommandProcessor.cs` (#19846) --- .../engine/NativeCommandProcessor.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/System.Management.Automation/engine/NativeCommandProcessor.cs b/src/System.Management.Automation/engine/NativeCommandProcessor.cs index b511054a051..b769bc026d9 100644 --- a/src/System.Management.Automation/engine/NativeCommandProcessor.cs +++ b/src/System.Management.Automation/engine/NativeCommandProcessor.cs @@ -136,7 +136,7 @@ internal ProcessOutputObject(object data, MinishellStream stream) #nullable enable /// /// This exception is used by the NativeCommandProcessor to indicate an error - /// when a native command retuns a non-zero exit code. + /// when a native command returns a non-zero exit code. /// public sealed class NativeCommandExitException : RuntimeException { From ca85002e42a8aaca13a9b174b017e6d4d361361e Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Tue, 27 Jun 2023 17:01:23 -0700 Subject: [PATCH 614/779] Update `metadata.json` and `README.md` for upcoming releases (#19863) --- README.md | 54 ++++++++++++++++++++++----------------------- tools/metadata.json | 6 ++--- 2 files changed, 30 insertions(+), 30 deletions(-) diff --git a/README.md b/README.md index c66570eade2..4ae4f28b611 100644 --- a/README.md +++ b/README.md @@ -64,33 +64,33 @@ You can also download the PowerShell binary archives for Windows, macOS and Linu | Windows (ARM) | [64-bit][rl-winarm64] (preview) | [64-bit][pv-winarm64] | [Instructions][in-arm] | | Raspbian (ARM) | [32-bit][rl-arm32]/[64-bit][rl-arm64] | [32-bit][pv-arm32]/[64-bit][pv-arm64] | [Instructions][in-raspbian] | -[lts-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.11/PowerShell-7.2.11-win-x86.msi -[lts-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.11/PowerShell-7.2.11-win-x64.msi -[lts-deb]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.11/powershell-lts_7.2.11-1.deb_amd64.deb -[lts-rh]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.11/powershell-lts-7.2.11-1.rh.x86_64.rpm -[lts-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.11/powershell-lts-7.2.11-osx-x64.pkg -[lts-macos-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.11/powershell-lts-7.2.11-osx-arm64.pkg - -[rl-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.4/PowerShell-7.3.4-win-x64.msi -[rl-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.4/PowerShell-7.3.4-win-x86.msi -[rl-deb]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.4/powershell_7.3.4-1.deb_amd64.deb -[rl-ubuntu22]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.4/powershell_7.3.4-1.deb_amd64.deb -[rl-ubuntu20]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.4/powershell_7.3.4-1.deb_amd64.deb -[rl-ubuntu18]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.4/powershell_7.3.4-1.deb_amd64.deb -[rl-debian10]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.4/powershell_7.3.4-1.deb_amd64.deb -[rl-debian11]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.4/powershell_7.3.4-1.deb_amd64.deb -[rl-centos]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.4/powershell-7.3.4-1.rh.x86_64.rpm -[rl-centos8]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.4/powershell-7.3.4-1.rh.x86_64.rpm -[rl-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.4/powershell-7.3.4-osx-x64.pkg -[rl-macos-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.4/powershell-7.3.4-osx-arm64.pkg -[rl-winarm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.4/PowerShell-7.3.4-win-arm64.zip -[rl-winx86-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.4/PowerShell-7.3.4-win-x86.zip -[rl-winx64-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.4/PowerShell-7.3.4-win-x64.zip -[rl-macos-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.4/powershell-7.3.4-osx-x64.tar.gz -[rl-macos-tar-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.4/powershell-7.3.4-osx-arm64.tar.gz -[rl-linux-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.4/powershell-7.3.4-linux-x64.tar.gz -[rl-arm32]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.4/powershell-7.3.4-linux-arm32.tar.gz -[rl-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.4/powershell-7.3.4-linux-arm64.tar.gz +[lts-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.12/PowerShell-7.2.12-win-x86.msi +[lts-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.12/PowerShell-7.2.12-win-x64.msi +[lts-deb]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.12/powershell-lts_7.2.12-1.deb_amd64.deb +[lts-rh]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.12/powershell-lts-7.2.12-1.rh.x86_64.rpm +[lts-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.12/powershell-lts-7.2.12-osx-x64.pkg +[lts-macos-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.12/powershell-lts-7.2.12-osx-arm64.pkg + +[rl-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.5/PowerShell-7.3.5-win-x64.msi +[rl-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.5/PowerShell-7.3.5-win-x86.msi +[rl-deb]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.5/powershell_7.3.5-1.deb_amd64.deb +[rl-ubuntu22]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.5/powershell_7.3.5-1.deb_amd64.deb +[rl-ubuntu20]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.5/powershell_7.3.5-1.deb_amd64.deb +[rl-ubuntu18]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.5/powershell_7.3.5-1.deb_amd64.deb +[rl-debian10]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.5/powershell_7.3.5-1.deb_amd64.deb +[rl-debian11]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.5/powershell_7.3.5-1.deb_amd64.deb +[rl-centos]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.5/powershell-7.3.5-1.rh.x86_64.rpm +[rl-centos8]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.5/powershell-7.3.5-1.rh.x86_64.rpm +[rl-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.5/powershell-7.3.5-osx-x64.pkg +[rl-macos-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.5/powershell-7.3.5-osx-arm64.pkg +[rl-winarm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.5/PowerShell-7.3.5-win-arm64.zip +[rl-winx86-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.5/PowerShell-7.3.5-win-x86.zip +[rl-winx64-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.5/PowerShell-7.3.5-win-x64.zip +[rl-macos-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.5/powershell-7.3.5-osx-x64.tar.gz +[rl-macos-tar-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.5/powershell-7.3.5-osx-arm64.tar.gz +[rl-linux-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.5/powershell-7.3.5-linux-x64.tar.gz +[rl-arm32]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.5/powershell-7.3.5-linux-arm32.tar.gz +[rl-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.5/powershell-7.3.5-linux-arm64.tar.gz [rl-snap]: https://snapcraft.io/powershell [pv-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.3/PowerShell-7.4.0-preview.3-win-x64.msi diff --git a/tools/metadata.json b/tools/metadata.json index 4742b3b0268..c3796305276 100644 --- a/tools/metadata.json +++ b/tools/metadata.json @@ -1,9 +1,9 @@ { - "StableReleaseTag": "v7.3.4", + "StableReleaseTag": "v7.3.5", "PreviewReleaseTag": "v7.4.0-preview.3", "ServicingReleaseTag": "v7.0.13", - "ReleaseTag": "v7.3.4", - "LTSReleaseTag" : ["v7.2.11"], + "ReleaseTag": "v7.3.5", + "LTSReleaseTag" : ["v7.2.12"], "NextReleaseTag": "v7.4.0-preview.4", "LTSRelease": { "Latest": false, "Package": false }, "StableRelease": { "Latest": false, "Package": false } From b059c7e1348eff96ce9c70f974d77996bd8bfe98 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 28 Jun 2023 19:10:01 +0500 Subject: [PATCH 615/779] Bump Microsoft.NET.Test.Sdk from 17.6.2 to 17.6.3 (#19867) Bumps [Microsoft.NET.Test.Sdk](https://github.com/microsoft/vstest) from 17.6.2 to 17.6.3. - [Release notes](https://github.com/microsoft/vstest/releases) - [Changelog](https://github.com/microsoft/vstest/blob/main/docs/releases.md) - [Commits](https://github.com/microsoft/vstest/compare/v17.6.2...v17.6.3) --- updated-dependencies: - dependency-name: Microsoft.NET.Test.Sdk dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- test/xUnit/xUnit.tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/xUnit/xUnit.tests.csproj b/test/xUnit/xUnit.tests.csproj index 5471c3e28a5..1590e4dade3 100644 --- a/test/xUnit/xUnit.tests.csproj +++ b/test/xUnit/xUnit.tests.csproj @@ -27,7 +27,7 @@ - + From b229d15151bbcefb474c7ed9bf0f215ef24db16c Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Thu, 29 Jun 2023 18:57:37 +0000 Subject: [PATCH 616/779] Merged PR 26525: Update change log for v7.4.0-preview.4 Update change log for v7.4.0-preview.4 --- .spelling | 22 ++++++ CHANGELOG/preview.md | 156 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 178 insertions(+) diff --git a/.spelling b/.spelling index 9647f0c0448..792ac487e02 100644 --- a/.spelling +++ b/.spelling @@ -32,6 +32,7 @@ adityapatwardhan ADOPTERS.md aetos382 aiello +Aishat452 al-cheb alepauly alexandair @@ -94,6 +95,8 @@ beta.6 beta.7 beta.8 beta.9 +beta.406 +beta.507 beta2 bgelens Bhaal22 @@ -307,6 +310,7 @@ export-clixml export-csv export-formatdata export-modulemember +fabricbot.json failurecode failurecount farmerau @@ -395,6 +399,7 @@ glachancecmaisonneuve global.json globbing GoogleTest +gregsdennis GUIs gzip hackathons @@ -440,6 +445,7 @@ includeusername informationrecord initializers InitialSessionState.cs +InlineAsTypeCheck install-packageprovider IntelliSense interactivetesting @@ -471,11 +477,13 @@ joeltankam joeyaiello jokajak JohnLBevan +josea joshuacooper journalctl jpsnover json jsonconfigfileaccessor +JsonSchema.Net judgement jumplist jwmoss @@ -531,6 +539,7 @@ macos macports maertendmsft mahawar +mailmap Markdig.Signed markdown.yml manifest.spdx.json @@ -585,6 +594,7 @@ mikeTWC1984 mirichmo mjanko5 mkdir +mkht mklement0 ModuleCmdletBase.cs MohiTheFish @@ -608,6 +618,7 @@ NameObscurerTelemetryInitializer namespace nano nanoserver +NativeCommandProcessor.cs NativeCultureResolver nativeexecution net5.0 @@ -639,6 +650,7 @@ NextTurn ngharo Newtonsoft.Json NJsonSchema +nohwnd NoMoreFood non-22 non-cim @@ -693,6 +705,7 @@ perfview perfview.exe peter-evans petseral +PingPathCommand.cs pinvoke pinvokes plaintext @@ -759,6 +772,7 @@ preview1-24530-04 preview1.22217.1 preview7 ProcessorArchitecture +ProductCode productversion program.cs prototyyppi @@ -780,6 +794,7 @@ psobjects psoptions.json psproxyjobs psreadline +psresourceget psrp.windows psscriptanalyzer pssessionconfiguration @@ -796,6 +811,7 @@ pwsh pwsh.deps.json qmfrederik raghav710 +Random.Shared RandomNoun7 RandomNumberGenerator.Fill raspbian @@ -831,6 +847,7 @@ register-packagesource register-psrepository registryprovider relationlink +releaseTools.psm1 RemoteSessionNamedPipe remotesigned remoting @@ -870,6 +887,7 @@ robo210 ronn rpalo rpolley +runas runspace runspaceinit runspaces @@ -989,6 +1007,7 @@ test1.txt test2.txt testcase testdrive +TestPathCommand.cs tests.zip tgz theflyingcorpse @@ -1046,6 +1065,7 @@ update-typedata uri urizen-source urls +UseMU userdata uservoice utf-8 @@ -1060,6 +1080,7 @@ v0.4.0 v0.5.0 v0.6.0 v141 +v2 v3 v4 v5 @@ -1124,6 +1145,7 @@ win32-openssh win7 win8 windos +windows.json windowspsmodulepath windowsversion winrm diff --git a/CHANGELOG/preview.md b/CHANGELOG/preview.md index 32999c16889..1bd020db9ce 100644 --- a/CHANGELOG/preview.md +++ b/CHANGELOG/preview.md @@ -1,5 +1,161 @@ # Current preview release +## [7.4.0-preview.4] - 2023-06-29 + +### Breaking Changes + +- `Test-Json`: Use `JsonSchema.Net` (`System.Text.Json`) instead of `NJsonSchema` (`Newtonsoft.Json`) (#18141) (Thanks @gregsdennis!) +- `Test-Connection`: Increase output detail when performing a TCP test (#11452) (Thanks @jackdcasey!) + +### Engine Updates and Fixes + +- Fix native executables not redirecting to file (#19842) +- Add a new experimental feature to control native argument passing style on Windows (#18706) +- Fix `TabExpansion2` variable leak when completing variables (#18763) (Thanks @MartinGC94!) +- Enable completion of variables across ScriptBlock scopes (#19819) (Thanks @MartinGC94!) +- Fix completion of the `foreach` statement variable (#19814) (Thanks @MartinGC94!) +- Fix variable type inference precedence (#18691) (Thanks @MartinGC94!) +- Fix member completion for PowerShell Enum class (#19740) (Thanks @MartinGC94!) +- Fix parsing for array literals in index expressions in method calls (#19224) (Thanks @MartinGC94!) +- Fix incorrect string to type conversion (#19560) (Thanks @MartinGC94!) +- Fix slow execution when many breakpoints are used (#14953) (Thanks @nohwnd!) +- Add a public API for getting locations of `PSModulePath` elements (#19422) +- Add WDAC Audit logging (#19641) +- Improve path completion (#19489) (Thanks @MartinGC94!) +- Fix an indexing out of bound error in `CompleteInput` for empty script input (#19501) (Thanks @MartinGC94!) +- Improve variable completion performance (#19595) (Thanks @MartinGC94!) +- Allow partial culture matching in `Update-Help` (#18037) (Thanks @dkaszews!) +- Fix the check when reading input in `NativeCommandProcessor` (#19614) +- Add support of respecting `$PSStyle.OutputRendering` on the remote host (#19601) +- Support byte stream piping between native commands and file redirection (#17857) + +### General Cmdlet Updates and Fixes + +- Disallow negative values for `Get-Content` cmdlet parameters `-Head` and `-Tail` (#19715) (Thanks @CarloToso!) +- Make `Update-Help` throw proper error when current culture is not associated with a language (#19765) (Thanks @josea!) +- Do not require activity when creating a completed progress record (#18474) (Thanks @MartinGC94!) +- WebCmdlets: Add alias for `-TimeoutSec` to `-ConnectionTimeoutSeconds` and add `-OperationTimeoutSeconds` (#19558) (Thanks @stevenebutler!) +- Avoid checking screen scraping on non-Windows platforms before launching native app (#19812) +- Add reference to PSResourceGet (#19597) +- Add `FileNameStar` to `MultipartFileContent` in WebCmdlets (#19467) (Thanks @CarloToso!) +- Add `ParameterSetName` for the `-Detailed` parameter of `Test-Connection` (#19727) +- Remove the property disabling optimization (#19701) +- Filter completion for enum parameter against `ValidateRange` attributes (#17750) (Thanks @fflaten!) +- Small cleanup `Invoke-RestMethod` (#19490) (Thanks @CarloToso!) +- Fix wildcard globbing in root of device paths (#19442) (Thanks @MartinGC94!) +- Add specific error message that creating Junctions requires absolute path (#19409) +- Fix array type parsing in generic types (#19205) (Thanks @MartinGC94!) +- Improve the verbose message of WebCmdlets to show correct HTTP version (#19616) (Thanks @CarloToso!) +- Fix HTTP status from 409 to 429 for WebCmdlets to get retry interval from Retry-After header. (#19622) (Thanks @mkht!) +- Remove minor versions from `PSCompatibleVersions` (#18635) (Thanks @xtqqczze!) +- Update `JsonSchema.Net` version to 4.1.0 (#19610) (Thanks @gregsdennis!) +- Allow combining of `-Skip` and `-SkipLast` parameters in `Select-Object` cmdlet. (#18849) (Thanks @ArmaanMcleod!) +- Fix constructing `PSModulePath` if a sub-path has trailing separator (#13147) +- Add `Get-SecureRandom` cmdlet (#19587) +- Fix `New-Item` to re-create `Junction` when `-Force` is specified (#18311) (Thanks @GigaScratch!) +- Improve Hashtable key completion for type constrained variable assignments, nested Hashtables and more (#17660) (Thanks @MartinGC94!) +- `Set-Clipboard -AsOSC52` for remote usage (#18222) (Thanks @dkaszews!) +- Refactor `MUIFileSearcher.AddFiles` in the help related code (#18825) (Thanks @xtqqczze!) +- Set `SetLastError` to `true` for symbolic and hard link native APIs (#19566) +- Fix `Get-AuthenticodeSignature -Content` to not roundtrip the bytes to a Unicode string and then back to bytes (#18774) (Thanks @jborean93!) +- WebCmdlets: Rename `-TimeoutSec` to `-ConnectionTimeoutSeconds` (with alias) and add `-OperationTimeoutSeconds` (#19558) (Thanks @stevenebutler!) + +### Code Cleanup + +
    + + + +

    We thank the following contributors!

    +

    @eltociear, @ArmaanMcleod, @turbedi, @CarloToso, @Molkree, @xtqqczze

    + +
    + +
      +
    • Fix typo in NativeCommandProcessor.cs (#19846) (Thanks @eltociear!)
    • +
    • Rename file from PingPathCommand.cs to TestPathCommand.cs (#19782) (Thanks @ArmaanMcleod!)
    • +
    • Make use of the new Random.Shared property (#18417) (Thanks @turbedi!)
    • +
    • six files (#19695) (Thanks @CarloToso!)
    • +
    • Apply IDE0019: InlineAsTypeCheck in Microsoft.PowerShell.Commands (#19688)(#19690)(#19687)(#19689) (Thanks @Molkree!)
    • +
    • Remove PSv2CompletionCompleter as part of the PowerShell v2 code cleanup (#18337) (Thanks @xtqqczze!)
    • +
    • Enable more nullable annotations in WebCmdlets (#19359) (Thanks @CarloToso!)
    • +
    + +
    + +### Tools + +- Add Git mailmap for Andy Jordan (#19469) +- Add backport function to release tools (#19568) + +### Tests + +- Improve reliability of the `Ctrl+c` tests for WebCmdlets (#19532) (Thanks @stevenebutler!) +- Fix logic for `Import-CliXml` test (#19805) +- Add some debugging to the transcript test for `SilentlyContinue` (#19770) +- Re-enable `Get-ComputerInfo` pending tests (#19746) +- Update syslog parser to handle modern formats. (#19737) +- Pass `-UserScope` as required by `RunUpdateHelpTests` (#13400) (Thanks @yecril71pl!) +- Change how `isPreview` is determined for default cmdlets tests (#19650) +- Skip file signature tests on 2012R2 where PKI cmdlet do not work (#19643) +- Change logic for testing missing or extra cmdlets. (#19635) +- Fix incorrect test cases in `ExecutionPolicy.Tests.ps1` (#19485) (Thanks @xtqqczze!) +- Fixing structure typo in test setup (#17458) (Thanks @powercode!) +- Fix test failures on Windows for time zone and remoting (#19466) +- Harden 'All approved Cmdlets present' test (#19530) + +### Build and Packaging Improvements + +
    + + +

    Updated to .NET 8 Preview 4 +

    We thank the following contributors!

    +

    @krishnayalavarthi

    + +
    + +
      +
    • Update to the latest NOTICES file (#19537)(#19820)(#19784)(#19720)(#19644)(#19620)(#19605)(#19546)
    • +
    • Bump Microsoft.NET.Test.Sdk from 17.5.0 to 17.6.3 (#19867)(#19762)(#19733)(#19668)(#19613)
    • +
    • Update the cgmanifest (#19847)(#19800)(#19792)(#19776)(#19763)(#19697)(#19631)
    • +
    • Bump StyleCop.Analyzers from 1.2.0-beta.406 to 1.2.0-beta.507 (#19837)
    • +
    • Bump Microsoft.CodeAnalysis.CSharp from 4.6.0-1.final to 4.7.0-2.final (#19838)(#19667)
    • +
    • Update to .NET 8 Preview 4 (#19696)
    • +
    • Update experimental-feature json files (#19828)
    • +
    • Bump JsonSchema.Net from 4.1.1 to 4.1.5 (#19790)(#19768)(#19788)
    • +
    • Update group to assign PRs in fabricbot.json (#19759)
    • +
    • Add retry on failure for all upload tasks in Azure Pipelines (#19761)
    • +
    • Bump Microsoft.PowerShell.MarkdownRender from 7.2.0 to 7.2.1 (#19751)(#19752)
    • +
    • Delete symbols on Linux as well (#19735)
    • +
    • Update windows.json packaging BOM (#19728)
    • +
    • Disable SBOM signing for CI and add extra files for packaging tests (#19729)
    • +
    • Update experimental-feature json files (#19698(#19588))
    • +
    • Add ProductCode in registry for MSI install (#19590)
    • +
    • Runas format changed (#15434) (Thanks @krishnayalavarthi!)
    • +
    • For Preview releases, add pwsh-preview.exe alias to MSIX package (#19602)
    • +
    • Add prompt to fix conflict during backport (#19583)
    • +
    • Add comment in wix detailing use of UseMU (#19371)
    • +
    • Verify that packages have license data (#19543)
    • +
    • Add an explicit manual stage for changelog update (#19551)
    • +
    • Update the team member list in releaseTools.psm1 (#19544)
    • +
    + +
    + +### Documentation and Help Content + +- Update `metadata.json` and `README.md` for upcoming releases (#19863)(#19542) +- Update message to use the actual parameter name (#19851) +- Update `CONTRIBUTING.md` to include Code of Conduct enforcement (#19810) +- Update `working-group-definitions.md` (#19809)(#19561) +- Update `working-group.md` to add section about reporting working group members (#19758) +- Correct capitalization in readme (#19666) (Thanks @Aishat452!) +- Updated the public dashboard link (#19634) +- Fix a typo in `serialization.cs` (#19598) (Thanks @eltociear!) + +[7.4.0-preview.4]: https://github.com/PowerShell/PowerShell/compare/v7.4.0-preview.3...v7.4.0-preview.4 + ## [7.4.0-preview.3] - 2023-04-20 ### Breaking Changes From abe3ec5f95b2c2fc556b29992f3c46826b5a7a82 Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Thu, 29 Jun 2023 15:07:59 -0700 Subject: [PATCH 617/779] Update `README.md` and `metadata.json` for `7.4.0-preview.4` release (#19872) --- README.md | 28 ++++++++++++++-------------- tools/metadata.json | 4 ++-- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index 4ae4f28b611..76277ae9858 100644 --- a/README.md +++ b/README.md @@ -93,20 +93,20 @@ You can also download the PowerShell binary archives for Windows, macOS and Linu [rl-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.5/powershell-7.3.5-linux-arm64.tar.gz [rl-snap]: https://snapcraft.io/powershell -[pv-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.3/PowerShell-7.4.0-preview.3-win-x64.msi -[pv-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.3/PowerShell-7.4.0-preview.3-win-x86.msi -[pv-deb]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.3/powershell-preview_7.4.0-preview.3-1.deb_amd64.deb -[pv-rpm]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.3/powershell-preview-7.4.0_preview.3-1.rh.x86_64.rpm -[pv-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.3/powershell-7.4.0-preview.3-osx-x64.pkg -[pv-macos-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.3/powershell-7.4.0-preview.3-osx-arm64.pkg -[pv-winarm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.3/PowerShell-7.4.0-preview.3-win-arm64.zip -[pv-winx86-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.3/PowerShell-7.4.0-preview.3-win-x86.zip -[pv-winx64-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.3/PowerShell-7.4.0-preview.3-win-x64.zip -[pv-macos-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.3/powershell-7.4.0-preview.3-osx-x64.tar.gz -[pv-macos-tar-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.3/powershell-7.4.0-preview.3-osx-arm64.tar.gz -[pv-linux-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.3/powershell-7.4.0-preview.3-linux-x64.tar.gz -[pv-arm32]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.3/powershell-7.4.0-preview.3-linux-arm32.tar.gz -[pv-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.3/powershell-7.4.0-preview.3-linux-arm64.tar.gz +[pv-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.4/PowerShell-7.4.0-preview.4-win-x64.msi +[pv-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.4/PowerShell-7.4.0-preview.4-win-x86.msi +[pv-deb]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.4/powershell-preview_7.4.0-preview.4-1.deb_amd64.deb +[pv-rpm]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.4/powershell-preview-7.4.0_preview.4-1.rh.x86_64.rpm +[pv-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.4/powershell-7.4.0-preview.4-osx-x64.pkg +[pv-macos-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.4/powershell-7.4.0-preview.4-osx-arm64.pkg +[pv-winarm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.4/PowerShell-7.4.0-preview.4-win-arm64.zip +[pv-winx86-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.4/PowerShell-7.4.0-preview.4-win-x86.zip +[pv-winx64-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.4/PowerShell-7.4.0-preview.4-win-x64.zip +[pv-macos-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.4/powershell-7.4.0-preview.4-osx-x64.tar.gz +[pv-macos-tar-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.4/powershell-7.4.0-preview.4-osx-arm64.tar.gz +[pv-linux-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.4/powershell-7.4.0-preview.4-linux-x64.tar.gz +[pv-arm32]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.4/powershell-7.4.0-preview.4-linux-arm32.tar.gz +[pv-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.4/powershell-7.4.0-preview.4-linux-arm64.tar.gz [pv-snap]: https://snapcraft.io/powershell-preview [in-windows]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-windows diff --git a/tools/metadata.json b/tools/metadata.json index c3796305276..c5c94011eea 100644 --- a/tools/metadata.json +++ b/tools/metadata.json @@ -1,10 +1,10 @@ { "StableReleaseTag": "v7.3.5", - "PreviewReleaseTag": "v7.4.0-preview.3", + "PreviewReleaseTag": "v7.4.0-preview.4", "ServicingReleaseTag": "v7.0.13", "ReleaseTag": "v7.3.5", "LTSReleaseTag" : ["v7.2.12"], - "NextReleaseTag": "v7.4.0-preview.4", + "NextReleaseTag": "v7.4.0-preview.5", "LTSRelease": { "Latest": false, "Package": false }, "StableRelease": { "Latest": false, "Package": false } } From ee13bb9f05882adfbeb4ac29113d3fbec49f6c60 Mon Sep 17 00:00:00 2001 From: "James Truher [MSFT]" Date: Wed, 5 Jul 2023 07:40:30 -0700 Subject: [PATCH 618/779] Add more debugging to try to determine why these test fail in release build. (#19829) --- .../PackageManagement.Tests.ps1 | 26 +++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/test/powershell/Modules/PackageManagement/PackageManagement.Tests.ps1 b/test/powershell/Modules/PackageManagement/PackageManagement.Tests.ps1 index 01b4d4738a6..e6fdb981f15 100644 --- a/test/powershell/Modules/PackageManagement/PackageManagement.Tests.ps1 +++ b/test/powershell/Modules/PackageManagement/PackageManagement.Tests.ps1 @@ -22,12 +22,34 @@ Describe "PackageManagement Acceptance Test" -Tags "Feature" { # register the asset directory $localSourceName = [Guid]::NewGuid().ToString("n") $localSourceLocation = Join-Path $PSScriptRoot assets - $newSourceResult = Register-PackageSource -Name $localSourceName -provider NuGet -Location $localSourceLocation -Force -Trusted + $newSourceResult = Register-PackageSource -Name $localSourceName -provider NuGet -Location $localSourceLocation -Force -Trusted -Verbose Write-Verbose -Verbose -Message "Register-PackageSource -Name $localSourceName -provider NuGet -Location $localSourceLocation -Force -Trusted" $newSourceResult | Out-String -Stream | Write-Verbose -Verbose + $localSourceCheck = Get-PackageSource -Name $localSourceName -ErrorAction Ignore $skipPackageTests = $false - if ($newSourceResult.Location -ne $localSourceLocation) { + # It is possible that Register-PackageSource appears to succeed but the source is not actually registered + # collect as much information as possible to help diagnose the problem + if (($newSourceResult.Location -ne $localSourceLocation) -or ($localSourceCheck.Location -ne $localSourceLocation)) { + Write-Verbose -Verbose "Skipping tests because local source could not be correctly created" + if ( $newSourceResult ) { + $newSourceResult | out-string -str | Write-Verbose -Verbose + } + else { + Write-Verbose "newSourceResult is null" + } + + if ( $localSourceCheck ) { + $localSourceCheck | out-string -str | Write-Verbose -Verbose + } + else { + Write-Verbose "LocalSourceCheck is null" + } + + if (-not $IsWindows) { + Get-ChildItem "$HOME/.config" -Recurse -File | out-string -str | Write-Verbose -Verbose + } + $skipPackageTests = $true } From fc87be75c0de63817962ee8c051139f55f2d23da Mon Sep 17 00:00:00 2001 From: PowerShell Team Bot <69177312+pwshBot@users.noreply.github.com> Date: Wed, 5 Jul 2023 12:50:37 -0700 Subject: [PATCH 619/779] Update to the latest NOTICES file (#19856) --- ThirdPartyNotices.txt | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/ThirdPartyNotices.txt b/ThirdPartyNotices.txt index c68f35d92fe..ec109ac4126 100644 --- a/ThirdPartyNotices.txt +++ b/ThirdPartyNotices.txt @@ -696,7 +696,7 @@ SOFTWARE. --------------------------------------------------------- -Microsoft.Windows.Compatibility 7.0.3 - MIT +Microsoft.Windows.Compatibility 7.0.4 - MIT (c) Microsoft Corporation @@ -3461,7 +3461,7 @@ SOFTWARE. --------------------------------------------------------- -System.Security.Cryptography.Pkcs 7.0.2 - MIT +System.Security.Cryptography.Pkcs 7.0.3 - MIT (c) Microsoft Corporation @@ -4594,12 +4594,9 @@ SOFTWARE. --------------------------------------------------------- -System.Web.Services.Description 4.9.0 - MIT +System.Web.Services.Description 4.10.0 - MIT -(c) Microsoft Corporation. -Copyright (c) .NET Foundation and Contributors -Copyright (c) 2000-2014 The Legion of the Bouncy Castle Inc. (http://www.bouncycastle.org) The MIT License (MIT) From 64d1d5caaed90055c98cabea5e0764abe0e5bc1f Mon Sep 17 00:00:00 2001 From: Anam Navied Date: Thu, 6 Jul 2023 13:52:04 -0400 Subject: [PATCH 620/779] Add runtime and packaging type info for mariner2 arm64 (#19450) --- build.psm1 | 12 ++++++-- tools/ci.psm1 | 2 +- tools/packaging/packaging.psm1 | 50 ++++++++++++++++++++++++++++++---- 3 files changed, 55 insertions(+), 9 deletions(-) diff --git a/build.psm1 b/build.psm1 index 3d0be1a846b..016e3254e00 100644 --- a/build.psm1 +++ b/build.psm1 @@ -310,6 +310,7 @@ function Start-PSBuild { [ValidateSet("alpine-x64", "fxdependent", "fxdependent-linux-x64", + "fxdependent-linux-arm64", "fxdependent-win-desktop", "linux-arm", "linux-arm64", @@ -428,6 +429,7 @@ Fix steps: PSModuleRestore=$PSModuleRestore ForMinimalSize=$ForMinimalSize } + $script:Options = New-PSOptions @OptionsArguments if ($StopDevPowerShell) { @@ -886,6 +888,7 @@ function New-PSOptions { "alpine-x64", "fxdependent", "fxdependent-linux-x64", + "fxdependent-linux-arm64", "fxdependent-win-desktop", "linux-arm", "linux-arm64", @@ -970,9 +973,14 @@ function New-PSOptions { # Build the Output path if (!$Output) { - if ($Runtime -like 'fxdependent*') { + if ($Runtime -like 'fxdependent*' -and $Runtime -like 'fxdependent*linux*') { + $outputRuntime = $Runtime -replace 'fxdependent-', '' + $Output = [IO.Path]::Combine($Top, "bin", $Configuration, $Framework, $outputRuntime, "publish", $Executable) + } + elseif ($Runtime -like 'fxdependent*') { $Output = [IO.Path]::Combine($Top, "bin", $Configuration, $Framework, "publish", $Executable) - } else { + } + else { $Output = [IO.Path]::Combine($Top, "bin", $Configuration, $Framework, $Runtime, "publish", $Executable) } } else { diff --git a/tools/ci.psm1 b/tools/ci.psm1 index 731ab4eaebf..060519d30a6 100644 --- a/tools/ci.psm1 +++ b/tools/ci.psm1 @@ -784,7 +784,7 @@ function New-LinuxPackage # Only build packages for PowerShell/PowerShell repository # branches, not pull requests - $packages = @(Start-PSPackage @packageParams -SkipReleaseChecks -Type deb, rpm, tar) + $packages = @(Start-PSPackage @packageParams -SkipReleaseChecks -Type deb, rpm, rpm-fxdependent-arm64, tar) foreach($package in $packages) { if (Test-Path $package) diff --git a/tools/packaging/packaging.psm1 b/tools/packaging/packaging.psm1 index e3ef1e0ed49..cdb42ecccb2 100644 --- a/tools/packaging/packaging.psm1 +++ b/tools/packaging/packaging.psm1 @@ -50,7 +50,7 @@ function Start-PSPackage { [string]$Name = "powershell", # Ubuntu, CentOS, Fedora, macOS, and Windows packages are supported - [ValidateSet("msix", "deb", "osxpkg", "rpm", "rpm-fxdependent", "msi", "zip", "zip-pdb", "nupkg", "tar", "tar-arm", "tar-arm64", "tar-alpine", "fxdependent", "fxdependent-win-desktop", "min-size")] + [ValidateSet("msix", "deb", "osxpkg", "rpm", "rpm-fxdependent", "rpm-fxdependent-arm64", "msi", "zip", "zip-pdb", "nupkg", "tar", "tar-arm", "tar-arm64", "tar-alpine", "fxdependent", "fxdependent-win-desktop", "min-size")] [string[]]$Type, # Generate windows downlevel package @@ -111,7 +111,10 @@ function Start-PSPackage { } } elseif ($Type.Count -eq 1 -and $Type[0] -eq "rpm-fxdependent") { New-PSOptions -Configuration "Release" -Runtime 'fxdependent-linux-x64' -WarningAction SilentlyContinue | ForEach-Object { $_.Runtime, $_.Configuration } - } else { + } elseif ($Type.Count -eq 1 -and $Type[0] -eq "rpm-fxdependent-arm64") { + New-PSOptions -Configuration "Release" -Runtime 'fxdependent-linux-arm64' -WarningAction SilentlyContinue | ForEach-Object { $_.Runtime, $_.Configuration } + } + else { New-PSOptions -Configuration "Release" -WarningAction SilentlyContinue | ForEach-Object { $_.Runtime, $_.Configuration } } @@ -592,6 +595,7 @@ function Start-PSPackage { Force = $Force NoSudo = $NoSudo LTS = $LTS + HostArchitecture = "amd64" } foreach ($Distro in $Script:DebianDistributions) { $Arguments["Distribution"] = $Distro @@ -609,6 +613,7 @@ function Start-PSPackage { Force = $Force NoSudo = $NoSudo LTS = $LTS + HostArchitecture = "x86_64" } foreach ($Distro in $Script:RedhatFullDistributions) { $Arguments["Distribution"] = $Distro @@ -627,6 +632,7 @@ function Start-PSPackage { Force = $Force NoSudo = $NoSudo LTS = $LTS + HostArchitecture = "x86_64" } foreach ($Distro in $Script:RedhatFddDistributions) { $Arguments["Distribution"] = $Distro @@ -636,6 +642,26 @@ function Start-PSPackage { } } } + 'rpm-fxdependent-arm64' { + $Arguments = @{ + Type = 'rpm' + PackageSourcePath = $Source + Name = $Name + Version = $Version + Force = $Force + NoSudo = $NoSudo + LTS = $LTS + HostArchitecture = "aarch64" + } + foreach ($Distro in $Script:RedhatFddDistributions) { + $Arguments["Distribution"] = $Distro + $Arguments["HostArchitecture"] = $HostArchitecture + if ($PSCmdlet.ShouldProcess("Create RPM Package for $Distro")) { + Write-Verbose -Verbose "Creating RPM Package for $Distro" + New-UnixPackage @Arguments + } + } + } 'osxpkg' { $HostArchitecture = "x86_64" if ($MacOSRuntime -match "-arm64") { @@ -668,6 +694,7 @@ function Start-PSPackage { Force = $Force NoSudo = $NoSudo LTS = $LTS + HostArchitecture = "all" } if ($PSCmdlet.ShouldProcess("Create $_ Package")) { @@ -926,6 +953,10 @@ function New-UnixPackage { # This is a string because strings are appended to it [string]$Iteration = "1", + [string] + [ValidateSet("x86_64", "amd64", "aarch64", "native", "all", "noarch", "any")] + $HostArchitecture, + [Switch] $Force, @@ -955,9 +986,9 @@ function New-UnixPackage { $Attributes = New-Object "System.Collections.ObjectModel.Collection``1[System.Attribute]" $Attributes.Add($ParameterAttr) > $null $Attributes.Add($ValidateSetAttr) > $null - - $Parameter = New-Object "System.Management.Automation.RuntimeDefinedParameter" -ArgumentList ("Distribution", [string], $Attributes) $Dict = New-Object "System.Management.Automation.RuntimeDefinedParameterDictionary" + $Parameter = New-Object "System.Management.Automation.RuntimeDefinedParameter" -ArgumentList ("Distribution", [string], $Attributes) + $Dict.Add("Distribution", $Parameter) > $null return $Dict } elseif ($Type -eq "osxpkg") { @@ -1072,6 +1103,7 @@ function New-UnixPackage { # Destination for symlink to powershell executable $Link = Get-PwshExecutablePath -IsPreview:$IsPreview + $links = @(New-LinkInfo -LinkDestination $Link -LinkTarget "$Destination/pwsh") if($LTS) { @@ -1131,7 +1163,10 @@ function New-UnixPackage { # Setup package dependencies $Dependencies = @(Get-PackageDependencies @packageDependenciesParams) - $Arguments = Get-FpmArguments ` + $Arguments = @() + + + $Arguments += Get-FpmArguments ` -Name $Name ` -Version $packageVersion ` -Iteration $Iteration ` @@ -1147,6 +1182,7 @@ function New-UnixPackage { -LinkInfo $Links ` -AppsFolder $AppsFolder ` -Distribution $DebDistro ` + -HostArchitecture $HostArchitecture ` -ErrorAction Stop # Build package @@ -1398,7 +1434,8 @@ function Get-FpmArguments return $true })] [String]$AppsFolder, - [String]$Distribution = 'rhel.7' + [String]$Distribution = 'rhel.7', + [string]$HostArchitecture ) $Arguments = @( @@ -1410,6 +1447,7 @@ function Get-FpmArguments "--vendor", "Microsoft Corporation", "--url", "https://microsoft.com/powershell", "--description", $Description, + "--architecture", $HostArchitecture, "--category", "shells", "-t", $Type, "-s", "dir" From 73630960efa0a84475731bfbee4b46c046be72ad Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 7 Jul 2023 15:50:02 +0500 Subject: [PATCH 621/779] Bump xunit.runner.visualstudio from 2.4.5 to 2.5.0 (#19901) Bumps [xunit.runner.visualstudio](https://github.com/xunit/visualstudio.xunit) from 2.4.5 to 2.5.0. - [Release notes](https://github.com/xunit/visualstudio.xunit/releases) - [Commits](https://github.com/xunit/visualstudio.xunit/compare/v2.4.5...2.5.0) --- updated-dependencies: - dependency-name: xunit.runner.visualstudio dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- test/xUnit/xUnit.tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/xUnit/xUnit.tests.csproj b/test/xUnit/xUnit.tests.csproj index 1590e4dade3..9257f579c54 100644 --- a/test/xUnit/xUnit.tests.csproj +++ b/test/xUnit/xUnit.tests.csproj @@ -25,7 +25,7 @@ - + From aa31732aa94c52605d28822215f889ca3174d850 Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Fri, 7 Jul 2023 10:15:35 -0700 Subject: [PATCH 622/779] Switch to GitHub Action for linting markdown (#19899) --- .github/workflows/markdownLink.yml | 18 +- .../markdown-link/markdown-link.tests.ps1 | 156 -- test/common/markdown-lint/.gitignore | 1 - test/common/markdown-lint/gulpfile.js | 60 - test/common/markdown-lint/markdown.tests.ps1 | 100 - test/common/markdown-lint/package.json | 35 - test/common/markdown-lint/yarn.lock | 2390 ----------------- 7 files changed, 17 insertions(+), 2743 deletions(-) delete mode 100644 test/common/markdown-link/markdown-link.tests.ps1 delete mode 100644 test/common/markdown-lint/.gitignore delete mode 100644 test/common/markdown-lint/gulpfile.js delete mode 100644 test/common/markdown-lint/markdown.tests.ps1 delete mode 100644 test/common/markdown-lint/package.json delete mode 100644 test/common/markdown-lint/yarn.lock diff --git a/.github/workflows/markdownLink.yml b/.github/workflows/markdownLink.yml index 2c0796ac2d1..7fe0e955507 100644 --- a/.github/workflows/markdownLink.yml +++ b/.github/workflows/markdownLink.yml @@ -4,7 +4,7 @@ on: - master - 'release/**' -name: Check links for modified files +name: Check modified markdown files permissions: contents: read @@ -19,3 +19,19 @@ jobs: use-verbose-mode: 'yes' check-modified-files-only: 'yes' config-file: .github/workflows/markdown-link/config.json + markdown-lint: + permissions: + contents: read + packages: read + statuses: write + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - name: Lint Markdown + uses: super-linter/super-linter@v5 + env: + VALIDATE_ALL_CODEBASE: false + DEFAULT_BRANCH: master + FILTER_REGEX_INCLUDE: .*\.md + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + diff --git a/test/common/markdown-link/markdown-link.tests.ps1 b/test/common/markdown-link/markdown-link.tests.ps1 deleted file mode 100644 index 96c101afd4a..00000000000 --- a/test/common/markdown-link/markdown-link.tests.ps1 +++ /dev/null @@ -1,156 +0,0 @@ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. - -Describe "Verify Markdown Links" { - BeforeAll { - if(!(Get-Command -Name 'markdown-link-check' -ErrorAction SilentlyContinue)) - { - Write-Verbose "installing markdown-link-check ..." -Verbose - start-nativeExecution { - sudo yarn global add markdown-link-check@3.8.5 - } - } - - if(!(Get-Module -Name 'ThreadJob' -ListAvailable -ErrorAction SilentlyContinue)) - { - Install-Module -Name ThreadJob -Scope CurrentUser - } - - # Cleanup jobs for reliability - Get-Job | Remove-Job -Force - } - - AfterAll { - # Cleanup jobs to leave the process the same - Get-Job | Remove-Job -Force - } - - $gciParams = @{} - if ($env:MARKDOWN_FOLDER) { - $gciParams["Path"] = (Join-Path -Path $env:MARKDOWN_FOLDER -ChildPath '*.md') - } else { - $gciParams["Path"] = "$PSScriptRoot\..\..\..\*.md" - } - - if ($env:MARKDOWN_RECURSE -ne 'False') { - $gciParams["Recurse"] = $true - } - - $groups = Get-ChildItem @gciParams | Where-Object {$_.DirectoryName -notlike '*node_modules*'} | Group-Object -Property directory - - $jobs = @{} - # start all link verification in parallel - Foreach($group in $groups) - { - Write-Verbose -Verbose "starting jobs for $($group.Name) ..." - $job = Start-ThreadJob { - param([object] $group) - foreach($file in $group.Group) - { - $results = markdown-link-check -r $file 2>&1 - Write-Output ([PSCustomObject]@{ - file = $file - results = $results - }) - } - } -ArgumentList @($group) - $jobs.add($group.name,$job) - } - - Write-Verbose -Verbose "Getting results ..." - # Get the results and verify - foreach($key in $jobs.keys) - { - $job = $jobs.$key - $results = Receive-Job -Job $job -Wait - Remove-Job -Job $Job - foreach($jobResult in $results) - { - $file = $jobResult.file - $result = $jobResult.results - Context "Verify links in $file" { - # failures look like `[✖] https://someurl` (perhaps without the https://) - # passes look like `[✓] https://someurl` (perhaps without the https://) - $failures = $result -like '*[✖]*' | ForEach-Object { $_.Substring(4).Trim() } - $passes = $result -like '*[✓]*' | ForEach-Object { - @{url=$_.Substring(4).Trim() } - } - $trueFailures = @() - $verifyFailures = @() - foreach ($failure in $failures) { - if($failure -like 'https://www.amazon.com*') - { - # In testing amazon links often failed when they are valid - # Verify manually - $verifyFailures += @{url = $failure} - } - else - { - $trueFailures += @{url = $failure} - } - } - - # must have some code in the test for it to pass - function noop { - } - - if($passes) - { - It " should work" -TestCases $passes { - noop - } - } - - if($trueFailures) - { - It " should work" -TestCases $trueFailures { - param($url) - - # there could be multiple reasons why a failure is ok - # check against the allowed failures - $allowedFailures = [System.Net.HttpStatusCode[]]( - 503, # Service Unavailable - 504, # Gateway Timeout - 403 # Forbidden, some sites block with from AzDO with this code - ) - - $prefix = $url.Substring(0,7) - - # Logging for diagnosability. Azure DevOps sometimes redacts the full url. - Write-Verbose "prefix: '$prefix'" - if($url -match '^http(s)?:') - { - # If invoke-WebRequest can handle the URL, re-verify, with 6 retries - try - { - $null = Invoke-WebRequest -Uri $url -RetryIntervalSec 10 -MaximumRetryCount 6 - } - catch [Microsoft.PowerShell.Commands.HttpResponseException] - { - if ( $allowedFailures -notcontains $_.Exception.Response.StatusCode ) { - throw "Failed to complete request to `"$url`". $($_.Exception.Response.StatusCode) $($_.Exception.Message)" - } - } - } - else { - throw "Tool reported URL as unreachable." - } - } - } - - if($verifyFailures) - { - It " should work" -TestCases $verifyFailures -Pending { - } - } - - if(!$passes -and !$trueFailures -and !$verifyFailures) - { - It "has no links" { - noop - } - } - } - } - } -} diff --git a/test/common/markdown-lint/.gitignore b/test/common/markdown-lint/.gitignore deleted file mode 100644 index c2658d7d1b3..00000000000 --- a/test/common/markdown-lint/.gitignore +++ /dev/null @@ -1 +0,0 @@ -node_modules/ diff --git a/test/common/markdown-lint/gulpfile.js b/test/common/markdown-lint/gulpfile.js deleted file mode 100644 index 90014969b7d..00000000000 --- a/test/common/markdown-lint/gulpfile.js +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -function runTest() { - "use strict"; - var gulp = require("gulp"); - var concat = require("gulp-concat"); - var through2 = require("through2"); - var markdownlint = require("markdownlint"); - - gulp.task("test-mdsyntax", function task() { - var paths = []; - var rootpath; - - // assign --repoRoot into rootpath - var j = process.argv.indexOf("--rootpath"); - if (j > -1) { - rootpath = process.argv[j + 1]; - } - - if (rootpath === null) { - throw "--rootpath must be specified before all other parameters"; - } - - // parse --filter into paths. --rootpath must be specified first. - j = process.argv.indexOf("--filter"); - if (j > -1) { - var filters = process.argv[j + 1].split(","); - filters.forEach(function(filter) { - paths.push(rootpath + "/" + filter); - }, this); - } - - if (paths.length === 0) { - throw "--filter must be specified"; - } - - var rootJsonFile = rootpath + "/.markdownlint.json"; - var fs = require("fs"); - fs.appendFileSync("markdownissues.txt", "--EMPTY--\r\n"); - return gulp.src(paths, { "read": false }) - .pipe(through2.obj(function obj(file, enc, next) { - markdownlint({ - "files": [file.path], - "config": require(rootJsonFile) - }, - function callback(err, result) { - var resultString = (result || "").toString(); - if (resultString) { - file.contents = Buffer.from(resultString); - } - next(err, file); - }); - })) - .pipe(concat("markdownissues.txt", { newLine: "\r\n" })) - .pipe(gulp.dest(".")); - }); -} - -runTest(); diff --git a/test/common/markdown-lint/markdown.tests.ps1 b/test/common/markdown-lint/markdown.tests.ps1 deleted file mode 100644 index ee152b5c703..00000000000 --- a/test/common/markdown-lint/markdown.tests.ps1 +++ /dev/null @@ -1,100 +0,0 @@ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. - -Import-Module HelpersCommon -$moduleRootFilePath = Split-Path -Path $PSScriptRoot -Parent - -# Identify the repository root path of the resource module -$repoRootPath = (Resolve-Path -LiteralPath (Join-Path $moduleRootFilePath "../..")).ProviderPath -$repoRootPathFound = $false - -Describe 'Common Tests - Validate Markdown Files' -Tag 'CI' { - BeforeAll { - Push-Location $psscriptroot - $skip = $false - $NpmInstalled = "not installed" - if (Get-Command -Name 'yarn' -ErrorAction SilentlyContinue) - { - $NpmInstalled = "Installed" - Write-Verbose -Message "Checking if Gulp is installed. This may take a few moments." -Verbose - start-nativeExecution { yarn } - if(!(Get-Command -Name 'gulp' -ErrorAction SilentlyContinue)) - { - start-nativeExecution { - sudo yarn global add 'gulp@4.0.2' - } - } - if(!(Get-Command -Name 'node' -ErrorAction SilentlyContinue)) - { - throw "node not found" - } - } - if(!(Get-Command -Name 'node' -ErrorAction SilentlyContinue)) - { - <# - On Windows, pre-requisites are missing - For now we will skip, and write a warning. Work to resolve this is tracked in: - https://github.com/PowerShell/PowerShell/issues/3429 - #> - Write-Warning "Node and yarn are required to run this test" - $skip = $true - } - - $mdIssuesPath = Join-Path -Path $PSScriptRoot -ChildPath "markdownissues.txt" - Remove-Item -Path $mdIssuesPath -Force -ErrorAction SilentlyContinue - } - - AfterAll { - Pop-Location - } - - It "Should not have errors in any markdown files" -Skip:$skip { - $NpmInstalled | Should -BeExactly "Installed" - $mdErrors = 0 - Push-Location -Path $PSScriptRoot - try - { - $docsToTest = @( - './.github/*.md' - './README.md' - './demos/python/*.md' - './docker/*.md' - './docs/building/*.md' - './docs/community/*.md' - './docs/host-powershell/*.md' - './docs/cmdlet-example/*.md' - './docs/maintainers/*.md' - './test/powershell/README.md' - './tools/*.md' - './.github/ISSUE_TEMPLATE/*.md' - ) - $filter = ($docsToTest -join ',') - - # Gulp 4 beta is returning non-zero exit code even when there is not an error - Start-NativeExecution { - &"gulp" test-mdsyntax --silent ` - --rootpath $repoRootPath ` - --filter $filter - } -VerboseOutputOnError -IgnoreExitcode - - } - finally - { - Pop-Location - } - - $mdIssuesPath | Should -Exist - - [string[]] $markdownErrors = Get-Content -Path $mdIssuesPath - Remove-Item -Path $mdIssuesPath -Force -ErrorAction SilentlyContinue - - if ($markdownErrors -ne "--EMPTY--") - { - $markdownErrors += ' (See https://github.com/DavidAnson/markdownlint/blob/master/doc/Rules.md for an explanation of the error codes)' - } - - $markdownErrors | Write-Host - - $markdownErrors -join "`n" | Should -BeExactly "--EMPTY--" - } -} diff --git a/test/common/markdown-lint/package.json b/test/common/markdown-lint/package.json deleted file mode 100644 index f04a98e44fa..00000000000 --- a/test/common/markdown-lint/package.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "powershell.common.markdown.tests", - "private": true, - "version": "1.0.0", - "description": "The PowerShell Common Markdown Tests.", - "main": "gulpfile.js", - "dependencies": { - "gulp": "^4.0.2", - "markdownlint": "^0.25.1", - "through2": "^4.0.2" - }, - "resolutions": { - "yargs-parser": "^13.1.2" , - "y18n": "^5.0.5", - "ini": "^1.3.6", - "copy-props":"^2.0.5", - "glob-parent":"^5.1.2", - "hosted-git-info":"^3.0.8", - "set-value":"^4.0.1" - }, - "devDependencies": { - "gulp-concat": "^2.6.1", - "gulp-debug": "^4.0.0" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/PowerShell/PowerShell.git" - }, - "author": "Microsoft Corporation", - "license": "MIT", - "bugs": { - "url": "https://github.com/PowerShell/PowerShell/issues" - }, - "homepage": "https://github.com/PowerShell/PowerShell#readme" -} diff --git a/test/common/markdown-lint/yarn.lock b/test/common/markdown-lint/yarn.lock deleted file mode 100644 index 1bf37b9eadf..00000000000 --- a/test/common/markdown-lint/yarn.lock +++ /dev/null @@ -1,2390 +0,0 @@ -# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. -# yarn lockfile v1 - - -ansi-colors@^1.0.1: - version "1.1.0" - resolved "https://registry.yarnpkg.com/ansi-colors/-/ansi-colors-1.1.0.tgz" - integrity sha512-SFKX67auSNoVR38N3L+nvsPjOE0bybKTYbkf5tRvushrAPQ9V75huw0ZxBkKVeRU9kqH3d6HA4xTckbwZ4ixmA== - dependencies: - ansi-wrap "^0.1.0" - -ansi-gray@^0.1.1: - version "0.1.1" - resolved "https://registry.yarnpkg.com/ansi-gray/-/ansi-gray-0.1.1.tgz" - integrity sha1-KWLPVOyXksSFEKPetSRDaGHvclE= - dependencies: - ansi-wrap "0.1.0" - -ansi-regex@^2.0.0: - version "2.1.1" - resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-2.1.1.tgz" - integrity sha1-w7M6te42DYbg5ijwRorn7yfWVN8= - -ansi-styles@^3.2.1: - version "3.2.1" - resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-3.2.1.tgz" - integrity sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA== - dependencies: - color-convert "^1.9.0" - -ansi-wrap@0.1.0, ansi-wrap@^0.1.0: - version "0.1.0" - resolved "https://registry.yarnpkg.com/ansi-wrap/-/ansi-wrap-0.1.0.tgz" - integrity sha1-qCJQ3bABXponyoLoLqYDu/pF768= - -anymatch@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/anymatch/-/anymatch-2.0.0.tgz" - integrity sha512-5teOsQWABXHHBFP9y3skS5P3d/WfWXpv3FUpy+LorMrNYaT9pI4oLMQX7jzQ2KklNpGpWHzdCXTDT2Y3XGlZBw== - dependencies: - micromatch "^3.1.4" - normalize-path "^2.1.1" - -append-buffer@^1.0.2: - version "1.0.2" - resolved "https://registry.yarnpkg.com/append-buffer/-/append-buffer-1.0.2.tgz" - integrity sha1-2CIM9GYIFSXv6lBhTz3mUU36WPE= - dependencies: - buffer-equal "^1.0.0" - -archy@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/archy/-/archy-1.0.0.tgz" - integrity sha1-+cjBN1fMHde8N5rHeyxipcKGjEA= - -argparse@^2.0.1: - version "2.0.1" - resolved "https://registry.yarnpkg.com/argparse/-/argparse-2.0.1.tgz#246f50f3ca78a3240f6c997e8a9bd1eac49e4b38" - integrity sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q== - -arr-diff@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/arr-diff/-/arr-diff-4.0.0.tgz" - integrity sha1-1kYQdP6/7HHn4VI1dhoyml3HxSA= - -arr-filter@^1.1.1: - version "1.1.2" - resolved "https://registry.yarnpkg.com/arr-filter/-/arr-filter-1.1.2.tgz" - integrity sha1-Q/3d0JHo7xGqTEXZzcGOLf8XEe4= - dependencies: - make-iterator "^1.0.0" - -arr-flatten@^1.0.1, arr-flatten@^1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/arr-flatten/-/arr-flatten-1.1.0.tgz" - integrity sha512-L3hKV5R/p5o81R7O02IGnwpDmkp6E982XhtbuwSe3O4qOtMMMtodicASA1Cny2U+aCXcNpml+m4dPsvsJ3jatg== - -arr-map@^2.0.0, arr-map@^2.0.2: - version "2.0.2" - resolved "https://registry.yarnpkg.com/arr-map/-/arr-map-2.0.2.tgz" - integrity sha1-Onc0X/wc814qkYJWAfnljy4kysQ= - dependencies: - make-iterator "^1.0.0" - -arr-union@^3.1.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/arr-union/-/arr-union-3.1.0.tgz" - integrity sha1-45sJrqne+Gao8gbiiK9jkZuuOcQ= - -array-each@^1.0.0, array-each@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/array-each/-/array-each-1.0.1.tgz" - integrity sha1-p5SvDAWrF1KEbudTofIRoFugxE8= - -array-initial@^1.0.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/array-initial/-/array-initial-1.1.0.tgz" - integrity sha1-L6dLJnOTccOUe9enrcc74zSz15U= - dependencies: - array-slice "^1.0.0" - is-number "^4.0.0" - -array-last@^1.1.1: - version "1.3.0" - resolved "https://registry.yarnpkg.com/array-last/-/array-last-1.3.0.tgz" - integrity sha512-eOCut5rXlI6aCOS7Z7kCplKRKyiFQ6dHFBem4PwlwKeNFk2/XxTrhRh5T9PyaEWGy/NHTZWbY+nsZlNFJu9rYg== - dependencies: - is-number "^4.0.0" - -array-slice@^1.0.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/array-slice/-/array-slice-1.1.0.tgz" - integrity sha512-B1qMD3RBP7O8o0H2KbrXDyB0IccejMF15+87Lvlor12ONPRHP6gTjXMNkt/d3ZuOGbAe66hFmaCfECI24Ufp6w== - -array-sort@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/array-sort/-/array-sort-1.0.0.tgz" - integrity sha512-ihLeJkonmdiAsD7vpgN3CRcx2J2S0TiYW+IS/5zHBI7mKUq3ySvBdzzBfD236ubDBQFiiyG3SWCPc+msQ9KoYg== - dependencies: - default-compare "^1.0.0" - get-value "^2.0.6" - kind-of "^5.0.2" - -array-unique@^0.3.2: - version "0.3.2" - resolved "https://registry.yarnpkg.com/array-unique/-/array-unique-0.3.2.tgz" - integrity sha1-qJS3XUvE9s1nnvMkSp/Y9Gri1Cg= - -assign-symbols@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/assign-symbols/-/assign-symbols-1.0.0.tgz" - integrity sha1-WWZ/QfrdTyDMvCu5a41Pf3jsA2c= - -async-done@^1.2.0, async-done@^1.2.2: - version "1.3.2" - resolved "https://registry.yarnpkg.com/async-done/-/async-done-1.3.2.tgz" - integrity sha512-uYkTP8dw2og1tu1nmza1n1CMW0qb8gWWlwqMmLb7MhBVs4BXrFziT6HXUd+/RlRA/i4H9AkofYloUbs1fwMqlw== - dependencies: - end-of-stream "^1.1.0" - once "^1.3.2" - process-nextick-args "^2.0.0" - stream-exhaust "^1.0.1" - -async-each@^1.0.1: - version "1.0.3" - resolved "https://registry.yarnpkg.com/async-each/-/async-each-1.0.3.tgz" - integrity sha512-z/WhQ5FPySLdvREByI2vZiTWwCnF0moMJ1hK9YQwDTHKh6I7/uSckMetoRGb5UBZPC1z0jlw+n/XCgjeH7y1AQ== - -async-settle@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/async-settle/-/async-settle-1.0.0.tgz" - integrity sha1-HQqRS7Aldb7IqPOnTlCA9yssDGs= - dependencies: - async-done "^1.2.2" - -atob@^2.1.2: - version "2.1.2" - resolved "https://registry.yarnpkg.com/atob/-/atob-2.1.2.tgz" - integrity sha512-Wm6ukoaOGJi/73p/cl2GvLjTI5JM1k/O14isD73YML8StrH/7/lRFgmg8nICZgD3bZZvjwCGxtMOD3wWNAu8cg== - -bach@^1.0.0: - version "1.2.0" - resolved "https://registry.yarnpkg.com/bach/-/bach-1.2.0.tgz" - integrity sha1-Szzpa/JxNPeaG0FKUcFONMO9mIA= - dependencies: - arr-filter "^1.1.1" - arr-flatten "^1.0.1" - arr-map "^2.0.0" - array-each "^1.0.0" - array-initial "^1.0.0" - array-last "^1.1.1" - async-done "^1.2.2" - async-settle "^1.0.0" - now-and-later "^2.0.0" - -balanced-match@^1.0.0: - version "1.0.2" - resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.2.tgz#e83e3a7e3f300b34cb9d87f615fa0cbf357690ee" - integrity sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw== - -base@^0.11.1: - version "0.11.2" - resolved "https://registry.yarnpkg.com/base/-/base-0.11.2.tgz" - integrity sha512-5T6P4xPgpp0YDFvSWwEZ4NoE3aM4QBQXDzmVbraCkFj8zHM+mba8SyqB5DbZWyR7mYHo6Y7BdQo3MoA4m0TeQg== - dependencies: - cache-base "^1.0.1" - class-utils "^0.3.5" - component-emitter "^1.2.1" - define-property "^1.0.0" - isobject "^3.0.1" - mixin-deep "^1.2.0" - pascalcase "^0.1.1" - -binary-extensions@^1.0.0: - version "1.13.1" - resolved "https://registry.yarnpkg.com/binary-extensions/-/binary-extensions-1.13.1.tgz" - integrity sha512-Un7MIEDdUC5gNpcGDV97op1Ywk748MpHcFTHoYs6qnj1Z3j7I53VG3nwZhKzoBZmbdRNnb6WRdFlwl7tSDuZGw== - -bindings@^1.5.0: - version "1.5.0" - resolved "https://registry.yarnpkg.com/bindings/-/bindings-1.5.0.tgz" - integrity sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ== - dependencies: - file-uri-to-path "1.0.0" - -brace-expansion@^1.1.7: - version "1.1.11" - resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-1.1.11.tgz#3c7fcbf529d87226f3d2f52b966ff5271eb441dd" - integrity sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA== - dependencies: - balanced-match "^1.0.0" - concat-map "0.0.1" - -braces@^2.3.1, braces@^2.3.2: - version "2.3.2" - resolved "https://registry.yarnpkg.com/braces/-/braces-2.3.2.tgz" - integrity sha512-aNdbnj9P8PjdXU4ybaWLK2IF3jc/EoDYbC7AazW6to3TRsfXxscC9UXOB5iDiEQrkyIbWp2SLQda4+QAa7nc3w== - dependencies: - arr-flatten "^1.1.0" - array-unique "^0.3.2" - extend-shallow "^2.0.1" - fill-range "^4.0.0" - isobject "^3.0.1" - repeat-element "^1.1.2" - snapdragon "^0.8.1" - snapdragon-node "^2.0.1" - split-string "^3.0.2" - to-regex "^3.0.1" - -buffer-equal@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/buffer-equal/-/buffer-equal-1.0.0.tgz" - integrity sha1-WWFrSYME1Var1GaWayLu2j7KX74= - -buffer-from@^1.0.0: - version "1.1.1" - resolved "https://registry.yarnpkg.com/buffer-from/-/buffer-from-1.1.1.tgz" - integrity sha512-MQcXEUbCKtEo7bhqEs6560Hyd4XaovZlO/k9V3hjVUF/zwW7KBVdSK4gIt/bzwS9MbR5qob+F5jusZsb0YQK2A== - -cache-base@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/cache-base/-/cache-base-1.0.1.tgz" - integrity sha512-AKcdTnFSWATd5/GCPRxr2ChwIJ85CeyrEyjRHlKxQ56d4XJMGym0uAiKn0xbLOGOl3+yRpOTi484dVCEc5AUzQ== - dependencies: - collection-visit "^1.0.0" - component-emitter "^1.2.1" - get-value "^2.0.6" - has-value "^1.0.0" - isobject "^3.0.1" - set-value "^2.0.0" - to-object-path "^0.3.0" - union-value "^1.0.0" - unset-value "^1.0.0" - -call-bind@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/call-bind/-/call-bind-1.0.0.tgz" - integrity sha512-AEXsYIyyDY3MCzbwdhzG3Jx1R0J2wetQyUynn6dYHAO+bg8l1k7jwZtRv4ryryFs7EP+NDlikJlVe59jr0cM2w== - dependencies: - function-bind "^1.1.1" - get-intrinsic "^1.0.0" - -camelcase@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-3.0.0.tgz" - integrity sha1-MvxLn82vhF/N9+c7uXysImHwqwo= - -camelcase@^5.0.0: - version "5.3.1" - resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-5.3.1.tgz#e3c9b31569e106811df242f715725a1f4c494320" - integrity sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg== - -chalk@^2.3.0: - version "2.4.2" - resolved "https://registry.yarnpkg.com/chalk/-/chalk-2.4.2.tgz" - integrity sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ== - dependencies: - ansi-styles "^3.2.1" - escape-string-regexp "^1.0.5" - supports-color "^5.3.0" - -chokidar@^2.0.0: - version "2.1.8" - resolved "https://registry.yarnpkg.com/chokidar/-/chokidar-2.1.8.tgz" - integrity sha512-ZmZUazfOzf0Nve7duiCKD23PFSCs4JPoYyccjUFF3aQkQadqBhfzhjkwBH2mNOG9cTBwhamM37EIsIkZw3nRgg== - dependencies: - anymatch "^2.0.0" - async-each "^1.0.1" - braces "^2.3.2" - glob-parent "^3.1.0" - inherits "^2.0.3" - is-binary-path "^1.0.0" - is-glob "^4.0.0" - normalize-path "^3.0.0" - path-is-absolute "^1.0.0" - readdirp "^2.2.1" - upath "^1.1.1" - optionalDependencies: - fsevents "^1.2.7" - -class-utils@^0.3.5: - version "0.3.6" - resolved "https://registry.yarnpkg.com/class-utils/-/class-utils-0.3.6.tgz" - integrity sha512-qOhPa/Fj7s6TY8H8esGu5QNpMMQxz79h+urzrNYN6mn+9BnxlDGf5QZ+XeCDsxSjPqsSR56XOZOJmpeurnLMeg== - dependencies: - arr-union "^3.1.0" - define-property "^0.2.5" - isobject "^3.0.0" - static-extend "^0.1.1" - -cliui@^3.2.0: - version "3.2.0" - resolved "https://registry.yarnpkg.com/cliui/-/cliui-3.2.0.tgz" - integrity sha1-EgYBU3qRbSmUD5NNo7SNWFo5IT0= - dependencies: - string-width "^1.0.1" - strip-ansi "^3.0.1" - wrap-ansi "^2.0.0" - -clone-buffer@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/clone-buffer/-/clone-buffer-1.0.0.tgz" - integrity sha1-4+JbIHrE5wGvch4staFnksrD3Fg= - -clone-stats@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/clone-stats/-/clone-stats-1.0.0.tgz" - integrity sha1-s3gt/4u1R04Yuba/D9/ngvh3doA= - -clone@^2.1.1: - version "2.1.2" - resolved "https://registry.yarnpkg.com/clone/-/clone-2.1.2.tgz" - integrity sha1-G39Ln1kfHo+DZwQBYANFoCiHQ18= - -cloneable-readable@^1.0.0: - version "1.1.3" - resolved "https://registry.yarnpkg.com/cloneable-readable/-/cloneable-readable-1.1.3.tgz" - integrity sha512-2EF8zTQOxYq70Y4XKtorQupqF0m49MBz2/yf5Bj+MHjvpG3Hy7sImifnqD6UA+TKYxeSV+u6qqQPawN5UvnpKQ== - dependencies: - inherits "^2.0.1" - process-nextick-args "^2.0.0" - readable-stream "^2.3.5" - -code-point-at@^1.0.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/code-point-at/-/code-point-at-1.1.0.tgz" - integrity sha1-DQcLTQQ6W+ozovGkDi7bPZpMz3c= - -collection-map@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/collection-map/-/collection-map-1.0.0.tgz" - integrity sha1-rqDwb40mx4DCt1SUOFVEsiVa8Yw= - dependencies: - arr-map "^2.0.2" - for-own "^1.0.0" - make-iterator "^1.0.0" - -collection-visit@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/collection-visit/-/collection-visit-1.0.0.tgz" - integrity sha1-S8A3PBZLwykbTTaMgpzxqApZ3KA= - dependencies: - map-visit "^1.0.0" - object-visit "^1.0.0" - -color-convert@^1.9.0: - version "1.9.3" - resolved "https://registry.yarnpkg.com/color-convert/-/color-convert-1.9.3.tgz" - integrity sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg== - dependencies: - color-name "1.1.3" - -color-name@1.1.3: - version "1.1.3" - resolved "https://registry.yarnpkg.com/color-name/-/color-name-1.1.3.tgz" - integrity sha1-p9BVi9icQveV3UIyj3QIMcpTvCU= - -color-support@^1.1.3: - version "1.1.3" - resolved "https://registry.yarnpkg.com/color-support/-/color-support-1.1.3.tgz" - integrity sha512-qiBjkpbMLO/HL68y+lh4q0/O1MZFj2RX6X/KmMa3+gJD3z+WwI1ZzDHysvqHGS3mP6mznPckpXmw1nI9cJjyRg== - -component-emitter@^1.2.1: - version "1.3.0" - resolved "https://registry.yarnpkg.com/component-emitter/-/component-emitter-1.3.0.tgz" - integrity sha512-Rd3se6QB+sO1TwqZjscQrurpEPIfO0/yYnSin6Q/rD3mOutHvUrCAhJub3r90uNb+SESBuE0QYoB90YdfatsRg== - -concat-map@0.0.1: - version "0.0.1" - resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b" - integrity sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg== - -concat-stream@^1.6.0: - version "1.6.2" - resolved "https://registry.yarnpkg.com/concat-stream/-/concat-stream-1.6.2.tgz" - integrity sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw== - dependencies: - buffer-from "^1.0.0" - inherits "^2.0.3" - readable-stream "^2.2.2" - typedarray "^0.0.6" - -concat-with-sourcemaps@^1.0.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/concat-with-sourcemaps/-/concat-with-sourcemaps-1.1.0.tgz" - integrity sha512-4gEjHJFT9e+2W/77h/DS5SGUgwDaOwprX8L/gl5+3ixnzkVJJsZWDSelmN3Oilw3LNDZjZV0yqH1hLG3k6nghg== - dependencies: - source-map "^0.6.1" - -convert-source-map@^1.5.0: - version "1.7.0" - resolved "https://registry.yarnpkg.com/convert-source-map/-/convert-source-map-1.7.0.tgz" - integrity sha512-4FJkXzKXEDB1snCFZlLP4gpC3JILicCpGbzG9f9G7tGqGCzETQ2hWPrcinA9oU4wtf2biUaEH5065UnMeR33oA== - dependencies: - safe-buffer "~5.1.1" - -copy-descriptor@^0.1.0: - version "0.1.1" - resolved "https://registry.yarnpkg.com/copy-descriptor/-/copy-descriptor-0.1.1.tgz" - integrity sha1-Z29us8OZl8LuGsOpJP1hJHSPV40= - -copy-props@^2.0.1, copy-props@^2.0.5: - version "2.0.5" - resolved "https://registry.yarnpkg.com/copy-props/-/copy-props-2.0.5.tgz#03cf9ae328d4ebb36f8f1d804448a6af9ee3f2d2" - integrity sha512-XBlx8HSqrT0ObQwmSzM7WE5k8FxTV75h1DX1Z3n6NhQ/UYYAvInWYmG06vFt7hQZArE2fuO62aihiWIVQwh1sw== - dependencies: - each-props "^1.3.2" - is-plain-object "^5.0.0" - -core-util-is@~1.0.0: - version "1.0.2" - resolved "https://registry.yarnpkg.com/core-util-is/-/core-util-is-1.0.2.tgz" - integrity sha1-tf1UIgqivFq1eqtxQMlAdUUDwac= - -d@1, d@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/d/-/d-1.0.1.tgz" - integrity sha512-m62ShEObQ39CfralilEQRjH6oAMtNCV1xJyEx5LpRYUVN+EviphDgUc/F3hnYbADmkiNs67Y+3ylmlG7Lnu+FA== - dependencies: - es5-ext "^0.10.50" - type "^1.0.1" - -debug@^2.2.0, debug@^2.3.3: - version "2.6.9" - resolved "https://registry.yarnpkg.com/debug/-/debug-2.6.9.tgz" - integrity sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA== - dependencies: - ms "2.0.0" - -decamelize@^1.1.1, decamelize@^1.2.0: - version "1.2.0" - resolved "https://registry.yarnpkg.com/decamelize/-/decamelize-1.2.0.tgz#f6534d15148269b20352e7bee26f501f9a191290" - integrity sha1-9lNNFRSCabIDUue+4m9QH5oZEpA= - -decode-uri-component@^0.2.0: - version "0.2.2" - resolved "https://registry.yarnpkg.com/decode-uri-component/-/decode-uri-component-0.2.2.tgz#e69dbe25d37941171dd540e024c444cd5188e1e9" - integrity sha512-FqUYQ+8o158GyGTrMFJms9qh3CqTKvAqgqsTnkLI8sKu0028orqBhxNMFkFen0zGyg6epACD32pjVk58ngIErQ== - -default-compare@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/default-compare/-/default-compare-1.0.0.tgz" - integrity sha512-QWfXlM0EkAbqOCbD/6HjdwT19j7WCkMyiRhWilc4H9/5h/RzTF9gv5LYh1+CmDV5d1rki6KAWLtQale0xt20eQ== - dependencies: - kind-of "^5.0.2" - -default-resolution@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/default-resolution/-/default-resolution-2.0.0.tgz" - integrity sha1-vLgrqnKtebQmp2cy8aga1t8m1oQ= - -define-properties@^1.1.3: - version "1.1.3" - resolved "https://registry.yarnpkg.com/define-properties/-/define-properties-1.1.3.tgz" - integrity sha512-3MqfYKj2lLzdMSf8ZIZE/V+Zuy+BgD6f164e8K2w7dgnpKArBDerGYpM46IYYcjnkdPNMjPk9A6VFB8+3SKlXQ== - dependencies: - object-keys "^1.0.12" - -define-property@^0.2.5: - version "0.2.5" - resolved "https://registry.yarnpkg.com/define-property/-/define-property-0.2.5.tgz" - integrity sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY= - dependencies: - is-descriptor "^0.1.0" - -define-property@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/define-property/-/define-property-1.0.0.tgz" - integrity sha1-dp66rz9KY6rTr56NMEybvnm/sOY= - dependencies: - is-descriptor "^1.0.0" - -define-property@^2.0.2: - version "2.0.2" - resolved "https://registry.yarnpkg.com/define-property/-/define-property-2.0.2.tgz" - integrity sha512-jwK2UV4cnPpbcG7+VRARKTZPUWowwXA8bzH5NP6ud0oeAxyYPuGZUAC7hMugpCdz4BeSZl2Dl9k66CHJ/46ZYQ== - dependencies: - is-descriptor "^1.0.2" - isobject "^3.0.1" - -detect-file@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/detect-file/-/detect-file-1.0.0.tgz" - integrity sha1-8NZtA2cqglyxtzvbP+YjEMjlUrc= - -duplexify@^3.6.0: - version "3.7.1" - resolved "https://registry.yarnpkg.com/duplexify/-/duplexify-3.7.1.tgz" - integrity sha512-07z8uv2wMyS51kKhD1KsdXJg5WQ6t93RneqRxUHnskXVtlYYkLqM0gqStQZ3pj073g687jPCHrqNfCzawLYh5g== - dependencies: - end-of-stream "^1.0.0" - inherits "^2.0.1" - readable-stream "^2.0.0" - stream-shift "^1.0.0" - -each-props@^1.3.2: - version "1.3.2" - resolved "https://registry.yarnpkg.com/each-props/-/each-props-1.3.2.tgz#ea45a414d16dd5cfa419b1a81720d5ca06892333" - integrity sha512-vV0Hem3zAGkJAyU7JSjixeU66rwdynTAa1vofCrSA5fEln+m67Az9CcnkVD776/fsN/UjIWmBDoNRS6t6G9RfA== - dependencies: - is-plain-object "^2.0.1" - object.defaults "^1.1.0" - -end-of-stream@^1.0.0, end-of-stream@^1.1.0: - version "1.4.4" - resolved "https://registry.yarnpkg.com/end-of-stream/-/end-of-stream-1.4.4.tgz" - integrity sha512-+uw1inIHVPQoaVuHzRyXd21icM+cnt4CzD5rW+NC1wjOUSTOs+Te7FOv7AhN7vS9x/oIyhLP5PR1H+phQAHu5Q== - dependencies: - once "^1.4.0" - -entities@~2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/entities/-/entities-2.1.0.tgz#992d3129cf7df6870b96c57858c249a120f8b8b5" - integrity sha512-hCx1oky9PFrJ611mf0ifBLBRW8lUUVRlFolb5gWRfIELabBlbp9xZvrqZLZAs+NxFnbfQoeGd8wDkygjg7U85w== - -error-ex@^1.2.0: - version "1.3.2" - resolved "https://registry.yarnpkg.com/error-ex/-/error-ex-1.3.2.tgz" - integrity sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g== - dependencies: - is-arrayish "^0.2.1" - -es5-ext@^0.10.35, es5-ext@^0.10.46, es5-ext@^0.10.50: - version "0.10.53" - resolved "https://registry.yarnpkg.com/es5-ext/-/es5-ext-0.10.53.tgz" - integrity sha512-Xs2Stw6NiNHWypzRTY1MtaG/uJlwCk8kH81920ma8mvN8Xq1gsfhZvpkImLQArw8AHnv8MT2I45J3c0R8slE+Q== - dependencies: - es6-iterator "~2.0.3" - es6-symbol "~3.1.3" - next-tick "~1.0.0" - -es6-iterator@^2.0.1, es6-iterator@^2.0.3, es6-iterator@~2.0.3: - version "2.0.3" - resolved "https://registry.yarnpkg.com/es6-iterator/-/es6-iterator-2.0.3.tgz" - integrity sha1-p96IkUGgWpSwhUQDstCg+/qY87c= - dependencies: - d "1" - es5-ext "^0.10.35" - es6-symbol "^3.1.1" - -es6-symbol@^3.1.1, es6-symbol@~3.1.3: - version "3.1.3" - resolved "https://registry.yarnpkg.com/es6-symbol/-/es6-symbol-3.1.3.tgz" - integrity sha512-NJ6Yn3FuDinBaBRWl/q5X/s4koRHBrgKAu+yGI6JCBeiu3qrcbJhwT2GeR/EXVfylRk8dpQVJoLEFhK+Mu31NA== - dependencies: - d "^1.0.1" - ext "^1.1.2" - -es6-weak-map@^2.0.1: - version "2.0.3" - resolved "https://registry.yarnpkg.com/es6-weak-map/-/es6-weak-map-2.0.3.tgz" - integrity sha512-p5um32HOTO1kP+w7PRnB+5lQ43Z6muuMuIMffvDN8ZB4GcnjLBV6zGStpbASIMk4DCAvEaamhe2zhyCb/QXXsA== - dependencies: - d "1" - es5-ext "^0.10.46" - es6-iterator "^2.0.3" - es6-symbol "^3.1.1" - -escape-string-regexp@^1.0.5: - version "1.0.5" - resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz" - integrity sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ= - -expand-brackets@^2.1.4: - version "2.1.4" - resolved "https://registry.yarnpkg.com/expand-brackets/-/expand-brackets-2.1.4.tgz" - integrity sha1-t3c14xXOMPa27/D4OwQVGiJEliI= - dependencies: - debug "^2.3.3" - define-property "^0.2.5" - extend-shallow "^2.0.1" - posix-character-classes "^0.1.0" - regex-not "^1.0.0" - snapdragon "^0.8.1" - to-regex "^3.0.1" - -expand-tilde@^2.0.0, expand-tilde@^2.0.2: - version "2.0.2" - resolved "https://registry.yarnpkg.com/expand-tilde/-/expand-tilde-2.0.2.tgz" - integrity sha1-l+gBqgUt8CRU3kawK/YhZCzchQI= - dependencies: - homedir-polyfill "^1.0.1" - -ext@^1.1.2: - version "1.4.0" - resolved "https://registry.yarnpkg.com/ext/-/ext-1.4.0.tgz" - integrity sha512-Key5NIsUxdqKg3vIsdw9dSuXpPCQ297y6wBjL30edxwPgt2E44WcWBZey/ZvUc6sERLTxKdyCu4gZFmUbk1Q7A== - dependencies: - type "^2.0.0" - -extend-shallow@^2.0.1: - version "2.0.1" - resolved "https://registry.yarnpkg.com/extend-shallow/-/extend-shallow-2.0.1.tgz" - integrity sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8= - dependencies: - is-extendable "^0.1.0" - -extend-shallow@^3.0.0, extend-shallow@^3.0.2: - version "3.0.2" - resolved "https://registry.yarnpkg.com/extend-shallow/-/extend-shallow-3.0.2.tgz" - integrity sha1-Jqcarwc7OfshJxcnRhMcJwQCjbg= - dependencies: - assign-symbols "^1.0.0" - is-extendable "^1.0.1" - -extend@^3.0.0: - version "3.0.2" - resolved "https://registry.yarnpkg.com/extend/-/extend-3.0.2.tgz" - integrity sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g== - -extglob@^2.0.4: - version "2.0.4" - resolved "https://registry.yarnpkg.com/extglob/-/extglob-2.0.4.tgz" - integrity sha512-Nmb6QXkELsuBr24CJSkilo6UHHgbekK5UiZgfE6UHD3Eb27YC6oD+bhcT+tJ6cl8dmsgdQxnWlcry8ksBIBLpw== - dependencies: - array-unique "^0.3.2" - define-property "^1.0.0" - expand-brackets "^2.1.4" - extend-shallow "^2.0.1" - fragment-cache "^0.2.1" - regex-not "^1.0.0" - snapdragon "^0.8.1" - to-regex "^3.0.1" - -fancy-log@^1.3.2: - version "1.3.3" - resolved "https://registry.yarnpkg.com/fancy-log/-/fancy-log-1.3.3.tgz" - integrity sha512-k9oEhlyc0FrVh25qYuSELjr8oxsCoc4/LEZfg2iJJrfEk/tZL9bCoJE47gqAvI2m/AUjluCS4+3I0eTx8n3AEw== - dependencies: - ansi-gray "^0.1.1" - color-support "^1.1.3" - parse-node-version "^1.0.0" - time-stamp "^1.0.0" - -fast-levenshtein@^1.0.0: - version "1.1.4" - resolved "https://registry.yarnpkg.com/fast-levenshtein/-/fast-levenshtein-1.1.4.tgz" - integrity sha1-5qdUzI8V5YmHqpy9J69m/W9OWvk= - -file-uri-to-path@1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz" - integrity sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw== - -fill-range@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/fill-range/-/fill-range-4.0.0.tgz" - integrity sha1-1USBHUKPmOsGpj3EAtJAPDKMOPc= - dependencies: - extend-shallow "^2.0.1" - is-number "^3.0.0" - repeat-string "^1.6.1" - to-regex-range "^2.1.0" - -find-up@^1.0.0: - version "1.1.2" - resolved "https://registry.yarnpkg.com/find-up/-/find-up-1.1.2.tgz" - integrity sha1-ay6YIrGizgpgq2TWEOzK1TyyTQ8= - dependencies: - path-exists "^2.0.0" - pinkie-promise "^2.0.0" - -findup-sync@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/findup-sync/-/findup-sync-2.0.0.tgz" - integrity sha1-kyaxSIwi0aYIhlCoaQGy2akKLLw= - dependencies: - detect-file "^1.0.0" - is-glob "^3.1.0" - micromatch "^3.0.4" - resolve-dir "^1.0.1" - -findup-sync@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/findup-sync/-/findup-sync-3.0.0.tgz" - integrity sha512-YbffarhcicEhOrm4CtrwdKBdCuz576RLdhJDsIfvNtxUuhdRet1qZcsMjqbePtAseKdAnDyM/IyXbu7PRPRLYg== - dependencies: - detect-file "^1.0.0" - is-glob "^4.0.0" - micromatch "^3.0.4" - resolve-dir "^1.0.1" - -fined@^1.0.1: - version "1.2.0" - resolved "https://registry.yarnpkg.com/fined/-/fined-1.2.0.tgz" - integrity sha512-ZYDqPLGxDkDhDZBjZBb+oD1+j0rA4E0pXY50eplAAOPg2N/gUBSSk5IM1/QhPfyVo19lJ+CvXpqfvk+b2p/8Ng== - dependencies: - expand-tilde "^2.0.2" - is-plain-object "^2.0.3" - object.defaults "^1.1.0" - object.pick "^1.2.0" - parse-filepath "^1.0.1" - -flagged-respawn@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/flagged-respawn/-/flagged-respawn-1.0.1.tgz" - integrity sha512-lNaHNVymajmk0OJMBn8fVUAU1BtDeKIqKoVhk4xAALB57aALg6b4W0MfJ/cUE0g9YBXy5XhSlPIpYIJ7HaY/3Q== - -flush-write-stream@^1.0.2: - version "1.1.1" - resolved "https://registry.yarnpkg.com/flush-write-stream/-/flush-write-stream-1.1.1.tgz" - integrity sha512-3Z4XhFZ3992uIq0XOqb9AreonueSYphE6oYbpt5+3u06JWklbsPkNv3ZKkP9Bz/r+1MWCaMoSQ28P85+1Yc77w== - dependencies: - inherits "^2.0.3" - readable-stream "^2.3.6" - -for-in@^1.0.1, for-in@^1.0.2: - version "1.0.2" - resolved "https://registry.yarnpkg.com/for-in/-/for-in-1.0.2.tgz" - integrity sha1-gQaNKVqBQuwKxybG4iAMMPttXoA= - -for-own@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/for-own/-/for-own-1.0.0.tgz" - integrity sha1-xjMy9BXO3EsE2/5wz4NklMU8tEs= - dependencies: - for-in "^1.0.1" - -fragment-cache@^0.2.1: - version "0.2.1" - resolved "https://registry.yarnpkg.com/fragment-cache/-/fragment-cache-0.2.1.tgz" - integrity sha1-QpD60n8T6Jvn8zeZxrxaCr//DRk= - dependencies: - map-cache "^0.2.2" - -fs-mkdirp-stream@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/fs-mkdirp-stream/-/fs-mkdirp-stream-1.0.0.tgz" - integrity sha1-C3gV/DIBxqaeFNuYzgmMFpNSWes= - dependencies: - graceful-fs "^4.1.11" - through2 "^2.0.3" - -fs.realpath@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/fs.realpath/-/fs.realpath-1.0.0.tgz" - integrity sha1-FQStJSMVjKpA20onh8sBQRmU6k8= - -fsevents@^1.2.7: - version "1.2.13" - resolved "https://registry.yarnpkg.com/fsevents/-/fsevents-1.2.13.tgz" - integrity sha512-oWb1Z6mkHIskLzEJ/XWX0srkpkTQ7vaopMQkyaEIoq0fmtFVxOthb8cCxeT+p3ynTdkk/RZwbgG4brR5BeWECw== - dependencies: - bindings "^1.5.0" - nan "^2.12.1" - -function-bind@^1.1.1: - version "1.1.1" - resolved "https://registry.yarnpkg.com/function-bind/-/function-bind-1.1.1.tgz" - integrity sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A== - -get-caller-file@^1.0.1: - version "1.0.3" - resolved "https://registry.yarnpkg.com/get-caller-file/-/get-caller-file-1.0.3.tgz" - integrity sha512-3t6rVToeoZfYSGd8YoLFR2DJkiQrIiUrGcjvFX2mDw3bn6k2OtwHN0TNCLbBO+w8qTvimhDkv+LSscbJY1vE6w== - -get-intrinsic@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/get-intrinsic/-/get-intrinsic-1.0.1.tgz" - integrity sha512-ZnWP+AmS1VUaLgTRy47+zKtjTxz+0xMpx3I52i+aalBK1QP19ggLF3Db89KJX7kjfOfP2eoa01qc++GwPgufPg== - dependencies: - function-bind "^1.1.1" - has "^1.0.3" - has-symbols "^1.0.1" - -get-own-enumerable-property-symbols@^3.0.0: - version "3.0.2" - resolved "https://registry.yarnpkg.com/get-own-enumerable-property-symbols/-/get-own-enumerable-property-symbols-3.0.2.tgz" - integrity sha512-I0UBV/XOz1XkIJHEUDMZAbzCThU/H8DxmSfmdGcKPnVhu2VfFqr34jr9777IyaTYvxjedWhqVIilEDsCdP5G6g== - -get-value@^2.0.3, get-value@^2.0.6: - version "2.0.6" - resolved "https://registry.yarnpkg.com/get-value/-/get-value-2.0.6.tgz" - integrity sha1-3BXKHGcjh8p2vTesCjlbogQqLCg= - -glob-parent@^3.1.0, glob-parent@^5.1.2: - version "5.1.2" - resolved "https://registry.yarnpkg.com/glob-parent/-/glob-parent-5.1.2.tgz#869832c58034fe68a4093c17dc15e8340d8401c4" - integrity sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow== - dependencies: - is-glob "^4.0.1" - -glob-stream@^6.1.0: - version "6.1.0" - resolved "https://registry.yarnpkg.com/glob-stream/-/glob-stream-6.1.0.tgz" - integrity sha1-cEXJlBOz65SIjYOrRtC0BMx73eQ= - dependencies: - extend "^3.0.0" - glob "^7.1.1" - glob-parent "^3.1.0" - is-negated-glob "^1.0.0" - ordered-read-streams "^1.0.0" - pumpify "^1.3.5" - readable-stream "^2.1.5" - remove-trailing-separator "^1.0.1" - to-absolute-glob "^2.0.0" - unique-stream "^2.0.2" - -glob-watcher@^5.0.3: - version "5.0.5" - resolved "https://registry.yarnpkg.com/glob-watcher/-/glob-watcher-5.0.5.tgz" - integrity sha512-zOZgGGEHPklZNjZQaZ9f41i7F2YwE+tS5ZHrDhbBCk3stwahn5vQxnFmBJZHoYdusR6R1bLSXeGUy/BhctwKzw== - dependencies: - anymatch "^2.0.0" - async-done "^1.2.0" - chokidar "^2.0.0" - is-negated-glob "^1.0.0" - just-debounce "^1.0.0" - normalize-path "^3.0.0" - object.defaults "^1.1.0" - -glob@^7.1.1: - version "7.1.6" - resolved "https://registry.yarnpkg.com/glob/-/glob-7.1.6.tgz" - integrity sha512-LwaxwyZ72Lk7vZINtNNrywX0ZuLyStrdDtabefZKAY5ZGJhVtgdznluResxNmPitE0SAO+O26sWTHeKSI2wMBA== - dependencies: - fs.realpath "^1.0.0" - inflight "^1.0.4" - inherits "2" - minimatch "^3.0.4" - once "^1.3.0" - path-is-absolute "^1.0.0" - -global-modules@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/global-modules/-/global-modules-1.0.0.tgz" - integrity sha512-sKzpEkf11GpOFuw0Zzjzmt4B4UZwjOcG757PPvrfhxcLFbq0wpsgpOqxpxtxFiCG4DtG93M6XRVbF2oGdev7bg== - dependencies: - global-prefix "^1.0.1" - is-windows "^1.0.1" - resolve-dir "^1.0.0" - -global-prefix@^1.0.1: - version "1.0.2" - resolved "https://registry.yarnpkg.com/global-prefix/-/global-prefix-1.0.2.tgz" - integrity sha1-2/dDxsFJklk8ZVVoy2btMsASLr4= - dependencies: - expand-tilde "^2.0.2" - homedir-polyfill "^1.0.1" - ini "^1.3.4" - is-windows "^1.0.1" - which "^1.2.14" - -glogg@^1.0.0: - version "1.0.2" - resolved "https://registry.yarnpkg.com/glogg/-/glogg-1.0.2.tgz" - integrity sha512-5mwUoSuBk44Y4EshyiqcH95ZntbDdTQqA3QYSrxmzj28Ai0vXBGMH1ApSANH14j2sIRtqCEyg6PfsuP7ElOEDA== - dependencies: - sparkles "^1.0.0" - -graceful-fs@^4.0.0, graceful-fs@^4.1.11, graceful-fs@^4.1.2, graceful-fs@^4.1.6: - version "4.2.4" - resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.4.tgz" - integrity sha512-WjKPNJF79dtJAVniUlGGWHYGz2jWxT6VhN/4m1NdkbZ2nOsEF+cI1Edgql5zCRhs/VsQYRvrXctxktVXZUkixw== - -gulp-cli@^2.2.0: - version "2.3.0" - resolved "https://registry.yarnpkg.com/gulp-cli/-/gulp-cli-2.3.0.tgz" - integrity sha512-zzGBl5fHo0EKSXsHzjspp3y5CONegCm8ErO5Qh0UzFzk2y4tMvzLWhoDokADbarfZRL2pGpRp7yt6gfJX4ph7A== - dependencies: - ansi-colors "^1.0.1" - archy "^1.0.0" - array-sort "^1.0.0" - color-support "^1.1.3" - concat-stream "^1.6.0" - copy-props "^2.0.1" - fancy-log "^1.3.2" - gulplog "^1.0.0" - interpret "^1.4.0" - isobject "^3.0.1" - liftoff "^3.1.0" - matchdep "^2.0.0" - mute-stdout "^1.0.0" - pretty-hrtime "^1.0.0" - replace-homedir "^1.0.0" - semver-greatest-satisfied-range "^1.1.0" - v8flags "^3.2.0" - yargs "^7.1.0" - -gulp-concat@^2.6.1: - version "2.6.1" - resolved "https://registry.yarnpkg.com/gulp-concat/-/gulp-concat-2.6.1.tgz" - integrity sha1-Yz0WyV2IUEYorQJmVmPO5aR5M1M= - dependencies: - concat-with-sourcemaps "^1.0.0" - through2 "^2.0.0" - vinyl "^2.0.0" - -gulp-debug@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/gulp-debug/-/gulp-debug-4.0.0.tgz" - integrity sha512-cn/GhMD2nVZCVxAl5vWao4/dcoZ8wUJ8w3oqTvQaGDmC1vT7swNOEbhQTWJp+/otKePT64aENcqAQXDcdj5H1g== - dependencies: - chalk "^2.3.0" - fancy-log "^1.3.2" - plur "^3.0.0" - stringify-object "^3.0.0" - through2 "^2.0.0" - tildify "^1.1.2" - -gulp@^4.0.2: - version "4.0.2" - resolved "https://registry.yarnpkg.com/gulp/-/gulp-4.0.2.tgz" - integrity sha512-dvEs27SCZt2ibF29xYgmnwwCYZxdxhQ/+LFWlbAW8y7jt68L/65402Lz3+CKy0Ov4rOs+NERmDq7YlZaDqUIfA== - dependencies: - glob-watcher "^5.0.3" - gulp-cli "^2.2.0" - undertaker "^1.2.1" - vinyl-fs "^3.0.0" - -gulplog@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/gulplog/-/gulplog-1.0.0.tgz" - integrity sha1-4oxNRdBey77YGDY86PnFkmIp/+U= - dependencies: - glogg "^1.0.0" - -has-flag@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-3.0.0.tgz" - integrity sha1-tdRU3CGZriJWmfNGfloH87lVuv0= - -has-symbols@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/has-symbols/-/has-symbols-1.0.1.tgz" - integrity sha512-PLcsoqu++dmEIZB+6totNFKq/7Do+Z0u4oT0zKOJNl3lYK6vGwwu2hjHs+68OEZbTjiUE9bgOABXbP/GvrS0Kg== - -has-value@^0.3.1: - version "0.3.1" - resolved "https://registry.yarnpkg.com/has-value/-/has-value-0.3.1.tgz" - integrity sha1-ex9YutpiyoJ+wKIHgCVlSEWZXh8= - dependencies: - get-value "^2.0.3" - has-values "^0.1.4" - isobject "^2.0.0" - -has-value@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/has-value/-/has-value-1.0.0.tgz" - integrity sha1-GLKB2lhbHFxR3vJMkw7SmgvmsXc= - dependencies: - get-value "^2.0.6" - has-values "^1.0.0" - isobject "^3.0.0" - -has-values@^0.1.4: - version "0.1.4" - resolved "https://registry.yarnpkg.com/has-values/-/has-values-0.1.4.tgz" - integrity sha1-bWHeldkd/Km5oCCJrThL/49it3E= - -has-values@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/has-values/-/has-values-1.0.0.tgz" - integrity sha1-lbC2P+whRmGab+V/51Yo1aOe/k8= - dependencies: - is-number "^3.0.0" - kind-of "^4.0.0" - -has@^1.0.3: - version "1.0.3" - resolved "https://registry.yarnpkg.com/has/-/has-1.0.3.tgz" - integrity sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw== - dependencies: - function-bind "^1.1.1" - -homedir-polyfill@^1.0.1: - version "1.0.3" - resolved "https://registry.yarnpkg.com/homedir-polyfill/-/homedir-polyfill-1.0.3.tgz" - integrity sha512-eSmmWE5bZTK2Nou4g0AI3zZ9rswp7GRKoKXS1BLUkvPviOqs4YTN1djQIqrXy9k5gEtdLPy86JjRwsNM9tnDcA== - dependencies: - parse-passwd "^1.0.0" - -hosted-git-info@^2.1.4, hosted-git-info@^3.0.8: - version "3.0.8" - resolved "https://registry.yarnpkg.com/hosted-git-info/-/hosted-git-info-3.0.8.tgz#6e35d4cc87af2c5f816e4cb9ce350ba87a3f370d" - integrity sha512-aXpmwoOhRBrw6X3j0h5RloK4x1OzsxMPyxqIHyNfSe2pypkVTZFpEiRoSipPEPlMrh0HW/XsjkJ5WgnCirpNUw== - dependencies: - lru-cache "^6.0.0" - -inflight@^1.0.4: - version "1.0.6" - resolved "https://registry.yarnpkg.com/inflight/-/inflight-1.0.6.tgz" - integrity sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk= - dependencies: - once "^1.3.0" - wrappy "1" - -inherits@2, inherits@^2.0.1, inherits@^2.0.3, inherits@~2.0.3: - version "2.0.4" - resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.4.tgz" - integrity sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ== - -ini@^1.3.4, ini@^1.3.6: - version "1.3.8" - resolved "https://registry.yarnpkg.com/ini/-/ini-1.3.8.tgz#a29da425b48806f34767a4efce397269af28432c" - integrity sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew== - -interpret@^1.4.0: - version "1.4.0" - resolved "https://registry.yarnpkg.com/interpret/-/interpret-1.4.0.tgz" - integrity sha512-agE4QfB2Lkp9uICn7BAqoscw4SZP9kTE2hxiFI3jBPmXJfdqiahTbUuKGsMoN2GtqL9AxhYioAcVvgsb1HvRbA== - -invert-kv@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/invert-kv/-/invert-kv-1.0.0.tgz" - integrity sha1-EEqOSqym09jNFXqO+L+rLXo//bY= - -irregular-plurals@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/irregular-plurals/-/irregular-plurals-2.0.0.tgz" - integrity sha512-Y75zBYLkh0lJ9qxeHlMjQ7bSbyiSqNW/UOPWDmzC7cXskL1hekSITh1Oc6JV0XCWWZ9DE8VYSB71xocLk3gmGw== - -is-absolute@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/is-absolute/-/is-absolute-1.0.0.tgz" - integrity sha512-dOWoqflvcydARa360Gvv18DZ/gRuHKi2NU/wU5X1ZFzdYfH29nkiNZsF3mp4OJ3H4yo9Mx8A/uAGNzpzPN3yBA== - dependencies: - is-relative "^1.0.0" - is-windows "^1.0.1" - -is-accessor-descriptor@^0.1.6: - version "0.1.6" - resolved "https://registry.yarnpkg.com/is-accessor-descriptor/-/is-accessor-descriptor-0.1.6.tgz" - integrity sha1-qeEss66Nh2cn7u84Q/igiXtcmNY= - dependencies: - kind-of "^3.0.2" - -is-accessor-descriptor@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz" - integrity sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ== - dependencies: - kind-of "^6.0.0" - -is-arrayish@^0.2.1: - version "0.2.1" - resolved "https://registry.yarnpkg.com/is-arrayish/-/is-arrayish-0.2.1.tgz" - integrity sha1-d8mYQFJ6qOyxqLppe4BkWnqSap0= - -is-binary-path@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/is-binary-path/-/is-binary-path-1.0.1.tgz" - integrity sha1-dfFmQrSA8YenEcgUFh/TpKdlWJg= - dependencies: - binary-extensions "^1.0.0" - -is-buffer@^1.1.5: - version "1.1.6" - resolved "https://registry.yarnpkg.com/is-buffer/-/is-buffer-1.1.6.tgz" - integrity sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w== - -is-core-module@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/is-core-module/-/is-core-module-2.1.0.tgz" - integrity sha512-YcV7BgVMRFRua2FqQzKtTDMz8iCuLEyGKjr70q8Zm1yy2qKcurbFEd79PAdHV77oL3NrAaOVQIbMmiHQCHB7ZA== - dependencies: - has "^1.0.3" - -is-data-descriptor@^0.1.4: - version "0.1.4" - resolved "https://registry.yarnpkg.com/is-data-descriptor/-/is-data-descriptor-0.1.4.tgz" - integrity sha1-C17mSDiOLIYCgueT8YVv7D8wG1Y= - dependencies: - kind-of "^3.0.2" - -is-data-descriptor@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz" - integrity sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ== - dependencies: - kind-of "^6.0.0" - -is-descriptor@^0.1.0: - version "0.1.6" - resolved "https://registry.yarnpkg.com/is-descriptor/-/is-descriptor-0.1.6.tgz" - integrity sha512-avDYr0SB3DwO9zsMov0gKCESFYqCnE4hq/4z3TdUlukEy5t9C0YRq7HLrsN52NAcqXKaepeCD0n+B0arnVG3Hg== - dependencies: - is-accessor-descriptor "^0.1.6" - is-data-descriptor "^0.1.4" - kind-of "^5.0.0" - -is-descriptor@^1.0.0, is-descriptor@^1.0.2: - version "1.0.2" - resolved "https://registry.yarnpkg.com/is-descriptor/-/is-descriptor-1.0.2.tgz" - integrity sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg== - dependencies: - is-accessor-descriptor "^1.0.0" - is-data-descriptor "^1.0.0" - kind-of "^6.0.2" - -is-extendable@^0.1.0, is-extendable@^0.1.1: - version "0.1.1" - resolved "https://registry.yarnpkg.com/is-extendable/-/is-extendable-0.1.1.tgz" - integrity sha1-YrEQ4omkcUGOPsNqYX1HLjAd/Ik= - -is-extendable@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/is-extendable/-/is-extendable-1.0.1.tgz" - integrity sha512-arnXMxT1hhoKo9k1LZdmlNyJdDDfy2v0fXjFlmok4+i8ul/6WlbVge9bhM74OpNPQPMGUToDtz+KXa1PneJxOA== - dependencies: - is-plain-object "^2.0.4" - -is-extglob@^2.1.0, is-extglob@^2.1.1: - version "2.1.1" - resolved "https://registry.yarnpkg.com/is-extglob/-/is-extglob-2.1.1.tgz" - integrity sha1-qIwCU1eR8C7TfHahueqXc8gz+MI= - -is-fullwidth-code-point@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-1.0.0.tgz" - integrity sha1-754xOG8DGn8NZDr4L95QxFfvAMs= - dependencies: - number-is-nan "^1.0.0" - -is-glob@^3.1.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/is-glob/-/is-glob-3.1.0.tgz" - integrity sha1-e6WuJCF4BKxwcHuWkiVnSGzD6Eo= - dependencies: - is-extglob "^2.1.0" - -is-glob@^4.0.0, is-glob@^4.0.1: - version "4.0.1" - resolved "https://registry.yarnpkg.com/is-glob/-/is-glob-4.0.1.tgz#7567dbe9f2f5e2467bc77ab83c4a29482407a5dc" - integrity sha512-5G0tKtBTFImOqDnLB2hG6Bp2qcKEFduo4tZu9MT/H6NQv/ghhy30o55ufafxJ/LdH79LLs2Kfrn85TLKyA7BUg== - dependencies: - is-extglob "^2.1.1" - -is-negated-glob@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/is-negated-glob/-/is-negated-glob-1.0.0.tgz" - integrity sha1-aRC8pdqMleeEtXUbl2z1oQ/uNtI= - -is-number@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/is-number/-/is-number-3.0.0.tgz" - integrity sha1-JP1iAaR4LPUFYcgQJ2r8fRLXEZU= - dependencies: - kind-of "^3.0.2" - -is-number@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/is-number/-/is-number-4.0.0.tgz" - integrity sha512-rSklcAIlf1OmFdyAqbnWTLVelsQ58uvZ66S/ZyawjWqIviTWCjg2PzVGw8WUA+nNuPTqb4wgA+NszrJ+08LlgQ== - -is-obj@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/is-obj/-/is-obj-1.0.1.tgz" - integrity sha1-PkcprB9f3gJc19g6iW2rn09n2w8= - -is-plain-object@^2.0.1, is-plain-object@^2.0.3, is-plain-object@^2.0.4: - version "2.0.4" - resolved "https://registry.yarnpkg.com/is-plain-object/-/is-plain-object-2.0.4.tgz" - integrity sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og== - dependencies: - isobject "^3.0.1" - -is-plain-object@^5.0.0: - version "5.0.0" - resolved "https://registry.yarnpkg.com/is-plain-object/-/is-plain-object-5.0.0.tgz#4427f50ab3429e9025ea7d52e9043a9ef4159344" - integrity sha512-VRSzKkbMm5jMDoKLbltAkFQ5Qr7VDiTFGXxYFXXowVj387GeGNOCsOH6Msy00SGZ3Fp84b1Naa1psqgcCIEP5Q== - -is-primitive@^3.0.1: - version "3.0.1" - resolved "https://registry.yarnpkg.com/is-primitive/-/is-primitive-3.0.1.tgz#98c4db1abff185485a657fc2905052b940524d05" - integrity sha512-GljRxhWvlCNRfZyORiH77FwdFwGcMO620o37EOYC0ORWdq+WYNVqW0w2Juzew4M+L81l6/QS3t5gkkihyRqv9w== - -is-regexp@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/is-regexp/-/is-regexp-1.0.0.tgz" - integrity sha1-/S2INUXEa6xaYz57mgnof6LLUGk= - -is-relative@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/is-relative/-/is-relative-1.0.0.tgz" - integrity sha512-Kw/ReK0iqwKeu0MITLFuj0jbPAmEiOsIwyIXvvbfa6QfmN9pkD1M+8pdk7Rl/dTKbH34/XBFMbgD4iMJhLQbGA== - dependencies: - is-unc-path "^1.0.0" - -is-unc-path@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/is-unc-path/-/is-unc-path-1.0.0.tgz" - integrity sha512-mrGpVd0fs7WWLfVsStvgF6iEJnbjDFZh9/emhRDcGWTduTfNHd9CHeUwH3gYIjdbwo4On6hunkztwOaAw0yllQ== - dependencies: - unc-path-regex "^0.1.2" - -is-utf8@^0.2.0, is-utf8@^0.2.1: - version "0.2.1" - resolved "https://registry.yarnpkg.com/is-utf8/-/is-utf8-0.2.1.tgz" - integrity sha1-Sw2hRCEE0bM2NA6AeX6GXPOffXI= - -is-valid-glob@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/is-valid-glob/-/is-valid-glob-1.0.0.tgz" - integrity sha1-Kb8+/3Ab4tTTFdusw5vDn+j2Aao= - -is-windows@^1.0.1, is-windows@^1.0.2: - version "1.0.2" - resolved "https://registry.yarnpkg.com/is-windows/-/is-windows-1.0.2.tgz" - integrity sha512-eXK1UInq2bPmjyX6e3VHIzMLobc4J94i4AWn+Hpq3OU5KkrRC96OAcR3PRJ/pGu6m8TRnBHP9dkXQVsT/COVIA== - -isarray@1.0.0, isarray@~1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/isarray/-/isarray-1.0.0.tgz" - integrity sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE= - -isexe@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/isexe/-/isexe-2.0.0.tgz" - integrity sha1-6PvzdNxVb/iUehDcsFctYz8s+hA= - -isobject@^2.0.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/isobject/-/isobject-2.1.0.tgz" - integrity sha1-8GVWEJaj8dou9GJy+BXIQNh+DIk= - dependencies: - isarray "1.0.0" - -isobject@^3.0.0, isobject@^3.0.1: - version "3.0.1" - resolved "https://registry.yarnpkg.com/isobject/-/isobject-3.0.1.tgz" - integrity sha1-TkMekrEalzFjaqH5yNHMvP2reN8= - -json-stable-stringify-without-jsonify@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz" - integrity sha1-nbe1lJatPzz+8wp1FC0tkwrXJlE= - -just-debounce@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/just-debounce/-/just-debounce-1.0.0.tgz" - integrity sha1-h/zPrv/AtozRnVX2cilD+SnqNeo= - -kind-of@^3.0.2, kind-of@^3.0.3, kind-of@^3.2.0: - version "3.2.2" - resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-3.2.2.tgz" - integrity sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ= - dependencies: - is-buffer "^1.1.5" - -kind-of@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-4.0.0.tgz" - integrity sha1-IIE989cSkosgc3hpGkUGb65y3Vc= - dependencies: - is-buffer "^1.1.5" - -kind-of@^5.0.0, kind-of@^5.0.2: - version "5.1.0" - resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-5.1.0.tgz" - integrity sha512-NGEErnH6F2vUuXDh+OlbcKW7/wOcfdRHaZ7VWtqCztfHri/++YKmP51OdWeGPuqCOba6kk2OTe5d02VmTB80Pw== - -kind-of@^6.0.0, kind-of@^6.0.2: - version "6.0.3" - resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-6.0.3.tgz" - integrity sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw== - -last-run@^1.1.0: - version "1.1.1" - resolved "https://registry.yarnpkg.com/last-run/-/last-run-1.1.1.tgz" - integrity sha1-RblpQsF7HHnHchmCWbqUO+v4yls= - dependencies: - default-resolution "^2.0.0" - es6-weak-map "^2.0.1" - -lazystream@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/lazystream/-/lazystream-1.0.0.tgz" - integrity sha1-9plf4PggOS9hOWvolGJAe7dxaOQ= - dependencies: - readable-stream "^2.0.5" - -lcid@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/lcid/-/lcid-1.0.0.tgz" - integrity sha1-MIrMr6C8SDo4Z7S28rlQYlHRuDU= - dependencies: - invert-kv "^1.0.0" - -lead@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/lead/-/lead-1.0.0.tgz" - integrity sha1-bxT5mje+Op3XhPVJVpDlkDRm7kI= - dependencies: - flush-write-stream "^1.0.2" - -liftoff@^3.1.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/liftoff/-/liftoff-3.1.0.tgz" - integrity sha512-DlIPlJUkCV0Ips2zf2pJP0unEoT1kwYhiiPUGF3s/jtxTCjziNLoiVVh+jqWOWeFi6mmwQ5fNxvAUyPad4Dfog== - dependencies: - extend "^3.0.0" - findup-sync "^3.0.0" - fined "^1.0.1" - flagged-respawn "^1.0.0" - is-plain-object "^2.0.4" - object.map "^1.0.0" - rechoir "^0.6.2" - resolve "^1.1.7" - -linkify-it@^3.0.1: - version "3.0.2" - resolved "https://registry.yarnpkg.com/linkify-it/-/linkify-it-3.0.2.tgz" - integrity sha512-gDBO4aHNZS6coiZCKVhSNh43F9ioIL4JwRjLZPkoLIY4yZFwg264Y5lu2x6rb1Js42Gh6Yqm2f6L2AJcnkzinQ== - dependencies: - uc.micro "^1.0.1" - -load-json-file@^1.0.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/load-json-file/-/load-json-file-1.1.0.tgz" - integrity sha1-lWkFcI1YtLq0wiYbBPWfMcmTdMA= - dependencies: - graceful-fs "^4.1.2" - parse-json "^2.2.0" - pify "^2.0.0" - pinkie-promise "^2.0.0" - strip-bom "^2.0.0" - -lru-cache@^6.0.0: - version "6.0.0" - resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-6.0.0.tgz#6d6fe6570ebd96aaf90fcad1dafa3b2566db3a94" - integrity sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA== - dependencies: - yallist "^4.0.0" - -make-iterator@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/make-iterator/-/make-iterator-1.0.1.tgz" - integrity sha512-pxiuXh0iVEq7VM7KMIhs5gxsfxCux2URptUQaXo4iZZJxBAzTPOLE2BumO5dbfVYq/hBJFBR/a1mFDmOx5AGmw== - dependencies: - kind-of "^6.0.2" - -map-cache@^0.2.0, map-cache@^0.2.2: - version "0.2.2" - resolved "https://registry.yarnpkg.com/map-cache/-/map-cache-0.2.2.tgz" - integrity sha1-wyq9C9ZSXZsFFkW7TyasXcmKDb8= - -map-visit@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/map-visit/-/map-visit-1.0.0.tgz" - integrity sha1-7Nyo8TFE5mDxtb1B8S80edmN+48= - dependencies: - object-visit "^1.0.0" - -markdown-it@12.3.2: - version "12.3.2" - resolved "https://registry.yarnpkg.com/markdown-it/-/markdown-it-12.3.2.tgz#bf92ac92283fe983fe4de8ff8abfb5ad72cd0c90" - integrity sha512-TchMembfxfNVpHkbtriWltGWc+m3xszaRD0CZup7GFFhzIgQqxIfn3eGj1yZpfuflzPvfkt611B2Q/Bsk1YnGg== - dependencies: - argparse "^2.0.1" - entities "~2.1.0" - linkify-it "^3.0.1" - mdurl "^1.0.1" - uc.micro "^1.0.5" - -markdownlint@^0.25.1: - version "0.25.1" - resolved "https://registry.yarnpkg.com/markdownlint/-/markdownlint-0.25.1.tgz#df04536607ebeeda5ccd5e4f38138823ed623788" - integrity sha512-AG7UkLzNa1fxiOv5B+owPsPhtM4D6DoODhsJgiaNg1xowXovrYgOnLqAgOOFQpWOlHFVQUzjMY5ypNNTeov92g== - dependencies: - markdown-it "12.3.2" - -matchdep@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/matchdep/-/matchdep-2.0.0.tgz" - integrity sha1-xvNINKDY28OzfCfui7yyfHd1WC4= - dependencies: - findup-sync "^2.0.0" - micromatch "^3.0.4" - resolve "^1.4.0" - stack-trace "0.0.10" - -mdurl@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/mdurl/-/mdurl-1.0.1.tgz" - integrity sha1-/oWy7HWlkDfyrf7BAP1sYBdhFS4= - -micromatch@^3.0.4, micromatch@^3.1.10, micromatch@^3.1.4: - version "3.1.10" - resolved "https://registry.yarnpkg.com/micromatch/-/micromatch-3.1.10.tgz" - integrity sha512-MWikgl9n9M3w+bpsY3He8L+w9eF9338xRl8IAO5viDizwSzziFEyUzo2xrrloB64ADbTf8uA8vRqqttDTOmccg== - dependencies: - arr-diff "^4.0.0" - array-unique "^0.3.2" - braces "^2.3.1" - define-property "^2.0.2" - extend-shallow "^3.0.2" - extglob "^2.0.4" - fragment-cache "^0.2.1" - kind-of "^6.0.2" - nanomatch "^1.2.9" - object.pick "^1.3.0" - regex-not "^1.0.0" - snapdragon "^0.8.1" - to-regex "^3.0.2" - -minimatch@^3.0.4: - version "3.1.2" - resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.1.2.tgz#19cd194bfd3e428f049a70817c038d89ab4be35b" - integrity sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw== - dependencies: - brace-expansion "^1.1.7" - -mixin-deep@^1.2.0: - version "1.3.2" - resolved "https://registry.yarnpkg.com/mixin-deep/-/mixin-deep-1.3.2.tgz" - integrity sha512-WRoDn//mXBiJ1H40rqa3vH0toePwSsGb45iInWlTySa+Uu4k3tYUSxa2v1KqAiLtvlrSzaExqS1gtk96A9zvEA== - dependencies: - for-in "^1.0.2" - is-extendable "^1.0.1" - -ms@2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/ms/-/ms-2.0.0.tgz" - integrity sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g= - -mute-stdout@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/mute-stdout/-/mute-stdout-1.0.1.tgz" - integrity sha512-kDcwXR4PS7caBpuRYYBUz9iVixUk3anO3f5OYFiIPwK/20vCzKCHyKoulbiDY1S53zD2bxUpxN/IJ+TnXjfvxg== - -nan@^2.12.1: - version "2.14.2" - resolved "https://registry.yarnpkg.com/nan/-/nan-2.14.2.tgz" - integrity sha512-M2ufzIiINKCuDfBSAUr1vWQ+vuVcA9kqx8JJUsbQi6yf1uGRyb7HfpdfUr5qLXf3B/t8dPvcjhKMmlfnP47EzQ== - -nanomatch@^1.2.9: - version "1.2.13" - resolved "https://registry.yarnpkg.com/nanomatch/-/nanomatch-1.2.13.tgz" - integrity sha512-fpoe2T0RbHwBTBUOftAfBPaDEi06ufaUai0mE6Yn1kacc3SnTErfb/h+X94VXzI64rKFHYImXSvdwGGCmwOqCA== - dependencies: - arr-diff "^4.0.0" - array-unique "^0.3.2" - define-property "^2.0.2" - extend-shallow "^3.0.2" - fragment-cache "^0.2.1" - is-windows "^1.0.2" - kind-of "^6.0.2" - object.pick "^1.3.0" - regex-not "^1.0.0" - snapdragon "^0.8.1" - to-regex "^3.0.1" - -next-tick@~1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/next-tick/-/next-tick-1.0.0.tgz" - integrity sha1-yobR/ogoFpsBICCOPchCS524NCw= - -normalize-package-data@^2.3.2: - version "2.5.0" - resolved "https://registry.yarnpkg.com/normalize-package-data/-/normalize-package-data-2.5.0.tgz" - integrity sha512-/5CMN3T0R4XTj4DcGaexo+roZSdSFW/0AOOTROrjxzCG1wrWXEsGbRKevjlIL+ZDE4sZlJr5ED4YW0yqmkK+eA== - dependencies: - hosted-git-info "^2.1.4" - resolve "^1.10.0" - semver "2 || 3 || 4 || 5" - validate-npm-package-license "^3.0.1" - -normalize-path@^2.1.1: - version "2.1.1" - resolved "https://registry.yarnpkg.com/normalize-path/-/normalize-path-2.1.1.tgz" - integrity sha1-GrKLVW4Zg2Oowab35vogE3/mrtk= - dependencies: - remove-trailing-separator "^1.0.1" - -normalize-path@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/normalize-path/-/normalize-path-3.0.0.tgz" - integrity sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA== - -now-and-later@^2.0.0: - version "2.0.1" - resolved "https://registry.yarnpkg.com/now-and-later/-/now-and-later-2.0.1.tgz" - integrity sha512-KGvQ0cB70AQfg107Xvs/Fbu+dGmZoTRJp2TaPwcwQm3/7PteUyN2BCgk8KBMPGBUXZdVwyWS8fDCGFygBm19UQ== - dependencies: - once "^1.3.2" - -number-is-nan@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/number-is-nan/-/number-is-nan-1.0.1.tgz" - integrity sha1-CXtgK1NCKlIsGvuHkDGDNpQaAR0= - -object-copy@^0.1.0: - version "0.1.0" - resolved "https://registry.yarnpkg.com/object-copy/-/object-copy-0.1.0.tgz" - integrity sha1-fn2Fi3gb18mRpBupde04EnVOmYw= - dependencies: - copy-descriptor "^0.1.0" - define-property "^0.2.5" - kind-of "^3.0.3" - -object-keys@^1.0.12, object-keys@^1.1.1: - version "1.1.1" - resolved "https://registry.yarnpkg.com/object-keys/-/object-keys-1.1.1.tgz" - integrity sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA== - -object-visit@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/object-visit/-/object-visit-1.0.1.tgz" - integrity sha1-95xEk68MU3e1n+OdOV5BBC3QRbs= - dependencies: - isobject "^3.0.0" - -object.assign@^4.0.4: - version "4.1.2" - resolved "https://registry.yarnpkg.com/object.assign/-/object.assign-4.1.2.tgz" - integrity sha512-ixT2L5THXsApyiUPYKmW+2EHpXXe5Ii3M+f4e+aJFAHao5amFRW6J0OO6c/LU8Be47utCx2GL89hxGB6XSmKuQ== - dependencies: - call-bind "^1.0.0" - define-properties "^1.1.3" - has-symbols "^1.0.1" - object-keys "^1.1.1" - -object.defaults@^1.0.0, object.defaults@^1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/object.defaults/-/object.defaults-1.1.0.tgz" - integrity sha1-On+GgzS0B96gbaFtiNXNKeQ1/s8= - dependencies: - array-each "^1.0.1" - array-slice "^1.0.0" - for-own "^1.0.0" - isobject "^3.0.0" - -object.map@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/object.map/-/object.map-1.0.1.tgz" - integrity sha1-z4Plncj8wK1fQlDh94s7gb2AHTc= - dependencies: - for-own "^1.0.0" - make-iterator "^1.0.0" - -object.pick@^1.2.0, object.pick@^1.3.0: - version "1.3.0" - resolved "https://registry.yarnpkg.com/object.pick/-/object.pick-1.3.0.tgz" - integrity sha1-h6EKxMFpS9Lhy/U1kaZhQftd10c= - dependencies: - isobject "^3.0.1" - -object.reduce@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/object.reduce/-/object.reduce-1.0.1.tgz" - integrity sha1-b+NI8qx/oPlcpiEiZZkJaCW7A60= - dependencies: - for-own "^1.0.0" - make-iterator "^1.0.0" - -once@^1.3.0, once@^1.3.1, once@^1.3.2, once@^1.4.0: - version "1.4.0" - resolved "https://registry.yarnpkg.com/once/-/once-1.4.0.tgz" - integrity sha1-WDsap3WWHUsROsF9nFC6753Xa9E= - dependencies: - wrappy "1" - -ordered-read-streams@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/ordered-read-streams/-/ordered-read-streams-1.0.1.tgz" - integrity sha1-d8DLN8QVJdZBZtmQ/61+xqDhNj4= - dependencies: - readable-stream "^2.0.1" - -os-homedir@^1.0.0: - version "1.0.2" - resolved "https://registry.yarnpkg.com/os-homedir/-/os-homedir-1.0.2.tgz" - integrity sha1-/7xJiDNuDoM94MFox+8VISGqf7M= - -os-locale@^1.4.0: - version "1.4.0" - resolved "https://registry.yarnpkg.com/os-locale/-/os-locale-1.4.0.tgz" - integrity sha1-IPnxeuKe00XoveWDsT0gCYA8FNk= - dependencies: - lcid "^1.0.0" - -parse-filepath@^1.0.1: - version "1.0.2" - resolved "https://registry.yarnpkg.com/parse-filepath/-/parse-filepath-1.0.2.tgz" - integrity sha1-pjISf1Oq89FYdvWHLz/6x2PWyJE= - dependencies: - is-absolute "^1.0.0" - map-cache "^0.2.0" - path-root "^0.1.1" - -parse-json@^2.2.0: - version "2.2.0" - resolved "https://registry.yarnpkg.com/parse-json/-/parse-json-2.2.0.tgz" - integrity sha1-9ID0BDTvgHQfhGkJn43qGPVaTck= - dependencies: - error-ex "^1.2.0" - -parse-node-version@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/parse-node-version/-/parse-node-version-1.0.1.tgz" - integrity sha512-3YHlOa/JgH6Mnpr05jP9eDG254US9ek25LyIxZlDItp2iJtwyaXQb57lBYLdT3MowkUFYEV2XXNAYIPlESvJlA== - -parse-passwd@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/parse-passwd/-/parse-passwd-1.0.0.tgz" - integrity sha1-bVuTSkVpk7I9N/QKOC1vFmao5cY= - -pascalcase@^0.1.1: - version "0.1.1" - resolved "https://registry.yarnpkg.com/pascalcase/-/pascalcase-0.1.1.tgz" - integrity sha1-s2PlXoAGym/iF4TS2yK9FdeRfxQ= - -path-exists@^2.0.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/path-exists/-/path-exists-2.1.0.tgz" - integrity sha1-D+tsZPD8UY2adU3V77YscCJ2H0s= - dependencies: - pinkie-promise "^2.0.0" - -path-is-absolute@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/path-is-absolute/-/path-is-absolute-1.0.1.tgz" - integrity sha1-F0uSaHNVNP+8es5r9TpanhtcX18= - -path-parse@^1.0.6: - version "1.0.7" - resolved "https://registry.yarnpkg.com/path-parse/-/path-parse-1.0.7.tgz#fbc114b60ca42b30d9daf5858e4bd68bbedb6735" - integrity sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw== - -path-root-regex@^0.1.0: - version "0.1.2" - resolved "https://registry.yarnpkg.com/path-root-regex/-/path-root-regex-0.1.2.tgz" - integrity sha1-v8zcjfWxLcUsi0PsONGNcsBLqW0= - -path-root@^0.1.1: - version "0.1.1" - resolved "https://registry.yarnpkg.com/path-root/-/path-root-0.1.1.tgz" - integrity sha1-mkpoFMrBwM1zNgqV8yCDyOpHRbc= - dependencies: - path-root-regex "^0.1.0" - -path-type@^1.0.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/path-type/-/path-type-1.1.0.tgz" - integrity sha1-WcRPfuSR2nBNpBXaWkBwuk+P5EE= - dependencies: - graceful-fs "^4.1.2" - pify "^2.0.0" - pinkie-promise "^2.0.0" - -pify@^2.0.0: - version "2.3.0" - resolved "https://registry.yarnpkg.com/pify/-/pify-2.3.0.tgz" - integrity sha1-7RQaasBDqEnqWISY59yosVMw6Qw= - -pinkie-promise@^2.0.0: - version "2.0.1" - resolved "https://registry.yarnpkg.com/pinkie-promise/-/pinkie-promise-2.0.1.tgz" - integrity sha1-ITXW36ejWMBprJsXh3YogihFD/o= - dependencies: - pinkie "^2.0.0" - -pinkie@^2.0.0: - version "2.0.4" - resolved "https://registry.yarnpkg.com/pinkie/-/pinkie-2.0.4.tgz" - integrity sha1-clVrgM+g1IqXToDnckjoDtT3+HA= - -plur@^3.0.0: - version "3.1.1" - resolved "https://registry.yarnpkg.com/plur/-/plur-3.1.1.tgz" - integrity sha512-t1Ax8KUvV3FFII8ltczPn2tJdjqbd1sIzu6t4JL7nQ3EyeL/lTrj5PWKb06ic5/6XYDr65rQ4uzQEGN70/6X5w== - dependencies: - irregular-plurals "^2.0.0" - -posix-character-classes@^0.1.0: - version "0.1.1" - resolved "https://registry.yarnpkg.com/posix-character-classes/-/posix-character-classes-0.1.1.tgz" - integrity sha1-AerA/jta9xoqbAL+q7jB/vfgDqs= - -pretty-hrtime@^1.0.0: - version "1.0.3" - resolved "https://registry.yarnpkg.com/pretty-hrtime/-/pretty-hrtime-1.0.3.tgz" - integrity sha1-t+PqQkNaTJsnWdmeDyAesZWALuE= - -process-nextick-args@^2.0.0, process-nextick-args@~2.0.0: - version "2.0.1" - resolved "https://registry.yarnpkg.com/process-nextick-args/-/process-nextick-args-2.0.1.tgz" - integrity sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag== - -pump@^2.0.0: - version "2.0.1" - resolved "https://registry.yarnpkg.com/pump/-/pump-2.0.1.tgz" - integrity sha512-ruPMNRkN3MHP1cWJc9OWr+T/xDP0jhXYCLfJcBuX54hhfIBnaQmAUMfDcG4DM5UMWByBbJY69QSphm3jtDKIkA== - dependencies: - end-of-stream "^1.1.0" - once "^1.3.1" - -pumpify@^1.3.5: - version "1.5.1" - resolved "https://registry.yarnpkg.com/pumpify/-/pumpify-1.5.1.tgz" - integrity sha512-oClZI37HvuUJJxSKKrC17bZ9Cu0ZYhEAGPsPUy9KlMUmv9dKX2o77RUmq7f3XjIxbwyGwYzbzQ1L2Ks8sIradQ== - dependencies: - duplexify "^3.6.0" - inherits "^2.0.3" - pump "^2.0.0" - -read-pkg-up@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/read-pkg-up/-/read-pkg-up-1.0.1.tgz" - integrity sha1-nWPBMnbAZZGNV/ACpX9AobZD+wI= - dependencies: - find-up "^1.0.0" - read-pkg "^1.0.0" - -read-pkg@^1.0.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/read-pkg/-/read-pkg-1.1.0.tgz" - integrity sha1-9f+qXs0pyzHAR0vKfXVra7KePyg= - dependencies: - load-json-file "^1.0.0" - normalize-package-data "^2.3.2" - path-type "^1.0.0" - -readable-stream@3: - version "3.6.0" - resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-3.6.0.tgz" - integrity sha512-BViHy7LKeTz4oNnkcLJ+lVSL6vpiFeX6/d3oSH8zCW7UxP2onchk+vTGB143xuFjHS3deTgkKoXXymXqymiIdA== - dependencies: - inherits "^2.0.3" - string_decoder "^1.1.1" - util-deprecate "^1.0.1" - -readable-stream@^2.0.0, readable-stream@^2.0.1, readable-stream@^2.0.2, readable-stream@^2.0.5, readable-stream@^2.1.5, readable-stream@^2.2.2, readable-stream@^2.3.3, readable-stream@^2.3.5, readable-stream@^2.3.6, readable-stream@~2.3.6: - version "2.3.7" - resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-2.3.7.tgz" - integrity sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw== - dependencies: - core-util-is "~1.0.0" - inherits "~2.0.3" - isarray "~1.0.0" - process-nextick-args "~2.0.0" - safe-buffer "~5.1.1" - string_decoder "~1.1.1" - util-deprecate "~1.0.1" - -readdirp@^2.2.1: - version "2.2.1" - resolved "https://registry.yarnpkg.com/readdirp/-/readdirp-2.2.1.tgz" - integrity sha512-1JU/8q+VgFZyxwrJ+SVIOsh+KywWGpds3NTqikiKpDMZWScmAYyKIgqkO+ARvNWJfXeXR1zxz7aHF4u4CyH6vQ== - dependencies: - graceful-fs "^4.1.11" - micromatch "^3.1.10" - readable-stream "^2.0.2" - -rechoir@^0.6.2: - version "0.6.2" - resolved "https://registry.yarnpkg.com/rechoir/-/rechoir-0.6.2.tgz" - integrity sha1-hSBLVNuoLVdC4oyWdW70OvUOM4Q= - dependencies: - resolve "^1.1.6" - -regex-not@^1.0.0, regex-not@^1.0.2: - version "1.0.2" - resolved "https://registry.yarnpkg.com/regex-not/-/regex-not-1.0.2.tgz" - integrity sha512-J6SDjUgDxQj5NusnOtdFxDwN/+HWykR8GELwctJ7mdqhcyy1xEc4SRFHUXvxTp661YaVKAjfRLZ9cCqS6tn32A== - dependencies: - extend-shallow "^3.0.2" - safe-regex "^1.1.0" - -remove-bom-buffer@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/remove-bom-buffer/-/remove-bom-buffer-3.0.0.tgz" - integrity sha512-8v2rWhaakv18qcvNeli2mZ/TMTL2nEyAKRvzo1WtnZBl15SHyEhrCu2/xKlJyUFKHiHgfXIyuY6g2dObJJycXQ== - dependencies: - is-buffer "^1.1.5" - is-utf8 "^0.2.1" - -remove-bom-stream@^1.2.0: - version "1.2.0" - resolved "https://registry.yarnpkg.com/remove-bom-stream/-/remove-bom-stream-1.2.0.tgz" - integrity sha1-BfGlk/FuQuH7kOv1nejlaVJflSM= - dependencies: - remove-bom-buffer "^3.0.0" - safe-buffer "^5.1.0" - through2 "^2.0.3" - -remove-trailing-separator@^1.0.1, remove-trailing-separator@^1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/remove-trailing-separator/-/remove-trailing-separator-1.1.0.tgz" - integrity sha1-wkvOKig62tW8P1jg1IJJuSN52O8= - -repeat-element@^1.1.2: - version "1.1.3" - resolved "https://registry.yarnpkg.com/repeat-element/-/repeat-element-1.1.3.tgz" - integrity sha512-ahGq0ZnV5m5XtZLMb+vP76kcAM5nkLqk0lpqAuojSKGgQtn4eRi4ZZGm2olo2zKFH+sMsWaqOCW1dqAnOru72g== - -repeat-string@^1.6.1: - version "1.6.1" - resolved "https://registry.yarnpkg.com/repeat-string/-/repeat-string-1.6.1.tgz" - integrity sha1-jcrkcOHIirwtYA//Sndihtp15jc= - -replace-ext@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/replace-ext/-/replace-ext-1.0.1.tgz" - integrity sha512-yD5BHCe7quCgBph4rMQ+0KkIRKwWCrHDOX1p1Gp6HwjPM5kVoCdKGNhN7ydqqsX6lJEnQDKZ/tFMiEdQ1dvPEw== - -replace-homedir@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/replace-homedir/-/replace-homedir-1.0.0.tgz" - integrity sha1-6H9tUTuSjd6AgmDBK+f+xv9ueYw= - dependencies: - homedir-polyfill "^1.0.1" - is-absolute "^1.0.0" - remove-trailing-separator "^1.1.0" - -require-directory@^2.1.1: - version "2.1.1" - resolved "https://registry.yarnpkg.com/require-directory/-/require-directory-2.1.1.tgz" - integrity sha1-jGStX9MNqxyXbiNE/+f3kqam30I= - -require-main-filename@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/require-main-filename/-/require-main-filename-1.0.1.tgz" - integrity sha1-l/cXtp1IeE9fUmpsWqj/3aBVpNE= - -resolve-dir@^1.0.0, resolve-dir@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/resolve-dir/-/resolve-dir-1.0.1.tgz" - integrity sha1-eaQGRMNivoLybv/nOcm7U4IEb0M= - dependencies: - expand-tilde "^2.0.0" - global-modules "^1.0.0" - -resolve-options@^1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/resolve-options/-/resolve-options-1.1.0.tgz" - integrity sha1-MrueOcBtZzONyTeMDW1gdFZq0TE= - dependencies: - value-or-function "^3.0.0" - -resolve-url@^0.2.1: - version "0.2.1" - resolved "https://registry.yarnpkg.com/resolve-url/-/resolve-url-0.2.1.tgz" - integrity sha1-LGN/53yJOv0qZj/iGqkIAGjiBSo= - -resolve@^1.1.6, resolve@^1.1.7, resolve@^1.10.0, resolve@^1.4.0: - version "1.19.0" - resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.19.0.tgz" - integrity sha512-rArEXAgsBG4UgRGcynxWIWKFvh/XZCcS8UJdHhwy91zwAvCZIbcs+vAbflgBnNjYMs/i/i+/Ux6IZhML1yPvxg== - dependencies: - is-core-module "^2.1.0" - path-parse "^1.0.6" - -ret@~0.1.10: - version "0.1.15" - resolved "https://registry.yarnpkg.com/ret/-/ret-0.1.15.tgz" - integrity sha512-TTlYpa+OL+vMMNG24xSlQGEJ3B/RzEfUlLct7b5G/ytav+wPrplCpVMFuwzXbkecJrb6IYo1iFb0S9v37754mg== - -safe-buffer@^5.1.0, safe-buffer@~5.2.0: - version "5.2.1" - resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.2.1.tgz" - integrity sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ== - -safe-buffer@~5.1.0, safe-buffer@~5.1.1: - version "5.1.2" - resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.1.2.tgz" - integrity sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g== - -safe-regex@^1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/safe-regex/-/safe-regex-1.1.0.tgz" - integrity sha1-QKNmnzsHfR6UPURinhV91IAjvy4= - dependencies: - ret "~0.1.10" - -semver-greatest-satisfied-range@^1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/semver-greatest-satisfied-range/-/semver-greatest-satisfied-range-1.1.0.tgz" - integrity sha1-E+jCZYq5aRywzXEJMkAoDTb3els= - dependencies: - sver-compat "^1.5.0" - -"semver@2 || 3 || 4 || 5": - version "5.7.1" - resolved "https://registry.yarnpkg.com/semver/-/semver-5.7.1.tgz" - integrity sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ== - -set-blocking@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/set-blocking/-/set-blocking-2.0.0.tgz" - integrity sha1-BF+XgtARrppoA93TgrJDkrPYkPc= - -set-value@^2.0.0, set-value@^2.0.1, set-value@^4.0.1: - version "4.1.0" - resolved "https://registry.yarnpkg.com/set-value/-/set-value-4.1.0.tgz#aa433662d87081b75ad88a4743bd450f044e7d09" - integrity sha512-zTEg4HL0RwVrqcWs3ztF+x1vkxfm0lP+MQQFPiMJTKVceBwEV0A569Ou8l9IYQG8jOZdMVI1hGsc0tmeD2o/Lw== - dependencies: - is-plain-object "^2.0.4" - is-primitive "^3.0.1" - -snapdragon-node@^2.0.1: - version "2.1.1" - resolved "https://registry.yarnpkg.com/snapdragon-node/-/snapdragon-node-2.1.1.tgz" - integrity sha512-O27l4xaMYt/RSQ5TR3vpWCAB5Kb/czIcqUFOM/C4fYcLnbZUc1PkjTAMjof2pBWaSTwOUd6qUHcFGVGj7aIwnw== - dependencies: - define-property "^1.0.0" - isobject "^3.0.0" - snapdragon-util "^3.0.1" - -snapdragon-util@^3.0.1: - version "3.0.1" - resolved "https://registry.yarnpkg.com/snapdragon-util/-/snapdragon-util-3.0.1.tgz" - integrity sha512-mbKkMdQKsjX4BAL4bRYTj21edOf8cN7XHdYUJEe+Zn99hVEYcMvKPct1IqNe7+AZPirn8BCDOQBHQZknqmKlZQ== - dependencies: - kind-of "^3.2.0" - -snapdragon@^0.8.1: - version "0.8.2" - resolved "https://registry.yarnpkg.com/snapdragon/-/snapdragon-0.8.2.tgz" - integrity sha512-FtyOnWN/wCHTVXOMwvSv26d+ko5vWlIDD6zoUJ7LW8vh+ZBC8QdljveRP+crNrtBwioEUWy/4dMtbBjA4ioNlg== - dependencies: - base "^0.11.1" - debug "^2.2.0" - define-property "^0.2.5" - extend-shallow "^2.0.1" - map-cache "^0.2.2" - source-map "^0.5.6" - source-map-resolve "^0.5.0" - use "^3.1.0" - -source-map-resolve@^0.5.0: - version "0.5.3" - resolved "https://registry.yarnpkg.com/source-map-resolve/-/source-map-resolve-0.5.3.tgz" - integrity sha512-Htz+RnsXWk5+P2slx5Jh3Q66vhQj1Cllm0zvnaY98+NFx+Dv2CF/f5O/t8x+KaNdrdIAsruNzoh/KpialbqAnw== - dependencies: - atob "^2.1.2" - decode-uri-component "^0.2.0" - resolve-url "^0.2.1" - source-map-url "^0.4.0" - urix "^0.1.0" - -source-map-url@^0.4.0: - version "0.4.0" - resolved "https://registry.yarnpkg.com/source-map-url/-/source-map-url-0.4.0.tgz" - integrity sha1-PpNdfd1zYxuXZZlW1VEo6HtQhKM= - -source-map@^0.5.6: - version "0.5.7" - resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.5.7.tgz" - integrity sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w= - -source-map@^0.6.1: - version "0.6.1" - resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.6.1.tgz" - integrity sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g== - -sparkles@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/sparkles/-/sparkles-1.0.1.tgz" - integrity sha512-dSO0DDYUahUt/0/pD/Is3VIm5TGJjludZ0HVymmhYF6eNA53PVLhnUk0znSYbH8IYBuJdCE+1luR22jNLMaQdw== - -spdx-correct@^3.0.0: - version "3.1.1" - resolved "https://registry.yarnpkg.com/spdx-correct/-/spdx-correct-3.1.1.tgz" - integrity sha512-cOYcUWwhCuHCXi49RhFRCyJEK3iPj1Ziz9DpViV3tbZOwXD49QzIN3MpOLJNxh2qwq2lJJZaKMVw9qNi4jTC0w== - dependencies: - spdx-expression-parse "^3.0.0" - spdx-license-ids "^3.0.0" - -spdx-exceptions@^2.1.0: - version "2.3.0" - resolved "https://registry.yarnpkg.com/spdx-exceptions/-/spdx-exceptions-2.3.0.tgz" - integrity sha512-/tTrYOC7PPI1nUAgx34hUpqXuyJG+DTHJTnIULG4rDygi4xu/tfgmq1e1cIRwRzwZgo4NLySi+ricLkZkw4i5A== - -spdx-expression-parse@^3.0.0: - version "3.0.1" - resolved "https://registry.yarnpkg.com/spdx-expression-parse/-/spdx-expression-parse-3.0.1.tgz" - integrity sha512-cbqHunsQWnJNE6KhVSMsMeH5H/L9EpymbzqTQ3uLwNCLZ1Q481oWaofqH7nO6V07xlXwY6PhQdQ2IedWx/ZK4Q== - dependencies: - spdx-exceptions "^2.1.0" - spdx-license-ids "^3.0.0" - -spdx-license-ids@^3.0.0: - version "3.0.6" - resolved "https://registry.yarnpkg.com/spdx-license-ids/-/spdx-license-ids-3.0.6.tgz" - integrity sha512-+orQK83kyMva3WyPf59k1+Y525csj5JejicWut55zeTWANuN17qSiSLUXWtzHeNWORSvT7GLDJ/E/XiIWoXBTw== - -split-string@^3.0.2: - version "3.1.0" - resolved "https://registry.yarnpkg.com/split-string/-/split-string-3.1.0.tgz" - integrity sha512-NzNVhJDYpwceVVii8/Hu6DKfD2G+NrQHlS/V/qgv763EYudVwEcMQNxd2lh+0VrUByXN/oJkl5grOhYWvQUYiw== - dependencies: - extend-shallow "^3.0.0" - -stack-trace@0.0.10: - version "0.0.10" - resolved "https://registry.yarnpkg.com/stack-trace/-/stack-trace-0.0.10.tgz" - integrity sha1-VHxws0fo0ytOEI6hoqFZ5f3eGcA= - -static-extend@^0.1.1: - version "0.1.2" - resolved "https://registry.yarnpkg.com/static-extend/-/static-extend-0.1.2.tgz" - integrity sha1-YICcOcv/VTNyJv1eC1IPNB8ftcY= - dependencies: - define-property "^0.2.5" - object-copy "^0.1.0" - -stream-exhaust@^1.0.1: - version "1.0.2" - resolved "https://registry.yarnpkg.com/stream-exhaust/-/stream-exhaust-1.0.2.tgz" - integrity sha512-b/qaq/GlBK5xaq1yrK9/zFcyRSTNxmcZwFLGSTG0mXgZl/4Z6GgiyYOXOvY7N3eEvFRAG1bkDRz5EPGSvPYQlw== - -stream-shift@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/stream-shift/-/stream-shift-1.0.1.tgz" - integrity sha512-AiisoFqQ0vbGcZgQPY1cdP2I76glaVA/RauYR4G4thNFgkTqr90yXTo4LYX60Jl+sIlPNHHdGSwo01AvbKUSVQ== - -string-width@^1.0.1, string-width@^1.0.2: - version "1.0.2" - resolved "https://registry.yarnpkg.com/string-width/-/string-width-1.0.2.tgz" - integrity sha1-EYvfW4zcUaKn5w0hHgfisLmxB9M= - dependencies: - code-point-at "^1.0.0" - is-fullwidth-code-point "^1.0.0" - strip-ansi "^3.0.0" - -string_decoder@^1.1.1: - version "1.3.0" - resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-1.3.0.tgz" - integrity sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA== - dependencies: - safe-buffer "~5.2.0" - -string_decoder@~1.1.1: - version "1.1.1" - resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-1.1.1.tgz" - integrity sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg== - dependencies: - safe-buffer "~5.1.0" - -stringify-object@^3.0.0: - version "3.3.0" - resolved "https://registry.yarnpkg.com/stringify-object/-/stringify-object-3.3.0.tgz" - integrity sha512-rHqiFh1elqCQ9WPLIC8I0Q/g/wj5J1eMkyoiD6eoQApWHP0FtlK7rqnhmabL5VUY9JQCcqwwvlOaSuutekgyrw== - dependencies: - get-own-enumerable-property-symbols "^3.0.0" - is-obj "^1.0.1" - is-regexp "^1.0.0" - -strip-ansi@^3.0.0, strip-ansi@^3.0.1: - version "3.0.1" - resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-3.0.1.tgz" - integrity sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8= - dependencies: - ansi-regex "^2.0.0" - -strip-bom@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/strip-bom/-/strip-bom-2.0.0.tgz" - integrity sha1-YhmoVhZSBJHzV4i9vxRHqZx+aw4= - dependencies: - is-utf8 "^0.2.0" - -supports-color@^5.3.0: - version "5.5.0" - resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-5.5.0.tgz" - integrity sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow== - dependencies: - has-flag "^3.0.0" - -sver-compat@^1.5.0: - version "1.5.0" - resolved "https://registry.yarnpkg.com/sver-compat/-/sver-compat-1.5.0.tgz" - integrity sha1-PPh9/rTQe0o/FIJ7wYaz/QxkXNg= - dependencies: - es6-iterator "^2.0.1" - es6-symbol "^3.1.1" - -through2-filter@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/through2-filter/-/through2-filter-3.0.0.tgz" - integrity sha512-jaRjI2WxN3W1V8/FMZ9HKIBXixtiqs3SQSX4/YGIiP3gL6djW48VoZq9tDqeCWs3MT8YY5wb/zli8VW8snY1CA== - dependencies: - through2 "~2.0.0" - xtend "~4.0.0" - -through2@^2.0.0, through2@^2.0.3, through2@~2.0.0: - version "2.0.5" - resolved "https://registry.yarnpkg.com/through2/-/through2-2.0.5.tgz" - integrity sha512-/mrRod8xqpA+IHSLyGCQ2s8SPHiCDEeQJSep1jqLYeEUClOFG2Qsh+4FU6G9VeqpZnGW/Su8LQGc4YKni5rYSQ== - dependencies: - readable-stream "~2.3.6" - xtend "~4.0.1" - -through2@^4.0.2: - version "4.0.2" - resolved "https://registry.yarnpkg.com/through2/-/through2-4.0.2.tgz" - integrity sha512-iOqSav00cVxEEICeD7TjLB1sueEL+81Wpzp2bY17uZjZN0pWZPuo4suZ/61VujxmqSGFfgOcNuTZ85QJwNZQpw== - dependencies: - readable-stream "3" - -tildify@^1.1.2: - version "1.2.0" - resolved "https://registry.yarnpkg.com/tildify/-/tildify-1.2.0.tgz" - integrity sha1-3OwD9V3Km3qj5bBPIYF+tW5jWIo= - dependencies: - os-homedir "^1.0.0" - -time-stamp@^1.0.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/time-stamp/-/time-stamp-1.1.0.tgz" - integrity sha1-dkpaEa9QVhkhsTPztE5hhofg9cM= - -to-absolute-glob@^2.0.0: - version "2.0.2" - resolved "https://registry.yarnpkg.com/to-absolute-glob/-/to-absolute-glob-2.0.2.tgz" - integrity sha1-GGX0PZ50sIItufFFt4z/fQ98hJs= - dependencies: - is-absolute "^1.0.0" - is-negated-glob "^1.0.0" - -to-object-path@^0.3.0: - version "0.3.0" - resolved "https://registry.yarnpkg.com/to-object-path/-/to-object-path-0.3.0.tgz" - integrity sha1-KXWIt7Dn4KwI4E5nL4XB9JmeF68= - dependencies: - kind-of "^3.0.2" - -to-regex-range@^2.1.0: - version "2.1.1" - resolved "https://registry.yarnpkg.com/to-regex-range/-/to-regex-range-2.1.1.tgz" - integrity sha1-fIDBe53+vlmeJzZ+DU3VWQFB2zg= - dependencies: - is-number "^3.0.0" - repeat-string "^1.6.1" - -to-regex@^3.0.1, to-regex@^3.0.2: - version "3.0.2" - resolved "https://registry.yarnpkg.com/to-regex/-/to-regex-3.0.2.tgz" - integrity sha512-FWtleNAtZ/Ki2qtqej2CXTOayOH9bHDQF+Q48VpWyDXjbYxA4Yz8iDB31zXOBUlOHHKidDbqGVrTUvQMPmBGBw== - dependencies: - define-property "^2.0.2" - extend-shallow "^3.0.2" - regex-not "^1.0.2" - safe-regex "^1.1.0" - -to-through@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/to-through/-/to-through-2.0.0.tgz" - integrity sha1-/JKtq6ByZHvAtn1rA2ZKoZUJOvY= - dependencies: - through2 "^2.0.3" - -type@^1.0.1: - version "1.2.0" - resolved "https://registry.yarnpkg.com/type/-/type-1.2.0.tgz" - integrity sha512-+5nt5AAniqsCnu2cEQQdpzCAh33kVx8n0VoFidKpB1dVVLAN/F+bgVOqOJqOnEnrhp222clB5p3vUlD+1QAnfg== - -type@^2.0.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/type/-/type-2.1.0.tgz" - integrity sha512-G9absDWvhAWCV2gmF1zKud3OyC61nZDwWvBL2DApaVFogI07CprggiQAOOjvp2NRjYWFzPyu7vwtDrQFq8jeSA== - -typedarray@^0.0.6: - version "0.0.6" - resolved "https://registry.yarnpkg.com/typedarray/-/typedarray-0.0.6.tgz" - integrity sha1-hnrHTjhkGHsdPUfZlqeOxciDB3c= - -uc.micro@^1.0.1, uc.micro@^1.0.5: - version "1.0.6" - resolved "https://registry.yarnpkg.com/uc.micro/-/uc.micro-1.0.6.tgz" - integrity sha512-8Y75pvTYkLJW2hWQHXxoqRgV7qb9B+9vFEtidML+7koHUFapnVJAZ6cKs+Qjz5Aw3aZWHMC6u0wJE3At+nSGwA== - -unc-path-regex@^0.1.2: - version "0.1.2" - resolved "https://registry.yarnpkg.com/unc-path-regex/-/unc-path-regex-0.1.2.tgz" - integrity sha1-5z3T17DXxe2G+6xrCufYxqadUPo= - -undertaker-registry@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/undertaker-registry/-/undertaker-registry-1.0.1.tgz" - integrity sha1-XkvaMI5KiirlhPm5pDWaSZglzFA= - -undertaker@^1.2.1: - version "1.3.0" - resolved "https://registry.yarnpkg.com/undertaker/-/undertaker-1.3.0.tgz" - integrity sha512-/RXwi5m/Mu3H6IHQGww3GNt1PNXlbeCuclF2QYR14L/2CHPz3DFZkvB5hZ0N/QUkiXWCACML2jXViIQEQc2MLg== - dependencies: - arr-flatten "^1.0.1" - arr-map "^2.0.0" - bach "^1.0.0" - collection-map "^1.0.0" - es6-weak-map "^2.0.1" - fast-levenshtein "^1.0.0" - last-run "^1.1.0" - object.defaults "^1.0.0" - object.reduce "^1.0.0" - undertaker-registry "^1.0.0" - -union-value@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/union-value/-/union-value-1.0.1.tgz" - integrity sha512-tJfXmxMeWYnczCVs7XAEvIV7ieppALdyepWMkHkwciRpZraG/xwT+s2JN8+pr1+8jCRf80FFzvr+MpQeeoF4Xg== - dependencies: - arr-union "^3.1.0" - get-value "^2.0.6" - is-extendable "^0.1.1" - set-value "^2.0.1" - -unique-stream@^2.0.2: - version "2.3.1" - resolved "https://registry.yarnpkg.com/unique-stream/-/unique-stream-2.3.1.tgz" - integrity sha512-2nY4TnBE70yoxHkDli7DMazpWiP7xMdCYqU2nBRO0UB+ZpEkGsSija7MvmvnZFUeC+mrgiUfcHSr3LmRFIg4+A== - dependencies: - json-stable-stringify-without-jsonify "^1.0.1" - through2-filter "^3.0.0" - -unset-value@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/unset-value/-/unset-value-1.0.0.tgz" - integrity sha1-g3aHP30jNRef+x5vw6jtDfyKtVk= - dependencies: - has-value "^0.3.1" - isobject "^3.0.0" - -upath@^1.1.1: - version "1.2.0" - resolved "https://registry.yarnpkg.com/upath/-/upath-1.2.0.tgz" - integrity sha512-aZwGpamFO61g3OlfT7OQCHqhGnW43ieH9WZeP7QxN/G/jS4jfqUkZxoryvJgVPEcrl5NL/ggHsSmLMHuH64Lhg== - -urix@^0.1.0: - version "0.1.0" - resolved "https://registry.yarnpkg.com/urix/-/urix-0.1.0.tgz" - integrity sha1-2pN/emLiH+wf0Y1Js1wpNQZ6bHI= - -use@^3.1.0: - version "3.1.1" - resolved "https://registry.yarnpkg.com/use/-/use-3.1.1.tgz" - integrity sha512-cwESVXlO3url9YWlFW/TA9cshCEhtu7IKJ/p5soJ/gGpj7vbvFrAY/eIioQ6Dw23KjZhYgiIo8HOs1nQ2vr/oQ== - -util-deprecate@^1.0.1, util-deprecate@~1.0.1: - version "1.0.2" - resolved "https://registry.yarnpkg.com/util-deprecate/-/util-deprecate-1.0.2.tgz" - integrity sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8= - -v8flags@^3.2.0: - version "3.2.0" - resolved "https://registry.yarnpkg.com/v8flags/-/v8flags-3.2.0.tgz" - integrity sha512-mH8etigqMfiGWdeXpaaqGfs6BndypxusHHcv2qSHyZkGEznCd/qAXCWWRzeowtL54147cktFOC4P5y+kl8d8Jg== - dependencies: - homedir-polyfill "^1.0.1" - -validate-npm-package-license@^3.0.1: - version "3.0.4" - resolved "https://registry.yarnpkg.com/validate-npm-package-license/-/validate-npm-package-license-3.0.4.tgz" - integrity sha512-DpKm2Ui/xN7/HQKCtpZxoRWBhZ9Z0kqtygG8XCgNQ8ZlDnxuQmWhj566j8fN4Cu3/JmbhsDo7fcAJq4s9h27Ew== - dependencies: - spdx-correct "^3.0.0" - spdx-expression-parse "^3.0.0" - -value-or-function@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/value-or-function/-/value-or-function-3.0.0.tgz" - integrity sha1-HCQ6ULWVwb5Up1S/7OhWO5/42BM= - -vinyl-fs@^3.0.0: - version "3.0.3" - resolved "https://registry.yarnpkg.com/vinyl-fs/-/vinyl-fs-3.0.3.tgz" - integrity sha512-vIu34EkyNyJxmP0jscNzWBSygh7VWhqun6RmqVfXePrOwi9lhvRs//dOaGOTRUQr4tx7/zd26Tk5WeSVZitgng== - dependencies: - fs-mkdirp-stream "^1.0.0" - glob-stream "^6.1.0" - graceful-fs "^4.0.0" - is-valid-glob "^1.0.0" - lazystream "^1.0.0" - lead "^1.0.0" - object.assign "^4.0.4" - pumpify "^1.3.5" - readable-stream "^2.3.3" - remove-bom-buffer "^3.0.0" - remove-bom-stream "^1.2.0" - resolve-options "^1.1.0" - through2 "^2.0.0" - to-through "^2.0.0" - value-or-function "^3.0.0" - vinyl "^2.0.0" - vinyl-sourcemap "^1.1.0" - -vinyl-sourcemap@^1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/vinyl-sourcemap/-/vinyl-sourcemap-1.1.0.tgz" - integrity sha1-kqgAWTo4cDqM2xHYswCtS+Y7PhY= - dependencies: - append-buffer "^1.0.2" - convert-source-map "^1.5.0" - graceful-fs "^4.1.6" - normalize-path "^2.1.1" - now-and-later "^2.0.0" - remove-bom-buffer "^3.0.0" - vinyl "^2.0.0" - -vinyl@^2.0.0: - version "2.2.1" - resolved "https://registry.yarnpkg.com/vinyl/-/vinyl-2.2.1.tgz" - integrity sha512-LII3bXRFBZLlezoG5FfZVcXflZgWP/4dCwKtxd5ky9+LOtM4CS3bIRQsmR1KMnMW07jpE8fqR2lcxPZ+8sJIcw== - dependencies: - clone "^2.1.1" - clone-buffer "^1.0.0" - clone-stats "^1.0.0" - cloneable-readable "^1.0.0" - remove-trailing-separator "^1.0.1" - replace-ext "^1.0.0" - -which-module@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/which-module/-/which-module-1.0.0.tgz" - integrity sha1-u6Y8qGGUiZT/MHc2CJ47lgJsKk8= - -which@^1.2.14: - version "1.3.1" - resolved "https://registry.yarnpkg.com/which/-/which-1.3.1.tgz" - integrity sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ== - dependencies: - isexe "^2.0.0" - -wrap-ansi@^2.0.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-2.1.0.tgz" - integrity sha1-2Pw9KE3QV5T+hJc8rs3Rz4JP3YU= - dependencies: - string-width "^1.0.1" - strip-ansi "^3.0.1" - -wrappy@1: - version "1.0.2" - resolved "https://registry.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz" - integrity sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8= - -xtend@~4.0.0, xtend@~4.0.1: - version "4.0.2" - resolved "https://registry.yarnpkg.com/xtend/-/xtend-4.0.2.tgz" - integrity sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ== - -y18n@^3.2.1, y18n@^5.0.5: - version "5.0.5" - resolved "https://registry.yarnpkg.com/y18n/-/y18n-5.0.5.tgz#8769ec08d03b1ea2df2500acef561743bbb9ab18" - integrity sha512-hsRUr4FFrvhhRH12wOdfs38Gy7k2FFzB9qgN9v3aLykRq0dRcdcpz5C9FxdS2NuhOrI/628b/KSTJ3rwHysYSg== - -yallist@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/yallist/-/yallist-4.0.0.tgz#9bb92790d9c0effec63be73519e11a35019a3a72" - integrity sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A== - -yargs-parser@5.0.0-security.0, yargs-parser@^13.1.2: - version "13.1.2" - resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-13.1.2.tgz#130f09702ebaeef2650d54ce6e3e5706f7a4fb38" - integrity sha512-3lbsNRf/j+A4QuSZfDRA7HRSfWrzO0YjqTJd5kjAq37Zep1CEgaYmrH9Q3GwPiB9cHyd1Y1UwggGhJGoxipbzg== - dependencies: - camelcase "^5.0.0" - decamelize "^1.2.0" - -yargs@^7.1.0: - version "7.1.1" - resolved "https://registry.yarnpkg.com/yargs/-/yargs-7.1.1.tgz" - integrity sha512-huO4Fr1f9PmiJJdll5kwoS2e4GqzGSsMT3PPMpOwoVkOK8ckqAewMTZyA6LXVQWflleb/Z8oPBEvNsMft0XE+g== - dependencies: - camelcase "^3.0.0" - cliui "^3.2.0" - decamelize "^1.1.1" - get-caller-file "^1.0.1" - os-locale "^1.4.0" - read-pkg-up "^1.0.1" - require-directory "^2.1.1" - require-main-filename "^1.0.1" - set-blocking "^2.0.0" - string-width "^1.0.2" - which-module "^1.0.0" - y18n "^3.2.1" - yargs-parser "5.0.0-security.0" From 56ef8481a3717c51bc9a555ea7074ec80c48378f Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Fri, 7 Jul 2023 13:30:40 -0700 Subject: [PATCH 623/779] Checkout history for markdown lint check (#19908) --- .github/workflows/markdownLink.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/workflows/markdownLink.yml b/.github/workflows/markdownLink.yml index 7fe0e955507..ac1be6eba8d 100644 --- a/.github/workflows/markdownLink.yml +++ b/.github/workflows/markdownLink.yml @@ -27,6 +27,10 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 + with: + # Full git history is needed to get a proper + # list of changed files within `super-linter` + fetch-depth: 0 - name: Lint Markdown uses: super-linter/super-linter@v5 env: From 8eb767d00942a34b42aa94d8430fb8c3e88e5d85 Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Fri, 7 Jul 2023 13:33:53 -0700 Subject: [PATCH 624/779] Change variable used to bypass nuget security scanning (#19907) * Add debugging output to determine whether the nuget.config really does have multiple feeds. * Fix up all the nuget config changes * Add new variable. * Revert "Fix up all the nuget config changes" This reverts commit 04a963da70011c48b9c50ef9d02a9eed2a06cc67. --------- Co-authored-by: James Truher --- tools/releaseBuild/azureDevOps/releaseBuild.yml | 2 ++ .../templates/insert-nuget-config-azfeed.yml | 17 +++++++++++++---- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/tools/releaseBuild/azureDevOps/releaseBuild.yml b/tools/releaseBuild/azureDevOps/releaseBuild.yml index be7ce29d2ca..1b8afb39865 100644 --- a/tools/releaseBuild/azureDevOps/releaseBuild.yml +++ b/tools/releaseBuild/azureDevOps/releaseBuild.yml @@ -34,6 +34,8 @@ variables: value: 1 - name: POWERSHELL_TELEMETRY_OPTOUT value: 1 + - name: nugetMultiFeedWarnLevel + value: none - name: NugetSecurityAnalysisWarningLevel value: none # Prevents auto-injection of nuget-security-analysis@0 diff --git a/tools/releaseBuild/azureDevOps/templates/insert-nuget-config-azfeed.yml b/tools/releaseBuild/azureDevOps/templates/insert-nuget-config-azfeed.yml index 3ba642407ce..3ff723be6ed 100644 --- a/tools/releaseBuild/azureDevOps/templates/insert-nuget-config-azfeed.yml +++ b/tools/releaseBuild/azureDevOps/templates/insert-nuget-config-azfeed.yml @@ -4,25 +4,34 @@ parameters: steps: - pwsh: | + $configPath = "${env:NugetConfigDir}/nuget.config" Import-Module ${{ parameters.repoRoot }}/build.psm1 -Force - New-NugetConfigFile -NugetFeedUrl $(AzDevOpsFeed) -UserName $(AzDevOpsFeedUserName) -ClearTextPAT $(AzDevOpsFeedPAT2) -FeedName AzDevOpsFeed -Destination '${{ parameters.repoRoot }}/src/Modules' + New-NugetConfigFile -NugetFeedUrl $(AzDevOpsFeed) -UserName $(AzDevOpsFeedUserName) -ClearTextPAT $(AzDevOpsFeedPAT2) -FeedName AzDevOpsFeed -Destination "${env:NugetConfigDir}" - if(-not (Test-Path "${{ parameters.repoRoot }}/src/Modules/nuget.config")) + if(-not (Test-Path $configPath)) { throw "nuget.config is not created" } + Get-Content $configPath | Write-Verbose -Verbose displayName: 'Add nuget.config for Azure DevOps feed for PSGallery modules' condition: and(succeededOrFailed(), ne(variables['AzDevOpsFeed'], '')) + env: + NugetConfigDir: ${{ parameters.repoRoot }}/src/Modules + - pwsh: | + $configPath = "${env:NugetConfigDir}/nuget.config" Import-Module ${{ parameters.repoRoot }}/build.psm1 -Force - New-NugetConfigFile -NugetFeedUrl $(PSInternalNugetFeed) -UserName $(PSInternalNugetFeedUserName) -ClearTextPAT $(PSInternalNugetFeedPAT) -FeedName AzDevOpsFeed -Destination '${{ parameters.repoRoot }}' + New-NugetConfigFile -NugetFeedUrl $(PSInternalNugetFeed) -UserName $(PSInternalNugetFeedUserName) -ClearTextPAT $(PSInternalNugetFeedPAT) -FeedName AzDevOpsFeed -Destination "${env:NugetConfigDir}" - if(-not (Test-Path "${{ parameters.repoRoot }}/nuget.config")) + if(-not (Test-Path $configPath)) { throw "nuget.config is not created" } + Get-Content $configPath | Write-Verbose -Verbose displayName: 'Add nuget.config for Azure DevOps feed for packages' condition: and(succeededOrFailed(), ne(variables['PSInternalNugetFeed'], '')) + env: + NugetConfigDir: ${{ parameters.repoRoot }} - task: nuget-security-analysis@0 displayName: 'Run Secure Supply Chain analysis' From b90bd97929afa155d2eb91abbd127c1a389f23a2 Mon Sep 17 00:00:00 2001 From: "microsoft-github-policy-service[bot]" <77245923+microsoft-github-policy-service[bot]@users.noreply.github.com> Date: Sat, 8 Jul 2023 19:18:35 +0000 Subject: [PATCH 625/779] FabricBot: Onboarding to GitOps.ResourceManagement because of FabricBot decommissioning (#19905) * Add prIssueManagement.yml to onboard repo to GitOps.ResourceManagement as FabricBot replacement Owners of the FabricBot configuration should have received email notification. The same information contained in the email is published internally at: https://aka.ms/gim/fabricbot. Details on the replacement service and the syntax of the new yaml configuration file is available publicly at: https://microsoft.github.io/GitOps/policies/resource-management.html Please review and merge this PR to complete the process of onboarding to the new service. * Deleting fabricbot.json * Update .github/policies/resourceManagement.yml --------- Co-authored-by: microsoft-github-policy-service[bot] <77245923+microsoft-github-policy-service[bot]@users.noreply.github.com> Co-authored-by: Travis Plunk --- .github/fabricbot.json | 2096 ----------------------- .github/policies/resourceManagement.yml | 387 +++++ 2 files changed, 387 insertions(+), 2096 deletions(-) delete mode 100644 .github/fabricbot.json create mode 100644 .github/policies/resourceManagement.yml diff --git a/.github/fabricbot.json b/.github/fabricbot.json deleted file mode 100644 index 3fcf27f06dd..00000000000 --- a/.github/fabricbot.json +++ /dev/null @@ -1,2096 +0,0 @@ -[ - { - "taskType": "trigger", - "capabilityId": "AutoMerge", - "subCapability": "AutoMerge", - "version": "1.0", - "config": { - "taskName": "AutoMerge", - "minMinutesOpen": "1440", - "mergeType": "squash", - "deleteBranches": true, - "label": "AutoMerge", - "minimumNumberOfStatuses": 6, - "requireAllStatuses": false, - "removeLabelOnPush": true, - "requireSpecificCheckRuns": false, - "requireAllStatuses_exemptList": [ - "CodeFactor", - "Codacy/PR Quality Review" - ], - "requireSpecificCheckRunsList": [ - "PowerShell-CI-linux", - "PowerShell-CI-macos", - "PowerShell-CI-static-analysis", - "PowerShell-CI-windows", - "WIP" - ], - "usePrDescriptionAsCommitMessage": true - }, - "disabled": false - }, - { - "taskType": "trigger", - "capabilityId": "ReleaseAnnouncement", - "subCapability": "ReleaseAnnouncement", - "version": "1.0", - "config": { - "taskName": "Announce a fix has been released", - "prReply": ":tada:`${version}` has been released which incorporates this pull request.:tada:\n\nHandy links:\n* [Release Notes](https://github.com/${owner}/${repo}/releases/tag/${version})\n", - "issueReply": ":tada:This issue was addressed in #${prNumber}, which has now been successfully released as `${version}`.:tada:\n\nHandy links:\n* [Release Notes](https://github.com/${owner}/${repo}/releases/tag/${version})\n", - "packageRegex": "(v\\d+\\.\\d+\\.\\d+(-\\w+(\\.\\d+)?)?)", - "referencedPrsRegex": "\\(#(\\d+)\\)", - "packageVersionGroup": 0, - "packageNameGroup": 1 - } - }, - { - "taskType": "trigger", - "capabilityId": "IssueResponder", - "subCapability": "PullRequestReviewResponder", - "version": "1.0", - "config": { - "taskName": "Add needs author feedback label to pull requests when changes are requested", - "conditions": { - "operator": "and", - "operands": [ - { - "name": "isAction", - "parameters": { - "action": "submitted" - } - }, - { - "name": "isReviewState", - "parameters": { - "state": "changes_requested" - } - } - ] - }, - "actions": [ - { - "name": "addLabel", - "parameters": { - "label": "Waiting on Author" - } - }, - { - "name": "removeMilestone", - "parameters": {} - }, - { - "name": "removeLabel", - "parameters": { - "label": "Review - Needed" - } - } - ], - "eventType": "pull_request", - "eventNames": [ - "pull_request_review" - ] - } - }, - { - "taskType": "trigger", - "capabilityId": "IssueResponder", - "subCapability": "PullRequestResponder", - "version": "1.0", - "config": { - "taskName": "Remove needs author feedback label when the author responds to a pull request", - "conditions": { - "operator": "and", - "operands": [ - { - "name": "isActivitySender", - "parameters": { - "user": { - "type": "author" - } - } - }, - { - "operator": "not", - "operands": [ - { - "name": "isAction", - "parameters": { - "action": "closed" - } - } - ] - }, - { - "name": "hasLabel", - "parameters": { - "label": "Waiting on Author" - } - }, - { - "operator": "not", - "operands": [ - { - "name": "titleContains", - "parameters": { - "isRegex": true, - "titlePattern": "(WIP|Work in progress|🚧)" - } - } - ] - } - ] - }, - "actions": [ - { - "name": "removeLabel", - "parameters": { - "label": "Waiting on Author" - } - } - ], - "eventType": "pull_request", - "eventNames": [ - "pull_request", - "issues", - "project_card" - ] - } - }, - { - "taskType": "trigger", - "capabilityId": "IssueResponder", - "subCapability": "PullRequestCommentResponder", - "version": "1.0", - "config": { - "taskName": "Remove needs author feedback label when the author comments on a pull request", - "conditions": { - "operator": "and", - "operands": [ - { - "name": "isActivitySender", - "parameters": { - "user": { - "type": "author" - } - } - }, - { - "name": "hasLabel", - "parameters": { - "label": "Waiting on Author" - } - } - ] - }, - "actions": [ - { - "name": "removeLabel", - "parameters": { - "label": "Waiting on Author" - } - } - ], - "eventType": "pull_request", - "eventNames": [ - "issue_comment" - ] - } - }, - { - "taskType": "trigger", - "capabilityId": "IssueResponder", - "subCapability": "PullRequestReviewResponder", - "version": "1.0", - "config": { - "taskName": "Remove needs author feedback label when the author responds to a pull request review comment", - "conditions": { - "operator": "and", - "operands": [ - { - "name": "isActivitySender", - "parameters": { - "user": { - "type": "author" - } - } - }, - { - "name": "hasLabel", - "parameters": { - "label": "Waiting on Author" - } - } - ] - }, - "actions": [ - { - "name": "removeLabel", - "parameters": { - "label": "Waiting on Author" - } - } - ], - "eventType": "pull_request", - "eventNames": [ - "pull_request_review" - ] - } - }, - { - "taskType": "trigger", - "capabilityId": "IssueResponder", - "subCapability": "PullRequestResponder", - "version": "1.0", - "config": { - "taskName": "Remove no recent activity label from pull requests", - "conditions": { - "operator": "and", - "operands": [ - { - "operator": "not", - "operands": [ - { - "name": "isAction", - "parameters": { - "action": "closed" - } - } - ] - }, - { - "name": "hasLabel", - "parameters": { - "label": "Stale" - } - }, - { - "name": "isActivitySender", - "parameters": { - "user": { - "type": "author" - } - } - } - ] - }, - "actions": [ - { - "name": "removeLabel", - "parameters": { - "label": "Stale" - } - } - ], - "eventType": "pull_request", - "eventNames": [ - "pull_request", - "issues", - "project_card" - ] - } - }, - { - "taskType": "trigger", - "capabilityId": "IssueResponder", - "subCapability": "PullRequestCommentResponder", - "version": "1.0", - "config": { - "taskName": "Remove no recent activity label when a pull request is commented on", - "conditions": { - "operator": "and", - "operands": [ - { - "name": "hasLabel", - "parameters": { - "label": "Stale" - } - } - ] - }, - "actions": [ - { - "name": "removeLabel", - "parameters": { - "label": "Stale" - } - } - ], - "eventType": "pull_request", - "eventNames": [ - "issue_comment" - ] - } - }, - { - "taskType": "trigger", - "capabilityId": "IssueResponder", - "subCapability": "PullRequestReviewResponder", - "version": "1.0", - "config": { - "taskName": "Remove no recent activity label when a pull request is reviewed", - "conditions": { - "operator": "and", - "operands": [ - { - "name": "hasLabel", - "parameters": { - "label": "Stale" - } - } - ] - }, - "actions": [ - { - "name": "removeLabel", - "parameters": { - "label": "Stale" - } - } - ], - "eventType": "pull_request", - "eventNames": [ - "pull_request_review" - ] - } - }, - { - "taskType": "scheduled", - "capabilityId": "ScheduledSearch", - "subCapability": "ScheduledSearch", - "version": "1.1", - "config": { - "taskName": "Close stale pull requests", - "frequency": [ - { - "weekDay": 0, - "hours": [ - 10, - 22 - ], - "timezoneOffset": -8 - }, - { - "weekDay": 1, - "hours": [ - 10, - 22 - ], - "timezoneOffset": -8 - }, - { - "weekDay": 2, - "hours": [ - 10, - 22 - ], - "timezoneOffset": -8 - }, - { - "weekDay": 3, - "hours": [ - 10, - 22 - ], - "timezoneOffset": -8 - }, - { - "weekDay": 4, - "hours": [ - 10, - 22 - ], - "timezoneOffset": -8 - }, - { - "weekDay": 5, - "hours": [ - 10, - 22 - ], - "timezoneOffset": -8 - }, - { - "weekDay": 6, - "hours": [ - 10, - 22 - ], - "timezoneOffset": -8 - } - ], - "searchTerms": [ - { - "name": "isPr", - "parameters": {} - }, - { - "name": "isOpen", - "parameters": {} - }, - { - "name": "hasLabel", - "parameters": { - "label": "Waiting on Author" - } - }, - { - "name": "hasLabel", - "parameters": { - "label": "Stale" - } - }, - { - "name": "noActivitySince", - "parameters": { - "days": 10 - } - } - ], - "actions": [ - { - "name": "closeIssue", - "parameters": {} - } - ] - } - }, - { - "taskType": "scheduled", - "capabilityId": "ScheduledSearch", - "subCapability": "ScheduledSearch", - "version": "1.1", - "config": { - "taskName": "Add no recent activity label to pull requests", - "frequency": [ - { - "weekDay": 0, - "hours": [ - 1, - 4, - 7, - 10, - 13, - 16, - 19, - 22 - ], - "timezoneOffset": -7 - }, - { - "weekDay": 1, - "hours": [ - 1, - 4, - 7, - 10, - 13, - 16, - 19, - 22 - ], - "timezoneOffset": -7 - }, - { - "weekDay": 2, - "hours": [ - 1, - 4, - 7, - 10, - 13, - 16, - 19, - 22 - ], - "timezoneOffset": -7 - }, - { - "weekDay": 3, - "hours": [ - 1, - 4, - 7, - 10, - 13, - 16, - 19, - 22 - ], - "timezoneOffset": -7 - }, - { - "weekDay": 4, - "hours": [ - 1, - 4, - 7, - 10, - 13, - 16, - 19, - 22 - ], - "timezoneOffset": -7 - }, - { - "weekDay": 5, - "hours": [ - 1, - 4, - 7, - 10, - 13, - 16, - 19, - 22 - ], - "timezoneOffset": -7 - }, - { - "weekDay": 6, - "hours": [ - 1, - 4, - 7, - 10, - 13, - 16, - 19, - 22 - ], - "timezoneOffset": -7 - } - ], - "searchTerms": [ - { - "name": "isPr", - "parameters": {} - }, - { - "name": "isOpen", - "parameters": {} - }, - { - "name": "hasLabel", - "parameters": { - "label": "Waiting on Author" - } - }, - { - "name": "noActivitySince", - "parameters": { - "days": 15 - } - }, - { - "name": "noLabel", - "parameters": { - "label": "Stale" - } - } - ], - "actions": [ - { - "name": "addLabel", - "parameters": { - "label": "Stale" - } - }, - { - "name": "addReply", - "parameters": { - "comment": "This pull request has been automatically marked as stale because it has been marked as requiring author feedback but has not had any activity for **15 days**. It will be closed if no further activity occurs **within 10 days of this comment**." - } - }, - { - "name": "removeMilestone", - "parameters": {} - } - ] - } - }, - { - "taskType": "scheduled", - "capabilityId": "ScheduledSearch", - "subCapability": "ScheduledSearch", - "version": "1.1", - "config": { - "taskName": "Close duplicate issues", - "frequency": [ - { - "weekDay": 0, - "hours": [ - 0, - 3, - 6, - 9, - 12, - 15, - 18, - 21 - ], - "timezoneOffset": -8 - }, - { - "weekDay": 1, - "hours": [ - 0, - 3, - 6, - 9, - 12, - 15, - 18, - 21 - ], - "timezoneOffset": -8 - }, - { - "weekDay": 2, - "hours": [ - 0, - 3, - 6, - 9, - 12, - 15, - 18, - 21 - ], - "timezoneOffset": -8 - }, - { - "weekDay": 3, - "hours": [ - 0, - 3, - 6, - 9, - 12, - 15, - 18, - 21 - ], - "timezoneOffset": -8 - }, - { - "weekDay": 4, - "hours": [ - 0, - 3, - 6, - 9, - 12, - 15, - 18, - 21 - ], - "timezoneOffset": -8 - }, - { - "weekDay": 5, - "hours": [ - 0, - 3, - 6, - 9, - 12, - 15, - 18, - 21 - ], - "timezoneOffset": -8 - }, - { - "weekDay": 6, - "hours": [ - 0, - 3, - 6, - 9, - 12, - 15, - 18, - 21 - ], - "timezoneOffset": -8 - } - ], - "searchTerms": [ - { - "name": "isIssue", - "parameters": {} - }, - { - "name": "isOpen", - "parameters": {} - }, - { - "name": "hasLabel", - "parameters": { - "label": "Resolution-Duplicate" - } - }, - { - "name": "noActivitySince", - "parameters": { - "days": 1 - } - } - ], - "actions": [ - { - "name": "addReply", - "parameters": { - "comment": "This issue has been marked as duplicate and has not had any activity for **1 day**. It has been closed for housekeeping purposes." - } - }, - { - "name": "closeIssue", - "parameters": {} - } - ] - }, - "disabled": false - }, - { - "taskType": "scheduled", - "capabilityId": "ScheduledSearch", - "subCapability": "ScheduledSearch", - "version": "1.1", - "config": { - "taskName": "Close external issues", - "frequency": [ - { - "weekDay": 0, - "hours": [ - 2, - 5, - 8, - 11, - 14, - 17, - 20, - 23 - ], - "timezoneOffset": -8 - }, - { - "weekDay": 1, - "hours": [ - 2, - 5, - 8, - 11, - 14, - 17, - 20, - 23 - ], - "timezoneOffset": -8 - }, - { - "weekDay": 2, - "hours": [ - 2, - 5, - 8, - 11, - 14, - 17, - 20, - 23 - ], - "timezoneOffset": -8 - }, - { - "weekDay": 3, - "hours": [ - 2, - 5, - 8, - 11, - 14, - 17, - 20, - 23 - ], - "timezoneOffset": -8 - }, - { - "weekDay": 4, - "hours": [ - 2, - 5, - 8, - 11, - 14, - 17, - 20, - 23 - ], - "timezoneOffset": -8 - }, - { - "weekDay": 5, - "hours": [ - 2, - 5, - 8, - 11, - 14, - 17, - 20, - 23 - ], - "timezoneOffset": -8 - }, - { - "weekDay": 6, - "hours": [ - 2, - 5, - 8, - 11, - 14, - 17, - 20, - 23 - ], - "timezoneOffset": -8 - } - ], - "searchTerms": [ - { - "name": "isIssue", - "parameters": {} - }, - { - "name": "isOpen", - "parameters": {} - }, - { - "name": "hasLabel", - "parameters": { - "label": "Resolution-External" - } - }, - { - "name": "noActivitySince", - "parameters": { - "days": 1 - } - } - ], - "actions": [ - { - "name": "addReply", - "parameters": { - "comment": "This issue has been marked as external and has not had any activity for **1 day**. It has been be closed for housekeeping purposes." - } - }, - { - "name": "closeIssue", - "parameters": {} - } - ] - } - }, - { - "taskType": "scheduled", - "capabilityId": "ScheduledSearch", - "subCapability": "ScheduledSearch", - "version": "1.1", - "config": { - "taskName": "Close answered issues", - "frequency": [ - { - "weekDay": 0, - "hours": [ - 0, - 12 - ] - }, - { - "weekDay": 1, - "hours": [ - 0, - 12 - ] - }, - { - "weekDay": 2, - "hours": [ - 0, - 12 - ] - }, - { - "weekDay": 3, - "hours": [ - 0, - 12 - ] - }, - { - "weekDay": 4, - "hours": [ - 0, - 12 - ] - }, - { - "weekDay": 5, - "hours": [ - 0, - 12 - ] - }, - { - "weekDay": 6, - "hours": [ - 0, - 12 - ] - } - ], - "searchTerms": [ - { - "name": "isIssue", - "parameters": {} - }, - { - "name": "isOpen", - "parameters": {} - }, - { - "name": "hasLabel", - "parameters": { - "label": "Resolution-Answered" - } - }, - { - "name": "noActivitySince", - "parameters": { - "days": 1 - } - } - ], - "actions": [ - { - "name": "addReply", - "parameters": { - "comment": "This issue has been marked as answered and has not had any activity for **1 day**. It has been closed for housekeeping purposes." - } - }, - { - "name": "closeIssue", - "parameters": {} - } - ] - } - }, - { - "taskType": "scheduled", - "capabilityId": "ScheduledSearch", - "subCapability": "ScheduledSearch", - "version": "1.1", - "config": { - "taskName": "Close fixed issues", - "frequency": [ - { - "weekDay": 0, - "hours": [ - 8, - 20 - ], - "timezoneOffset": -8 - }, - { - "weekDay": 1, - "hours": [ - 8, - 20 - ], - "timezoneOffset": -8 - }, - { - "weekDay": 2, - "hours": [ - 8, - 20 - ], - "timezoneOffset": -8 - }, - { - "weekDay": 3, - "hours": [ - 8, - 20 - ], - "timezoneOffset": -8 - }, - { - "weekDay": 4, - "hours": [ - 8, - 20 - ], - "timezoneOffset": -8 - }, - { - "weekDay": 5, - "hours": [ - 8, - 20 - ], - "timezoneOffset": -8 - }, - { - "weekDay": 6, - "hours": [ - 8, - 20 - ], - "timezoneOffset": -8 - } - ], - "searchTerms": [ - { - "name": "isIssue", - "parameters": {} - }, - { - "name": "isOpen", - "parameters": {} - }, - { - "name": "hasLabel", - "parameters": { - "label": "Resolution-Fixed" - } - }, - { - "name": "noActivitySince", - "parameters": { - "days": 1 - } - } - ], - "actions": [ - { - "name": "addReply", - "parameters": { - "comment": "This issue has been marked as fixed and has not had any activity for **1 day**. It has been closed for housekeeping purposes." - } - }, - { - "name": "closeIssue", - "parameters": {} - } - ] - } - }, - { - "taskType": "trigger", - "capabilityId": "IssueResponder", - "subCapability": "PullRequestResponder", - "version": "1.0", - "config": { - "conditions": { - "operator": "and", - "operands": [ - { - "operator": "not", - "operands": [ - { - "name": "isAssignedToSomeone", - "parameters": {} - } - ] - }, - { - "name": "isAction", - "parameters": { - "action": "opened" - } - } - ] - }, - "eventType": "pull_request", - "eventNames": [ - "pull_request", - "issues", - "project_card" - ], - "actions": [ - { - "name": "assignToGitHubUserGroup", - "parameters": { - "groupId": "wr87plQOBSdssuPwnMk9T", - "skipOpener": true - } - } - ], - "taskName": "Assign unassigned PRs - on push" - } - }, - { - "taskType": "trigger", - "capabilityId": "IssueResponder", - "subCapability": "PullRequestCommentResponder", - "version": "1.0", - "config": { - "conditions": { - "operator": "and", - "operands": [ - { - "operator": "not", - "operands": [ - { - "name": "isAssignedToSomeone", - "parameters": {} - } - ] - } - ] - }, - "eventType": "pull_request", - "eventNames": [ - "issue_comment" - ], - "taskName": "Assign unassigned PRs - on comments", - "actions": [ - { - "name": "assignToGitHubUserGroup", - "parameters": { - "groupId": "wr87plQOBSdssuPwnMk9T" - } - } - ] - }, - "disabled": true - }, - { - "taskType": "trigger", - "capabilityId": "EmailCleanser", - "subCapability": "EmailCleanser", - "version": "1.0", - "config": { - "taskName": "Email reply cleanser" - } - }, - { - "taskType": "scheduled", - "capabilityId": "ScheduledSearch", - "subCapability": "ScheduledSearch", - "version": "1.1", - "config": { - "taskName": "Needs attention", - "frequency": [ - { - "weekDay": 0, - "hours": [ - 6, - 18 - ], - "timezoneOffset": -8 - }, - { - "weekDay": 1, - "hours": [ - 6, - 18 - ], - "timezoneOffset": -8 - }, - { - "weekDay": 2, - "hours": [ - 6, - 18 - ], - "timezoneOffset": -8 - }, - { - "weekDay": 3, - "hours": [ - 6, - 18 - ], - "timezoneOffset": -8 - }, - { - "weekDay": 4, - "hours": [ - 6, - 18 - ], - "timezoneOffset": -8 - }, - { - "weekDay": 5, - "hours": [ - 6, - 18 - ], - "timezoneOffset": -8 - }, - { - "weekDay": 6, - "hours": [ - 6, - 18 - ], - "timezoneOffset": -8 - } - ], - "searchTerms": [ - { - "name": "isPr", - "parameters": {} - }, - { - "name": "isOpen", - "parameters": {} - }, - { - "name": "noLabel", - "parameters": { - "label": "Waiting on Author" - } - }, - { - "name": "noActivitySince", - "parameters": { - "days": 7 - } - }, - { - "name": "noLabel", - "parameters": { - "label": "Stale" - } - }, - { - "name": "noLabel", - "parameters": { - "label": "Review - Needed" - } - }, - { - "name": "noLabel", - "parameters": { - "label": "Review - Committee" - } - }, - { - "name": "isDraftPr", - "parameters": { - "value": "false" - } - } - ], - "actions": [ - { - "name": "addLabel", - "parameters": { - "label": "Review - Needed" - } - }, - { - "name": "addReply", - "parameters": { - "comment": "This pull request has been automatically marked as Review Needed because it has been there has not been any activity for **7 days**.\nMaintainer, please provide feedback and/or mark it as `Waiting on Author`" - } - } - ] - } - }, - { - "taskType": "trigger", - "capabilityId": "IssueResponder", - "subCapability": "PullRequestResponder", - "version": "1.0", - "config": { - "conditions": { - "operator": "and", - "operands": [ - { - "name": "hasLabel", - "parameters": { - "label": "Review - Needed" - } - }, - { - "operator": "or", - "operands": [ - { - "name": "isAction", - "parameters": { - "action": "merged" - } - }, - { - "name": "isAction", - "parameters": { - "action": "closed" - } - }, - { - "name": "isAction", - "parameters": { - "action": "reopened" - } - }, - { - "name": "isAction", - "parameters": { - "action": "assigned" - } - }, - { - "name": "isAction", - "parameters": { - "action": "unassigned" - } - }, - { - "name": "isAction", - "parameters": { - "action": "unlabeled" - } - } - ] - }, - { - "operator": "or", - "operands": [ - { - "name": "activitySenderHasPermissions", - "parameters": { - "association": "MEMBER", - "permissions": "admin" - } - }, - { - "name": "isActivitySender", - "parameters": { - "user": "iSazonov" - } - } - ] - } - ] - }, - "eventType": "pull_request", - "eventNames": [ - "pull_request", - "issues", - "project_card" - ], - "actions": [ - { - "name": "removeLabel", - "parameters": { - "label": "Review - Needed" - } - } - ], - "taskName": "remove review - need when PR updated" - }, - "disabled": false - }, - { - "taskType": "trigger", - "capabilityId": "IssueResponder", - "subCapability": "PullRequestCommentResponder", - "version": "1.0", - "config": { - "conditions": { - "operator": "and", - "operands": [ - { - "name": "hasLabel", - "parameters": { - "label": "Review - Needed" - } - }, - { - "operator": "or", - "operands": [ - { - "name": "activitySenderHasPermissions", - "parameters": { - "association": "MEMBER", - "permissions": "admin" - } - }, - { - "name": "isActivitySender", - "parameters": { - "user": "iSazonov" - } - } - ] - } - ] - }, - "eventType": "pull_request", - "eventNames": [ - "issue_comment" - ], - "taskName": "remove review - need when PR updated - comment created", - "actions": [ - { - "name": "removeLabel", - "parameters": { - "label": "Review - Needed" - } - } - ] - } - }, - { - "taskType": "scheduled", - "capabilityId": "ScheduledSearch", - "subCapability": "ScheduledSearch", - "version": "1.1", - "config": { - "frequency": [ - { - "weekDay": 0, - "hours": [ - 0, - 12 - ], - "timezoneOffset": -7 - }, - { - "weekDay": 1, - "hours": [ - 0, - 12 - ], - "timezoneOffset": -7 - }, - { - "weekDay": 2, - "hours": [ - 0, - 12 - ], - "timezoneOffset": -7 - }, - { - "weekDay": 3, - "hours": [ - 0, - 12 - ], - "timezoneOffset": -7 - }, - { - "weekDay": 4, - "hours": [ - 0, - 12 - ], - "timezoneOffset": -7 - }, - { - "weekDay": 5, - "hours": [ - 0, - 12 - ], - "timezoneOffset": -7 - }, - { - "weekDay": 6, - "hours": [ - 0, - 12 - ], - "timezoneOffset": -7 - } - ], - "searchTerms": [ - { - "name": "isOpen", - "parameters": {} - }, - { - "name": "isDraftPr", - "parameters": { - "value": "true" - } - }, - { - "name": "noLabel", - "parameters": { - "label": "Review - Committee" - } - }, - { - "name": "noLabel", - "parameters": { - "label": "Waiting on Author" - } - }, - { - "name": "noLabel", - "parameters": { - "label": "Stale" - } - }, - { - "name": "noActivitySince", - "parameters": { - "days": 3 - } - } - ], - "actions": [ - { - "name": "addLabel", - "parameters": { - "label": "Waiting on Author" - } - } - ], - "taskName": "Label draft PRs as waiting on author" - }, - "disabled": false - }, - { - "taskType": "trigger", - "capabilityId": "IssueResponder", - "subCapability": "PullRequestResponder", - "version": "1.0", - "config": { - "conditions": { - "operator": "and", - "operands": [ - { - "name": "addedToMilestone", - "parameters": {} - }, - { - "name": "isOpen", - "parameters": {} - } - ] - }, - "eventType": "pull_request", - "eventNames": [ - "pull_request", - "issues", - "project_card" - ], - "actions": [ - { - "name": "removeMilestone", - "parameters": {} - }, - { - "name": "addReply", - "parameters": { - "comment": "Open PRs should not be assigned to milestone, so they are not assigned to the wrong milestone after they are merged. For backport consideration, use a `backport` label. " - } - } - ], - "taskName": "Remove label on Open PRs" - } - }, - { - "taskType": "trigger", - "capabilityId": "IssueResponder", - "subCapability": "IssuesOnlyResponder", - "version": "1.0", - "config": { - "conditions": { - "operator": "and", - "operands": [ - { - "name": "isAction", - "parameters": { - "action": "closed" - } - } - ] - }, - "eventType": "issue", - "eventNames": [ - "issues", - "project_card" - ], - "taskName": "Remove 'Needs-Triage' label when an issue is closed", - "actions": [ - { - "name": "removeLabel", - "parameters": { - "label": "Needs-Triage" - } - } - ] - } - }, - { - "taskType": "scheduled", - "capabilityId": "ScheduledSearch", - "subCapability": "ScheduledSearch", - "version": "1.1", - "config": { - "frequency": [ - { - "weekDay": 0, - "hours": [ - 3, - 15 - ], - "timezoneOffset": -7 - }, - { - "weekDay": 1, - "hours": [ - 3, - 15 - ], - "timezoneOffset": -7 - }, - { - "weekDay": 2, - "hours": [ - 3, - 15 - ], - "timezoneOffset": -7 - }, - { - "weekDay": 3, - "hours": [ - 3, - 15 - ], - "timezoneOffset": -7 - }, - { - "weekDay": 4, - "hours": [ - 3, - 15 - ], - "timezoneOffset": -7 - }, - { - "weekDay": 5, - "hours": [ - 3, - 15 - ], - "timezoneOffset": -7 - }, - { - "weekDay": 6, - "hours": [ - 3, - 15 - ], - "timezoneOffset": -7 - } - ], - "searchTerms": [ - { - "name": "isIssue", - "parameters": {} - }, - { - "name": "isOpen", - "parameters": {} - }, - { - "name": "hasLabel", - "parameters": { - "label": "Resolution-Declined" - } - }, - { - "name": "noActivitySince", - "parameters": { - "days": 1 - } - } - ], - "taskName": "Close declined issues", - "actions": [ - { - "name": "addReply", - "parameters": { - "comment": "This issue has been marked as declined and has not had any activity for **1 day**. It has been closed for housekeeping purposes." - } - }, - { - "name": "closeIssue", - "parameters": {} - } - ] - } - }, - { - "taskType": "scheduled", - "capabilityId": "ScheduledSearch", - "subCapability": "ScheduledSearch", - "version": "1.1", - "config": { - "frequency": [ - { - "weekDay": 0, - "hours": [ - 2, - 14 - ], - "timezoneOffset": -7 - }, - { - "weekDay": 1, - "hours": [ - 2, - 14 - ], - "timezoneOffset": -7 - }, - { - "weekDay": 2, - "hours": [ - 2, - 14 - ], - "timezoneOffset": -7 - }, - { - "weekDay": 3, - "hours": [ - 2, - 14 - ], - "timezoneOffset": -7 - }, - { - "weekDay": 4, - "hours": [ - 2, - 14 - ], - "timezoneOffset": -7 - }, - { - "weekDay": 5, - "hours": [ - 2, - 14 - ], - "timezoneOffset": -7 - }, - { - "weekDay": 6, - "hours": [ - 2, - 14 - ], - "timezoneOffset": -7 - } - ], - "searchTerms": [ - { - "name": "isIssue", - "parameters": {} - }, - { - "name": "isOpen", - "parameters": {} - }, - { - "name": "hasLabel", - "parameters": { - "label": "Resolution-By Design" - } - }, - { - "name": "noActivitySince", - "parameters": { - "days": 1 - } - } - ], - "taskName": "Close by-design issues", - "actions": [ - { - "name": "addReply", - "parameters": { - "comment": "This issue has been marked as by-design and has not had any activity for **1 day**. It has been closed for housekeeping purposes." - } - }, - { - "name": "closeIssue", - "parameters": {} - } - ] - } - }, - { - "taskType": "scheduled", - "capabilityId": "ScheduledSearch", - "subCapability": "ScheduledSearch", - "version": "1.1", - "config": { - "frequency": [ - { - "weekDay": 0, - "hours": [ - 2, - 14 - ], - "timezoneOffset": -7 - }, - { - "weekDay": 1, - "hours": [ - 2, - 14 - ], - "timezoneOffset": -7 - }, - { - "weekDay": 2, - "hours": [ - 2, - 14 - ], - "timezoneOffset": -7 - }, - { - "weekDay": 3, - "hours": [ - 2, - 14 - ], - "timezoneOffset": -7 - }, - { - "weekDay": 4, - "hours": [ - 2, - 14 - ], - "timezoneOffset": -7 - }, - { - "weekDay": 5, - "hours": [ - 2, - 14 - ], - "timezoneOffset": -7 - }, - { - "weekDay": 6, - "hours": [ - 2, - 14 - ], - "timezoneOffset": -7 - } - ], - "searchTerms": [ - { - "name": "isIssue", - "parameters": {} - }, - { - "name": "isOpen", - "parameters": {} - }, - { - "name": "hasLabel", - "parameters": { - "label": "Resolution-Won't Fix" - } - }, - { - "name": "noActivitySince", - "parameters": { - "days": 1 - } - } - ], - "taskName": "Close won't fix issues", - "actions": [ - { - "name": "addReply", - "parameters": { - "comment": "This issue has been marked as won't fix and has not had any activity for **1 day**. It has been closed for housekeeping purposes." - } - }, - { - "name": "closeIssue", - "parameters": {} - } - ] - } - }, - { - "taskType": "trigger", - "capabilityId": "InPrLabel", - "subCapability": "InPrLabel", - "version": "1.0", - "config": { - "taskName": "Add 'In-PR' label to issue", - "label_inPr": "In-PR", - "fixedLabelEnabled": true, - "label_fixed": "Resolution-Fixed" - } - }, - { - "taskType": "trigger", - "capabilityId": "IssueResponder", - "subCapability": "IssueCommentResponder", - "version": "1.0", - "config": { - "conditions": { - "operator": "and", - "operands": [ - { - "name": "isActivitySender", - "parameters": { - "user": { - "type": "author" - } - } - }, - { - "name": "hasLabel", - "parameters": { - "label": "Waiting on Author" - } - } - ] - }, - "eventType": "issue", - "eventNames": [ - "issue_comment" - ], - "taskName": "Remove needs author feedback label when the author comments on an issue", - "actions": [ - { - "name": "removeLabel", - "parameters": { - "label": "Waiting on Author" - } - } - ] - } - }, - { - "taskType": "scheduled", - "capabilityId": "ScheduledSearch", - "subCapability": "ScheduledSearch", - "version": "1.1", - "config": { - "frequency": [ - { - "weekDay": 0, - "hours": [ - 8, - 20 - ], - "timezoneOffset": -8 - }, - { - "weekDay": 1, - "hours": [ - 8, - 20 - ], - "timezoneOffset": -8 - }, - { - "weekDay": 2, - "hours": [ - 8, - 20 - ], - "timezoneOffset": -8 - }, - { - "weekDay": 3, - "hours": [ - 8, - 20 - ], - "timezoneOffset": -8 - }, - { - "weekDay": 4, - "hours": [ - 8, - 20 - ], - "timezoneOffset": -8 - }, - { - "weekDay": 5, - "hours": [ - 8, - 20 - ], - "timezoneOffset": -8 - }, - { - "weekDay": 6, - "hours": [ - 8, - 20 - ], - "timezoneOffset": -8 - } - ], - "searchTerms": [ - { - "name": "isOpen", - "parameters": {} - }, - { - "name": "isIssue", - "parameters": {} - }, - { - "name": "hasLabel", - "parameters": { - "label": "Waiting on Author" - } - }, - { - "name": "noActivitySince", - "parameters": { - "days": 7 - } - } - ], - "taskName": "Close stale issues", - "actions": [ - { - "name": "addReply", - "parameters": { - "comment": "This issue has been marked as \"Waiting on Author\" and has not had any activity for **7 day**. It has been closed for housekeeping purposes." - } - }, - { - "name": "closeIssue", - "parameters": {} - } - ] - } - } -] diff --git a/.github/policies/resourceManagement.yml b/.github/policies/resourceManagement.yml new file mode 100644 index 00000000000..34a322185ef --- /dev/null +++ b/.github/policies/resourceManagement.yml @@ -0,0 +1,387 @@ +id: +name: GitOps.PullRequestIssueManagement +description: GitOps.PullRequestIssueManagement primitive +owner: +resource: repository +disabled: false +where: +configuration: + resourceManagementConfiguration: + scheduledSearches: + - description: + frequencies: + - hourly: + hour: 12 + filters: + - isPullRequest + - isOpen + - hasLabel: + label: Waiting on Author + - hasLabel: + label: Stale + - noActivitySince: + days: 10 + actions: + - closeIssue + - description: + frequencies: + - hourly: + hour: 3 + filters: + - isPullRequest + - isOpen + - hasLabel: + label: Waiting on Author + - noActivitySince: + days: 15 + - isNotLabeledWith: + label: Stale + actions: + - addLabel: + label: Stale + - addReply: + reply: This pull request has been automatically marked as stale because it has been marked as requiring author feedback but has not had any activity for **15 days**. It will be closed if no further activity occurs **within 10 days of this comment**. + - description: + frequencies: + - hourly: + hour: 3 + filters: + - isIssue + - isOpen + - hasLabel: + label: Resolution-Duplicate + - noActivitySince: + days: 1 + actions: + - addReply: + reply: This issue has been marked as duplicate and has not had any activity for **1 day**. It has been closed for housekeeping purposes. + - closeIssue + - description: + frequencies: + - hourly: + hour: 3 + filters: + - isIssue + - isOpen + - hasLabel: + label: Resolution-External + - noActivitySince: + days: 1 + actions: + - addReply: + reply: This issue has been marked as external and has not had any activity for **1 day**. It has been be closed for housekeeping purposes. + - closeIssue + - description: + frequencies: + - hourly: + hour: 12 + filters: + - isIssue + - isOpen + - hasLabel: + label: Resolution-Answered + - noActivitySince: + days: 1 + actions: + - addReply: + reply: This issue has been marked as answered and has not had any activity for **1 day**. It has been closed for housekeeping purposes. + - closeIssue + - description: + frequencies: + - hourly: + hour: 12 + filters: + - isIssue + - isOpen + - hasLabel: + label: Resolution-Fixed + - noActivitySince: + days: 1 + actions: + - addReply: + reply: This issue has been marked as fixed and has not had any activity for **1 day**. It has been closed for housekeeping purposes. + - closeIssue + - description: + frequencies: + - hourly: + hour: 12 + filters: + - isPullRequest + - isOpen + - isNotLabeledWith: + label: Waiting on Author + - noActivitySince: + days: 7 + - isNotLabeledWith: + label: Stale + - isNotLabeledWith: + label: Review - Needed + - isNotLabeledWith: + label: Review - Committee + - isNotDraftPullRequest + actions: + - addLabel: + label: Review - Needed + - addReply: + reply: >- + This pull request has been automatically marked as Review Needed because it has been there has not been any activity for **7 days**. + + Maintainer, please provide feedback and/or mark it as `Waiting on Author` + - description: + frequencies: + - hourly: + hour: 12 + filters: + - isOpen + - isDraftPullRequest + - isNotLabeledWith: + label: Review - Committee + - isNotLabeledWith: + label: Waiting on Author + - isNotLabeledWith: + label: Stale + - noActivitySince: + days: 3 + actions: + - addLabel: + label: Waiting on Author + - description: + frequencies: + - hourly: + hour: 12 + filters: + - isIssue + - isOpen + - hasLabel: + label: Resolution-Declined + - noActivitySince: + days: 1 + actions: + - addReply: + reply: This issue has been marked as declined and has not had any activity for **1 day**. It has been closed for housekeeping purposes. + - closeIssue + - description: + frequencies: + - hourly: + hour: 12 + filters: + - isIssue + - isOpen + - hasLabel: + label: Resolution-By Design + - noActivitySince: + days: 1 + actions: + - addReply: + reply: This issue has been marked as by-design and has not had any activity for **1 day**. It has been closed for housekeeping purposes. + - closeIssue + - description: + frequencies: + - hourly: + hour: 12 + filters: + - isIssue + - isOpen + - hasLabel: + label: Resolution-Won't Fix + - noActivitySince: + days: 1 + actions: + - addReply: + reply: This issue has been marked as won't fix and has not had any activity for **1 day**. It has been closed for housekeeping purposes. + - closeIssue + - description: + frequencies: + - hourly: + hour: 12 + filters: + - isOpen + - isIssue + - hasLabel: + label: Waiting on Author + - noActivitySince: + days: 7 + actions: + - addReply: + reply: This issue has been marked as "Waiting on Author" and has not had any activity for **7 day**. It has been closed for housekeeping purposes. + - closeIssue + eventResponderTasks: + - if: + - payloadType: Pull_Request + - hasLabel: + label: AutoMerge + then: + - enableAutoMerge: + mergeMethod: Squash + description: + - if: + - payloadType: Pull_Request + - labelRemoved: + label: AutoMerge + then: + - disableAutoMerge + description: + - if: + - payloadType: Pull_Request_Review + - isAction: + action: Submitted + - isReviewState: + reviewState: Changes_requested + then: + - addLabel: + label: Waiting on Author + - removeLabel: + label: Review - Needed + description: + - if: + - payloadType: Pull_Request + - isActivitySender: + issueAuthor: True + - not: + isAction: + action: Closed + - hasLabel: + label: Waiting on Author + - not: + titleContains: + pattern: "(WIP|Work in progress|\U0001F6A7)" + isRegex: True + then: + - removeLabel: + label: Waiting on Author + description: + - if: + - payloadType: Issue_Comment + - isActivitySender: + issueAuthor: True + - hasLabel: + label: Waiting on Author + then: + - removeLabel: + label: Waiting on Author + description: + - if: + - payloadType: Pull_Request_Review + - isActivitySender: + issueAuthor: True + - hasLabel: + label: Waiting on Author + then: + - removeLabel: + label: Waiting on Author + description: + - if: + - payloadType: Pull_Request + - not: + isAction: + action: Closed + - hasLabel: + label: Stale + - isActivitySender: + issueAuthor: True + then: + - removeLabel: + label: Stale + description: + - if: + - payloadType: Issue_Comment + - hasLabel: + label: Stale + then: + - removeLabel: + label: Stale + description: + - if: + - payloadType: Pull_Request_Review + - hasLabel: + label: Stale + then: + - removeLabel: + label: Stale + description: + - if: + - payloadType: Pull_Request + - not: isAssignedToSomeone + - isAction: + action: Opened + then: + - assignTo: + users: + - TravisEz13 + - daxian-dbw + - adityapatwardhan + - iSazonov + - SeeminglyScience + description: + - if: + - payloadType: Issue_Comment + then: + - cleanEmailReply + description: + - if: + - payloadType: Pull_Request + - hasLabel: + label: Review - Needed + - or: + - isAction: + action: Null + - isAction: + action: Closed + - isAction: + action: Reopened + - isAction: + action: Assigned + - isAction: + action: Unassigned + - isAction: + action: Unlabeled + - or: + - activitySenderHasPermission: + permission: Admin + - isActivitySender: + user: iSazonov + issueAuthor: False + then: + - removeLabel: + label: Review - Needed + description: + - if: + - payloadType: Issue_Comment + - hasLabel: + label: Review - Needed + - or: + - activitySenderHasPermission: + permission: Admin + - isActivitySender: + user: iSazonov + issueAuthor: False + then: + - removeLabel: + label: Review - Needed + description: + - if: + - payloadType: Issues + - isAction: + action: Closed + then: + - removeLabel: + label: Needs-Triage + description: + - if: + - payloadType: Pull_Request + then: + - inPrLabel: + label: In-PR + description: + - if: + - payloadType: Issue_Comment + - isActivitySender: + issueAuthor: True + - hasLabel: + label: Waiting on Author + then: + - removeLabel: + label: Waiting on Author + description: +onFailure: +onSuccess: From e8984010016378173696492f059276a7d3c4406e Mon Sep 17 00:00:00 2001 From: Anam Navied Date: Mon, 10 Jul 2023 14:16:11 -0400 Subject: [PATCH 626/779] Remove `HostArchitecture` dynamic parameter for `osxpkg` (#19917) --- tools/packaging/packaging.psm1 | 19 ++++--------------- 1 file changed, 4 insertions(+), 15 deletions(-) diff --git a/tools/packaging/packaging.psm1 b/tools/packaging/packaging.psm1 index cdb42ecccb2..d4b3a7064f3 100644 --- a/tools/packaging/packaging.psm1 +++ b/tools/packaging/packaging.psm1 @@ -953,8 +953,11 @@ function New-UnixPackage { # This is a string because strings are appended to it [string]$Iteration = "1", + # Host architecture values allowed for deb type packages: amd64 + # Host architecture values allowed for rpm type packages include: x86_64, aarch64, native, all, noarch, any + # Host architecture values allowed for osxpkg type packages include: x86_64, arm64 [string] - [ValidateSet("x86_64", "amd64", "aarch64", "native", "all", "noarch", "any")] + [ValidateSet("x86_64", "amd64", "aarch64", "arm64", "native", "all", "noarch", "any")] $HostArchitecture, [Switch] @@ -991,19 +994,6 @@ function New-UnixPackage { $Dict.Add("Distribution", $Parameter) > $null return $Dict - } elseif ($Type -eq "osxpkg") { - # Add a dynamic parameter '-HostArchitecture' when the specified package type is 'osxpkg'. - # The '-HostArchitecture' parameter is used to indicate which Mac processor this package is targeting, - # Intel (x86_64) or Apple Silicon (arm64). - $ParameterAttr = New-Object "System.Management.Automation.ParameterAttribute" - $ValidateSetAttr = New-Object "System.Management.Automation.ValidateSetAttribute" -ArgumentList "x86_64", "arm64" - $Attributes = New-Object "System.Collections.ObjectModel.Collection``1[System.Attribute]" - $Attributes.Add($ParameterAttr) > $null - $Attributes.Add($ValidateSetAttr) > $null - $Parameter = New-Object "System.Management.Automation.RuntimeDefinedParameter" -ArgumentList ("HostArchitecture", [string], $Attributes) - $Dict = New-Object "System.Management.Automation.RuntimeDefinedParameterDictionary" - $Dict.Add("HostArchitecture", $Parameter) > $null - return $Dict } } @@ -1057,7 +1047,6 @@ function New-UnixPackage { throw ($ErrorMessage -f "macOS") } - $HostArchitecture = $PSBoundParameters['HostArchitecture'] $DebDistro = 'macOS' } } From 83b06a1cc34515e553bfcb8f65fc096b4bb685b6 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 10 Jul 2023 11:25:51 -0700 Subject: [PATCH 627/779] Bump xunit from 2.4.2 to 2.5.0 (#19902) --- test/xUnit/xUnit.tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/xUnit/xUnit.tests.csproj b/test/xUnit/xUnit.tests.csproj index 9257f579c54..32de853f5aa 100644 --- a/test/xUnit/xUnit.tests.csproj +++ b/test/xUnit/xUnit.tests.csproj @@ -23,7 +23,7 @@
    - + From 919c189f8bff536e434c94b678fce03f8473595c Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 10 Jul 2023 11:36:16 -0700 Subject: [PATCH 628/779] Bump JsonSchema.Net from 4.1.5 to 4.1.6 (#19885) --- .../Microsoft.PowerShell.Commands.Utility.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj index 0eb0a781f19..a3aec44cb82 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj +++ b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj @@ -35,7 +35,7 @@ - + From 1fd1ab7bb0414c11b887b4a8b0d460d0e023e99c Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 10 Jul 2023 12:04:35 -0700 Subject: [PATCH 629/779] Bump XunitXml.TestLogger from 3.0.78 to 3.1.11 (#19900) --- test/xUnit/xUnit.tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/xUnit/xUnit.tests.csproj b/test/xUnit/xUnit.tests.csproj index 32de853f5aa..ecb77cbfaa2 100644 --- a/test/xUnit/xUnit.tests.csproj +++ b/test/xUnit/xUnit.tests.csproj @@ -26,7 +26,7 @@ - + From c5cc8c8bbc20ea7f345c6eda2a37dd426929cf59 Mon Sep 17 00:00:00 2001 From: MartinGC94 <42123497+MartinGC94@users.noreply.github.com> Date: Mon, 10 Jul 2023 21:31:27 +0200 Subject: [PATCH 630/779] Fix a null reference crash in completion code (#19916) --- .../CommandCompletion/CommandCompletion.cs | 3 ++- .../Host/TabCompletion/BugFix.Tests.ps1 | 17 +++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs b/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs index 8071679d63c..9956cf9fa92 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs @@ -516,7 +516,8 @@ private static CommandCompletion CompleteInputImpl(Ast ast, Token[] tokens, IScr // If we were invoked from TabExpansion2, we want to "remove" TabExpansion2 and anything it calls // from our results. We do this by faking out the session so that TabExpansion2 isn't anywhere to be found. SessionStateScope scopeToRestore; - if (context.CurrentCommandProcessor.Command.CommandInfo.Name.Equals("TabExpansion2", StringComparison.OrdinalIgnoreCase) + if (context.CurrentCommandProcessor is not null + && context.CurrentCommandProcessor.Command.CommandInfo.Name.Equals("TabExpansion2", StringComparison.OrdinalIgnoreCase) && context.CurrentCommandProcessor.UseLocalScope && context.EngineSessionState.CurrentScope.Parent is not null) { diff --git a/test/powershell/Host/TabCompletion/BugFix.Tests.ps1 b/test/powershell/Host/TabCompletion/BugFix.Tests.ps1 index dabb215cb16..e0ec96aa87b 100644 --- a/test/powershell/Host/TabCompletion/BugFix.Tests.ps1 +++ b/test/powershell/Host/TabCompletion/BugFix.Tests.ps1 @@ -87,4 +87,21 @@ Describe "Tab completion bug fix" -Tags "CI" { $result.CompletionMatches[0].CompletionText | Should -BeExactly 'Ascending' $result.CompletionMatches[1].CompletionText | Should -BeExactly 'Descending' } + + It "Issue#19912 - Tab completion should not crash" { + $ISS = [initialsessionstate]::CreateDefault() + $Runspace = [runspacefactory]::CreateRunspace($ISS) + $Runspace.Open() + $OldRunspace = [runspace]::DefaultRunspace + try + { + [runspace]::DefaultRunspace = $Runspace + {[System.Management.Automation.CommandCompletion]::CompleteInput('Get-', 3, $null)} | Should -Not -Throw + } + finally + { + [runspace]::DefaultRunspace = $OldRunspace + $Runspace.Dispose() + } + } } From 612857a38c9b84ddbda4aadcaccad2cc82729a74 Mon Sep 17 00:00:00 2001 From: MartinGC94 <42123497+MartinGC94@users.noreply.github.com> Date: Mon, 10 Jul 2023 21:32:21 +0200 Subject: [PATCH 631/779] Remove unused string completion code (#19879) --- .../CommandCompletion/CompletionAnalysis.cs | 134 ++++-------------- 1 file changed, 28 insertions(+), 106 deletions(-) diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs index 4f02f251623..bc18ed21979 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs @@ -387,7 +387,7 @@ internal List GetResults(PowerShell powerShell, out int replac completionContext.ExecutionContext.LanguageMode = PSLanguageMode.ConstrainedLanguage; } - return GetResultHelper(completionContext, out replacementIndex, out replacementLength, false); + return GetResultHelper(completionContext, out replacementIndex, out replacementLength); } finally { @@ -398,7 +398,7 @@ internal List GetResults(PowerShell powerShell, out int replac } } - internal List GetResultHelper(CompletionContext completionContext, out int replacementIndex, out int replacementLength, bool isQuotedString) + internal List GetResultHelper(CompletionContext completionContext, out int replacementIndex, out int replacementLength) { replacementIndex = -1; replacementLength = -1; @@ -434,16 +434,12 @@ internal List GetResultHelper(CompletionContext completionCont return result; } - result = GetResultForIdentifier(completionContext, ref replacementIndex, ref replacementLength, isQuotedString); + result = GetResultForIdentifier(completionContext, ref replacementIndex, ref replacementLength); } break; case TokenKind.Parameter: - // When it's the content of a quoted string, we only handle variable/member completion - if (isQuotedString) - break; - completionContext.WordToComplete = tokenAtCursor.Text; var cmdAst = lastAst.Parent as CommandAst; if (lastAst is StringConstantExpressionAst && cmdAst != null && cmdAst.CommandElements.Count == 1) @@ -491,10 +487,6 @@ internal List GetResultHelper(CompletionContext completionCont break; case TokenKind.Comment: - // When it's the content of a quoted string, we only handle variable/member completion - if (isQuotedString) - break; - completionContext.WordToComplete = tokenAtCursor.Text; result = CompletionCompleters.CompleteComment(completionContext, ref replacementIndex, ref replacementLength); break; @@ -527,7 +519,7 @@ internal List GetResultHelper(CompletionContext completionCont return CompletionCompleters.CompleteIndexExpression(completionContext, indexExpressionAst.Target); } - result = GetResultForString(completionContext, ref replacementIndex, ref replacementLength, isQuotedString); + result = GetResultForString(completionContext, ref replacementIndex, ref replacementLength); break; case TokenKind.RBracket: @@ -839,8 +831,7 @@ internal List GetResultHelper(CompletionContext completionCont bool skipAutoCompleteForCommandCall = isCursorLineEmpty && !isLineContinuationBeforeCursor; bool lastAstIsExpressionAst = lastAst is ExpressionAst; - if (!isQuotedString && - !skipAutoCompleteForCommandCall && + if (!skipAutoCompleteForCommandCall && (lastAst is CommandParameterAst || lastAst is CommandAst || (lastAstIsExpressionAst && lastAst.Parent is CommandAst) || (lastAstIsExpressionAst && lastAst.Parent is CommandParameterAst) || @@ -879,7 +870,7 @@ internal List GetResultHelper(CompletionContext completionCont replacementLength = completionContext.ReplacementLength; } } - else if (!isQuotedString) + else { // // Handle completion of empty line within configuration statement @@ -1778,111 +1769,50 @@ private static List GetResultForEnumPropertyValueOfDSCResource return result; } - private List GetResultForString(CompletionContext completionContext, ref int replacementIndex, ref int replacementLength, bool isQuotedString) + private static List GetResultForString(CompletionContext completionContext, ref int replacementIndex, ref int replacementLength) { - // When it's the content of a quoted string, we only handle variable/member completion - if (isQuotedString) { return null; } - - var tokenAtCursor = completionContext.TokenAtCursor; var lastAst = completionContext.RelatedAsts.Last(); - - List result = null; var expandableString = lastAst as ExpandableStringExpressionAst; var constantString = lastAst as StringConstantExpressionAst; if (constantString == null && expandableString == null) { return null; } string strValue = constantString != null ? constantString.Value : expandableString.Value; - StringConstantType strType = constantString != null ? constantString.StringConstantType : expandableString.StringConstantType; - string subInput = null; bool shouldContinue; - result = GetResultForEnumPropertyValueOfDSCResource(completionContext, strValue, ref replacementIndex, ref replacementLength, out shouldContinue); + List result = GetResultForEnumPropertyValueOfDSCResource(completionContext, strValue, ref replacementIndex, ref replacementLength, out shouldContinue); if (!shouldContinue || (result != null && result.Count > 0)) { return result; } - if (strType == StringConstantType.DoubleQuoted) - { - var match = Regex.Match(strValue, @"(\$[\w\d]+\.[\w\d\*]*)$"); - if (match.Success) - { - subInput = match.Groups[1].Value; - } - else if ((match = Regex.Match(strValue, @"(\[[\w\d\.]+\]::[\w\d\*]*)$")).Success) - { - subInput = match.Groups[1].Value; - } - } + var commandElementAst = lastAst as CommandElementAst; + string wordToComplete = + CompletionCompleters.ConcatenateStringPathArguments(commandElementAst, string.Empty, completionContext); - // Handle variable/member completion - if (subInput != null) + if (wordToComplete != null) { - int stringStartIndex = tokenAtCursor.Extent.StartScriptPosition.Offset; - int cursorIndexInString = _cursorPosition.Offset - stringStartIndex - 1; - if (cursorIndexInString >= strValue.Length) - cursorIndexInString = strValue.Length; - - var analysis = new CompletionAnalysis(_ast, _tokens, _cursorPosition, _options); - var subContext = analysis.CreateCompletionContext(completionContext.TypeInferenceContext); + completionContext.WordToComplete = wordToComplete; - var subResult = analysis.GetResultHelper(subContext, out int subReplaceIndex, out _, true); - - if (subResult != null && subResult.Count > 0) + // Handle scenarios like this: cd 'c:\windows\win' + if (lastAst.Parent is CommandAst || lastAst.Parent is CommandParameterAst) { - result = new List(); - replacementIndex = stringStartIndex + 1 + (cursorIndexInString - subInput.Length); - replacementLength = subInput.Length; - ReadOnlySpan prefix = subInput.AsSpan(0, subReplaceIndex); - - foreach (CompletionResult entry in subResult) - { - string completionText = string.Concat(prefix, entry.CompletionText.AsSpan()); - if (entry.ResultType == CompletionResultType.Property) - { - completionText = TokenKind.DollarParen.Text() + completionText + TokenKind.RParen.Text(); - } - else if (entry.ResultType == CompletionResultType.Method) - { - completionText = TokenKind.DollarParen.Text() + completionText; - } - - completionText += "\""; - result.Add(new CompletionResult(completionText, entry.ListItemText, entry.ResultType, entry.ToolTip)); - } + result = CompletionCompleters.CompleteCommandArgument(completionContext); + replacementIndex = completionContext.ReplacementIndex; + replacementLength = completionContext.ReplacementLength; } - } - else - { - var commandElementAst = lastAst as CommandElementAst; - string wordToComplete = - CompletionCompleters.ConcatenateStringPathArguments(commandElementAst, string.Empty, completionContext); - - if (wordToComplete != null) + // Handle scenarios like this: "c:\wind". Treat the StringLiteral/StringExpandable as path/command + else { - completionContext.WordToComplete = wordToComplete; + // Handle path/commandname completion for quoted string + result = new List(CompletionCompleters.CompleteFilename(completionContext)); - // Handle scenarios like this: cd 'c:\windows\win' - if (lastAst.Parent is CommandAst || lastAst.Parent is CommandParameterAst) + // Try command name completion only if the text contains '-' + if (wordToComplete.Contains('-')) { - result = CompletionCompleters.CompleteCommandArgument(completionContext); - replacementIndex = completionContext.ReplacementIndex; - replacementLength = completionContext.ReplacementLength; - } - // Handle scenarios like this: "c:\wind". Treat the StringLiteral/StringExpandable as path/command - else - { - // Handle path/commandname completion for quoted string - result = new List(CompletionCompleters.CompleteFilename(completionContext)); - - // Try command name completion only if the text contains '-' - if (wordToComplete.Contains('-')) + var commandNameResult = CompletionCompleters.CompleteCommand(completionContext); + if (commandNameResult != null && commandNameResult.Count > 0) { - var commandNameResult = CompletionCompleters.CompleteCommand(completionContext); - if (commandNameResult != null && commandNameResult.Count > 0) - { - result.AddRange(commandNameResult); - } + result.AddRange(commandNameResult); } } } @@ -2000,7 +1930,7 @@ private static List GetResultForIdentifierInConfiguration( return results; } - private static List GetResultForIdentifier(CompletionContext completionContext, ref int replacementIndex, ref int replacementLength, bool isQuotedString) + private static List GetResultForIdentifier(CompletionContext completionContext, ref int replacementIndex, ref int replacementLength) { List result = null; var tokenAtCursor = completionContext.TokenAtCursor; @@ -2148,9 +2078,6 @@ private static List GetResultForIdentifier(CompletionContext c } } - // When it's the content of a quoted string, we only handle variable/member completion - if (isQuotedString) { return result; } - // Handle the StringExpandableToken; var strToken = tokenAtCursor as StringExpandableToken; if (strToken != null && strToken.NestedTokens != null && strConst != null) @@ -2220,8 +2147,6 @@ private static List GetResultForIdentifier(CompletionContext c // When it's the content of a quoted string, we only handle variable/member completion if (isSingleDash) { - if (isQuotedString) { return result; } - var res = CompletionCompleters.CompleteCommandParameter(completionContext); if (res.Count != 0) { @@ -2327,9 +2252,6 @@ private static List GetResultForIdentifier(CompletionContext c } } - // When it's the content of a quoted string, we only handle variable/member completion - if (isQuotedString) { return result; } - bool needFileCompletion = false; if (lastAst.Parent is FileRedirectionAst || CompleteAgainstSwitchFile(lastAst, completionContext.TokenBeforeCursor)) { From 5ec04f1f4eedc578c36d2c4b11ade067de41f2f3 Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Mon, 10 Jul 2023 14:06:34 -0700 Subject: [PATCH 632/779] Publish rpm package for rhel9 (#19750) --- tools/packages.microsoft.com/mapping.json | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/tools/packages.microsoft.com/mapping.json b/tools/packages.microsoft.com/mapping.json index 9ae06c5f1b8..a1ea93f4e03 100644 --- a/tools/packages.microsoft.com/mapping.json +++ b/tools/packages.microsoft.com/mapping.json @@ -14,6 +14,13 @@ ], "PackageFormat": "PACKAGE_NAME-POWERSHELL_RELEASE-1.rh.x86_64.rpm" }, + { + "url": "microsoft-rhel9.0-prod", + "distribution": [ + "stable" + ], + "PackageFormat": "PACKAGE_NAME-POWERSHELL_RELEASE-1.rh.x86_64.rpm" + }, { "url": "microsoft-rhel7.3-prod", "distribution": [ From d9fff5bea998a83754db7d84dfbe18245d7bf2ef Mon Sep 17 00:00:00 2001 From: Sean Wheeler Date: Mon, 10 Jul 2023 16:10:38 -0500 Subject: [PATCH 633/779] Migrate user docs to the PowerShell-Docs repo (#19871) --- .spelling | 13 + docs/DOCSMIGRATION.md | 46 ++- docs/FAQ.md | 96 ++--- docs/learning-powershell/README.md | 127 ------- .../create-powershell-scripts.md | 65 ---- .../debugging-from-commandline.md | 173 --------- .../powershell-beginners-guide.md | 339 ------------------ .../working-with-powershell-objects.md | 125 ------- 8 files changed, 99 insertions(+), 885 deletions(-) delete mode 100644 docs/learning-powershell/README.md delete mode 100644 docs/learning-powershell/create-powershell-scripts.md delete mode 100644 docs/learning-powershell/debugging-from-commandline.md delete mode 100644 docs/learning-powershell/powershell-beginners-guide.md delete mode 100644 docs/learning-powershell/working-with-powershell-objects.md diff --git a/.spelling b/.spelling index 792ac487e02..0e2e0dde586 100644 --- a/.spelling +++ b/.spelling @@ -1338,6 +1338,13 @@ microsoft.extensions.objectpool microsoft.codeanalysis.analyzers benchmarkdotnet winforms +MicrosoftDocs +about_Scripts +debugging-from-commandline +about_Object_Creation +about_Functions_Advanced +Microsoft.PowerShell.SDK +NuGet.org. - CHANGELOG.md aavdberg asrosent @@ -1740,3 +1747,9 @@ preview.3.23178.7 PoolNames techguy16 sdwheeler +MicrosoftDocs +about_Scripts +about_Object_Creation +about_Functions_Advanced +Microsoft.PowerShell.SDK +NuGet.org. diff --git a/docs/DOCSMIGRATION.md b/docs/DOCSMIGRATION.md index 43c1b23dfe4..9b2003be5a6 100644 --- a/docs/DOCSMIGRATION.md +++ b/docs/DOCSMIGRATION.md @@ -1,20 +1,38 @@ # Documentation Migration -The docs folder in this repo contains a lot of documentation about the PowerShell source code and build environment. -It also has contained documentation about installing and using PowerShell. -That documentation belongs in the [PowerShell/PowerShell-Docs](https://github.com/PowerShell/PowerShell-Docs) repo. +The docs folder in this repository contains documentation about the PowerShell source code and build +environment. -We are in the process of migrating the user-focused articles to the docs repo. -This file records which files have been migrated. +User-focused documentation has been moved to the [MicrosoftDocs/PowerShell-Docs][01] repository. -## 2018-05-18 +The files from the `learning-powershell` folder have been removed from this repository. This list +provides links to suitable replacements. -The following files have been moved to the PowerShell/PowerShell-Docs repo. +- **create-powershell-scripts.md** + - [about_Scripts][06] +- **debugging-from-commandline.md** + - [about_Debuggers][04] +- **powershell-beginners-guide.md** + - [PowerShell 101][09] +- **README.md** + - [Install PowerShell on Windows, Linux, and macOS][07] + - [Using Visual Studio Code (VS Code)][11] + - [Pester Guides][02] + - [Writing Pester Tests Guidelines][03] + - [PowerShell learning resources][08] +- **working-with-powershell-objects.md** + - [about_Object_Creation][05] + - [Crescendo overview][10] -| Original file location | New location in PowerShell/PowerShell-Docs | -|--------------------------------|----------------------------------------------------------------------------| -| `docs/installation/linux.md` | `reference/docs-conceptual/setup/Installing-PowerShell-Core-on-Linux.md` | -| `docs/installation/macos.md` | `reference/docs-conceptual/setup/Installing-PowerShell-Core-on-macOS.md` | -| `docs/installation/windows.md` | `reference/docs-conceptual/setup/Installing-PowerShell-Core-on-Windows.md` | -| `docs/BREAKINGCHANGES.md` | `reference/docs-conceptual/whats-new/breaking-changes-ps6.md` | -| `docs/KNOWNISSUES.md` | `reference/docs-conceptual/whats-new/known-issues-ps6.md` | + +[01]: https://github.com/MicrosoftDocs/PowerShell-Docs +[02]: https://github.com/pester/Pester +[03]: https://github.com/PowerShell/PowerShell/blob/master/docs/testing-guidelines/WritingPesterTests.md +[04]: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_debuggers +[05]: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_object_creation +[06]: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_scripts +[07]: https://learn.microsoft.com/powershell/scripting/install/installing-powershell +[08]: https://learn.microsoft.com/powershell/scripting/learn/more-powershell-learning +[09]: https://learn.microsoft.com/powershell/scripting/learn/ps101/00-introduction +[10]: https://learn.microsoft.com/powershell/utility-modules/crescendo/overview?view=ps-modules +[11]: https://learn.microsoft.com/powershell/scripting/dev-cross-plat/vscode/using-vscode diff --git a/docs/FAQ.md b/docs/FAQ.md index 2de12360485..92ed78334f3 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -2,89 +2,86 @@ ## Where can I learn PowerShell's syntax? -[SS64.com](https://ss64.com/ps/syntax.html) is a good resource. -[Microsoft Docs](https://docs.microsoft.com/powershell/scripting/overview) is another excellent resource. +- [What is PowerShell?][12] +- [Discover PowerShell][09] +- [PowerShell 101][11] +- [PowerShell learning resources][10] ## What are the best practices and style? -The [PoshCode][] unofficial guide is our reference. - -[PoshCode]: https://github.com/PoshCode/PowerShellPracticeAndStyle +The [PoshCode][03] unofficial guide is our reference. ## What are PowerShell's scoping rules? - Variables are created in your current scope unless explicitly indicated. - Variables are visible in a child scope unless explicitly indicated. -- Variables created in a child scope are not visible to a parent unless - explicitly indicated. +- Variables created in a child scope are not visible to a parent unless explicitly indicated. - Variables may be placed explicitly in a scope. ### Things that create a scope -- [functions](https://ss64.com/ps/syntax-functions.html) -- [call operator](https://ss64.com/ps/call.html) (`& { }`) -- [script invocations](https://ss64.com/ps/syntax-run.html) +- [about_Functions_Advanced][04] +- [about Operators - Call operator][06] (`& { }`) +- [about Scopes][08] ### Things that operate in the current scope -- [source operator](https://ss64.com/ps/source.html) (`. { }`) -- [statements](https://ss64.com/ps/statements.html) (`if .. else`, `for`, `switch`, etc.) +- [about Operators - Dot source operator][07] (`. { }`) +- [about Language Keywords][05] (`if .. else`, `for`, `switch`, etc.) ## Why didn't an error throw an exception? -Error handling in PowerShell is a bit weird, as not all errors result in catchable exceptions by default. -Setting `$ErrorActionPreference = 'Stop'` will likely do what you want; -that is, cause non-terminating errors instead to terminate. -Read [An Introduction To Error Handling in PowerShell][error] for more information. - -[error]: https://gist.github.com/TravisEz13/9bb811c63b88501f3beec803040a9996 +Error handling in PowerShell is unique, as not all errors result in catchable exceptions by default. +Setting `$ErrorActionPreference = 'Stop'` will likely do what you want; that is, cause +non-terminating errors instead to terminate. Read the [GitHub issue][02] for more information. ## Where do I get the PowerShell Core SDK package? -The SDK NuGet package `Microsoft.PowerShell.SDK` is provided for developers to write .NET Core C# code targeting PowerShell Core. -PowerShell NuGet packages for releases starting from v6.0.0-alpha.9 will be published to the [powershell-core][] myget feed. +The SDK NuGet package **Microsoft.PowerShell.SDK** is provided for developers to write C# code +targeting PowerShell. PowerShell NuGet packages are published to [Microsoft.PowerShell.SDK][13] on +NuGet.org. -To use the `Microsoft.PowerShell.SDK` NuGet package, declare `PackageReference` tags in your `.csproj` file as follows: +To use the `Microsoft.PowerShell.SDK` NuGet package, declare `PackageReference` tags in your +`.csproj` file as follows: ```xml - - - + + + ``` -[powershell-core]: https://powershell.myget.org/gallery/powershell-core - ## Why did my build fail? -There are few common issues with the build. -The easiest way to resolve most issues with the build is to run `Start-PSBuild -Clean`. +There are few common issues with the build. The easiest way to resolve most issues with the build is +to run `Start-PSBuild -Clean`. ### Dependency changed -If package dependencies were changed in any `project.json`, you need to manually -run `dotnet restore` to update your local dependency graphs. -`Start-PSBuild -Restore` can automatically do this. +If package dependencies were changed in any `project.json`, you need to manually run +`dotnet restore` to update your local dependency graphs. `Start-PSBuild -Restore` can automatically +do this. ### Resource changed -`Start-PSBuild` automatically calls `Start-ResGen` on the very first run. -On subsequent runs, you may need to explicitly use `Start-PSBuild -ResGen` command. +`Start-PSBuild` automatically calls `Start-ResGen` on the very first run. On subsequent runs, you +may need to explicitly use `Start-PSBuild -ResGen` command. Try it, when you see compilation error about *strings. -[More details](dev-process/resx-files.md) about resource. +[More details][01] about resource. ### TypeGen -Similar to `-ResGen` parameter, there is `-TypeGen` parameter that triggers regeneration of type catalog. +Similar to `-ResGen` parameter, there is `-TypeGen` parameter that triggers regeneration of type +catalog. ## Why did `Start-PSBuild` tell me to update `dotnet`? -We depend on the latest version of the .NET CLI, as we use the output of `dotnet ---info` to determine the current runtime identifier. -Without this information, our build function can't know where `dotnet` is going to place the build artifacts. +We depend on the latest version of the .NET CLI, as we use the output of `dotnet --info` to +determine the current runtime identifier. Without this information, our build function can't know +where `dotnet` is going to place the build artifacts. You can automatically install this using `Start-PSBootstrap`. **However, you must first manually uninstall other versions of the CLI.** @@ -98,7 +95,22 @@ If you have installed by using any of the following means: You *must* manually uninstall it. -Additionally, if you've just unzipped their binary drops (or used their obtain -scripts, which do essentially the same thing), you must manually delete the -folder, as the .NET CLI team re-engineered how their binaries are setup, such -that new packages' binaries get stomped on by old packages' binaries. +Additionally, if you've just unzipped their binary drops (or used their obtain scripts, which do +essentially the same thing), you must manually delete the folder, as the .NET CLI team re-engineered +how their binaries are setup, such that new packages' binaries get stomped on by old packages' +binaries. + + +[01]: dev-process/resx-files.md +[02]: https://github.com/MicrosoftDocs/PowerShell-Docs/issues/1583 +[03]: https://github.com/PoshCode/PowerShellPracticeAndStyle +[04]: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_functions_advanced +[05]: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_language_keywords +[06]: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_operators#call-operator- +[07]: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_operators#dot-sourcing-operator- +[08]: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_scopes +[09]: https://learn.microsoft.com/powershell/scripting/discover-powershell +[10]: https://learn.microsoft.com/powershell/scripting/learn/more-powershell-learning +[11]: https://learn.microsoft.com/powershell/scripting/learn/ps101/00-introduction +[12]: https://learn.microsoft.com/powershell/scripting/overview +[13]: https://www.nuget.org/packages/Microsoft.PowerShell.SDK diff --git a/docs/learning-powershell/README.md b/docs/learning-powershell/README.md deleted file mode 100644 index 32a7dfb052f..00000000000 --- a/docs/learning-powershell/README.md +++ /dev/null @@ -1,127 +0,0 @@ -# Learning PowerShell - -Whether you're a Developer, a DevOps or an IT Professional, this doc will help you getting started with PowerShell. -In this document we'll cover the following: -Installing PowerShell, samples walkthrough, PowerShell editor, debugger, testing tools and a map book for experienced bash users to get started with PowerShell faster. - -The exercises in this document are intended to give you a solid foundation in how to use PowerShell. -You won't be a PowerShell guru at the end of reading this material but you will be well on your way with the right set of knowledge to start using PowerShell. - -If you have 30 minutes now, let’s try it. - -## Installing PowerShell - -First you need to set up your computer working environment if you have not done so. -Choose the platform below and follow the instructions. -At the end of this exercise, you should be able to launch the PowerShell session. - -- Get PowerShell by installing package - * [PowerShell on Linux][inst-linux] - * [PowerShell on macOS][inst-macos] - * [PowerShell on Windows][inst-win] - - For this tutorial, you do not need to install PowerShell if you are running on Windows. - You can launch PowerShell console by pressing Windows key, typing PowerShell, and clicking on Windows PowerShell. - However if you want to try out the latest PowerShell, follow the [PowerShell on Windows][inst-win]. - -- Alternatively you can get the PowerShell by [building it][build-powershell] - -[build-powershell]:../../README.md#building-the-repository -[inst-linux]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-linux -[inst-win]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-windows -[inst-macos]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-macos - -## Getting Started with PowerShell - -PowerShell commands follow a Verb-Noun semantic with a set of parameters. -It's easy to learn and use PowerShell. -For example, `Get-Process` will display all the running processes on your system. -Let's walk through with a few examples from the [PowerShell Beginner's Guide](powershell-beginners-guide.md). - -Now you have learned the basics of PowerShell. -Please continue reading if you want to do some development work in PowerShell. - -### PowerShell Editor - -In this section, you will create a PowerShell script using a text editor. -You can use your favorite editor to write scripts. -We use Visual Studio Code (VS Code) which works on Windows, Linux, and macOS. -Click on the following link to create your first PowerShell script. - -- [Using Visual Studio Code (VS Code)](https://docs.microsoft.com/powershell/scripting/dev-cross-plat/vscode/using-vscode) - -### PowerShell Debugger - -Debugging can help you find bugs and fix problems in your PowerShell scripts. -Click on the link below to learn more about debugging: - -- [Using Visual Studio Code (VS Code)](https://docs.microsoft.com/powershell/scripting/dev-cross-plat/vscode/using-vscode#debugging-with-visual-studio-code) -- [PowerShell Command-line Debugging][cli-debugging] - -[cli-debugging]:./debugging-from-commandline.md - -### PowerShell Testing - -We recommend using Pester testing tool which is initiated by the PowerShell Community for writing test cases. -To use the tool please read [Pester Guides](https://github.com/pester/Pester) and [Writing Pester Tests Guidelines](https://github.com/PowerShell/PowerShell/blob/master/docs/testing-guidelines/WritingPesterTests.md). - -### Map Book for Experienced Bash users - -The table below lists the usage of some basic commands to help you get started on PowerShell faster. -Note that all bash commands should continue working on PowerShell session. - -| Bash | PowerShell | Description -|:--------------------------------|:----------------------------------------|:--------------------- -| ls | dir, Get-ChildItem | List files and folders -| tree | dir -Recurse, Get-ChildItem -Recurse | List all files and folders -| cd | cd, Set-Location | Change directory -| pwd | pwd, $pwd, Get-Location | Show working directory -| clear, Ctrl+L, reset | cls, clear | Clear screen -| mkdir | New-Item -ItemType Directory | Create a new folder -| touch test.txt | New-Item -Path test.txt | Create a new empty file -| cat test1.txt test2.txt | Get-Content test1.txt, test2.txt | Display files contents -| cp ./source.txt ./dest/dest.txt | Copy-Item source.txt dest/dest.txt | Copy a file -| cp -r ./source ./dest | Copy-Item ./source ./dest -Recurse | Recursively copy from one folder to another -| mv ./source.txt ./dest/dest.txt | Move-Item ./source.txt ./dest/dest.txt | Move a file to other folder -| rm test.txt | Remove-Item test.txt | Delete a file -| rm -r <folderName> | Remove-Item <folderName> -Recurse | Delete a folder -| find -name build* | Get-ChildItem build* -Recurse | Find a file or folder starting with 'build' -| grep -Rin "sometext" --include="*.cs" |Get-ChildItem -Recurse -Filter *.cs
    \| Select-String -Pattern "sometext" | Recursively case-insensitive search for text in files -| curl https://github.com | Invoke-RestMethod https://github.com | Transfer data to or from the web - -### Recommended Training and Reading - -- Microsoft Virtual Academy: [Getting Started with PowerShell][getstarted-with-powershell] -- [Why Learn PowerShell][why-learn-powershell] by Ed Wilson -- PowerShell Web Docs: [Basic cookbooks][basic-cookbooks] -- [The Guide to Learning PowerShell][ebook-from-Idera] by Tobias Weltner -- [PowerShell-related Videos][channel9-learn-powershell] on Channel 9 -- [PowerShell Quick Reference Guides][quick-reference] by PowerShellMagazine.com -- [PowerShell Tips][idera-powershell-tips] from Idera -- [PowerShell 5 How-To Videos][script-guy-how-to] by Ed Wilson -- [PowerShell Documentation](https://docs.microsoft.com/powershell) -- [Interactive learning with PSKoans](https://aka.ms/pskoans) - -### Commercial Resources - -- [Windows PowerShell in Action][in-action] by [Bruce Payette](https://github.com/brucepay) -- [Introduction to PowerShell][powershell-intro] from Pluralsight -- [PowerShell Training and Tutorials][lynda-training] from Lynda.com -- [Learn Windows PowerShell in a Month of Lunches][learn-win-powershell] by Don Jones and Jeffrey Hicks -- [Learn PowerShell in a Month of Lunches][learn-powershell] by Travis Plunk (@TravisEz13), - Tyler Leonhardt (@tylerleonhardt), Don Jones, and Jeffery Hicks - -[in-action]: https://www.amazon.com/Windows-PowerShell-Action-Second-Payette/dp/1935182137 -[powershell-intro]: https://www.pluralsight.com/courses/powershell-intro -[lynda-training]: https://www.lynda.com/PowerShell-training-tutorials/5779-0.html -[learn-win-powershell]: https://www.amazon.com/Learn-Windows-PowerShell-Month-Lunches/dp/1617294160 -[learn-powershell]: https://www.manning.com/books/learn-powershell-in-a-month-of-lunches - -[getstarted-with-powershell]: https://channel9.msdn.com/Series/GetStartedPowerShell3 -[why-learn-powershell]: https://blogs.technet.microsoft.com/heyscriptingguy/2014/10/18/weekend-scripter-why-learn-powershell/ -[ebook-from-Idera]:https://www.idera.com/resourcecentral/whitepapers/powershell-ebook -[channel9-learn-powershell]: https://channel9.msdn.com/Search?term=powershell#ch9Search -[idera-powershell-tips]: https://blog.idera.com/database-tools/powershell/powertips/ -[quick-reference]: https://www.powershellmagazine.com/2014/04/24/windows-powershell-4-0-and-other-quick-reference-guides/ -[script-guy-how-to]:https://blogs.technet.microsoft.com/tommypatterson/2015/09/04/ed-wilsons-powershell5-videos-now-on-channel9-2/ -[basic-cookbooks]:https://docs.microsoft.com/powershell/scripting/samples/sample-scripts-for-administration diff --git a/docs/learning-powershell/create-powershell-scripts.md b/docs/learning-powershell/create-powershell-scripts.md deleted file mode 100644 index 5f93eb97ab3..00000000000 --- a/docs/learning-powershell/create-powershell-scripts.md +++ /dev/null @@ -1,65 +0,0 @@ -# How to Create and Run PowerShell Scripts - -You can combine a series of commands in a text file and save it with the file extension '.ps1', and the file will become a PowerShell script. -This would begin by opening your favorite text editor and pasting in the following example. - -```powershell -# Script to return current IPv4 addresses on a Linux or MacOS host -$ipInfo = ifconfig | Select-String 'inet' -$ipInfo = [regex]::matches($ipInfo,"addr:\b(?:\d{1,3}\.){3}\d{1,3}\b") | ForEach-Object value -foreach ($ip in $ipInfo) -{ - $ip.Replace('addr:','') -} -``` - -Then save the file to something memorable, such as .\NetIP.ps1. -In the future when you need to get the IP addresses for the node, you can simplify this task by executing the script. - -```powershell -.\NetIP.ps1 -10.0.0.1 -127.0.0.1 -``` - -You can accomplish this same task on Windows. - -```powershell -# One line script to return current IPv4 addresses on a Windows host -Get-NetIPAddress | Where-Object {$_.AddressFamily -eq 'IPv4'} | ForEach-Object IPAddress -``` - -As before, save the file as .\NetIP.ps1 and execute within a PowerShell environment. -Note: If you are using Windows, make sure you set the PowerShell's execution policy to "RemoteSigned" in this case. -See [Running PowerShell Scripts Is as Easy as 1-2-3][run-ps] for more details. - -```powershell -NetIP.ps1 -127.0.0.1 -10.0.0.1 -``` - -## Creating a script that can accomplish the same task on multiple operating systems - -If you would like to author one script that will return the IP address across Linux, MacOS, or Windows, you could accomplish this using an IF statement. - -```powershell -# Script to return current IPv4 addresses for Linux, MacOS, or Windows -$IP = if ($IsLinux -or $IsMacOS) -{ - $ipInfo = ifconfig | Select-String 'inet' - $ipInfo = [regex]::matches($ipInfo,"addr:\b(?:\d{1,3}\.){3}\d{1,3}\b") | ForEach-Object value - foreach ($ip in $ipInfo) { - $ip.Replace('addr:','') - } -} -else -{ - Get-NetIPAddress | Where-Object {$_.AddressFamily -eq 'IPv4'} | ForEach-Object IPAddress -} - -# Remove loopback address from output regardless of platform -$IP | Where-Object {$_ -ne '127.0.0.1'} -``` - -[run-ps]:https://www.itprotoday.com/powershell/running-powershell-scripts-easy-1-2-3 diff --git a/docs/learning-powershell/debugging-from-commandline.md b/docs/learning-powershell/debugging-from-commandline.md deleted file mode 100644 index 1aaab218256..00000000000 --- a/docs/learning-powershell/debugging-from-commandline.md +++ /dev/null @@ -1,173 +0,0 @@ -# Debugging in PowerShell Command-line - -As we know, we can debug PowerShell code via GUI tools like [Visual Studio Code](https://docs.microsoft.com/powershell/scripting/dev-cross-plat/vscode/using-vscode#debugging-with-visual-studio-code). In addition, we can -directly perform debugging within the PowerShell command-line session by using the PowerShell debugger cmdlets. This document demonstrates how to use the cmdlets for the PowerShell command-line debugging. We will cover the following topics: -setting a debug breakpoint on a line of code and on a variable. - -Let's use the following code snippet as our sample script. - -```powershell -# Convert Fahrenheit to Celsius -function ConvertFahrenheitToCelsius([double] $fahrenheit) -{ -$celsius = $fahrenheit - 32 -$celsius = $celsius / 1.8 -$celsius -} - -$fahrenheit = Read-Host 'Input a temperature in Fahrenheit' -$result =[int](ConvertFahrenheitToCelsius($fahrenheit)) -Write-Host "$result Celsius" -``` - -## Setting a Breakpoint on a Line - -- Open a [PowerShell editor](README.md#powershell-editor) -- Save the above code snippet to a file. For example, "test.ps1" -- Go to your command-line PowerShell -- Clear existing breakpoints if any - -```powershell - PS /home/jen/debug>Get-PSBreakpoint | Remove-PSBreakpoint -``` - -- Use **Set-PSBreakpoint** cmdlet to set a debug breakpoint. In this case, we will set it to line 5 - -```powershell -PS /home/jen/debug>Set-PSBreakpoint -Line 5 -Script ./test.ps1 - -ID Script Line Command Variable Action --- ------ ---- ------- -------- ------ - 0 test.ps1 5 -``` - -- Run the script "test.ps1". As we have set a breakpoint, it is expected the program will break into the debugger at the line 5. - -```powershell - -PS /home/jen/debug> ./test.ps1 -Input a temperature in Fahrenheit: 80 -Hit Line breakpoint on '/home/jen/debug/test.ps1:5' - -At /home/jen/debug/test.ps1:5 char:1 -+ $celsius = $celsius / 1.8 -+ ~~~~~~~~~~~~~~~~~~~~~~~~~ -[DBG]: PS /home/jen/debug>> -``` - -- The PowerShell prompt now has the prefix **[DBG]:** as you may have noticed. This means - we have entered into the debug mode. To watch the variables like $celsius, simply type **$celsius** as below. -- To exit from the debugging, type **q** -- To get help for the debugging commands, simply type **?**. The following is an example of debugging output. - -```PowerShell -[DBG]: PS /home/jen/debug>> $celsius -48 -[DBG]: PS /home/jen/debug>> $fahrenheit -80 -[DBG]: PS /home/jen/debug>> ? - - s, stepInto Single step (step into functions, scripts, etc.) - v, stepOver Step to next statement (step over functions, scripts, etc.) - o, stepOut Step out of the current function, script, etc. - - c, continue Continue operation - q, quit Stop operation and exit the debugger - d, detach Continue operation and detach the debugger. - - k, Get-PSCallStack Display call stack - - l, list List source code for the current script. - Use "list" to start from the current line, "list " - to start from line , and "list " to list - lines starting from line - - Repeat last command if it was stepInto, stepOver or list - - ?, h displays this help message. - - -For instructions about how to customize your debugger prompt, type "help about_prompt". - -[DBG]: PS /home/jen/debug>> s -At PS /home/jen/debug/test.ps1:6 char:1 -+ $celsius -+ ~~~~~~~~ -[DBG]: PS /home/jen/debug>> $celsius -26.6666666666667 -[DBG]: PS /home/jen/debug>> $fahrenheit -80 - -[DBG]: PS /home/jen/debug>> q -PS /home/jen/debug> - -``` - -## Setting a Breakpoint on a Variable -- Clear existing breakpoints if there are any - -```powershell - PS /home/jen/debug>Get-PSBreakpoint | Remove-PSBreakpoint - ``` - -- Use **Set-PSBreakpoint** cmdlet to set a debug breakpoint. In this case, we set it to line 5 - -```powershell - - PS /home/jen/debug>Set-PSBreakpoint -Variable "celsius" -Mode write -Script ./test.ps1 - -``` - -- Run the script "test.ps1" - - Once hit the debug breakpoint, we can type **l** to list the source code that debugger is currently executing. As we can see line 3 has an asterisk at the front, meaning that's the line the program is currently executing and broke into the debugger as illustrated below. -- Type **q** to exit from the debugging mode. The following is an example of debugging output. - -```powershell -./test.ps1 -Input a temperature in Fahrenheit: 80 -Hit Variable breakpoint on '/home/jen/debug/test.ps1:$celsius' (Write access) - -At /home/jen/debug/test.ps1:3 char:1 -+ $celsius = $fahrenheit - 32 -+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~ -[DBG]: PS /home/jen/debug>> l - - - 1: function ConvertFahrenheitToCelsius([double] $fahrenheit) - 2: { - 3:* $celsius = $fahrenheit - 32 - 4: $celsius = $celsius / 1.8 - 5: $celsius - 6: } - 7: - 8: $fahrenheit = Read-Host 'Input a temperature in Fahrenheit' - 9: $result =[int](ConvertFahrenheitToCelsius($fahrenheit)) - 10: Write-Host "$result Celsius" - - -[DBG]: PS /home/jen/debug>> $celsius -48 -[DBG]: PS /home/jen/debug>> v -At /home/jen/debug/test.ps1:4 char:1 -+ $celsius = $celsius / 1.8 -+ ~~~~~~~~~~~~~~~~~~~~~~~~~ -[DBG]: PS /home/jen/debug>> v -Hit Variable breakpoint on '/home/jen/debug/test.ps1:$celsius' (Write access) - -At /home/jen/debug/test.ps1:4 char:1 -+ $celsius = $celsius / 1.8 -+ ~~~~~~~~~~~~~~~~~~~~~~~~~ -[DBG]: PS /home/jen/debug>> $celsius -26.6666666666667 -[DBG]: PS /home/jen/debug>> q -PS /home/jen/debug> - -``` - -Now you know the basics of the PowerShell debugging from PowerShell command-line. For further learning, read the following articles. - -## More Reading - -- [about_Debuggers](https://docs.microsoft.com/powershell/module/microsoft.powershell.core/about/about_debuggers) -- [PowerShell Debugging](https://blogs.technet.microsoft.com/heyscriptingguy/tag/debugging/) diff --git a/docs/learning-powershell/powershell-beginners-guide.md b/docs/learning-powershell/powershell-beginners-guide.md deleted file mode 100644 index 1f84722c8ab..00000000000 --- a/docs/learning-powershell/powershell-beginners-guide.md +++ /dev/null @@ -1,339 +0,0 @@ -# PowerShell Beginner’s Guide - -If you are new to PowerShell, this document will walk you through a few examples to give you some basic ideas of PowerShell. -We recommend that you open a PowerShell console/session and type along with the instructions in this document to get most out of this exercise. - -## Launch PowerShell Console/Session - -First you need to launch a PowerShell session by following the [Installing PowerShell Guide](./README.md#installing-powershell). - -## Getting Familiar with PowerShell Commands - -In this section, you will learn how to - -- create a file, delete a file and change file directory -- discover what version of PowerShell you are currently using -- exit a PowerShell session -- get help if you needed -- find syntax of PowerShell cmdlets -- and more - -As mentioned above, PowerShell commands are designed to have Verb-Noun structure, for instance `Get-Process`, `Set-Location`, `Clear-Host`, etc. -Let’s exercise some of the basic PowerShell commands, also known as **cmdlets**. - -Please note that we will use the PowerShell prompt sign **PS />** as it appears on Linux in the following examples. -It is shown as `PS C:\>` on Windows. - -1. `Get-Process`: Gets the processes that are running on the local computer or a remote computer. - - By default, you will get data back similar to the following: - - ```powershell - PS /> Get-Process - - Handles NPM(K) PM(K) WS(K) CPU(s) Id ProcessName - ------- ------ ----- ----- ------ -- ----------- - - - - 1 0.012 12 bash - - - - 21 20.220 449 powershell - - - - 11 61.630 8620 code - - - - 74 403.150 1209 firefox - - … - ``` - - Only interested in the instance of Firefox process that is running on your computer? - - Try this: - - ```powershell - PS /> Get-Process -Name firefox - - Handles NPM(K) PM(K) WS(K) CPU(s) Id ProcessName - ------- ------ ----- ----- ------ -- ----------- - - - - 74 403.150 1209 firefox - - ``` - - Want to get back more than one process? - Then just specify process names and separate them with commas. - - ```powershell - PS /> Get-Process -Name firefox, powershell - Handles NPM(K) PM(K) WS(K) CPU(s) Id ProcessName - ------- ------ ----- ----- ------ -- ----------- - - - - 74 403.150 1209 firefox - - - - 21 20.220 449 powershell - - ``` - -1. `Clear-Host`: Clears the display in the host program. - - ```powershell - PS /> Get-Process - PS /> Clear-Host - ``` - - Type too much just for clearing the screen? - - Here is how the alias can help. - -1. `Get-Alias`: Gets the aliases for the current session. - - ```powershell - Get-Alias - - CommandType Name - ----------- ---- - … - - Alias cd -> Set-Location - Alias cls -> Clear-Host - Alias clear -> Clear-Host - Alias copy -> Copy-Item - Alias dir -> Get-ChildItem - Alias gc -> Get-Content - Alias gmo -> Get-Module - Alias ri -> Remove-Item - Alias type -> Get-Content - … - ``` - - As you can see `cls` or `clear` is an alias of `Clear-Host`. - - Now try it: - - ```powershell - PS /> Get-Process - PS /> cls - ``` - -1. `cd -> Set-Location`: Sets the current working location to a specified location. - - ```powershell - PS /> Set-Location /home - PS /home> - ``` - -1. `dir -> Get-ChildItem`: Gets the items and child items in one or more specified locations. - - ```powershell - # Get all files under the current directory: - PS /> Get-ChildItem - - # Get all files under the current directory as well as its subdirectories: - PS /> cd $home - PS /home/jen> dir -Recurse - - # List all files with "txt" file extension. - PS /> cd $home - PS /home/jen> dir –Path *.txt -Recurse - ``` - -1. `New-Item`: Creates a new item. - - ```powershell - # An empty file is created if you type the following: - PS /home/jen> New-Item -Path ./test.txt - - - Directory: /home/jen - - - Mode LastWriteTime Length Name - ---- ------------- ------ ---- - -a---- 7/7/2016 7:17 PM 0 test.txt - ``` - - You can use the `-Value` parameter to add some data to your file. - - For example, the following command adds the phrase `Hello world!` as a file content to the `test.txt`. - - Because the test.txt file exists already, we use `-Force` parameter to replace the existing content. - - ```powershell - PS /home/jen> New-Item -Path ./test.txt -Value "Hello world!" -Force - - Directory: /home/jen - - - Mode LastWriteTime Length Name - ---- ------------- ------ ---- - -a---- 7/7/2016 7:19 PM 24 test.txt - - ``` - - There are other ways to add some data to a file. - - For example, you can use `Set-Content` to set the file contents: - - ```powershell - PS /home/jen>Set-Content -Path ./test.txt -Value "Hello world again!" - ``` - - Or simply use `>` as below: - - ```powershell - # create an empty file - "" > test.txt - - # set "Hello world!" as content of test.txt file - "Hello world!!!" > test.txt - - ``` - - The pound sign `#` above is used for comments in PowerShell. - -1. `type -> Get-Content`: Gets the content of the item at the specified location. - - ```powershell - PS /home/jen> Get-Content -Path ./test.txt - PS /home/jen> type -Path ./test.txt - - Hello world again! - ``` - -1. `del -> Remove-Item`: Deletes the specified items. - - This cmdlet will delete the file `/home/jen/test.txt`: - - ```powershell - PS /home/jen> Remove-Item ./test.txt - ``` - -1. `$PSVersionTable`: Displays the version of PowerShell you are currently using. - - Type `$PSVersionTable` in your PowerShell session, you will see something like below. - "PSVersion" indicates the PowerShell version that you are using. - - ```powershell - Name Value - ---- ----- - PSVersion 6.0.0-alpha - PSEdition Core - PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...} - BuildVersion 3.0.0.0 - GitCommitId v6.0.0-alpha.12 - CLRVersion - WSManStackVersion 3.0 - PSRemotingProtocolVersion 2.3 - SerializationVersion 1.1.0.1 - - ``` - -1. `Exit`: To exit the PowerShell session, type `exit`. - - ```powershell - exit - ``` - -## Need Help? - -The most important command in PowerShell is possibly the `Get-Help`, which allows you to quickly learn PowerShell without having to search around the internet. - -The `Get-Help` cmdlet also shows you how PowerShell commands work with examples. - -It shows the syntax and other technical information of the `Get-Process` cmdlet. - -```powershell -PS /> Get-Help -Name Get-Process -``` - -It displays the examples how to use the `Get-Process` cmdlet. - -```powershell -PS />Get-Help -Name Get-Process -Examples -``` - -If you use **-Full** parameter, for example, `Get-Help -Name Get-Process -Full`, it will display more technical information. - -## Discover Commands Available on Your System - -You want to discover what PowerShell cmdlets available on your system? Just run `Get-Command` as below: - -```powershell -PS /> Get-Command -``` - -If you want to know whether a particular cmdlet exists on your system, you can do something like below: - -```powershell -PS /> Get-Command Get-Process -``` - -If you want to know the syntax of `Get-Process` cmdlet, type: - -```powershell -PS /> Get-Command Get-Process -Syntax -``` - -If you want to know how to use the `Get-Process`, type: - -```powershell -PS /> Get-Help Get-Process -Example -``` - -## PowerShell Pipeline `|` - -Sometimes when you run Get-ChildItem or "dir", you want to get a list of files and folders in a descending order. -To achieve that, type: - -```powershell -PS /home/jen> dir | Sort-Object -Descending -``` - -Say you want to get the largest file in a directory - -```powershell -PS /home/jen> dir | Sort-Object -Property Length -Descending | Select-Object -First 1 - - - Directory: /home/jen - - -Mode LastWriteTime Length Name ----- ------------- ------ ---- --a---- 5/16/2016 1:15 PM 32972 test.log - -``` - -## How to Create and Run PowerShell scripts - -You can use Visual Studio Code or your favorite editor to create a PowerShell script and save it with a `.ps1` file extension. -For more details, see [Create and Run PowerShell Script Guide][create-run-script] - -## Recommended Training and Reading - -- Video: [Get Started with PowerShell][remoting] from Channel9 -- [eBooks from PowerShell.org](https://leanpub.com/u/devopscollective) -- [eBooks List][ebook-list] by Martin Schvartzman -- [Tutorial from MVP][tutorial] -- Script Guy blog: [The best way to Learn PowerShell][to-learn] -- [Understanding PowerShell Module][ps-module] -- [How and When to Create PowerShell Module][create-ps-module] by Adam Bertram -- Video: [PowerShell Remoting in Depth][in-depth] from Channel9 -- [PowerShell Basics: Remote Management][remote-mgmt] from ITPro -- [Running Remote Commands][remote-commands] from PowerShell Web Docs -- [Samples for Writing a PowerShell Script Module][examples-ps-module] -- [Writing a PowerShell module in C#][writing-ps-module] -- [Examples of Cmdlets Code][sample-code] - -## Commercial Resources - -- [Windows PowerShell in Action][in-action] by Bruce Payette -- [Windows PowerShell Cookbook][cookbook] by Lee Holmes - -[in-action]: https://www.amazon.com/Windows-PowerShell-Action-Bruce-Payette/dp/1633430294 -[cookbook]: http://shop.oreilly.com/product/9780596801519.do -[ebook-list]: https://martin77s.wordpress.com/2014/05/26/free-powershell-ebooks/ -[tutorial]: https://www.computerperformance.co.uk/powershell/index-13/ -[to-learn]:https://blogs.technet.microsoft.com/heyscriptingguy/2015/01/04/weekend-scripter-the-best-ways-to-learn-powershell/ -[ps-module]:https://docs.microsoft.com/powershell/scripting/developer/module/understanding-a-windows-powershell-module -[create-ps-module]:https://www.business.com/articles/powershell-modules/ -[remoting]:https://channel9.msdn.com/Series/GetStartedPowerShell3/06 -[in-depth]: https://docs.microsoft.com/en-us/events/mms-2012/sv-b406 -[remote-mgmt]:https://www.itprotoday.com/powershell/powershell-basics-remote-management -[remote-commands]:https://docs.microsoft.com/powershell/scripting/learn/remoting/running-remote-commands -[examples-ps-module]:https://docs.microsoft.com/powershell/scripting/developer/module/how-to-write-a-powershell-script-module -[writing-ps-module]:https://www.powershellmagazine.com/2014/03/18/writing-a-powershell-module-in-c-part-1-the-basics/ -[sample-code]:https://docs.microsoft.com/powershell/scripting/developer/cmdlet/examples-of-cmdlet-code -[create-run-script]:./create-powershell-scripts.md diff --git a/docs/learning-powershell/working-with-powershell-objects.md b/docs/learning-powershell/working-with-powershell-objects.md deleted file mode 100644 index ab127483cfe..00000000000 --- a/docs/learning-powershell/working-with-powershell-objects.md +++ /dev/null @@ -1,125 +0,0 @@ -# Working with PowerShell Objects - -When cmdlets are executed in PowerShell, the output is an Object, as opposed to only returning text. -This provides the ability to store information as properties. -As a result, handling large amounts of data and getting only specific properties is a trivial task. - -As a simple example, the following function retrieves information about storage Devices on a Linux or MacOS operating system platform. -This is accomplished by parsing the output of an existing command, *parted -l* in administrative context, and creating an object from the raw text by using the *New-Object* cmdlet. - -```powershell -function Get-DiskInfo -{ - $disks = sudo parted -l | Select-String "Disk /dev/sd*" -Context 1,0 - $diskinfo = @() - foreach ($disk in $disks) { - $diskline1 = $disk.ToString().Split("`n")[0].ToString().Replace(' Model: ','') - $diskline2 = $disk.ToString().Split("`n")[1].ToString().Replace('> Disk ','') - $i = New-Object psobject -Property @{'Friendly Name' = $diskline1; Device=$diskline2.Split(': ')[0]; 'Total Size'=$diskline2.Split(':')[1]} - $diskinfo += $i - } - $diskinfo -} -``` - -Execute the function and store the results as a variable. -Now retrieve the value of the variable. -The results are formatted as a table with the default view. - -*Note: in this example, the disks are virtual disks in a Microsoft Azure virtual machine.* - -```powershell -PS /home/psuser> $d = Get-DiskInfo -[sudo] password for psuser: -PS /home/psuser> $d - -Friendly Name Total Size Device -------------- ---------- ------ -Msft Virtual Disk (scsi) 31.5GB /dev/sda -Msft Virtual Disk (scsi) 145GB /dev/sdb - -``` - -Passing the variable down the pipeline to *Get-Member* reveals available methods and properties. -This is because the value of *$d* is not just text output. -The value is actually an array of .Net objects with methods and properties. -The properties include Device, Friendly Name, and Total Size. - -```powershell -PS /home/psuser> $d | Get-Member - - - TypeName: System.Management.Automation.PSCustomObject - -Name MemberType Definition ----- ---------- ---------- -Equals Method bool Equals(System.Object obj) -GetHashCode Method int GetHashCode() -GetType Method type GetType() -ToString Method string ToString() -Device NoteProperty string Device=/dev/sda -Friendly Name NoteProperty string Friendly Name=Msft Virtual Disk (scsi) -Total Size NoteProperty string Total Size= 31.5GB -``` - -To confirm, we can call the GetType() method interactively from the console. - -```powershell -PS /home/psuser> $d.GetType() - -IsPublic IsSerial Name BaseType --------- -------- ---- -------- -True True Object[] System.Array -``` - -To index in to the array and return only specific objects, use the square brackets. - -```powershell -PS /home/psuser> $d[0] - -Friendly Name Total Size Device -------------- ---------- ------ -Msft Virtual Disk (scsi) 31.5GB /dev/sda - -PS /home/psuser> $d[0].GetType() - -IsPublic IsSerial Name BaseType --------- -------- ---- -------- -True False PSCustomObject System.Object -``` - -To return a specific property, the property name can be called interactively from the console. - -```powershell -PS /home/psuser> $d.Device -/dev/sda -/dev/sdb -``` - -To output a view of the information other than default, such as a view with only specific properties selected, pass the value to the *Select-Object* cmdlet. - -```powershell -PS /home/psuser> $d | Select-Object Device, 'Total Size' - -Device Total Size ------- ---------- -/dev/sda 31.5GB -/dev/sdb 145GB -``` - -Finally, the example below demonstrates use of the *ForEach-Object* cmdlet to iterate through the array and manipulate the value of a specific property of each object. -In this case the Total Size property, which was given in Gigabytes, is changed to Megabytes. -Alternatively, index in to a position in the array as shown below in the third example. - -```powershell -PS /home/psuser> $d | ForEach-Object 'Total Size' - 31.5GB - 145GB - -PS /home/psuser> $d | ForEach-Object {$_.'Total Size' / 1MB} -32256 -148480 - -PS /home/psuser> $d[1].'Total Size' / 1MB -148480 -``` From ac87d2ae0e5bc1778ffa3dfae4269aff08cbd5e4 Mon Sep 17 00:00:00 2001 From: MartinGC94 <42123497+MartinGC94@users.noreply.github.com> Date: Tue, 11 Jul 2023 02:15:05 +0200 Subject: [PATCH 634/779] Add completion for variables assigned by the `Data` statement (#19831) --- .../CommandCompletion/CompletionCompleters.cs | 15 +++++++++++++++ .../Host/TabCompletion/TabCompletion.Tests.ps1 | 6 ++++++ 2 files changed, 21 insertions(+) diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs index 9dec8bcb3a5..e4fb1044858 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs @@ -5656,6 +5656,21 @@ public override AstVisitAction VisitScriptBlockExpression(ScriptBlockExpressionA parent = parent.Parent; } } + + public override AstVisitAction VisitDataStatement(DataStatementAst dataStatementAst) + { + if (dataStatementAst.Extent.StartOffset >= StopSearchOffset) + { + return AstVisitAction.StopVisit; + } + + if (dataStatementAst.Variable is not null) + { + SaveVariableInfo(dataStatementAst.Variable, variableType: null, isConstraint: false); + } + + return AstVisitAction.SkipChildren; + } } private static readonly Lazy> s_specialVariablesCache = new Lazy>(BuildSpecialVariablesCache); diff --git a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 index ca159b798c3..9e50e10f623 100644 --- a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 +++ b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 @@ -657,6 +657,12 @@ ConstructorTestClass(int i, bool b) $res.CompletionMatches[0].CompletionText | Should -BeExactly Cat } + It 'Should complete variable assigned with Data statement' { + $TestString = 'data MyDataVar {"Hello"};$MyDatav' + $res = TabExpansion2 -inputScript $TestString + $res.CompletionMatches[0].CompletionText | Should -BeExactly '$MyDataVar' + } + it 'Should complete "Value" parameter value in "Where-Object" for Enum property with no input' { $res = TabExpansion2 -inputScript 'Get-Command | where-Object CommandType -eq ' $res.CompletionMatches[0].CompletionText | Should -BeExactly Alias From b679b59e73f4b797ebacb40109987a7365d8db98 Mon Sep 17 00:00:00 2001 From: Dmitry Volodin Date: Tue, 11 Jul 2023 04:16:32 +0400 Subject: [PATCH 635/779] Apply the `InlineAsTypeCheck` rule in the engine code - 1st pass (#19692) --- .../DscSupport/CimDSCParser.cs | 36 ++++++------------- .../cmdletization/MethodInvocationInfo.cs | 9 ++--- .../cmdletization/ObjectModelWrapper.cs | 3 +- .../cimSupport/cmdletization/ScriptWriter.cs | 9 ++--- .../other/ciminstancetypeadapter.cs | 15 +++----- .../logging/LogProvider.cs | 4 +-- .../logging/MshLog.cs | 22 +++++++----- .../security/SecurityManager.cs | 3 +- .../security/SecuritySupport.cs | 3 +- .../singleshell/config/MshSnapinInfo.cs | 3 +- .../utils/CryptoUtils.cs | 4 +-- .../utils/ExecutionExceptions.cs | 3 +- .../utils/ParameterBinderExceptions.cs | 3 +- .../utils/PowerShellExecutionHelper.cs | 3 +- .../utils/PsUtils.cs | 35 ++++++++---------- .../utils/RuntimeException.cs | 8 ++--- .../utils/SessionStateExceptions.cs | 6 ++-- 17 files changed, 63 insertions(+), 106 deletions(-) diff --git a/src/System.Management.Automation/DscSupport/CimDSCParser.cs b/src/System.Management.Automation/DscSupport/CimDSCParser.cs index 261c567ac8d..6160577beb2 100644 --- a/src/System.Management.Automation/DscSupport/CimDSCParser.cs +++ b/src/System.Management.Automation/DscSupport/CimDSCParser.cs @@ -1935,8 +1935,7 @@ private static ParseError[] CheckMandatoryPropertiesPresent(DynamicKeywordStatem object evalResultObject; if (IsConstantValueVisitor.IsConstant(pair.Item1, out evalResultObject, forAttribute: false, forRequires: false)) { - var presentName = evalResultObject as string; - if (presentName != null) + if (evalResultObject is string presentName) { if (mandatoryPropertiesNames.Remove(presentName) && mandatoryPropertiesNames.Count == 0) { @@ -2298,8 +2297,7 @@ internal static string GenerateMofForAst(TypeDefinitionAst typeAst) internal static string MapTypeNameToMofType(ITypeName typeName, string memberName, string className, out bool isArrayType, out string embeddedInstanceType, List embeddedInstanceTypes, ref string[] enumNames) { TypeName propTypeName; - var arrayTypeName = typeName as ArrayTypeName; - if (arrayTypeName != null) + if (typeName is ArrayTypeName arrayTypeName) { isArrayType = true; propTypeName = arrayTypeName.ElementType as TypeName; @@ -2362,15 +2360,13 @@ private static void GenerateMofForAst(TypeDefinitionAst typeAst, StringBuilder s while (bases.Count > 0) { var b = bases.Dequeue(); - var tc = b as TypeConstraintAst; - if (tc != null) + if (b is TypeConstraintAst tc) { b = tc.TypeName.GetReflectionType(); if (b == null) { - var td = tc.TypeName as TypeName; - if (td != null && td._typeDefinitionAst != null) + if (tc.TypeName is TypeName td && td._typeDefinitionAst != null) { ProcessMembers(sb, embeddedInstanceTypes, td._typeDefinitionAst, className); foreach (var b1 in td._typeDefinitionAst.BaseTypes) @@ -2412,8 +2408,7 @@ private static bool GetResourceMethodsLineNumber(TypeDefinitionAst typeDefinitio methodsLinePosition = new Dictionary(); foreach (var member in typeDefinitionAst.Members) { - var functionMemberAst = member as FunctionMemberAst; - if (functionMemberAst != null) + if (member is FunctionMemberAst functionMemberAst) { if (functionMemberAst.Name.Equals(getMethodName, StringComparison.OrdinalIgnoreCase)) { @@ -2493,9 +2488,7 @@ private static void ProcessMembers(StringBuilder sb, List embeddedInstan { foreach (var member in typeDefinitionAst.Members) { - var property = member as PropertyMemberAst; - - if (property == null || property.IsStatic || + if (member is not PropertyMemberAst property || property.IsStatic || property.Attributes.All(a => a.TypeName.GetReflectionAttributeType() != typeof(DscPropertyAttribute))) { continue; @@ -2598,8 +2591,7 @@ private static bool GetResourceDefinitionsFromModule(string fileName, out IEnume resourceDefinitions = ast.FindAll(n => { - var typeAst = n as TypeDefinitionAst; - if (typeAst != null) + if (n is TypeDefinitionAst typeAst) { for (int i = 0; i < typeAst.Attributes.Count; i++) { @@ -2674,13 +2666,9 @@ private static bool ImportKeywordsFromScriptFile(string fileName, PSModuleInfo m { foreach (var na in attr.NamedArguments) { - if (na.ArgumentName.Equals("RunAsCredential", StringComparison.OrdinalIgnoreCase)) + if (na.ArgumentName.Equals("RunAsCredential", StringComparison.OrdinalIgnoreCase) && attr.GetAttribute() is DscResourceAttribute dscResourceAttribute) { - var dscResourceAttribute = attr.GetAttribute() as DscResourceAttribute; - if (dscResourceAttribute != null) - { - runAsBehavior = dscResourceAttribute.RunAsCredential; - } + runAsBehavior = dscResourceAttribute.RunAsCredential; } } } @@ -2914,8 +2902,7 @@ private static string MapAttributesToMof(string[] enumNames, IEnumerable bool needComma = false; foreach (var attr in customAttributes) { - var dscProperty = attr as DscPropertyAttribute; - if (dscProperty != null) + if (attr is DscPropertyAttribute dscProperty) { if (dscProperty.Key) { @@ -2938,8 +2925,7 @@ private static string MapAttributesToMof(string[] enumNames, IEnumerable continue; } - var validateSet = attr as ValidateSetAttribute; - if (validateSet != null) + if (attr is ValidateSetAttribute validateSet) { bool valueMapComma = false; StringBuilder sbValues = new(", Values{"); diff --git a/src/System.Management.Automation/cimSupport/cmdletization/MethodInvocationInfo.cs b/src/System.Management.Automation/cimSupport/cmdletization/MethodInvocationInfo.cs index d8ea4ed2398..c2d30f6610e 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/MethodInvocationInfo.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/MethodInvocationInfo.cs @@ -62,20 +62,17 @@ internal IEnumerable GetArgumentsOfType() where T : class continue; } - var objectInstance = methodParameter.Value as T; - if (objectInstance != null) + if (methodParameter.Value is T objectInstance) { result.Add(objectInstance); continue; } - var objectInstanceArray = methodParameter.Value as IEnumerable; - if (objectInstanceArray != null) + if (methodParameter.Value is IEnumerable objectInstanceArray) { foreach (object element in objectInstanceArray) { - var objectInstance2 = element as T; - if (objectInstance2 != null) + if (element is T objectInstance2) { result.Add(objectInstance2); } diff --git a/src/System.Management.Automation/cimSupport/cmdletization/ObjectModelWrapper.cs b/src/System.Management.Automation/cimSupport/cmdletization/ObjectModelWrapper.cs index 325d8c52c99..082d7218023 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/ObjectModelWrapper.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/ObjectModelWrapper.cs @@ -29,8 +29,7 @@ internal void Initialize(PSCmdlet cmdlet, string className, string classVersion, _classVersion = classVersion; _privateData = privateData; - var compiledScript = this.Cmdlet as PSScriptCmdlet; - if (compiledScript != null) + if (this.Cmdlet is PSScriptCmdlet compiledScript) { compiledScript.StoppingEvent += delegate { this.StopProcessing(); }; compiledScript.DisposingEvent += diff --git a/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs b/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs index ccc95b9735c..e0bbcaa3969 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs @@ -100,14 +100,12 @@ internal ScriptWriter( } catch (InvalidOperationException e) { - XmlSchemaException schemaException = e.InnerException as XmlSchemaException; - if (schemaException != null) + if (e.InnerException is XmlSchemaException schemaException) { throw new XmlException(schemaException.Message, schemaException, schemaException.LineNumber, schemaException.LinePosition); } - XmlException xmlException = e.InnerException as XmlException; - if (xmlException != null) + if (e.InnerException is XmlException xmlException) { throw xmlException; } @@ -828,8 +826,7 @@ private void SetParameters(CommandMetadata commandMetadata, params Dictionary GetProperties(object baseObject) { // baseObject should never be null - CimInstance cimInstance = baseObject as CimInstance; - if (cimInstance == null) + if (baseObject is not CimInstance cimInstance) { string msg = string.Format(CultureInfo.InvariantCulture, CimInstanceTypeAdapterResources.BaseObjectNotCimInstance, @@ -107,8 +106,7 @@ public override PSAdaptedProperty GetProperty(object baseObject, string property } // baseObject should never be null - CimInstance cimInstance = baseObject as CimInstance; - if (cimInstance == null) + if (baseObject is not CimInstance cimInstance) { string msg = string.Format(CultureInfo.InvariantCulture, CimInstanceTypeAdapterResources.BaseObjectNotCimInstance, @@ -142,8 +140,7 @@ public override PSAdaptedProperty GetFirstPropertyOrDefault(object baseObject, M } // baseObject should never be null - CimInstance cimInstance = baseObject as CimInstance; - if (cimInstance == null) + if (baseObject is not CimInstance cimInstance) { string msg = string.Format( CultureInfo.InvariantCulture, @@ -197,8 +194,7 @@ public override string GetPropertyTypeName(PSAdaptedProperty adaptedProperty) { ArgumentNullException.ThrowIfNull(adaptedProperty); - CimProperty cimProperty = adaptedProperty.Tag as CimProperty; - if (cimProperty != null) + if (adaptedProperty.Tag is CimProperty cimProperty) { return CimTypeToTypeNameDisplayString(cimProperty.CimType); } @@ -219,8 +215,7 @@ public override object GetPropertyValue(PSAdaptedProperty adaptedProperty) { ArgumentNullException.ThrowIfNull(adaptedProperty); - CimProperty cimProperty = adaptedProperty.Tag as CimProperty; - if (cimProperty != null) + if (adaptedProperty.Tag is CimProperty cimProperty) { return cimProperty.Value; } diff --git a/src/System.Management.Automation/logging/LogProvider.cs b/src/System.Management.Automation/logging/LogProvider.cs index 6bcc2b7c132..e02807a38e8 100644 --- a/src/System.Management.Automation/logging/LogProvider.cs +++ b/src/System.Management.Automation/logging/LogProvider.cs @@ -200,9 +200,7 @@ protected static void AppendException(StringBuilder sb, Exception except) { sb.AppendLine(StringUtil.Format(EtwLoggingStrings.ErrorRecordMessage, except.Message)); - IContainsErrorRecord ier = except as IContainsErrorRecord; - - if (ier != null) + if (except is IContainsErrorRecord ier) { ErrorRecord er = ier.ErrorRecord; diff --git a/src/System.Management.Automation/logging/MshLog.cs b/src/System.Management.Automation/logging/MshLog.cs index da48dc816aa..aae65271892 100644 --- a/src/System.Management.Automation/logging/MshLog.cs +++ b/src/System.Management.Automation/logging/MshLog.cs @@ -211,9 +211,11 @@ internal static void LogEngineHealthEvent(ExecutionContext executionContext, } InvocationInfo invocationInfo = null; - IContainsErrorRecord icer = exception as IContainsErrorRecord; - if (icer != null && icer.ErrorRecord != null) + if (exception is IContainsErrorRecord icer && icer.ErrorRecord != null) + { invocationInfo = icer.ErrorRecord.InvocationInfo; + } + foreach (LogProvider provider in GetLogProvider(executionContext)) { if (NeedToLogEngineHealthEvent(provider, executionContext)) @@ -413,9 +415,11 @@ Severity severity } InvocationInfo invocationInfo = null; - IContainsErrorRecord icer = exception as IContainsErrorRecord; - if (icer != null && icer.ErrorRecord != null) + if (exception is IContainsErrorRecord icer && icer.ErrorRecord != null) + { invocationInfo = icer.ErrorRecord.InvocationInfo; + } + foreach (LogProvider provider in GetLogProvider(executionContext)) { if (NeedToLogCommandHealthEvent(provider, executionContext)) @@ -605,9 +609,11 @@ Severity severity } InvocationInfo invocationInfo = null; - IContainsErrorRecord icer = exception as IContainsErrorRecord; - if (icer != null && icer.ErrorRecord != null) + if (exception is IContainsErrorRecord icer && icer.ErrorRecord != null) + { invocationInfo = icer.ErrorRecord.InvocationInfo; + } + foreach (LogProvider provider in GetLogProvider(executionContext)) { if (NeedToLogProviderHealthEvent(provider, executionContext)) @@ -804,9 +810,7 @@ private static LogContext GetLogContext(ExecutionContext executionContext, Invoc logContext.User = Logging.UnknownUserName; } - System.Management.Automation.Remoting.PSSenderInfo psSenderInfo = - executionContext.SessionState.PSVariable.GetValue("PSSenderInfo") as System.Management.Automation.Remoting.PSSenderInfo; - if (psSenderInfo != null) + if (executionContext.SessionState.PSVariable.GetValue("PSSenderInfo") is System.Management.Automation.Remoting.PSSenderInfo psSenderInfo) { logContext.ConnectedUser = psSenderInfo.UserInfo.Identity.Name; } diff --git a/src/System.Management.Automation/security/SecurityManager.cs b/src/System.Management.Automation/security/SecurityManager.cs index 38a9aa511dc..137daecc5b4 100644 --- a/src/System.Management.Automation/security/SecurityManager.cs +++ b/src/System.Management.Automation/security/SecurityManager.cs @@ -651,8 +651,7 @@ protected internal override bool ShouldRun(CommandInfo commandInfo, break; case CommandTypes.ExternalScript: - ExternalScriptInfo si = commandInfo as ExternalScriptInfo; - if (si == null) + if (commandInfo is not ExternalScriptInfo si) { reason = PSTraceSource.NewArgumentException("scriptInfo"); } diff --git a/src/System.Management.Automation/security/SecuritySupport.cs b/src/System.Management.Automation/security/SecuritySupport.cs index 0892465804d..2089c2217ed 100644 --- a/src/System.Management.Automation/security/SecuritySupport.cs +++ b/src/System.Management.Automation/security/SecuritySupport.cs @@ -663,8 +663,7 @@ private static bool CertHasKeyUsage(X509Certificate2 c, X509KeyUsageFlags keyUsa { foreach (X509Extension extension in c.Extensions) { - X509KeyUsageExtension keyUsageExtension = extension as X509KeyUsageExtension; - if (keyUsageExtension != null) + if (extension is X509KeyUsageExtension keyUsageExtension) { if ((keyUsageExtension.KeyUsages & keyUsage) == keyUsage) { diff --git a/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs b/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs index 17804d0360e..643e649ca7e 100644 --- a/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs +++ b/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs @@ -761,8 +761,7 @@ private static Collection ReadMultiStringValue(RegistryKey mshsnapinKey, if (msv == null) { // Check if the value is in string format - string singleValue = value as string; - if (singleValue != null) + if (value is string singleValue) { msv = new string[1]; msv[0] = singleValue; diff --git a/src/System.Management.Automation/utils/CryptoUtils.cs b/src/System.Management.Automation/utils/CryptoUtils.cs index c2139680ab0..2441d416a4d 100644 --- a/src/System.Management.Automation/utils/CryptoUtils.cs +++ b/src/System.Management.Automation/utils/CryptoUtils.cs @@ -866,12 +866,10 @@ internal PSRemotingCryptoHelperServer() internal override string EncryptSecureString(SecureString secureString) { - ServerRemoteSession session = Session as ServerRemoteSession; - // session!=null check required for DRTs TestEncryptSecureString* entries in CryptoUtilsTest/UTUtils.dll // for newer clients, server will never initiate key exchange. // for server, just the session key is required to encrypt/decrypt anything - if ((session != null) && (session.Context.ClientCapability.ProtocolVersion >= RemotingConstants.ProtocolVersionWin8RTM)) + if (Session is ServerRemoteSession session && session.Context.ClientCapability.ProtocolVersion >= RemotingConstants.ProtocolVersionWin8RTM) { _rsaCryptoProvider.GenerateSessionKey(); } diff --git a/src/System.Management.Automation/utils/ExecutionExceptions.cs b/src/System.Management.Automation/utils/ExecutionExceptions.cs index 460a98c5cd8..69a58d326b2 100644 --- a/src/System.Management.Automation/utils/ExecutionExceptions.cs +++ b/src/System.Management.Automation/utils/ExecutionExceptions.cs @@ -54,8 +54,7 @@ internal CmdletInvocationException(Exception innerException, ArgumentNullException.ThrowIfNull(innerException); // invocationInfo may be null - IContainsErrorRecord icer = innerException as IContainsErrorRecord; - if (icer != null && icer.ErrorRecord != null) + if (innerException is IContainsErrorRecord icer && icer.ErrorRecord != null) { _errorRecord = new ErrorRecord(icer.ErrorRecord, innerException); } diff --git a/src/System.Management.Automation/utils/ParameterBinderExceptions.cs b/src/System.Management.Automation/utils/ParameterBinderExceptions.cs index 2f9a15d4dd2..4052eec0b81 100644 --- a/src/System.Management.Automation/utils/ParameterBinderExceptions.cs +++ b/src/System.Management.Automation/utils/ParameterBinderExceptions.cs @@ -637,8 +637,7 @@ internal ParameterBindingValidationException( errorId, args) { - ValidationMetadataException validationException = innerException as ValidationMetadataException; - if (validationException != null && validationException.SwallowException) + if (innerException is ValidationMetadataException validationException && validationException.SwallowException) { _swallowException = true; } diff --git a/src/System.Management.Automation/utils/PowerShellExecutionHelper.cs b/src/System.Management.Automation/utils/PowerShellExecutionHelper.cs index 632e1445ee4..981680e3e45 100644 --- a/src/System.Management.Automation/utils/PowerShellExecutionHelper.cs +++ b/src/System.Management.Automation/utils/PowerShellExecutionHelper.cs @@ -120,9 +120,8 @@ internal static string SafeToString(object obj) try { - PSObject pso = obj as PSObject; string result; - if (pso != null) + if (obj is PSObject pso) { object baseObject = pso.BaseObject; if (baseObject != null && baseObject is not PSCustomObject) diff --git a/src/System.Management.Automation/utils/PsUtils.cs b/src/System.Management.Automation/utils/PsUtils.cs index 483491847fd..53809e586a0 100644 --- a/src/System.Management.Automation/utils/PsUtils.cs +++ b/src/System.Management.Automation/utils/PsUtils.cs @@ -354,33 +354,28 @@ internal static Hashtable GetModuleManifestProperties(string psDataFilePath, str } var pipeline = ast.GetSimplePipeline(false, out _, out _); - if (pipeline != null) + if (pipeline?.GetPureExpression() is HashtableAst hashtableAst) { - var hashtableAst = pipeline.GetPureExpression() as HashtableAst; - if (hashtableAst != null) + var result = new Hashtable(StringComparer.OrdinalIgnoreCase); + foreach (var pair in hashtableAst.KeyValuePairs) { - var result = new Hashtable(StringComparer.OrdinalIgnoreCase); - foreach (var pair in hashtableAst.KeyValuePairs) + if (pair.Item1 is StringConstantExpressionAst key && keys.Contains(key.Value, StringComparer.OrdinalIgnoreCase)) { - var key = pair.Item1 as StringConstantExpressionAst; - if (key != null && keys.Contains(key.Value, StringComparer.OrdinalIgnoreCase)) + try { - try - { - var val = pair.Item2.SafeGetValue(); - result[key.Value] = val; - } - catch - { - throw PSTraceSource.NewInvalidOperationException( - ParserStrings.InvalidPowerShellDataFile, - psDataFilePath); - } + var val = pair.Item2.SafeGetValue(); + result[key.Value] = val; + } + catch + { + throw PSTraceSource.NewInvalidOperationException( + ParserStrings.InvalidPowerShellDataFile, + psDataFilePath); } } - - return result; } + + return result; } throw PSTraceSource.NewInvalidOperationException( diff --git a/src/System.Management.Automation/utils/RuntimeException.cs b/src/System.Management.Automation/utils/RuntimeException.cs index 8c0bcee5f1d..4cfdc31bcb6 100644 --- a/src/System.Management.Automation/utils/RuntimeException.cs +++ b/src/System.Management.Automation/utils/RuntimeException.cs @@ -252,13 +252,9 @@ public bool WasThrownFromThrowStatement set { _thrownByThrowStatement = value; - if (_errorRecord != null) + if (_errorRecord?.Exception is RuntimeException exception) { - RuntimeException exception = _errorRecord.Exception as RuntimeException; - if (exception != null) - { - exception.WasThrownFromThrowStatement = value; - } + exception.WasThrownFromThrowStatement = value; } } } diff --git a/src/System.Management.Automation/utils/SessionStateExceptions.cs b/src/System.Management.Automation/utils/SessionStateExceptions.cs index dd15e9ad463..4121eac17eb 100644 --- a/src/System.Management.Automation/utils/SessionStateExceptions.cs +++ b/src/System.Management.Automation/utils/SessionStateExceptions.cs @@ -66,8 +66,7 @@ internal ProviderInvocationException(ProviderInfo provider, Exception innerExcep _message = base.Message; _providerInfo = provider; - IContainsErrorRecord icer = innerException as IContainsErrorRecord; - if (icer != null && icer.ErrorRecord != null) + if (innerException is IContainsErrorRecord icer && icer.ErrorRecord != null) { _errorRecord = new ErrorRecord(icer.ErrorRecord, innerException); } @@ -199,8 +198,7 @@ internal ProviderInvocationException( errorRecordException = new ParentContainsErrorRecordException(this); } - IContainsErrorRecord icer = innerException as IContainsErrorRecord; - if (icer != null && icer.ErrorRecord != null) + if (innerException is IContainsErrorRecord icer && icer.ErrorRecord != null) { _errorRecord = new ErrorRecord(icer.ErrorRecord, errorRecordException); } From a26b09d71edbe1d3bd01bd06fc35eef29da811ff Mon Sep 17 00:00:00 2001 From: Dmitry Volodin Date: Tue, 11 Jul 2023 04:17:08 +0400 Subject: [PATCH 636/779] Apply the `InlineAsTypeCheck` in the engine code - 2nd pass (#19694) --- .../common/BaseFormattingCommandParameters.cs | 6 +- .../common/BaseOutputtingCommand.cs | 59 +++++++------------ .../FormatAndOutput/common/ComplexWriter.cs | 9 +-- .../common/DisplayDatabase/XmlLoaderBase.cs | 10 +--- .../displayDescriptionData_Complex.cs | 14 +---- .../displayDescriptionData_List.cs | 3 +- .../displayDescriptionData_Table.cs | 3 +- .../displayDescriptionData_Wide.cs | 3 +- .../common/DisplayDatabase/typeDataQuery.cs | 9 +-- .../DisplayDatabase/typeDataXmlLoader.cs | 12 ++-- .../common/FormatMsgCtxManager.cs | 3 +- .../common/FormatViewGenerator.cs | 18 ++---- .../common/FormatViewGenerator_Complex.cs | 15 ++--- .../common/FormatViewGenerator_List.cs | 11 ++-- .../common/FormatViewGenerator_Table.cs | 11 +--- .../common/FormatViewManager.cs | 6 +- .../FormatAndOutput/common/FormatXMLWriter.cs | 9 +-- .../common/FormattingObjectsDeserializer.cs | 6 +- .../FormatAndOutput/common/OutputQueue.cs | 16 ++--- .../common/Utilities/MshObjectUtil.cs | 46 ++++++--------- .../common/Utilities/Mshexpression.cs | 3 +- .../FormatAndOutput/out-console/OutConsole.cs | 4 +- 22 files changed, 93 insertions(+), 183 deletions(-) diff --git a/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommandParameters.cs b/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommandParameters.cs index 95c58353457..7f88727ace7 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommandParameters.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommandParameters.cs @@ -176,15 +176,13 @@ internal override object Verify(object val, // need to check the type: // it can be a string or a script block - ScriptBlock sb = val as ScriptBlock; - if (sb != null) + if (val is ScriptBlock sb) { PSPropertyExpression ex = new PSPropertyExpression(sb); return ex; } - string s = val as string; - if (s != null) + if (val is string s) { if (string.IsNullOrEmpty(s)) { diff --git a/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs b/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs index 088a6a76b67..113acf3fa6a 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs @@ -131,9 +131,7 @@ private bool ProcessObject(PSObject so) _cache ??= new FormattedObjectsCache(this.LineOutput.RequiresBuffering); // no need for formatting, just process the object - FormatStartData formatStart = o as FormatStartData; - - if (formatStart != null) + if (o is FormatStartData formatStart) { // get autosize flag from object // turn on group caching @@ -145,8 +143,7 @@ private bool ProcessObject(PSObject so) else { // If the format info doesn't define column widths, then auto-size based on the first ten elements - TableHeaderInfo headerInfo = formatStart.shapeInfo as TableHeaderInfo; - if ((headerInfo != null) && + if ((formatStart.shapeInfo is TableHeaderInfo headerInfo) && (headerInfo.tableColumnInfoList.Count > 0) && (headerInfo.tableColumnInfoList[0].width == 0)) { @@ -258,8 +255,7 @@ private enum PreprocessingState { raw, processed, error } /// Whether the object needs to be shunted to preprocessing. private bool NeedsPreprocessing(object o) { - FormatEntryData fed = o as FormatEntryData; - if (fed != null) + if (o is FormatEntryData fed) { // we got an already pre-processed object if (!fed.outOfBand) @@ -322,8 +318,7 @@ private void ValidateCurrentFormattingState(FormattingState expectedFormattingSt // need to abort the command string violatingCommand = "format-*"; - StartData sdObj = obj as StartData; - if (sdObj != null) + if (obj is StartData sdObj) { if (sdObj.shapeInfo is WideViewHeaderInfo) { @@ -383,18 +378,16 @@ private FormatMessagesContextManager.OutputContext CreateOutputContext( FormatMessagesContextManager.OutputContext parentContext, FormatInfoData formatInfoData) { - FormatStartData formatStartData = formatInfoData as FormatStartData; // initialize the format context - if (formatStartData != null) + if (formatInfoData is FormatStartData formatStartData) { FormatOutputContext foc = new FormatOutputContext(parentContext, formatStartData); return foc; } - GroupStartData gsd = formatInfoData as GroupStartData; // we are starting a group, initialize the group context - if (gsd != null) + if (formatInfoData is GroupStartData gsd) { GroupOutputContext goc = null; @@ -544,8 +537,7 @@ private void ProcessPayload(FormatEntryData fed, FormatMessagesContextManager.Ou private void ProcessOutOfBandPayload(FormatEntryData fed) { // try if it is raw text - RawTextFormatEntry rte = fed.formatEntryInfo as RawTextFormatEntry; - if (rte != null) + if (fed.formatEntryInfo is RawTextFormatEntry rte) { if (fed.isHelpObject) { @@ -564,8 +556,7 @@ private void ProcessOutOfBandPayload(FormatEntryData fed) } // try if it is a complex entry - ComplexViewEntry cve = fed.formatEntryInfo as ComplexViewEntry; - if (cve != null && cve.formatValueList != null) + if (fed.formatEntryInfo is ComplexViewEntry cve && cve.formatValueList != null) { ComplexWriter complexWriter = new ComplexWriter(); @@ -575,8 +566,7 @@ private void ProcessOutOfBandPayload(FormatEntryData fed) return; } // try if it is a list view - ListViewEntry lve = fed.formatEntryInfo as ListViewEntry; - if (lve != null && lve.listViewFieldList != null) + if (fed.formatEntryInfo is ListViewEntry lve && lve.listViewFieldList != null) { ListWriter listWriter = new ListWriter(); @@ -628,9 +618,7 @@ private FormatOutputContext FormatContext { for (FormatMessagesContextManager.OutputContext oc = _ctxManager.ActiveOutputContext; oc != null; oc = oc.ParentContext) { - FormatOutputContext foc = oc as FormatOutputContext; - - if (foc != null) + if (oc is FormatOutputContext foc) return foc; } @@ -655,17 +643,13 @@ private void ProcessCachedGroup(FormatStartData formatStartData, List internal override void Initialize() { - TableFormattingHint tableHint = this.InnerCommand.RetrieveFormattingHint() as TableFormattingHint; int[] columnWidthsHint = null; - // We expect that console width is less then 120. + // We expect that console width is less than 120. - if (tableHint != null) + if (this.InnerCommand.RetrieveFormattingHint() is TableFormattingHint tableHint) { columnWidthsHint = tableHint.columnWidths; } @@ -1215,13 +1198,11 @@ internal override void Initialize() // set the hard wider default, to be used if no other info is available int itemsPerRow = 2; - // get the header info and the view hint - WideFormattingHint hint = this.InnerCommand.RetrieveFormattingHint() as WideFormattingHint; - + // get the header info int columnsOnTheScreen = GetConsoleWindowWidth(this.InnerCommand._lo.ColumnNumber); // give a preference to the hint, if there - if (hint != null && hint.maxWidth > 0) + if (this.InnerCommand.RetrieveFormattingHint() is WideFormattingHint hint && hint.maxWidth > 0) { itemsPerRow = TableWriter.ComputeWideViewBestItemsPerRowFit(hint.maxWidth, columnsOnTheScreen); } @@ -1402,10 +1383,10 @@ internal override void Initialize() /// FormatEntryData to process. internal override void ProcessPayload(FormatEntryData fed) { - ComplexViewEntry cve = fed.formatEntryInfo as ComplexViewEntry; - if (cve == null || cve.formatValueList == null) - return; - _writer.WriteObject(cve.formatValueList); + if (fed.formatEntryInfo is ComplexViewEntry cve && cve.formatValueList is not null) + { + _writer.WriteObject(cve.formatValueList); + } } private readonly ComplexWriter _writer = new ComplexWriter(); diff --git a/src/System.Management.Automation/FormatAndOutput/common/ComplexWriter.cs b/src/System.Management.Automation/FormatAndOutput/common/ComplexWriter.cs index 099bec43dc6..61a3f962daf 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/ComplexWriter.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/ComplexWriter.cs @@ -70,8 +70,7 @@ private void GenerateFormatEntryDisplay(FormatEntry fe, int currentDepth) { foreach (object obj in fe.formatValueList) { - FormatEntry feChild = obj as FormatEntry; - if (feChild != null) + if (obj is FormatEntry feChild) { if (currentDepth < maxRecursionDepth) { @@ -100,15 +99,13 @@ private void GenerateFormatEntryDisplay(FormatEntry fe, int currentDepth) continue; } - FormatTextField ftf = obj as FormatTextField; - if (ftf != null) + if (obj is FormatTextField ftf) { this.AddToBuffer(ftf.text); continue; } - FormatPropertyField fpf = obj as FormatPropertyField; - if (fpf != null) + if (obj is FormatPropertyField fpf) { this.AddToBuffer(fpf.propertyValue); } diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/XmlLoaderBase.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/XmlLoaderBase.cs index e8fc15d5558..9ebc79a762a 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/XmlLoaderBase.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/XmlLoaderBase.cs @@ -384,14 +384,10 @@ private bool MatchNodeNameHelper(XmlNode n, string s, bool allowAttributes) match = true; } - if (match && !allowAttributes) + if (match && !allowAttributes && n is XmlElement e && e.Attributes.Count > 0) { - XmlElement e = n as XmlElement; - if (e != null && e.Attributes.Count > 0) - { - // Error at XPath {0} in file {1}: The XML Element {2} does not allow attributes. - ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.AttributesNotAllowed, ComputeCurrentXPath(), FilePath, n.Name)); - } + // Error at XPath {0} in file {1}: The XML Element {2} does not allow attributes. + ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.AttributesNotAllowed, ComputeCurrentXPath(), FilePath, n.Name)); } return match; diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Complex.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Complex.cs index d3290c18752..f40bb557c31 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Complex.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Complex.cs @@ -179,14 +179,12 @@ internal static CustomItemBase Create(FormatToken token) return new CustomItemNewline(); } - var textToken = token as TextToken; - if (textToken != null) + if (token is TextToken textToken) { return new CustomItemText { Text = textToken.text }; } - var frameToken = token as FrameToken; - if (frameToken != null) + if (token is FrameToken frameToken) { var frame = new CustomItemFrame { @@ -211,8 +209,7 @@ internal static CustomItemBase Create(FormatToken token) return frame; } - var cpt = token as CompoundPropertyToken; - if (cpt != null) + if (token is CompoundPropertyToken cpt) { var cie = new CustomItemExpression { EnumerateCollection = cpt.enumerateCollection }; @@ -234,11 +231,6 @@ internal static CustomItemBase Create(FormatToken token) return cie; } - var fpt = token as FieldPropertyToken; - if (fpt != null) - { - } - Diagnostics.Assert(false, "Unexpected formatting token kind"); return null; diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_List.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_List.cs index 4ac470d288c..293b4c5b82e 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_List.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_List.cs @@ -318,8 +318,7 @@ internal ListControlEntryItem(ListControlItemDefinition definition) Label = definition.label.text; } - FieldPropertyToken fpt = definition.formatTokenList[0] as FieldPropertyToken; - if (fpt != null) + if (definition.formatTokenList[0] is FieldPropertyToken fpt) { if (fpt.fieldFormattingDirective.formatString != null) { diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Table.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Table.cs index e509530538d..026b9b82f73 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Table.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Table.cs @@ -446,10 +446,9 @@ internal TableControlRow(TableRowDefinition rowdefinition) : this() foreach (TableRowItemDefinition itemdef in rowdefinition.rowItemDefinitionList) { - FieldPropertyToken fpt = itemdef.formatTokenList[0] as FieldPropertyToken; TableControlColumn column; - if (fpt != null) + if (itemdef.formatTokenList[0] is FieldPropertyToken fpt) { column = new TableControlColumn(fpt.expression.expressionValue, itemdef.alignment, fpt.expression.isScriptBlock, fpt.fieldFormattingDirective.formatString); diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Wide.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Wide.cs index 220446bfe17..1f5b42fd262 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Wide.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Wide.cs @@ -204,8 +204,7 @@ internal WideControlEntryItem() internal WideControlEntryItem(WideControlEntryDefinition definition) : this() { - FieldPropertyToken fpt = definition.formatTokenList[0] as FieldPropertyToken; - if (fpt != null) + if (definition.formatTokenList[0] is FieldPropertyToken fpt) { DisplayEntry = new DisplayEntry(fpt.expression); FormatString = fpt.fieldFormattingDirective.formatString; diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs index 78aef16483b..c9ecd0042dd 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs @@ -143,9 +143,8 @@ private int ComputeBestMatch(AppliesTo appliesTo, PSObject currentObject) } int currentMatch = BestMatchIndexUndefined; - TypeReference tr = r as TypeReference; - if (tr != null) + if (r is TypeReference tr) { // we have a type currentMatch = MatchTypeIndex(tr.name, currentObject, ex); @@ -486,9 +485,8 @@ private static void TraceHelper(ViewDefinition vd, bool isMatched) foreach (TypeOrGroupReference togr in vd.appliesTo.referenceList) { StringBuilder sb = new StringBuilder(); - TypeReference tr = togr as TypeReference; sb.Append(isMatched ? "MATCH FOUND" : "NOT MATCH"); - if (tr != null) + if (togr is TypeReference tr) { sb.AppendFormat( CultureInfo.InvariantCulture, @@ -601,8 +599,7 @@ internal static AppliesTo GetAllApplicableTypes(TypeInfoDataBase db, AppliesTo a foreach (TypeOrGroupReference r in appliesTo.referenceList) { // if it is a type reference, just add the type name - TypeReference tr = r as TypeReference; - if (tr != null) + if (r is TypeReference tr) { if (!allTypes.Contains(tr.name)) allTypes.Add(tr.name); diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs index faa065f57eb..b8a25e5e207 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs @@ -1085,20 +1085,17 @@ private ComplexControlEntryDefinition LoadComplexControlEntryDefinitionFromObjec private FormatToken LoadFormatTokenFromObjectModel(CustomItemBase item, int viewIndex, string typeName) { - var newline = item as CustomItemNewline; - if (newline != null) + if (item is CustomItemNewline newline) { return new NewLineToken { count = newline.Count }; } - var text = item as CustomItemText; - if (text != null) + if (item is CustomItemText text) { return new TextToken { text = text.Text }; } - var expr = item as CustomItemExpression; - if (expr != null) + if (item is CustomItemExpression expr) { var cpt = new CompoundPropertyToken { enumerateCollection = expr.EnumerateCollection }; @@ -1766,9 +1763,8 @@ private TextToken LoadTextToken(XmlNode n) private bool LoadStringResourceReference(XmlNode n, out StringResourceReference resource) { resource = null; - XmlElement e = n as XmlElement; - if (e == null) + if (n is not XmlElement e) { // Error at XPath {0} in file {1}: Node should be an XmlElement. this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.NonXmlElementNode, ComputeCurrentXPath(), FilePath)); diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatMsgCtxManager.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatMsgCtxManager.cs index 3eabcc975a0..1018936d2c1 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatMsgCtxManager.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatMsgCtxManager.cs @@ -68,8 +68,7 @@ internal OutputContext(OutputContext parentContextInStack) internal void Process(object o) { PacketInfoData formatData = o as PacketInfoData; - FormatEntryData fed = formatData as FormatEntryData; - if (fed != null) + if (formatData is FormatEntryData fed) { OutputContext ctx = null; diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator.cs index 41c4dafe85c..db1bc0704aa 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator.cs @@ -141,13 +141,10 @@ private void InitializeAutoSize() return; } // check if we have a view with autosize checked - if (this.dataBaseInfo.view != null && this.dataBaseInfo.view.mainControl != null) + if (this.dataBaseInfo.view != null && this.dataBaseInfo.view.mainControl != null + && this.dataBaseInfo.view.mainControl is ControlBody controlBody && controlBody.autosize.HasValue) { - ControlBody controlBody = this.dataBaseInfo.view.mainControl as ControlBody; - if (controlBody != null && controlBody.autosize.HasValue) - { - _autosize = controlBody.autosize.Value; - } + _autosize = controlBody.autosize.Value; } } @@ -439,17 +436,14 @@ protected FormatPropertyField GenerateFormatPropertyField(List form if (formatTokenList.Count != 0) { FormatToken token = formatTokenList[0]; - FieldPropertyToken fpt = token as FieldPropertyToken; - if (fpt != null) + if (token is FieldPropertyToken fpt) { PSPropertyExpression ex = this.expressionFactory.CreateFromExpressionToken(fpt.expression, this.dataBaseInfo.view.loadingInfo); fpf.propertyValue = this.GetExpressionDisplayValue(so, enumerationLimit, ex, fpt.fieldFormattingDirective, out result); } - else + else if (token is TextToken tt) { - TextToken tt = token as TextToken; - if (tt != null) - fpf.propertyValue = this.dataBaseInfo.db.displayResourceManagerCache.GetTextTokenString(tt); + fpf.propertyValue = this.dataBaseInfo.db.displayResourceManagerCache.GetTextTokenString(tt); } } else diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Complex.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Complex.cs index 5573c28f78b..b2bbd27c2b9 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Complex.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Complex.cs @@ -107,8 +107,7 @@ private bool ExecuteFormatControl(TraversalInfo level, ControlBase control, ComplexControlBody complexBody = null; // we might have a reference - ControlReference controlReference = control as ControlReference; - if (controlReference != null && controlReference.controlType == typeof(ComplexControlBody)) + if (control is ControlReference controlReference && controlReference.controlType == typeof(ComplexControlBody)) { // retrieve the reference complexBody = DisplayDataQuery.ResolveControlReference( @@ -205,8 +204,7 @@ private void ExecuteFormatTokenList(TraversalInfo level, #region foreach loop foreach (FormatToken t in formatTokenList) { - TextToken tt = t as TextToken; - if (tt != null) + if (t is TextToken tt) { FormatTextField ftf = new FormatTextField(); ftf.text = _db.displayResourceManagerCache.GetTextTokenString(tt); @@ -214,8 +212,7 @@ private void ExecuteFormatTokenList(TraversalInfo level, continue; } - var newline = t as NewLineToken; - if (newline != null) + if (t is NewLineToken newline) { for (int i = 0; i < newline.count; i++) { @@ -225,8 +222,7 @@ private void ExecuteFormatTokenList(TraversalInfo level, continue; } - FrameToken ft = t as FrameToken; - if (ft != null) + if (t is FrameToken ft) { // instantiate a new entry and attach a frame info object FormatEntry feFrame = new FormatEntry(); @@ -245,8 +241,7 @@ private void ExecuteFormatTokenList(TraversalInfo level, continue; } #region CompoundPropertyToken - CompoundPropertyToken cpt = t as CompoundPropertyToken; - if (cpt != null) + if (t is CompoundPropertyToken cpt) { if (!EvaluateDisplayCondition(so, cpt.conditionToken)) { diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_List.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_List.cs index 1cee3067011..f7acd9ed226 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_List.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_List.cs @@ -114,20 +114,17 @@ private ListViewEntry GenerateListViewEntryFromDataBaseInfo(PSObject so, int enu // we try to fall back and see if we have an un-resolved PSPropertyExpression FormatToken token = listItem.formatTokenList[0]; - FieldPropertyToken fpt = token as FieldPropertyToken; - if (fpt != null) + if (token is FieldPropertyToken fpt) { PSPropertyExpression ex = this.expressionFactory.CreateFromExpressionToken(fpt.expression, this.dataBaseInfo.view.loadingInfo); // use the un-resolved PSPropertyExpression string as a label lvf.label = ex.ToString(); } - else + else if (token is TextToken tt) { - TextToken tt = token as TextToken; - if (tt != null) - // we had a text token, use it as a label (last resort...) - lvf.label = this.dataBaseInfo.db.displayResourceManagerCache.GetTextTokenString(tt); + // we had a text token, use it as a label (last resort...) + lvf.label = this.dataBaseInfo.db.displayResourceManagerCache.GetTextTokenString(tt); } } diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Table.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Table.cs index c6fc9887c9a..442603b448e 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Table.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Table.cs @@ -191,18 +191,13 @@ private TableHeaderInfo GenerateTableHeaderInfoFromDataBaseInfo(PSObject so) token = rowItem.formatTokenList[0]; if (token != null) { - FieldPropertyToken fpt = token as FieldPropertyToken; - if (fpt != null) + if (token is FieldPropertyToken fpt) { ci.label = fpt.expression.expressionValue; } - else + else if (token is TextToken tt) { - TextToken tt = token as TextToken; - if (tt != null) - { - ci.label = this.dataBaseInfo.db.displayResourceManagerCache.GetTextTokenString(tt); - } + ci.label = this.dataBaseInfo.db.displayResourceManagerCache.GetTextTokenString(tt); } } else diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatViewManager.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatViewManager.cs index 0737e43476e..891dfce6829 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatViewManager.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatViewManager.cs @@ -646,8 +646,7 @@ private static ErrorRecord GenerateErrorRecord(FormattingError error) { ErrorRecord errorRecord = null; string msg = null; - PSPropertyExpressionError psPropertyExpressionError = error as PSPropertyExpressionError; - if (psPropertyExpressionError != null) + if (error is PSPropertyExpressionError psPropertyExpressionError) { errorRecord = new ErrorRecord( psPropertyExpressionError.result.Exception, @@ -660,8 +659,7 @@ private static ErrorRecord GenerateErrorRecord(FormattingError error) errorRecord.ErrorDetails = new ErrorDetails(msg); } - StringFormatError formattingError = error as StringFormatError; - if (formattingError != null) + if (error is StringFormatError formattingError) { errorRecord = new ErrorRecord( formattingError.exception, diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatXMLWriter.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatXMLWriter.cs index c18297c620e..c8b077918fe 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatXMLWriter.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatXMLWriter.cs @@ -385,8 +385,7 @@ internal void WriteCustomControl(CustomControl customControl) internal void WriteCustomItem(CustomItemBase item) { - var newline = item as CustomItemNewline; - if (newline != null) + if (item is CustomItemNewline newline) { for (int i = 0; i < newline.Count; i++) { @@ -396,15 +395,13 @@ internal void WriteCustomItem(CustomItemBase item) return; } - var text = item as CustomItemText; - if (text != null) + if (item is CustomItemText text) { _writer.WriteElementString("Text", text.Text); return; } - var expr = item as CustomItemExpression; - if (expr != null) + if (item is CustomItemExpression expr) { _writer.WriteStartElement("ExpressionBinding"); if (expr.EnumerateCollection) diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormattingObjectsDeserializer.cs b/src/System.Management.Automation/FormatAndOutput/common/FormattingObjectsDeserializer.cs index f26a20ae6a9..00923a103ec 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormattingObjectsDeserializer.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormattingObjectsDeserializer.cs @@ -30,8 +30,7 @@ internal FormatObjectDeserializer(TerminatingErrorContext errorContext) internal bool IsFormatInfoData(PSObject so) { - var fid = PSObject.Base(so) as FormatInfoData; - if (fid != null) + if (PSObject.Base(so) is FormatInfoData fid) { if (fid is FormatStartData || fid is FormatEndData || @@ -86,8 +85,7 @@ fid is GroupEndData || /// Deserialized object or null. internal object Deserialize(PSObject so) { - var fid = PSObject.Base(so) as FormatInfoData; - if (fid != null) + if (PSObject.Base(so) is FormatInfoData fid) { if (fid is FormatStartData || fid is FormatEndData || diff --git a/src/System.Management.Automation/FormatAndOutput/common/OutputQueue.cs b/src/System.Management.Automation/FormatAndOutput/common/OutputQueue.cs index 1909b03939c..333b0b42689 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/OutputQueue.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/OutputQueue.cs @@ -43,8 +43,7 @@ internal OutputGroupQueue(FormattedObjectsCache.ProcessCachedGroupNotification c /// Objects the cache needs to return. It can be null. internal List Add(PacketInfoData o) { - FormatStartData fsd = o as FormatStartData; - if (fsd != null) + if (o is FormatStartData fsd) { // just cache the reference (used during the notification call) _formatStartData = fsd; @@ -120,12 +119,10 @@ private void UpdateObjectCount(PacketInfoData o) { // add only of it's not a control message // and it's not out of band - FormatEntryData fed = o as FormatEntryData; - - if (fed == null || fed.outOfBand) - return; - - _currentObjectCount++; + if (o is FormatEntryData fed && !fed.outOfBand) + { + _currentObjectCount++; + } } private void Notify() @@ -139,8 +136,7 @@ private void Notify() foreach (PacketInfoData x in _queue) { - FormatEntryData fed = x as FormatEntryData; - if (fed != null && fed.outOfBand) + if (x is FormatEntryData fed && fed.outOfBand) continue; validObjects.Add(x); diff --git a/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshObjectUtil.cs b/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshObjectUtil.cs index ce3590520a5..ea200bcb5f5 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshObjectUtil.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshObjectUtil.cs @@ -121,8 +121,7 @@ internal static PSPropertyExpressionResult GetDisplayName(PSObject target, PSPro /// Object to extract the IEnumerable from. internal static IEnumerable GetEnumerable(object obj) { - PSObject mshObj = obj as PSObject; - if (mshObj != null) + if (obj is PSObject mshObj) { obj = mshObj.BaseObject; } @@ -228,8 +227,7 @@ internal static string SmartToString(PSObject so, PSPropertyExpressionFactory ex IEnumerator enumerator = e.GetEnumerator(); if (enumerator != null) { - IBlockingEnumerator be = enumerator as IBlockingEnumerator; - if (be != null) + if (enumerator is IBlockingEnumerator be) { while (be.MoveNext(false)) { @@ -418,22 +416,18 @@ private static PSMemberSet MaskDeserializedAndGetStandardMembers(PSObject so) private static List GetDefaultPropertySet(PSMemberSet standardMembersSet) { - if (standardMembersSet != null) + if (standardMembersSet != null && standardMembersSet.Members[TypeTable.DefaultDisplayPropertySet] is PSPropertySet defaultDisplayPropertySet) { - PSPropertySet defaultDisplayPropertySet = standardMembersSet.Members[TypeTable.DefaultDisplayPropertySet] as PSPropertySet; - if (defaultDisplayPropertySet != null) + List retVal = new List(); + foreach (string prop in defaultDisplayPropertySet.ReferencedPropertyNames) { - List retVal = new List(); - foreach (string prop in defaultDisplayPropertySet.ReferencedPropertyNames) + if (!string.IsNullOrEmpty(prop)) { - if (!string.IsNullOrEmpty(prop)) - { - retVal.Add(new PSPropertyExpression(prop)); - } + retVal.Add(new PSPropertyExpression(prop)); } - - return retVal; } + + return retVal; } return new List(); @@ -457,21 +451,17 @@ internal static List GetDefaultPropertySet(PSObject so) private static PSPropertyExpression GetDefaultNameExpression(PSMemberSet standardMembersSet) { - if (standardMembersSet != null) + if (standardMembersSet != null && standardMembersSet.Members[TypeTable.DefaultDisplayProperty] is PSNoteProperty defaultDisplayProperty) { - PSNoteProperty defaultDisplayProperty = standardMembersSet.Members[TypeTable.DefaultDisplayProperty] as PSNoteProperty; - if (defaultDisplayProperty != null) + string expressionString = defaultDisplayProperty.Value.ToString(); + if (string.IsNullOrEmpty(expressionString)) { - string expressionString = defaultDisplayProperty.Value.ToString(); - if (string.IsNullOrEmpty(expressionString)) - { - // invalid data, the PSObject is empty - return null; - } - else - { - return new PSPropertyExpression(expressionString); - } + // invalid data, the PSObject is empty + return null; + } + else + { + return new PSPropertyExpression(expressionString); } } diff --git a/src/System.Management.Automation/FormatAndOutput/common/Utilities/Mshexpression.cs b/src/System.Management.Automation/FormatAndOutput/common/Utilities/Mshexpression.cs index 9a675824e59..552d511fd4e 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/Utilities/Mshexpression.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/Utilities/Mshexpression.cs @@ -215,8 +215,7 @@ public List ResolveNames(PSObject target, bool expand) foreach (PSMemberInfo member in members) { // it can be a property set - PSPropertySet propertySet = member as PSPropertySet; - if (propertySet != null) + if (member is PSPropertySet propertySet) { if (expand) { diff --git a/src/System.Management.Automation/FormatAndOutput/out-console/OutConsole.cs b/src/System.Management.Automation/FormatAndOutput/out-console/OutConsole.cs index 8d51f42de8c..8629afe87a6 100644 --- a/src/System.Management.Automation/FormatAndOutput/out-console/OutConsole.cs +++ b/src/System.Management.Automation/FormatAndOutput/out-console/OutConsole.cs @@ -69,9 +69,7 @@ protected override void BeginProcessing() ((OutputManagerInner)this.implementation).LineOutput = lineOutput; - MshCommandRuntime mrt = this.CommandRuntime as MshCommandRuntime; - - if (mrt != null) + if (this.CommandRuntime is MshCommandRuntime mrt) { mrt.MergeUnclaimedPreviousErrorResults = true; } From 21555584f32f1c53cb823e5de769ef1667692fd4 Mon Sep 17 00:00:00 2001 From: PowerShell Team Bot <69177312+pwshBot@users.noreply.github.com> Date: Tue, 11 Jul 2023 09:55:50 -0700 Subject: [PATCH 637/779] Update the cgmanifest (#19924) --- tools/cgmanifest.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/cgmanifest.json b/tools/cgmanifest.json index 7686a5581fb..d611becf352 100644 --- a/tools/cgmanifest.json +++ b/tools/cgmanifest.json @@ -56,7 +56,7 @@ "Type": "nuget", "Nuget": { "Name": "JsonSchema.Net", - "Version": "4.1.5" + "Version": "4.1.6" } }, "DevelopmentDependency": false From a8ec19b4f63f771895a70e434416320ea3877635 Mon Sep 17 00:00:00 2001 From: MartinGC94 <42123497+MartinGC94@users.noreply.github.com> Date: Tue, 11 Jul 2023 21:12:32 +0200 Subject: [PATCH 638/779] Fix completion regression for filesystem paths with custom `PSDrive` names (#19921) --- .../CommandCompletion/CompletionCompleters.cs | 24 ++++++++++++++++--- .../TabCompletion/TabCompletion.Tests.ps1 | 7 ++++++ 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs index e4fb1044858..200eebbed32 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs @@ -4618,9 +4618,27 @@ private static List GetFileSystemProviderResults( string basePath; if (!relativePaths) { - basePath = dirInfo.FullName.EndsWith(provider.ItemSeparator) - ? providerPrefix + dirInfo.FullName - : providerPrefix + dirInfo.FullName + provider.ItemSeparator; + string providerName = $"{provider.ModuleName}\\{provider.Name}::"; + if (pathInfo.Path.StartsWith(providerName, StringComparison.OrdinalIgnoreCase)) + { + basePath = pathInfo.Path.Substring(providerName.Length); + } + else + { + providerName = $"{provider.Name}::"; + if (pathInfo.Path.StartsWith(providerName, StringComparison.OrdinalIgnoreCase)) + { + basePath = pathInfo.Path.Substring(providerName.Length); + } + else + { + basePath = pathInfo.Path; + } + } + + basePath = basePath.EndsWith(provider.ItemSeparator) + ? providerPrefix + basePath + : providerPrefix + basePath + provider.ItemSeparator; basePath = RebuildPathWithVars(basePath, homePath, stringType, literalPaths, out baseQuotesNeeded); } else diff --git a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 index 9e50e10f623..b2072345d91 100644 --- a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 +++ b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 @@ -1260,6 +1260,13 @@ class InheritedClassTest : System.Attribute } } + It 'Should keep custom drive names when completing file paths' { + $TempDriveName = "asdf" + $null = New-PSDrive -Name $TempDriveName -PSProvider FileSystem -Root $HOME + (TabExpansion2 -inputScript "${TempDriveName}:\").CompletionMatches[0].CompletionText | Should -BeLike "${TempDriveName}:*" + Remove-PSDrive -Name $TempDriveName + } + Context "Cmdlet name completion" { BeforeAll { $testCases = @( From 427e519af29a260097c17f0ec956dfe10fe128e9 Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Tue, 11 Jul 2023 16:33:07 -0700 Subject: [PATCH 639/779] Update the link for getting started in `README.md` (#19932) --- README.md | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 76277ae9858..740f67aac99 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ It includes a command-line shell, an associated scripting language and a framewo ## Windows PowerShell vs. PowerShell Core -Although this repository started as a fork of the Windows PowerShell code base, changes made in this repository do not make their way back to Windows PowerShell 5.1 automatically. +Although this repository started as a fork of the Windows PowerShell codebase, changes made in this repository do not make their way back to Windows PowerShell 5.1 automatically. This also means that [issues tracked here][issues] are only for PowerShell Core 6 and higher. Windows PowerShell specific issues should be reported with the [Feedback Hub app][feedback-hub], by choosing "Apps > PowerShell" in category. @@ -20,7 +20,7 @@ Windows PowerShell specific issues should be reported with the [Feedback Hub app If you are new to PowerShell and would like to learn more, we recommend reviewing the [getting started][] documentation. -[getting started]: https://github.com/PowerShell/PowerShell/tree/master/docs/learning-powershell +[getting started]: https://learn.microsoft.com/powershell/scripting/learn/more-powershell-learning ## Get PowerShell @@ -34,7 +34,7 @@ You can download and install a PowerShell package for any of the following platf | [Ubuntu 20.04][corefx-linux] | [.deb][lts-deb] | [.deb][rl-ubuntu20] | [.deb][pv-deb] | [Instructions][in-ubuntu20] | | [Ubuntu 18.04][corefx-linux] | [.deb][lts-deb] | [.deb][rl-ubuntu18] | [.deb][pv-deb] | [Instructions][in-ubuntu18] | | [Ubuntu 16.04][corefx-linux] | [.deb][lts-deb] | N/A | N/A | [Instructions][in-ubuntu16] | -| [Debian 10][corefx-linux] | [.deb][lts-deb] | [.deb][rl-debian10] | [.deb][pv-deb] | [Instructions][in-deb9] | +| [Debian 10][corefx-linux] | [.deb][lts-deb] | [.deb][rl-debian10] | [.deb][pv-deb] | [Instructions][in-deb10] | | [Debian 11][corefx-linux] | [.deb][lts-deb] | [.deb][rl-debian11] | [.deb][pv-deb] | | | [CentOS 7][corefx-linux] | [.rpm][lts-rh] | [.rpm][rl-centos] | [.rpm][pv-rpm] | [Instructions][in-centos] | | [CentOS 8][corefx-linux] | [.rpm][lts-rh] | [.rpm][rl-centos8] | [.rpm][pv-rpm] | | @@ -114,7 +114,6 @@ You can also download the PowerShell binary archives for Windows, macOS and Linu [in-ubuntu18]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-linux#ubuntu-1804 [in-ubuntu20]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-linux#ubuntu-2004 [in-ubuntu22]: https://learn.microsoft.com/powershell/scripting/install/installing-powershell-on-linux?view=powershell-7.3#ubuntu -[in-deb9]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-linux#debian-9 [in-deb10]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-linux#debian-10 [in-centos]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-linux#centos-7 [in-rhel7]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-linux#red-hat-enterprise-linux-rhel-7 From 30098c744adb52ea14f29f03897487fecc1dc4f0 Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Wed, 12 Jul 2023 11:47:24 -0700 Subject: [PATCH 640/779] Add `Microsoft.Powershell.PSResourceGet` for telemetry module list (#19926) --- src/System.Management.Automation/utils/Telemetry.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/System.Management.Automation/utils/Telemetry.cs b/src/System.Management.Automation/utils/Telemetry.cs index 88193cc03a9..a1c3d324b5d 100644 --- a/src/System.Management.Automation/utils/Telemetry.cs +++ b/src/System.Management.Automation/utils/Telemetry.cs @@ -444,6 +444,7 @@ static ApplicationInsightsTelemetry() "Microsoft.PowerShell.Management", "Microsoft.PowerShell.ODataUtils", "Microsoft.PowerShell.Operation.Validation", + "Microsoft.PowerShell.PSResourceGet", "Microsoft.PowerShell.RemotingTools", "Microsoft.PowerShell.SecretManagement", "Microsoft.PowerShell.SecretStore", @@ -806,7 +807,7 @@ internal static void SendPSCoreStartupTelemetry(string mode, double parametersUs // This is the payload for the parameter data which is sent as a metric. var parameters = new Dictionary(); - // The variable POWERSHELL_DISTRIBUTION_CHANNEL is set in our docker images and + // The variable POWERSHELL_DISTRIBUTION_CHANNEL is set in our docker images and // by various other environments. This allows us to track the actual docker OS as // OSDescription provides only "linuxkit" which has limited usefulness. var channel = Environment.GetEnvironmentVariable("POWERSHELL_DISTRIBUTION_CHANNEL"); @@ -900,7 +901,7 @@ private static Guid CreateUniqueIdentifierAndFile(string telemetryFilePath) catch { // There was a problem in creating the directory for the file, do not attempt to create the file. - // We don't send telemetry here because there are valid reasons for the directory to not exist + // We don't send telemetry here because there are valid reasons for the directory to not exist // and not be able to be created. attemptFileCreation = false; } From c95a8e43ee1413beb941e9e8dc4210e77e719ed7 Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Wed, 12 Jul 2023 14:33:00 -0700 Subject: [PATCH 641/779] Change variable used to bypass nuget security scanning (#19954) --- tools/releaseBuild/azureDevOps/compliance.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tools/releaseBuild/azureDevOps/compliance.yml b/tools/releaseBuild/azureDevOps/compliance.yml index 43ef005402b..57c29194de6 100644 --- a/tools/releaseBuild/azureDevOps/compliance.yml +++ b/tools/releaseBuild/azureDevOps/compliance.yml @@ -24,6 +24,8 @@ variables: value: 1 - name: POWERSHELL_TELEMETRY_OPTOUT value: 1 + - name: nugetMultiFeedWarnLevel + value: none - name: NugetSecurityAnalysisWarningLevel value: none # Defines the variables AzureFileCopySubscription, StorageAccount, StorageAccountKey, StorageResourceGroup, StorageSubscriptionName From 8acad1fd42600bf757e67b8799c8a9a8b700f7d0 Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Wed, 12 Jul 2023 14:45:14 -0700 Subject: [PATCH 642/779] Don't publish notice on failure because it prevent retry (#19955) --- .../azureDevOps/templates/compliance/generateNotice.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/tools/releaseBuild/azureDevOps/templates/compliance/generateNotice.yml b/tools/releaseBuild/azureDevOps/templates/compliance/generateNotice.yml index 45bb52ae9c7..3e91b9174d2 100644 --- a/tools/releaseBuild/azureDevOps/templates/compliance/generateNotice.yml +++ b/tools/releaseBuild/azureDevOps/templates/compliance/generateNotice.yml @@ -87,5 +87,4 @@ jobs: targetPath: $(System.ArtifactsDirectory) artifactName: notice displayName: Publish notice artifacts - condition: always() retryCountOnTaskFailure: 2 From b58ff3b8eae8d8a2ea25f510535dc3ce86589bb9 Mon Sep 17 00:00:00 2001 From: Sean Wheeler Date: Wed, 12 Jul 2023 22:16:57 -0500 Subject: [PATCH 643/779] Fix ///-comments that violate the docs schema (#19957) --- .../ReadOnlyObservableAsyncCollection.cs | 4 +- .../ManagementList/Common/ScalableImage.cs | 2 +- .../ManagementList/Innerlist.cs | 2 +- .../commands/utility/MatchString.cs | 8 +- .../engine/Attributes.cs | 12 +- .../engine/CommandInfo.cs | 22 +- .../engine/ErrorPackage.cs | 16 +- .../engine/ProgressRecord.cs | 18 +- .../engine/cmdlet.cs | 8 +- .../engine/hostifaces/ChoiceDescription.cs | 4 +- .../engine/hostifaces/Connection.cs | 9 +- .../engine/hostifaces/FieldDescription.cs | 12 +- .../hostifaces/MshHostRawUserInterface.cs | 2 +- .../engine/hostifaces/MshHostUserInterface.cs | 18 +- .../engine/lang/interface/PSToken.cs | 190 +++++++++++------- .../engine/parser/PreOrderVisitor.cs | 2 +- .../engine/parser/ast.cs | 4 +- .../engine/parser/token.cs | 6 +- .../ProviderDeclarationAttribute.cs | 40 ++-- .../utils/StructuredTraceSource.cs | 31 +-- 20 files changed, 228 insertions(+), 182 deletions(-) diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/ReadOnlyObservableAsyncCollection.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/ReadOnlyObservableAsyncCollection.cs index 7734bc4903c..99f08931aa4 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/ReadOnlyObservableAsyncCollection.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/ReadOnlyObservableAsyncCollection.cs @@ -44,7 +44,7 @@ public ReadOnlyObservableAsyncCollection(IList list) /// Occurs when the collection changes, either by adding or removing an item. /// /// - /// see + /// see /// public event NotifyCollectionChangedEventHandler CollectionChanged; @@ -52,7 +52,7 @@ public ReadOnlyObservableAsyncCollection(IList list) /// Occurs when a property changes. /// /// - /// see + /// see /// public event PropertyChangedEventHandler PropertyChanged; #endregion Events diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/ScalableImage.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/ScalableImage.cs index b994bb1a29a..ea5f91adc87 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/ScalableImage.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/ScalableImage.cs @@ -75,7 +75,7 @@ protected override void OnRender(DrawingContext drawingContext) } /// - /// Override of . + /// Override of . /// Make this control to respect the ClipToBounds attribute value. /// /// An instance of used for calculating an additional clip. diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/Innerlist.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/Innerlist.cs index a970a5290e5..aa945a1d90c 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/Innerlist.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/Innerlist.cs @@ -93,7 +93,7 @@ public InnerList() /// /// Gets ItemsSource instead. - /// Does not support adding to Items. + /// Does not support adding to Items. /// [Browsable(false)] public new ItemCollection Items diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs index 9b9fe1aff13..a149c1b10ee 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs @@ -127,11 +127,11 @@ public MatchInfo(IReadOnlyList matchIndexes, IReadOnlyList matchLength /// /// Gets the base name of the file containing the matching line. + /// /// /// It will be the string "InputStream" if the object came from the input stream. /// This is a readonly property calculated from the path . /// - /// /// The file name. public string Filename { @@ -150,10 +150,10 @@ public string Filename /// /// Gets or sets the full path of the file containing the matching line. + /// /// /// It will be "InputStream" if the object came from the input stream. /// - /// /// The path name. public string Path { @@ -182,11 +182,11 @@ public string Path /// /// Returns the path of the matching file truncated relative to the parameter. + /// /// /// For example, if the matching path was c:\foo\bar\baz.c and the directory argument was c:\foo /// the routine would return bar\baz.c . /// - /// /// The directory base the truncation on. /// The relative path that was produced. public string RelativePath(string directory) @@ -232,12 +232,12 @@ public string RelativePath(string directory) /// /// Returns the string representation of this object. The format /// depends on whether a path has been set for this object or not. + /// /// /// If the path component is set, as would be the case when matching /// in a file, ToString() would return the path, line number and line text. /// If path is not set, then just the line text is presented. /// - /// /// The string representation of the match object. public override string ToString() { diff --git a/src/System.Management.Automation/engine/Attributes.cs b/src/System.Management.Automation/engine/Attributes.cs index 3e4d848faa2..9e698c05174 100644 --- a/src/System.Management.Automation/engine/Attributes.cs +++ b/src/System.Management.Automation/engine/Attributes.cs @@ -1356,11 +1356,11 @@ public sealed class ValidatePatternAttribute : ValidateEnumeratedArgumentsAttrib /// Gets or sets the custom error message pattern that is displayed to the user. /// The text representation of the object being validated and the validating regex is passed as /// the first and second formatting parameters to the ErrorMessage formatting pattern. - /// + /// /// /// [ValidatePattern("\s+", ErrorMessage="The text '{0}' did not pass validation of regex '{1}'")] /// - /// + /// /// public string ErrorMessage { get; set; } @@ -1422,11 +1422,11 @@ public sealed class ValidateScriptAttribute : ValidateEnumeratedArgumentsAttribu /// Gets or sets the custom error message that is displayed to the user. /// The item being validated and the validating scriptblock is passed as the first and second /// formatting argument. - /// + /// /// /// [ValidateScript("$_ % 2", ErrorMessage = "The item '{0}' did not pass validation of script '{1}'")] /// - /// + /// /// public string ErrorMessage { get; set; } @@ -1687,11 +1687,11 @@ public sealed class ValidateSetAttribute : ValidateEnumeratedArgumentsAttribute /// Gets or sets the custom error message that is displayed to the user. /// The item being validated and a text representation of the validation set is passed as the /// first and second formatting argument to the formatting pattern. - /// + /// /// /// [ValidateSet("A","B","C", ErrorMessage="The item '{0}' is not part of the set '{1}'.") /// - /// + /// /// public string ErrorMessage { get; set; } diff --git a/src/System.Management.Automation/engine/CommandInfo.cs b/src/System.Management.Automation/engine/CommandInfo.cs index 6b90b1d1640..eb5fbf70f3b 100644 --- a/src/System.Management.Automation/engine/CommandInfo.cs +++ b/src/System.Management.Automation/engine/CommandInfo.cs @@ -24,26 +24,20 @@ public enum CommandTypes { /// /// Aliases create a name that refers to other command types. - /// - /// /// Aliases are only persisted within the execution of a single engine. - /// + /// Alias = 0x0001, /// /// Script functions that are defined by a script block. - /// - /// /// Functions are only persisted within the execution of a single engine. - /// + /// Function = 0x0002, /// /// Script filters that are defined by a script block. - /// - /// /// Filters are only persisted within the execution of a single engine. - /// + /// Filter = 0x0004, /// @@ -58,11 +52,9 @@ public enum CommandTypes /// /// Any existing application (can be console or GUI). - /// - /// /// An application can have any extension that can be executed either directly through CreateProcess /// or indirectly through ShellExecute. - /// + /// Application = 0x0020, /// @@ -77,11 +69,9 @@ public enum CommandTypes /// /// All possible command types. + /// NOTE: a CommandInfo instance will never specify All as its CommandType + /// but All can be used when filtering the CommandTypes. /// - /// - /// Note, a CommandInfo instance will never specify - /// All as its CommandType but All can be used when filtering the CommandTypes. - /// All = Alias | Function | Filter | Cmdlet | Script | ExternalScript | Application | Configuration, } diff --git a/src/System.Management.Automation/engine/ErrorPackage.cs b/src/System.Management.Automation/engine/ErrorPackage.cs index 2bca96372a7..8eeec501031 100644 --- a/src/System.Management.Automation/engine/ErrorPackage.cs +++ b/src/System.Management.Automation/engine/ErrorPackage.cs @@ -28,13 +28,15 @@ namespace System.Management.Automation public enum ErrorCategory { /// + /// /// No error category is specified, or the error category is invalid. - /// - /// + /// + /// /// Do not specify ErrorCategory.NotSpecified when creating an /// . /// Choose the best match from among the other values. - /// + /// + /// NotSpecified = 0, /// @@ -132,14 +134,16 @@ public enum ErrorCategory WriteError = 23, /// + /// /// A native command reported an error to its STDERR pipe. - /// - /// + /// + /// /// The Engine uses this ErrorCategory when it executes a native /// console applications and captures the errors reported by the /// native application. Avoid using ErrorCategory.FromStdErr /// in other circumstances. - /// + /// + /// FromStdErr = 24, /// diff --git a/src/System.Management.Automation/engine/ProgressRecord.cs b/src/System.Management.Automation/engine/ProgressRecord.cs index 7e45e022ab2..4319d78f042 100644 --- a/src/System.Management.Automation/engine/ProgressRecord.cs +++ b/src/System.Management.Automation/engine/ProgressRecord.cs @@ -505,7 +505,7 @@ internal PSObject ToPSObjectForRemoting() string activity = string.IsNullOrEmpty(Activity) ? " " : Activity; PSObject progressAsPSObject = RemotingEncoder.CreateEmptyPSObject(); - + progressAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.ProgressRecord_Activity, activity)); progressAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.ProgressRecord_ActivityId, this.ActivityId)); progressAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.ProgressRecord_StatusDescription, this.StatusDescription)); @@ -529,9 +529,10 @@ internal PSObject ToPSObjectForRemoting() enum ProgressRecordType { /// + /// /// Operation just started or is not yet complete. - /// - /// + /// + /// /// A cmdlet can call WriteProgress with ProgressRecordType.Processing /// as many times as it wishes. However, at the end of the operation, /// it should call once more with ProgressRecordType.Completed. @@ -542,17 +543,20 @@ enum ProgressRecordType /// of the same Id, the host will update that display. /// Finally, when the host receives a 'completed' record /// for that activity, it will remove the progress indicator. - /// + /// + /// Processing, /// + /// /// Operation is complete. - /// - /// + /// + /// /// If a cmdlet uses WriteProgress, it should use /// ProgressRecordType.Completed exactly once, in the last call /// to WriteProgress. - /// + /// + /// Completed } } diff --git a/src/System.Management.Automation/engine/cmdlet.cs b/src/System.Management.Automation/engine/cmdlet.cs index 2f60c95ee47..b2b63d364b5 100644 --- a/src/System.Management.Automation/engine/cmdlet.cs +++ b/src/System.Management.Automation/engine/cmdlet.cs @@ -1820,14 +1820,16 @@ public enum ShouldProcessReason None = 0x0, /// + /// /// WhatIf behavior was requested. - /// - /// + /// + /// /// In the host, WhatIf behavior can be requested explicitly /// for one cmdlet instance using the -WhatIf commandline parameter, /// or implicitly for all SupportsShouldProcess cmdlets with $WhatIfPreference. /// Other hosts may have other ways to request WhatIf behavior. - /// + /// + /// WhatIf = 0x1, } } diff --git a/src/System.Management.Automation/engine/hostifaces/ChoiceDescription.cs b/src/System.Management.Automation/engine/hostifaces/ChoiceDescription.cs index 4c7c3e65b2b..0cac1d02b6f 100644 --- a/src/System.Management.Automation/engine/hostifaces/ChoiceDescription.cs +++ b/src/System.Management.Automation/engine/hostifaces/ChoiceDescription.cs @@ -6,7 +6,7 @@ namespace System.Management.Automation.Host { /// - /// Provides a description of a choice for use by . + /// Provides a description of a choice for use by . /// /// public sealed @@ -84,7 +84,7 @@ class ChoiceDescription /// /// Note that the special character & (ampersand) may be embedded in the label string to identify the next character in the label /// as a "hot key" (aka "keyboard accelerator") that the Console.PromptForChoice implementation may use to allow the user to - /// quickly set input focus to this choice. The implementation of + /// quickly set input focus to this choice. The implementation of /// is responsible for parsing the label string for this special character and rendering it accordingly. /// /// For examples, a choice named "Yes to All" might have "Yes to &All" as it's label. diff --git a/src/System.Management.Automation/engine/hostifaces/Connection.cs b/src/System.Management.Automation/engine/hostifaces/Connection.cs index 5f0f8e036db..3f5911d1c62 100644 --- a/src/System.Management.Automation/engine/hostifaces/Connection.cs +++ b/src/System.Management.Automation/engine/hostifaces/Connection.cs @@ -95,7 +95,7 @@ RunspaceState expectedState /// The that contains contextual information /// about the source or destination. /// - [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected InvalidRunspaceStateException(SerializationInfo info, StreamingContext context) { throw new NotSupportedException(); @@ -219,12 +219,9 @@ public enum PSThreadOptions ReuseThread = 2, /// - /// Doesn't create a new thread; the execution occurs on the - /// thread that calls Invoke. + /// Doesn't create a new thread; the execution occurs on the thread + /// that calls Invoke. This option is not valid for asynchronous calls. /// - /// - /// This option is not valid for asynchronous calls - /// UseCurrentThread = 3 } diff --git a/src/System.Management.Automation/engine/hostifaces/FieldDescription.cs b/src/System.Management.Automation/engine/hostifaces/FieldDescription.cs index b8a0793a5f6..541b1607df0 100644 --- a/src/System.Management.Automation/engine/hostifaces/FieldDescription.cs +++ b/src/System.Management.Automation/engine/hostifaces/FieldDescription.cs @@ -165,7 +165,7 @@ public string Name /// /// A short, human-presentable message to describe and identify the field. If supplied, a typical implementation of - /// will use this value instead of + /// will use this value instead of /// the field name to identify the field to the user. /// /// @@ -174,9 +174,9 @@ public string Name /// /// Note that the special character & (ampersand) may be embedded in the label string to identify the next /// character in the label as a "hot key" (aka "keyboard accelerator") that the - /// implementation may use + /// implementation may use /// to allow the user to quickly set input focus to this field. The implementation of - /// is responsible for parsing + /// is responsible for parsing /// the label string for this special character and rendering it accordingly. /// /// For example, a field named "SSN" might have "&Social Security Number" as it's label. @@ -256,12 +256,12 @@ public string Name } /// - /// Gets and sets the default value, if any, for the implementation of + /// Gets and sets the default value, if any, for the implementation of /// to pre-populate its UI with. This is a PSObject instance so that the value can be serialized, converted, /// manipulated like any pipeline object. /// /// - /// It is up to the implementer of to decide if it + /// It is up to the implementer of to decide if it /// can make use of the object in its presentation of the fields prompt. /// /// @@ -283,7 +283,7 @@ public string Name } /// - /// Gets the Attribute classes that apply to the field. In the case that + /// Gets the Attribute classes that apply to the field. In the case that /// is being called from the engine, this will contain the set of prompting attributes that are attached to a /// cmdlet parameter declaration. /// diff --git a/src/System.Management.Automation/engine/hostifaces/MshHostRawUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/MshHostRawUserInterface.cs index c7e1b2ce849..201caf3c827 100644 --- a/src/System.Management.Automation/engine/hostifaces/MshHostRawUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/MshHostRawUserInterface.cs @@ -1784,7 +1784,7 @@ char source /// /// Creates a 2D array of BufferCells by examining .Character. - /// + /// /// /// /// The number of columns of the resulting array diff --git a/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs index ddc6fce782d..29fc5fa1f7f 100644 --- a/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs @@ -112,10 +112,10 @@ public abstract System.Management.Automation.Host.PSHostRawUserInterface RawUI /// /// The default implementation writes a carriage return to the screen buffer. - /// - /// - /// - /// + /// + /// + /// + /// /// public virtual void WriteLine() { @@ -170,10 +170,10 @@ public virtual void WriteLine(ConsoleColor foregroundColor, ConsoleColor backgro /// /// Writes a line to the "error display" of the host, as opposed to the "output display," which is /// written to by the variants of - /// - /// - /// and - /// + /// + /// + /// and + /// /// /// /// The characters to be written. @@ -314,7 +314,7 @@ public static string GetFormatStyleString(FormatStyle formatStyle) return string.Empty; } - PSStyle psstyle = PSStyle.Instance; + PSStyle psstyle = PSStyle.Instance; switch (formatStyle) { case FormatStyle.Reset: diff --git a/src/System.Management.Automation/engine/lang/interface/PSToken.cs b/src/System.Management.Automation/engine/lang/interface/PSToken.cs index 048de2facac..306a64a0b61 100644 --- a/src/System.Management.Automation/engine/lang/interface/PSToken.cs +++ b/src/System.Management.Automation/engine/lang/interface/PSToken.cs @@ -370,223 +370,275 @@ public enum PSTokenType /// /// Unknown token. /// - /// - /// Unknown, /// + /// /// Command. - /// - /// + /// + /// /// For example, 'get-process' in /// - /// get-process -name foo - /// + /// get-process -name foo + /// + /// Command, /// + /// /// Command Parameter. - /// - /// + /// + /// /// For example, '-name' in /// - /// get-process -name foo - /// + /// get-process -name foo + /// + /// CommandParameter, /// + /// /// Command Argument. - /// - /// + /// + /// /// For example, 'foo' in /// - /// get-process -name foo - /// + /// get-process -name foo + /// + /// CommandArgument, /// + /// /// Number. - /// - /// + /// + /// /// For example, 12 in /// - /// $a=12 - /// + /// $a=12 + /// + /// Number, /// + /// /// String. - /// - /// + /// + /// /// For example, "12" in /// - /// $a="12" - /// + /// $a="12" + /// + /// String, /// + /// /// Variable. - /// + /// + /// /// /// For example, $a in /// - /// $a="12" - /// + /// $a="12" + /// + /// Variable, /// + /// /// Property name or method name. - /// - /// + /// + /// /// For example, Name in /// - /// $a.Name - /// + /// $a.Name + /// + /// Member, /// + /// /// Loop label. - /// - /// + /// + /// /// For example, :loop in /// + /// /// :loop /// foreach($a in $b) /// { /// $a /// } - /// + /// + /// LoopLabel, /// + /// /// Attributes. - /// - /// + /// + /// /// For example, Mandatory in /// - /// param([Mandatory] $a) - /// + /// param([Mandatory] $a) + /// + /// Attribute, /// + /// /// Types. - /// - /// + /// + /// /// For example, [string] in /// - /// $a = [string] 12 - /// + /// $a = [string] 12 + /// + /// Type, /// + /// /// Operators. - /// - /// + /// + /// /// For example, + in /// - /// $a = 1 + 2 - /// + /// $a = 1 + 2 + /// + /// Operator, /// + /// /// Group Starter. - /// - /// + /// + /// /// For example, { in /// + /// /// if ($a -gt 4) /// { /// $a++; /// } - /// + /// + /// + /// GroupStart, /// + /// /// Group Ender. - /// - /// + /// + /// /// For example, } in /// + /// /// if ($a -gt 4) /// { /// $a++; /// } - /// + /// + /// + /// GroupEnd, /// + /// /// Keyword. - /// - /// + /// + /// /// For example, if in /// + /// /// if ($a -gt 4) /// { /// $a++; /// } - /// + /// + /// + /// Keyword, /// + /// /// Comment. - /// - /// + /// + /// /// For example, #here in /// + /// /// #here /// if ($a -gt 4) /// { /// $a++; /// } - /// + /// + /// + /// Comment, /// + /// /// Statement separator. This is ';' - /// - /// + /// + /// /// For example, ; in /// + /// /// #here /// if ($a -gt 4) /// { /// $a++; /// } - /// + /// + /// + /// StatementSeparator, /// + /// /// New line. This is '\n' - /// - /// + /// + /// /// For example, \n in /// + /// /// #here /// if ($a -gt 4) /// { /// $a++; /// } - /// + /// + /// + /// NewLine, /// + /// /// Line continuation. - /// - /// + /// + /// /// For example, ` in /// + /// /// get-command -name ` /// foo - /// + /// + /// + /// LineContinuation, /// + /// /// Position token. - /// - /// - /// Position token are bogus tokens generated for identifying a location + /// + /// + /// Position tokens are bogus tokens generated for identifying a location /// in the script. - /// + /// + /// Position } } diff --git a/src/System.Management.Automation/engine/parser/PreOrderVisitor.cs b/src/System.Management.Automation/engine/parser/PreOrderVisitor.cs index 91c0c6247e9..675e53394c6 100644 --- a/src/System.Management.Automation/engine/parser/PreOrderVisitor.cs +++ b/src/System.Management.Automation/engine/parser/PreOrderVisitor.cs @@ -6,7 +6,7 @@ namespace System.Management.Automation.Language { /// - /// Each Visit* method in returns one of these values to control + /// Each Visit* method in returns one of these values to control /// how visiting nodes in the AST should proceed. /// public enum AstVisitAction diff --git a/src/System.Management.Automation/engine/parser/ast.cs b/src/System.Management.Automation/engine/parser/ast.cs index a4138a502ed..5222f2f53ba 100644 --- a/src/System.Management.Automation/engine/parser/ast.cs +++ b/src/System.Management.Automation/engine/parser/ast.cs @@ -6038,8 +6038,8 @@ public CommandAst(IScriptExtent extent, /// Returns the name of the command invoked by this ast. /// This command name may not be known statically, in which case null is returned. /// - /// For example, if the command name is in a variable: & $foo, then the parser cannot know which command is executed. - /// Similarly, if the command is being invoked in a module: & (gmo SomeModule) Bar, then the parser does not know the + /// For example, if the command name is in a variable: & $foo, then the parser cannot know which command is executed. + /// Similarly, if the command is being invoked in a module: & (gmo SomeModule) Bar, then the parser does not know the /// command name is Bar because the parser can't determine that the expression (gmo SomeModule) returns a module instead /// of a string. /// diff --git a/src/System.Management.Automation/engine/parser/token.cs b/src/System.Management.Automation/engine/parser/token.cs index 2d71602fca0..3cee7580ff9 100644 --- a/src/System.Management.Automation/engine/parser/token.cs +++ b/src/System.Management.Automation/engine/parser/token.cs @@ -1180,7 +1180,7 @@ static TokenTraits() #endif /// - /// Return all the flags for a given TokenKind. + /// Return all the flags for a given . /// public static TokenFlags GetTraits(this TokenKind kind) { @@ -1188,7 +1188,7 @@ public static TokenFlags GetTraits(this TokenKind kind) } /// - /// Return true if the TokenKind has the given trait. + /// Return true if the has the given trait. /// public static bool HasTrait(this TokenKind kind, TokenFlags flag) { @@ -1202,7 +1202,7 @@ internal static int GetBinaryPrecedence(this TokenKind kind) } /// - /// Return the text for a given TokenKind. + /// Return the text for a given . /// public static string Text(this TokenKind kind) { diff --git a/src/System.Management.Automation/namespaces/ProviderDeclarationAttribute.cs b/src/System.Management.Automation/namespaces/ProviderDeclarationAttribute.cs index 0601adce6be..cd38b92c177 100644 --- a/src/System.Management.Automation/namespaces/ProviderDeclarationAttribute.cs +++ b/src/System.Management.Automation/namespaces/ProviderDeclarationAttribute.cs @@ -82,50 +82,58 @@ public enum ProviderCapabilities None = 0x0, /// + /// /// The provider does the inclusion filtering for those commands that take an Include /// parameter. The PowerShell engine should not try to do the filtering on behalf of this /// provider. - /// - /// - /// Note, the provider should make every effort to filter in a way that is consistent + /// + /// + /// The implementer of the provider should make every effort to filter in a way that is consistent /// with the PowerShell engine. This option is allowed because in many cases the provider /// can be much more efficient at filtering. - /// + /// + /// Include = 0x1, /// + /// /// The provider does the exclusion filtering for those commands that take an Exclude /// parameter. The PowerShell engine should not try to do the filtering on behalf of this /// provider. - /// - /// - /// Note, the provider should make every effort to filter in a way that is consistent + /// + /// + /// The implementer of the provider should make every effort to filter in a way that is consistent /// with the PowerShell engine. This option is allowed because in many cases the provider /// can be much more efficient at filtering. - /// + /// + /// Exclude = 0x2, /// + /// /// The provider can take a provider specific filter string. - /// - /// - /// When this attribute is specified a provider specific filter can be passed from + /// + /// + /// For implementers of providers using this attribute, a provider specific filter can be passed from /// the Core Commands to the provider. This filter string is not interpreted in any /// way by the PowerShell engine. - /// + /// + /// Filter = 0x4, /// + /// /// The provider does the wildcard matching for those commands that allow for it. The PowerShell /// engine should not try to do the wildcard matching on behalf of the provider when this /// flag is set. - /// - /// - /// Note, the provider should make every effort to do the wildcard matching in a way that is consistent + /// + /// + /// The implementer of the provider should make every effort to do the wildcard matching in a way that is consistent /// with the PowerShell engine. This option is allowed because in many cases wildcard matching /// cannot occur via the path name or because the provider can do the matching in a much more /// efficient manner. - /// + /// + /// ExpandWildcards = 0x8, /// diff --git a/src/System.Management.Automation/utils/StructuredTraceSource.cs b/src/System.Management.Automation/utils/StructuredTraceSource.cs index be5f10da080..0122e9e26d8 100644 --- a/src/System.Management.Automation/utils/StructuredTraceSource.cs +++ b/src/System.Management.Automation/utils/StructuredTraceSource.cs @@ -144,13 +144,10 @@ public enum PSTraceSourceOptions Assert = 0x00004000, /// - /// A combination of flags that trace the execution flow will - /// be traced. - /// - /// + /// A combination of flags that trace the execution flow. /// The methods associated with the flags; Constructor, Dispose, - /// Finalizer, Method, Delegates, and Events will be enabled - /// + /// Finalizer, Method, Delegates, and Events will be enabled. + /// ExecutionFlow = Constructor | Dispose | @@ -161,13 +158,10 @@ public enum PSTraceSourceOptions Scope, /// - /// A combination of flags that trace the data will be traced - /// be traced. - /// - /// + /// A combination of flags that trace the data. /// The methods associated with the flags; Constructor, Dispose, - /// Finalizer, Property, and WriteLine will be enabled - /// + /// Finalizer, Property, and WriteLine will be enabled. + /// Data = Constructor | Dispose | @@ -178,22 +172,17 @@ public enum PSTraceSourceOptions /// /// A combination of flags that trace the errors. - /// - /// /// The methods associated with the flags; Error, - /// and Exception will be enabled - /// + /// and Exception will be enabled. + /// Errors = Error | Exception, /// - /// All combination of trace flags will be set - /// be traced. - /// - /// + /// All combination of trace flags will be set. /// All methods for tracing will be enabled. - /// + /// All = Constructor | Dispose | From 6689c775133b94c68d0ba68477e4c60028b9fce6 Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Thu, 13 Jul 2023 16:07:34 -0700 Subject: [PATCH 644/779] Update README.md and metadata.json for release v7.2.13 and v7.3.6 (#19964) --- README.md | 54 ++++++++++++++++++++++----------------------- tools/metadata.json | 6 ++--- 2 files changed, 30 insertions(+), 30 deletions(-) diff --git a/README.md b/README.md index 740f67aac99..49a7c1aa314 100644 --- a/README.md +++ b/README.md @@ -64,33 +64,33 @@ You can also download the PowerShell binary archives for Windows, macOS and Linu | Windows (ARM) | [64-bit][rl-winarm64] (preview) | [64-bit][pv-winarm64] | [Instructions][in-arm] | | Raspbian (ARM) | [32-bit][rl-arm32]/[64-bit][rl-arm64] | [32-bit][pv-arm32]/[64-bit][pv-arm64] | [Instructions][in-raspbian] | -[lts-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.12/PowerShell-7.2.12-win-x86.msi -[lts-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.12/PowerShell-7.2.12-win-x64.msi -[lts-deb]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.12/powershell-lts_7.2.12-1.deb_amd64.deb -[lts-rh]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.12/powershell-lts-7.2.12-1.rh.x86_64.rpm -[lts-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.12/powershell-lts-7.2.12-osx-x64.pkg -[lts-macos-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.12/powershell-lts-7.2.12-osx-arm64.pkg - -[rl-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.5/PowerShell-7.3.5-win-x64.msi -[rl-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.5/PowerShell-7.3.5-win-x86.msi -[rl-deb]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.5/powershell_7.3.5-1.deb_amd64.deb -[rl-ubuntu22]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.5/powershell_7.3.5-1.deb_amd64.deb -[rl-ubuntu20]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.5/powershell_7.3.5-1.deb_amd64.deb -[rl-ubuntu18]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.5/powershell_7.3.5-1.deb_amd64.deb -[rl-debian10]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.5/powershell_7.3.5-1.deb_amd64.deb -[rl-debian11]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.5/powershell_7.3.5-1.deb_amd64.deb -[rl-centos]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.5/powershell-7.3.5-1.rh.x86_64.rpm -[rl-centos8]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.5/powershell-7.3.5-1.rh.x86_64.rpm -[rl-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.5/powershell-7.3.5-osx-x64.pkg -[rl-macos-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.5/powershell-7.3.5-osx-arm64.pkg -[rl-winarm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.5/PowerShell-7.3.5-win-arm64.zip -[rl-winx86-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.5/PowerShell-7.3.5-win-x86.zip -[rl-winx64-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.5/PowerShell-7.3.5-win-x64.zip -[rl-macos-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.5/powershell-7.3.5-osx-x64.tar.gz -[rl-macos-tar-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.5/powershell-7.3.5-osx-arm64.tar.gz -[rl-linux-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.5/powershell-7.3.5-linux-x64.tar.gz -[rl-arm32]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.5/powershell-7.3.5-linux-arm32.tar.gz -[rl-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.5/powershell-7.3.5-linux-arm64.tar.gz +[lts-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.13/PowerShell-7.2.13-win-x86.msi +[lts-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.13/PowerShell-7.2.13-win-x64.msi +[lts-deb]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.13/powershell-lts_7.2.13-1.deb_amd64.deb +[lts-rh]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.13/powershell-lts-7.2.13-1.rh.x86_64.rpm +[lts-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.13/powershell-lts-7.2.13-osx-x64.pkg +[lts-macos-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.13/powershell-lts-7.2.13-osx-arm64.pkg + +[rl-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.6/PowerShell-7.3.6-win-x64.msi +[rl-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.6/PowerShell-7.3.6-win-x86.msi +[rl-deb]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.6/powershell_7.3.6-1.deb_amd64.deb +[rl-ubuntu22]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.6/powershell_7.3.6-1.deb_amd64.deb +[rl-ubuntu20]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.6/powershell_7.3.6-1.deb_amd64.deb +[rl-ubuntu18]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.6/powershell_7.3.6-1.deb_amd64.deb +[rl-debian10]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.6/powershell_7.3.6-1.deb_amd64.deb +[rl-debian11]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.6/powershell_7.3.6-1.deb_amd64.deb +[rl-centos]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.6/powershell-7.3.6-1.rh.x86_64.rpm +[rl-centos8]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.6/powershell-7.3.6-1.rh.x86_64.rpm +[rl-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.6/powershell-7.3.6-osx-x64.pkg +[rl-macos-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.6/powershell-7.3.6-osx-arm64.pkg +[rl-winarm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.6/PowerShell-7.3.6-win-arm64.zip +[rl-winx86-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.6/PowerShell-7.3.6-win-x86.zip +[rl-winx64-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.6/PowerShell-7.3.6-win-x64.zip +[rl-macos-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.6/powershell-7.3.6-osx-x64.tar.gz +[rl-macos-tar-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.6/powershell-7.3.6-osx-arm64.tar.gz +[rl-linux-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.6/powershell-7.3.6-linux-x64.tar.gz +[rl-arm32]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.6/powershell-7.3.6-linux-arm32.tar.gz +[rl-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.3.6/powershell-7.3.6-linux-arm64.tar.gz [rl-snap]: https://snapcraft.io/powershell [pv-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.4.0-preview.4/PowerShell-7.4.0-preview.4-win-x64.msi diff --git a/tools/metadata.json b/tools/metadata.json index c5c94011eea..6d85770f1d9 100644 --- a/tools/metadata.json +++ b/tools/metadata.json @@ -1,9 +1,9 @@ { - "StableReleaseTag": "v7.3.5", + "StableReleaseTag": "v7.3.6", "PreviewReleaseTag": "v7.4.0-preview.4", "ServicingReleaseTag": "v7.0.13", - "ReleaseTag": "v7.3.5", - "LTSReleaseTag" : ["v7.2.12"], + "ReleaseTag": "v7.3.6", + "LTSReleaseTag" : ["v7.2.13"], "NextReleaseTag": "v7.4.0-preview.5", "LTSRelease": { "Latest": false, "Package": false }, "StableRelease": { "Latest": false, "Package": false } From 927c5595ca32f9a1116a38f1eeb3355ec0b31e0a Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Fri, 14 Jul 2023 11:57:35 -0700 Subject: [PATCH 645/779] Update variable used to bypass the blocking check for multiple NuGet feeds (#19967) * nuget multiple feed fixes * Update tools/releaseBuild/azureDevOps/vpackRelease.yml * Update linux.yml * Update mac.yml * Update windows.yml * Update windows-packaging.yml * fix whitespace issues * more whitespace * more whitespace --- .vsts-ci/linux.yml | 1 + .vsts-ci/mac.yml | 1 + .vsts-ci/windows.yml | 1 + .vsts-ci/windows/windows-packaging.yml | 2 ++ tools/releaseBuild/azureDevOps/vpackRelease.yml | 4 +++- 5 files changed, 8 insertions(+), 1 deletion(-) diff --git a/.vsts-ci/linux.yml b/.vsts-ci/linux.yml index 7e2b2235832..57c60bc25a7 100644 --- a/.vsts-ci/linux.yml +++ b/.vsts-ci/linux.yml @@ -55,6 +55,7 @@ variables: # Avoid expensive initialization of dotnet cli, see: https://donovanbrown.com/post/Stop-wasting-time-during-NET-Core-builds DOTNET_SKIP_FIRST_TIME_EXPERIENCE: 1 __SuppressAnsiEscapeSequences: 1 + nugetMultiFeedWarnLevel: none resources: repositories: diff --git a/.vsts-ci/mac.yml b/.vsts-ci/mac.yml index 24646a0da4b..4f5e999a335 100644 --- a/.vsts-ci/mac.yml +++ b/.vsts-ci/mac.yml @@ -49,6 +49,7 @@ variables: # Turn off Homebrew analytics HOMEBREW_NO_ANALYTICS: 1 __SuppressAnsiEscapeSequences: 1 + nugetMultiFeedWarnLevel: none resources: - repo: self diff --git a/.vsts-ci/windows.yml b/.vsts-ci/windows.yml index ef6241800e4..c3a39647852 100644 --- a/.vsts-ci/windows.yml +++ b/.vsts-ci/windows.yml @@ -46,6 +46,7 @@ variables: DOTNET_SKIP_FIRST_TIME_EXPERIENCE: 1 __SuppressAnsiEscapeSequences: 1 NugetSecurityAnalysisWarningLevel: none + nugetMultiFeedWarnLevel: none resources: - repo: self diff --git a/.vsts-ci/windows/windows-packaging.yml b/.vsts-ci/windows/windows-packaging.yml index d7443ffa135..4a7c9f81fdb 100644 --- a/.vsts-ci/windows/windows-packaging.yml +++ b/.vsts-ci/windows/windows-packaging.yml @@ -54,6 +54,8 @@ variables: - group: fakeNugetKey - name: SBOMGenerator_Formats value: spdx:2.2 + - name: nugetMultiFeedWarnLevel + value: none resources: repositories: diff --git a/tools/releaseBuild/azureDevOps/vpackRelease.yml b/tools/releaseBuild/azureDevOps/vpackRelease.yml index 8e58720c67b..87b26d3e6dc 100644 --- a/tools/releaseBuild/azureDevOps/vpackRelease.yml +++ b/tools/releaseBuild/azureDevOps/vpackRelease.yml @@ -15,12 +15,14 @@ variables: value: 1 - name: POWERSHELL_TELEMETRY_OPTOUT value: 1 + - name: nugetMultiFeedWarnLevel + value: none + - group: Azure Blob variable group # adds the pat to publish the vPack # instructions to create are in the description of the library - group: vPack - stages: - stage: prep displayName: Create buildInfo and name the Pipeline From 8b7552779977891568c8cef22792bbdf4060118e Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Fri, 14 Jul 2023 12:00:45 -0700 Subject: [PATCH 646/779] Update variable used to bypass the blocking check for multiple NuGet feeds for release pipeline (#19963) --- tools/releaseBuild/azureDevOps/releasePipeline.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tools/releaseBuild/azureDevOps/releasePipeline.yml b/tools/releaseBuild/azureDevOps/releasePipeline.yml index 10796c7a0db..6955e8be127 100644 --- a/tools/releaseBuild/azureDevOps/releasePipeline.yml +++ b/tools/releaseBuild/azureDevOps/releasePipeline.yml @@ -22,6 +22,8 @@ resources: variables: - name: runCodesignValidationInjection value : false + - name: nugetMultiFeedWarnLevel + value: none - name: NugetSecurityAnalysisWarningLevel value: none - name: skipComponentGovernanceDetection From adc1c60420f3bcccb887374cf5667746fa786e64 Mon Sep 17 00:00:00 2001 From: PowerShell Team Bot <69177312+pwshBot@users.noreply.github.com> Date: Mon, 17 Jul 2023 09:28:51 -0700 Subject: [PATCH 647/779] Update to the latest NOTICES file (#19971) --- ThirdPartyNotices.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ThirdPartyNotices.txt b/ThirdPartyNotices.txt index ec109ac4126..f9d238879a8 100644 --- a/ThirdPartyNotices.txt +++ b/ThirdPartyNotices.txt @@ -238,7 +238,7 @@ SOFTWARE. --------------------------------------------------------- -JsonSchema.Net 4.1.5 - MIT +JsonSchema.Net 4.1.6 - MIT From a064d81b1c070b2e5d96ab06a6d661d3d427e57a Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Mon, 17 Jul 2023 09:31:14 -0700 Subject: [PATCH 648/779] Make PR creation tool use `--web` because it is more reliable (#19944) --- tools/releaseTools.psm1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/releaseTools.psm1 b/tools/releaseTools.psm1 index 3c222482348..86b04ac6b50 100644 --- a/tools/releaseTools.psm1 +++ b/tools/releaseTools.psm1 @@ -824,7 +824,7 @@ function Invoke-PRBackport { } if ($PSCmdlet.ShouldProcess("Create the PR")) { - gh pr create --base $Target --title $backportTitle --body "Backport #$PrNumber" + gh pr create --base $Target --title $backportTitle --body "Backport #$PrNumber" --web } } From 3ce65f39e0d01cc57dac04028698b3df2598819c Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Mon, 17 Jul 2023 09:32:03 -0700 Subject: [PATCH 649/779] Hide expected error for negative test on windows for script extension (#19929) --- test/powershell/Host/ConsoleHost.Tests.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/powershell/Host/ConsoleHost.Tests.ps1 b/test/powershell/Host/ConsoleHost.Tests.ps1 index e821df9b457..0ca8978353d 100644 --- a/test/powershell/Host/ConsoleHost.Tests.ps1 +++ b/test/powershell/Host/ConsoleHost.Tests.ps1 @@ -174,7 +174,7 @@ Describe "ConsoleHost unit tests" -tags "Feature" { It "-File should fail for script without .ps1 extension" -Skip:(!$IsWindows) { $Filename = 'test.xxx' Set-Content -Path $testdrive/$Filename -Value "'hello'" - & $powershell -NoProfile -File $testdrive/$Filename > $null + & $powershell -NoProfile -File $testdrive/$Filename 2>&1 $null $LASTEXITCODE | Should -Be 64 } From d24285f4378f188fbd01bd407cb170b4a64c139f Mon Sep 17 00:00:00 2001 From: Armaan Mcleod Date: Tue, 18 Jul 2023 03:30:10 +1000 Subject: [PATCH 650/779] Remove input text from the error message resulted by `SecureString` and `PSCredential` conversion failure (#19977) --- .../engine/LanguagePrimitives.cs | 23 +++++++++++++++++-- .../resources/ExtendedTypeSystem.resx | 3 +++ .../SecureString.Tests.ps1 | 10 ++++++++ .../engine/Basic/Credential.Tests.ps1 | 5 ++++ 4 files changed, 39 insertions(+), 2 deletions(-) diff --git a/src/System.Management.Automation/engine/LanguagePrimitives.cs b/src/System.Management.Automation/engine/LanguagePrimitives.cs index 9979d7433e5..ac78e5e80d5 100644 --- a/src/System.Management.Automation/engine/LanguagePrimitives.cs +++ b/src/System.Management.Automation/engine/LanguagePrimitives.cs @@ -21,6 +21,7 @@ using System.Text; using System.Text.RegularExpressions; using System.Xml; +using System.Security; using Dbg = System.Management.Automation.Diagnostics; using MethodCacheEntry = System.Management.Automation.DotNetAdapter.MethodCacheEntry; @@ -4918,8 +4919,26 @@ internal static Tuple GetInvalidCastMessages(object valueToConve typeConversion.WriteLine("Type Conversion failed."); errorId = "ConvertToFinalInvalidCastException"; - errorMsg = StringUtil.Format(ExtendedTypeSystem.InvalidCastException, valueToConvert.ToString(), - ObjectToTypeNameString(valueToConvert), resultType.ToString()); + + string valueToConvertTypeName = ObjectToTypeNameString(valueToConvert); + string resultTypeName = resultType.ToString(); + + if (resultType == typeof(SecureString) || resultType == typeof(PSCredential)) + { + errorMsg = StringUtil.Format( + ExtendedTypeSystem.InvalidCastExceptionWithoutValue, + valueToConvertTypeName, + resultTypeName); + } + else + { + errorMsg = StringUtil.Format( + ExtendedTypeSystem.InvalidCastException, + valueToConvert.ToString(), + valueToConvertTypeName, + resultTypeName); + } + return Tuple.Create(errorId, errorMsg); } diff --git a/src/System.Management.Automation/resources/ExtendedTypeSystem.resx b/src/System.Management.Automation/resources/ExtendedTypeSystem.resx index 195fdbb7a1b..f8f9ca714cb 100644 --- a/src/System.Management.Automation/resources/ExtendedTypeSystem.resx +++ b/src/System.Management.Automation/resources/ExtendedTypeSystem.resx @@ -189,6 +189,9 @@ Cannot convert the "{0}" value of type "{1}" to type "{2}". + + Cannot convert the value of type "{0}" to type "{1}". + Cannot convert value "{0}" to type "{1}". Error: "{2}" diff --git a/test/powershell/Modules/Microsoft.PowerShell.Security/SecureString.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Security/SecureString.Tests.ps1 index df1fa9294e1..c26689cb7e9 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Security/SecureString.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Security/SecureString.Tests.ps1 @@ -41,4 +41,14 @@ Describe "SecureString conversion tests" -Tags "CI" { $ss2 = $encodedStr | ConvertTo-SecureString -Key $key $ss2 | ConvertFrom-SecureString -AsPlainText | Should -BeExactly $testString } + + It "Using invalid secure string with ConvertFrom-SecureString produces an exception message without value" { + $ex = { ConvertFrom-SecureString "1234" } | Should -Throw -ErrorId "CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.ConvertFromSecureStringCommand" -PassThru + $ex.Exception.Message | Should -Not -Match "1234" + } + + It "Using invalid securestring with cast produces an exception message without value" { + $ex = { [securestring]"1234" } | Should -Throw -ErrorId "ConvertToFinalInvalidCastException" -PassThru + $ex.Exception.Message | Should -Not -Match "1234" + } } diff --git a/test/powershell/engine/Basic/Credential.Tests.ps1 b/test/powershell/engine/Basic/Credential.Tests.ps1 index eeccb18879f..850d40c9c52 100644 --- a/test/powershell/engine/Basic/Credential.Tests.ps1 +++ b/test/powershell/engine/Basic/Credential.Tests.ps1 @@ -5,4 +5,9 @@ Describe "Credential tests" -Tags "CI" { # We should explicitly check that the expression returns $null [PSCredential]::Empty.GetNetworkCredential() | Should -BeNullOrEmpty } + + It "Explicit credential cast with string produces an exception message without value" { + $ex = { [pscredential]"1234" } | Should -Throw -ErrorId "ConvertToFinalInvalidCastException" -PassThru + $ex.Exception.Message | Should -Not -Match "1234" + } } From d372832325f442bd7741a8513a46a8d2c2a53d3c Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Mon, 17 Jul 2023 11:03:59 -0700 Subject: [PATCH 651/779] Remove spelling CI in favor of GitHub Action (#19973) * Remove spelling CI * Delete mdSpell.yml * Delete markdown.yml * Update CONTRIBUTING.md * repo issues * markdown term fixes * command-line term * fix syntax issues * fix codebase term * Disable VALIDATE_EDITORCONFIG --- .github/CONTRIBUTING.md | 57 ++++++++++++++--------------- .github/workflows/markdownLink.yml | 2 +- .vsts-ci/misc-analysis.yml | 5 --- .vsts-ci/misc-analysis/markdown.yml | 57 ----------------------------- .vsts-ci/misc-analysis/mdSpell.yml | 56 ---------------------------- 5 files changed, 28 insertions(+), 149 deletions(-) delete mode 100644 .vsts-ci/misc-analysis/markdown.yml delete mode 100644 .vsts-ci/misc-analysis/mdSpell.yml diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index ce87c469d22..2e43a299d24 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -12,8 +12,8 @@ Please read the rest of this document to ensure a smooth contribution process. * Make sure you have a [GitHub account](https://github.com/signup/free). * Learning Git: - * GitHub Help: [Good Resources for Learning Git and GitHub][good-git-resources] - * [Git Basics](../docs/git/basics.md): install and getting started + * GitHub Help: [Good Resources for Learning Git and GitHub][good-git-resources] + * [Git Basics](../docs/git/basics.md): install and getting started * [GitHub Flow Guide](https://guides.github.com/introduction/flow/): step-by-step instructions of GitHub Flow @@ -52,17 +52,17 @@ if you don't have it - `Install-Module PlatyPS`. 1. Clone the [`MicrosoftDocs/PowerShell-Docs`](https://github.com/MicrosoftDocs/PowerShell-Docs) -repo if you don't already have it. +repository if you don't already have it. 1. Start your local build of PowerShell (with the change to the cmdlet you made). -1. Find the cmdlet's markdown file in PowerShell Docs - usually under +1. Find the cmdlet's Markdown file in PowerShell Docs - usually under `PowerShell-Docs/reference///.md` (Ex. `PowerShell-Docs/reference/7/Microsoft.PowerShell.Utility/Select-String.md`) 1. Run -`Update-MarkdownHelp -Path ` +`Update-MarkdownHelp -Path ` which will update the documentation for you. 1. Make any additional changes needed for the cmdlet to be properly documented. -1. Send a Pull Request to the PowerShell Docs repo with the changes that +1. Send a Pull Request to the PowerShell Docs repository with the changes that `PlatyPS` made. 1. Link your Docs PR to your original change PR. @@ -71,35 +71,34 @@ made. * When writing Markdown documentation, use [semantic linefeeds][]. In most cases, it means "one clause/idea per line". -* Otherwise, these issues should be treated like any other issue in this repo. +* Otherwise, these issues should be treated like any other issue in this repository. #### Spellchecking documentation Documentation is spellchecked. We use the -[markdown-spellcheck](https://github.com/lukeapage/node-markdown-spellcheck) command line tool, -which can be run in interactive mode to correct typos or add words to the ignore list -(`.spelling` at the repository root). +[textlint](https://github.com/textlint/textlint/wiki/Collection-of-textlint-rule) command-line tool, +which can be run in interactive mode to correct typos. To run the spellchecker, follow these steps: * install [Node.js](https://nodejs.org/en/) (v10 or up) -* install [markdown-spellcheck](https://github.com/lukeapage/node-markdown-spellcheck) by - `npm install -g markdown-spellcheck` (v0.11.0 or up) -* run `mdspell "**/*.md" "!**/dotnet-tools/**/*.md" --ignore-numbers --ignore-acronyms --en-us`. - - The folder `dotnet-tools` is excluded because files in that folder are copied from the `dotnet/performance` repository - and will need to be synchronized from time to time. -* if the `.spelling` file is updated, commit and push it +* install [textlint](https://github.com/textlint/textlint/wiki/Collection-of-textlint-rule) by + `npm install -g textlint textlint-rule-terminology` +* run `textlint --rule terminology `, + adding `--fix` will accept all the recommendations. + +If you need to add a term or disable checking part of a file see the [configuration sections of the rule](https://github.com/sapegin/textlint-rule-terminology). #### Checking links in documentation Documentation is link-checked. We make use of the -markdown-link-check command line tool, +`markdown-link-check` command-line tool, which can be run to see if any links are dead. To run the link-checker, follow these steps: * install [Node.js](https://nodejs.org/en/) (v10 or up) -* install markdown-link-check by +* install `markdown-link-check` by `npm install -g markdown-link-check@3.8.5` * run `find . \*.md -exec markdown-link-check {} \;` @@ -177,14 +176,14 @@ Additional references: See [this][closing-via-message] for more details. * Please use the present tense and imperative mood when describing your changes: - * Instead of "Adding support for Windows Server 2012 R2", write "Add support for Windows Server 2012 R2". - * Instead of "Fixed for server connection issue", write "Fix server connection issue". + * Instead of "Adding support for Windows Server 2012 R2", write "Add support for Windows Server 2012 R2". + * Instead of "Fixed for server connection issue", write "Fix server connection issue". - This form is akin to giving commands to the code base + This form is akin to giving commands to the codebase and is recommended by the Git SCM developers. It is also used in the [Git commit messages](#common-engineering-practices). * If the change is related to a specific resource, please prefix the description with the resource name: - * Instead of "New parameter 'ConnectionCredential' in New-SqlConnection", + * Instead of "New parameter 'ConnectionCredential' in New-SqlConnection", write "New-SqlConnection: add parameter 'ConnectionCredential'". * If your change warrants an update to user-facing documentation, a Maintainer will add the `Documentation Needed` label to your PR and add an issue to the [PowerShell-Docs repository][PowerShell-Docs], @@ -195,7 +194,7 @@ Additional references: (See [Contributing to documentation related to PowerShell](#contributing-to-documentation-related-to-powershell) for more info.) * If your change adds a new source file, ensure the appropriate copyright and license headers is on top. It is standard practice to have both a copyright and license notice for each source file. - * For `.h`, `.cpp`, and `.cs` files use the copyright header with empty line after it: + * For `.h`, `.cpp`, and `.cs` files use the copyright header with empty line after it: ```c# // Copyright (c) Microsoft Corporation. @@ -203,7 +202,7 @@ Additional references: ``` - * For `.ps1` and `.psm1` files use the copyright header with empty line after it: + * For `.ps1` and `.psm1` files use the copyright header with empty line after it: ```powershell # Copyright (c) Microsoft Corporation. @@ -235,8 +234,8 @@ Additional references: * After submitting your pull request, our [CI system (Azure DevOps Pipelines)][ci-system] will run a suite of tests and automatically update the status of the pull request. -* Our CI contains automated spellchecking and link checking for markdown files. If there is any false-positive, - [run the spellchecker command line tool in interactive mode](#spellchecking-documentation) +* Our CI contains automated spellchecking and link checking for Markdown files. If there is any false-positive, + [run the spellchecker command-line tool in interactive mode](#spellchecking-documentation) to add words to the `.spelling` file. * Our packaging test may not pass and ask you to update `files.wxs` file if you add/remove/update nuget package references or add/remove assert files. @@ -280,7 +279,7 @@ Additional references: - `Approve` if you believe your feedback has been addressed or the code is fine as-is, it is customary (although not required) to leave a simple "Looks good to me" (or "LGTM") as the comment for approval. - `Comment` if you are making suggestions that the *author* does not have to accept. Early in the review, it is acceptable to provide feedback on coding formatting based on the published [Coding Guidelines][coding-guidelines], however, - after the PR has been approved, it is generally _not_ recommended to focus on formatting issues unless they go against the [Coding Guidelines][coding-guidelines]. + after the PR has been approved, it is generally *not* recommended to focus on formatting issues unless they go against the [Coding Guidelines][coding-guidelines]. Non-critical late feedback (after PR has been approved) can be submitted as a new issue or new pull request from the *reviewer*. 1. *Assignees* who are always *Maintainers* ensure that proper review has occurred and if they believe one approval is not sufficient, the *maintainer* is responsible to add more reviewers. An *assignee* may also be a reviewer, but the roles are distinct. @@ -299,7 +298,7 @@ In these cases: - If the *reviewer*'s comments are very minor, merge the change, fix the code immediately, and create a new PR with the fixes addressing the minor comments. - If the changes required to merge the pull request are significant but needed, *assignee* creates a new branch with the changes and open an issue to merge the code into the dev branch. Mention the original pull request ID in the description of the new issue and close the abandoned pull request. - - If the changes in an abandoned pull request are no longer needed (e.g. due to refactoring of the code base or a design change), *assignee* will simply close the pull request. + - If the changes in an abandoned pull request are no longer needed (e.g. due to refactoring of the codebase or a design change), *assignee* will simply close the pull request. ## Making Breaking Changes @@ -389,11 +388,9 @@ The duration of the temporary ban will depend on the impact and/or severity of t This can vary from 1 day, a few days, a week, and up to 30 days. Repeat offenses may result in a permanent ban from the PowerShell org. -[testing-guidelines]: ../docs/testing-guidelines/testing-guidelines.md [running-tests-outside-of-ci]: ../docs/testing-guidelines/testing-guidelines.md#running-tests-outside-of-ci [issue-management]: ../docs/maintainers/issue-management.md [vuln-reporting]: ./SECURITY.md -[governance]: ../docs/community/governance.md [using-prs]: https://help.github.com/articles/using-pull-requests/ [fork-a-repo]: https://help.github.com/articles/fork-a-repo/ [closing-via-message]: https://help.github.com/articles/closing-issues-via-commit-messages/ diff --git a/.github/workflows/markdownLink.yml b/.github/workflows/markdownLink.yml index ac1be6eba8d..b7df90232f6 100644 --- a/.github/workflows/markdownLink.yml +++ b/.github/workflows/markdownLink.yml @@ -38,4 +38,4 @@ jobs: DEFAULT_BRANCH: master FILTER_REGEX_INCLUDE: .*\.md GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - + VALIDATE_EDITORCONFIG: false diff --git a/.vsts-ci/misc-analysis.yml b/.vsts-ci/misc-analysis.yml index b9e19a2a505..15b3277635b 100644 --- a/.vsts-ci/misc-analysis.yml +++ b/.vsts-ci/misc-analysis.yml @@ -46,8 +46,3 @@ stages: - checkout: ComplianceRepo - template: ci-compliance.yml@ComplianceRepo -- stage: markdown_spelling_lint - displayName: Markdown Spelling and Lint - dependsOn: [] - jobs: - - template: ./misc-analysis/mdSpell.yml diff --git a/.vsts-ci/misc-analysis/markdown.yml b/.vsts-ci/misc-analysis/markdown.yml deleted file mode 100644 index b63e817ef35..00000000000 --- a/.vsts-ci/misc-analysis/markdown.yml +++ /dev/null @@ -1,57 +0,0 @@ -parameters: - - name: matrix - - name: dependsOn - -jobs: -- job: markdown - strategy: - matrix: ${{ parameters.matrix }} - maxParallel: 5 - - displayName: Markdown Link Verification - - dependsOn: ${{ parameters.dependsOn }} - - pool: - vmImage: ubuntu-20.04 - - variables: - - name: repoPath - value: $(Agent.BuildDirectory)/$(repoFolder) - - name: YARN_CACHE_FOLDER - value: $(Pipeline.Workspace)/.yarn - - name: YARN_GLOBAL_CACHE_FOLDER - value: $(Pipeline.Workspace)/.yarn-global - - steps: - - checkout: self - clean: true - path: $(repoFolder) - - - checkout: ComplianceRepo - - - powershell: | - Install-module Pester -Scope CurrentUser -Force -MaximumVersion 4.99 - displayName: Install Pester - - - bash: | - curl -o- --progress-bar -L https://yarnpkg.com/install.sh | bash - displayName: Bootstrap Yarn - - - bash: | - yarn config set global-folder "$(YARN_GLOBAL_CACHE_FOLDER)" - displayName: Set Yarn global cache folder - - - ${{ if not(contains(variables['SYSTEM.COLLECTIONURI'],'mscodehub')) }}: - - pwsh: | - Import-module ./build.psm1 - $path = Join-Path -Path $pwd -ChildPath './commonTestResults.xml' - $results = invoke-pester -Script ./test/common/markdown-link -OutputFile $path -OutputFormat NUnitXml -PassThru - Write-Host "##vso[results.publish type=NUnit;mergeResults=true;runTitle=Markdown Link;publishRunAttachments=true;resultFiles=$path;]" - if($results.TotalCount -eq 0 -or $results.FailedCount -gt 0) - { - throw "Markdown tests failed" - } - displayName: Run Markdown Link Tests - condition: succeededOrFailed() - workingDirectory: '$(repoPath)' diff --git a/.vsts-ci/misc-analysis/mdSpell.yml b/.vsts-ci/misc-analysis/mdSpell.yml deleted file mode 100644 index e9d046e5e96..00000000000 --- a/.vsts-ci/misc-analysis/mdSpell.yml +++ /dev/null @@ -1,56 +0,0 @@ -jobs: -- job: markdown - displayName: Markdown Spelling - - pool: - vmImage: ubuntu-20.04 - - variables: - - name: repoPath - value: $(Agent.BuildDirectory)/$(repoFolder) - - steps: - - checkout: self - clean: true - path: $(repoFolder) - - - checkout: ComplianceRepo - - - powershell: | - Get-ChildItem -Path env: - displayName: Capture Environment - condition: succeededOrFailed() - - - bash: | - curl -o- --progress-bar -L https://yarnpkg.com/install.sh | bash - displayName: Bootstrap Yarn - condition: succeededOrFailed() - - - bash: | - sudo yarn global add markdown-spellcheck@0.11.0 - displayName: Install mdspell - condition: succeededOrFailed() - - - bash: | - mdspell '**/*.md' '!**/Pester/**/*.md' '!**/dotnet-tools/**/*.md' --ignore-numbers --ignore-acronyms --report --en-us; - displayName: Test Spelling in Markdown - condition: succeededOrFailed() - workingDirectory: '$(repoPath)' - - - ${{ if not(contains(variables['SYSTEM.COLLECTIONURI'],'mscodehub')) }}: - - pwsh: | - Import-module ./build.psm1 - $path = Join-Path -Path $pwd -ChildPath './commonTestResults.xml' - $results = invoke-pester -Script ./test/common/markdown-lint -OutputFile $path -OutputFormat NUnitXml -PassThru - Write-Host "##vso[results.publish type=NUnit;mergeResults=true;runTitle=Markdown Lint;publishRunAttachments=true;resultFiles=$path;]" - if($results.TotalCount -eq 0 -or $results.FailedCount -gt 0) - { - throw "Markdown tests failed" - } - displayName: Run Markdown Lint Tests - condition: succeededOrFailed() - workingDirectory: '$(repoPath)' - - - template: dailyBuildCompliance.yml@ComplianceRepo - parameters: - sourceScanPath: '$(repoPath)/test/common' From 153feb2e6022c138cfedc3c28f2e6745be13617d Mon Sep 17 00:00:00 2001 From: Patrick Meinecke Date: Mon, 17 Jul 2023 14:10:35 -0400 Subject: [PATCH 652/779] Fix deadlock when piping to shell associated file extension (#19940) --- .../engine/NativeCommandProcessor.cs | 19 ++++++------------- 1 file changed, 6 insertions(+), 13 deletions(-) diff --git a/src/System.Management.Automation/engine/NativeCommandProcessor.cs b/src/System.Management.Automation/engine/NativeCommandProcessor.cs index b769bc026d9..326e96dfac8 100644 --- a/src/System.Management.Automation/engine/NativeCommandProcessor.cs +++ b/src/System.Management.Automation/engine/NativeCommandProcessor.cs @@ -604,19 +604,6 @@ private void InitNativeProcess() { _nativeProcess = new Process() { StartInfo = startInfo }; _nativeProcess.Start(); - if (UpstreamIsNativeCommand) - { - SemaphoreSlim processInitialized = _processInitialized; - if (processInitialized is null) - { - lock (_sync) - { - processInitialized = _processInitialized ??= new SemaphoreSlim(0, 1); - } - } - - processInitialized?.Release(); - } } catch (Win32Exception) { @@ -695,6 +682,12 @@ private void InitNativeProcess() } #endif } + + if (UpstreamIsNativeCommand) + { + _processInitialized ??= new SemaphoreSlim(0, 1); + _processInitialized.Release(); + } } if (this.Command.MyInvocation.PipelinePosition < this.Command.MyInvocation.PipelineLength) From 329034369a9842c6580c92fcd4046fc06cf15d70 Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Mon, 17 Jul 2023 11:14:31 -0700 Subject: [PATCH 653/779] Check for pre-release packages when it's a stable release (#19939) --- tools/findMissingNotices.ps1 | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/tools/findMissingNotices.ps1 b/tools/findMissingNotices.ps1 index d1c43816b29..0ea53c665b4 100644 --- a/tools/findMissingNotices.ps1 +++ b/tools/findMissingNotices.ps1 @@ -6,7 +6,8 @@ # Requires the module dotnet.project.assets from the PowerShell Gallery authored by @TravisEz13 param( - [switch] $Fix + [switch] $Fix, + [switch] $IsStable ) Import-Module dotnet.project.assets @@ -274,6 +275,17 @@ foreach ($runtime in "win7-x64", "linux-x64", "osx-x64", "alpine-x64", "win-arm" $newRegistrations = $registrations.Keys | Sort-Object | ForEach-Object { $registrations[$_] } +if ($IsStable) { + foreach ($registion in $newRegistrations) { + $name = $registion.Component.Name() + $version = $registion.Component.Version() + $developmentDependency = $registion.DevelopmentDependency + if ($version -match '-' -and !$developmentDependency) { + throw "Version $version of $name is preview. This is not allowed." + } + } +} + $count = $newRegistrations.Count $newJson = @{ Registrations = $newRegistrations From 24c704f5617bf7c8ee7a3c0446412da5ac3bc1f3 Mon Sep 17 00:00:00 2001 From: Sean Wheeler Date: Mon, 17 Jul 2023 13:22:57 -0500 Subject: [PATCH 654/779] Add Help proxy function for non-Windows platforms (#19972) --- .../engine/InitialSessionState.cs | 162 ++++++++++++++++-- 1 file changed, 147 insertions(+), 15 deletions(-) diff --git a/src/System.Management.Automation/engine/InitialSessionState.cs b/src/System.Management.Automation/engine/InitialSessionState.cs index 6e5d26dd168..d367f4eb106 100644 --- a/src/System.Management.Automation/engine/InitialSessionState.cs +++ b/src/System.Management.Automation/engine/InitialSessionState.cs @@ -4126,16 +4126,7 @@ internal static string GetExecFunctionText() } #endif - /// - /// This is the default function to use for man/help. It uses - /// splatting to pass in the parameters. - /// - internal static string GetHelpPagingFunctionText() - { - // We used to generate the text for this function so you could add a parameter - // to Get-Help and not worry about adding it here. That was a little slow at - // startup, so it's hard coded, with a test to make sure the parameters match. - return @" + internal const string WindowsHelpFunctionText = @" <# .FORWARDHELPTARGETNAME Get-Help .FORWARDHELPCATEGORY Cmdlet @@ -4209,14 +4200,132 @@ .FORWARDHELPCATEGORY Cmdlet elseif ($help -ne $null) { # By default use more on Windows and less on Linux. - if ($IsWindows) { - $pagerCommand = 'more.com' - $pagerArgs = $null + $pagerCommand = 'more.com' + $pagerArgs = $null + + # Respect PAGER environment variable which allows user to specify a custom pager. + # Ignore a pure whitespace PAGER value as that would cause the tokenizer to return 0 tokens. + if (![string]::IsNullOrWhitespace($env:PAGER)) { + if (Get-Command $env:PAGER -ErrorAction Ignore) { + # Entire PAGER value corresponds to a single command. + $pagerCommand = $env:PAGER + $pagerArgs = $null + } + else { + # PAGER value is not a valid command, check if PAGER command and arguments have been specified. + # Tokenize the specified $env:PAGER value. Ignore tokenizing errors since any errors may be valid + # argument syntax for the paging utility. + $errs = $null + $tokens = [System.Management.Automation.PSParser]::Tokenize($env:PAGER, [ref]$errs) + + $customPagerCommand = $tokens[0].Content + if (!(Get-Command $customPagerCommand -ErrorAction Ignore)) { + # Custom pager command is invalid, issue a warning. + Write-Warning ""Custom-paging utility command not found. Ignoring command specified in `$env:PAGER: $env:PAGER"" + } + else { + # This approach will preserve all the pagers args. + $pagerCommand = $customPagerCommand + $pagerArgs = if ($tokens.Count -gt 1) { + $env:PAGER.Substring($tokens[1].Start) + } + else { + $null + } + } + } + } + + $pagerCommandInfo = Get-Command -Name $pagerCommand -ErrorAction Ignore + if ($pagerCommandInfo -eq $null) { + $help + } + elseif ($pagerCommandInfo.CommandType -eq 'Application') { + # If the pager is an application, format the output width before sending to the app. + $consoleWidth = [System.Math]::Max([System.Console]::WindowWidth, 20) + + if ($pagerArgs) { + $help | Out-String -Stream -Width ($consoleWidth - 1) | & $pagerCommand $pagerArgs + } + else { + $help | Out-String -Stream -Width ($consoleWidth - 1) | & $pagerCommand + } } else { - $pagerCommand = 'less' - $pagerArgs = '-s','-P','Page %db?B of %D:.\. Press h for help or q to quit\.' + # The pager command is a PowerShell function, script or alias, so pipe directly into it. + $help | & $pagerCommand $pagerArgs } + } +"; + + internal const string UnixHelpFunctionText = @" +<# +.FORWARDHELPTARGETNAME Get-Help +.FORWARDHELPCATEGORY Cmdlet +#> +[CmdletBinding(DefaultParameterSetName='AllUsersView', HelpUri='https://go.microsoft.com/fwlink/?LinkID=113316')] +param( + [Parameter(Position=0, ValueFromPipelineByPropertyName=$true)] + [string] + ${Name}, + + [string] + ${Path}, + + [ValidateSet('Alias','Cmdlet','Provider','General','FAQ','Glossary','HelpFile','ScriptCommand','Function','Filter','ExternalScript','All','DefaultHelp','DscResource','Class','Configuration')] + [string[]] + ${Category}, + + [Parameter(ParameterSetName='DetailedView', Mandatory=$true)] + [switch] + ${Detailed}, + + [Parameter(ParameterSetName='AllUsersView')] + [switch] + ${Full}, + + [Parameter(ParameterSetName='Examples', Mandatory=$true)] + [switch] + ${Examples}, + + [Parameter(ParameterSetName='Parameters', Mandatory=$true)] + [string[]] + ${Parameter}, + + [string[]] + ${Component}, + + [string[]] + ${Functionality}, + + [string[]] + ${Role}, + + [Parameter(ParameterSetName='Online', Mandatory=$true)] + [switch] + ${Online}) + + # Display the full help topic by default but only for the AllUsersView parameter set. + if (($psCmdlet.ParameterSetName -eq 'AllUsersView') -and !$Full) { + $PSBoundParameters['Full'] = $true + } + + # Linux need the default + $OutputEncoding = [System.Console]::OutputEncoding + + $help = Get-Help @PSBoundParameters + + # If a list of help is returned or AliasHelpInfo (because it is small), don't pipe to more + $psTypeNames = ($help | Select-Object -First 1).PSTypeNames + if ($psTypeNames -Contains 'HelpInfoShort' -Or $psTypeNames -Contains 'AliasHelpInfo') + { + $help + } + elseif ($help -ne $null) + { + # By default use more on Windows and less on Linux. + $pagerCommand = 'less' + $pagerArgs = '-s','-P','Page %db?B of %D:.\. Press h for help or q to quit\.' # Respect PAGER environment variable which allows user to specify a custom pager. # Ignore a pure whitespace PAGER value as that would cause the tokenizer to return 0 tokens. @@ -4267,8 +4376,31 @@ .FORWARDHELPCATEGORY Cmdlet } } "; + + /// + /// This is the default function to use for man/help. It uses + /// splatting to pass in the parameters. + /// +#if !UNIX + internal static string GetHelpPagingFunctionText() + { + // We used to generate the text for this function so you could add a parameter + // to Get-Help and not worry about adding it here. That was a little slow at + // startup, so it's hard coded, with a test to make sure the parameters match. + return WindowsHelpFunctionText; } +#else + internal static string GetHelpPagingFunctionText() + { + // We used to generate the text for this function so you could add a parameter + // to Get-Help and not worry about adding it here. That was a little slow at + // startup, so it's hard coded, with a test to make sure the parameters match. + // This version removes the -ShowWindow parameter since it is not supported on Linux. + return UnixHelpFunctionText; + } +#endif + internal static string GetMkdirFunctionText() { return @" From 60dc724023bbee8a99448961feb0ff1a9c2cf853 Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Mon, 17 Jul 2023 11:42:07 -0700 Subject: [PATCH 655/779] Merge `7.3.5`, `7.3.6`, `7.2.12` and `7.2.13` change logs (#19968) --- CHANGELOG/7.2.md | 105 ++++++++++++++++++++++++++++++++++++-------- CHANGELOG/7.3.md | 110 ++++++++++++++++++++++++++++++++++++++--------- 2 files changed, 176 insertions(+), 39 deletions(-) diff --git a/CHANGELOG/7.2.md b/CHANGELOG/7.2.md index 78313f1f084..ca7e08a2613 100644 --- a/CHANGELOG/7.2.md +++ b/CHANGELOG/7.2.md @@ -1,5 +1,74 @@ # 7.2 Changelog +## [7.2.13] - 2023-07-13 + +### Tests + +- Increase the timeout to make subsystem tests more reliable (#19937) +- Increase the timeout when waiting for the event log (#19936) + +### Build and Packaging Improvements + +
    + + + +

    Bump .NET SDK version to 6.0.412

    + +
    + +
      +
    • Update Notice file (#19956)
    • +
    • Update cgmanifest (#19938)
    • +
    • Bump to 6.0.412 SDK (#19933)
    • +
    • Update variable used to bypass the blocking check for multiple NuGet feeds (#19935)
    • +
    + +
    + +[7.2.13]: https://github.com/PowerShell/PowerShell/compare/v7.2.12...v7.2.13 + +## [7.2.12] - 2023-06-27 + +### Build and Packaging Improvements + +
    + + + +

    Bump .NET version to 6.0.411

    + +
    + +
      +
    • Disable SBOM signing for CI and add extra files for packaging tests (#19729)
    • +
    • Update ThirdPartyNotices (Internal 26349)
    • +
    • Update the cgmanifest
    • +
    • Add PoolNames variable group to compliance pipeline (#19408)
    • +
    • Add tool to trigger license information gathering for NuGet modules (#18827)
    • +
    • Update to .NET 6.0.410 (#19798)
    • +
    • Always regenerate files wxs fragment (#19803)
    • +
    • Add prompt to fix conflict during backport (#19583)
    • +
    • Add backport function to release tools (#19568)
    • +
    • Do not remove penimc_cor3.dll from build (#18438)
    • +
    • Remove unnecessary native dependencies from the package (#18213)
    • +
    • Delete symbols on Linux as well (#19735)
    • +
    • Bump Microsoft.PowerShell.MarkdownRender (#19751)
    • +
    • Backport compliance changes (#19719)
    • +
    • Delete charset regular expression test (#19585)
    • +
    • Fix issue with merge of 19068 (#19586)
    • +
    • Update the team member list in releaseTools.psm1 (#19574)
    • +
    • Verify that packages have license data (#19543) (#19575)
    • +
    • Update experimental-feature.json (#19581)
    • +
    • Fix the regular expression used for package name check in vPack build (#19573)
    • +
    • Make the vPack PAT library more obvious (#19572)
    • +
    • Add an explicit manual stage for changelog update (#19551) (#19567)
    • +
    + +
    + +[7.2.12]: https://github.com/PowerShell/PowerShell/compare/v7.2.11...v7.2.12 + ## [7.2.11] - 2023-04-12 ### Build and Packaging Improvements @@ -176,7 +245,7 @@ ### General Cmdlet Updates and Fixes - Make `Out-String` and `Out-File` keep string input unchanged (#17455) -- Update regex used to remove ANSI escape sequences to be more specific to decoration and hyperlinks (#16811) +- Update regular expression used to remove ANSI escape sequences to be more specific to decoration and hyperlinks (#16811) - Fix legacy `ErrorView` types to use `$host.PrivateData` colors (#17705) - Fix `Export-PSSession` to not throw error when a rooted path is specified for `-OutputModule` (#17671) @@ -217,7 +286,7 @@ - Make Assembly Load Native test work on a FX Dependent Linux Install (#17496) - Enable more tests to be run in a container. (#17294) -- Switch to using GitHub action to verify markdown links for PRs (#17281) +- Switch to using GitHub action to verify Markdown links for PRs (#17281) - Try to stabilize a few tests that fail intermittently (#17426) - TLS test fix back-port (#17424) @@ -238,7 +307,7 @@
  • Backport test fixes for 7.2 (#17494)
  • Update dotnet-runtime version (#17472)
  • Update to use windows-latest as the build agent image (#17418)
  • -
  • Publish preview versions of mariner to preview repo (#17464)
  • +
  • Publish preview versions of mariner to preview repository (#17464)
  • Move cgmanifest generation to daily (#17258)
  • Fix mariner mappings (#17413)
  • Make sure we execute tests on LTS package for older LTS releases (#17430)
  • @@ -344,7 +413,7 @@
  • Add SBOM manifest for release packages (#16641, #16711)
  • Add Linux package dependencies for packaging (#16807)
  • Switch to our custom images for build and release (#16801, #16580)
  • -
  • Remove all references to cmake for the builds in this repo (#16578)
  • +
  • Remove all references to cmake for the builds in this repository (#16578)
  • Register NuGet source when generating CGManifest (#16570)
  • @@ -384,7 +453,7 @@
  • vPack release should use buildInfoJson new to 7.2 (#16402)
  • Add checkout to build json stage to get ci.psm1 (#16399)
  • Update the usage of metadata.json for getting LTS information (#16381)
  • -
  • Move mapping file into product repo and add Debian 11 (#16316)
  • +
  • Move mapping file into product repository and add Debian 11 (#16316)
  • @@ -470,7 +539,7 @@
  • Update vPack task version to 12 (#16250)
  • Sign third party executables (#16229)
  • Add Software Bill of Materials to the main packages (#16202)
  • -
  • Upgrade set-value package for markdown test (#16196)
  • +
  • Upgrade set-value package for Markdown test (#16196)
  • Fix Microsoft update spelling issue (#16178)
  • Move vPack build to 1ES Pool (#16169)
  • @@ -612,14 +681,14 @@ Details - Enable `/rebase` to automatically rebase a PR (#15808) - Update `.editorconfig` to not replace tabs with spaces in `.tsv` files (#15815) (Thanks @SethFalco!) -- Update PowerShell team members in the change log generation script (#15817) +- Update PowerShell team members in the changelog generation script (#15817) ### Tests - Add more tests to validate the current command error handling behaviors (#15919) - Make `Measure-Object` property test independent of the file system (#15879) - Add more information when a `syslog` parsing error occurs (#15857) -- Harden logic when looking for `syslog` entries to be sure that we select based on the process id (#15841) +- Harden logic when looking for `syslog` entries to be sure that we select based on the process ID (#15841) ### Build and Packaging Improvements @@ -644,7 +713,7 @@ Details ### Documentation and Help Content - Update `README` and `metadata files` for release `v7.2.0-preview.8` (#15819) -- Update change logs for 7.0.7 and 7.1.4 (#15921) +- Update changelogs for 7.0.7 and 7.1.4 (#15921) - Fix spelling in XML docs (#15939) (Thanks @slowy07!) - Update PowerShell Committee members (#15837) @@ -664,7 +733,7 @@ Details - Use `$PSStyle.Formatting.FormatAccent` for `Format-List` and `$PSStyle.Formatting.TableHeader` for `Format-Table` output (#14406) - Highlight using error color the exception `Message` and underline in `PositionMessage` for `Get-Error` (#15786) - Implement a completion for View parameter of format cmdlets (#14513) (Thanks @iSazonov!) -- Add support to colorize `FileInfo` file names (#14403) +- Add support to colorize `FileInfo` filenames (#14403) - Don't serialize to JSON ETS properties for `DateTime` and `string` types (#15665) - Fix `HyperVSocketEndPoint.ServiceId` setter (#15704) (Thanks @xtqqczze!) - Add `DetailedView` to `$ErrorView` (#15609) @@ -928,7 +997,7 @@ Update .NET to version v6.0.0-preview.4 - Make PowerShell Linux deb and RPM packages universal (#15109) - Enforce AppLocker Deny configuration before Execution Policy Bypass configuration (#15035) -- Disallow mixed dash and slash in command line parameter prefix (#15142) (Thanks @davidBar-On!) +- Disallow mixed dash and slash in command-line parameter prefix (#15142) (Thanks @davidBar-On!) ### Experimental Features @@ -997,7 +1066,7 @@ Update .NET to version v6.0.0-preview.4
    • Fix yarn-lock for copy-props (#15225)
    • -
    • Make package validation regex accept universal Linux packages (#15226)
    • +
    • Make package validation regular expression accept universal Linux packages (#15226)
    • Bump NJsonSchema from 10.4.0 to 10.4.1 (#15190)
    • Make MSI and EXE signing always copy to fix daily build (#15191)
    • Sign internals of EXE package so that it works correctly when signed (#15132)
    • @@ -1071,7 +1140,7 @@ Update .NET to version 6.0.100-preview.2.21155.3
    • Enable building PowerShell for Apple M1 runtime (#14923)
    • Fix the variable name in the condition for miscellaneous analysis CI (#14975)
    • Fix the variable usage in CI yaml (#14974)
    • -
    • Disable running markdown link verification in release build CI (#14971)
    • +
    • Disable running Markdown link verification in release build CI (#14971)
    • Bump Microsoft.CodeAnalysis.CSharp from 3.9.0-3.final to 3.9.0 (#14934) (Thanks @dependabot[bot]!)
    • Declare which variable group is used for checking the blob in the release build (#14970)
    • Update metadata and script to enable consuming .NET daily builds (#14940)
    • @@ -1099,7 +1168,7 @@ Update .NET to version 6.0.100-preview.2.21155.3 ### Documentation and Help Content - Update `README.md` and `metadata.json` for upcoming releases (#14755) -- Merge 7.1.3 and 7.0.6 Change log to master (#15009) +- Merge 7.1.3 and 7.0.6 changelog to master (#15009) - Update `README` and `metadata.json` for releases (#14997) - Update ChangeLog for `v7.1.2` release (#14783) - Update ChangeLog for `v7.0.5` release (#14782) (Internal 14479) @@ -1164,7 +1233,7 @@ Update .NET to version 6.0.100-preview.2.21155.3 - Update script to use .NET 6 build resources (#14705) - Fix the daily GitHub action (#14711) (Thanks @imba-tjd!) - GitHub Actions: fix deprecated `::set-env` (#14629) (Thanks @imba-tjd!) -- Update markdown test tools (#14325) (Thanks @RDIL!) +- Update Markdown test tools (#14325) (Thanks @RDIL!) - Upgrade `StyleCopAnalyzers` to `v1.2.0-beta.312` (#14354) (Thanks @xtqqczze!) ### Tests @@ -1206,7 +1275,7 @@ Update .NET to version 6.0.100-preview.2.21155.3 - Update distribution support request template to point to .NET 5.0 support document (#14578) - Remove security GitHub issue template (#14453) -- Add intent for using the Discussions feature in repo (#14399) +- Add intent for using the Discussions feature in repository (#14399) - Fix Universal Dashboard to refer to PowerShell Universal (#14437) - Update document link because of HTTP 301 redirect (#14431) (Thanks @xtqqczze!) @@ -1363,7 +1432,7 @@ Update .NET to version 6.0.100-preview.2.21155.3 ### Tests - Reinstate `Test-Connection` tests (#13324) -- Update markdown test packages with security fixes (#14145) +- Update Markdown test packages with security fixes (#14145) ### Build and Packaging Improvements @@ -1498,7 +1567,7 @@ Update .NET to version 6.0.100-preview.2.21155.3
    • Add checkout step to release build templates (#13840)
    • Turn on /features:strict for all projects (#13383) (Thanks @xtqqczze!)
    • Bump NJsonSchema to 10.2.2 (#13722, #13751)
    • -
    • Add flag to make Linux script publish to production repo (#13714)
    • +
    • Add flag to make Linux script publish to production repository (#13714)
    • Bump Markdig.Signed to 0.22.0 (#13741)
    • Use new release script for Linux packages (#13705)
    diff --git a/CHANGELOG/7.3.md b/CHANGELOG/7.3.md index 295cf217fc0..e0e511feea8 100644 --- a/CHANGELOG/7.3.md +++ b/CHANGELOG/7.3.md @@ -1,5 +1,73 @@ # 7.3 Changelog +## [7.3.6] - 2023-07-13 + +### Build and Packaging Improvements + +
    + + + +

    Bump .NET to 7.0.306

    + +
    + +
      +
    • Update Notices file
    • +
    • Don't publish notice on failure because it prevents retry
    • +
    • Bump .NET to 7.0.306 (#19945)
    • +
    • Remove the property disabling optimization (#19952)
    • +
    • Add ProductCode in registry for MSI install (#19951)
    • +
    • Update variable used to bypass the blocking check for multiple NuGet feeds (#19953)
    • +
    • Change System.Security.AccessControl preview version to stable version (#19931)
    • +
    + +
    + +### Documentation and Help Content + +- Update the link for getting started in `README.md` (#19947) + +[7.3.6]: https://github.com/PowerShell/PowerShell/compare/v7.3.5...v7.3.6 + +## [7.3.5] - 2023-06-27 + +### Build and Packaging Improvements + +
    + + + +

    Bump to use .NET 7.0.305

    + +
    + +
      +
    • Update the ThirdPartyNotice (Internal 26372)
    • +
    • Add PoolNames variable group to compliance pipeline (#19408)
    • +
    • Update cgmanifest.json
    • +
    • Update to .NET 7.0.304 (#19807)
    • +
    • Disable SBOM signing for CI and add extra files for packaging tests (#19729)
    • +
    • Increase timeout to make subsystem tests more reliable (#18380)
    • +
    • Increase the timeout when waiting for the event log (#19264)
    • +
    • Implement IDisposable in NamedPipeClient (#18341) (Thanks @xtqqczze!)
    • +
    • Always regenerate files wxs fragment (#19196)
    • +
    • Bump Microsoft.PowerShell.MarkdownRender (#19751)
    • +
    • Delete symbols on Linux as well (#19735)
    • +
    • Add prompt to fix conflict during backport (#19583)
    • +
    • Add backport function to release tools (#19568)
    • +
    • Add an explicit manual stage for changelog update (#19551)
    • +
    • Update the team member list in releaseTools.psm1 (#19544)
    • +
    • Verify that packages have license data (#19543)
    • +
    • Fix the regex used for package name check in vPack build (#19511)
    • +
    • Make the vPack PAT library more obvious (#19505)
    • +
    • Update the metadata.json to mark 7.3 releases as latest for stable channel (#19565)
    • +
    + +
    + +[7.3.5]: https://github.com/PowerShell/PowerShell/compare/v7.3.4...v7.3.5 + ## [7.3.4] - 2023-04-12 ### Engine Updates and Fixes @@ -68,7 +136,7 @@ ### Engine Updates and Fixes -- Fix `SuspiciousContentChecker.Match` to detect a pre-defined string when the text starts with it (#18916) +- Fix `SuspiciousContentChecker.Match` to detect a predefined string when the text starts with it (#18916) - Fix for JEA session leaking functions (Internal 23820) ### General Cmdlet Updates and Fixes @@ -275,7 +343,7 @@ ### General Cmdlet Updates and Fixes - Fix for deserializing imported ordered dictionary (#15545) (Thanks @davidBar-On!) -- Make generated implicit remoting modules backwards compatible with PowerShell 5.1 (#17227) (Thanks @Tadas!) +- Make generated implicit remoting modules backward compatible with PowerShell 5.1 (#17227) (Thanks @Tadas!) - Re-enable IDE0031: Use Null propagation (#17811) (Thanks @fflaten!) - Allow commands to still be executed even if the current working directory no longer exists (#17579) - Stop referencing `Microsoft.PowerShell.Security` when the core snapin is used (#17771) @@ -440,7 +508,7 @@ ### Documentation and Help Content - Remove `katacoda.com` from doc as it now returns 404 (#17625) -- Update change log for `v7.2.5` and `v7.3.0-preview.5` (#17565) +- Update changelog for `v7.2.5` and `v7.3.0-preview.5` (#17565) - Update `README.md` and `metadata.json` for upcoming releases (#17526) [7.3.0-preview.6]: https://github.com/PowerShell/PowerShell/compare/v7.3.0-preview.5...v7.3.0-preview.6 @@ -452,7 +520,7 @@ - Improve type inference and completions (#16963) (Thanks @MartinGC94!) - Make `Out-String` and `Out-File` keep string input unchanged (#17455) - Make `AnsiRegex` able to capture Hyperlink ANSI sequences (#17442) -- Add the `-ConfigurationFile` command line parameter to `pwsh` to support local session configuration (#17447) +- Add the `-ConfigurationFile` command-line parameter to `pwsh` to support local session configuration (#17447) - Fix native library loading for `osx-arm64` (#17365) (Thanks @awakecoding!) - Fix formatting to act appropriately when the style of table header or list label is empty string (#17463) @@ -493,7 +561,7 @@ - Add reminder workflows (#17387) - Move to configuring the fabric bot via JSON (#17411) - Update Documentation Issue Template URL (#17410) (Thanks @michaeltlombardi!) -- Update script to automatically take new preview pre-release builds (#17375) +- Update script to automatically take new preview prerelease builds (#17375) ### Tests @@ -528,7 +596,7 @@ - Update the cgmanifest (#17478) (Thanks @github-actions[bot]!) - Correct spelling in Comments and tests (#17480) (Thanks @Yulv-git!) - Fix spelling errors introduced in changelog (#17414) -- Update change log for v7.3.0-preview.4 release (#17412) +- Update changelog for v7.3.0-preview.4 release (#17412) - Update readme and metadata for 7.3.0-preview.4 release (#17378) [7.3.0-preview.5]: https://github.com/PowerShell/PowerShell/compare/v7.3.0-preview.4...v7.3.0-preview.5 @@ -633,7 +701,7 @@
  • Improve how Linux container CI builds are identified (#17295)
  • Only inject NuGet security analysis if we are using secure nuget.config (#17293)
  • Reduce unneeded verbose message from build.psm1 (#17291)
  • -
  • Switch to using GitHub action to verify markdown links for PRs (#17281)
  • +
  • Switch to using GitHub action to verify Markdown links for PRs (#17281)
  • Put Secure supply chain analysis at correct place (#17273)
  • Fix build id variable name when selecting CI container (#17279)
  • Add rotation between the two mariner images (#17277)
  • @@ -653,7 +721,7 @@
  • Fixed package names verification to support multi-digit versions (#17220)
  • Bump Microsoft.CodeAnalysis.CSharp from 4.2.0-1.final to 4.2.0-4.final (#17210)
  • Add backport action (#17212)
  • -
  • Updated change logs for v7.0.9 / v7.0.10 / v7.1.6 / v7.1.7 / v7.2.2 / v7.2.3 (#17207)
  • +
  • Updated changelogs for v7.0.9 / v7.0.10 / v7.1.6 / v7.1.7 / v7.2.2 / v7.2.3 (#17207)
  • Updated metadata.json and README.md for v7.2.3 and v7.0.10 (#17158)
  • Update package fallback list for ubuntu (from those updated for ubuntu 22.04) (deb) (#17180)
  • Update wix to include security extensions package (#17171)
  • @@ -730,7 +798,7 @@ ### General Cmdlet Updates and Fixes - Prevent command completion if the word to complete is a single dash (#16781) (Thanks @ayousuf23!) -- Use `FindFirstFileW` instead of `FindFirstFileExW` to correctly handle Unicode file names on FAT32 (#16840) (Thanks @iSazonov!) +- Use `FindFirstFileW` instead of `FindFirstFileExW` to correctly handle Unicode filenames on FAT32 (#16840) (Thanks @iSazonov!) - Add completion for loop labels after Break/Continue (#16438) (Thanks @MartinGC94!) - Support OpenSSH options for `PSRP` over SSH commands (#12802) (Thanks @BrannenGH!) - Adds a `.ResolvedTarget` Property to `File-System` Items to Reflect a Symlink's Target as `FileSystemInfo` (#16490) (Thanks @hammy3502!) @@ -763,7 +831,7 @@
  • Fix typo in PowerShellExecutionHelper.cs (#16776) (Thanks @eltociear!)
  • Use more efficient platform detection API (#16760) (Thanks @iSazonov!)
  • Seal ClientRemotePowerShell (#15802) (Thanks @xtqqczze!)
  • -
  • Fix the DSC overview URL in a markdown file and some small cleanup changes (#16629)
  • +
  • Fix the DSC overview URL in a Markdown file and some small cleanup changes (#16629)
  • @@ -798,7 +866,7 @@ when not needed and dynamically determine the DOTNET_ROOT (Internal 19268, 19269
  • Use Start-PSBootStrap for installing .NET during nuget packaging
  • Fix pool syntax for deployments (Internal 19189)
  • Bump NJsonSchema from 10.5.2 to 10.6.9 (#16888)
  • -
  • Update projects and scripts to use .NET 7 preview 1 pre-release builds (#16856)
  • +
  • Update projects and scripts to use .NET 7 preview 1 prerelease builds (#16856)
  • Add warning messages when package precheck fails (#16867)
  • Refactor Global Tool packaging to include SBOM generation (#16860)
  • Update to use windows-latest as the build agent image (#16831)
  • @@ -823,9 +891,9 @@ when not needed and dynamically determine the DOTNET_ROOT (Internal 19268, 19269
  • Bring changes from 7.3.0-preview.1 (#16640)
  • Update the vmImage and PowerShell root directory for macOS builds (#16611)
  • Update macOS build image and root folder for build (#16609)
  • -
  • Disabled Yarn cache in markdown.yml (#16599)
  • +
  • Disabled Yarn cache in markdown.yml (#16599)
  • Update cgmanifest (#16600)
  • -
  • Fix broken links in markdown (#16598)
  • +
  • Fix broken links in Markdown (#16598)
  • @@ -835,7 +903,7 @@ when not needed and dynamically determine the DOTNET_ROOT (Internal 19268, 19269 - Add newly joined members to their respective Working Groups (#16849) - Update Engine Working Group members (#16780) - Replace the broken link about pull request (#16771) -- Update change log to remove a broken URL (#16735) +- Update changelog to remove a broken URL (#16735) - Updated `README.md` and `metadata.json` for `v7.3.0-preview.1` release (#16627) - Updating changelog for `7.2.1` (#16616) - Updated `README.md` and `metadata.json` for `7.2.1` release (#16586) @@ -977,9 +1045,9 @@ when not needed and dynamically determine the DOTNET_ROOT (Internal 19268, 19269
  • Merge the v7.2.0-preview.9 release branch back to GitHub master (#15983)
  • Publish global tool package for stable releases (#15961)
  • Bump Microsoft.CodeAnalysis.NetAnalyzers to newer version (#15962)
  • -
  • Disabled Yarn cache in markdown.yml (#16599)
  • +
  • Disabled Yarn cache in markdown.yml (#16599)
  • Update cgmanifest (#16600)
  • -
  • Fix broken links in markdown (#16598)
  • +
  • Fix broken links in Markdown (#16598)
  • Add explicit job name for approval tasks in Snap stage (#16579)
  • Bring back pwsh.exe for framework dependent packages to support Start-Job (#16535)
  • Fix NuGet package generation in release build (#16509)
  • @@ -987,7 +1055,7 @@ when not needed and dynamically determine the DOTNET_ROOT (Internal 19268, 19269
  • Bump Microsoft.CodeAnalysis.CSharp from `4.0.0-6.final` to `4.0.1` (#16423)
  • use different containers for different branches (#16434)
  • Add import so we can use common GitHub workflow function. (#16433)
  • -
  • Remove pre-release .NET 6 build sources (#16418)
  • +
  • Remove prerelease .NET 6 build sources (#16418)
  • Update release instructions with link to new build (#16419)
  • Bump Microsoft.ApplicationInsights from 2.18.0 to 2.19.0 (#16413)
  • Update metadata.json to make 7.2.0 the latest LTS (#16417)
  • @@ -1046,7 +1114,7 @@ when not needed and dynamically determine the DOTNET_ROOT (Internal 19268, 19269
  • Remove unneeded `NuGetConfigFile` resource string (#16232)
  • Add Software Bill of Materials to the main packages (#16202)
  • Sign third party exes (#16229)
  • -
  • Upgrade set-value package for markdown test (#16196)
  • +
  • Upgrade set-value package for Markdown test (#16196)
  • Use Ubuntu 20.04 for SSH remoting test (#16225)
  • Bump Microsoft.CodeAnalysis.NetAnalyzers (#16194)
  • Bump `Microsoft.CodeAnalysis.NetAnalyzers` from `6.0.0-rc2.21458.5` to `6.0.0-rtm.21480.8` (#16183)
  • @@ -1063,10 +1131,10 @@ when not needed and dynamically determine the DOTNET_ROOT (Internal 19268, 19269 - Update more docs for `net6.0` TFM (#16102) (Thanks @xtqqczze!) - Change `snippet` tag to `code` tag in XML comments (#16106) - Update build documentation to reflect .NET 6 (#15751) (Thanks @Kellen-Stuart!) -- Update `README.md` about the change logs (#16471) (Thanks @powershellpr0mpt!) -- Update change log for 7.2.0 (#16401) +- Update `README.md` about the changelogs (#16471) (Thanks @powershellpr0mpt!) +- Update changelog for 7.2.0 (#16401) - Update `metadata.json` and `README.md` for 7.2.0 release (#16395) - Update `README.md` and `metadata.json` files for `v7.2.0-rc.1` release (#16285) -- Update the change logs for `v7.0.8` and `v7.1.5` releases (#16248) +- Update the changelogs for `v7.0.8` and `v7.1.5` releases (#16248) [7.3.0-preview.1]: https://github.com/PowerShell/PowerShell/compare/v7.2.0-preview.10...v7.3.0-preview.1 From 5a6c66be13ff30a6b6caa4f7b730f9b3d8cd8d0f Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Mon, 17 Jul 2023 14:20:06 -0700 Subject: [PATCH 656/779] `Restore-Computer` and `Stop-Computer` should fail with error when not running via `sudo` on Unix (#19824) --- .../commands/management/ComputerUnix.cs | 49 ++++++++++++++++--- .../resources/ComputerResources.resx | 3 ++ .../resources/ConsoleHostStrings.resx | 3 -- .../Restart-Computer.Tests.ps1 | 13 +++++ .../Stop-Computer.Tests.ps1 | 13 +++++ 5 files changed, 70 insertions(+), 11 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/ComputerUnix.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ComputerUnix.cs index a11fb0270c9..eb286f7c190 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ComputerUnix.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/ComputerUnix.cs @@ -5,10 +5,13 @@ using System; using System.Diagnostics; +using System.IO; using System.Management.Automation; using System.Management.Automation.Internal; using System.Runtime.InteropServices; +#nullable enable + namespace Microsoft.PowerShell.Commands { #region Restart-Computer @@ -36,13 +39,13 @@ protected override void BeginProcessing() { string errMsg = StringUtil.Format("Command returned 0x{0:X}", retVal); ErrorRecord error = new ErrorRecord( - new InvalidOperationException(errMsg), "Command Failed", ErrorCategory.OperationStopped, "localhost"); + new InvalidOperationException(errMsg), "CommandFailed", ErrorCategory.OperationStopped, "localhost"); WriteError(error); } return; } - RunCommand("/sbin/shutdown", "-r now"); + RunShutdown("-r now"); } #endregion "Overrides" } @@ -78,13 +81,13 @@ protected override void BeginProcessing() { string errMsg = StringUtil.Format("Command returned 0x{0:X}", retVal); ErrorRecord error = new ErrorRecord( - new InvalidOperationException(errMsg), "Command Failed", ErrorCategory.OperationStopped, "localhost"); + new InvalidOperationException(errMsg), "CommandFailed", ErrorCategory.OperationStopped, "localhost"); WriteError(error); } return; } - RunCommand("/sbin/shutdown", args); + RunShutdown(args); } #endregion "Overrides" } @@ -95,7 +98,7 @@ protected override void BeginProcessing() public class CommandLineCmdletBase : PSCmdlet, IDisposable { #region Private Members - private Process _process = null; + private Process? _process = null; #endregion #region "IDisposable Members" @@ -150,22 +153,52 @@ protected override void StopProcessing() #region "Internals" + private static string? shutdownPath; + /// - /// Run a command. + /// Run shutdown command. /// - protected void RunCommand(String command, String args) { + protected void RunShutdown(String args) + { + if (shutdownPath is null) + { + CommandInfo cmdinfo = CommandDiscovery.LookupCommandInfo( + "shutdown", CommandTypes.Application, + SearchResolutionOptions.None, CommandOrigin.Internal, this.Context); + + if (cmdinfo is not null) + { + shutdownPath = cmdinfo.Definition; + } + else + { + ErrorRecord error = new ErrorRecord( + new InvalidOperationException(ComputerResources.ShutdownCommandNotFound), "CommandNotFound", ErrorCategory.ObjectNotFound, targetObject: null); + ThrowTerminatingError(error); + } + } + _process = new Process() { StartInfo = new ProcessStartInfo { - FileName = "/sbin/shutdown", + FileName = shutdownPath, Arguments = string.Empty, RedirectStandardOutput = false, + RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = true, } }; _process.Start(); + _process.WaitForExit(); + if (_process.ExitCode != 0) + { + string stderr = _process.StandardError.ReadToEnd(); + ErrorRecord error = new ErrorRecord( + new InvalidOperationException(stderr), "CommandFailed", ErrorCategory.OperationStopped, null); + ThrowTerminatingError(error); + } } #endregion } diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/ComputerResources.resx b/src/Microsoft.PowerShell.Commands.Management/resources/ComputerResources.resx index 63a671c0248..95685239fd7 100644 --- a/src/Microsoft.PowerShell.Commands.Management/resources/ComputerResources.resx +++ b/src/Microsoft.PowerShell.Commands.Management/resources/ComputerResources.resx @@ -387,4 +387,7 @@ The {0} parameter is not supported for CoreCLR. + + The required native command 'shutdown' was not found. + diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/ConsoleHostStrings.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/ConsoleHostStrings.resx index e8dcccb3dee..ce124ec084c 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/resources/ConsoleHostStrings.resx +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/ConsoleHostStrings.resx @@ -164,9 +164,6 @@ End time: {0:yyyyMMddHHmmss} {0}:{1,-3} {2} - - An error occurred while running '{0}': {1} - The current session does not support debugging; execution will continue. diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Restart-Computer.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Restart-Computer.Tests.ps1 index 8a2c050a90f..9f845f81af9 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Restart-Computer.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Restart-Computer.Tests.ps1 @@ -107,3 +107,16 @@ finally Disable-Testhook -testhookName $restartTesthookName Set-TesthookResult -testhookName $restartTesthookResultName -value 0 } + +Describe 'Non-admin on Unix' { + BeforeAll { + $skip = $false + if ($IsWindows -or [environment]::IsPrivilegedProcess -or ($null -eq (Get-Command shutdown -CommandType Application -ErrorAction Ignore))) { + $skip = $true + } + } + + It 'Reports error if not run under sudo' -Skip:($skip) { + { Restart-Computer -ErrorAction Stop } | Should -Throw -ErrorId "CommandFailed,Microsoft.PowerShell.Commands.RestartComputerCommand" + } +} diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Stop-Computer.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Stop-Computer.Tests.ps1 index c2a89117167..1bda1471e78 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Stop-Computer.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Stop-Computer.Tests.ps1 @@ -58,3 +58,16 @@ finally Disable-Testhook -testhookName $stopTesthook Set-TesthookResult -testhookName $stopTesthookResultName -Value $DefaultResultValue } + +Describe 'Non-admin on Unix' { + BeforeAll { + $skip = $false + if ($IsWindows -or [environment]::IsPrivilegedProcess -or ($null -eq (Get-Command shutdown -CommandType Application -ErrorAction Ignore))) { + $skip = $true + } + } + + It 'Reports error if not run under sudo' -Skip:($skip) { + { Stop-Computer -ErrorAction Stop } | Should -Throw -ErrorId "CommandFailed,Microsoft.PowerShell.Commands.StopComputerCommand" + } +} From 92833aee648f12a7c73b10164583b0a382c3f75c Mon Sep 17 00:00:00 2001 From: Sean Wheeler Date: Mon, 17 Jul 2023 17:30:37 -0500 Subject: [PATCH 657/779] Update man page to match current help for pwsh (#19993) --- assets/pwsh.1.ronn | 210 ++++++++++++++++++++++++++++++++++----------- 1 file changed, 159 insertions(+), 51 deletions(-) diff --git a/assets/pwsh.1.ronn b/assets/pwsh.1.ronn index bcc38f7b8b0..13126164551 100644 --- a/assets/pwsh.1.ronn +++ b/assets/pwsh.1.ronn @@ -3,11 +3,17 @@ pwsh(1) -- PowerShell command-line shell and .NET REPL ## SYNOPSIS -`pwsh` [`-NoLogo`] [`-NoExit`] [`-NoProfile`] [`-NonInteractive`] -[`-InputFormat` {Text | XML}] [`-OutputFormat` {Text | XML}] +`pwsh` [`-Login`] [ [`-File`] [args] ] +[`-Command` { - | [`-args` ] | +[] } ] [`-ConfigurationFile` ] +[`-ConfigurationName` ] [`-CustomPipeName` ] +[`-EncodedArguments` ] [`-EncodedCommand` ] -[`-File` ] [`-ExecutionPolicy` ] -[`-Command` { `-` | [`-args` ] | [] } ] +[`-ExecutionPolicy` ] [`-Help`] [`-InputFormat` {Text | XML}] +[`-Interactive`] [`-MTA`] [`-NoExit`] [`-NoLogo`] [`-NonInteractive`] +[`-NoProfile`] [`-NoProfileLoadTime`] [`-OutputFormat` {Text | XML}] +[`-SettingsFile` ] [`-SSHServerMode`] [`-STA`] [`-Version`] +[`-WindowStyle`