Posts

Showing posts with the label powershell

Why does powershell give different result in one-liner than two-liner when converting JSON?

Image
Clash Royale CLAN TAG #URR8PPP Why does powershell give different result in one-liner than two-liner when converting JSON? Overview From a powershell 3 prompt,, I want to call a RESTful service, get some JSON, and pretty-print it. I discovered that if I convert the data to a powershell object, and then convert the powershell object back to json, I get back a nice pretty-printed string. However, if I combine the two conversions into a one-liner with a pipe I will get a different result. TL;DR: this: PS> $psobj = $orig | ConvertFrom-JSON PS> $psobj | ConvertTo-JSON ... gives me different result than this: PS> $orig | ConvertFrom-JSON | ConvertTo-JSON Original data [ { "Type": "1", "Name": "QA" }, { "Type": "2", "Name": "whatver" } ] Doing the conversion in two steps I'm going to remove the whitespace (so it fits on one line...), convert it to a powershell object, and then...

Loading C# DLL with powershell, [System.Type]::GetType returns null

Image
Clash Royale CLAN TAG #URR8PPP Loading C# DLL with powershell, [System.Type]::GetType returns null I have a simple DotNet DLL like this namespace ClassLibrary1 { public class Class1 { public static void Test() { Process.Start("CMD.exe", "/C calc"); } } } When I try to load this DLL with powershell $Path = "c:\test\ClassLibrary1.dll"; $Namespace = "ClassLibrary1"; $ClassName = "Class1"; $Method = "Test"; $Arguments = $null $Full_Path = [System.IO.Path]::GetFullPath($Path); $AssemblyName = [System.Reflection.AssemblyName]::GetAssemblyName($Full_Path) $Full_Class_Name = "$Namespace.$ClassName" $Type_Name = "$Full_Class_Name, $($AssemblyName.FullName)" $Type = [System.Type]::GetType($Type_Name) $MethodInfo = $Type.GetMethod($Method) $MethodInfo.Invoke($null, $Arguments) It does not work, because [System.Type]::GetType($Type_Name) ...

Can I get Full computer name using powershell?

Image
Clash Royale CLAN TAG #URR8PPP Can I get Full computer name using powershell? My system has different full computer name. But I got answers like computername+domainName. I want only "Full computer name" in the properties. Well what do you want? The FQDN? Only the Device Name? – Paxz 30 mins ago Possible duplicate of Powershell: Get FQDN Hostname – Rogerson Nazário 29 mins ago @Paxz I want Full Computer Name from the system properties. I don't want device name or FQDN or Computer name or ComputerName+FQDN – Akhil Teej 15 mins ago ...

How do I suppress my event-handling function from emitting unwanted text?

Image
Clash Royale CLAN TAG #URR8PPP How do I suppress my event-handling function from emitting unwanted text? I have a PowerShell script that composes a WinForms UI. Here are the pertinent bits: cls [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") Function FormClosed() { $global:Canceled = $true } $global:MainForm = New-Object 'System.Windows.Forms.Form' $global:MainForm.add_FormClosed({FormClosed}) $global:MainForm.ShowDialog() When I run the program, I get a PowerShell console window and the UI (as expected). When I click the main form control box "X", the function FormClosed is invoked (as expected). However, the text Cancel unexpectedly appears in the console window. FormClosed Cancel I put a breakpoint on $global:Canceled = $true in the function FormClosed . At this breakpoint, I step and then I see the execution pointer is on the } i...

Powershell comparing two List with foreach

Image
Clash Royale CLAN TAG #URR8PPP Powershell comparing two List with foreach I'm trying to compare two lists that I obtained with the Get-ChildItem cmdlet. Get-ChildItem I read about the Compare-Object cmdlet, but in this context I would prefer doing with a foreach because is useful to have access to the $file variable. Compare-Object $file $StartingFolderPath = "C:---StartingFolder" $EndingFolderPath = "C:---EndingFolder" $AllStartingFiles = Get-ChildItem $StartingFolderPath $AllEndingFiles = Get-ChildItem $EndingFolderPath Write-Host "First folder content:"$AllStartingFiles Write-Host "Second folder content:" $AllEndingFiles foreach($file in $AllEndingFiles){ write-Host "Element :" $file.Name $result = $AllStartingFiles.Contains($file.Name) write-host $result if($AllStartingFiles.Contains($file.Name)){ Write-Host "You are here" Write-Host $file.Name } } But it seems that I cannot pass the...

Pester Should -BeLike

Image
Clash Royale CLAN TAG #URR8PPP Pester Should -BeLike I have this test It 'Should not find environment' { {Add-Patchgroup -ComputerName $serversHash.serverWithNotExistingEnvironment -WarningVariable warning -WarningAction SilentlyContinue} $warning | Should -BeLike ('*55555*') } $warning contains this string (exactly as you see here with the newline and whitespace on the second row) $warning Could not add <nameOfTheServer> to patchgroup Exception message: Environment F was not found But my test is passing which should not: Context Find the environment [+] Should not find environment 79ms [+] Should find environment 147ms EDIT: seems like the test is not working at all even with -Be parameter. The test is still passing. -Be $warning | Should -Be 'randomrandom' 1 Answer 1 I'm not sure why your test is passing, that is very strange. But I think ...

Get unique values

Image
Clash Royale CLAN TAG #URR8PPP Get unique values We're trying to optimize some code that removes duplicates from an Array as fast as possible. Normally this can be easily done by piping the input to Group-Object and then using only the Name property. But we would like to avoid the pipeline, as it is slower. Array Group-Object Name However, we tried the following code: [System.Collections.ArrayList]$uniqueFrom = @() $From = @('A', 'A', 'B') $From.Where({-not ($uniqueFrom.Contains($_))}).ForEach({ $uniqueFrom.Add($_) }) $uniqueFrom In theory, this should work. But for one reason or another the output is not the expected @('A', 'B') . Why is it not reevaluating the ArrayList in the .where clause? @('A', 'B') ArrayList .where Why so complicated? $uniqueFrom = @($From | Select-Object -Unique) – Ansgar Wiechers 2 hours ago ...

Are we in a Remote Powershell session?

Image
Clash Royale CLAN TAG #URR8PPP Are we in a Remote Powershell session? From a Powershell script, how can I check if the script was called from a Remote Powershell session, or from a local session? stackoverflow.com/questions/13394196/… – Vivek Kumar Singh 15 secs ago By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

How to get the key of all the Azure Services in same way through powershell

Image
Clash Royale CLAN TAG #URR8PPP How to get the key of all the Azure Services in same way through powershell I am trying to develop a PowerShell script for getting the key using Invoke-AzureRmResourceAction command of different Azure services, like below Invoke-AzureRmResourceAction $keyValue=Invoke-AzureRmResourceAction -Action listKeys -ResourceId $ResourceId -force The problem is, I am getting the key to different services in a different way. Like for storage account, I have to write $keyValue.keys[0].value for getting the 1st key value. But for cognitive service, I have to write $keyValue.key1 . Is there any way to generalized it so that same thing works for all the services in Azure which has the s key. $keyValue.keys[0].value $keyValue.key1 1 Answer 1 I think you could not access it via the same command. Different azure services have different resource structures, so the result format of ...

Remove iistart.htm?

Image
Clash Royale CLAN TAG #URR8PPP Remove iistart.htm? I am trying to rename (or even remove) iisstart.htm. I have tried the below but it is not doing anything. The result does not change anything: Set-WebConfigurationProperty -PSPath 'MACHINE/WEBROOT/APPHOST' -Filter 'system.webServer/defaultDocument/files/add[@value="iisstart.htm"]' -Name 'value' -Value (@{value="REMOVE_iisstart.htm"}) I used to be able to do this via appcmd: set config /section:system.webServer/defaultDocument /-files.[value='iisstart.htm'] set config /section:system.webServer/defaultDocument /-files.[value='iisstart.htm'] Any idea what is going wrong here? Getting the info back I am using this and it shows nothing as changed when I set a hash table for value=REMOVE_iisstart.htm Get-WebConfigurationProperty -PSPath 'MACHINE/WEBROOT/APPHOST' -Filter 'system.webServer/defaultDocument/files/add' -Name 'value' ...

Powershell select statement

Image
Clash Royale CLAN TAG #URR8PPP Powershell select statement forEach($subscription in Get-AzureRmSubscription) { Select-AzureRmSubscription -SubscriptionId $subscription.Id | Out-Null Get-AzurermVM -Status | select $subscription.Name, ResourceGroupName, Name, PowerState | ConvertTo-Csv -NoTypeInformation -Delimiter "|"} I'm trying to return the results of this query, but it does not include the subscription name in the results. It shows it in the table header, but not in each line of the results. It should show it on every line, but it is blank for the first column on each row. I'm guessing this has to do with the subscription variable not being apart of the -Status properties, but it shows it in the table header? 1 Answer 1 If you want to include a static value as a property of the custom objects output by the Select-Object cmdlet ( select is a built-in alias name), you must u...

How to edit only the Firstname (givenName) of multiple users and import with csv

Image
Clash Royale CLAN TAG #URR8PPP How to edit only the Firstname (givenName) of multiple users and import with csv If I have a list of users where the samAccountName for all the users are all numerical Example, 745744, 745746, etc…. I was looking for a powershell script that could accomplish the following: Is having only one column in excel with the samAccountName sufficient for the csv, or do i need to also have all of the users givenName as well inside of the csv?? Example column A samAccountName, column B Firstname?? Example givenName is, JOAQUIN, I would need the first name to be XXJOAQUIN. I have about 500 users that I would have to do this for, and we are doing it manually right now, So the only thing that I need changed is adding the “XX” before the users givenNames…. Thanks everyone in advance. 3 Answers 3 If your CSV file just contains a header with the samAccountName followed by the samAccou...

Displaying the Next Available Number in a sequence

Image
Clash Royale CLAN TAG #URR8PPP Displaying the Next Available Number in a sequence Our organisation renames all new computers before they join our domain and I am trying to create a script to display the next available number. So, our naming convention is as follows Example: GBYOR-DT1 GB - YOR - DT - 1 [Country] [City] [Desktop] [Number] However my predecessor thought to number these in no logical order and that just isn't happening on my watch. (Did someone say OCD?) Currently I run Get-ADComputer -Filter * | where{$_.Name -Like "GBYOR-DT*" | FL Name | Export-CSV -Path "X Location" I then go into Excel, split the cells and the sort numerically. What I would like is to create a script that just shows me the next available number. For example, as it currently stands, we have X number of machines, one is GBYOR-DT4, another is GBYOR-DT245 but there is no GBYOR-DT15. I would like to script this so that when I run it, it will look at all...

Proper export from txt to html in Powershell

Image
Proper export from txt to html in Powershell I have a script, which stores output in txt and I need to convert this output into html. The format of txt file is following: This file is generated for commits from: 2018-07-15 to: 2018-07-21 for branch: repositories contains: mineq =============somerepo============= Branch is development 1234567 Merge pull request #1227 from qp-10421_service_version_information 1234567 Merge branch 'development' into qp-10421_service_version_information 1234567 merged with development 1234567 QP-2071: update packages =============Someotherrepo============= Branch is development =============MineqConfigApi============= Branch is development 1234567 QP-10881 Remove WindowsVpnSettings service 1234567 Merge pull request #9 from quarti/QP-10881 1234567 QP-10881 Set SshClient ConnectionTimeout 10 minutes and Change sql query to skip Deleted Assets To send this text into html, I use following code: $SourceFile = "$env:WORKSPACEcommits.txt" $Ta...