Quantcast
Channel: /r/powershell – How to Code .NET
Viewing all 8793 articles
Browse latest View live

Translate IP Address to number.

$
0
0

So without giving too much detail i need to ask a question. Where i work the IP Scheme of the location is based off of the store number. For example our 250th location would be xxx.xx2.50.xxx , our 9th location would be xxx.xxx.9.xxx or our 20th location would be xxx.xxx.20.xxx but our 120th would be xxx.xx1.20.xxx or the 104th would be xxx.xx1.4.xxx and so on and so forth. The hostname naming scheme is such that if i can pull the ip address and have it translate into the store number, i could then have it reach out to the proper server for what i need it to do. I am decent with PS but cant even begin to think of a way to make this work. Any help would be greatly appreciated.

submitted by /u/Sw33T4ct10n
[link] [comments]

The post Translate IP Address to number. appeared first on How to Code .NET.


BGInfo, but with PowerShell?

$
0
0

Preface: This may be a better question for r/sysadmin. My coworker and I are trying to find/create a way to put some basic workstation info on the desktop without installing extra software.

Ideally we would display the host name, IP, and serial number or service tag as some sort of transparent overlay above the system tray. If there was a way to “hijack” the location where the PaintDesktopVersion registry that would be perfect. I’d also like to make wallpaper agnostic if possible.

Anyone know if something like this is even possible? I’m sure I can muddle my way through the code to do it if there’s some sort of framework for this kind of thing, but I’m genuinely clueless as to whether it can even be done without installing extra software.

Any suggestions?

submitted by /u/infinit_e
[link] [comments]

The post BGInfo, but with PowerShell? appeared first on How to Code .NET.

Create Exchange Mailflow Rule?

$
0
0

Trying to write an offboarding script using POSH. One of the things we do after someone leaves is create a redirect rule in our O365 exchange to the employees manager. For some reason I’m having trouble finding some decent examples to follow to do such a thing… any help appreciated!

Edit: Spelling mistakes.

submitted by /u/yarooski
[link] [comments]

The post Create Exchange Mailflow Rule? appeared first on How to Code .NET.

Help with understanding switch parameter

$
0
0

Hey all, so I come from more of a PHP programming background and I think that’s whats causing some of my confusion here.

I’m doing an onboarding script, it’s going to grab info from a csv and perform a New-ADUser. We have multiple OU’s for different departments, let’s just call them Sales, Training and Management.

What I would like to have is a function to see/check on which OU it needs to assign to a certain user from the value in the csv. so in the CSV, let’s say for the Sales its “Sales” which is in the OU: “OU=Sales, DC=domain, DC=com”

or am I a complete idiot and over thinking this and should be doing this another way? lol

function Get-OU { [cmdletbinding()] param( [Parameter()] [switch] $OU ) if ($Sales.IsPresent) { $OU = "OU=Sales, DC=domain, DC=com" } elseif ($Management.IsPresent) { $OU = "OU=Management, DC=domain, DC=com" } etc... 

or use

Switch ($OU) { 'Sales' {$OU = "OU=Sales, DC=domain, DC=com"} 'Management' {$OU = "OU=Management, DC=domain, DC=com"} 'Training' {$OU = "OU=Training, DC=domain, DC=com"} } } function New-User { $users = Import-Csv -Path "C:new-users.csv" foreach ($user in $users) { $Username = $User.Firstname + "." + $User.Lastname $Displayname = $User.Firstname + " " + $User.Lastname $SAM = $Username $OU = Get-OU -OU:$user.OU New-ADUser -DisplayName $Displayname -SamAccountName $SAM -Path = $OU etc.... } } 

submitted by /u/Dyasi
[link] [comments]

The post Help with understanding switch parameter appeared first on How to Code .NET.

Best Way to monitor if powershell script has run

365 Tenancy – List Distribution Groups for a User

$
0
0

Hey guys, struggling with running a Powershell to list all Distribution Groups a particular user belongs to, we have 365 as cloud-only, in the past we had AD on-prem so that was easy enough but now its all in the cloud, no more Distribution Groups in AD to reference.

My end goal is to list distribution groups of that particular user and copy that across to a new team member, I’ve been searching high and low, unable to find something that works for my particular solution. Anyone able to help?

Example of something I tried already but didn’t quite get anywhere with it: https://imgur.com/SWaiP2b

submitted by /u/Skilfil
[link] [comments]

The post 365 Tenancy – List Distribution Groups for a User appeared first on How to Code .NET.

Deleting registry keys through Invoke-Command?

$
0
0

I’m a Powershell newbie and i’m trying to repurpose this simple script I found to remotely remove Outlook profiles.

Before I started using Invoke-Command, the script worked as intended.

Now, I’m getting the following error:

Cannot find path ‘HKEY_CURRENT_USERSoftwareMicrosoftOffice16.0OutlookProfiles’ because it does not exist.

+ CategoryInfo : ObjectNotFound: (HKEY_CURRENT_US…utlookProfiles:String) [Get-ChildItem], ItemNotFoundException

+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand

Very weird because obviously the reg key exists. If I take the script out of Invoke-Command and run the steps through a PSSession everything works.

Any insight is appreciated

Invoke-Command -ComputerName $host -Credential $Cred -ArgumentList $Cred -ScriptBlock { param($Cred) New-PSDrive -Name P -PSProvider FileSystem -Root <UNC path> -Credential $Cred -ErrorAction SilentlyContinue Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass If ($process=Get-process 'outlook' -ErrorAction SilentlyContinue){ Write-host "Closing Outlook..." -ForegroundColor Yellow Stop-process $process } $reg="HKCU:SoftwareMicrosoftOffice16.0OutlookProfiles" $child=(Get-ChildItem -Path $reg).Name foreach($item in $child){ Remove-Item -Path registry::$item -Recurse } Write-host "All Outlook profiles have been removed" -ForegroundColor Yellow } 

submitted by /u/swagga-dragon
[link] [comments]

The post Deleting registry keys through Invoke-Command? appeared first on How to Code .NET.

Powershell wpf MahApps.Metro theme step by step


How can I find a match in an array?

$
0
0

I’m trying to create an array of only the exact objects I’m looking for based on the name. I was going to create a switch or maybe several if conditions but I thought that was very inefficient. I’m trying to use -match but having no luck so far. Is this the right approach?

$list = @('Prod_Windows','Prod_Linux') $clusters = New-Object System.Collections.Arraylist foreach ($cls in Get-Cluster){ if ($cls.Name -match $list){ $clusters.Add($cls) } } 

submitted by /u/Ghlave
[link] [comments]

The post How can I find a match in an array? appeared first on How to Code .NET.

Running Large T-SQL Scripts

$
0
0

I’m working on a way to automate Some environment setups in Azure, part of that includes setting up the Azure SQL Database.

I have a folder of 12 LARGE build scripts 10s of throusands of rows that our DBAs have made over the years, in order to setup the schema for our product you have to run them all in order.

I wrote a while loop to run through these scripts in order and even keep track of progress in a json file in the event something is interrupted as some of these take a while to run. the loop works fine when I use dummy queries.

unfortunately the issue seems to be that scripts that will run in SSMS, seem to have issues running programmatically.

I’ve tried a few different methods to no real success

by default I used SQLPS and “Invoke-Sqlcmd”, I set the timeout to 3600 seconds to give an hour just in case and the verbose output warns me about the script being too deeply nested, it’s really not more than 4-5 levels nested in some cases.

SSMS doesn’t complain it just chugs for a while and runs it, I also tried Invoke-Sqlcmd2 because I prefer using it since it’s much lighter and just leverages the existing .NET methods, but this gave the same error about nesting as above.

additionally I tried setting up my own SMO script using

Add-Type "Microsoft.SqlServer.Smo" 

and

$db.ExecuteWithResults($Query) 

and that just generates an exception, As best I can guess SSMS in some ways makes up for sloppy T-SQL and does some of the chunking the code up behind the scenes without telling you, the DBA is on contract so it’s not going to be an option to have them rewrite the scripts, so just trying to figure out if I should give up this dream and just get used to babysitting SSMS.

If nothing else I built a cool Script that fully automates resource setups using AzureRM Module

  • $ds = $db.ExecuteWithResults(“$testscript”)
  • ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    • CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    • FullyQualifiedErrorId : FailedOperationException

submitted by /u/Matth12582
[link] [comments]

The post Running Large T-SQL Scripts appeared first on How to Code .NET.

Timer creation

$
0
0

Greetings all,

Basically I want a function that starts a timer, starts a stopwatch, stays in the function for ten seconds, then breaks out of the function.

function timerfunction{

$StopWatch = New-Object -TypeName System.Diagnostics.Stopwatch

$StopWatch.Start()

$seconds = $StopWatch.Elapsed.Minutes

foreach($x in $seconds){

if ($x -lt 10) {

Write-Host ‘Loading’

}

else{

break

}

}

This is what I currently have and it’s not looping, any idea to get it to loop until it hits 10? Thanks all

submitted by /u/lakerskill
[link] [comments]

The post Timer creation appeared first on How to Code .NET.

Out-printer and font size

$
0
0

Hello gurus,

I had a question that thought would be pretty simple but im having a tough time with it.

When I print anything using the out-printer cmdlet the font is tiny. So, I have a couple of question.

  1. Where does the “out-Printer” cmdlet pull its font/style info from?

and 2. Is there any way to make this larger?

Hopefully its a pretty easy question and Im just missing something :).

submitted by /u/TheEZ1
[link] [comments]

The post Out-printer and font size appeared first on How to Code .NET.

Trying to wrap my head around this powershell stuff, could use some simpler explanations.

$
0
0

I’m still learning powershell and haven’t really learned a lot about object oriented computing, but I’m starting to get the idea. I see something like this in a script:

ForEach ($c in $computer) 

My understanding is things with $ in front are variables. The $c variable hasn’t been declared/defined anywhere in the script previous to that code. How come it works?

Also, I see these things at the beginning of the scripts:

[cmdletbinding( somethingsomething = 'something', )] Param( [Parameter( something = $True,)] [string[]]$computer ) 

In short, what does cmdletbinding and Param do? How about the string[] part at the end? Appreciate any help, thanks!

submitted by /u/PowerOverShelling
[link] [comments]

The post Trying to wrap my head around this powershell stuff, could use some simpler explanations. appeared first on How to Code .NET.

Trying to export values from remote registry

$
0
0

Hi all, I may be going about this all wrong, but I’m trying to see what computers have a specific registry key and to export the results along with the server name into a CSV.

I have my servers in a csv file

$servers = import-csv C:tempnew.csv foreach ($server in $servers.name) { $w32reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine',$server) $keypath = 'SoftwareMicrosoftWindowsCurrentVersionUninstall{D0D3DB16-3CB1-41E4-BB59-C90029DAB38B}' $key = $w32reg.OpenSubKey($keypath) $results = $key.GetValue('DisplayName') } 

This is where i’m confused, how do I now export those results? If i do a Write-Host $results it displays the key name or error, as it zips through the servers. I want to know which servers are failing. Any idea?

submitted by /u/absoluteczech
[link] [comments]

The post Trying to export values from remote registry appeared first on How to Code .NET.

Programming


Make VS code like Steroids?

$
0
0

The one thing that is keeping me from going all in on Code is one feature of ISEsteroids, the variables pane. Yes I know you can see active variables while in debug mode, but one of my favorite elements of steroids is that the variables and their values persist. In code once you pass your breakpoints and finish execution, those values are cleared from the debug window. The thing I find funny is that the variables definitely persist within the terminal, but I’d rather not have to echo them to screen…

So that’s a long winded way of asking, is there a way to persist the variables and their values within a window in Code that I just haven’t discovered yet? Or am I stuck using Steroids for this feature? Many thanks

submitted by /u/VTsnowboarder42
[link] [comments]

The post Make VS code like Steroids? appeared first on How to Code .NET.

Hex values

$
0
0

Hi all,

I’ve recently written a script to produce a list of hex values incrementally from 1 – 10000. This also adds a prefix to the beginning if the length does not hit a certain criteria.

The code is working as I’d like it too, but was wondering if you could see any improvements. Normally I don’t like writing short-hand PS but trying to see if I can improve anything I’ve written, below is my code and all comments welcomed.

for ($i = 1; $i -le 10000; $i++){ #{0:x} - hex value $name = "{0:x}" -f $i if($($name.Length) -ne 6){ for($l = $($name.Length); $l -lt 6; $l++){ $name = $name.insert(0,"0") } } $FullName = "ABCD$($name)" Write-Host $FullName } 

submitted by /u/divideddarko1
[link] [comments]

The post Hex values appeared first on How to Code .NET.

Copy File from source to multiple destinations

$
0
0

Just a quick background: I originally posted a question about this in Stack Overflow, however I have found that I am not familiar enough with Powershell to understand the broad answers I receive there.

I have a software vendor that requires us to copy .ini files to all of the systems that run it’s software. I currently navigate to the admin share on each pc and copy the file into the destination manually. When the vendor sends this file it is usually because there is an immediate need to have it on each PC, meaning pushing the file via GPO is not the best solution.

My script below should read a list of computer names from the PC_List.txt file and copy the file from my $Source to the Temp folder on each PC. Here is my script:

$Computers = gc "C:TempScriptPC_List.txt" $Source = "C:TempScriptAAAAA.txt" $Session = New-PSSession -Credential "localadmin" foreach ($Computer in $Computers) { $Session ; Copy-Item $Source -Destination "\$ComputerC$Temp" -Recurse} 

When I first run the script it prompt’s me for the local admin credentials (They are the same across the network) and then the script attempts to run. My problem is that I am getting the following errors for each PC.

Copy-Item : The target account name is incorrect. At C:TEMPScriptFileCopyTest3.ps1:5 char:48 + ... $Session ; Copy-Item $Source -Destination "\$ComputerC$Temp" -Re ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [Copy-Item], IOException + FullyQualifiedErrorId : System.IO.IOException,Microsoft.PowerShell.Commands.CopyItemCommand 

Am I using $session incorrectly?

Am I using the wrong type of credentials (I’ve tried <domain><domain admin account> and get the same message)?

submitted by /u/That1DudeOne
[link] [comments]

The post Copy File from source to multiple destinations appeared first on How to Code .NET.

Finding empty objects

$
0
0

Hey guys,

Should be a quick solution but I’m drawing a blank right now.

I’m trying to get only the results that have an null/empty property. Example: I want only the results that return an empty value for ‘StrongAuthenticationRequirements’.

UserPrincipalName StrongAuthenticationRequirements ----------------- -------------------------------- username@company.com {} 

The code I’m using doesn’t seem to work.

Get-MsolUser -All | Where-Object { $_.isLicensed -eq "TRUE" -and $_.StrongAuthenticationRequirements -eq $null} 

Any thoughts?

Thanks!

submitted by /u/BD_S
[link] [comments]

The post Finding empty objects appeared first on How to Code .NET.

Suppressing Encoding information in XML from console output

$
0
0

I am trying to suppress some XML data that is being outputted to the console in PowerShell. Ultimately, I’m trying to output a certain element of the same type of nodes in an XML document. I can get the desired output, I am just also getting “extra” XML information that I don’t want the user to see. I have tried Out-Null in a couple of different places, and nothing works. If anyone has any tips, I’d love a push in the right direction.

These are my functions. The parameter being passed to my Remove-UserFromSidecar is the path of the XML file that is returned from a different function.

Output looks like this:

xml Objects --- ------- version="1.0" encoding="utf-8" Objects These are the following users listed on the sidecar Joanne-3052 Claudia-4027 Holly-5014 Jessica-4024 Renee-1189 John-3389 Kevin-4092 version="1.0" encoding="UTF-8" 

Basically, I don’t want:

xml Objects --- ------- version="1.0" encoding="utf-8" Objects 

and I also don’t want the version="1.0" encoding="UTF-8" at the end.

Thanks!

submitted by /u/deathcat5
[link] [comments]

The post Suppressing Encoding information in XML from console output appeared first on How to Code .NET.

Viewing all 8793 articles
Browse latest View live