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

Carbon 2.5.4 Released


PowerShell and DB2

$
0
0

I’m not an admin or a dba but I’ve been tasked with monitoring db2 tables to start a root cause analysis for missing records.

How would any of you wonderful professionals here monitor record counts in db2 tables through powershell? I more than likely can’t download anything else to do this task.

I’ll eventually have to tackle quite a few tables with this but I figure getting an overnight variance in records for one of them is a good start.

I do have rstudio and msaccess.

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

The post PowerShell and DB2 appeared first on How to Code .NET.

Help: Script to record directory visits and datetimes (Powershell rook)

$
0
0

I’m relatively new to PowerShell and am trying to create a script that runs on startup presenting me with my 10 most used directories from the past week.

Currently I’m storing my visits in string “path_date” format in a txt file, importing them with Import-Csv and then counting the occurrences of each path in a hash table so I may present myself with the top 10.

It should be an easy task but I can’t get it to work properly, mainly due to my misunderstanding of Powershell data types and their recommended use cases. Does anyone have a clean methods of doing this?

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

The post Help: Script to record directory visits and datetimes (Powershell rook) appeared first on How to Code .NET.

Simple question – Attribute $null

$
0
0

Hey all, probably the simplest thing I have asked so far, it is bugging me that I can’t work it out.

I have this: #before loop $out = @() Import-CSV C:adminscriptsgrantscriptsexport.csv | foreach { $userphone = $_.phone $username = $_.username #during loop $userinfo = get-ADUser -identity $username -Properties * | select houseIdentifier, samaccountname, userprincipalname, primaryTelexNumber if ($userinfo.houseIdentifier -eq $null){ $houseIdentifierPresent = $false } else {$houseIdentifierPresent = $true} $outstring = ($userinfo.samaccountname + "; " + $houseIdentifierPresent + "; " + $userinfo.userprincipalname + "; " + $userinfo.primaryTelexNumber) $outstring $out += $outstring } #after loop $out |out-file c:temptestoutput.csv -append 

It still tells me all the “houseidentifier” values are true, when only a couple actually have something in them aside from the default windows <not set>. I thought this meant they were $null

CSV is just username,email,phone

Any suggestions?

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

The post Simple question – Attribute $null appeared first on How to Code .NET.

Trouble with script

$
0
0

I am trying to automate assigning E1 license to all our unlicensed users using the following script. I have removed our company name for obvious reasons. I keep getting a error saying i need to Set usage location BUT it doesnt come up whe i go through ISE or powershell. Please Help. iI dont have much experience in powershell but i don’t want to do it all one by one in the admin portal Edit: Fixed Spelling errors

Get-MsolUser -All -UnlicensedUsersOnly | Set-MsolUserLicense -UsageLocation AU -AddLicenses “<companyname>:STANDARDPACK:

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

The post Trouble with script appeared first on How to Code .NET.

Powershell considers moving default aliases to seperate modules

$
0
0

So last night I saw this tweet: https://twitter.com/Jaykul/status/1004851936523444225

It references this pull request on the PowerShell RFC: https://github.com/PowerShell/PowerShell-RFC/pull/129 Which in turn resolves this issue: https://github.com/PowerShell/PowerShell/issues/5870

So aliases like ls => Get-ChildItem, sc => Set-Content and curl => Invoke-WebRequest might be removed from the core PowerShell repository and in turn be moved to seperate modules.

They consider compatibility with the “WindowsPowerShell” aliases.

But if you have a GitHub account, go have your say.

Personally I think this is a brilliant way to keep old alises for Windows while allowing the user to remove the aliases.

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

The post Powershell considers moving default aliases to seperate modules appeared first on How to Code .NET.

NTFS Permissions

$
0
0

Hi everyone!

I need to change permissions of two files, one of them I need to take ownership first. Only problem, I have to do it in 500 machines… This machines are in WORKGROUP and in different geographic locations.

I wanted to make a script so I can just double click the script and it’s done but I can’t really find any pre-made scripts or info on how to do it. Not even on scrip center.

Anyone has any idea on how I can accomplish this? I’ve learned by now that it’s not a easy task so any help would be greatly appreciated.

Thanks in advance!

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

The post NTFS Permissions appeared first on How to Code .NET.

Remove Duplicate XML Section with PowerShell

$
0
0

I have been working on a script to parse an xml document in order to find any duplicates of a specific section inside the file. For context, this is a part of a pre-process that the XML document goes through before it’s passed through an import process.

I was able to narrow down the specific section that causes the import process to fail:

 <OrderLineAct IsEmpty="N" Imported="Y" RecordID="" Error="" Version="15.4.0.3" OrderNumber="21-000138765"> <Code>RR</Code> <CodeType>POSITION</CodeType> <JobCodeID>0</JobCodeID> <JobsFltID>0</JobsFltID> <LineID>16348542</LineID> <Modified>6/6/2018 8:50:00 AM</Modified> <ModifiedBy>JANETC</ModifiedBy> <OrderID>2294006</OrderID> <Qty>0</Qty> <QtyUOM></QtyUOM> <Section>3863523</Section> </OrderLineAct> <OrderLineAct IsEmpty="N" Imported="N" RecordID="" Error="" Version="15.4.0.3"> <Code>RR</Code> <CodeType>POSITION</CodeType> <JobCodeID>0</JobCodeID> <JobsFltID>0</JobsFltID> <LineID>16348542</LineID> <Modified>6/6/2018 8:50:00 AM</Modified> <ModifiedBy>JANETC</ModifiedBy> <OrderID>2294006</OrderID> <Qty>0</Qty> <QtyUOM></QtyUOM> <Section>3863523</Section> </OrderLineAct> 

Having this duplicate section causes the file to go through an infinite loop inside the importer, resulting in the file not completing it’s import process.

What I need to do is determine if any one of these OrderLineActs is identical to an existing one inside its parent Node. Each one of these OrderLineActs resides inside of a OrderLine segment.

I’m having difficulty thinking about how to accomplish this. My first thought was to go through and delete anything that contains Imported="N", but then could run into issues if another OrderLineAct fails the import for some reason.

My idea was to structure it similarly to how I am completely removing another tag inside the XML:

Function Remove-UnitMeter { param($xml) # strip the xml of any UnitMeter tags - done for every schema foreach($VendorInvoice in $xml.VendorInvoices) { foreach($Order in $VendorInvoice.Order) { # remove the UnitMeter tag from the XML file if ($Order.UnitMeter -ne $null){ $Order.RemoveChild($Order.UnitMeter) | Out-Null # out-null otherwise it'll output all of the tags } } # end order } # end vendorinvoice return $xml } 

I know I have to remove the child from the parent, but I need to be able to determine if it’s a true duplicate before I do.

Has anyone ever done anything like this before? I can provide more information as needed. Thanks.

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

The post Remove Duplicate XML Section with PowerShell appeared first on How to Code .NET.


Script that was working stopped

$
0
0

Code:

$Access = New-Object -com Access.Application $FB = 'UNC Path' $Access.OpenCurrentDatabase($FB,$false) $Access.Run('DailyImport') $Access.CloseCurrentDatabase() $Access.Quit() [System.Runtime.Interopservices.Marshal]::FinalReleaseComObject($Access) Remove-Variable -Name Access 

Error:

 Exception calling "Run" with "1" argument(s): "Exception from HRESULT: 0x800A9D9F" At C:ScriptsAccessImport.ps1:4 char:1 + $Access.Run('FBDailyImport') + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : COMException 

This is the last step in a decently simple scheduled task. It moves files from one folder to another, runs some excel macros which sort the files into sane data, then it runs an access import macro(which literally is one step calling the VB function) with the above script to Import the files.

The VB function is literally just 10 DoCmd.RunSavedImportExport calls (6 import 4 export)

Now a few days ago, around the time this broke, I had to drop an entire table from the database, and it was part of the import process. I still load all the data to my staging excel file, but I just went into the Access VB script and commented out the lines referring to that part of the import (might be added back at a later date). Given that’s literally the only thing I’ve touched that could affect the process, I’m assuming that’s somehow it.

What’s frustrating though is that running it through powershell fails now. Going into Access and running the macro there (either directly through VB or through the silly one step macro) works perfectly. The ONLY thing I can think of Access side is that I haven’t recompiled the VB stuff since the change, and that somehow the macro the powershell script is running is the old one, which would error. My concern is its NOT that (hard to test for various reason…need to wait until later) and I’m going to lose all the weekend data and have to load manually on Monday.

Anyone run into something like this before? I know my method/use isn’t even close to standard.

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

The post Script that was working stopped appeared first on How to Code .NET.

Assistance with Adding users Office Phone numbers by UPN.

Validating numbered variables

$
0
0

I am writing a script to generate a text file, based on user-provided variable values. The variables are provided through another application and they come into Windows as environmental variables.

So I have the following:

[hashtable]$variables = @{InstallPath = $env:InstallPath; ADBaseOUValue1 = $env:ADBaseOUValue1; ADBaseOUValue2 = $env:ADBaseOUValue2; LDAPQueryValue1 = $env:LDAPQueryValue1; LDAPQueryValue2 = $env:LDAPQueryValue2} 

This hash table is truncated, the user can define up to 15 ADBaseOUs and 15 LDAP queries and there are other variables provided, but none of them are numbered.

Now I need to validate the data.

  1. I need to make sure that ADBaseOUValue1 and LDAPQueryValue1 are not null
  2. I need to make sure that ADBaseOUValue1 matches a regex pattern
  3. I need to make sure that, if LDAPQueryValue1 has ampersands (&) not follwed by “amp;”, that I replace them
  4. Then I need to make both check 2 and 3, for any ADBaseOUValue# and LDAPQueryValue# that the user has provided.

I am doing data validation on the other variables (e.g. $env:InstallPath), to make sure they are not null and have the expected types of data.

In variables $env:ADBaseOUValue2 through 15 and $env:LDAPQueryValue2 through 15, how would I:

  1. Define the variable name when doing the “If” check against its regex
  2. Define the variable name when doing the “replace” of “&”

Once the variables are validated, the values will go into a Here String like:

<setting name="ADBaseOU1" serializeAs="String"> <value>$env:ADBaseOUValue1</value> </setting> <setting name="ADBaseOU2" serializeAs="String"> <value>$env:ADBaseOUValue2</value> </setting> 

Thanks, here is what I have right now (for the validation part):

Switch ($variables.GetEnumerator()) { {($_.Name -eq "ADBaseOUValue1") -and ($_.Value -ne $null)} { If ($env:ADBaseOUValue1 -notmatch $ldapUrlRegex) { Write-Host ("{0}: The variable `"{1}`" was not a valid LDAP URL. Please re-run the script and provide a valid value for the variable." -f (Get-Date -Format s), $_.Name) $variableErrorCount++ } } {($_.Name -eq "ADBaseOUValue1") -and ($_.Value -eq $null)} { If ($env:ADBaseOUValue1 -notmatch $ldapUrlRegex) { Write-Host ("{0}: The variable `"{1}`" was null. Please re-run the script and provide a value for the variable." -f (Get-Date -Format s), $_.Name) $variableErrorCount++ } } {($_.Name -match "ADBaseOUValue(d+)$") -and ($_.Name -ne "ADBaseOUValue1") -and ($_.Value -ne $null)} { If ($env:ADBaseOUValue1 -notmatch $ldapUrlRegex) { Write-Host ("{0}: The variable `"{1}`" was not a valid LDAP URL. Please re-run the script and provide a valid value for the variable." -f (Get-Date -Format s), $_.Name) $variableErrorCount++ } } {($_.Name -eq "LDAPQueryValue1") -and ($_.Value -ne $null)} { If ($env:LDAPQueryValue1 -notmatch "&amp;") { Write-Host ("{0}: Replacing `"&`" with `"&amp;`" in {1}." -f (Get-Date -Format s), $_.Name) $env:LDAPQueryValue1 = $env:LDAPQueryValue1.Replace("&", "&amp;") } } {($_.Name -eq "LDAPQueryValue1") -and ($_.Value -eq $null)} { If ($env:ADBaseOUValue1 -notmatch $ldapUrlRegex) { Write-Host ("{0}: The variable `"{1}`" was null. Please re-run the script and provide a value for the variable." -f (Get-Date -Format s), $_.Name) $variableErrorCount++ } } {($_.Name -match "LDAPQueryValue(d+)$") -and ($_.Name -ne "LDAPQueryValue1") -and ($_.Value -ne $null)} { If ($env:??? -notmatch "&amp;") { Write-Host ("{0}: Replacing `"&`" with `"&amp;`" in {1}." -f (Get-Date -Format s), $_.Name) $env:??? = $env:???.Replace("&", "&amp;") } } } 

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

The post Validating numbered variables appeared first on How to Code .NET.

Select-Object -first 1 breaks foreach loop?

$
0
0

I’m probably doing something really dumb and I just don’t know it.

I’ve got a Powershell script using the NetApp Powershell Toolkit that connects to all of the cluster-mode NetApp filers in my environment and iterates through each SVM on that filer to find the management IPs for that SVM. I only need to know one management IP per SVM for my purposes. Easy, right?

This is the code I have so far:

$filers = @([redacted]) $mgmtips = @() foreach ($filer in $filers) { Write-Host "Connecting to $filer with supplied credentials." Connect-NcController -Name $filer -Credential $credential $vservers = Get-NcVserver | Where-Object {$_.VserverType -eq 'data'} | Select-Object -ExpandProperty Vserver Write-Host "Successfully created list of vservers on filer $filer." foreach ($vserver in $vservers) { # Get first LIF with management access enabled Write-Host "Getting Management IP Address for $vserver." $IP = Get-NcNetInterface -vserver $vserver | Where-Object {$_.FirewallPolicy -eq "mgmt"} | Select-Object -ExpandProperty Address | Select-Object -First 1 $mgmtips += $IP } Write-Host "Disconnecting from $filer." $global:CurrentNcController = $null } 

However, whenever I run this code, it connects to the first filer in the list, pulls the management IP for the first SVM in $vservers as desired, and then stops dead. It never continues looping through $vservers to return the next management IP. If I remove the “Select-Object -First 1” part of the command it works fine (but gives me more IPs than I want).

What gives? Shouldn’t the command build a list of IPs for all the management interfaces on a given vserver, select the first object in the list, and then move on to the next vserver? What dumb logic error am I making? I don’t think this is a problem with the powershell toolkit specifically, but I haven’t tried reproducing this issue outside of it.

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

The post Select-Object -first 1 breaks foreach loop? appeared first on How to Code .NET.

Unrolling Collections…why?

$
0
0

I’m sure there is a good reason for this behavior but I have been bitten a few times by powershell’s unrolling of single or zero item “collections.” Consider the following code that gets a list of game mods that are installed on a multiplayer server:

$objTempNeededMods = GetListOfNeededMods;

[System.Collections.ArrayList]$aNeededMods;

If no mods are needed on the client I would expect the $objTempNeededMods to be an empty collection. Instead it is null. So I have to check for that condition here:

if($objTempNeededMods -eq $null)

{

LogOutput -Message "Nothing needs to be downloaded." -Severity [MessageSeverity]::INFO;

return;

}

On the other hand if only one mod is needed to download it becomes a simple string, and so I have to check for that condition here:

if($objTempNeededMods.GetType().Name -eq "String")

{

# Thanks Microsoft, for changing the data type on me.

$aNeededMods = New-Object System.Collections.ArrayList;

$aNeededMods.Add($objTempNeededMods);

}

Only at this point can I assume that the object is an actual ArrayList:

else

{

$aNeededMods = $objTempNeededMods;

}

Seems like a pain to me. What is the reasoning behind unrolling the collection in the event it has only 1 or zero items in it?

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

The post Unrolling Collections…why? appeared first on How to Code .NET.

git command line aliases

$
0
0

Here are some helpful git command line aliases that I’ve made. These are relatively simple, but effective. Also, I’ve arranged them to where they don’t conflict with any of the default powershell aliases. Simply add them to your powershell profile and enjoy!

$git = "C:Program FilesGitcmdgit.exe" function git-status { & $git 'status' } function git-checkout { & $git 'checkout' $args } function git-checkout-branch { & $git 'checkout' '-b' $args } function git-log { & $git 'log' $args } function git-add-all { & $git 'add' '--all' $args } function git-commit { & $git 'commit' '-a' '-m' $args } Set-Alias gst git-status Set-Alias gco git-checkout Set-Alias gcob git-checkout-branch Set-Alias glo git-log Set-Alias gaa git-add-all Set-Alias gcam git-commit 

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

The post git command line aliases appeared first on How to Code .NET.

Enable-Mailbox is not searching on specified Domain Controller

$
0
0

As part of my user creation script I run Enable-Mailbox for the newly created account. Occasionally this fails with this error.

The operation couldn't be performed because object 'testUser' couldn't be found on 'DC02.contoso.com'. + CategoryInfo : NotSpecified: (:) [Get-Mailbox], ManagementObjectNotFoundException + FullyQualifiedErrorId : [Server=exchange-01,RequestId=754fb25e-1f18-4ceb-adc3-86557fc086a3,TimeStamp=6/8/2018 8:02 :05 PM] [FailureCategory=Cmdlet-ManagementObjectNotFoundException] 9A93D50,Microsoft.Exchange.Management.RecipientT asks.GetMailbox + PSComputerName : exchange-01 

I added a check to verify the account exists on $domainController before running. I also specified the DC I want.

$domainController = DC01.contoso.com Enable-Mailbox -Identity $SAMname -Alias $mailAlias -DomainController $domainController 

I still receive an error that the account was not found on DC02.contoso.com. I ran with -Verbose and found the issue but I don’t know why it’s happening or how to fix it.

PS U:Powershell> Enable-Mailbox -Identity $SAMname -Alias $mailAlias -DomainController $domainController -Verbose -WhatIf VERBOSE: [20:22:18.906 GMT] Enable-Mailbox : Runspace context: Executing user: contoso.com/IT/People/Administrative/autobotIT, Executing user organization: , Current organization: , RBAC-enabled: Enabled. VERBOSE: [20:22:19.000 GMT] Enable-Mailbox : Active Directory session settings for 'Enable-Mailbox' are: View Entire Forest: 'False', Default Scope: 'contoso.com', Configuration Domain Controller: 'DC02.contoso.com', Preferred Global Catalog: 'DC02.contoso.com', Preferred Domain Controllers: '{ DC02.contoso.com }' VERBOSE: [20:22:19.000 GMT] Enable-Mailbox : Beginning processing Enable-Mailbox VERBOSE: [20:22:19.000 GMT] Enable-Mailbox : Instantiating handler with index 0 for cmdlet extension agent "Mailbox Creation Time Agent". VERBOSE: [20:22:19.016 GMT] Enable-Mailbox : Instantiating handler with index 1 for cmdlet extension agent "Query Base DN Agent". VERBOSE: [20:22:19.016 GMT] Enable-Mailbox : Instantiating handler with index 2 for cmdlet extension agent "Rus Agent". VERBOSE: [20:22:19.016 GMT] Enable-Mailbox : Instantiating handler with index 3 for cmdlet extension agent "Mailbox Resources Management Agent". VERBOSE: [20:22:19.016 GMT] Enable-Mailbox : Instantiating handler with index 4 for cmdlet extension agent "Provisioning Policy Agent". VERBOSE: [20:22:19.016 GMT] Enable-Mailbox : Instantiating handler with index 5 for cmdlet extension agent "Admin Audit Log Agent". VERBOSE: [20:22:19.047 GMT] Enable-Mailbox : Current ScopeSet is: { Recipient Read Scope: {{, }}, Recipient Write Scopes: {{, }}, Configuration Read Scope: {{, }}, Configuration Write Scope(s): {{, }, }, Exclusive Recipient Scope(s): {}, Exclusive Configuration Scope(s): {} } VERBOSE: [20:22:19.047 GMT] Enable-Mailbox : Searching objects "testUser" of type "ADUser" under the root "$null". VERBOSE: [20:22:19.063 GMT] Enable-Mailbox : Previous operation run on domain controller 'DC01.contoso.com'. 

There’s more in the log but this seems like the important bit. Why is line 3 referencing DC02.contoso.com when I specified DC01.contoso.com?

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

The post Enable-Mailbox is not searching on specified Domain Controller appeared first on How to Code .NET.


Looking for Pastebin alternatives.

PowerShell torrent client

How does your environment handle remote management with PowerShell?

$
0
0

As a PowerShell novice I find myself grasping for machines on my work network with PSRemoting enabled. Following the out-of-the-box design, I only find servers running WinRM. For a handful of end-user machines I lay hands on, I make sure to run Enable-PSRemoting, but there is no Default Domain Policy that enables remote management. I’ve deployed a GPO enabling remote management for a select group of machines I have to administer, but the PowerShell enthusiast in me wants more hostnames to send down the pipeline.

What does your setup look like? Is enabling PowerShell remoting across the domain feasible or wise?

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

The post How does your environment handle remote management with PowerShell? appeared first on How to Code .NET.

Script to add/create configuration baselines in sccm automatically

$
0
0

I understand the process of manually adding ps scripts to check and remediate compliance settings using the config manager console. I was wondering if someone here might be able to share an example that automates the entire process. Basically, looking for a ps script that connects to the sccm site server, uploads and configures specified compliance baseline check and remediation scripts/settings while targeting a specific collection automatically.

Probably a good question for /sccm was well.

Any help is appreciated. Thanks.

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

The post Script to add/create configuration baselines in sccm automatically appeared first on How to Code .NET.

Setting attribute to users in a nested OU

$
0
0

I’m assisting with a migration to 365. I need to create a script that’ll add a SMTP proxy attribute to users in a particular OU.

So far I have been successful when I direct the script to the exact OU. The problem I have is there are numerous users in nested OUs. For instance: District > School > SchoolName > Student > GradYEAR. The commonality is the Student OU. If there was a way to do a wild card for the grad year that’d work.

Posting what I have below…

 Import-Module ActiveDirectory $school = Read-Host 'What is the name of the school? ex. WCHS, CBCH?' $ou = 'Students' $users = Get-ADUser -Filter * -SearchBase "ou=$ou,ou=$school,OU=Schools,OU=DISTRICT,DC=ad,DC=CITY,DC=k12,DC=STATE,DC=us" foreach ($user in $users) { $email = $user.samaccountname + '@CITY.k12.state.us' $newemail = "SMTP:"+$email Set-ADUser $user -Add @{proxyAddresses = ($newemail)} Write-Host "Processed User: $($user.samaccountname)`n------------------------" } 

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

The post Setting attribute to users in a nested OU appeared first on How to Code .NET.

Viewing all 8793 articles
Browse latest View live